context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.IO;
using System.Drawing.Internal;
namespace System.Drawing.Imaging
{
/// <summary>
/// Defines a graphic metafile. A metafile contains records that describe a sequence of graphics operations that
/// can be recorded and played back.
/// </summary>
public sealed partial class Metafile : Image
{
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and
/// <see cref='WmfPlaceableFileHeader'/>.
/// </summary>
public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader) :
this(hmetafile, wmfHeader, false)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and
/// <see cref='WmfPlaceableFileHeader'/>.
/// </summary>
public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader, bool deleteWmf)
{
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromWmf(new HandleRef(null, hmetafile), deleteWmf, wmfHeader, out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and
/// <see cref='WmfPlaceableFileHeader'/>.
/// </summary>
public Metafile(IntPtr henhmetafile, bool deleteEmf)
{
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromEmf(new HandleRef(null, henhmetafile), deleteEmf, out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified filename.
/// </summary>
public Metafile(string filename)
{
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromFile(filename, out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified stream.
/// </summary>
public Metafile(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromStream(new GPStream(stream), out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle to a device context.
/// </summary>
public Metafile(IntPtr referenceHdc, EmfType emfType) :
this(referenceHdc, emfType, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle to a device context.
/// </summary>
public Metafile(IntPtr referenceHdc, EmfType emfType, String description)
{
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipRecordMetafile(new HandleRef(null, referenceHdc),
unchecked((int)emfType),
NativeMethods.NullHandleRef,
unchecked((int)MetafileFrameUnit.GdiCompatible),
description,
out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, RectangleF frameRect) :
this(referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit) :
this(referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type) :
this(referenceHdc, frameRect, frameUnit, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type, String description)
{
IntPtr metafile = IntPtr.Zero;
GPRECTF rectf = new GPRECTF(frameRect);
int status = SafeNativeMethods.Gdip.GdipRecordMetafile(new HandleRef(null, referenceHdc),
unchecked((int)type),
ref rectf,
unchecked((int)frameUnit),
description, out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, Rectangle frameRect) :
this(referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit) :
this(referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type) :
this(referenceHdc, frameRect, frameUnit, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded
/// by the specified rectangle.
/// </summary>
public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string desc)
{
IntPtr metafile = IntPtr.Zero;
int status;
if (frameRect.IsEmpty)
{
status = SafeNativeMethods.Gdip.GdipRecordMetafile(new HandleRef(null, referenceHdc),
unchecked((int)type),
NativeMethods.NullHandleRef,
unchecked((int)MetafileFrameUnit.GdiCompatible),
desc,
out metafile);
}
else
{
GPRECT gprect = new GPRECT(frameRect);
status = SafeNativeMethods.Gdip.GdipRecordMetafileI(new HandleRef(null, referenceHdc),
unchecked((int)type),
ref gprect,
unchecked((int)frameUnit),
desc,
out metafile);
}
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc) :
this(fileName, referenceHdc, EmfType.EmfPlusDual, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, EmfType type) :
this(fileName, referenceHdc, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, EmfType type, String description)
{
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipRecordMetafileFileName(fileName, new HandleRef(null, referenceHdc),
unchecked((int)type),
NativeMethods.NullHandleRef,
unchecked((int)MetafileFrameUnit.GdiCompatible),
description,
out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect) :
this(fileName, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit) :
this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit, EmfType type) :
this(fileName, referenceHdc, frameRect, frameUnit, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, string desc) :
this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, desc)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit, EmfType type, String description)
{
IntPtr metafile = IntPtr.Zero;
GPRECTF rectf = new GPRECTF(frameRect);
int status = SafeNativeMethods.Gdip.GdipRecordMetafileFileName(fileName,
new HandleRef(null, referenceHdc),
unchecked((int)type),
ref rectf,
unchecked((int)frameUnit),
description,
out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect) :
this(fileName, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect,
MetafileFrameUnit frameUnit) :
this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect,
MetafileFrameUnit frameUnit, EmfType type) :
this(fileName, referenceHdc, frameRect, frameUnit, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, string description) :
this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, description)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string description)
{
IntPtr metafile = IntPtr.Zero;
int status;
if (frameRect.IsEmpty)
{
status = SafeNativeMethods.Gdip.GdipRecordMetafileFileName(fileName,
new HandleRef(null, referenceHdc),
unchecked((int)type),
NativeMethods.NullHandleRef,
unchecked((int)frameUnit),
description,
out metafile);
}
else
{
GPRECT gprect = new GPRECT(frameRect);
status = SafeNativeMethods.Gdip.GdipRecordMetafileFileNameI(fileName,
new HandleRef(null, referenceHdc),
unchecked((int)type),
ref gprect,
unchecked((int)frameUnit),
description,
out metafile);
}
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc) :
this(stream, referenceHdc, EmfType.EmfPlusDual, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, EmfType type) :
this(stream, referenceHdc, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, EmfType type, string description)
{
IntPtr metafile = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipRecordMetafileStream(new GPStream(stream),
new HandleRef(null, referenceHdc),
unchecked((int)type),
NativeMethods.NullHandleRef,
unchecked((int)MetafileFrameUnit.GdiCompatible),
description,
out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect) :
this(stream, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit) :
this(stream, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit, EmfType type) :
this(stream, referenceHdc, frameRect, frameUnit, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit, EmfType type, string description)
{
IntPtr metafile = IntPtr.Zero;
GPRECTF rectf = new GPRECTF(frameRect);
int status = SafeNativeMethods.Gdip.GdipRecordMetafileStream(new GPStream(stream),
new HandleRef(null, referenceHdc),
unchecked((int)type),
ref rectf,
unchecked((int)frameUnit),
description,
out metafile);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect) :
this(stream, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect,
MetafileFrameUnit frameUnit) :
this(stream, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect,
MetafileFrameUnit frameUnit, EmfType type) :
this(stream, referenceHdc, frameRect, frameUnit, type, null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename.
/// </summary>
public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit,
EmfType type, string description)
{
IntPtr metafile = IntPtr.Zero;
int status;
if (frameRect.IsEmpty)
{
status = SafeNativeMethods.Gdip.GdipRecordMetafileStream(new GPStream(stream),
new HandleRef(null, referenceHdc),
unchecked((int)type),
NativeMethods.NullHandleRef,
unchecked((int)frameUnit),
description,
out metafile);
}
else
{
GPRECT gprect = new GPRECT(frameRect);
status = SafeNativeMethods.Gdip.GdipRecordMetafileStreamI(new GPStream(stream),
new HandleRef(null, referenceHdc),
unchecked((int)type),
ref gprect,
unchecked((int)frameUnit),
description,
out metafile);
}
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeImage(metafile);
}
/// <summary>
/// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>.
/// </summary>
public static MetafileHeader GetMetafileHeader(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader)
{
MetafileHeader header = new MetafileHeader();
header.wmf = new MetafileHeaderWmf();
int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromWmf(new HandleRef(null, hmetafile), wmfHeader, header.wmf);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return header;
}
/// <summary>
/// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>.
/// </summary>
public static MetafileHeader GetMetafileHeader(IntPtr henhmetafile)
{
MetafileHeader header = new MetafileHeader();
header.emf = new MetafileHeaderEmf();
int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromEmf(new HandleRef(null, henhmetafile), header.emf);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return header;
}
/// <summary>
/// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>.
/// </summary>
public static MetafileHeader GetMetafileHeader(string fileName)
{
MetafileHeader header = new MetafileHeader();
IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf)));
try
{
int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromFile(fileName, memory);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
int[] type = new int[] { 0 };
Marshal.Copy(memory, type, 0, 1);
MetafileType metafileType = (MetafileType)type[0];
if (metafileType == MetafileType.Wmf ||
metafileType == MetafileType.WmfPlaceable)
{
// WMF header
header.wmf = (MetafileHeaderWmf)UnsafeNativeMethods.PtrToStructure(memory, typeof(MetafileHeaderWmf));
header.emf = null;
}
else
{
// EMF header
header.wmf = null;
header.emf = (MetafileHeaderEmf)UnsafeNativeMethods.PtrToStructure(memory, typeof(MetafileHeaderEmf));
}
}
finally
{
Marshal.FreeHGlobal(memory);
}
return header;
}
/// <summary>
/// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>.
/// </summary>
public static MetafileHeader GetMetafileHeader(Stream stream)
{
MetafileHeader header;
IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf)));
try
{
int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromStream(new GPStream(stream), memory);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
int[] type = new int[] { 0 };
Marshal.Copy(memory, type, 0, 1);
MetafileType metafileType = (MetafileType)type[0];
header = new MetafileHeader();
if (metafileType == MetafileType.Wmf ||
metafileType == MetafileType.WmfPlaceable)
{
// WMF header
header.wmf = (MetafileHeaderWmf)UnsafeNativeMethods.PtrToStructure(memory, typeof(MetafileHeaderWmf));
header.emf = null;
}
else
{
// EMF header
header.wmf = null;
header.emf = (MetafileHeaderEmf)UnsafeNativeMethods.PtrToStructure(memory, typeof(MetafileHeaderEmf));
}
}
finally
{
Marshal.FreeHGlobal(memory);
}
return header;
}
/// <summary>
/// Returns the <see cref='MetafileHeader'/> associated with this <see cref='Metafile'/>.
/// </summary>
public MetafileHeader GetMetafileHeader()
{
MetafileHeader header;
IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf)));
try
{
int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromMetafile(new HandleRef(this, nativeImage), memory);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
int[] type = new int[] { 0 };
Marshal.Copy(memory, type, 0, 1);
MetafileType metafileType = (MetafileType)type[0];
header = new MetafileHeader();
if (metafileType == MetafileType.Wmf ||
metafileType == MetafileType.WmfPlaceable)
{
// WMF header
header.wmf = (MetafileHeaderWmf)UnsafeNativeMethods.PtrToStructure(memory, typeof(MetafileHeaderWmf));
header.emf = null;
}
else
{
// EMF header
header.wmf = null;
header.emf = (MetafileHeaderEmf)UnsafeNativeMethods.PtrToStructure(memory, typeof(MetafileHeaderEmf));
}
}
finally
{
Marshal.FreeHGlobal(memory);
}
return header;
}
/// <summary>
/// Returns a Windows handle to an enhanced <see cref='Metafile'/>.
/// </summary>
public IntPtr GetHenhmetafile()
{
IntPtr hEmf = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipGetHemfFromMetafile(new HandleRef(this, nativeImage), out hEmf);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return hEmf;
}
/// <summary>
/// Plays an EMF+ file.
/// </summary>
public void PlayRecord(EmfPlusRecordType recordType,
int flags,
int dataSize,
byte[] data)
{
// Used in conjunction with Graphics.EnumerateMetafile to play an EMF+
// The data must be DWORD aligned if it's an EMF or EMF+. It must be
// WORD aligned if it's a WMF.
int status = SafeNativeMethods.Gdip.GdipPlayMetafileRecord(new HandleRef(this, nativeImage),
recordType,
flags,
dataSize,
data);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/*
* Create a new metafile object from a native metafile handle.
* This is only for internal purpose.
*/
internal static Metafile FromGDIplus(IntPtr nativeImage)
{
Metafile metafile = new Metafile();
metafile.SetNativeImage(nativeImage);
return metafile;
}
private Metafile()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;
namespace NSane.Local
{
/// <summary>
/// This is a device that is locally connected.
/// </summary>
internal class LocalDevice : Device
{
private IntPtr _handle;
private bool _open;
private bool _started;
private IEnumerable<IDeviceOption> _options;
/// <summary>
/// Construct the device with the bits and bobs it needs
/// </summary>
/// <param name="name">The name of the device (unique I think)</param>
/// <param name="vendor">The vendor</param>
/// <param name="model">The model</param>
/// <param name="type">The type</param>
internal LocalDevice(string name,
string vendor,
string model,
string type)
: base(name, vendor, model, type)
{
_open = false;
}
/// <summary>
/// Construct a device in the open state
/// </summary>
/// <param name="name"></param>
/// <param name="handle"></param>
internal LocalDevice(string name, IntPtr handle)
: base(name, null, null, null)
{
_handle = handle;
_open = true;
}
/// <summary>
/// Opens the device
/// </summary>
/// <returns></returns>
public override IOpenedDevice Open()
{
IntPtr handle;
var status = NativeMethods.SaneOpen(Name, out handle);
if (status != (int)SaneStatus.Success)
throw NSaneException.CreateFromStatus((int)status);
_handle = handle;
return this;
}
/// <summary>
/// Implements the synchronous scanning method
/// </summary>
/// <returns></returns>
public override IScanResult Scan()
{
return Scan(null, null);
}
/// <summary>
/// Implements an asynchronous scan
/// </summary>
/// <param name="onCompleteCallback">The on complete callback</param>
/// <param name="onFailureCallback">The on failure callback</param>
/// <returns></returns>
public override IScanResult Scan(Action<BitmapSource> onCompleteCallback,
Action<AggregateException> onFailureCallback)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets all options
/// </summary>
public override IEnumerable<IDeviceOption> AllOptions
{
get
{
return _options ??
(_options = RequestOptionList(ReloadOptions).ToList());
}
}
/// <summary>
/// Create a user readble overview of the device (i.e. the
/// name, vendor, etc)
/// </summary>
/// <returns>The aforementioned description</returns>
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture,
"{0} ({1}, {2} - {3})",
Name,
Vendor ?? string.Empty,
Model ?? string.Empty,
Type ?? string.Empty);
}
/// <summary>
/// Dispose of the device object
/// </summary>
/// <param name="disposing"><c>true</c> if we are at disposing time
/// </param>
protected override void Dispose(bool disposing)
{
if (_open)
Close();
base.Dispose(disposing);
}
/// <summary>
/// Close the device
/// </summary>
private void Close()
{
if (_started)
Cancel();
NativeMethods.SaneClose(_handle);
_handle = IntPtr.Zero;
_open = false;
}
/// <summary>
/// Cancels the current scan
/// </summary>
private void Cancel()
{
NativeMethods.SaneCancel(_handle);
_started = false;
}
private IEnumerable<IDeviceOption> RequestOptionList(Action reloadFunction)
{
var p = NativeMethods.SaneGetOptionDescriptor(_handle, 0);
int count = p == IntPtr.Zero
? 0
: p.ToInt32();
for (int i = 1; i < count; i++)
{
var opt = ToOptionDescriptor(NativeMethods.SaneGetOptionDescriptor(_handle, i));
var localOption = new LocalDeviceOption(opt.Name,
opt.Title,
opt.Description,
opt.Size,
i,
opt.Type,
opt.Unit,
opt.Capabilities,
_handle,
reloadFunction);
yield return localOption;
}
}
private static SaneOptionDescriptor ToOptionDescriptor(IntPtr pointer)
{
return (SaneOptionDescriptor)Marshal.PtrToStructure(
pointer, typeof(SaneOptionDescriptor));
}
/// <summary>
/// This function is called when the device needs to have it's options
/// refreshed - we just call the get option list and then map the
/// properties across
/// </summary>
private void ReloadOptions()
{
var options = RequestOptionList(ReloadOptions);
foreach (var deviceOption in options)
{
var opt = _options
.Cast<DeviceOption>()
.Single(o => (o).Number ==
((DeviceOption)deviceOption).Number);
opt.Name = deviceOption.Name;
opt.Capabilities = deviceOption.Capabilities;
opt.Constraint = deviceOption.Constraint;
opt.Type = deviceOption.Type;
opt.Unit = deviceOption.Unit;
opt.Description = deviceOption.Description;
opt.Title = deviceOption.Title;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using MessageStream2;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayer
{
//Damn you americans - You're making me spell 'colour' wrong!
public class PlayerColorWorker
{
//Services
private DMPGame dmpGame;
private Settings dmpSettings;
private LockSystem lockSystem;
private PlayerStatusWindow playerStatusWindow;
private NetworkWorker networkWorker;
private bool registered;
public bool workerEnabled;
private NamedAction updateEvent;
private const int FRAMES_TO_DELAY_RETRY = 1;
private Dictionary<Vessel, FrameCount> delaySetColors = new Dictionary<Vessel, FrameCount>();
private List<Vessel> delayRemoveList = new List<Vessel>();
private Dictionary<string, Color> playerColors = new Dictionary<string, Color>();
private object playerColorLock = new object();
//Can't declare const - But no touchy.
public readonly Color DEFAULT_COLOR = Color.grey;
public PlayerColorWorker(DMPGame dmpGame, Settings dmpSettings, LockSystem lockSystem, NetworkWorker networkWorker)
{
this.dmpGame = dmpGame;
this.dmpSettings = dmpSettings;
this.lockSystem = lockSystem;
this.networkWorker = networkWorker;
updateEvent = new NamedAction(Update);
dmpGame.updateEvent.Add(updateEvent);
}
public void SetDependencies(PlayerStatusWindow playerStatusWindow)
{
this.playerStatusWindow = playerStatusWindow;
}
public void Update()
{
if (workerEnabled && !registered)
{
RegisterGameHooks();
}
if (!workerEnabled && registered)
{
UnregisterGameHooks();
}
if (!workerEnabled)
{
return;
}
if (!FlightGlobals.ready)
{
return;
}
DelaySetColors();
}
public void DetectNewVessel(Vessel v)
{
if (!delaySetColors.ContainsKey(v))
{
delaySetColors.Add(v, new FrameCount(FRAMES_TO_DELAY_RETRY));
}
}
private void DelaySetColors()
{
foreach (KeyValuePair<Vessel, FrameCount> kvp in delaySetColors)
{
FrameCount frameCount = kvp.Value;
frameCount.number = frameCount.number - 1;
if (frameCount.number == 0)
{
delayRemoveList.Add(kvp.Key);
}
}
foreach (Vessel setVessel in delayRemoveList)
{
delaySetColors.Remove(setVessel);
if (FlightGlobals.fetch.vessels.Contains(setVessel))
{
SetVesselColor(setVessel);
}
}
if (delayRemoveList.Count > 0)
{
delayRemoveList.Clear();
}
}
private void SetVesselColor(Vessel colorVessel)
{
if (colorVessel == null)
{
return;
}
if (workerEnabled)
{
if (lockSystem.ControlLockExists(colorVessel.id) && !lockSystem.ControlLockIsOurs(colorVessel.id))
{
string vesselOwner = lockSystem.ControlLockOwner(colorVessel.id);
DarkLog.Debug("Vessel " + colorVessel.id.ToString() + " owner is " + vesselOwner);
if (colorVessel.orbitRenderer != null)
{
colorVessel.orbitRenderer.SetColor(GetPlayerColor(vesselOwner));
}
}
else
{
if (colorVessel.orbitRenderer != null)
{
colorVessel.orbitRenderer.SetColor(DEFAULT_COLOR);
}
}
}
}
private void OnLockAcquire(string playerName, string lockName, bool result)
{
if (workerEnabled)
{
UpdateVesselColorsFromLockName(lockName);
}
}
private void OnLockRelease(string playerName, string lockName)
{
if (workerEnabled)
{
UpdateVesselColorsFromLockName(lockName);
}
}
private void UpdateVesselColorsFromLockName(string lockName)
{
if (lockName.StartsWith("control-", StringComparison.Ordinal))
{
string vesselID = lockName.Substring(8);
foreach (Vessel findVessel in FlightGlobals.fetch.vessels)
{
if (findVessel.id.ToString() == vesselID)
{
SetVesselColor(findVessel);
}
}
}
}
private void UpdateAllVesselColors()
{
foreach (Vessel updateVessel in FlightGlobals.fetch.vessels)
{
SetVesselColor(updateVessel);
}
}
public Color GetPlayerColor(string playerName)
{
lock (playerColorLock)
{
if (playerName == dmpSettings.playerName)
{
return dmpSettings.playerColor;
}
if (playerColors.ContainsKey(playerName))
{
return playerColors[playerName];
}
return DEFAULT_COLOR;
}
}
public void HandlePlayerColorMessage(ByteArray messageData)
{
using (MessageReader mr = new MessageReader(messageData.data))
{
PlayerColorMessageType messageType = (PlayerColorMessageType)mr.Read<int>();
switch (messageType)
{
case PlayerColorMessageType.LIST:
{
int numOfEntries = mr.Read<int>();
lock (playerColorLock)
{
playerColors = new Dictionary<string, Color>();
for (int i = 0; i < numOfEntries; i++)
{
string playerName = mr.Read<string>();
Color playerColor = ConvertFloatArrayToColor(mr.Read<float[]>());
playerColors.Add(playerName, playerColor);
playerStatusWindow.colorEventHandled = false;
}
}
}
break;
case PlayerColorMessageType.SET:
{
lock (playerColorLock)
{
string playerName = mr.Read<string>();
Color playerColor = ConvertFloatArrayToColor(mr.Read<float[]>());
DarkLog.Debug("Color message, name: " + playerName + " , color: " + playerColor.ToString());
playerColors[playerName] = playerColor;
UpdateAllVesselColors();
playerStatusWindow.colorEventHandled = false;
}
}
break;
default:
break;
}
}
}
public void SendPlayerColorToServer()
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)PlayerColorMessageType.SET);
mw.Write<string>(dmpSettings.playerName);
mw.Write<float[]>(ConvertColorToFloatArray(dmpSettings.playerColor));
networkWorker.SendPlayerColorMessage(mw.GetMessageBytes());
}
}
//Helpers
public static float[] ConvertColorToFloatArray(Color convertColour)
{
float[] returnArray = new float[3];
returnArray[0] = convertColour.r;
returnArray[1] = convertColour.g;
returnArray[2] = convertColour.b;
return returnArray;
}
public static Color ConvertFloatArrayToColor(float[] convertArray)
{
return new Color(convertArray[0], convertArray[1], convertArray[2]);
}
//Adapted from KMP
public static Color GenerateRandomColor()
{
System.Random rand = new System.Random();
int seed = rand.Next();
Color returnColor = Color.white;
switch (seed % 17)
{
case 0:
return Color.red;
case 1:
return new Color(1, 0, 0.5f, 1); //Rosy pink
case 2:
return new Color(0.6f, 0, 0.5f, 1); //OU Crimson
case 3:
return new Color(1, 0.5f, 0, 1); //Orange
case 4:
return Color.yellow;
case 5:
return new Color(1, 0.84f, 0, 1); //Gold
case 6:
return Color.green;
case 7:
return new Color(0, 0.651f, 0.576f, 1); //Persian Green
case 8:
return new Color(0, 0.651f, 0.576f, 1); //Persian Green
case 9:
return new Color(0, 0.659f, 0.420f, 1); //Jade
case 10:
return new Color(0.043f, 0.855f, 0.318f, 1); //Malachite
case 11:
return Color.cyan;
case 12:
return new Color(0.537f, 0.812f, 0.883f, 1); //Baby blue;
case 13:
return new Color(0, 0.529f, 0.741f, 1); //NCS blue
case 14:
return new Color(0.255f, 0.412f, 0.882f, 1); //Royal Blue
case 15:
return new Color(0.5f, 0, 1, 1); //Violet
default:
return Color.magenta;
}
}
private void RegisterGameHooks()
{
if (!registered)
{
registered = true;
GameEvents.onVesselCreate.Add(this.DetectNewVessel);
lockSystem.RegisterAcquireHook(this.OnLockAcquire);
lockSystem.RegisterReleaseHook(this.OnLockRelease);
}
}
private void UnregisterGameHooks()
{
if (registered)
{
registered = false;
GameEvents.onVesselCreate.Remove(this.DetectNewVessel);
lockSystem.UnregisterAcquireHook(this.OnLockAcquire);
lockSystem.UnregisterReleaseHook(this.OnLockRelease);
}
}
public void Stop()
{
workerEnabled = false;
UnregisterGameHooks();
}
//Can't modify a dictionary so we're going to have to make a reference class...
private class FrameCount
{
public int number;
public FrameCount(int number)
{
this.number = number;
}
}
}
}
| |
//////////////////////////////////////////////////////////////////////////
// Code Named: VG-Ripper
// Function : Extracts Images posted on RiP forums and attempts to fetch
// them to disk.
//
// This software is licensed under the MIT license. See license.txt for
// details.
//
// Copyright (c) The Watcher
// Partial Rights Reserved.
//
//////////////////////////////////////////////////////////////////////////
// This file is part of the RiP Ripper project base.
using System;
using System.Collections;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;
using System.Drawing;
using System.Windows.Forms;
namespace Ripper
{
using Ripper.Core.Components;
using Ripper.Core.Objects;
/// <summary>
/// Worker class to get images from TheImageHosting.com
/// </summary>
public class TheImageHosting : ServiceTemplate
{
public TheImageHosting(ref string sSavePath, ref string strURL, ref string thumbURL, ref string imageName, ref int imageNumber, ref Hashtable hashtable)
: base(sSavePath, strURL, thumbURL, imageName, imageNumber, ref hashtable)
{
}
protected override bool DoDownload()
{
string strImgURL = ImageLinkURL;
if (EventTable.ContainsKey(strImgURL))
{
return true;
}
string strFilePath = string.Empty;
strFilePath = strImgURL.Substring(strImgURL.LastIndexOf("img=") + 4);
strFilePath = strFilePath.Remove(strFilePath.Length - 5, 5);
try
{
if (!Directory.Exists(SavePath))
Directory.CreateDirectory(SavePath);
}
catch (IOException ex)
{
//MainForm.DeleteMessage = ex.Message;
//MainForm.Delete = true;
return false;
}
strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath));
CacheObject CCObj = new CacheObject();
CCObj.IsDownloaded = false;
CCObj.FilePath = strFilePath;
CCObj.Url = strImgURL;
try
{
EventTable.Add(strImgURL, CCObj);
}
catch (ThreadAbortException)
{
return true;
}
catch (Exception)
{
if (EventTable.ContainsKey(strImgURL))
{
return false;
}
else
{
EventTable.Add(strImgURL, CCObj);
}
}
string strNewURL = "http://images" + strImgURL.Substring(strImgURL.IndexOf("server") + 6, 1) + ".theimagehosting.com/" + strImgURL.Substring(strImgURL.IndexOf("img=") + 4);
//////////////////////////////////////////////////////////////////////////
HttpWebRequest lHttpWebRequest;
HttpWebResponse lHttpWebResponse;
Stream lHttpWebResponseStream;
//FileStream lFileStream = null;
//int bytesRead;
try
{
lHttpWebRequest = (HttpWebRequest)WebRequest.Create(strNewURL);
lHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6";
lHttpWebRequest.Headers.Add("Accept-Language: en-us,en;q=0.5");
lHttpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate");
lHttpWebRequest.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
lHttpWebRequest.Referer = strImgURL;
lHttpWebRequest.Accept = "image/png,*/*;q=0.5";
lHttpWebRequest.KeepAlive = true;
lHttpWebResponse = (HttpWebResponse)lHttpWebRequest.GetResponse();
lHttpWebResponseStream = lHttpWebRequest.GetResponse().GetResponseStream();
if (lHttpWebResponse.ContentType.IndexOf("image") < 0)
{
//if (lFileStream != null)
// lFileStream.Close();
return false;
}
if (lHttpWebResponse.ContentType.ToLower() == "image/jpeg")
strFilePath += ".jpg";
else if (lHttpWebResponse.ContentType.ToLower() == "image/gif")
strFilePath += ".gif";
else if (lHttpWebResponse.ContentType.ToLower() == "image/png")
strFilePath += ".png";
string NewAlteredPath = Utility.GetSuitableName(strFilePath);
if (strFilePath != NewAlteredPath)
{
strFilePath = NewAlteredPath;
((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;
}
//lFileStream = new FileStream(strFilePath, FileMode.Create);
lHttpWebResponseStream.Close();
WebClient client = new WebClient();
client.Headers.Add("Accept-Language: en-us,en;q=0.5");
client.Headers.Add("Accept-Encoding: gzip,deflate");
client.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
client.Headers.Add("Referer: " + strImgURL);
client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
client.DownloadFile(strNewURL, strFilePath);
/*do
{
// Read up to 1000 bytes into the bytesRead array.
bytesRead = lHttpWebResponseStream.Read(byteBuffer, 0, 999);
lFileStream.Write(byteBuffer, 0, bytesRead);
}while(bytesRead > 0);
lHttpWebResponseStream.Close();*/
}
catch (ThreadAbortException)
{
((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);
return true;
}
catch (IOException ex)
{
//MainForm.DeleteMessage = ex.Message;
//MainForm.Delete = true;
((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);
return true;
}
catch (WebException)
{
((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);
return false;
}
((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true;
//CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
CacheController.Instance().LastPic =((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;
return true;
}
//////////////////////////////////////////////////////////////////////////
}
}
| |
using lanterna.screen;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Collection = System.Collections.ICollection;
using EnumSet = System.Collections.IList;
using Class = System.Type;
using TextColor = System.Nullable<System.ConsoleColor>;
using lanterna.gui2;
namespace lanterna.graphics {
/**
* Implementation of ThemedTextGraphics that wraps a TextGraphics that all calls are delegated to, except for the
* method from ThemedTextGraphics which are handled. The theme is set at construction time, but you can create a clone
* of this object with a different theme.
* @author Martin
*/
class ImmutableThemedTextGraphics : TextGraphics, ThemedTextGraphics {
private TextGraphics backend;
private Theme theme;
/**
* Creates a new {@code ImmutableThemedTextGraphics} with a specified backend for all drawing operations and a
* theme.
* @param backend Backend to send all drawing operations to
* @param theme Theme to be associated with this object
*/
public ImmutableThemedTextGraphics(TextGraphics backend, Theme theme) {
this.backend = backend;
this.theme = theme;
}
/**
* Returns a new {@code ImmutableThemedTextGraphics} that targets the same backend but with another theme
* @param theme Theme the new {@code ImmutableThemedTextGraphics} is using
* @return New {@code ImmutableThemedTextGraphics} object that uses the same backend as this object
*/
public ImmutableThemedTextGraphics withTheme(Theme theme) {
return new ImmutableThemedTextGraphics(backend, theme);
}
/**
* Returns the underlying {@code TextGraphics} that is handling all drawing operations
* @return Underlying {@code TextGraphics} that is handling all drawing operations
*/
public TextGraphics getUnderlyingTextGraphics() {
return backend;
}
/**
* Returns the theme associated with this {@code ImmutableThemedTextGraphics}
* @return The theme associated with this {@code ImmutableThemedTextGraphics}
*/
public Theme getTheme() {
return theme;
}
//@Override
public ThemeDefinition getThemeDefinition(Class clazz) {
return theme.getDefinition(clazz);
}
//@Override
public /*Immutable*/ThemedTextGraphics applyThemeStyle(ThemeStyle themeStyle) {
setForegroundColor(themeStyle.getForeground());
setBackgroundColor(themeStyle.getBackground());
//setModifiers(themeStyle.getSGRs());
return this;
}
//@Override
public TerminalSize getSize() {
return backend.getSize();
}
//@Override
public /*ImmutableThemed*/TextGraphics newTextGraphics(TerminalPosition topLeftCorner, TerminalSize size) {
return new ImmutableThemedTextGraphics(backend.newTextGraphics(topLeftCorner, size), this.theme);
}
//@Override
public TextColor getBackgroundColor() {
return backend.getBackgroundColor();
}
//@Override
public /*ImmutableThemed*/TextGraphics setBackgroundColor(TextColor backgroundColor) {
backend.setBackgroundColor(backgroundColor);
return this;
}
//@Override
public TextColor getForegroundColor() {
return backend.getForegroundColor();
}
//@Override
public /*ImmutableThemed*/TextGraphics setForegroundColor(TextColor foregroundColor) {
backend.setForegroundColor(foregroundColor);
return this;
}
//@Override
//public ImmutableThemedTextGraphics enableModifiers(SGR... modifiers) {
// backend.enableModifiers(modifiers);
// return this;
//}
//@Override
//public ImmutableThemedTextGraphics disableModifiers(SGR... modifiers) {
// backend.disableModifiers(modifiers);
// return this;
//}
//@Override
//public ImmutableThemedTextGraphics setModifiers(EnumSet<SGR> modifiers) {
// backend.setModifiers(modifiers);
// return this;
//}
//@Override
//public ImmutableThemedTextGraphics clearModifiers() {
// backend.clearModifiers();
// return this;
//}
//@Override
//public EnumSet<SGR> getActiveModifiers() {
// return backend.getActiveModifiers();
//}
//@Override
public TabBehaviour getTabBehaviour() {
return backend.getTabBehaviour();
}
//@Override
public /*ImmutableThemed*/TextGraphics setTabBehaviour(TabBehaviour tabBehaviour) {
backend.setTabBehaviour(tabBehaviour);
return this;
}
//@Override
public /*ImmutableThemed*/TextGraphics fill(char c) {
backend.fill(c);
return this;
}
//@Override
public TextGraphics fillRectangle(TerminalPosition topLeft, TerminalSize size, char character) {
backend.fillRectangle(topLeft, size, character);
return this;
}
//@Override
public TextGraphics fillRectangle(TerminalPosition topLeft, TerminalSize size, TextCharacter character) {
backend.fillRectangle(topLeft, size, character);
return this;
}
//@Override
public TextGraphics drawRectangle(TerminalPosition topLeft, TerminalSize size, char character) {
backend.drawRectangle(topLeft, size, character);
return this;
}
//@Override
public TextGraphics drawRectangle(TerminalPosition topLeft, TerminalSize size, TextCharacter character) {
backend.drawRectangle(topLeft, size, character);
return this;
}
//@Override
public TextGraphics fillTriangle(TerminalPosition p1, TerminalPosition p2, TerminalPosition p3, char character) {
backend.fillTriangle(p1, p2, p3, character);
return this;
}
//@Override
public TextGraphics fillTriangle(TerminalPosition p1, TerminalPosition p2, TerminalPosition p3, TextCharacter character) {
backend.fillTriangle(p1, p2, p3, character);
return this;
}
//@Override
public TextGraphics drawTriangle(TerminalPosition p1, TerminalPosition p2, TerminalPosition p3, char character) {
backend.drawTriangle(p1, p2, p3, character);
return this;
}
//@Override
public TextGraphics drawTriangle(TerminalPosition p1, TerminalPosition p2, TerminalPosition p3, TextCharacter character) {
backend.drawTriangle(p1, p2, p3, character);
return this;
}
//@Override
public TextGraphics drawLine(TerminalPosition fromPoint, TerminalPosition toPoint, char character) {
backend.drawLine(fromPoint, toPoint, character);
return this;
}
//@Override
public TextGraphics drawLine(TerminalPosition fromPoint, TerminalPosition toPoint, TextCharacter character) {
backend.drawLine(fromPoint, toPoint, character);
return this;
}
//@Override
public TextGraphics drawLine(int fromX, int fromY, int toX, int toY, char character) {
backend.drawLine(fromX, fromY, toX, toY, character);
return this;
}
//@Override
public TextGraphics drawLine(int fromX, int fromY, int toX, int toY, TextCharacter character) {
backend.drawLine(fromX, fromY, toX, toY, character);
return this;
}
//@Override
public TextGraphics drawImage(TerminalPosition topLeft, TextImage image) {
backend.drawImage(topLeft, image);
return this;
}
//@Override
public TextGraphics drawImage(TerminalPosition topLeft, TextImage image, TerminalPosition sourceImageTopLeft, TerminalSize sourceImageSize) {
backend.drawImage(topLeft, image, sourceImageTopLeft, sourceImageSize);
return this;
}
//@Override
public TextGraphics setCharacter(TerminalPosition position, char character) {
backend.setCharacter(position, character);
return this;
}
//@Override
public TextGraphics setCharacter(TerminalPosition position, TextCharacter character) {
backend.setCharacter(position, character);
return this;
}
//@Override
public TextGraphics setCharacter(int column, int row, char character) {
backend.setCharacter(column, row, character);
return this;
}
//@Override
public TextGraphics setCharacter(int column, int row, TextCharacter character) {
backend.setCharacter(column, row, character);
return this;
}
//@Override
public /*ImmutableThemed*/TextGraphics putString(int column, int row, String @string) {
backend.putString(column, row, @string);
return this;
}
//@Override
public /*ImmutableThemed*/TextGraphics putString(TerminalPosition position, String @string) {
backend.putString(position, @string);
return this;
}
//@Override
//public ImmutableThemedTextGraphics putString(int column, int row, String string, SGR extraModifier, SGR... optionalExtraModifiers) {
// backend.putString(column, row, string, extraModifier, optionalExtraModifiers);
// return this;
//}
//@Override
//public ImmutableThemedTextGraphics putString(TerminalPosition position, String string, SGR extraModifier, SGR... optionalExtraModifiers) {
// backend.putString(position, string, extraModifier, optionalExtraModifiers);
// return this;
//}
//@Override
//public TextGraphics putString(int column, int row, String string, Collection<SGR> extraModifiers) {
// backend.putString(column, row, string, extraModifiers);
// return this;
//}
//@Override
public TextCharacter getCharacter(TerminalPosition position) {
return backend.getCharacter(position);
}
//@Override
public TextCharacter getCharacter(int column, int row) {
return backend.getCharacter(column, row);
}
}
}
| |
//
// Native.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright 2014 Aaron Bockover
//
// 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.Runtime.InteropServices;
namespace Curl
{
public static class Native
{
const string LIBCURL = "libcurl";
public static class Easy
{
[DllImport (LIBCURL, EntryPoint = "curl_easy_init")]
public static extern IntPtr Init ();
[DllImport (LIBCURL, EntryPoint = "curl_easy_cleanup")]
public static extern void Cleanup (IntPtr handle);
[DllImport (LIBCURL, EntryPoint = "curl_easy_perform")]
public static extern Code Perform (IntPtr handle);
[DllImport (LIBCURL, EntryPoint = "curl_easy_setopt")]
public static extern Code SetOpt (IntPtr handle, Option option, int value);
[DllImport (LIBCURL, EntryPoint = "curl_easy_setopt")]
public static extern Code SetOpt (IntPtr handle, Option option, IntPtr value);
public unsafe static Code SetOpt (IntPtr handle, Option option, string value)
{
if (value == null)
return SetOpt (handle, option, IntPtr.Zero);
var bytes = System.Text.Encoding.UTF8.GetBytes (value);
fixed (byte *ptr = bytes)
return SetOpt (handle, option, new IntPtr (ptr));
}
public delegate IntPtr DataHandler (IntPtr data, IntPtr size, IntPtr nmemb, IntPtr userdata);
[DllImport (LIBCURL, EntryPoint = "curl_easy_setopt")]
public static extern Code SetOpt (IntPtr handle, Option option, DataHandler value);
[DllImport (LIBCURL, EntryPoint = "curl_easy_getinfo")]
public static extern Code GetInfo (IntPtr handle, Info option, out int value);
[DllImport (LIBCURL, EntryPoint = "curl_easy_getinfo")]
public static extern Code GetInfo (IntPtr handle, Info option, out IntPtr value);
[DllImport (LIBCURL, EntryPoint = "curl_easy_getinfo")]
public static extern Code GetInfo (IntPtr handle, Info option, out double value);
}
public static class Multi
{
[DllImport (LIBCURL, EntryPoint = "curl_multi_init")]
public static extern IntPtr Init ();
[DllImport (LIBCURL, EntryPoint = "curl_multi_cleanup")]
public static extern MultiCode Cleanup (IntPtr multiHandle);
[DllImport (LIBCURL, EntryPoint = "curl_multi_add_handle")]
public static extern MultiCode AddHandle (IntPtr multiHandle, IntPtr easyHandle);
[DllImport (LIBCURL, EntryPoint = "curl_multi_remove_handle")]
public static extern MultiCode RemoveHandle (IntPtr multiHandle, IntPtr easyHandle);
[DllImport (LIBCURL, EntryPoint = "curl_multi_perform")]
public static extern MultiCode Perform (IntPtr multiHandle, ref int runningHandles);
[DllImport (LIBCURL, EntryPoint = "curl_multi_fdset")]
public static extern MultiCode FdSet (IntPtr multiHandle, IntPtr readfds, IntPtr writefds, IntPtr errorfds, ref int maxfds);
[DllImport (LIBCURL, EntryPoint = "curl_multi_timeout")]
public static extern MultiCode Timeout (IntPtr multiHandle, ref int timeout);
}
public class Select : IDisposable
{
const int FD_SETSIZE = 32; // __DARWIN_FD_SETSIZE
struct timeval {
public int tv_sec;
public int tv_usec;
}
[DllImport ("libc")]
static extern int select (int nfds, IntPtr readfds, IntPtr writefds, IntPtr errorfds, ref timeval timeout);
[DllImport ("libc")]
static extern IntPtr memset (IntPtr b, int c, IntPtr len);
public delegate bool SetFdsHandler (IntPtr readfds, IntPtr writefds, IntPtr errorfds, ref int maxfds);
IntPtr readfds = Marshal.AllocHGlobal (FD_SETSIZE);
IntPtr writefds = Marshal.AllocHGlobal (FD_SETSIZE);
IntPtr errorfds = Marshal.AllocHGlobal (FD_SETSIZE);
~Select ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (readfds != IntPtr.Zero) {
Marshal.FreeHGlobal (readfds);
readfds = IntPtr.Zero;
}
if (writefds != IntPtr.Zero) {
Marshal.FreeHGlobal (writefds);
writefds = IntPtr.Zero;
}
if (errorfds != IntPtr.Zero) {
Marshal.FreeHGlobal (errorfds);
errorfds = IntPtr.Zero;
}
}
public bool Perform (Func<TimeSpan> requestedTimeout = null, SetFdsHandler setFds = null)
{
if (readfds == IntPtr.Zero || writefds == IntPtr.Zero || errorfds == IntPtr.Zero)
throw new ObjectDisposedException ("Select");
int maxfds = -1;
memset (readfds, 0, (IntPtr)FD_SETSIZE);
memset (writefds, 0, (IntPtr)FD_SETSIZE);
memset (errorfds, 0, (IntPtr)FD_SETSIZE);
var timeout = new timeval ();
if (requestedTimeout != null) {
var timespan = requestedTimeout ();
if (timespan == TimeSpan.Zero)
return true;
timeout.tv_sec = (int)(timespan.Ticks / TimeSpan.TicksPerSecond);
timeout.tv_usec = (int)(timespan.Ticks % TimeSpan.TicksPerSecond / TimeSpan.TicksPerMillisecond);
}
if (setFds != null) {
if (!setFds (readfds, writefds, errorfds, ref maxfds))
return false;
}
return select (maxfds + 1, readfds, writefds, errorfds, ref timeout) == 0;
}
}
public enum MultiCode
{
CALL_MULTI_PERFORM = -1,
OK,
BAD_HANDLE,
BAD_EASY_HANDLE,
OUT_OF_MEMORY,
INTERNAL_ERROR,
BAD_SOCKET,
UNKNOWN_OPTION,
LAST
}
public enum Code : uint
{
OK = 0,
UNSUPPORTED_PROTOCOL,
FAILED_INIT,
URL_MALFORMAT,
NOT_BUILT_IN,
COULDNT_RESOLVE_PROXY,
COULDNT_RESOLVE_HOST,
COULDNT_CONNECT,
FTP_WEIRD_SERVER_REPLY,
REMOTE_ACCESS_DENIED,
FTP_ACCEPT_FAILED,
FTP_WEIRD_PASS_REPLY,
FTP_ACCEPT_TIMEOUT,
FTP_WEIRD_PASV_REPLY,
FTP_WEIRD_227_FORMAT,
FTP_CANT_GET_HOST,
OBSOLETE16,
FTP_COULDNT_SET_TYPE,
PARTIAL_FILE,
FTP_COULDNT_RETR_FILE,
OBSOLETE20,
QUOTE_ERROR,
HTTP_RETURNED_ERROR,
WRITE_ERROR,
OBSOLETE24,
UPLOAD_FAILED,
READ_ERROR,
OUT_OF_MEMORY,
OPERATION_TIMEDOUT,
OBSOLETE29,
FTP_PORT_FAILED,
FTP_COULDNT_USE_REST,
OBSOLETE32,
RANGE_ERROR,
HTTP_POST_ERROR,
SSL_CONNECT_ERROR,
BAD_DOWNLOAD_RESUME,
FILE_COULDNT_READ_FILE,
LDAP_CANNOT_BIND,
LDAP_SEARCH_FAILED,
OBSOLETE40,
FUNCTION_NOT_FOUND,
ABORTED_BY_CALLBACK,
BAD_FUNCTION_ARGUMENT,
OBSOLETE44,
INTERFACE_FAILED,
OBSOLETE46,
TOO_MANY_REDIRECTS,
UNKNOWN_OPTION,
TELNET_OPTION_SYNTAX,
OBSOLETE50,
PEER_FAILED_VERIFICATION,
GOT_NOTHING,
SSL_ENGINE_NOTFOUND,
SSL_ENGINE_SETFAILED,
SEND_ERROR,
RECV_ERROR,
OBSOLETE57,
SSL_CERTPROBLEM,
SSL_CIPHER,
SSL_CACERT,
BAD_CONTENT_ENCODING,
LDAP_INVALID_URL,
FILESIZE_EXCEEDED,
USE_SSL_FAILED,
SEND_FAIL_REWIND,
SSL_ENGINE_INITFAILED,
LOGIN_DENIED,
TFTP_NOTFOUND,
TFTP_PERM,
REMOTE_DISK_FULL,
TFTP_ILLEGAL,
TFTP_UNKNOWNID,
REMOTE_FILE_EXISTS,
TFTP_NOSUCHUSER,
CONV_FAILED,
CONV_REQD,
SSL_CACERT_BADFILE,
REMOTE_FILE_NOT_FOUND,
SSH,
SSL_SHUTDOWN_FAILED,
AGAIN,
SSL_CRL_BADFILE,
SSL_ISSUER_ERROR,
FTP_PRET_FAILED,
RTSP_CSEQ_ERROR,
RTSP_SESSION_ERROR,
FTP_BAD_FILE_LIST,
CHUNK_FAILED,
NO_CONNECTION_AVAILABLE,
LAST
}
public enum Option : uint
{
CURLOPT_FILE = 10000 + 1,
URL = 10000 + 2,
PORT = 0 + 3,
PROXY = 10000 + 4,
USERPWD = 10000 + 5,
PROXYUSERPWD = 10000 + 6,
RANGE = 10000 + 7,
INFILE = 10000 + 9,
ERRORBUFFER = 10000 + 10,
WRITEFUNCTION = 20000 + 11,
READFUNCTION = 20000 + 12,
TIMEOUT = 0 + 13,
INFILESIZE = 0 + 14,
POSTFIELDS = 10000 + 15,
REFERER = 10000 + 16,
FTPPORT = 10000 + 17,
USERAGENT = 10000 + 18,
LOW_SPEED_LIMIT = 0 + 19,
LOW_SPEED_TIME = 0 + 20,
RESUME_FROM = 0 + 21,
COOKIE = 10000 + 22,
HTTPHEADER = 10000 + 23,
HTTPPOST = 10000 + 24,
SSLCERT = 10000 + 25,
KEYPASSWD = 10000 + 26,
CRLF = 0 + 27,
QUOTE = 10000 + 28,
WRITEHEADER = 10000 + 29,
COOKIEFILE = 10000 + 31,
SSLVERSION = 0 + 32,
TIMECONDITION = 0 + 33,
TIMEVALUE = 0 + 34,
CUSTOMREQUEST = 10000 + 36,
STDERR = 10000 + 37,
POSTQUOTE = 10000 + 39,
WRITEINFO = 10000 + 40,
VERBOSE = 0 + 41,
HEADER = 0 + 42,
NOPROGRESS = 0 + 43,
NOBODY = 0 + 44,
FAILONERROR = 0 + 45,
UPLOAD = 0 + 46,
POST = 0 + 47,
DIRLISTONLY = 0 + 48,
APPEND = 0 + 50,
NETRC = 0 + 51,
FOLLOWLOCATION = 0 + 52,
TRANSFERTEXT = 0 + 53,
PUT = 0 + 54,
PROGRESSFUNCTION = 20000 + 56,
PROGRESSDATA = 10000 + 57,
AUTOREFERER = 0 + 58,
PROXYPORT = 0 + 59,
POSTFIELDSIZE = 0 + 60,
HTTPPROXYTUNNEL = 0 + 61,
INTERFACE = 10000 + 62,
KRBLEVEL = 10000 + 63,
SSL_VERIFYPEER = 0 + 64,
CAINFO = 10000 + 65,
MAXREDIRS = 0 + 68,
FILETIME = 0 + 69,
TELNETOPTIONS = 10000 + 70,
MAXCONNECTS = 0 + 71,
CLOSEPOLICY = 0 + 72,
FRESH_CONNECT = 0 + 74,
FORBID_REUSE = 0 + 75,
RANDOM_FILE = 10000 + 76,
EGDSOCKET = 10000 + 77,
CONNECTTIMEOUT = 0 + 78,
HEADERFUNCTION = 20000 + 79,
HTTPGET = 0 + 80,
SSL_VERIFYHOST = 0 + 81,
COOKIEJAR = 10000 + 82,
SSL_CIPHER_LIST = 10000 + 83,
HTTP_VERSION = 0 + 84,
FTP_USE_EPSV = 0 + 85,
SSLCERTTYPE = 10000 + 86,
SSLKEY = 10000 + 87,
SSLKEYTYPE = 10000 + 88,
SSLENGINE = 10000 + 89,
SSLENGINE_DEFAULT = 0 + 90,
DNS_USE_GLOBAL_CACHE = 0 + 91,
DNS_CACHE_TIMEOUT = 0 + 92,
PREQUOTE = 10000 + 93,
DEBUGFUNCTION = 20000 + 94,
DEBUGDATA = 10000 + 95,
COOKIESESSION = 0 + 96,
CAPATH = 10000 + 97,
BUFFERSIZE = 0 + 98,
NOSIGNAL = 0 + 99,
SHARE = 10000 + 100,
PROXYTYPE = 0 + 101,
ACCEPT_ENCODING = 10000 + 102,
PRIVATE = 10000 + 103,
HTTP200ALIASES = 10000 + 104,
UNRESTRICTED_AUTH = 0 + 105,
FTP_USE_EPRT = 0 + 106,
HTTPAUTH = 0 + 107,
SSL_CTX_FUNCTION = 20000 + 108,
SSL_CTX_DATA = 10000 + 109,
FTP_CREATE_MISSING_DIRS = 0 + 110,
PROXYAUTH = 0 + 111,
FTP_RESPONSE_TIMEOUT = 0 + 112,
IPRESOLVE = 0 + 113,
MAXFILESIZE = 0 + 114,
INFILESIZE_LARGE = 30000 + 115,
RESUME_FROM_LARGE = 30000 + 116,
MAXFILESIZE_LARGE = 30000 + 117,
NETRC_FILE = 10000 + 118,
USE_SSL = 0 + 119,
POSTFIELDSIZE_LARGE = 30000 + 120,
TCP_NODELAY = 0 + 121,
FTPSSLAUTH = 0 + 129,
IOCTLFUNCTION = 20000 + 130,
IOCTLDATA = 10000 + 131,
FTP_ACCOUNT = 10000 + 134,
COOKIELIST = 10000 + 135,
IGNORE_CONTENT_LENGTH = 0 + 136,
FTP_SKIP_PASV_IP = 0 + 137,
FTP_FILEMETHOD = 0 + 138,
LOCALPORT = 0 + 139,
LOCALPORTRANGE = 0 + 140,
CONNECT_ONLY = 0 + 141,
CONV_FROM_NETWORK_FUNCTION = 20000 + 142,
CONV_TO_NETWORK_FUNCTION = 20000 + 143,
CONV_FROM_UTF8_FUNCTION = 20000 + 144,
MAX_SEND_SPEED_LARGE = 30000 + 145,
MAX_RECV_SPEED_LARGE = 30000 + 146,
FTP_ALTERNATIVE_TO_USER = 10000 + 147,
SOCKOPTFUNCTION = 20000 + 148,
SOCKOPTDATA = 10000 + 149,
SSL_SESSIONID_CACHE = 0 + 150,
SSH_AUTH_TYPES = 0 + 151,
SSH_PUBLIC_KEYFILE = 10000 + 152,
SSH_PRIVATE_KEYFILE = 10000 + 153,
FTP_SSL_CCC = 0 + 154,
TIMEOUT_MS = 0 + 155,
CONNECTTIMEOUT_MS = 0 + 156,
HTTP_TRANSFER_DECODING = 0 + 157,
HTTP_CONTENT_DECODING = 0 + 158,
NEW_FILE_PERMS = 0 + 159,
NEW_DIRECTORY_PERMS = 0 + 160,
POSTREDIR = 0 + 161,
SSH_HOST_PUBLIC_KEY_MD5 = 10000 + 162,
OPENSOCKETFUNCTION = 20000 + 163,
OPENSOCKETDATA = 10000 + 164,
COPYPOSTFIELDS = 10000 + 165,
PROXY_TRANSFER_MODE = 0 + 166,
SEEKFUNCTION = 20000 + 167,
SEEKDATA = 10000 + 168,
CRLFILE = 10000 + 169,
ISSUERCERT = 10000 + 170,
ADDRESS_SCOPE = 0 + 171,
CERTINFO = 0 + 172,
USERNAME = 10000 + 173,
PASSWORD = 10000 + 174,
PROXYUSERNAME = 10000 + 175,
PROXYPASSWORD = 10000 + 176,
NOPROXY = 10000 + 177,
TFTP_BLKSIZE = 0 + 178,
SOCKS5_GSSAPI_SERVICE = 10000 + 179,
SOCKS5_GSSAPI_NEC = 0 + 180,
PROTOCOLS = 0 + 181,
REDIR_PROTOCOLS = 0 + 182,
SSH_KNOWNHOSTS = 10000 + 183,
SSH_KEYFUNCTION = 20000 + 184,
SSH_KEYDATA = 10000 + 185,
MAIL_FROM = 10000 + 186,
MAIL_RCPT = 10000 + 187,
FTP_USE_PRET = 0 + 188,
RTSP_REQUEST = 0 + 189,
RTSP_SESSION_ID = 10000 + 190,
RTSP_STREAM_URI = 10000 + 191,
RTSP_TRANSPORT = 10000 + 192,
RTSP_CLIENT_CSEQ = 0 + 193,
RTSP_SERVER_CSEQ = 0 + 194,
INTERLEAVEDATA = 10000 + 195,
INTERLEAVEFUNCTION = 20000 + 196,
WILDCARDMATCH = 0 + 197,
CHUNK_BGN_FUNCTION = 20000 + 198,
CHUNK_END_FUNCTION = 20000 + 199,
FNMATCH_FUNCTION = 20000 + 200,
CHUNK_DATA = 10000 + 201,
FNMATCH_DATA = 10000 + 202,
RESOLVE = 10000 + 203,
TLSAUTH_USERNAME = 10000 + 204,
TLSAUTH_PASSWORD = 10000 + 205,
TLSAUTH_TYPE = 10000 + 206,
TRANSFER_ENCODING = 0 + 207,
CLOSESOCKETFUNCTION = 20000 + 208,
CLOSESOCKETDATA = 10000 + 209,
GSSAPI_DELEGATION = 0 + 210,
DNS_SERVERS = 10000 + 211,
ACCEPTTIMEOUT_MS = 0 + 212,
TCP_KEEPALIVE = 0 + 213,
TCP_KEEPIDLE = 0 + 214,
TCP_KEEPINTVL = 0 + 215,
SSL_OPTIONS = 0 + 216,
MAIL_AUTH = 10000 + 217,
LASTENTRY
}
public enum Info : uint {
NONE,
EFFECTIVE_URL = 1048576 + 1,
RESPONSE_CODE = 2097152 + 2,
TOTAL_TIME = 3145728 + 3,
NAMELOOKUP_TIME = 3145728 + 4,
CONNECT_TIME = 3145728 + 5,
PRETRANSFER_TIME = 3145728 + 6,
SIZE_UPLOAD = 3145728 + 7,
SIZE_DOWNLOAD = 3145728 + 8,
SPEED_DOWNLOAD = 3145728 + 9,
SPEED_UPLOAD = 3145728 + 10,
HEADER_SIZE = 2097152 + 11,
REQUEST_SIZE = 2097152 + 12,
SSL_VERIFYRESULT = 2097152 + 13,
FILETIME = 2097152 + 14,
CONTENT_LENGTH_DOWNLOAD = 3145728 + 15,
CONTENT_LENGTH_UPLOAD = 3145728 + 16,
STARTTRANSFER_TIME = 3145728 + 17,
CONTENT_TYPE = 1048576 + 18,
REDIRECT_TIME = 3145728 + 19,
REDIRECT_COUNT = 2097152 + 20,
PRIVATE = 1048576 + 21,
HTTP_CONNECTCODE = 2097152 + 22,
HTTPAUTH_AVAIL = 2097152 + 23,
PROXYAUTH_AVAIL = 2097152 + 24,
OS_ERRNO = 2097152 + 25,
NUM_CONNECTS = 2097152 + 26,
SSL_ENGINES = 4194304 + 27,
COOKIELIST = 4194304 + 28,
LASTSOCKET = 2097152 + 29,
FTP_ENTRY_PATH = 1048576 + 30,
REDIRECT_URL = 1048576 + 31,
PRIMARY_IP = 1048576 + 32,
APPCONNECT_TIME = 3145728 + 33,
CERTINFO = 4194304 + 34,
CONDITION_UNMET = 2097152 + 35,
RTSP_SESSION_ID = 1048576 + 36,
RTSP_CLIENT_CSEQ = 2097152 + 37,
RTSP_SERVER_CSEQ = 2097152 + 38,
RTSP_CSEQ_RECV = 2097152 + 39,
PRIMARY_PORT = 2097152 + 40,
LOCAL_IP = 1048576 + 41,
LOCAL_PORT = 2097152 + 42,
LASTONE = 42
}
}
}
| |
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pash.Implementation;
namespace Pash.ParserIntrinsics.Tests
{
[TestFixture]
public class ParserTests
{
[Test]
public void GrammarErrorsCount()
{
// Obviously, we'd rather drive this to 0, but for now, let's lock it down
//
// Report this number in https://github.com/Pash-Project/Pash/issues/38
Assert.AreEqual(2, Parser.IronyParser.Language.Errors.Count, Parser.IronyParser.Language.Errors.JoinString("\r\n"));
}
[Test]
public void MultilineIfTest()
{
AssertIsValidInput(@"
if ($true)
{
}
");
}
[Test]
public void MultilineHashTable()
{
AssertIsValidInput(@"
@{
a = 'b'
c = 'd'
}
");
}
[Test]
[TestCase(@"if ($true) {}")]
[TestCase(@"if ($true) { }")] // having whitespace here was causing a parse error.
[TestCase(@"if ($host.Name -eq ""Console"") { }")]
[TestCase(@"if ($host.Name -ne ""Console"") { }")]
[TestCase(@"if ($true) {} else {}")]
[TestCase(@"if ($true) {} elseif ($true) {} ")]
[TestCase(@"if ($true) {} elseif ($true) {} else {}")]
[TestCase(@"if ($true) {} elseif ($true) {} elseif ($true) {} else {}")]
public void IfElseSyntax(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"[int]")]
[TestCase(@"[int][string]7")] // double cast is OK
[TestCase(@"[int]-3"), Description("Cast, not subtraction")]
[TestCase(@"[int],[string]")]
[TestCase(@"$x = [int]")]
[TestCase(@"$x::MaxValue")]
[TestCase(@"[int]::Parse('7')")]
[TestCase(@"$x::Parse()")]
[TestCase(@"$x.Assembly")]
[TestCase(@"$x.AsType()")]
[TestCase(@"[char]::IsUpper(""AbC"", 1)", Description = "two parameters")]
public void TypesAndMembers(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"[int] ::MaxValue")]
public void WhitespaceProhibition(string input)
{
AssertIsNotValidInput(input);
}
[Test]
[TestCase(@"$i = 100 # $i designates an int value 100@")]
[TestCase(@"$j = $i # $j designates an int value 100, which is a copy@")]
[TestCase(@"$a = 10,20,30 # $a designates an object[], Length 3, value 10,20,30@")]
[TestCase(@"$b = $a # $b designates exactly the same array as does $a, not a copy@")]
[TestCase(@"$a[1] = 50 # element 1 (which has a value type) is changed from 20 to 50 @")]
[TestCase(@"$b[1] # $b refers to the same array as $a, so $b[1] is 50@")]
public void Section4_Types(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"$a = 10,20,30")]
[TestCase(@"$a.Length # get instance property")]
[TestCase(@"(10,20,30).Length")]
[TestCase(@"$property = ""Length""")]
[TestCase(@"$a.$property # property name is a variable")]
[TestCase(@"$h1 = @{ FirstName = ""James""; LastName = ""Anderson""; IDNum = 123 }")]
[TestCase(@"$h1.FirstName # designates the key FirstName")]
[TestCase(@"$h1.Keys # gets the collection of keys")]
[TestCase(@"[int]::MinValue # get static property")]
[TestCase(@"[double]::PositiveInfinity # get static property")]
[TestCase(@"$property = ""MinValue""")]
[TestCase(@"[long]::$property # property name is a variable")]
[TestCase(@"
foreach ($t in [byte],[int],[long])
{
$t::MaxValue # get static property
}
", Explicit = true)]
[TestCase(@"$a = @{ID=1},@{ID=2},@{ID=3}")]
[TestCase(@"$a.ID # get ID from each element in the array ")]
public void Section7_1_2_MemberAccess(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"[math]::Sqrt(2.0) # call method with argument 2.0")]
[TestCase(@"[char]::IsUpper(""a"") # call method")]
[TestCase(@"$b = ""abc#$%XYZabc""
$b.ToUpper() # call instance method")]
[TestCase(@"[math]::Sqrt(2) # convert 2 to 2.0 and call method")]
[TestCase(@"[math]::Sqrt(2D) # convert 2D to 2.0 and call method")]
[TestCase(@"[math]::Sqrt($true) # convert $true to 1.0 and call method")]
[TestCase(@"[math]::Sqrt(""20"") # convert ""20"" to 20 and call method")]
[TestCase(@"$a = [math]::Sqrt # get method descriptor for Sqrt")]
[TestCase(@"$a.Invoke(2.0) # call Sqrt via the descriptor")]
[TestCase(@"$a = [math]::(""Sq""+""rt"") # get method descriptor for Sqrt")]
[TestCase(@"$a.Invoke(2.0) # call Sqrt via the descriptor")]
[TestCase(@"$a = [char]::ToLower # get method descriptor for ToLower")]
[TestCase(@"$a.Invoke(""X"") # call ToLower via the descriptor")]
public void Section7_1_3_InvocationExpressions(string input)
{
AssertIsValidInput(input);
}
[TestCase(@"$a = [int[]](10,20,30) # [int[]], Length 3")]
[TestCase(@"$a[1] # returns int 20")]
[TestCase(@"$a[20] # no such position, returns $null")]
[TestCase(@"$a[-1] # returns int 30, i.e., $a[$a.Length-1]")]
[TestCase(@"$a[2] = 5 # changes int 30 to int 5")]
[TestCase(@"$a[20] = 5 # implementation-defined behavior")]
[TestCase(@"$a = New-Object 'double[,]' 3,2")]
[TestCase(@"$a[0,0] = 10.5 # changes 0.0 to 10.5")]
[TestCase(@"$a[0,0]++ # changes 10.5 to 10.6")]
[TestCase(@"$list = (""red"",$true,10),20,(1.2, ""yes"")")]
[TestCase(@"$list[2][1] # returns string ""yes""")]
[TestCase(@"$a = @{ A = 10 },@{ B = $true },@{ C = 123.45 }")]
[TestCase(@"$a[1][""B""] # $a[1] is a Hashtable, where B is a key")]
[TestCase(@"$a = ""red"",""green""")]
[TestCase(@"$a[1][4] # returns string ""n"" from string in $a[1]")]
public void Section7_1_4_1_SubscriptingAnArray(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"$s = ""Hello""")]
[TestCase(@"$s = ""Hello"" # string, Length 5, positions 0-4")]
[TestCase(@"$c = $s[1] # returns ""e"" as a string")]
[TestCase(@"$c = $s[20] # no such position, returns $null")]
[TestCase(@"$c = $s[-1] # returns ""o"", i.e., $s[$s.Length-1]")]
public void Section7_1_4_2_SubscriptingAString(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"[int[]](30,40,50,60,70,80,90)")]
[TestCase(@"$a = [int[]](30,40,50,60,70,80,90)")]
[TestCase(@"$a[1,3,5] # slice has Length 3, value 40,60,80")]
[TestCase(@"++$a[1,3,5][1] # preincrement 60 in array 40,60,80")]
[TestCase(@"$a[,5] # slice with Length 1")]
[TestCase(@"$a[@()] # slice with Length 0")]
[TestCase(@"$a[-1..-3] # slice with Length 0, value 90,80,70")]
[TestCase(@"$a = New-Object 'int[,]' 3,2")]
[TestCase(@"$a[0,0] = 10; $a[0,1] = 20; $a[1,0] = 30")]
[TestCase(@"$a[1,1] = 40; $a[2,0] = 50; $a[2,1] = 60")]
[TestCase(@"$a[(0,1),(1,0)] # slice with Length 2, value 20,30, parens needed")]
[TestCase(@"$h1 = @{ FirstName = ""James""; LastName = ""Anderson""; IDNum = 123 }")]
[TestCase(@"$h1['FirstName'] # the value associated with key FirstName")]
[TestCase(@"$h1['BirthDate'] # no such key, returns $null")]
[TestCase(@"$h1['FirstName','IDNum'] # returns [object[]], Length 2 (James/123)")]
[TestCase(@"$h1['FirstName','xxx'] # returns [object[]], Length 2 (James/$null)")]
[TestCase(@"$h1[$null,'IDNum'] # returns [object[]], Length 1 (123)")]
public void Section7_1_4_5GeneratingArraySlices(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"$i = 0 # $i = 0")]
[TestCase(@"$i++ # $i is incremented by 1")]
[TestCase(@"$j = $i-- # $j takes on the value of $i before the decrement")]
[TestCase(@"$a = 1,2,3")]
[TestCase(@"$b = 9,8,7")]
[TestCase(@"$i = 0")]
[TestCase(@"$j = 1")]
[TestCase(@"$b[$j--] = $a[$i++] # $b[1] takes on the value of $a[0], then $j is")]
[TestCase(@" # decremented, $i incremented")]
[TestCase(@"$i = 2147483647 # $i holds a value of type int")]
[TestCase(@"$i++ # $i now holds a value of type double because")]
[TestCase(@" # 2147483648 is too big to fit in type int")]
[TestCase(@"[int]$k = 0 # $k is constrained to int", Explicit = true)]
[TestCase(@"$k = [int]::MaxValue # $k is set to 2147483647")]
[TestCase(@"$k++ # 2147483648 is too big to fit, imp-def bahavior")]
[TestCase(@"$x = $null # target is unconstrained, $null goes to [int]0")]
[TestCase(@"$x++ # value treated as int, 0->1")]
public void Section7_1_5_Postfix_Increment_And_DecrementOperators(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"$j = 20")]
[TestCase(@"$($i = 10) # pipeline gets nothing")]
[TestCase(@"$(($i = 10)) # pipeline gets int 10")]
[TestCase(@"$($i = 10; $j) # pipeline gets int 20")]
[TestCase(@"$(($i = 10); $j) # pipeline gets [object[]](10,20)")]
[TestCase(@"$(($i = 10); ++$j) # pipeline gets int 10")]
[TestCase(@"$(($i = 10); (++$j)) # pipeline gets [object[]](10,22)")]
[TestCase(@"$($i = 10; ++$j) # pipeline gets nothing")]
[TestCase(@"$(2,4,6) # pipeline gets [object[]](2,4,6)")]
public void Section7_1_6_SubexpressionOperator(string input)
{
AssertIsValidInput(input);
}
[Test]
public void StringWithDollarSign()
{
// This `$%` threw off the tokenizer
AssertIsValidInput(@"""abc#$%XYZabc""");
}
[Test]
public void ArrayLiteralParameter()
{
AssertIsValidInput(@"echo 1,2");
}
[Test]
public void UnaryArrayLiteralParameterShouldFail()
{
AssertIsNotValidInput(@"echo ,2");
}
[Test]
public void ParenthesisedUnaryArrayLiteralParameter()
{
AssertIsValidInput(@"echo (,2)");
}
[Test]
public void BinaryOperatorTest()
{
AssertIsValidInput(@"$foo.bar -or $true");
}
static void AssertIsValidInput(string input)
{
var parseTree = Parser.IronyParser.Parse(input);
if (parseTree.HasErrors())
{
Assert.Fail(parseTree.ParserMessages[0].ToString());
}
}
static void AssertIsNotValidInput(string input)
{
var parseTree = Parser.IronyParser.Parse(input);
if (!parseTree.HasErrors())
{
Assert.Fail();
}
}
}
}
| |
namespace AgileObjects.AgileMapper.ObjectPopulation
{
using System;
using System.Collections.Generic;
using System.Linq;
#if NET35
using Microsoft.Scripting.Ast;
#else
using System.Linq.Expressions;
#endif
using System.Reflection;
using ComplexTypes;
using Configuration.Dictionaries;
using Enumerables.Dictionaries;
using Extensions;
using Extensions.Internal;
using Members;
using Members.Dictionaries;
using Members.Population;
using NetStandardPolyfills;
using ReadableExpressions.Extensions;
internal class DictionaryMappingExpressionFactory : MappingExpressionFactoryBase
{
private readonly MemberPopulatorFactory _memberPopulatorFactory;
public DictionaryMappingExpressionFactory()
{
_memberPopulatorFactory = new MemberPopulatorFactory(GetAllTargetMembers);
}
#region Target Member Generation
private static IEnumerable<QualifiedMember> GetAllTargetMembers(ObjectMapperData mapperData)
{
var targetMembersFromSource = EnumerateAllTargetMembers(mapperData).ToArray();
var configuredDataSourceFactories = mapperData.MapperContext
.UserConfigurations
.QueryDataSourceFactories<ConfiguredDictionaryEntryDataSourceFactory>()
.Filter(mapperData, (md, dsf) => dsf.IsFor(md))
.ToArray();
if (configuredDataSourceFactories.None())
{
return targetMembersFromSource;
}
var configuredCustomTargetMembers =
GetConfiguredTargetMembers(configuredDataSourceFactories, targetMembersFromSource);
var allTargetMembers = targetMembersFromSource.Append(configuredCustomTargetMembers);
return allTargetMembers;
}
private static IEnumerable<QualifiedMember> EnumerateAllTargetMembers(ObjectMapperData mapperData)
{
var sourceMembers = GlobalContext.Instance.MemberCache.GetSourceMembers(mapperData.SourceType);
var targetDictionaryMember = (DictionaryTargetMember)mapperData.TargetMember;
var targetMembers = EnumerateTargetMembers(
sourceMembers,
targetDictionaryMember,
mapperData,
m => m.Name);
foreach (var targetMember in targetMembers)
{
yield return targetMember;
}
if (mapperData.IsRoot)
{
yield break;
}
foreach (var targetMember in GetParentContextFlattenedTargetMembers(mapperData, targetDictionaryMember))
{
yield return targetMember;
}
}
private static IEnumerable<DictionaryTargetMember> EnumerateTargetMembers(
IEnumerable<Member> sourceMembers,
DictionaryTargetMember targetDictionaryMember,
ObjectMapperData mapperData,
Func<Member, string> targetMemberNameFactory)
{
foreach (var sourceMember in sourceMembers)
{
var targetEntryMemberName = targetMemberNameFactory.Invoke(sourceMember);
var targetEntryMember = targetDictionaryMember.Append(sourceMember.DeclaringType, targetEntryMemberName);
if (targetDictionaryMember.HasObjectEntries)
{
targetEntryMember = (DictionaryTargetMember)targetEntryMember.WithType(sourceMember.Type);
}
var entryMapperData = new ChildMemberMapperData(targetEntryMember, mapperData);
var configuredKey = GetCustomKeyOrNull(entryMapperData);
if (configuredKey != null)
{
targetEntryMember.SetCustomKey(configuredKey);
}
if (!sourceMember.IsSimple && !targetDictionaryMember.HasComplexEntries)
{
targetEntryMember = targetEntryMember.WithTypeOf(sourceMember);
}
yield return targetEntryMember;
}
}
private static string GetCustomKeyOrNull(IMemberMapperData entryMapperData)
{
var dictionaries = entryMapperData.MapperContext.UserConfigurations.Dictionaries;
var configuredFullKey = dictionaries.GetFullKeyValueOrNull(entryMapperData);
return configuredFullKey ?? dictionaries.GetMemberKeyOrNull(entryMapperData);
}
private static IEnumerable<DictionaryTargetMember> GetParentContextFlattenedTargetMembers(
ObjectMapperData mapperData,
DictionaryTargetMember targetDictionaryMember)
{
while (mapperData.Parent != null)
{
mapperData = mapperData.Parent;
var sourceMembers = GlobalContext.Instance
.MemberCache
.GetSourceMembers(mapperData.SourceType)
.SelectMany(sm => MatchingFlattenedMembers(sm, targetDictionaryMember))
.ToArray();
var targetMembers = EnumerateTargetMembers(
sourceMembers,
targetDictionaryMember,
mapperData,
m => m.Name.StartsWithIgnoreCase(targetDictionaryMember.Name)
? m.Name.Substring(targetDictionaryMember.Name.Length)
: m.Name);
foreach (var targetMember in targetMembers)
{
yield return targetMember;
}
}
}
private static IEnumerable<Member> MatchingFlattenedMembers(Member sourceMember, IQualifiedMember targetDictionaryMember)
{
if (sourceMember.Name.EqualsIgnoreCase(targetDictionaryMember.Name))
{
return Enumerable<Member>.Empty;
}
if (sourceMember.Name.StartsWithIgnoreCase(targetDictionaryMember.Name))
{
// e.g. ValueLine1 -> Value
return new[] { sourceMember };
}
if (!targetDictionaryMember.Name.StartsWithIgnoreCase(sourceMember.Name))
{
return Enumerable<Member>.Empty;
}
// e.g. Val => Value
return GetNestedFlattenedMembers(sourceMember, sourceMember.Name, targetDictionaryMember.Name);
}
private static IEnumerable<Member> GetNestedFlattenedMembers(
Member parentMember,
string sourceMemberNameMatchSoFar,
string targetMemberName)
{
return GlobalContext.Instance
.MemberCache
.GetSourceMembers(parentMember.Type)
.SelectMany(sm =>
{
var flattenedSourceMemberName = sourceMemberNameMatchSoFar + sm.Name;
if (!targetMemberName.StartsWithIgnoreCase(flattenedSourceMemberName))
{
return Enumerable<Member>.Empty;
}
if (targetMemberName.EqualsIgnoreCase(flattenedSourceMemberName))
{
return GlobalContext.Instance
.MemberCache
.GetSourceMembers(sm.Type);
}
return GetNestedFlattenedMembers(
sm,
flattenedSourceMemberName,
targetMemberName);
})
.ToArray();
}
private static QualifiedMember[] GetConfiguredTargetMembers(
IEnumerable<ConfiguredDictionaryEntryDataSourceFactory> configuredDataSourceFactories,
IList<QualifiedMember> targetMembersFromSource)
{
return configuredDataSourceFactories
.GroupBy(dsf => dsf.TargetDictionaryEntryMember.Name)
.Project(targetMembersFromSource, (tmfs, group) =>
{
QualifiedMember targetMember = group.First().TargetDictionaryEntryMember;
targetMember.IsCustom = tmfs.None(
targetMember.Name,
(tmn, sourceMember) => sourceMember.RegistrationName == tmn);
return targetMember.IsCustom ? targetMember : null;
})
.WhereNotNull()
.ToArray();
}
#endregion
protected override bool TargetCannotBeMapped(IObjectMappingData mappingData, out string reason)
{
if (mappingData.MappingTypes.SourceType.IsDictionary())
{
return base.TargetCannotBeMapped(mappingData, out reason);
}
var targetMember = (DictionaryTargetMember)mappingData.MapperData.TargetMember;
if ((targetMember.KeyType == typeof(string)) || (targetMember.KeyType == typeof(object)))
{
return base.TargetCannotBeMapped(mappingData, out reason);
}
reason = "Only string- or object-keyed Dictionaries are supported";
return true;
}
protected override Expression GetNullMappingFallbackValue(IMemberMapperData mapperData)
=> mapperData.GetFallbackCollectionValue();
protected override void AddObjectPopulation(MappingCreationContext context)
{
Expression population;
if (!context.MapperData.TargetMember.IsDictionary)
{
population = GetDictionaryPopulation(context.MappingData);
goto ReturnPopulation;
}
var assignmentFactory = GetDictionaryAssignmentFactoryOrNull(context, out var useAssignmentOnly);
if (useAssignmentOnly)
{
context.MappingExpressions.Add(assignmentFactory.Invoke(context.MappingData));
return;
}
population = GetDictionaryPopulation(context.MappingData);
var assignment = assignmentFactory?.Invoke(context.MappingData);
if (assignment != null)
{
context.MappingExpressions.Add(assignment);
}
ReturnPopulation:
context.MappingExpressions.AddUnlessNullOrEmpty(population);
}
private static Func<IObjectMappingData, Expression> GetDictionaryAssignmentFactoryOrNull(
MappingCreationContext context,
out bool useAssignmentOnly)
{
if (!context.InstantiateLocalVariable || context.MapperData.TargetMember.IsReadOnly)
{
useAssignmentOnly = false;
return null;
}
var mapperData = context.MapperData;
if (SourceMemberIsDictionary(mapperData, out var sourceDictionaryMember))
{
if (UseDictionaryCloneConstructor(sourceDictionaryMember, mapperData, out var cloneConstructor))
{
useAssignmentOnly = true;
return md => GetClonedDictionaryAssignment(md.MapperData, cloneConstructor);
}
useAssignmentOnly = false;
return md => GetMappedDictionaryAssignment(sourceDictionaryMember, md);
}
useAssignmentOnly = false;
return GetParameterlessDictionaryAssignment;
}
private static bool SourceMemberIsDictionary(
IMemberMapperData mapperData,
out DictionarySourceMember sourceDictionaryMember)
{
sourceDictionaryMember = mapperData.GetDictionarySourceMemberOrNull();
return sourceDictionaryMember != null;
}
private static bool UseDictionaryCloneConstructor(
IQualifiedMember sourceDictionaryMember,
IQualifiedMemberContext context,
out ConstructorInfo cloneConstructor)
{
cloneConstructor = null;
return (sourceDictionaryMember.Type == context.TargetType) &&
context.TargetMember.ElementType.IsSimple() &&
((cloneConstructor = GetDictionaryCloneConstructor(context)) != null);
}
private static ConstructorInfo GetDictionaryCloneConstructor(ITypePair mapperData)
{
var dictionaryTypes = mapperData.TargetType.GetDictionaryTypes();
var dictionaryInterfaceType = typeof(IDictionary<,>).MakeGenericType(dictionaryTypes.Key, dictionaryTypes.Value);
var comparerProperty = mapperData.SourceType.GetPublicInstanceProperty("Comparer");
return FindDictionaryConstructor(
mapperData.TargetType,
dictionaryInterfaceType,
(comparerProperty != null) ? 2 : 1);
}
private static Expression GetClonedDictionaryAssignment(IMemberMapperData mapperData, ConstructorInfo cloneConstructor)
{
Expression cloneDictionary;
if (cloneConstructor.GetParameters().Length == 1)
{
cloneDictionary = Expression.New(cloneConstructor, mapperData.SourceObject);
}
else
{
var comparer = Expression.Property(mapperData.SourceObject, "Comparer");
cloneDictionary = Expression.New(cloneConstructor, mapperData.SourceObject, comparer);
}
var assignment = mapperData.TargetInstance.AssignTo(cloneDictionary);
return assignment;
}
private static ConstructorInfo FindDictionaryConstructor(
Type dictionaryType,
Type firstParameterType,
int numberOfParameters)
{
if (dictionaryType.IsInterface())
{
dictionaryType = GetConcreteDictionaryType(dictionaryType);
}
return dictionaryType
.GetPublicInstanceConstructors()
.Project(ctor => new { Ctor = ctor, Parameters = ctor.GetParameters() })
.First(ctor =>
(ctor.Parameters.Length == numberOfParameters) &&
(ctor.Parameters[0].ParameterType == firstParameterType))
.Ctor;
}
private static Type GetConcreteDictionaryType(Type dictionaryInterfaceType)
{
var types = dictionaryInterfaceType.GetDictionaryTypes();
return typeof(Dictionary<,>).MakeGenericType(types.Key, types.Value);
}
private static Expression GetMappedDictionaryAssignment(
DictionarySourceMember sourceDictionaryMember,
IObjectMappingData mappingData)
{
var mapperData = mappingData.MapperData;
if (UseParameterlessConstructor(sourceDictionaryMember, mapperData))
{
return GetParameterlessDictionaryAssignment(mappingData);
}
var comparerProperty = mapperData.SourceObject.Type.GetPublicInstanceProperty("Comparer");
var comparer = Expression.Property(mapperData.SourceObject, comparerProperty);
var constructor = FindDictionaryConstructor(
mapperData.TargetType,
comparer.Type,
numberOfParameters: 1);
var dictionaryConstruction = Expression.New(constructor, comparer);
return GetDictionaryAssignment(dictionaryConstruction, mappingData);
}
private static bool UseParameterlessConstructor(
DictionarySourceMember sourceDictionaryMember,
IQualifiedMemberContext context)
{
if (sourceDictionaryMember.Type.IsInterface())
{
return true;
}
return sourceDictionaryMember.ValueType != context.TargetMember.ElementType;
}
private static Expression GetParameterlessDictionaryAssignment(IObjectMappingData mappingData)
{
var helper = mappingData.MapperData.EnumerablePopulationBuilder.TargetTypeHelper;
var newDictionary = helper.GetEmptyInstanceCreation();
return GetDictionaryAssignment(newDictionary, mappingData);
}
private static Expression GetDictionaryAssignment(Expression value, IObjectMappingData mappingData)
{
var mapperData = mappingData.MapperData;
if (mapperData.TargetMember.IsReadOnly)
{
return null;
}
var valueResolution = TargetObjectResolutionFactory.GetObjectResolution(
value,
mappingData,
assignTargetObject: mapperData.HasRepeatedMapperFuncs);
if (valueResolution == mapperData.TargetInstance)
{
return null;
}
return mapperData.TargetInstance.AssignTo(valueResolution);
}
private Expression GetDictionaryPopulation(IObjectMappingData mappingData)
{
var mapperData = mappingData.MapperData;
if (mapperData.SourceMember.IsEnumerable)
{
return GetEnumerableToDictionaryMapping(mappingData);
}
var memberPopulations = _memberPopulatorFactory
.Create(mappingData)
.Project(memberPopulation => memberPopulation.GetPopulation())
.ToArray();
if (memberPopulations.None())
{
return null;
}
if (memberPopulations.HasOne())
{
return memberPopulations[0];
}
var memberPopulationBlock = Expression.Block(memberPopulations);
return memberPopulationBlock;
}
private static Expression GetEnumerableToDictionaryMapping(IObjectMappingData mappingData)
{
var builder = new DictionaryPopulationBuilder(mappingData.MapperData.EnumerablePopulationBuilder);
if (builder.HasSourceEnumerable)
{
builder.AssignSourceVariableFromSourceObject();
}
builder.AddItems(mappingData);
return builder;
}
}
}
| |
// Copyright (c) 2007-2012 Michael Chapman
// http://ipaddresscontrollib.googlecode.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.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Windows.Forms.Design.Behavior;
using System.Windows.Forms.VisualStyles;
namespace TCPUtils
{
namespace IPAddressControlBox
{
[DesignerAttribute(typeof(IPAddressControlDesigner))]
public class IPAddressControl : ContainerControl
{
#region Public Constants
public const int FieldCount = 4;
#endregion // Public Constants
#region Public Events
public event EventHandler<FieldChangedEventArgs> FieldChangedEvent;
#endregion //Public Events
#region Public Properties
[Browsable(true)]
public bool AllowInternalTab
{
get
{
foreach (FieldControl fc in _fieldControls)
{
return fc.TabStop;
}
return false;
}
set
{
foreach (FieldControl fc in _fieldControls)
{
fc.TabStop = value;
}
}
}
[Browsable(true)]
public bool AnyBlank
{
get
{
foreach (FieldControl fc in _fieldControls)
{
if (fc.Blank)
{
return true;
}
}
return false;
}
}
[Browsable(true)]
public bool AutoHeight
{
get { return _autoHeight; }
set
{
_autoHeight = value;
if (_autoHeight)
{
AdjustSize();
}
}
}
[Browsable(false)]
public int Baseline
{
get
{
NativeMethods.TEXTMETRIC textMetric = GetTextMetrics(Handle, Font);
int offset = textMetric.tmAscent + 1;
switch (BorderStyle)
{
case BorderStyle.Fixed3D:
offset += Fixed3DOffset.Height;
break;
case BorderStyle.FixedSingle:
offset += FixedSingleOffset.Height;
break;
}
return offset;
}
}
[Browsable(true)]
public bool Blank
{
get
{
foreach (FieldControl fc in _fieldControls)
{
if (!fc.Blank)
{
return false;
}
}
return true;
}
}
[Browsable(true)]
public BorderStyle BorderStyle
{
get { return _borderStyle; }
set
{
_borderStyle = value;
AdjustSize();
Invalidate();
}
}
[Browsable(false)]
public override bool Focused
{
get
{
foreach (FieldControl fc in _fieldControls)
{
if (fc.Focused)
{
return true;
}
}
return false;
}
}
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public IPAddress IPAddress
{
get { return new IPAddress(GetAddressBytes()); }
set
{
Clear();
if (null == value) { return; }
if (value.AddressFamily == AddressFamily.InterNetwork)
{
SetAddressBytes(value.GetAddressBytes());
}
}
}
[Browsable(true)]
public override Size MinimumSize
{
get { return CalculateMinimumSize(); }
}
[Browsable(true)]
public bool ReadOnly
{
get { return _readOnly; }
set
{
_readOnly = value;
foreach (FieldControl fc in _fieldControls)
{
fc.ReadOnly = _readOnly;
}
foreach (DotControl dc in _dotControls)
{
dc.ReadOnly = _readOnly;
}
Invalidate();
}
}
[Bindable(true)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text
{
get
{
StringBuilder sb = new StringBuilder(); ;
for (int index = 0; index < _fieldControls.Length; ++index)
{
sb.Append(_fieldControls[index].Text);
if (index < _dotControls.Length)
{
sb.Append(_dotControls[index].Text);
}
}
return sb.ToString();
}
set
{
Parse(value);
}
}
#endregion // Public Properties
#region Public Methods
public void Clear()
{
foreach (FieldControl fc in _fieldControls)
{
fc.Clear();
}
}
public byte[] GetAddressBytes()
{
byte[] bytes = new byte[FieldCount];
for (int index = 0; index < FieldCount; ++index)
{
bytes[index] = _fieldControls[index].Value;
}
return bytes;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", Justification = "Using Bytes seems more informative than SetAddressValues.")]
public void SetAddressBytes(byte[] bytes)
{
Clear();
if (bytes == null)
{
return;
}
int length = Math.Min(FieldCount, bytes.Length);
for (int i = 0; i < length; ++i)
{
_fieldControls[i].Text = bytes[i].ToString(CultureInfo.InvariantCulture);
}
}
public void SetFieldFocus(int fieldIndex)
{
if ((fieldIndex >= 0) && (fieldIndex < FieldCount))
{
_fieldControls[fieldIndex].TakeFocus(Direction.Forward, Selection.All);
}
}
public void SetFieldRange(int fieldIndex, byte rangeLower, byte rangeUpper)
{
if ((fieldIndex >= 0) && (fieldIndex < FieldCount))
{
_fieldControls[fieldIndex].RangeLower = rangeLower;
_fieldControls[fieldIndex].RangeUpper = rangeUpper;
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for (int index = 0; index < FieldCount; ++index)
{
sb.Append(_fieldControls[index].ToString());
if (index < _dotControls.Length)
{
sb.Append(_dotControls[index].ToString());
}
}
return sb.ToString();
}
#endregion Public Methods
#region Constructors
public IPAddressControl()
{
BackColor = SystemColors.Window;
ResetBackColorChanged();
for (int index = 0; index < _fieldControls.Length; ++index)
{
_fieldControls[index] = new FieldControl();
_fieldControls[index].CreateControl();
_fieldControls[index].FieldIndex = index;
_fieldControls[index].Name = "FieldControl" + index.ToString(CultureInfo.InvariantCulture);
_fieldControls[index].Parent = this;
_fieldControls[index].CedeFocusEvent += new EventHandler<CedeFocusEventArgs>(OnCedeFocus);
_fieldControls[index].Click += new EventHandler(OnSubControlClicked);
_fieldControls[index].DoubleClick += new EventHandler(OnSubControlDoubleClicked);
_fieldControls[index].GotFocus += new EventHandler(OnFieldGotFocus);
_fieldControls[index].KeyDown += new KeyEventHandler(OnFieldKeyDown);
_fieldControls[index].KeyPress += new KeyPressEventHandler(OnFieldKeyPressed);
_fieldControls[index].KeyUp += new KeyEventHandler(OnFieldKeyUp);
_fieldControls[index].LostFocus += new EventHandler(OnFieldLostFocus);
_fieldControls[index].MouseClick += new MouseEventHandler(OnSubControlMouseClicked);
_fieldControls[index].MouseDoubleClick += new MouseEventHandler(OnSubControlMouseDoubleClicked);
_fieldControls[index].MouseEnter += new EventHandler(OnSubControlMouseEntered);
_fieldControls[index].MouseHover += new EventHandler(OnSubControlMouseHovered);
_fieldControls[index].MouseLeave += new EventHandler(OnSubControlMouseLeft);
_fieldControls[index].MouseMove += new MouseEventHandler(OnSubControlMouseMoved);
_fieldControls[index].PreviewKeyDown += new PreviewKeyDownEventHandler(OnFieldPreviewKeyDown);
_fieldControls[index].TextChangedEvent += new EventHandler<TextChangedEventArgs>(OnFieldTextChanged);
Controls.Add(_fieldControls[index]);
if (index < (FieldCount - 1))
{
_dotControls[index] = new DotControl();
_dotControls[index].CreateControl();
_dotControls[index].Name = "DotControl" + index.ToString(CultureInfo.InvariantCulture);
_dotControls[index].Parent = this;
_dotControls[index].Click += new EventHandler(OnSubControlClicked);
_dotControls[index].DoubleClick += new EventHandler(OnSubControlDoubleClicked);
_dotControls[index].MouseClick += new MouseEventHandler(OnSubControlMouseClicked);
_dotControls[index].MouseDoubleClick += new MouseEventHandler(OnSubControlMouseDoubleClicked);
_dotControls[index].MouseEnter += new EventHandler(OnSubControlMouseEntered);
_dotControls[index].MouseHover += new EventHandler(OnSubControlMouseHovered);
_dotControls[index].MouseLeave += new EventHandler(OnSubControlMouseLeft);
_dotControls[index].MouseMove += new MouseEventHandler(OnSubControlMouseMoved);
Controls.Add(_dotControls[index]);
}
}
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.ContainerControl, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.FixedWidth, true);
SetStyle(ControlStyles.FixedHeight, true);
_referenceTextBox.AutoSize = true;
Cursor = Cursors.IBeam;
AutoScaleDimensions = new SizeF(96F, 96F);
AutoScaleMode = AutoScaleMode.Dpi;
Size = MinimumSize;
DragEnter += new DragEventHandler(IPAddressControl_DragEnter);
DragDrop += new DragEventHandler(IPAddressControl_DragDrop);
}
#endregion // Constructors
#region Protected Methods
protected override void Dispose(bool disposing)
{
if (disposing) { Cleanup(); }
base.Dispose(disposing);
}
protected override void OnBackColorChanged(EventArgs e)
{
base.OnBackColorChanged(e);
_backColorChanged = true;
}
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
AdjustSize();
}
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
_focused = true;
_fieldControls[0].TakeFocus(Direction.Forward, Selection.All);
}
protected override void OnLostFocus(EventArgs e)
{
if (!Focused)
{
_focused = false;
base.OnLostFocus(e);
}
}
protected override void OnMouseEnter(EventArgs e)
{
if (!_hasMouse)
{
_hasMouse = true;
base.OnMouseEnter(e);
}
}
protected override void OnMouseLeave(EventArgs e)
{
if (!HasMouse)
{
base.OnMouseLeave(e);
_hasMouse = false;
}
}
protected override void OnPaint(PaintEventArgs e)
{
if (null == e) { throw new ArgumentNullException("e"); }
base.OnPaint(e);
Color backColor = BackColor;
if (!_backColorChanged)
{
if (!Enabled || ReadOnly)
{
backColor = SystemColors.Control;
}
}
using (SolidBrush backgroundBrush = new SolidBrush(backColor))
{
e.Graphics.FillRectangle(backgroundBrush, ClientRectangle);
}
Rectangle rectBorder = new Rectangle(ClientRectangle.Left, ClientRectangle.Top,
ClientRectangle.Width - 1, ClientRectangle.Height - 1);
switch (BorderStyle)
{
case BorderStyle.Fixed3D:
if (Application.RenderWithVisualStyles)
{
using (Pen pen = new Pen(VisualStyleInformation.TextControlBorder))
{
e.Graphics.DrawRectangle(pen, rectBorder);
}
rectBorder.Inflate(-1, -1);
e.Graphics.DrawRectangle(SystemPens.Window, rectBorder);
}
else
{
ControlPaint.DrawBorder3D(e.Graphics, ClientRectangle, Border3DStyle.Sunken);
}
break;
case BorderStyle.FixedSingle:
ControlPaint.DrawBorder(e.Graphics, ClientRectangle,
SystemColors.WindowFrame, ButtonBorderStyle.Solid);
break;
}
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
AdjustSize();
}
#endregion // Protected Methods
#region Private Properties
private bool HasMouse
{
get
{
return DisplayRectangle.Contains(PointToClient(MousePosition));
}
}
#endregion // Private Properties
#region Private Methods
private void AdjustSize()
{
Size newSize = MinimumSize;
if (Width > newSize.Width)
{
newSize.Width = Width;
}
if (Height > newSize.Height)
{
newSize.Height = Height;
}
if (AutoHeight)
{
Size = new Size(newSize.Width, MinimumSize.Height);
}
else
{
Size = newSize;
}
LayoutControls();
}
private Size CalculateMinimumSize()
{
Size minimumSize = new Size(0, 0);
foreach (FieldControl fc in _fieldControls)
{
minimumSize.Width += fc.Width;
minimumSize.Height = Math.Max(minimumSize.Height, fc.Height);
}
foreach (DotControl dc in _dotControls)
{
minimumSize.Width += dc.Width;
minimumSize.Height = Math.Max(minimumSize.Height, dc.Height);
}
switch (BorderStyle)
{
case BorderStyle.Fixed3D:
minimumSize.Width += 6;
minimumSize.Height += (GetSuggestedHeight() - minimumSize.Height);
break;
case BorderStyle.FixedSingle:
minimumSize.Width += 4;
minimumSize.Height += (GetSuggestedHeight() - minimumSize.Height);
break;
}
return minimumSize;
}
private void Cleanup()
{
foreach (DotControl dc in _dotControls)
{
Controls.Remove(dc);
dc.Dispose();
}
foreach (FieldControl fc in _fieldControls)
{
Controls.Remove(fc);
fc.Dispose();
}
_dotControls = null;
_fieldControls = null;
}
private int GetSuggestedHeight()
{
_referenceTextBox.BorderStyle = BorderStyle;
_referenceTextBox.Font = Font;
return _referenceTextBox.Height;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806", Justification = "What should be done if ReleaseDC() doesn't work?")]
private static NativeMethods.TEXTMETRIC GetTextMetrics(IntPtr hwnd, Font font)
{
IntPtr hdc = NativeMethods.GetWindowDC(hwnd);
NativeMethods.TEXTMETRIC textMetric;
IntPtr hFont = font.ToHfont();
try
{
IntPtr hFontPrevious = NativeMethods.SelectObject(hdc, hFont);
NativeMethods.GetTextMetrics(hdc, out textMetric);
NativeMethods.SelectObject(hdc, hFontPrevious);
}
finally
{
NativeMethods.ReleaseDC(hwnd, hdc);
NativeMethods.DeleteObject(hFont);
}
return textMetric;
}
private void IPAddressControl_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
Text = e.Data.GetData(DataFormats.Text).ToString();
}
private void IPAddressControl_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LayoutControls()
{
SuspendLayout();
int difference = Width - MinimumSize.Width;
Debug.Assert(difference >= 0);
int numOffsets = _fieldControls.Length + _dotControls.Length + 1;
int div = difference / (numOffsets);
int mod = difference % (numOffsets);
int[] offsets = new int[numOffsets];
for (int index = 0; index < numOffsets; ++index)
{
offsets[index] = div;
if (index < mod)
{
++offsets[index];
}
}
int x = 0;
int y = 0;
switch (BorderStyle)
{
case BorderStyle.Fixed3D:
x = Fixed3DOffset.Width;
y = Fixed3DOffset.Height;
break;
case BorderStyle.FixedSingle:
x = FixedSingleOffset.Width;
y = FixedSingleOffset.Height;
break;
}
int offsetIndex = 0;
x += offsets[offsetIndex++];
for (int i = 0; i < _fieldControls.Length; ++i)
{
_fieldControls[i].Location = new Point(x, y);
x += _fieldControls[i].Width;
if (i < _dotControls.Length)
{
x += offsets[offsetIndex++];
_dotControls[i].Location = new Point(x, y);
x += _dotControls[i].Width;
x += offsets[offsetIndex++];
}
}
ResumeLayout(false);
}
private void OnCedeFocus(Object sender, CedeFocusEventArgs e)
{
switch (e.Action)
{
case Action.Home:
_fieldControls[0].TakeFocus(Action.Home);
return;
case Action.End:
_fieldControls[FieldCount - 1].TakeFocus(Action.End);
return;
case Action.Trim:
if (e.FieldIndex == 0)
{
return;
}
_fieldControls[e.FieldIndex - 1].TakeFocus(Action.Trim);
return;
}
if ((e.Direction == Direction.Reverse && e.FieldIndex == 0) ||
(e.Direction == Direction.Forward && e.FieldIndex == (FieldCount - 1)))
{
return;
}
int fieldIndex = e.FieldIndex;
if (e.Direction == Direction.Forward)
{
++fieldIndex;
}
else
{
--fieldIndex;
}
_fieldControls[fieldIndex].TakeFocus(e.Direction, e.Selection);
}
private void OnFieldGotFocus(Object sender, EventArgs e)
{
if (!_focused)
{
_focused = true;
base.OnGotFocus(EventArgs.Empty);
}
}
private void OnFieldKeyDown(Object sender, KeyEventArgs e)
{
OnKeyDown(e);
}
private void OnFieldKeyPressed(Object sender, KeyPressEventArgs e)
{
OnKeyPress(e);
}
private void OnFieldPreviewKeyDown(Object sender, PreviewKeyDownEventArgs e)
{
OnPreviewKeyDown(e);
}
private void OnFieldKeyUp(Object sender, KeyEventArgs e)
{
OnKeyUp(e);
}
private void OnFieldLostFocus(Object sender, EventArgs e)
{
if (!Focused)
{
_focused = false;
base.OnLostFocus(EventArgs.Empty);
}
}
private void OnFieldTextChanged(Object sender, TextChangedEventArgs e)
{
if (null != FieldChangedEvent)
{
FieldChangedEventArgs args = new FieldChangedEventArgs();
args.FieldIndex = e.FieldIndex;
args.Text = e.Text;
FieldChangedEvent(this, args);
}
OnTextChanged(EventArgs.Empty);
}
private void OnSubControlClicked(object sender, EventArgs e)
{
OnClick(e);
}
private void OnSubControlDoubleClicked(object sender, EventArgs e)
{
OnDoubleClick(e);
}
private void OnSubControlMouseClicked(object sender, MouseEventArgs e)
{
OnMouseClick(e);
}
private void OnSubControlMouseDoubleClicked(object sender, MouseEventArgs e)
{
OnMouseDoubleClick(e);
}
private void OnSubControlMouseEntered(object sender, EventArgs e)
{
OnMouseEnter(e);
}
private void OnSubControlMouseHovered(object sender, EventArgs e)
{
OnMouseHover(e);
}
private void OnSubControlMouseLeft(object sender, EventArgs e)
{
OnMouseLeave(e);
}
private void OnSubControlMouseMoved(object sender, MouseEventArgs e)
{
OnMouseMove(e);
}
private void Parse(String text)
{
Clear();
if (null == text)
{
return;
}
int textIndex = 0;
int index = 0;
for (index = 0; index < _dotControls.Length; ++index)
{
int findIndex = text.IndexOf(_dotControls[index].Text, textIndex, StringComparison.Ordinal);
if (findIndex >= 0)
{
_fieldControls[index].Text = text.Substring(textIndex, findIndex - textIndex);
textIndex = findIndex + _dotControls[index].Text.Length;
}
else
{
break;
}
}
_fieldControls[index].Text = text.Substring(textIndex);
}
// a hack to remove an FxCop warning
private void ResetBackColorChanged()
{
_backColorChanged = false;
}
#endregion Private Methods
#region Private Data
private bool _autoHeight = true;
private bool _backColorChanged;
private BorderStyle _borderStyle = BorderStyle.Fixed3D;
private DotControl[] _dotControls = new DotControl[FieldCount - 1];
private FieldControl[] _fieldControls = new FieldControl[FieldCount];
private bool _focused;
private bool _hasMouse;
private bool _readOnly;
private Size Fixed3DOffset = new Size(3, 3);
private Size FixedSingleOffset = new Size(2, 2);
private TextBox _referenceTextBox = new TextBox();
#endregion // Private Data
}
class IPAddressControlDesigner : ControlDesigner
{
public override SelectionRules SelectionRules
{
get
{
IPAddressControl control = (IPAddressControl)Control;
if (control.AutoHeight)
{
return SelectionRules.Moveable | SelectionRules.Visible | SelectionRules.LeftSizeable | SelectionRules.RightSizeable;
}
else
{
return SelectionRules.AllSizeable | SelectionRules.Moveable | SelectionRules.Visible;
}
}
}
public override IList SnapLines
{
get
{
IPAddressControl control = (IPAddressControl)Control;
IList snapLines = base.SnapLines;
snapLines.Add(new SnapLine(SnapLineType.Baseline, control.Baseline));
return snapLines;
}
}
}
internal class NativeMethods
{
private NativeMethods() { }
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetTextMetrics(IntPtr hdc, out TEXTMETRIC lptm);
[DllImport("gdi32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
[DllImport("gdi32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteObject(IntPtr hdc);
[Serializable, StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct TEXTMETRIC
{
public int tmHeight;
public int tmAscent;
public int tmDescent;
public int tmInternalLeading;
public int tmExternalLeading;
public int tmAveCharWidth;
public int tmMaxCharWidth;
public int tmWeight;
public int tmOverhang;
public int tmDigitizedAspectX;
public int tmDigitizedAspectY;
public char tmFirstChar;
public char tmLastChar;
public char tmDefaultChar;
public char tmBreakChar;
public byte tmItalic;
public byte tmUnderlined;
public byte tmStruckOut;
public byte tmPitchAndFamily;
public byte tmCharSet;
}
}
internal class FieldControl : TextBox
{
#region Public Constants
public const byte MinimumValue = 0;
public const byte MaximumValue = 255;
#endregion // Public Constants
#region Public Events
public event EventHandler<CedeFocusEventArgs> CedeFocusEvent;
public event EventHandler<TextChangedEventArgs> TextChangedEvent;
#endregion // Public Events
#region Public Properties
public bool Blank
{
get { return (TextLength == 0); }
}
public int FieldIndex
{
get { return _fieldIndex; }
set { _fieldIndex = value; }
}
public override Size MinimumSize
{
get
{
Graphics g = Graphics.FromHwnd(Handle);
Size minimumSize = TextRenderer.MeasureText(g,
Properties.Resources.FieldMeasureText, Font, Size,
_textFormatFlags);
g.Dispose();
return minimumSize;
}
}
public byte RangeLower
{
get { return _rangeLower; }
set
{
if (value < MinimumValue)
{
_rangeLower = MinimumValue;
}
else if (value > _rangeUpper)
{
_rangeLower = _rangeUpper;
}
else
{
_rangeLower = value;
}
if (Value < _rangeLower)
{
Text = _rangeLower.ToString(CultureInfo.InvariantCulture);
}
}
}
public byte RangeUpper
{
get { return _rangeUpper; }
set
{
if (value < _rangeLower)
{
_rangeUpper = _rangeLower;
}
else if (value > MaximumValue)
{
_rangeUpper = MaximumValue;
}
else
{
_rangeUpper = value;
}
if (Value > _rangeUpper)
{
Text = _rangeUpper.ToString(CultureInfo.InvariantCulture);
}
}
}
public byte Value
{
get
{
byte result;
if (!Byte.TryParse(Text, out result))
{
result = RangeLower;
}
return result;
}
}
#endregion // Public Properties
#region Public Methods
public void TakeFocus(Action action)
{
Focus();
switch (action)
{
case Action.Trim:
if (TextLength > 0)
{
int newLength = TextLength - 1;
base.Text = Text.Substring(0, newLength);
}
SelectionStart = TextLength;
return;
case Action.Home:
SelectionStart = 0;
SelectionLength = 0;
return;
case Action.End:
SelectionStart = TextLength;
return;
}
}
public void TakeFocus(Direction direction, Selection selection)
{
Focus();
if (selection == Selection.All)
{
SelectionStart = 0;
SelectionLength = TextLength;
}
else
{
SelectionStart = (direction == Direction.Forward) ? 0 : TextLength;
}
}
public override string ToString()
{
return Value.ToString(CultureInfo.InvariantCulture);
}
#endregion // Public Methods
#region Constructors
public FieldControl()
{
BorderStyle = BorderStyle.None;
MaxLength = 3;
Size = MinimumSize;
TabStop = false;
TextAlign = HorizontalAlignment.Center;
}
#endregion //Constructors
#region Protected Methods
protected override void OnKeyDown(KeyEventArgs e)
{
if (null == e) { throw new ArgumentNullException("e"); }
base.OnKeyDown(e);
switch (e.KeyCode)
{
case Keys.Home:
SendCedeFocusEvent(Action.Home);
return;
case Keys.End:
SendCedeFocusEvent(Action.End);
return;
}
if (IsCedeFocusKey(e))
{
SendCedeFocusEvent(Direction.Forward, Selection.All);
e.SuppressKeyPress = true;
return;
}
else if (IsForwardKey(e))
{
if (e.Control)
{
SendCedeFocusEvent(Direction.Forward, Selection.All);
return;
}
else if (SelectionLength == 0 && SelectionStart == TextLength)
{
SendCedeFocusEvent(Direction.Forward, Selection.None);
return;
}
}
else if (IsReverseKey(e))
{
if (e.Control)
{
SendCedeFocusEvent(Direction.Reverse, Selection.All);
return;
}
else if (SelectionLength == 0 && SelectionStart == 0)
{
SendCedeFocusEvent(Direction.Reverse, Selection.None);
return;
}
}
else if (IsBackspaceKey(e))
{
HandleBackspaceKey(e);
}
else if (!IsNumericKey(e) &&
!IsEditKey(e) &&
!IsEnterKey(e))
{
e.SuppressKeyPress = true;
}
}
protected override void OnParentBackColorChanged(EventArgs e)
{
base.OnParentBackColorChanged(e);
BackColor = Parent.BackColor;
}
protected override void OnParentForeColorChanged(EventArgs e)
{
base.OnParentForeColorChanged(e);
ForeColor = Parent.ForeColor;
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
Size = MinimumSize;
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
if (!Blank)
{
int value;
if (!Int32.TryParse(Text, out value))
{
base.Text = String.Empty;
}
else
{
if (value > RangeUpper)
{
base.Text = RangeUpper.ToString(CultureInfo.InvariantCulture);
SelectionStart = 0;
}
else if ((TextLength == MaxLength) && (value < RangeLower))
{
base.Text = RangeLower.ToString(CultureInfo.InvariantCulture);
SelectionStart = 0;
}
else
{
int originalLength = TextLength;
int newSelectionStart = SelectionStart;
base.Text = value.ToString(CultureInfo.InvariantCulture);
if (TextLength < originalLength)
{
newSelectionStart -= (originalLength - TextLength);
SelectionStart = Math.Max(0, newSelectionStart);
}
}
}
}
if (null != TextChangedEvent)
{
TextChangedEventArgs args = new TextChangedEventArgs();
args.FieldIndex = FieldIndex;
args.Text = Text;
TextChangedEvent(this, args);
}
if (TextLength == MaxLength && Focused && SelectionStart == TextLength)
{
SendCedeFocusEvent(Direction.Forward, Selection.All);
}
}
protected override void OnValidating(System.ComponentModel.CancelEventArgs e)
{
base.OnValidating(e);
if (!Blank)
{
if (Value < RangeLower)
{
Text = RangeLower.ToString(CultureInfo.InvariantCulture);
}
}
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x007b: // WM_CONTEXTMENU
return;
}
base.WndProc(ref m);
}
#endregion // Protected Methods
#region Private Methods
private void HandleBackspaceKey(KeyEventArgs e)
{
if (!ReadOnly && (TextLength == 0 || (SelectionStart == 0 && SelectionLength == 0)))
{
SendCedeFocusEvent(Action.Trim);
e.SuppressKeyPress = true;
}
}
private static bool IsBackspaceKey(KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
return true;
}
return false;
}
private bool IsCedeFocusKey(KeyEventArgs e)
{
if (e.KeyCode == Keys.OemPeriod ||
e.KeyCode == Keys.Decimal ||
e.KeyCode == Keys.Space)
{
if (TextLength != 0 && SelectionLength == 0 && SelectionStart != 0)
{
return true;
}
}
return false;
}
private static bool IsEditKey(KeyEventArgs e)
{
if (e.KeyCode == Keys.Back ||
e.KeyCode == Keys.Delete)
{
return true;
}
else if (e.Modifiers == Keys.Control &&
(e.KeyCode == Keys.C ||
e.KeyCode == Keys.V ||
e.KeyCode == Keys.X))
{
return true;
}
return false;
}
private static bool IsEnterKey(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter ||
e.KeyCode == Keys.Return)
{
return true;
}
return false;
}
private static bool IsForwardKey(KeyEventArgs e)
{
if (e.KeyCode == Keys.Right ||
e.KeyCode == Keys.Down)
{
return true;
}
return false;
}
private static bool IsNumericKey(KeyEventArgs e)
{
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
return false;
}
}
return true;
}
private static bool IsReverseKey(KeyEventArgs e)
{
if (e.KeyCode == Keys.Left ||
e.KeyCode == Keys.Up)
{
return true;
}
return false;
}
private void SendCedeFocusEvent(Action action)
{
if (null != CedeFocusEvent)
{
CedeFocusEventArgs args = new CedeFocusEventArgs();
args.FieldIndex = FieldIndex;
args.Action = action;
CedeFocusEvent(this, args);
}
}
private void SendCedeFocusEvent(Direction direction, Selection selection)
{
if (null != CedeFocusEvent)
{
CedeFocusEventArgs args = new CedeFocusEventArgs();
args.FieldIndex = FieldIndex;
args.Action = Action.None;
args.Direction = direction;
args.Selection = selection;
CedeFocusEvent(this, args);
}
}
#endregion // Private Methods
#region Private Data
private int _fieldIndex = -1;
private byte _rangeLower; // = MinimumValue; // this is removed for FxCop approval
private byte _rangeUpper = MaximumValue;
private TextFormatFlags _textFormatFlags = TextFormatFlags.HorizontalCenter |
TextFormatFlags.SingleLine | TextFormatFlags.NoPadding;
#endregion // Private Data
}
internal enum Direction
{
Forward,
Reverse
}
internal enum Selection
{
None,
All
}
internal enum Action
{
None,
Trim,
Home,
End
}
internal class CedeFocusEventArgs : EventArgs
{
private int _fieldIndex;
private Action _action;
private Direction _direction;
private Selection _selection;
public int FieldIndex
{
get { return _fieldIndex; }
set { _fieldIndex = value; }
}
public Action Action
{
get { return _action; }
set { _action = value; }
}
public Direction Direction
{
get { return _direction; }
set { _direction = value; }
}
public Selection Selection
{
get { return _selection; }
set { _selection = value; }
}
}
internal class TextChangedEventArgs : EventArgs
{
private int _fieldIndex;
private String _text;
public int FieldIndex
{
get { return _fieldIndex; }
set { _fieldIndex = value; }
}
public String Text
{
get { return _text; }
set { _text = value; }
}
}
public class FieldChangedEventArgs : EventArgs
{
private int _fieldIndex;
private String _text;
public int FieldIndex
{
get { return _fieldIndex; }
set { _fieldIndex = value; }
}
public String Text
{
get { return _text; }
set { _text = value; }
}
}
internal class DotControl : Control
{
#region Public Properties
public override Size MinimumSize
{
get
{
using (Graphics g = Graphics.FromHwnd(Handle))
{
_sizeText = g.MeasureString(Text, Font, -1, _stringFormat);
}
// MeasureString() cuts off the bottom pixel for descenders no matter
// which StringFormatFlags are chosen. This doesn't matter for '.' but
// it's here in case someone wants to modify the text.
//
_sizeText.Height += 1F;
return _sizeText.ToSize();
}
}
public bool ReadOnly
{
get
{
return _readOnly;
}
set
{
_readOnly = value;
Invalidate();
}
}
#endregion // Public Properties
#region Public Methods
public override string ToString()
{
return Text;
}
#endregion // Public Methods
#region Constructors
public DotControl()
{
Text = Properties.Resources.FieldSeparator;
_stringFormat = StringFormat.GenericTypographic;
_stringFormat.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
BackColor = SystemColors.Window;
Size = MinimumSize;
TabStop = false;
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.FixedHeight, true);
SetStyle(ControlStyles.FixedWidth, true);
}
#endregion // Constructors
#region Protected Methods
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
Size = MinimumSize;
}
protected override void OnPaint(PaintEventArgs e)
{
if (null == e) { throw new ArgumentNullException("e"); }
base.OnPaint(e);
Color backColor = BackColor;
if (!_backColorChanged)
{
if (!Enabled || ReadOnly)
{
backColor = SystemColors.Control;
}
}
Color textColor = ForeColor;
if (!Enabled)
{
textColor = SystemColors.GrayText;
}
else if (ReadOnly)
{
if (!_backColorChanged)
{
textColor = SystemColors.WindowText;
}
}
using (SolidBrush backgroundBrush = new SolidBrush(backColor))
{
e.Graphics.FillRectangle(backgroundBrush, ClientRectangle);
}
using (SolidBrush foreBrush = new SolidBrush(textColor))
{
float x = (float)ClientRectangle.Width / 2F - _sizeText.Width / 2F;
e.Graphics.DrawString(Text, Font, foreBrush,
new RectangleF(x, 0F, _sizeText.Width, _sizeText.Height), _stringFormat);
}
}
protected override void OnParentBackColorChanged(EventArgs e)
{
base.OnParentBackColorChanged(e);
BackColor = Parent.BackColor;
_backColorChanged = true;
}
protected override void OnParentForeColorChanged(EventArgs e)
{
base.OnParentForeColorChanged(e);
ForeColor = Parent.ForeColor;
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
base.Size = MinimumSize;
}
#endregion // Protected Methods
#region Private Data
private bool _backColorChanged;
private bool _readOnly;
private StringFormat _stringFormat;
private SizeF _sizeText;
#endregion // Private Data
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Management.Automation.Remoting;
using System.Management.Automation.Remoting.Server;
using System.Management.Automation.Runspaces;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// Handles all data structure handler communication with the client
/// runspace pool.
/// </summary>
internal class ServerRunspacePoolDataStructureHandler
{
#region Constructors
/// <summary>
/// Constructor which takes a server runspace pool driver and
/// creates an associated ServerRunspacePoolDataStructureHandler.
/// </summary>
/// <param name="driver"></param>
/// <param name="transportManager"></param>
internal ServerRunspacePoolDataStructureHandler(ServerRunspacePoolDriver driver,
AbstractServerSessionTransportManager transportManager)
{
_clientRunspacePoolId = driver.InstanceId;
_transportManager = transportManager;
}
#endregion Constructors
#region Data Structure Handler Methods
/// <summary>
/// Send a message with application private data to the client.
/// </summary>
/// <param name="applicationPrivateData">ApplicationPrivateData to send.</param>
/// <param name="serverCapability">Server capability negotiated during initial exchange of remoting messages / session capabilities of client and server.</param>
internal void SendApplicationPrivateDataToClient(PSPrimitiveDictionary applicationPrivateData, RemoteSessionCapability serverCapability)
{
// make server's PSVersionTable available to the client using ApplicationPrivateData
PSPrimitiveDictionary applicationPrivateDataWithVersionTable =
PSPrimitiveDictionary.CloneAndAddPSVersionTable(applicationPrivateData);
// override the hardcoded version numbers with the stuff that was reported to the client during negotiation
PSPrimitiveDictionary versionTable = (PSPrimitiveDictionary)applicationPrivateDataWithVersionTable[PSVersionInfo.PSVersionTableName];
versionTable[PSVersionInfo.PSRemotingProtocolVersionName] = serverCapability.ProtocolVersion;
versionTable[PSVersionInfo.SerializationVersionName] = serverCapability.SerializationVersion;
// Pass back the true PowerShell version to the client via application private data.
versionTable[PSVersionInfo.PSVersionName] = PSVersionInfo.PSVersion;
RemoteDataObject data = RemotingEncoder.GenerateApplicationPrivateData(
_clientRunspacePoolId, applicationPrivateDataWithVersionTable);
SendDataAsync(data);
}
/// <summary>
/// Send a message with the RunspacePoolStateInfo to the client.
/// </summary>
/// <param name="stateInfo">State info to send.</param>
internal void SendStateInfoToClient(RunspacePoolStateInfo stateInfo)
{
RemoteDataObject data = RemotingEncoder.GenerateRunspacePoolStateInfo(
_clientRunspacePoolId, stateInfo);
SendDataAsync(data);
}
/// <summary>
/// Send a message with the PSEventArgs to the client.
/// </summary>
/// <param name="e">Event to send.</param>
internal void SendPSEventArgsToClient(PSEventArgs e)
{
RemoteDataObject data = RemotingEncoder.GeneratePSEventArgs(_clientRunspacePoolId, e);
SendDataAsync(data);
}
/// <summary>
/// Called when session is connected from a new client
/// call into the sessionconnect handlers for each associated powershell dshandler.
/// </summary>
internal void ProcessConnect()
{
List<ServerPowerShellDataStructureHandler> dsHandlers;
lock (_associationSyncObject)
{
dsHandlers = new List<ServerPowerShellDataStructureHandler>(_associatedShells.Values);
}
foreach (var dsHandler in dsHandlers)
{
dsHandler.ProcessConnect();
}
}
/// <summary>
/// Process the data received from the runspace pool on
/// the server.
/// </summary>
/// <param name="receivedData">Data received.</param>
internal void ProcessReceivedData(RemoteDataObject<PSObject> receivedData)
{
if (receivedData == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(receivedData));
}
Dbg.Assert(receivedData.TargetInterface == RemotingTargetInterface.RunspacePool,
"RemotingTargetInterface must be Runspace");
switch (receivedData.DataType)
{
case RemotingDataType.CreatePowerShell:
{
Dbg.Assert(CreateAndInvokePowerShell != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events");
CreateAndInvokePowerShell.SafeInvoke(this, new RemoteDataEventArgs<RemoteDataObject<PSObject>>(receivedData));
}
break;
case RemotingDataType.GetCommandMetadata:
{
Dbg.Assert(GetCommandMetadata != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events");
GetCommandMetadata.SafeInvoke(this, new RemoteDataEventArgs<RemoteDataObject<PSObject>>(receivedData));
}
break;
case RemotingDataType.RemoteRunspaceHostResponseData:
{
Dbg.Assert(HostResponseReceived != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events");
RemoteHostResponse remoteHostResponse = RemoteHostResponse.Decode(receivedData.Data);
// part of host message robustness algo. Now the host response is back, report to transport that
// execution status is back to running
_transportManager.ReportExecutionStatusAsRunning();
HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs<RemoteHostResponse>(remoteHostResponse));
}
break;
case RemotingDataType.SetMaxRunspaces:
{
Dbg.Assert(SetMaxRunspacesReceived != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events");
SetMaxRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data));
}
break;
case RemotingDataType.SetMinRunspaces:
{
Dbg.Assert(SetMinRunspacesReceived != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events");
SetMinRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data));
}
break;
case RemotingDataType.AvailableRunspaces:
{
Dbg.Assert(GetAvailableRunspacesReceived != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events");
GetAvailableRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data));
}
break;
case RemotingDataType.ResetRunspaceState:
{
Dbg.Assert(ResetRunspaceState != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events.");
ResetRunspaceState.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data));
}
break;
}
}
/// <summary>
/// Creates a powershell data structure handler from this runspace pool.
/// </summary>
/// <param name="instanceId">Powershell instance id.</param>
/// <param name="runspacePoolId">Runspace pool id.</param>
/// <param name="remoteStreamOptions">Remote stream options.</param>
/// <param name="localPowerShell">Local PowerShell object.</param>
/// <returns>ServerPowerShellDataStructureHandler.</returns>
internal ServerPowerShellDataStructureHandler CreatePowerShellDataStructureHandler(
Guid instanceId, Guid runspacePoolId, RemoteStreamOptions remoteStreamOptions, PowerShell localPowerShell)
{
// start with pool's transport manager.
AbstractServerTransportManager cmdTransportManager = _transportManager;
if (instanceId != Guid.Empty)
{
cmdTransportManager = _transportManager.GetCommandTransportManager(instanceId);
Dbg.Assert(cmdTransportManager.TypeTable != null, "This should be already set in managed C++ code");
}
ServerPowerShellDataStructureHandler dsHandler =
new ServerPowerShellDataStructureHandler(instanceId, runspacePoolId, remoteStreamOptions, cmdTransportManager, localPowerShell);
lock (_associationSyncObject)
{
_associatedShells.Add(dsHandler.PowerShellId, dsHandler);
}
dsHandler.RemoveAssociation += HandleRemoveAssociation;
return dsHandler;
}
/// <summary>
/// Returns the currently active PowerShell datastructure handler.
/// </summary>
/// <returns>
/// ServerPowerShellDataStructureHandler if one is present, null otherwise.
/// </returns>
internal ServerPowerShellDataStructureHandler GetPowerShellDataStructureHandler()
{
lock (_associationSyncObject)
{
if (_associatedShells.Count > 0)
{
foreach (object o in _associatedShells.Values)
{
ServerPowerShellDataStructureHandler result = o as ServerPowerShellDataStructureHandler;
if (result != null)
{
return result;
}
}
}
}
return null;
}
/// <summary>
/// Dispatch the message to the associated powershell data structure handler.
/// </summary>
/// <param name="rcvdData">Message to dispatch.</param>
internal void DispatchMessageToPowerShell(RemoteDataObject<PSObject> rcvdData)
{
ServerPowerShellDataStructureHandler dsHandler =
GetAssociatedPowerShellDataStructureHandler(rcvdData.PowerShellId);
// if data structure handler is not found, then association has already been
// removed, discard message
if (dsHandler != null)
{
dsHandler.ProcessReceivedData(rcvdData);
}
}
/// <summary>
/// Send the specified response to the client. The client call will
/// be blocked on the same.
/// </summary>
/// <param name="callId">Call id on the client.</param>
/// <param name="response">Response to send.</param>
internal void SendResponseToClient(long callId, object response)
{
RemoteDataObject message =
RemotingEncoder.GenerateRunspacePoolOperationResponse(_clientRunspacePoolId, response, callId);
SendDataAsync(message);
}
/// <summary>
/// TypeTable used for Serialization/Deserialization.
/// </summary>
internal TypeTable TypeTable
{
get { return _transportManager.TypeTable; }
set { _transportManager.TypeTable = value; }
}
#endregion Data Structure Handler Methods
#region Data Structure Handler events
/// <summary>
/// This event is raised whenever there is a request from the
/// client to create a powershell on the server and invoke it.
/// </summary>
internal event EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>> CreateAndInvokePowerShell;
/// <summary>
/// This event is raised whenever there is a request from the
/// client to run command discovery pipeline.
/// </summary>
internal event EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>> GetCommandMetadata;
/// <summary>
/// This event is raised when a host call response is received.
/// </summary>
internal event EventHandler<RemoteDataEventArgs<RemoteHostResponse>> HostResponseReceived;
/// <summary>
/// This event is raised when there is a request to modify the
/// maximum runspaces in the runspace pool.
/// </summary>
internal event EventHandler<RemoteDataEventArgs<PSObject>> SetMaxRunspacesReceived;
/// <summary>
/// This event is raised when there is a request to modify the
/// minimum runspaces in the runspace pool.
/// </summary>
internal event EventHandler<RemoteDataEventArgs<PSObject>> SetMinRunspacesReceived;
/// <summary>
/// This event is raised when there is a request to get the
/// available runspaces in the runspace pool.
/// </summary>
internal event EventHandler<RemoteDataEventArgs<PSObject>> GetAvailableRunspacesReceived;
/// <summary>
/// This event is raised when the client requests the runspace state
/// to be reset.
/// </summary>
internal event EventHandler<RemoteDataEventArgs<PSObject>> ResetRunspaceState;
#endregion Data Structure Handler events
#region Private Methods
/// <summary>
/// Send the data specified as a RemoteDataObject asynchronously
/// to the runspace pool on the remote session.
/// </summary>
/// <param name="data">Data to send.</param>
/// <remarks>This overload takes a RemoteDataObject and should
/// be the one thats used to send data from within this
/// data structure handler class</remarks>
private void SendDataAsync(RemoteDataObject data)
{
Dbg.Assert(data != null, "Cannot send null object.");
_transportManager.SendDataToClient(data, true);
}
/// <summary>
/// Get the associated powershell data structure handler for the specified
/// powershell id.
/// </summary>
/// <param name="clientPowerShellId">powershell id for the
/// powershell data structure handler</param>
/// <returns>ServerPowerShellDataStructureHandler.</returns>
internal ServerPowerShellDataStructureHandler GetAssociatedPowerShellDataStructureHandler
(Guid clientPowerShellId)
{
ServerPowerShellDataStructureHandler dsHandler = null;
lock (_associationSyncObject)
{
bool success = _associatedShells.TryGetValue(clientPowerShellId, out dsHandler);
if (!success)
{
dsHandler = null;
}
}
return dsHandler;
}
/// <summary>
/// Remove the association of the powershell from the runspace pool.
/// </summary>
/// <param name="sender">Sender of this event.</param>
/// <param name="e">Unused.</param>
private void HandleRemoveAssociation(object sender, EventArgs e)
{
Dbg.Assert(sender is ServerPowerShellDataStructureHandler, @"sender of the event
must be ServerPowerShellDataStructureHandler");
ServerPowerShellDataStructureHandler dsHandler = sender as ServerPowerShellDataStructureHandler;
lock (_associationSyncObject)
{
_associatedShells.Remove(dsHandler.PowerShellId);
}
// let session transport manager remove its association of command transport manager.
_transportManager.RemoveCommandTransportManager(dsHandler.PowerShellId);
}
#endregion Private Methods
#region Private Members
private readonly Guid _clientRunspacePoolId;
// transport manager using which this
// runspace pool driver handles all client
// communication
private readonly AbstractServerSessionTransportManager _transportManager;
private readonly Dictionary<Guid, ServerPowerShellDataStructureHandler> _associatedShells
= new Dictionary<Guid, ServerPowerShellDataStructureHandler>();
// powershell data structure handlers associated with this
// runspace pool data structure handler
private readonly object _associationSyncObject = new object();
// object to synchronize operations to above
#endregion Private Members
}
/// <summary>
/// Handles all PowerShell data structure handler communication
/// with the client side PowerShell.
/// </summary>
internal class ServerPowerShellDataStructureHandler
{
#region Private Members
// transport manager using which this
// powershell driver handles all client
// communication
private readonly AbstractServerTransportManager _transportManager;
private readonly Guid _clientRunspacePoolId;
private readonly Guid _clientPowerShellId;
private readonly RemoteStreamOptions _streamSerializationOptions;
private Runspace _rsUsedToInvokePowerShell;
#endregion Private Members
#region Constructors
/// <summary>
/// Default constructor for creating ServerPowerShellDataStructureHandler
/// instance.
/// </summary>
/// <param name="instanceId">Powershell instance id.</param>
/// <param name="runspacePoolId">Runspace pool id.</param>
/// <param name="remoteStreamOptions">Remote stream options.</param>
/// <param name="transportManager">Transport manager.</param>
/// <param name="localPowerShell">Local powershell object.</param>
internal ServerPowerShellDataStructureHandler(Guid instanceId, Guid runspacePoolId, RemoteStreamOptions remoteStreamOptions,
AbstractServerTransportManager transportManager, PowerShell localPowerShell)
{
_clientPowerShellId = instanceId;
_clientRunspacePoolId = runspacePoolId;
_transportManager = transportManager;
_streamSerializationOptions = remoteStreamOptions;
transportManager.Closing += HandleTransportClosing;
if (localPowerShell != null)
{
localPowerShell.RunspaceAssigned += LocalPowerShell_RunspaceAssigned;
}
}
private void LocalPowerShell_RunspaceAssigned(object sender, PSEventArgs<Runspace> e)
{
_rsUsedToInvokePowerShell = e.Args;
}
#endregion Constructors
#region Data Structure Handler Methods
/// <summary>
/// Prepare transport manager to send data to client.
/// </summary>
internal void Prepare()
{
// When Guid.Empty is used, PowerShell must be using pool's transport manager
// to send data to client. so we dont need to prepare command transport manager
if (_clientPowerShellId != Guid.Empty)
{
_transportManager.Prepare();
}
}
/// <summary>
/// Send the state information to the client.
/// </summary>
/// <param name="stateInfo">state information to be
/// sent to the client</param>
internal void SendStateChangedInformationToClient(PSInvocationStateInfo
stateInfo)
{
Dbg.Assert((stateInfo.State == PSInvocationState.Completed) ||
(stateInfo.State == PSInvocationState.Failed) ||
(stateInfo.State == PSInvocationState.Stopped),
"SendStateChangedInformationToClient should be called to notify a termination state");
SendDataAsync(RemotingEncoder.GeneratePowerShellStateInfo(
stateInfo, _clientPowerShellId, _clientRunspacePoolId));
// Close the transport manager only if the PowerShell Guid != Guid.Empty.
// When Guid.Empty is used, PowerShell must be using pool's transport manager
// to send data to client.
if (_clientPowerShellId != Guid.Empty)
{
// no need to listen for closing events as we are initiating the close
_transportManager.Closing -= HandleTransportClosing;
// if terminal state is reached close the transport manager instead of letting
// the client initiate the close.
_transportManager.Close(null);
}
}
/// <summary>
/// Send the output data to the client.
/// </summary>
/// <param name="data">Data to send.</param>
internal void SendOutputDataToClient(PSObject data)
{
SendDataAsync(RemotingEncoder.GeneratePowerShellOutput(data,
_clientPowerShellId, _clientRunspacePoolId));
}
/// <summary>
/// Send the error record to client.
/// </summary>
/// <param name="errorRecord">Error record to send.</param>
internal void SendErrorRecordToClient(ErrorRecord errorRecord)
{
errorRecord.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToErrorRecord) != 0;
SendDataAsync(RemotingEncoder.GeneratePowerShellError(
errorRecord, _clientRunspacePoolId, _clientPowerShellId));
}
/// <summary>
/// Send the specified warning record to client.
/// </summary>
/// <param name="record">Warning record.</param>
internal void SendWarningRecordToClient(WarningRecord record)
{
record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToWarningRecord) != 0;
SendDataAsync(RemotingEncoder.GeneratePowerShellInformational(
record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellWarning));
}
/// <summary>
/// Send the specified debug record to client.
/// </summary>
/// <param name="record">Debug record.</param>
internal void SendDebugRecordToClient(DebugRecord record)
{
record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToDebugRecord) != 0;
SendDataAsync(RemotingEncoder.GeneratePowerShellInformational(
record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellDebug));
}
/// <summary>
/// Send the specified verbose record to client.
/// </summary>
/// <param name="record">Warning record.</param>
internal void SendVerboseRecordToClient(VerboseRecord record)
{
record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToVerboseRecord) != 0;
SendDataAsync(RemotingEncoder.GeneratePowerShellInformational(
record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellVerbose));
}
/// <summary>
/// Send the specified progress record to client.
/// </summary>
/// <param name="record">Progress record.</param>
internal void SendProgressRecordToClient(ProgressRecord record)
{
SendDataAsync(RemotingEncoder.GeneratePowerShellInformational(
record, _clientRunspacePoolId, _clientPowerShellId));
}
/// <summary>
/// Send the specified information record to client.
/// </summary>
/// <param name="record">Information record.</param>
internal void SendInformationRecordToClient(InformationRecord record)
{
SendDataAsync(RemotingEncoder.GeneratePowerShellInformational(
record, _clientRunspacePoolId, _clientPowerShellId));
}
/// <summary>
/// Called when session is connected from a new client
/// calls into observers of this event.
/// observers include corresponding driver that shutdown
/// input stream is present.
/// </summary>
internal void ProcessConnect()
{
OnSessionConnected.SafeInvoke(this, EventArgs.Empty);
}
/// <summary>
/// Process the data received from the powershell on
/// the client.
/// </summary>
/// <param name="receivedData">Data received.</param>
internal void ProcessReceivedData(RemoteDataObject<PSObject> receivedData)
{
if (receivedData == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(receivedData));
}
Dbg.Assert(receivedData.TargetInterface == RemotingTargetInterface.PowerShell,
"RemotingTargetInterface must be PowerShell");
switch (receivedData.DataType)
{
case RemotingDataType.StopPowerShell:
{
Dbg.Assert(StopPowerShellReceived != null,
"ServerPowerShellDriver should subscribe to all data structure handler events");
StopPowerShellReceived.SafeInvoke(this, EventArgs.Empty);
}
break;
case RemotingDataType.PowerShellInput:
{
Dbg.Assert(InputReceived != null,
"ServerPowerShellDriver should subscribe to all data structure handler events");
InputReceived.SafeInvoke(this, new RemoteDataEventArgs<object>(receivedData.Data));
}
break;
case RemotingDataType.PowerShellInputEnd:
{
Dbg.Assert(InputEndReceived != null,
"ServerPowerShellDriver should subscribe to all data structure handler events");
InputEndReceived.SafeInvoke(this, EventArgs.Empty);
}
break;
case RemotingDataType.RemotePowerShellHostResponseData:
{
Dbg.Assert(HostResponseReceived != null,
"ServerPowerShellDriver should subscribe to all data structure handler events");
RemoteHostResponse remoteHostResponse = RemoteHostResponse.Decode(receivedData.Data);
// part of host message robustness algo. Now the host response is back, report to transport that
// execution status is back to running
_transportManager.ReportExecutionStatusAsRunning();
HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs<RemoteHostResponse>(remoteHostResponse));
}
break;
}
}
/// <summary>
/// Raise a remove association event. This is raised
/// when the powershell has gone into a terminal state
/// and the runspace pool need not maintain any further
/// associations.
/// </summary>
internal void RaiseRemoveAssociationEvent()
{
Dbg.Assert(RemoveAssociation != null, @"The ServerRunspacePoolDataStructureHandler should subscribe
to the RemoveAssociation event of ServerPowerShellDataStructureHandler");
RemoveAssociation.SafeInvoke(this, EventArgs.Empty);
}
/// <summary>
/// Creates a ServerRemoteHost which is associated with this powershell.
/// </summary>
/// <param name="powerShellHostInfo">Host information about the host associated
/// PowerShell object on the client.</param>
/// <param name="runspaceServerRemoteHost">Host associated with the RunspacePool
/// on the server.</param>
/// <returns>A new ServerRemoteHost for the PowerShell.</returns>
internal ServerRemoteHost GetHostAssociatedWithPowerShell(
HostInfo powerShellHostInfo,
ServerRemoteHost runspaceServerRemoteHost)
{
HostInfo hostInfo;
// If host was null use the runspace's host for this powershell; otherwise,
// use the HostInfo to create a proxy host of the powershell's host.
if (powerShellHostInfo.UseRunspaceHost)
{
hostInfo = runspaceServerRemoteHost.HostInfo;
}
else
{
hostInfo = powerShellHostInfo;
}
// If the host was not null on the client, then the PowerShell object should
// get a brand spanking new host.
return new ServerRemoteHost(_clientRunspacePoolId, _clientPowerShellId, hostInfo,
_transportManager, runspaceServerRemoteHost.Runspace, runspaceServerRemoteHost as ServerDriverRemoteHost);
}
#endregion Data Structure Handler Methods
#region Data Structure Handler events
/// <summary>
/// This event is raised when the state of associated
/// powershell is terminal and the runspace pool has
/// to detach the association.
/// </summary>
internal event EventHandler RemoveAssociation;
/// <summary>
/// This event is raised when the a message to stop the
/// powershell is received from the client.
/// </summary>
internal event EventHandler StopPowerShellReceived;
/// <summary>
/// This event is raised when an input object is received
/// from the client.
/// </summary>
internal event EventHandler<RemoteDataEventArgs<object>> InputReceived;
/// <summary>
/// This event is raised when end of input is received from
/// the client.
/// </summary>
internal event EventHandler InputEndReceived;
/// <summary>
/// Raised when server session is connected from a new client.
/// </summary>
internal event EventHandler OnSessionConnected;
/// <summary>
/// This event is raised when a host response is received.
/// </summary>
internal event EventHandler<RemoteDataEventArgs<RemoteHostResponse>> HostResponseReceived;
#endregion Data Structure Handler events
#region Internal Methods
/// <summary>
/// Client powershell id.
/// </summary>
internal Guid PowerShellId
{
get
{
return _clientPowerShellId;
}
}
/// <summary>
/// Runspace used to invoke PowerShell, this is used by the steppable
/// pipeline driver.
/// </summary>
internal Runspace RunspaceUsedToInvokePowerShell
{
get { return _rsUsedToInvokePowerShell; }
}
#endregion Internal Methods
#region Private Methods
/// <summary>
/// Send the data specified as a RemoteDataObject asynchronously
/// to the runspace pool on the remote session.
/// </summary>
/// <param name="data">Data to send.</param>
/// <remarks>This overload takes a RemoteDataObject and should
/// be the one thats used to send data from within this
/// data structure handler class</remarks>
private void SendDataAsync(RemoteDataObject data)
{
Dbg.Assert(data != null, "Cannot send null object.");
// this is from a command execution..let transport manager collect
// as much data as possible and send bigger buffer to client.
_transportManager.SendDataToClient(data, false);
}
/// <summary>
/// Handle transport manager's closing event.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void HandleTransportClosing(object sender, EventArgs args)
{
StopPowerShellReceived.SafeInvoke(this, args);
}
#endregion Private Methods
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// The Regex class represents a single compiled instance of a regular
// expression.
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
#if FEATURE_COMPILED
using System.Runtime.CompilerServices;
#endif
using System.Runtime.Serialization;
namespace System.Text.RegularExpressions
{
/// <summary>
/// Represents an immutable, compiled regular expression. Also
/// contains static methods that allow use of regular expressions without instantiating
/// a Regex explicitly.
/// </summary>
public partial class Regex : ISerializable
{
internal const int MaxOptionShift = 10;
protected internal string pattern; // The string pattern provided
protected internal RegexOptions roptions; // the top-level options from the options string
protected internal RegexRunnerFactory factory;
protected internal Hashtable caps; // if captures are sparse, this is the hashtable capnum->index
protected internal Hashtable capnames; // if named captures are used, this maps names->index
protected internal string[] capslist; // if captures are sparse or named captures are used, this is the sorted list of names
protected internal int capsize; // the size of the capture array
internal ExclusiveReference _runnerref; // cached runner
internal WeakReference<RegexReplacement> _replref; // cached parsed replacement pattern
internal RegexCode _code; // if interpreted, this is the code for RegexInterpreter
internal bool _refsInitialized = false;
protected Regex()
{
internalMatchTimeout = s_defaultMatchTimeout;
}
/// <summary>
/// Creates and compiles a regular expression object for the specified regular
/// expression.
/// </summary>
public Regex(string pattern)
: this(pattern, RegexOptions.None, s_defaultMatchTimeout, false)
{
}
/// <summary>
/// Creates and compiles a regular expression object for the
/// specified regular expression with options that modify the pattern.
/// </summary>
public Regex(string pattern, RegexOptions options)
: this(pattern, options, s_defaultMatchTimeout, false)
{
}
public Regex(string pattern, RegexOptions options, TimeSpan matchTimeout)
: this(pattern, options, matchTimeout, false)
{
}
protected Regex(SerializationInfo info, StreamingContext context)
: this(info.GetString("pattern"), (RegexOptions)info.GetInt32("options"))
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
private Regex(string pattern, RegexOptions options, TimeSpan matchTimeout, bool addToCache)
{
if (pattern == null)
{
throw new ArgumentNullException(nameof(pattern));
}
if (options < RegexOptions.None || (((int)options) >> MaxOptionShift) != 0)
{
throw new ArgumentOutOfRangeException(nameof(options));
}
if ((options & RegexOptions.ECMAScript) != 0
&& (options & ~(RegexOptions.ECMAScript |
RegexOptions.IgnoreCase |
RegexOptions.Multiline |
RegexOptions.Compiled |
RegexOptions.CultureInvariant
#if DEBUG
| RegexOptions.Debug
#endif
)) != 0)
{
throw new ArgumentOutOfRangeException(nameof(options));
}
ValidateMatchTimeout(matchTimeout);
// After parameter validation assign
this.pattern = pattern;
roptions = options;
internalMatchTimeout = matchTimeout;
// Cache handling. Try to look up this regex in the cache.
CultureInfo culture = (options & RegexOptions.CultureInvariant) != 0 ?
CultureInfo.InvariantCulture :
CultureInfo.CurrentCulture;
var key = new CachedCodeEntryKey(options, culture.ToString(), pattern);
CachedCodeEntry cached = GetCachedCode(key, false);
if (cached == null)
{
// Parse the input
RegexTree tree = RegexParser.Parse(pattern, roptions, culture);
// Extract the relevant information
capnames = tree.CapNames;
capslist = tree.CapsList;
_code = RegexWriter.Write(tree);
caps = _code.Caps;
capsize = _code.CapSize;
InitializeReferences();
tree = null;
if (addToCache)
cached = GetCachedCode(key, true);
}
else
{
caps = cached.Caps;
capnames = cached.Capnames;
capslist = cached.Capslist;
capsize = cached.Capsize;
_code = cached.Code;
#if FEATURE_COMPILED
factory = cached.Factory;
#endif
// Cache runner and replacement
_runnerref = cached.Runnerref;
_replref = cached.ReplRef;
_refsInitialized = true;
}
#if FEATURE_COMPILED
// if the compile option is set, then compile the code if it's not already
if (UseOptionC() && factory == null)
{
factory = Compile(_code, roptions);
if (addToCache && cached != null)
{
cached.AddCompiled(factory);
}
_code = null;
}
#endif
}
[CLSCompliant(false)]
protected IDictionary Caps
{
get
{
return caps;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
caps = value as Hashtable ?? new Hashtable(value);
}
}
[CLSCompliant(false)]
protected IDictionary CapNames
{
get
{
return capnames;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
capnames = value as Hashtable ?? new Hashtable(value);
}
}
#if FEATURE_COMPILED
/// <summary>
/// This method is here for perf reasons: if the call to RegexCompiler is NOT in the
/// Regex constructor, we don't load RegexCompiler and its reflection classes when
/// instantiating a non-compiled regex.
/// </summary>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private RegexRunnerFactory Compile(RegexCode code, RegexOptions roptions)
{
return RegexCompiler.Compile(code, roptions);
}
#endif
#if FEATURE_COMPILEAPIS
public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_CompileToAssembly);
}
public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname, CustomAttributeBuilder[] attributes)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_CompileToAssembly);
}
public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname, CustomAttributeBuilder[] attributes, string resourceFile)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_CompileToAssembly);
}
#endif // FEATURE_COMPILEAPIS
/// <summary>
/// Escapes a minimal set of metacharacters (\, *, +, ?, |, {, [, (, ), ^, $, ., #, and
/// whitespace) by replacing them with their \ codes. This converts a string so that
/// it can be used as a constant within a regular expression safely. (Note that the
/// reason # and whitespace must be escaped is so the string can be used safely
/// within an expression parsed with x mode. If future Regex features add
/// additional metacharacters, developers should depend on Escape to escape those
/// characters as well.)
/// </summary>
public static string Escape(string str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
return RegexParser.Escape(str);
}
/// <summary>
/// Unescapes any escaped characters in the input string.
/// </summary>
public static string Unescape(string str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
return RegexParser.Unescape(str);
}
/// <summary>
/// Returns the options passed into the constructor
/// </summary>
public RegexOptions Options => roptions;
/// <summary>
/// Indicates whether the regular expression matches from right to left.
/// </summary>
public bool RightToLeft => UseOptionR();
/// <summary>
/// Returns the regular expression pattern passed into the constructor
/// </summary>
public override string ToString() => pattern;
/*
* Returns an array of the group names that are used to capture groups
* in the regular expression. Only needed if the regex is not known until
* runtime, and one wants to extract captured groups. (Probably unusual,
* but supplied for completeness.)
*/
/// <summary>
/// Returns the GroupNameCollection for the regular expression. This collection contains the
/// set of strings used to name capturing groups in the expression.
/// </summary>
public string[] GetGroupNames()
{
string[] result;
if (capslist == null)
{
int max = capsize;
result = new string[max];
for (int i = 0; i < max; i++)
{
result[i] = Convert.ToString(i, CultureInfo.InvariantCulture);
}
}
else
{
result = new string[capslist.Length];
Array.Copy(capslist, 0, result, 0, capslist.Length);
}
return result;
}
/*
* Returns an array of the group numbers that are used to capture groups
* in the regular expression. Only needed if the regex is not known until
* runtime, and one wants to extract captured groups. (Probably unusual,
* but supplied for completeness.)
*/
/// <summary>
/// Returns the integer group number corresponding to a group name.
/// </summary>
public int[] GetGroupNumbers()
{
int[] result;
if (caps == null)
{
int max = capsize;
result = new int[max];
for (int i = 0; i < result.Length; i++)
{
result[i] = i;
}
}
else
{
result = new int[caps.Count];
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator de = caps.GetEnumerator();
while (de.MoveNext())
{
result[(int)de.Value] = (int)de.Key;
}
}
return result;
}
/*
* Given a group number, maps it to a group name. Note that numbered
* groups automatically get a group name that is the decimal string
* equivalent of its number.
*
* Returns null if the number is not a recognized group number.
*/
/// <summary>
/// Retrieves a group name that corresponds to a group number.
/// </summary>
public string GroupNameFromNumber(int i)
{
if (capslist == null)
{
if (i >= 0 && i < capsize)
return i.ToString(CultureInfo.InvariantCulture);
return string.Empty;
}
else
{
if (caps != null)
{
if (!caps.TryGetValue(i, out i))
return string.Empty;
}
if (i >= 0 && i < capslist.Length)
return capslist[i];
return string.Empty;
}
}
/*
* Given a group name, maps it to a group number. Note that numbered
* groups automatically get a group name that is the decimal string
* equivalent of its number.
*
* Returns -1 if the name is not a recognized group name.
*/
/// <summary>
/// Returns a group number that corresponds to a group name.
/// </summary>
public int GroupNumberFromName(string name)
{
int result = -1;
if (name == null)
throw new ArgumentNullException(nameof(name));
// look up name if we have a hashtable of names
if (capnames != null)
{
if (!capnames.TryGetValue(name, out result))
return -1;
return result;
}
// convert to an int if it looks like a number
result = 0;
for (int i = 0; i < name.Length; i++)
{
char ch = name[i];
if (ch > '9' || ch < '0')
return -1;
result *= 10;
result += (ch - '0');
}
// return int if it's in range
if (result >= 0 && result < capsize)
return result;
return -1;
}
protected void InitializeReferences()
{
if (_refsInitialized)
throw new NotSupportedException(SR.OnlyAllowedOnce);
_refsInitialized = true;
_runnerref = new ExclusiveReference();
_replref = new WeakReference<RegexReplacement>(null);
}
/// <summary>
/// Internal worker called by all the public APIs
/// </summary>
/// <returns></returns>
internal Match Run(bool quick, int prevlen, string input, int beginning, int length, int startat)
{
if (startat < 0 || startat > input.Length)
throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative);
if (length < 0 || length > input.Length)
throw new ArgumentOutOfRangeException(nameof(length), SR.LengthNotNegative);
// There may be a cached runner; grab ownership of it if we can.
RegexRunner runner = _runnerref.Get();
// Create a RegexRunner instance if we need to
if (runner == null)
{
// Use the compiled RegexRunner factory if the code was compiled to MSIL
if (factory != null)
runner = factory.CreateInstance();
else
runner = new RegexInterpreter(_code, UseOptionInvariant() ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture);
}
Match match;
try
{
// Do the scan starting at the requested position
match = runner.Scan(this, input, beginning, beginning + length, startat, prevlen, quick, internalMatchTimeout);
}
finally
{
// Release or fill the cache slot
_runnerref.Release(runner);
}
#if DEBUG
if (Debug && match != null)
match.Dump();
#endif
return match;
}
protected bool UseOptionC() => (roptions & RegexOptions.Compiled) != 0;
/*
* True if the L option was set
*/
protected internal bool UseOptionR() => (roptions & RegexOptions.RightToLeft) != 0;
internal bool UseOptionInvariant() => (roptions & RegexOptions.CultureInvariant) != 0;
#if DEBUG
/// <summary>
/// True if the regex has debugging enabled
/// </summary>
internal bool Debug => (roptions & RegexOptions.Debug) != 0;
#endif
}
}
| |
using System;
/// <summary>
/// System.Text.StringBuilder.Replace(oldChar,newChar,startIndex,count)
/// </summary>
class StringBuilderReplace2
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars)
private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars)
private const int c_MAX_LONG_STR_LEN = 65535;
public static int Main()
{
StringBuilderReplace2 test = new StringBuilderReplace2();
TestLibrary.TestFramework.BeginTestCase("for Method:System.Text.StringBuilder.Replace(oldChar,newChar,indexStart,count)");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = posTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive test scenarios
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Old char does not exist in source StringBuilder, random new char. ";
const string c_TEST_ID = "P001";
char oldChar = TestLibrary.Generator.GetChar(-55);
int length = c_MIN_STRING_LEN+TestLibrary.Generator.GetInt32(-55) %(c_MAX_STRING_LEN-c_MIN_STRING_LEN);
int index = 0;
char ch;
string oldString = string.Empty;
while (index < length)
{
ch = TestLibrary.Generator.GetChar(-55);
if (oldChar == ch)
{
continue;
}
oldString += ch.ToString();
index++;
}
int startIndex = TestLibrary.Generator.GetInt32(-55) % oldString.Length;
int count = TestLibrary.Generator.GetInt32(-55) % (oldString.Length - startIndex);
int indexChar = oldString.IndexOf(oldChar, startIndex, count);
char newChar = TestLibrary.Generator.GetChar(-55);
while (oldString.IndexOf(newChar, startIndex, count) > -1)
{
newChar = TestLibrary.Generator.GetChar(-55);
}
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldChar, newChar,startIndex,count);
if ((indexChar != stringBuilder.ToString().IndexOf(newChar,startIndex,count)) || (-1 != stringBuilder.ToString().IndexOf(oldChar,startIndex,count)))
{
TestLibrary.TestFramework.LogError("001", "StringBuilder\"" + oldString + "\" can't corrently Replace \"" + oldChar.ToString() + "\" to \"" + newChar + "\" from index of StringBuilder :" + startIndex.ToString() + "to count " + count.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e );
retVal = false;
}
return retVal;
}
public bool posTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Old char exists in source StringBuilder, random new char. ";
const string c_TEST_ID = "P002";
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
int startIndex = TestLibrary.Generator.GetInt32(-55) % oldString.Length;
int count = TestLibrary.Generator.GetInt32(-55) % (oldString.Length - startIndex);
char oldChar;
if (count == 0)
{
oldChar = oldString[0];
}
else
{
oldChar = oldString[startIndex + TestLibrary.Generator.GetInt32(-55) % count];
}
int indexChar = oldString.IndexOf(oldChar, startIndex, count);
char newChar = TestLibrary.Generator.GetChar(-55);
while (oldString.IndexOf(newChar, startIndex, count) > -1)
{
newChar = TestLibrary.Generator.GetChar(-55);
}
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldChar, newChar, startIndex, count);
if ((indexChar != stringBuilder.ToString().IndexOf(newChar, startIndex, count)) || (-1 != stringBuilder.ToString().IndexOf(oldChar, startIndex, count)))
{
TestLibrary.TestFramework.LogError("003", "StringBuilder\"" + oldString + "\" can't corrently Replace \"" + oldChar.ToString() + "\" to \"" + newChar + "\" from index of StringBuilder :" + startIndex.ToString() + "to count " + count.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e );
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: Verify StringBuilder Replace char that stringBuilder includes ";
const string c_TEST_ID = "P003";
string oldString = TestLibrary.Generator.GetString(-55, false, 0, 0);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(oldString);
int startIndex = 0;
int count = 0;
char oldChar = TestLibrary.Generator.GetChar(-55);
char newChar = TestLibrary.Generator.GetChar(-55);
int indexChar = oldString.IndexOf(oldString, startIndex, count);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (-1 != stringBuilder.ToString().IndexOf(newChar, startIndex, count))
{
TestLibrary.TestFramework.LogError("005", "StringBuilder\"" + oldString + "\" can't corrently Replace \"" + oldChar.ToString() + "\" to \"" + newChar + "\" from index of StringBuilder :" + startIndex.ToString() + "to count " + count.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e );
retVal = false;
}
return retVal;
}
#endregion
#region NegitiveTesting
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: Start index is larger than source StringBuilder's length";
const string c_TEST_ID = "N001";
string strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
char oldChar = TestLibrary.Generator.GetChar(-55);
char newChar = TestLibrary.Generator.GetChar(-55);
int startIndex = strSrc.Length +TestLibrary.Generator.GetInt32(-55) % (Int32.MaxValue - strSrc.Length);
int count = TestLibrary.Generator.GetInt32(-55);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldChar, newChar, startIndex, count);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, startIndex,count,oldChar,newChar));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex,count,oldChar,newChar));
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: Replace count is larger than source StringBuilder's length";
const string c_TEST_ID = "N002";
string strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
char oldChar = TestLibrary.Generator.GetChar(-55);
char newChar = TestLibrary.Generator.GetChar(-55);
int startIndex = TestLibrary.Generator.GetInt32(-55) % strSrc.Length;
int count = strSrc.Length - startIndex + TestLibrary.Generator.GetInt32(-55);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldChar, newChar, startIndex, count);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, startIndex,count,oldChar,newChar));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex,count,oldChar,newChar));
retVal = false;
}
return retVal;
}
#endregion
#region Helper methords for testing
private string GetDataString(string strSrc, int startIndex, int count,char oldChar,char newChar)
{
string str1, str;
int len1;
if (null == strSrc)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = strSrc;
len1 = strSrc.Length;
}
str = string.Format("\n[Source StingBulider value]\n \"{0}\"", str1);
str += string.Format("\n[Length of source StringBuilder]\n {0}", len1);
str += string.Format("\n[Start index ]\n{0}", startIndex);
str += string.Format("\n[Replace count]\n{0}", count);
str += string.Format("\n[Old char]\n{0}", oldChar);
str += string.Format("\n[New char]\n{0}", newChar);
return str;
}
#endregion
}
| |
// 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!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedTargetInstancesClientSnippets
{
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedListRequestObject()
{
// Snippet: AggregatedList(AggregatedListTargetInstancesRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
AggregatedListTargetInstancesRequest request = new AggregatedListTargetInstancesRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<TargetInstanceAggregatedList, KeyValuePair<string, TargetInstancesScopedList>> response = targetInstancesClient.AggregatedList(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, TargetInstancesScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (TargetInstanceAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, TargetInstancesScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListRequestObjectAsync()
{
// Snippet: AggregatedListAsync(AggregatedListTargetInstancesRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
AggregatedListTargetInstancesRequest request = new AggregatedListTargetInstancesRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<TargetInstanceAggregatedList, KeyValuePair<string, TargetInstancesScopedList>> response = targetInstancesClient.AggregatedListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, TargetInstancesScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((TargetInstanceAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, TargetInstancesScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedList()
{
// Snippet: AggregatedList(string, string, int?, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<TargetInstanceAggregatedList, KeyValuePair<string, TargetInstancesScopedList>> response = targetInstancesClient.AggregatedList(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, TargetInstancesScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (TargetInstanceAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, TargetInstancesScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListAsync()
{
// Snippet: AggregatedListAsync(string, string, int?, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<TargetInstanceAggregatedList, KeyValuePair<string, TargetInstancesScopedList>> response = targetInstancesClient.AggregatedListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, TargetInstancesScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((TargetInstanceAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, TargetInstancesScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, TargetInstancesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteTargetInstanceRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
DeleteTargetInstanceRequest request = new DeleteTargetInstanceRequest
{
Zone = "",
RequestId = "",
Project = "",
TargetInstance = "",
};
// Make the request
lro::Operation<Operation, Operation> response = targetInstancesClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetInstancesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteTargetInstanceRequest, CallSettings)
// Additional: DeleteAsync(DeleteTargetInstanceRequest, CancellationToken)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
DeleteTargetInstanceRequest request = new DeleteTargetInstanceRequest
{
Zone = "",
RequestId = "",
Project = "",
TargetInstance = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await targetInstancesClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetInstancesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, string, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
string project = "";
string zone = "";
string targetInstance = "";
// Make the request
lro::Operation<Operation, Operation> response = targetInstancesClient.Delete(project, zone, targetInstance);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetInstancesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, string, CallSettings)
// Additional: DeleteAsync(string, string, string, CancellationToken)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string zone = "";
string targetInstance = "";
// Make the request
lro::Operation<Operation, Operation> response = await targetInstancesClient.DeleteAsync(project, zone, targetInstance);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetInstancesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetTargetInstanceRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
GetTargetInstanceRequest request = new GetTargetInstanceRequest
{
Zone = "",
Project = "",
TargetInstance = "",
};
// Make the request
TargetInstance response = targetInstancesClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetTargetInstanceRequest, CallSettings)
// Additional: GetAsync(GetTargetInstanceRequest, CancellationToken)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
GetTargetInstanceRequest request = new GetTargetInstanceRequest
{
Zone = "",
Project = "",
TargetInstance = "",
};
// Make the request
TargetInstance response = await targetInstancesClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, string, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
string project = "";
string zone = "";
string targetInstance = "";
// Make the request
TargetInstance response = targetInstancesClient.Get(project, zone, targetInstance);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, string, CallSettings)
// Additional: GetAsync(string, string, string, CancellationToken)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string zone = "";
string targetInstance = "";
// Make the request
TargetInstance response = await targetInstancesClient.GetAsync(project, zone, targetInstance);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertTargetInstanceRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
InsertTargetInstanceRequest request = new InsertTargetInstanceRequest
{
Zone = "",
RequestId = "",
Project = "",
TargetInstanceResource = new TargetInstance(),
};
// Make the request
lro::Operation<Operation, Operation> response = targetInstancesClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetInstancesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertTargetInstanceRequest, CallSettings)
// Additional: InsertAsync(InsertTargetInstanceRequest, CancellationToken)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
InsertTargetInstanceRequest request = new InsertTargetInstanceRequest
{
Zone = "",
RequestId = "",
Project = "",
TargetInstanceResource = new TargetInstance(),
};
// Make the request
lro::Operation<Operation, Operation> response = await targetInstancesClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetInstancesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, string, TargetInstance, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
string project = "";
string zone = "";
TargetInstance targetInstanceResource = new TargetInstance();
// Make the request
lro::Operation<Operation, Operation> response = targetInstancesClient.Insert(project, zone, targetInstanceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = targetInstancesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, string, TargetInstance, CallSettings)
// Additional: InsertAsync(string, string, TargetInstance, CancellationToken)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string zone = "";
TargetInstance targetInstanceResource = new TargetInstance();
// Make the request
lro::Operation<Operation, Operation> response = await targetInstancesClient.InsertAsync(project, zone, targetInstanceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await targetInstancesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListTargetInstancesRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
ListTargetInstancesRequest request = new ListTargetInstancesRequest
{
Zone = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<TargetInstanceList, TargetInstance> response = targetInstancesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (TargetInstance item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (TargetInstanceList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TargetInstance item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TargetInstance> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TargetInstance item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListTargetInstancesRequest, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
ListTargetInstancesRequest request = new ListTargetInstancesRequest
{
Zone = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<TargetInstanceList, TargetInstance> response = targetInstancesClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TargetInstance item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((TargetInstanceList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TargetInstance item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TargetInstance> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TargetInstance item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, string, int?, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = TargetInstancesClient.Create();
// Initialize request argument(s)
string project = "";
string zone = "";
// Make the request
PagedEnumerable<TargetInstanceList, TargetInstance> response = targetInstancesClient.List(project, zone);
// Iterate over all response items, lazily performing RPCs as required
foreach (TargetInstance item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (TargetInstanceList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TargetInstance item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TargetInstance> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TargetInstance item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, string, int?, CallSettings)
// Create client
TargetInstancesClient targetInstancesClient = await TargetInstancesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string zone = "";
// Make the request
PagedAsyncEnumerable<TargetInstanceList, TargetInstance> response = targetInstancesClient.ListAsync(project, zone);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TargetInstance item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((TargetInstanceList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TargetInstance item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TargetInstance> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TargetInstance item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Models;
using osuTK;
namespace osu.Game.Tournament.Screens.Editors
{
public class SeedingEditorScreen : TournamentEditorScreen<SeedingEditorScreen.SeeingResultRow, SeedingResult>
{
private readonly TournamentTeam team;
protected override BindableList<SeedingResult> Storage => team.SeedingResults;
public SeedingEditorScreen(TournamentTeam team)
{
this.team = team;
}
public class SeeingResultRow : CompositeDrawable, IModelBacked<SeedingResult>
{
public SeedingResult Model { get; }
[Resolved]
private LadderInfo ladderInfo { get; set; }
public SeeingResultRow(TournamentTeam team, SeedingResult round)
{
Model = round;
Masking = true;
CornerRadius = 10;
SeedingBeatmapEditor beatmapEditor = new SeedingBeatmapEditor(round)
{
Width = 0.95f
};
InternalChildren = new Drawable[]
{
new Box
{
Colour = OsuColour.Gray(0.1f),
RelativeSizeAxes = Axes.Both,
},
new FillFlowContainer
{
Margin = new MarginPadding(5),
Padding = new MarginPadding { Right = 160 },
Spacing = new Vector2(5),
Direction = FillDirection.Full,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new SettingsTextBox
{
LabelText = "Mod",
Width = 0.33f,
Bindable = Model.Mod
},
new SettingsSlider<int>
{
LabelText = "Seed",
Width = 0.33f,
Bindable = Model.Seed
},
new SettingsButton
{
Width = 0.2f,
Margin = new MarginPadding(10),
Text = "Add beatmap",
Action = () => beatmapEditor.CreateNew()
},
beatmapEditor
}
},
new DangerousSettingsButton
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
RelativeSizeAxes = Axes.None,
Width = 150,
Text = "Delete result",
Action = () =>
{
Expire();
team.SeedingResults.Remove(Model);
},
}
};
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
}
public class SeedingBeatmapEditor : CompositeDrawable
{
private readonly SeedingResult round;
private readonly FillFlowContainer flow;
public SeedingBeatmapEditor(SeedingResult round)
{
this.round = round;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
InternalChild = flow = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
ChildrenEnumerable = round.Beatmaps.Select(p => new SeedingBeatmapRow(round, p))
};
}
public void CreateNew()
{
var user = new SeedingBeatmap();
round.Beatmaps.Add(user);
flow.Add(new SeedingBeatmapRow(round, user));
}
public class SeedingBeatmapRow : CompositeDrawable
{
private readonly SeedingResult result;
public SeedingBeatmap Model { get; }
[Resolved]
protected IAPIProvider API { get; private set; }
private readonly Bindable<string> beatmapId = new Bindable<string>();
private readonly Bindable<string> score = new Bindable<string>();
private readonly Container drawableContainer;
public SeedingBeatmapRow(SeedingResult result, SeedingBeatmap beatmap)
{
this.result = result;
Model = beatmap;
Margin = new MarginPadding(10);
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Masking = true;
CornerRadius = 5;
InternalChildren = new Drawable[]
{
new Box
{
Colour = OsuColour.Gray(0.2f),
RelativeSizeAxes = Axes.Both,
},
new FillFlowContainer
{
Margin = new MarginPadding(5),
Padding = new MarginPadding { Right = 160 },
Spacing = new Vector2(5),
Direction = FillDirection.Horizontal,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new SettingsNumberBox
{
LabelText = "Beatmap ID",
RelativeSizeAxes = Axes.None,
Width = 200,
Bindable = beatmapId,
},
new SettingsSlider<int>
{
LabelText = "Seed",
RelativeSizeAxes = Axes.None,
Width = 200,
Bindable = beatmap.Seed
},
new SettingsTextBox
{
LabelText = "Score",
RelativeSizeAxes = Axes.None,
Width = 200,
Bindable = score,
},
drawableContainer = new Container
{
Size = new Vector2(100, 70),
},
}
},
new DangerousSettingsButton
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
RelativeSizeAxes = Axes.None,
Width = 150,
Text = "Delete Beatmap",
Action = () =>
{
Expire();
result.Beatmaps.Remove(beatmap);
},
}
};
}
[BackgroundDependencyLoader]
private void load(RulesetStore rulesets)
{
beatmapId.Value = Model.ID.ToString();
beatmapId.BindValueChanged(idString =>
{
int parsed;
int.TryParse(idString.NewValue, out parsed);
Model.ID = parsed;
if (idString.NewValue != idString.OldValue)
Model.BeatmapInfo = null;
if (Model.BeatmapInfo != null)
{
updatePanel();
return;
}
var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = Model.ID });
req.Success += res =>
{
Model.BeatmapInfo = res.ToBeatmap(rulesets);
updatePanel();
};
req.Failure += _ =>
{
Model.BeatmapInfo = null;
updatePanel();
};
API.Queue(req);
}, true);
score.Value = Model.Score.ToString();
score.BindValueChanged(str => long.TryParse(str.NewValue, out Model.Score));
}
private void updatePanel()
{
drawableContainer.Clear();
if (Model.BeatmapInfo != null)
{
drawableContainer.Child = new TournamentBeatmapPanel(Model.BeatmapInfo, result.Mod.Value)
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Width = 300
};
}
}
}
}
}
protected override SeeingResultRow CreateDrawable(SeedingResult model) => new SeeingResultRow(team, model);
}
}
| |
using System;
using System.Globalization;
using Newtonsoft.Json;
// -----===== autogenerated code =====-----
// ReSharper disable All
// generator: FractionValuesGenerator, UnitJsonConverterGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator
namespace iSukces.UnitedValues
{
[Serializable]
[JsonConverter(typeof(LinearForceJsonConverter))]
public partial struct LinearForce : IUnitedValue<LinearForceUnit>, IEquatable<LinearForce>, IFormattable
{
/// <summary>
/// creates instance of LinearForce
/// </summary>
/// <param name="value">value</param>
/// <param name="unit">unit</param>
public LinearForce(decimal value, LinearForceUnit unit)
{
Value = value;
Unit = unit;
}
public LinearForce(decimal value, ForceUnit counterUnit, LengthUnit denominatorUnit)
{
Value = value;
Unit = new LinearForceUnit(counterUnit, denominatorUnit);
}
public LinearForce ConvertTo(LinearForceUnit newUnit)
{
// generator : FractionValuesGenerator.Add_ConvertTo
if (Unit.Equals(newUnit))
return this;
var a = new Force(Value, Unit.CounterUnit);
var b = new Length(1, Unit.DenominatorUnit);
a = a.ConvertTo(newUnit.CounterUnit);
b = b.ConvertTo(newUnit.DenominatorUnit);
return new LinearForce(a.Value / b.Value, newUnit);
}
public bool Equals(LinearForce other)
{
return Value == other.Value && !(Unit is null) && Unit.Equals(other.Unit);
}
public bool Equals(IUnitedValue<LinearForceUnit> other)
{
if (other is null)
return false;
return Value == other.Value && !(Unit is null) && Unit.Equals(other.Unit);
}
public override bool Equals(object other)
{
return other is IUnitedValue<LinearForceUnit> unitedValue ? Equals(unitedValue) : false;
}
public decimal GetBaseUnitValue()
{
// generator : BasicUnitValuesGenerator.Add_GetBaseUnitValue
var factor1 = GlobalUnitRegistry.Factors.Get(Unit.CounterUnit);
var factor2 = GlobalUnitRegistry.Factors.Get(Unit.DenominatorUnit);
if ((factor1.HasValue && factor2.HasValue))
return Value * factor1.Value / factor2.Value;
throw new Exception("Unable to find multiplication for unit " + Unit);
}
public override int GetHashCode()
{
unchecked
{
return (Value.GetHashCode() * 397) ^ Unit?.GetHashCode() ?? 0;
}
}
public LinearForce Round(int decimalPlaces)
{
return new LinearForce(Math.Round(Value, decimalPlaces), Unit);
}
/// <summary>
/// Returns unit name
/// </summary>
public override string ToString()
{
return Value.ToString(CultureInfo.InvariantCulture) + Unit.UnitName;
}
/// <summary>
/// Returns unit name
/// </summary>
/// <param name="format"></param>
/// <param name="provider"></param>
public string ToString(string format, IFormatProvider provider = null)
{
return this.ToStringFormat(format, provider);
}
public LinearForce WithCounterUnit(ForceUnit newUnit)
{
// generator : FractionValuesGenerator.Add_WithCounterUnit
var oldUnit = Unit.CounterUnit;
if (oldUnit == newUnit)
return this;
var oldFactor = GlobalUnitRegistry.Factors.GetThrow(oldUnit);
var newFactor = GlobalUnitRegistry.Factors.GetThrow(newUnit);
var resultUnit = Unit.WithCounterUnit(newUnit);
return new LinearForce(oldFactor / newFactor * Value, resultUnit);
}
public LinearForce WithDenominatorUnit(LengthUnit newUnit)
{
// generator : FractionValuesGenerator.Add_WithDenominatorUnit
var oldUnit = Unit.DenominatorUnit;
if (oldUnit == newUnit)
return this;
var oldFactor = GlobalUnitRegistry.Factors.GetThrow(oldUnit);
var newFactor = GlobalUnitRegistry.Factors.GetThrow(newUnit);
var resultUnit = Unit.WithDenominatorUnit(newUnit);
return new LinearForce(newFactor / oldFactor * Value, resultUnit);
}
/// <summary>
/// Inequality operator
/// </summary>
/// <param name="left">first value to compare</param>
/// <param name="right">second value to compare</param>
public static bool operator !=(LinearForce left, LinearForce right)
{
return !left.Equals(right);
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="linearForce">a dividend (counter) - a value that is being divided</param>
/// <param name="length">a divisor (denominator) - a value which dividend is divided by</param>
public static Pressure operator /(LinearForce linearForce, Length length)
{
// generator : MultiplyAlgebraGenerator.CreateCodeForLeftFractionValue
// Pressure operator /(LinearForce linearForce, Length length)
// scenario with hint
// .Is<LinearForce, Length, Pressure>("/")
// hint location HandleCreateOperatorCode, line 50 Def_LinearForce_Length_Pressure
var leftConverted = linearForce.ConvertTo(new LinearForceUnit(ForceUnits.Newton, LengthUnits.Meter));
var rightConverted = length.ConvertTo(LengthUnits.Meter);
var value = leftConverted.Value / rightConverted.Value;
return new Pressure(value, PressureUnits.Pascal);
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="linearForce">a dividend (counter) - a value that is being divided</param>
/// <param name="pressure">a divisor (denominator) - a value which dividend is divided by</param>
public static Length operator /(LinearForce linearForce, Pressure pressure)
{
// generator : MultiplyAlgebraGenerator.CreateCodeForLeftFractionValue
// Length operator /(LinearForce linearForce, Pressure pressure)
// scenario with hint
// .Is<LinearForce, Pressure, Length>("/")
// hint location HandleCreateOperatorCode, line 43 Def_LinearForce_Length_Pressure
var leftConverted = linearForce.ConvertTo(new LinearForceUnit(ForceUnits.Newton, LengthUnits.Meter));
var rightConverted = pressure.ConvertTo(PressureUnits.Pascal);
var value = leftConverted.Value / rightConverted.Value;
return new Length(value, LengthUnits.Meter);
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="linearForce">a dividend (counter) - a value that is being divided</param>
/// <param name="length">a divisor (denominator) - a value which dividend is divided by</param>
public static Pressure? operator /(LinearForce? linearForce, Length length)
{
// generator : MultiplyAlgebraGenerator.CreateCode
if (linearForce is null)
return null;
return linearForce.Value / length;
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="linearForce">a dividend (counter) - a value that is being divided</param>
/// <param name="pressure">a divisor (denominator) - a value which dividend is divided by</param>
public static Length? operator /(LinearForce? linearForce, Pressure pressure)
{
// generator : MultiplyAlgebraGenerator.CreateCode
if (linearForce is null)
return null;
return linearForce.Value / pressure;
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="linearForce">a dividend (counter) - a value that is being divided</param>
/// <param name="length">a divisor (denominator) - a value which dividend is divided by</param>
public static Pressure? operator /(LinearForce linearForce, Length? length)
{
// generator : MultiplyAlgebraGenerator.CreateCode
if (length is null)
return null;
return linearForce / length.Value;
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="linearForce">a dividend (counter) - a value that is being divided</param>
/// <param name="pressure">a divisor (denominator) - a value which dividend is divided by</param>
public static Length? operator /(LinearForce linearForce, Pressure? pressure)
{
// generator : MultiplyAlgebraGenerator.CreateCode
if (pressure is null)
return null;
return linearForce / pressure.Value;
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="linearForce">a dividend (counter) - a value that is being divided</param>
/// <param name="length">a divisor (denominator) - a value which dividend is divided by</param>
public static Pressure? operator /(LinearForce? linearForce, Length? length)
{
// generator : MultiplyAlgebraGenerator.CreateCode
if (linearForce is null || length is null)
return null;
return linearForce.Value / length.Value;
}
/// <summary>
/// Division operation, calculates value dividend/divisor with unit that derives from dividend unit
/// </summary>
/// <param name="linearForce">a dividend (counter) - a value that is being divided</param>
/// <param name="pressure">a divisor (denominator) - a value which dividend is divided by</param>
public static Length? operator /(LinearForce? linearForce, Pressure? pressure)
{
// generator : MultiplyAlgebraGenerator.CreateCode
if (linearForce is null || pressure is null)
return null;
return linearForce.Value / pressure.Value;
}
/// <summary>
/// Equality operator
/// </summary>
/// <param name="left">first value to compare</param>
/// <param name="right">second value to compare</param>
public static bool operator ==(LinearForce left, LinearForce right)
{
return left.Equals(right);
}
public static LinearForce Parse(string value)
{
// generator : FractionValuesGenerator.Add_Parse
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException(nameof(value));
var r = CommonParse.Parse(value, typeof(LinearForce));
var units = Common.SplitUnitNameBySlash(r.UnitName);
if (units.Length != 2)
throw new Exception($"{r.UnitName} is not valid LinearForce unit");
var counterUnit = new ForceUnit(units[0]);
var denominatorUnit = new LengthUnit(units[1]);
return new LinearForce(r.Value, counterUnit, denominatorUnit);
}
/// <summary>
/// value
/// </summary>
public decimal Value { get; }
/// <summary>
/// unit
/// </summary>
public LinearForceUnit Unit { get; }
}
public partial class LinearForceJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(LinearForceUnit);
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The JsonReader to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.ValueType == typeof(string))
{
if (objectType == typeof(LinearForce))
return LinearForce.Parse((string)reader.Value);
}
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is null)
writer.WriteNull();
else
writer.WriteValue(value.ToString());
}
}
}
| |
// 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 OLEDB.Test.ModuleCore;
using System.IO;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
/////////////////////////////////////////////////////////////////////////
// TestCase ReadValue
//
/////////////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract partial class TCReadValue : TCXMLReaderBaseGeneral
{
public const String ST_TEST_NAME = "CHARS1";
public const String ST_GEN_ENT_NAME = "e1";
public const String ST_GEN_ENT_VALUE = "e1foo";
private bool VerifyInvalidReadValue(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
Char[] buffer = new Char[iBufferSize];
ReloadSource();
DataReader.PositionOnElement(ST_TEST_NAME);
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return bPassed;
}
catch (NotSupportedException)
{
return true;
}
}
try
{
DataReader.ReadValueChunk(buffer, iIndex, iCount);
}
catch (Exception e)
{
CError.WriteLine("Actual exception:{0}", e.GetType().ToString());
CError.WriteLine("Expected exception:{0}", exceptionType.ToString());
bPassed = (e.GetType().ToString() == exceptionType.ToString());
}
return bPassed;
}
[Variation("ReadValue", Pri = 0)]
public int TestReadValuePri0()
{
char[] buffer = new char[5];
ReloadSource(new StringReader("<root>value</root>"));
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didn't read 5 chars");
CError.Compare("value", new string(buffer), "Strings don't match");
return TEST_PASS;
}
[Variation("ReadValue on Element", Pri = 0)]
public int TestReadValuePri0onElement()
{
char[] buffer = new char[5];
ReloadSource(new StringReader("<root>value</root>"));
DataReader.PositionOnElement("root");
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
}
catch (InvalidOperationException)
{
return TEST_PASS;
}
throw new CTestFailedException("ReadValue didnt throw expected exception");
}
[Variation("ReadValue on Attribute", Pri = 0)]
public int TestReadValueOnAttribute0()
{
char[] buffer = new char[5];
ReloadSource(new StringReader("<root name=\"value\">value</root>"));
DataReader.PositionOnElement("root");
DataReader.MoveToNextAttribute(); //This takes to text node of attribute.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didnt read 5 chars");
CError.Compare("value", new string(buffer), "Strings don't match");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 0, "Did read 5 chars");
return TEST_PASS;
}
[Variation("ReadValue on Attribute after ReadAttributeValue", Pri = 2)]
public int TestReadValueOnAttribute1()
{
char[] buffer = new char[5];
ReloadSource(new StringReader("<root name=\"value\">value</root>"));
DataReader.PositionOnElement("root");
DataReader.MoveToNextAttribute(); //This takes to text node of attribute.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadAttributeValue(), true, "Didnt read attribute value");
CError.Compare(DataReader.Value, "value", "Didnt read correct attribute value");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didnt read 5 chars");
CError.Compare("value", new string(buffer), "Strings don't match");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 0, "Did read 5 chars");
CError.WriteLineIgnore(DataReader.MoveToElement() + "");
DataReader.Read();
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didnt read 5 chars on text node");
CError.Compare("value", new string(buffer), "Strings don't match");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 0, "Did read 5 chars on text node");
return TEST_PASS;
}
[Variation("ReadValue on empty buffer", Pri = 0)]
public int TestReadValue2Pri0()
{
char[] buffer = new char[0];
ReloadSource(new StringReader("<root>value</root>"));
DataReader.PositionOnElement("root");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
}
catch (ArgumentException)
{
return TEST_PASS;
}
throw new CTestFailedException("ReadValue didnt throw expected exception");
}
[Variation("ReadValue on negative count", Pri = 0)]
public int TestReadValue3Pri0()
{
char[] buffer = new char[5];
ReloadSource(new StringReader("<root>value</root>"));
DataReader.PositionOnElement("root");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, -1);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
try
{
DataReader.ReadValueChunk(buffer, 0, -1);
}
catch (ArgumentOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestFailedException("ReadValue didnt throw expected exception");
}
[Variation("ReadValue on negative offset", Pri = 0)]
public int TestReadValue4Pri0()
{
char[] buffer = new char[5];
ReloadSource(new StringReader("<root>value</root>"));
DataReader.PositionOnElement("root");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, -1, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
try
{
DataReader.ReadValueChunk(buffer, -1, 5);
}
catch (ArgumentOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestFailedException("ReadValue didnt throw expected exception");
}
[Variation("ReadValue with buffer = element content / 2", Pri = 0)]
public int TestReadValue1()
{
Char[] buffer = new Char[5];
ReloadSource();
DataReader.PositionOnElement(ST_TEST_NAME);
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didnt read first 5");
CError.Compare("01234", new string(buffer), "First strings don't match");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didnt read second 5 chars");
CError.Compare("56789", new string(buffer), "Second strings don't match");
return TEST_PASS;
}
[Variation("ReadValue entire value in one call", Pri = 0)]
public int TestReadValue2()
{
Char[] buffer = new Char[10];
ReloadSource();
DataReader.PositionOnElement(ST_TEST_NAME);
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 10), 10, "Didnt read 10");
CError.Compare("0123456789", new string(buffer), "Strings don't match");
return TEST_PASS;
}
[Variation("ReadValue bit by bit", Pri = 0)]
public int TestReadValue3()
{
Char[] buffer = new Char[10];
ReloadSource();
DataReader.PositionOnElement(ST_TEST_NAME);
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
int index = 0;
for (index = 0; index < buffer.Length; index++)
{
CError.Compare(DataReader.ReadValueChunk(buffer, index, 1), 1, "Read " + index);
}
CError.Compare("0123456789", new string(buffer), "Strings don't match");
return TEST_PASS;
}
[Variation("ReadValue for value more than 4K", Pri = 0)]
public int TestReadValue4()
{
int size = 8192;
Char[] buffer = new Char[size];
string val = new string('x', size);
ReloadSource(new StringReader("<root>" + val + "</root>"));
DataReader.PositionOnElement("root");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
int index = 0;
for (index = 0; index < buffer.Length; index++)
{
CError.Compare(DataReader.ReadValueChunk(buffer, index, 1), 1, "Read " + index);
}
CError.Compare(val, new string(buffer), "Strings don't match");
return TEST_PASS;
}
[Variation("ReadValue for value more than 4K and invalid element", Pri = 1)]
public int TestReadValue5()
{
int size = 8192;
Char[] buffer = new Char[size];
string val = new string('x', size);
if (IsRoundTrippedReader())
return TEST_SKIPPED;
ReloadSource(new StringReader("<root>" + val + "</notroot>"));
DataReader.PositionOnElement("root");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
int index = 0;
for (index = 0; index < buffer.Length; index++)
{
CError.Compare(DataReader.ReadValueChunk(buffer, index, 1), 1, "Read " + index);
}
CError.Compare(val, new string(buffer), "Strings don't match");
try
{
DataReader.Read();
return TEST_FAIL;
}
catch (XmlException)
{
return TEST_PASS;
}
}
[Variation("ReadValue with count > buffer size")]
public int TestReadValue7()
{
return BoolToLTMResult(VerifyInvalidReadValue(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadValue with index > buffer size")]
public int TestReadValue8()
{
return BoolToLTMResult(VerifyInvalidReadValue(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadValue with index + count exceeds buffer")]
public int TestReadValue10()
{
return BoolToLTMResult(VerifyInvalidReadValue(5, 2, 5, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadValue with combination Text, CDATA and Whitespace")]
public int TestReadChar11()
{
string strExpected = "AB";
ReloadSource();
DataReader.PositionOnElement("CAT");
DataReader.Read();
char[] buffer = new char[strExpected.Length];
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue");
CError.Compare(new string(buffer), strExpected, "str");
return TEST_PASS;
}
[Variation("ReadValue with combination Text, CDATA and SignificantWhitespace")]
public int TestReadChar12()
{
string strExpected = "AB";
ReloadSource();
DataReader.PositionOnElement("CATMIXED");
DataReader.Read();
char[] buffer = new char[strExpected.Length];
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue");
CError.Compare(new string(buffer), strExpected, "str");
return TEST_PASS;
}
[Variation("ReadValue with buffer == null")]
public int TestReadChar13()
{
ReloadSource();
DataReader.PositionOnElement("CHARS1");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(null, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
try
{
DataReader.ReadValueChunk(null, 0, 0);
}
catch (ArgumentNullException)
{
return TEST_PASS;
}
return TEST_FAIL;
}
[Variation("ReadValue with multiple different inner nodes")]
public int TestReadChar14()
{
string strExpected = "somevalue";
char[] buffer = new char[strExpected.Length];
string strxml = "<ROOT>somevalue<![CDATA[somevalue]]>somevalue</ROOT>";
ReloadSourceStr(strxml);
DataReader.PositionOnElement("ROOT");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue1");
CError.Compare(new string(buffer), strExpected, "str1");
DataReader.Read();//Now on CDATA.
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue2");
CError.Compare(new string(buffer), strExpected, "str2");
DataReader.Read();//Now back on Text
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue3");
CError.Compare(new string(buffer), strExpected, "str3");
return TEST_PASS;
}
[Variation("ReadValue after failed ReadValue")]
public int TestReadChar15()
{
string strExpected = "somevalue";
char[] buffer = new char[strExpected.Length];
string strxml = "<ROOT>somevalue</ROOT>";
ReloadSourceStr(strxml);
DataReader.PositionOnElement("ROOT");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
int nChars;
try
{
nChars = DataReader.ReadValueChunk(buffer, strExpected.Length, 3);
}
catch (ArgumentException)
{
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue Count");
CError.Compare(new string(buffer), strExpected, "str");
return TEST_PASS;
}
CError.WriteLine("Couldnt read after ArgumentException");
return TEST_FAIL;
}
[Variation("Read after partial ReadValue")]
public int TestReadChar16()
{
string strExpected = "somevalue";
char[] buffer = new char[strExpected.Length];
string strxml = "<ROOT>somevalue</ROOT>";
ReloadSourceStr(strxml);
DataReader.PositionOnElement("ROOT");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
int nChars = DataReader.ReadValueChunk(buffer, 0, 2);
CError.Compare(nChars, 2, "Read 2");
DataReader.Read();
CError.Compare(DataReader.VerifyNode(XmlNodeType.EndElement, "ROOT", String.Empty), "1vn");
return TEST_PASS;
}
[Variation("Test error after successful ReadValue")]
public int TestReadChar19()
{
if (IsRoundTrippedReader() || IsSubtreeReader()) return TEST_SKIPPED;
Char[] buffer = new Char[9];
ReloadSource(new StringReader("<root>somevalue</root></root>"));
DataReader.PositionOnElement("root");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
int index = 0;
for (index = 0; index < buffer.Length; index++)
{
CError.Compare(DataReader.ReadValueChunk(buffer, index, 1), 1, "Read " + index);
}
CError.Compare("somevalue", new string(buffer), "Strings don't match");
try
{
while (DataReader.Read()) ;
}
catch (XmlException)
{
return TEST_PASS;
}
return TEST_FAIL;
}
//[Variation("Call on invalid element content after 4k boundary", Pri = 1, Params = new object[] { false, 1024 * 4})]
//[Variation("Call on invalid element content after 64k boundary for Async", Pri = 1, Params = new object[] { true, 1024 * 64 })]
public int TestReadChar21()
{
if (IsRoundTrippedReader()) return TEST_SKIPPED;
bool forAsync = (bool)CurVariation.Params[0];
if (forAsync != AsyncUtil.IsAsyncEnabled)
return TEST_SKIPPED;
int size = (int)CurVariation.Params[1];
string somechar = new string('x', size);
string strxml = String.Format("<ROOT>a" + somechar + "{0}c</ROOT>", Convert.ToChar(0));
ReloadSourceStr(strxml);
DataReader.PositionOnElement("ROOT");
char[] buffer = new char[1];
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
DataReader.Read();
try
{
while (DataReader.ReadValueChunk(buffer, 0, 1) > 0) ;
}
catch (XmlException xe)
{
CError.WriteLineIgnore(xe.ToString());
return TEST_PASS;
}
return TEST_FAIL;
}
[Variation("ReadValue with whitespaces")]
public int TestTextReadValue25()
{
string strExpected = "somevalue";
char[] buffer = new char[strExpected.Length];
string strxml = "<ROOT>somevalue<![CDATA[somevalue]]><test1/> <test2/></ROOT>";
ReloadSourceStr(strxml);
DataReader.PositionOnElement("ROOT");
DataReader.Read();
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue1");
CError.Compare(new string(buffer), strExpected, "str1");
DataReader.Read();//Now on CDATA.
CError.Compare(DataReader.ReadValueChunk(buffer, 0, buffer.Length), strExpected.Length, "ReadValue2");
CError.Compare(new string(buffer), strExpected, "str2");
DataReader.Read();//Now on test
char[] spaces = new char[4];
DataReader.Read();//Now on whitespace.
CError.Compare(DataReader.ReadValueChunk(spaces, 0, spaces.Length), spaces.Length, "ReadValue3");
CError.Compare(new string(spaces), " ", "str3");
return TEST_PASS;
}
[Variation("ReadValue when end tag doesn't exist")]
public int TestTextReadValue26()
{
if (IsRoundTrippedReader()) return TEST_SKIPPED;
char[] buffer = new char[5];
ReloadSource(new StringReader("<root>value</notroot>"));
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 5), 5, "Didnt read 5 chars");
CError.Compare("value", new string(buffer), "Strings don't match");
try
{
DataReader.Read();
return TEST_FAIL;
}
catch (XmlException)
{
return TEST_PASS;
}
}
[Variation("Testing with character entities")]
public int TestCharEntities0()
{
char[] buffer = new char[1];
ReloadSource(new StringReader("<root>va</root>lue</root>"));
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
while (DataReader.ReadValueChunk(buffer, 0, 1) > 0) ;
DataReader.Read();//This takes you to end element
DataReader.Read();//This finishes the reading and sets nodetype to none.
CError.Compare(DataReader.NodeType, XmlNodeType.None, "Not on End");
return TEST_PASS;
}
[Variation("Testing with character entities when value more than 4k")]
public int TestCharEntities1()
{
char[] buffer = new char[1];
ReloadSource(new StringReader("<root>va" + new string('x', 5000) + "l</root>ue</root>"));
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
while (DataReader.ReadValueChunk(buffer, 0, 1) > 0) ;
DataReader.Read();//This takes you to end element
DataReader.Read();//This finishes the reading and sets nodetype to none.
CError.Compare(DataReader.NodeType, XmlNodeType.None, "Not on End");
return TEST_PASS;
}
[Variation("Testing with character entities with another pattern")]
public int TestCharEntities2()
{
char[] buffer = new char[1];
ReloadSource(new StringReader("<!DOCTYPE root[<!ENTITY x \"somevalue\"><!ELEMENT root ANY>]><root>value&x;</root>"));
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
if (!DataReader.CanReadValueChunk)
{
try
{
DataReader.ReadValueChunk(buffer, 0, 5);
return TEST_FAIL;
}
catch (NotSupportedException)
{
return TEST_PASS;
}
}
while (DataReader.ReadValueChunk(buffer, 0, 1) > 0) ;
DataReader.Read();//This takes you to end element
DataReader.Read();//This finishes the reading and sets nodetype to none.
CError.Compare(DataReader.NodeType, XmlNodeType.None, "Not on End");
return TEST_PASS;
}
[Variation("Testing a usecase pattern with large file")]
public int TestReadValueOnBig()
{
ReloadSource();
char[] buffer = new char[1];
while (DataReader.Read())
{
if (DataReader.HasValue && DataReader.CanReadValueChunk)
{
Random rand = new Random();
if (rand.Next(1) == 1)
{
CError.WriteLineIgnore(DataReader.Value);
}
int count;
do
{
count = rand.Next(4) + 1;
buffer = new char[count];
if (rand.Next(1) == 1)
{
CError.WriteLineIgnore(DataReader.Value);
break;
}
}
while (DataReader.ReadValueChunk(buffer, 0, count) > 0);
CError.WriteLineIgnore(DataReader.Value);
}
else
{
if (!DataReader.CanReadValueChunk)
{
try
{
buffer = new char[1];
DataReader.ReadValueChunk(buffer, 0, 1);
}
catch (NotSupportedException)
{
}
}
else
{
try
{
buffer = new char[1];
DataReader.ReadValueChunk(buffer, 0, 1);
}
catch (InvalidOperationException)
{
}
}
}
}
return TEST_PASS;
}
[Variation("ReadValue on Comments with IgnoreComments")]
public int TestReadValueOnComments0()
{
if (!IsFactoryReader())
return TEST_SKIPPED;
char[] buffer = null;
buffer = new char[3];
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
MyDict<string, object> ht = new MyDict<string, object>();
ht[ReaderFactory.HT_CURDESC] = GetDescription().ToLowerInvariant();
ht[ReaderFactory.HT_CURVAR] = CurVariation.Desc.ToLowerInvariant();
ht[ReaderFactory.HT_STRINGREADER] = new StringReader("<root>val<!--Comment-->ue</root>");
ht[ReaderFactory.HT_READERSETTINGS] = settings;
ReloadSource(ht);
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Didnt read 3 chars");
CError.Compare("val", new string(buffer), "Strings don't match");
buffer = new char[2];
DataReader.Read(); //This takes to text node.
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 2), 2, "Didnt read 2 chars");
CError.Compare("ue", new string(buffer), "Strings don't match");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("ReadValue on PI with IgnorePI")]
public int TestReadValueOnPIs0()
{
if (!IsFactoryReader())
return TEST_SKIPPED;
char[] buffer = null;
buffer = new char[3];
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreProcessingInstructions = true;
MyDict<string, object> ht = new MyDict<string, object>();
ht[ReaderFactory.HT_CURDESC] = GetDescription().ToLowerInvariant();
ht[ReaderFactory.HT_CURVAR] = CurVariation.Desc.ToLowerInvariant();
ht[ReaderFactory.HT_STRINGREADER] = new StringReader("<root>val<?pi target?>ue</root>");
ht[ReaderFactory.HT_READERSETTINGS] = settings;
ReloadSource(ht);
DataReader.PositionOnElement("root");
DataReader.Read(); //This takes to text node.
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Didnt read 3 chars");
CError.Compare("val", new string(buffer), "Strings don't match");
buffer = new char[2];
DataReader.Read(); //This takes to text node.
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 2), 2, "Didnt read 2 chars");
CError.Compare("ue", new string(buffer), "Strings don't match");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("Skip after ReadAttributeValue/ReadValueChunk")]
public int SkipAfterReadAttributeValueAndReadValueChunkDoesNotThrow()
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Ignore;
XmlReader reader = XmlReader.Create(FilePathUtil.getStream(this.StandardPath + @"\XML10\ms_xml\vs084.xml"), settings);
reader.ReadToFollowing("a");
reader.MoveToNextAttribute();
reader.ReadAttributeValue();
reader.ReadValueChunk(new char[3], 0, 3); //<< removing this line works fine.
reader.Skip();
CError.Compare(reader.NodeType, XmlNodeType.Whitespace, "NT");
reader.Read();
CError.Compare(reader.NodeType, XmlNodeType.Element, "NT1");
CError.Compare(reader.Name, "a", "Name");
return TEST_PASS;
}
[Variation("ReadValueChunk - doesn't work correctly on attributes")]
public int ReadValueChunkDoesWorkProperlyOnAttributes()
{
if (!IsFactoryReader())
return TEST_SKIPPED;
string xml = @"<root a1='12345' a2='value'/>";
ReloadSource(new StringReader(xml));
Char[] buffer = new Char[10];
CError.Compare(DataReader.Read(), "Read");
CError.Compare(DataReader.MoveToNextAttribute(), "MoveToNextAttribute");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Error");
CError.Compare(buffer[0].ToString(), "1", "buffer1");
CError.Compare(buffer[1].ToString(), "2", "buffer1");
CError.Compare(buffer[2].ToString(), "3", "buffer1");
CError.WriteLine("LineNumber" + DataReader.LineNumber);
CError.WriteLine("LinePosition" + DataReader.LinePosition);
CError.Compare(DataReader.MoveToNextAttribute(), "MoveToNextAttribute");
CError.Compare(DataReader.MoveToFirstAttribute(), "MoveToFirstAttribute");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Error");
CError.Compare(buffer[0].ToString(), "1", "buffer2");
CError.Compare(buffer[1].ToString(), "2", "buffer2");
CError.Compare(buffer[2].ToString(), "3", "buffer2");
CError.WriteLine("LineNumber" + DataReader.LineNumber);
CError.WriteLine("LinePosition" + DataReader.LinePosition);
return TEST_PASS;
}
[Variation("ReadValueChunk - doesn't work correctly on special attributes")]
public int ReadValueChunkDoesWorkProperlyOnSpecialAttributes()
{
if (!IsFactoryReader())
return TEST_SKIPPED;
string xml = @"<?xml version='1.0'?><root/>";
ReloadSource(new StringReader(xml));
Char[] buffer = new Char[10];
CError.Compare(DataReader.Read(), "Read");
CError.Compare(DataReader.MoveToFirstAttribute(), "MoveToFirstAttribute");
CError.Compare(DataReader.Name, "version", "Name");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Error");
CError.Compare(buffer[0].ToString(), "1", "buffer1");
CError.Compare(buffer[1].ToString(), ".", "buffer1");
CError.Compare(buffer[2].ToString(), "0", "buffer1");
CError.WriteLine("LineNumber" + DataReader.LineNumber);
CError.WriteLine("LinePosition" + DataReader.LinePosition);
CError.Compare(DataReader.MoveToElement(), "MoveToElement");
CError.Compare(DataReader.MoveToFirstAttribute(), "MoveToFirstAttribute");
CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Error");
CError.Compare(buffer[0].ToString(), "1", "buffer2");
CError.Compare(buffer[1].ToString(), ".", "buffer2");
CError.Compare(buffer[2].ToString(), "0", "buffer2");
CError.WriteLine("LineNumber" + DataReader.LineNumber);
CError.WriteLine("LinePosition" + DataReader.LinePosition);
return TEST_PASS;
}
[Variation("SubtreeReader inserted attributes don't work with ReadValueChunk")]
public int ReadValueChunkWorksProperlyWithSubtreeReaderInsertedAttributes()
{
if (!IsFactoryReader())
return TEST_SKIPPED;
string xml = "<root xmlns='foo'><bar/></root>";
ReloadSource(new StringReader(xml));
DataReader.Read();
DataReader.Read();
using (XmlReader sr = DataReader.ReadSubtree())
{
sr.Read();
sr.MoveToFirstAttribute();
CError.WriteLine("Value: " + sr.Value);
sr.MoveToFirstAttribute();
char[] chars = new char[100];
int i = sr.ReadValueChunk(chars, 0, 100);
CError.WriteLine("ReadValueChunk: length = " + i + " value = '" + new string(chars, 0, i) + "'");
}
return TEST_PASS;
}
[Variation("goto to text node, ask got.Value, ReadValueChunk")]
public int TestReadValue_1()
{
string xml = "<elem0>123</elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
DataReader.Read();
DataReader.Read();
CError.Compare(DataReader.Value, "123", "value");
try
{
CError.Compare(DataReader.ReadValueChunk(chars, 0, 1), 1, "size");
}
catch (NotSupportedException e) { CError.WriteLine(e); }
DataReader.Close();
return TEST_PASS;
}
[Variation("goto to text node, ReadValueChunk, ask got.Value")]
public int TestReadValue_2()
{
string xml = "<elem0>123</elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
DataReader.Read();
DataReader.Read();
try
{
CError.Compare(DataReader.ReadValueChunk(chars, 0, 1), 1, "size");
CError.Compare(DataReader.Value, "23", "value");
}
catch (NotSupportedException e) { CError.WriteLine(e); }
DataReader.Close();
return TEST_PASS;
}
[Variation("goto to huge text node, read several chars with ReadValueChank and Move forward with .Read()")]
public int TestReadValue_3()
{
string xml = "<elem0>123 $^ 56789 abcdefg hij klmn opqrst 12345 uvw xy ^ z</elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
DataReader.Read();
DataReader.Read();
try
{
CError.Compare(DataReader.ReadValueChunk(chars, 0, 5), 5, "size");
}
catch (NotSupportedException e) { CError.WriteLine(e); }
DataReader.Read();
DataReader.Close();
return TEST_PASS;
}
[Variation("goto to huge text node with invalid chars, read several chars with ReadValueChank and Move forward with .Read()")]
public int TestReadValue_4()
{
string xml = "<elem0>123 $^ 56789 abcdefg hij klmn opqrst 12345 uvw xy ^ z</elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
DataReader.Read();
DataReader.Read();
try
{
CError.Compare(DataReader.ReadValueChunk(chars, 0, 5), 5, "size");
DataReader.Read();
}
catch (XmlException e) { CError.WriteLine(e); }
catch (NotSupportedException e) { CError.WriteLine(e); }
finally
{
DataReader.Close();
}
return TEST_PASS;
}
[Variation("Call ReadValueChunk on two or more nodes")]
public int TestReadValue_5()
{
string xml = "<elem0>123<elem1>123<elem2>123</elem2>123</elem1>123</elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
int startPos = 0;
int readSize = 3;
int currentSize = 0;
while (DataReader.Read())
{
DataReader.Read();
if (DataReader.NodeType == XmlNodeType.Text || DataReader.NodeType == XmlNodeType.None)
continue;
currentSize = DataReader.ReadValueChunk(chars, startPos, readSize);
CError.Equals(currentSize, 3, "size");
CError.Equals(chars[0].ToString(), "1", "buffer1");
CError.Equals(chars[1].ToString(), "2", "buffer2");
CError.Equals(chars[2].ToString(), "3", "buffer3");
CError.Equals(DataReader.LineNumber, 0, "LineNumber");
CError.Equals(DataReader.LinePosition, 0, "LinePosition");
}
DataReader.Close();
return TEST_PASS;
}
//[Variation("ReadValueChunk on an xmlns attribute", Param = "<foo xmlns='default'> <bar > id='1'/> </foo>")]
//[Variation("ReadValueChunk on an xmlns:k attribute", Param = "<k:foo xmlns:k='default'> <k:bar id='1'/> </k:foo>")]
//[Variation("ReadValueChunk on an xml:space attribute", Param = "<foo xml:space='default'> <bar > id='1'/> </foo>")]
//[Variation("ReadValueChunk on an xml:lang attribute", Param = "<foo xml:lang='default'> <bar > id='1'/> </foo>")]
public int TestReadValue_6()
{
string xml = (string)this.CurVariation.Param;
ReloadSource(new StringReader(xml));
char[] chars = new char[8];
DataReader.Read();
DataReader.MoveToAttribute(0);
try
{
CError.Equals(DataReader.Value, "default", "value");
CError.Equals(DataReader.ReadValueChunk(chars, 0, 8), 7, "size");
}
catch (NotSupportedException e) { CError.WriteLine(e); }
DataReader.Close();
return TEST_PASS;
}
[Variation("Call ReadValueChunk on two or more nodes and whitespace")]
public int TestReadValue_7()
{
string xml = @"<elem0> 123" + "\n" + @" <elem1>" + "\r" + @"123
<elem2>
123 </elem2>" + "\r\n" + @" 123</elem1> 123 </elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
int startPos = 0;
int readSize = 3;
int currentSize = 0;
try
{
while (DataReader.Read())
{
DataReader.Read();
if (DataReader.NodeType == XmlNodeType.Text || DataReader.NodeType == XmlNodeType.None)
continue;
currentSize = DataReader.ReadValueChunk(chars, startPos, readSize);
CError.Equals(currentSize, 3, "size");
CError.Equals(DataReader.LineNumber, 0, "LineNumber");
CError.Equals(DataReader.LinePosition, 0, "LinePosition");
}
}
catch (NotSupportedException e) { CError.WriteLine(e); }
DataReader.Close();
return TEST_PASS;
}
[Variation("Call ReadValueChunk on two or more nodes and whitespace after call Value")]
public int TestReadValue_8()
{
string xml = @"<elem0> 123" + "\n" + @" <elem1>" + "\r" + @"123
<elem2>
123 </elem2>" + "\r\n" + @" 123</elem1> 123 </elem0>";
ReloadSource(new StringReader(xml));
char[] chars = new char[100];
int startPos = 0;
int readSize = 3;
int currentSize = 0;
try
{
while (DataReader.Read())
{
DataReader.Read();
if (DataReader.NodeType == XmlNodeType.Text || DataReader.NodeType == XmlNodeType.None)
continue;
CError.Equals(DataReader.Value.Contains("123"), "Value");
currentSize = DataReader.ReadValueChunk(chars, startPos, readSize);
CError.Equals(currentSize, 3, "size");
CError.Equals(DataReader.LineNumber, 0, "LineNumber");
CError.Equals(DataReader.LinePosition, 0, "LinePosition");
}
}
catch (NotSupportedException e) { CError.WriteLine(e); }
DataReader.Close();
return TEST_PASS;
}
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;
namespace EdiEngine.Standards.X12_004010.Maps
{
public class M_202 : MapLoop
{
public M_202() : base(null)
{
Content.AddRange(new MapBaseEntity[] {
new BGN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new TRN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new L_N9(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
new CTT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
//1000
public class L_N1 : MapLoop
{
public L_N1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
});
}
}
//2000
public class L_N9 : MapLoop
{
public L_N9(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new L_DEX(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
});
}
}
//2100
public class L_DEX : MapLoop
{
public L_DEX(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new DEX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 15 },
new CN1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new INT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 4 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new MPP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new III() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 15 },
new L_ASM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_NM1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
});
}
}
//2110
public class L_ASM : MapLoop
{
public L_ASM(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new ASM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
});
}
}
//2120
public class L_NM1 : MapLoop
{
public L_NM1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new L_LX(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
});
}
}
//2121
public class L_LX : MapLoop
{
public L_LX(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 15 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new YNQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 6 },
new III() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 50 },
new LUC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new RLD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 50 },
new INT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 6 },
new PPD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new BUY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PEX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new BEP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new L_IGI(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_NX1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_LN1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new L_CRC(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_PAM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 4 },
new L_UWI(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
});
}
}
//2122
public class L_IGI : MapLoop
{
public L_IGI(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new IGI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//2123
public class L_NX1 : MapLoop
{
public L_NX1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NX1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 15 },
new REA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PDS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
});
}
}
//2124
public class L_LN1 : MapLoop
{
public L_LN1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LN1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new YNQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//2125
public class L_CRC : MapLoop
{
public L_CRC(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new CRC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new IN1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new IN2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 30 },
new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new YNQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new AIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 15 },
new L_SCM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2126
public class L_SCM : MapLoop
{
public L_SCM(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SCM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new SCS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
});
}
}
//2128
public class L_PAM : MapLoop
{
public L_PAM(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new PAM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new YNQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2129
public class L_UWI : MapLoop
{
public L_UWI(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new UWI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new III() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
}
}
| |
namespace android.text
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.text.Layout_))]
public abstract partial class Layout : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Layout(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class Alignment : java.lang.Enum
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Alignment(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public static global::android.text.Layout.Alignment[] values()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.Layout.Alignment._m0.native == global::System.IntPtr.Zero)
global::android.text.Layout.Alignment._m0 = @__env.GetStaticMethodIDNoThrow(global::android.text.Layout.Alignment.staticClass, "values", "()[Landroid/text/Layout/Alignment;");
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.text.Layout.Alignment>(@__env.CallStaticObjectMethod(android.text.Layout.Alignment.staticClass, global::android.text.Layout.Alignment._m0)) as android.text.Layout.Alignment[];
}
private static global::MonoJavaBridge.MethodId _m1;
public static global::android.text.Layout.Alignment valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.Layout.Alignment._m1.native == global::System.IntPtr.Zero)
global::android.text.Layout.Alignment._m1 = @__env.GetStaticMethodIDNoThrow(global::android.text.Layout.Alignment.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/text/Layout$Alignment;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.text.Layout.Alignment>(@__env.CallStaticObjectMethod(android.text.Layout.Alignment.staticClass, global::android.text.Layout.Alignment._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.text.Layout.Alignment;
}
internal static global::MonoJavaBridge.FieldId _ALIGN_CENTER5223;
public static global::android.text.Layout.Alignment ALIGN_CENTER
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.text.Layout.Alignment>(@__env.GetStaticObjectField(global::android.text.Layout.Alignment.staticClass, _ALIGN_CENTER5223)) as android.text.Layout.Alignment;
}
}
internal static global::MonoJavaBridge.FieldId _ALIGN_NORMAL5224;
public static global::android.text.Layout.Alignment ALIGN_NORMAL
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.text.Layout.Alignment>(@__env.GetStaticObjectField(global::android.text.Layout.Alignment.staticClass, _ALIGN_NORMAL5224)) as android.text.Layout.Alignment;
}
}
internal static global::MonoJavaBridge.FieldId _ALIGN_OPPOSITE5225;
public static global::android.text.Layout.Alignment ALIGN_OPPOSITE
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.text.Layout.Alignment>(@__env.GetStaticObjectField(global::android.text.Layout.Alignment.staticClass, _ALIGN_OPPOSITE5225)) as android.text.Layout.Alignment;
}
}
static Alignment()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.Layout.Alignment.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Layout$Alignment"));
global::android.text.Layout.Alignment._ALIGN_CENTER5223 = @__env.GetStaticFieldIDNoThrow(global::android.text.Layout.Alignment.staticClass, "ALIGN_CENTER", "Landroid/text/Layout$Alignment;");
global::android.text.Layout.Alignment._ALIGN_NORMAL5224 = @__env.GetStaticFieldIDNoThrow(global::android.text.Layout.Alignment.staticClass, "ALIGN_NORMAL", "Landroid/text/Layout$Alignment;");
global::android.text.Layout.Alignment._ALIGN_OPPOSITE5225 = @__env.GetStaticFieldIDNoThrow(global::android.text.Layout.Alignment.staticClass, "ALIGN_OPPOSITE", "Landroid/text/Layout$Alignment;");
}
}
[global::MonoJavaBridge.JavaClass()]
public partial class Directions : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Directions(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
static Directions()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.Layout.Directions.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Layout$Directions"));
}
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual float getLineWidth(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getLineWidth", "(I)F", ref global::android.text.Layout._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual global::java.lang.CharSequence getText()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::android.text.Layout.staticClass, "getText", "()Ljava/lang/CharSequence;", ref global::android.text.Layout._m1) as java.lang.CharSequence;
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual void draw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.text.Layout.staticClass, "draw", "(Landroid/graphics/Canvas;)V", ref global::android.text.Layout._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual void draw(android.graphics.Canvas arg0, android.graphics.Path arg1, android.graphics.Paint arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.text.Layout.staticClass, "draw", "(Landroid/graphics/Canvas;Landroid/graphics/Path;Landroid/graphics/Paint;I)V", ref global::android.text.Layout._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual int getWidth()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getWidth", "()I", ref global::android.text.Layout._m4);
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual int getHeight()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getHeight", "()I", ref global::android.text.Layout._m5);
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual global::android.text.TextPaint getPaint()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.text.Layout.staticClass, "getPaint", "()Landroid/text/TextPaint;", ref global::android.text.Layout._m6) as android.text.TextPaint;
}
private static global::MonoJavaBridge.MethodId _m7;
public abstract int getLineCount();
private static global::MonoJavaBridge.MethodId _m8;
public virtual int getLineBounds(int arg0, android.graphics.Rect arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineBounds", "(ILandroid/graphics/Rect;)I", ref global::android.text.Layout._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m9;
public static float getDesiredWidth(java.lang.CharSequence arg0, int arg1, int arg2, android.text.TextPaint arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.Layout._m9.native == global::System.IntPtr.Zero)
global::android.text.Layout._m9 = @__env.GetStaticMethodIDNoThrow(global::android.text.Layout.staticClass, "getDesiredWidth", "(Ljava/lang/CharSequence;IILandroid/text/TextPaint;)F");
return @__env.CallStaticFloatMethod(android.text.Layout.staticClass, global::android.text.Layout._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
public static float getDesiredWidth(string arg0, int arg1, int arg2, android.text.TextPaint arg3)
{
return getDesiredWidth((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1, arg2, arg3);
}
private static global::MonoJavaBridge.MethodId _m10;
public static float getDesiredWidth(java.lang.CharSequence arg0, android.text.TextPaint arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.Layout._m10.native == global::System.IntPtr.Zero)
global::android.text.Layout._m10 = @__env.GetStaticMethodIDNoThrow(global::android.text.Layout.staticClass, "getDesiredWidth", "(Ljava/lang/CharSequence;Landroid/text/TextPaint;)F");
return @__env.CallStaticFloatMethod(android.text.Layout.staticClass, global::android.text.Layout._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public static float getDesiredWidth(string arg0, android.text.TextPaint arg1)
{
return getDesiredWidth((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1);
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual int getEllipsizedWidth()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getEllipsizedWidth", "()I", ref global::android.text.Layout._m11);
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual void increaseWidthTo(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.text.Layout.staticClass, "increaseWidthTo", "(I)V", ref global::android.text.Layout._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual global::android.text.Layout.Alignment getAlignment()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.text.Layout.Alignment>(this, global::android.text.Layout.staticClass, "getAlignment", "()Landroid/text/Layout$Alignment;", ref global::android.text.Layout._m13) as android.text.Layout.Alignment;
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual float getSpacingMultiplier()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getSpacingMultiplier", "()F", ref global::android.text.Layout._m14);
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual float getSpacingAdd()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getSpacingAdd", "()F", ref global::android.text.Layout._m15);
}
private static global::MonoJavaBridge.MethodId _m16;
public abstract int getLineTop(int arg0);
private static global::MonoJavaBridge.MethodId _m17;
public abstract int getLineDescent(int arg0);
private static global::MonoJavaBridge.MethodId _m18;
public abstract int getLineStart(int arg0);
private static global::MonoJavaBridge.MethodId _m19;
public abstract int getParagraphDirection(int arg0);
private static global::MonoJavaBridge.MethodId _m20;
public abstract bool getLineContainsTab(int arg0);
private static global::MonoJavaBridge.MethodId _m21;
public abstract global::android.text.Layout.Directions getLineDirections(int arg0);
private static global::MonoJavaBridge.MethodId _m22;
public abstract int getTopPadding();
private static global::MonoJavaBridge.MethodId _m23;
public abstract int getBottomPadding();
private static global::MonoJavaBridge.MethodId _m24;
public virtual float getPrimaryHorizontal(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getPrimaryHorizontal", "(I)F", ref global::android.text.Layout._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual float getSecondaryHorizontal(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getSecondaryHorizontal", "(I)F", ref global::android.text.Layout._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual float getLineLeft(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getLineLeft", "(I)F", ref global::android.text.Layout._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual float getLineRight(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getLineRight", "(I)F", ref global::android.text.Layout._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m28;
public virtual float getLineMax(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.text.Layout.staticClass, "getLineMax", "(I)F", ref global::android.text.Layout._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual int getLineForVertical(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineForVertical", "(I)I", ref global::android.text.Layout._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m30;
public virtual int getLineForOffset(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineForOffset", "(I)I", ref global::android.text.Layout._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m31;
public virtual int getOffsetForHorizontal(int arg0, float arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getOffsetForHorizontal", "(IF)I", ref global::android.text.Layout._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m32;
public virtual int getLineEnd(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineEnd", "(I)I", ref global::android.text.Layout._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m33;
public virtual int getLineVisibleEnd(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineVisibleEnd", "(I)I", ref global::android.text.Layout._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m34;
public virtual int getLineBottom(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineBottom", "(I)I", ref global::android.text.Layout._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m35;
public virtual int getLineBaseline(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineBaseline", "(I)I", ref global::android.text.Layout._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m36;
public virtual int getLineAscent(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getLineAscent", "(I)I", ref global::android.text.Layout._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m37;
public virtual int getOffsetToLeftOf(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getOffsetToLeftOf", "(I)I", ref global::android.text.Layout._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m38;
public virtual int getOffsetToRightOf(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getOffsetToRightOf", "(I)I", ref global::android.text.Layout._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m39;
public virtual void getCursorPath(int arg0, android.graphics.Path arg1, java.lang.CharSequence arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.text.Layout.staticClass, "getCursorPath", "(ILandroid/graphics/Path;Ljava/lang/CharSequence;)V", ref global::android.text.Layout._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
public void getCursorPath(int arg0, android.graphics.Path arg1, string arg2)
{
getCursorPath(arg0, arg1, (global::java.lang.CharSequence)(global::java.lang.String)arg2);
}
private static global::MonoJavaBridge.MethodId _m40;
public virtual void getSelectionPath(int arg0, int arg1, android.graphics.Path arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.text.Layout.staticClass, "getSelectionPath", "(IILandroid/graphics/Path;)V", ref global::android.text.Layout._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m41;
public virtual global::android.text.Layout.Alignment getParagraphAlignment(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.text.Layout.Alignment>(this, global::android.text.Layout.staticClass, "getParagraphAlignment", "(I)Landroid/text/Layout$Alignment;", ref global::android.text.Layout._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.text.Layout.Alignment;
}
private static global::MonoJavaBridge.MethodId _m42;
public virtual int getParagraphLeft(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getParagraphLeft", "(I)I", ref global::android.text.Layout._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m43;
public virtual int getParagraphRight(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout.staticClass, "getParagraphRight", "(I)I", ref global::android.text.Layout._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m44;
protected virtual bool isSpanned()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.text.Layout.staticClass, "isSpanned", "()Z", ref global::android.text.Layout._m44);
}
private static global::MonoJavaBridge.MethodId _m45;
public abstract int getEllipsisStart(int arg0);
private static global::MonoJavaBridge.MethodId _m46;
public abstract int getEllipsisCount(int arg0);
private static global::MonoJavaBridge.MethodId _m47;
protected Layout(java.lang.CharSequence arg0, android.text.TextPaint arg1, int arg2, android.text.Layout.Alignment arg3, float arg4, float arg5) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.text.Layout._m47.native == global::System.IntPtr.Zero)
global::android.text.Layout._m47 = @__env.GetMethodIDNoThrow(global::android.text.Layout.staticClass, "<init>", "(Ljava/lang/CharSequence;Landroid/text/TextPaint;ILandroid/text/Layout$Alignment;FF)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.text.Layout.staticClass, global::android.text.Layout._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
Init(@__env, handle);
}
public static int DIR_LEFT_TO_RIGHT
{
get
{
return 1;
}
}
public static int DIR_RIGHT_TO_LEFT
{
get
{
return -1;
}
}
static Layout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.Layout.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Layout"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.text.Layout))]
internal sealed partial class Layout_ : android.text.Layout
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Layout_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override int getLineCount()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getLineCount", "()I", ref global::android.text.Layout_._m0);
}
private static global::MonoJavaBridge.MethodId _m1;
public override int getLineTop(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getLineTop", "(I)I", ref global::android.text.Layout_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m2;
public override int getLineDescent(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getLineDescent", "(I)I", ref global::android.text.Layout_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
public override int getLineStart(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getLineStart", "(I)I", ref global::android.text.Layout_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public override int getParagraphDirection(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getParagraphDirection", "(I)I", ref global::android.text.Layout_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public override bool getLineContainsTab(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.text.Layout_.staticClass, "getLineContainsTab", "(I)Z", ref global::android.text.Layout_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public override global::android.text.Layout.Directions getLineDirections(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.text.Layout_.staticClass, "getLineDirections", "(I)Landroid/text/Layout$Directions;", ref global::android.text.Layout_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.text.Layout.Directions;
}
private static global::MonoJavaBridge.MethodId _m7;
public override int getTopPadding()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getTopPadding", "()I", ref global::android.text.Layout_._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
public override int getBottomPadding()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getBottomPadding", "()I", ref global::android.text.Layout_._m8);
}
private static global::MonoJavaBridge.MethodId _m9;
public override int getEllipsisStart(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getEllipsisStart", "(I)I", ref global::android.text.Layout_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public override int getEllipsisCount(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.text.Layout_.staticClass, "getEllipsisCount", "(I)I", ref global::android.text.Layout_._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static Layout_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.Layout_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/Layout"));
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;
/// <summary>
/// A class that runs delegates using acceleration
/// </summary>
public static class DelegateSupport
{
private static Dictionary<MethodInfo, Type> delegateTypes = new Dictionary<MethodInfo, Type>();
private static Dictionary<MethodInfo, Delegate> openDelegates = new Dictionary<MethodInfo, Delegate>();
public static Delegate ToOpenDelegate(MethodInfo mi)
{
Delegate result;
if(!openDelegates.TryGetValue(mi, out result))
{
Type delegateType;
if(!delegateTypes.TryGetValue(mi, out delegateType))
{
var typeArgs = mi.GetParameters()
.Select(p => p.ParameterType)
.ToList();
typeArgs.Insert(0, mi.DeclaringType);
// builds a delegate type
if (mi.ReturnType == typeof(void)) {
delegateType = Expression.GetActionType(typeArgs.ToArray());
} else {
typeArgs.Add(mi.ReturnType);
delegateType = Expression.GetFuncType(typeArgs.ToArray());
}
delegateTypes[mi] = delegateType;
}
openDelegates[mi] = result = Delegate.CreateDelegate(delegateType, mi);
}
return result;
}
public static Delegate ToDelegate(MethodInfo mi, object target)
{
Delegate result;
Type delegateType;
if(!delegateTypes.TryGetValue(mi, out delegateType))
{
var typeArgs = mi.GetParameters()
.Select(p => p.ParameterType)
.ToList();
// builds a delegate type
if (mi.ReturnType == typeof(void)) {
delegateType = Expression.GetActionType(typeArgs.ToArray());
} else {
typeArgs.Add(mi.ReturnType);
delegateType = Expression.GetFuncType(typeArgs.ToArray());
}
delegateTypes[mi] = delegateType;
}
// creates a binded delegate if target is supplied
result = Delegate.CreateDelegate(delegateType, target, mi);
return result;
}
public class Index<TK, TR> : Dictionary<TK,TR> where TR : class, new()
{
public new TR this[TK index]
{
get
{
TR val;
if(!(TryGetValue(index, out val)))
{
base[index] = val = new TR();
}
return val;
}
set
{
base[index] = value;
}
}
}
private static Index<Type, Dictionary<string, Func<object, object[], Delegate, object>>> _functions = new Index<Type, Dictionary<string, Func<object, object[], Delegate,object>>>();
private static Dictionary<MethodInfo, Func<object, object[], object>> _methods = new Dictionary<MethodInfo, Func<object, object[], object>>();
/// <summary>
/// Registers an action type for acceleration
/// </summary>
/// <typeparam name='TType'>
/// The type to accelerate
/// </typeparam>
public static void RegisterActionType<TType>()
{
_functions[typeof(TType)][GetTypes(typeof(void))] = (object target, object[] parms, Delegate @delegate)=>{
((Action<TType>)@delegate)((TType)target); return null;
};
}
/// <summary>
/// Registers an action type for acceleration
/// </summary>
/// <typeparam name='TType'>
/// The type to accelerate
/// </typeparam>
public static void RegisterActionType<TType, T1>()
{
_functions[typeof(TType)][GetTypes(typeof(T1), typeof(void))] = (object target, object[] parms, Delegate @delegate)=>{
((Action<TType, T1>)@delegate)((TType)target, (T1)parms[0]); return null;
};
}
/// <summary>
/// Registers an action type for acceleration
/// </summary>
/// <typeparam name='TType'>
/// The type to accelerate
/// </typeparam>
public static void RegisterActionType<TType, T1, T2, T3>()
{
_functions[typeof(TType)][GetTypes(typeof(T1), typeof(T2), typeof(T3), typeof(void))] = (object target, object[] parms, Delegate @delegate)=>{
((Action<TType,T1,T2,T3>)@delegate)((TType)target, (T1)parms[0], (T2)parms[1], (T3)parms[2]); return null;
};
}
/// <summary>
/// Registers an action type for acceleration
/// </summary>
/// <typeparam name='TType'>
/// The type to accelerate
/// </typeparam>
public static void RegisterActionType<TType, T1, T2>()
{
_functions[typeof(TType)][GetTypes(typeof(T1), typeof(T2), typeof(void))] = (object target, object[] parms, Delegate @delegate)=>{
((Action<TType, T1, T2>)@delegate)((TType)target, (T1)parms[0], (T2)parms[1]); return null;
};
}
/// <summary>
/// Registers a function type for acceleration
/// </summary>
/// <typeparam name='TType'>
/// The type to accelerate
/// </typeparam>
public static void RegisterFunctionType<TType, TReturns>()
{
_functions[typeof(TType)][GetTypes(typeof(TReturns))] = (object target, object[] parms, Delegate @delegate)=>{
return (object)((Func<TType, TReturns>)@delegate)((TType)target);
};
}
/// <summary>
/// Registers a function type for acceleration
/// </summary>
/// <typeparam name='TType'>
/// The type to accelerate
/// </typeparam>
public static void RegisterFunctionType<TType, T1, TReturns>()
{
_functions[typeof(TType)][GetTypes(typeof(T1), typeof(TReturns))] = (object target, object[] parms, Delegate @delegate)=>{
return (object)((Func<TType, T1, TReturns>)@delegate)((TType)target, (T1)parms[0]);
};
}
/// <summary>
/// Registers a function type for acceleration
/// </summary>
/// <typeparam name='TType'>
/// The type to accelerate
/// </typeparam>
public static void RegisterFunctionType<TType, T1, T2, TReturns>()
{
_functions[typeof(TType)][GetTypes(typeof(T1), typeof(T2), typeof(TReturns))] = (object target, object[] parms, Delegate @delegate)=>{
return (object)((Func<TType, T1, T2, TReturns>)@delegate)((TType)target, (T1)parms[0], (T2)parms[1]);
};
}
/// <summary>
/// Registers a function type for acceleration
/// </summary>
/// <typeparam name='TType'>
/// The type to accelerate
/// </typeparam>
public static void RegisterFunctionType<TType, T1, T2, T3, TReturns>()
{
_functions[typeof(TType)][GetTypes(typeof(T1), typeof(T2), typeof(T3), typeof(TReturns))] = (object target, object[] parms, Delegate @delegate)=>{
return (object)((Func<TType, T1, T2, T3, TReturns>)@delegate)((TType)target, (T1)parms[0], (T2)parms[1], (T3)parms[2]);
};
}
/// <summary>
/// Invokes the method at high speed
/// </summary>
/// <returns>
/// The result of the invocation
/// </returns>
/// <param name='mi'>
/// The method to invoke
/// </param>
/// <param name='target'>
/// The target on which to invoke it
/// </param>
/// <param name='parameters'>
/// The parameters to pass to the method
/// </param>
public static object FastInvoke(this MethodInfo mi, object target, params object[] parameters)
{
Func<object, object[], object> getter;
string types;
if(!_methods.TryGetValue(mi, out getter))
{
if(!mi.IsStatic && _functions.ContainsKey(mi.DeclaringType) && _functions[mi.DeclaringType].ContainsKey(types = GetTypes(mi)))
{
var @delegate = ToOpenDelegate(mi);
var inner = _functions[mi.DeclaringType][types];
var complete = _methods[mi] = (t,p) => inner(t, p, @delegate);
return complete(target, parameters);
}
return mi.Invoke(target, parameters);
}
else
{
return getter(target, parameters);
}
}
static string GetTypes(params Type[] types)
{
return types.Select(t=>t.FullName).Aggregate("", (v,n)=>v += n);
}
static string GetTypes(MethodInfo mi)
{
return GetTypes(mi.GetParameters().Select(p=>p.ParameterType).Concat(new Type[] {mi.ReturnType}).ToArray());
}
}
| |
// 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.Linq;
using Xunit;
namespace System.Tests
{
public abstract partial class ArraySegment_Tests<T>
{
[Fact]
public void CopyTo_Default_ThrowsInvalidOperationException()
{
// Source is default
Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).CopyTo(new T[0]));
Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).CopyTo(new T[0], 0));
Assert.Throws<InvalidOperationException>(() => ((ICollection<T>)default(ArraySegment<T>)).CopyTo(new T[0], 0));
Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).CopyTo(new ArraySegment<T>(new T[0])));
// Destination is default
Assert.Throws<InvalidOperationException>(() => new ArraySegment<T>(new T[0]).CopyTo(default(ArraySegment<T>)));
}
[Fact]
public void Empty()
{
ArraySegment<T> empty = ArraySegment<T>.Empty;
// Assert.NotEqual uses its own Comparer, when it is comparing IEnumerables it calls GetEnumerator()
// ArraySegment<T>.GetEnumerator() throws InvalidOperationException when the array is null and default() returns null
Assert.True(default(ArraySegment<T>) != empty);
// Check that two Empty invocations return equal ArraySegments.
Assert.Equal(empty, ArraySegment<T>.Empty);
// Check that two Empty invocations return ArraySegments with a cached empty array.
// An empty array is necessary to ensure that someone doesn't use the indexer to store data in the array Empty refers to.
Assert.Same(empty.Array, ArraySegment<T>.Empty.Array);
Assert.Equal(0, empty.Array.Length);
Assert.Equal(0, empty.Offset);
Assert.Equal(0, empty.Count);
}
[Fact]
public void GetEnumerator_TypeProperties()
{
var arraySegment = new ArraySegment<T>(new T[1], 0, 1);
var ienumerableoft = (IEnumerable<T>)arraySegment;
var ienumerable = (IEnumerable)arraySegment;
ArraySegment<T>.Enumerator enumerator = arraySegment.GetEnumerator();
Assert.IsType<ArraySegment<T>.Enumerator>(enumerator);
Assert.IsAssignableFrom<IEnumerator<T>>(enumerator);
Assert.IsAssignableFrom<IEnumerator>(enumerator);
IEnumerator<T> ienumeratoroft = ienumerableoft.GetEnumerator();
IEnumerator ienumerator = ienumerable.GetEnumerator();
Assert.Equal(enumerator.GetType(), ienumeratoroft.GetType());
Assert.Equal(ienumeratoroft.GetType(), ienumerator.GetType());
}
[Fact]
public void GetEnumerator_Default_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).GetEnumerator());
}
[Fact]
public void Slice_Default_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).Slice(0));
Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).Slice(0, 0));
}
[Fact]
public void ToArray_Default_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => default(ArraySegment<T>).ToArray());
}
[Fact]
public void ToArray_Empty_ReturnsSameArray()
{
T[] cachedArray = ArraySegment<T>.Empty.ToArray();
Assert.Same(cachedArray, ArraySegment<T>.Empty.ToArray());
Assert.Same(cachedArray, new ArraySegment<T>(new T[0]).ToArray());
Assert.Same(cachedArray, new ArraySegment<T>(new T[1], 0, 0).ToArray());
}
[Fact]
public void ToArray_NonEmptyArray_DoesNotReturnSameArray()
{
// Prevent a faulty implementation like `if (Count == 0) { return Array; }`
var emptyArraySegment = new ArraySegment<T>(new T[1], 0, 0);
Assert.NotSame(emptyArraySegment.Array, emptyArraySegment.ToArray());
}
}
public static partial class ArraySegment_Tests
{
[Theory]
[MemberData(nameof(Conversion_FromArray_TestData))]
public static void Conversion_FromArray(int[] array)
{
ArraySegment<int> implicitlyConverted = array;
ArraySegment<int> explicitlyConverted = (ArraySegment<int>)array;
var expected = new ArraySegment<int>(array);
Assert.Equal(expected, implicitlyConverted);
Assert.Equal(expected, explicitlyConverted);
}
public static IEnumerable<object[]> Conversion_FromArray_TestData()
{
yield return new object[] { new int[0] };
yield return new object[] { new int[1] };
}
[Theory]
[MemberData(nameof(ArraySegment_TestData))]
public static void CopyTo(ArraySegment<int> arraySegment)
{
const int CopyPadding = 5;
const int DestinationSegmentPadding = 3;
int count = arraySegment.Count;
var destinationModel = new int[count + 2 * CopyPadding];
// CopyTo(T[])
CopyAndInvoke(destinationModel, destination =>
{
arraySegment.CopyTo(destination);
Assert.Equal(Enumerable.Repeat(default(int), 2 * CopyPadding), destination.Skip(count));
Assert.Equal(arraySegment, destination.Take(count));
});
// CopyTo(T[], int)
CopyAndInvoke(destinationModel, destination =>
{
arraySegment.CopyTo(destination, CopyPadding);
Assert.Equal(Enumerable.Repeat(default(int), CopyPadding), destination.Take(CopyPadding));
Assert.Equal(Enumerable.Repeat(default(int), CopyPadding), destination.Skip(CopyPadding + count));
Assert.Equal(arraySegment, destination.Skip(CopyPadding).Take(count));
});
// ICollection<T>.CopyTo(T[], int)
CopyAndInvoke(destinationModel, destination =>
{
((ICollection<int>)arraySegment).CopyTo(destination, CopyPadding);
Assert.Equal(Enumerable.Repeat(default(int), CopyPadding), destination.Take(CopyPadding));
Assert.Equal(Enumerable.Repeat(default(int), CopyPadding), destination.Skip(CopyPadding + count));
Assert.Equal(arraySegment, destination.Skip(CopyPadding).Take(count));
});
// CopyTo(ArraySegment<T>)
CopyAndInvoke(destinationModel, destination =>
{
// We want to make sure this overload is handling edge cases correctly, like ArraySegments that
// do not begin at the array's start, do not end at the array's end, or have a bigger count than
// the source ArraySegment. Construct an ArraySegment that will test all of these conditions.
int destinationIndex = DestinationSegmentPadding;
int destinationCount = destination.Length - 2 * DestinationSegmentPadding;
var destinationSegment = new ArraySegment<int>(destination, destinationIndex, destinationCount);
arraySegment.CopyTo(destinationSegment);
Assert.Equal(Enumerable.Repeat(default(int), destinationIndex), destination.Take(destinationIndex));
int remainder = destination.Length - destinationIndex - count;
Assert.Equal(Enumerable.Repeat(default(int), remainder), destination.Skip(destinationIndex + count));
Assert.Equal(arraySegment, destination.Skip(destinationIndex).Take(count));
});
}
private static void CopyAndInvoke<T>(T[] array, Action<T[]> action) => action(array.ToArray());
[Theory]
[MemberData(nameof(ArraySegment_TestData))]
public static void CopyTo_Invalid(ArraySegment<int> arraySegment)
{
int count = arraySegment.Count;
// ArraySegment.CopyTo calls Array.Copy internally, so the exception parameter names come from there.
// Destination is null
AssertExtensions.Throws<ArgumentNullException>("destinationArray", () => arraySegment.CopyTo(null));
AssertExtensions.Throws<ArgumentNullException>("destinationArray", () => arraySegment.CopyTo(null, 0));
// Destination index not within range
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", () => arraySegment.CopyTo(new int[0], -1));
// Destination array too small arraySegment.Count + destinationIndex > destinationArray.Length
AssertExtensions.Throws<ArgumentException>("destinationArray", () => arraySegment.CopyTo(new int[arraySegment.Count * 2], arraySegment.Count + 1));
if (arraySegment.Any())
{
// Destination not large enough
AssertExtensions.Throws<ArgumentException>("destinationArray", () => arraySegment.CopyTo(new int[count - 1]));
AssertExtensions.Throws<ArgumentException>("destinationArray", () => arraySegment.CopyTo(new int[count - 1], 0));
AssertExtensions.Throws<ArgumentException>(null, () => arraySegment.CopyTo(new ArraySegment<int>(new int[count - 1])));
// Don't write beyond the limits of the destination in cases where source.Count > destination.Count
AssertExtensions.Throws<ArgumentException>(null, () => arraySegment.CopyTo(new ArraySegment<int>(new int[count], 1, 0))); // destination.Array can't fit source at destination.Offset
AssertExtensions.Throws<ArgumentException>(null, () => arraySegment.CopyTo(new ArraySegment<int>(new int[count], 0, count - 1))); // destination.Array can fit source at destination.Offset, but destination can't
}
}
[Theory]
[MemberData(nameof(ArraySegment_TestData))]
public static void GetEnumerator(ArraySegment<int> arraySegment)
{
int[] array = arraySegment.Array;
int index = arraySegment.Offset;
int count = arraySegment.Count;
ArraySegment<int>.Enumerator enumerator = arraySegment.GetEnumerator();
var actual = new List<int>();
while (enumerator.MoveNext())
{
actual.Add(enumerator.Current);
}
// After MoveNext returns false once, it should return false the second time.
Assert.False(enumerator.MoveNext());
IEnumerable<int> expected = array.Skip(index).Take(count);
Assert.Equal(expected, actual);
}
[Theory]
[MemberData(nameof(ArraySegment_TestData))]
public static void GetEnumerator_Dispose(ArraySegment<int> arraySegment)
{
int[] array = arraySegment.Array;
int index = arraySegment.Offset;
ArraySegment<int>.Enumerator enumerator = arraySegment.GetEnumerator();
bool expected = arraySegment.Count > 0;
// Dispose shouldn't do anything. Call it twice and then assert like nothing happened.
enumerator.Dispose();
enumerator.Dispose();
Assert.Equal(expected, enumerator.MoveNext());
if (expected)
{
Assert.Equal(array[index], enumerator.Current);
}
}
[Theory]
[MemberData(nameof(ArraySegment_TestData))]
public static void GetEnumerator_Reset(ArraySegment<int> arraySegment)
{
int[] array = arraySegment.Array;
int index = arraySegment.Offset;
int count = arraySegment.Count;
var enumerator = (IEnumerator<int>)arraySegment.GetEnumerator();
int[] expected = array.Skip(index).Take(count).ToArray();
// Reset at a variety of different positions to ensure the implementation
// isn't something like `position -= CONSTANT`.
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < i; j++)
{
if (enumerator.MoveNext())
{
Assert.Equal(expected[j], enumerator.Current);
}
}
enumerator.Reset();
}
}
[Theory]
[MemberData(nameof(ArraySegment_TestData))]
public static void GetEnumerator_Invalid(ArraySegment<int> arraySegment)
{
ArraySegment<int>.Enumerator enumerator = arraySegment.GetEnumerator();
// Before beginning
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => ((IEnumerator<int>)enumerator).Current);
Assert.Throws<InvalidOperationException>(() => ((IEnumerator)enumerator).Current);
while (enumerator.MoveNext()) ;
// After end
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => ((IEnumerator<int>)enumerator).Current);
Assert.Throws<InvalidOperationException>(() => ((IEnumerator)enumerator).Current);
}
[Theory]
[MemberData(nameof(ArraySegment_TestData))]
public static void GetSetItem_InRange(ArraySegment<int> arraySegment)
{
int[] array = arraySegment.Array;
int index = arraySegment.Offset;
int count = arraySegment.Count;
int[] expected = array.Skip(index).Take(count).ToArray();
for (int i = 0; i < count; i++)
{
Assert.Equal(expected[i], arraySegment[i]);
Assert.Equal(expected[i], ((IList<int>)arraySegment)[i]);
Assert.Equal(expected[i], ((IReadOnlyList<int>)arraySegment)[i]);
}
var r = new Random(0);
for (int i = 0; i < count; i++)
{
int next = r.Next(int.MinValue, int.MaxValue);
// When we modify the underlying array, the indexer should return the updated values.
array[arraySegment.Offset + i] ^= next;
Assert.Equal(expected[i] ^ next, arraySegment[i]);
// When the indexer's set method is called, the underlying array should be modified.
arraySegment[i] ^= next;
Assert.Equal(expected[i], array[arraySegment.Offset + i]);
}
}
[Theory]
[MemberData(nameof(ArraySegment_TestData))]
public static void GetSetItem_NotInRange_Invalid(ArraySegment<int> arraySegment)
{
int[] array = arraySegment.Array;
// Before array start
Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[-arraySegment.Offset - 1]);
Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[-arraySegment.Offset - 1] = default(int));
// After array start (if Offset > 0), before start
Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[-1] = default(int));
// Before array end (if Offset + Count < Array.Length), after end
Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[arraySegment.Count]);
Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[arraySegment.Count] = default(int));
// After array end
Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[-arraySegment.Offset + array.Length]);
Assert.Throws<ArgumentOutOfRangeException>(() => arraySegment[-arraySegment.Offset + array.Length] = default(int));
}
[Theory]
[MemberData(nameof(Slice_TestData))]
public static void Slice(ArraySegment<int> arraySegment, int index, int count)
{
var expected = new ArraySegment<int>(arraySegment.Array, arraySegment.Offset + index, count);
if (index + count == arraySegment.Count)
{
Assert.Equal(expected, arraySegment.Slice(index));
}
Assert.Equal(expected, arraySegment.Slice(index, count));
}
public static IEnumerable<object[]> Slice_TestData()
{
IEnumerable<ArraySegment<int>> arraySegments = ArraySegment_TestData().Select(array => array.Single()).Cast<ArraySegment<int>>();
foreach (ArraySegment<int> arraySegment in arraySegments)
{
yield return new object[] { arraySegment, 0, 0 }; // Preserve start, no items
yield return new object[] { arraySegment, 0, arraySegment.Count }; // Preserve start, preserve count (noop)
yield return new object[] { arraySegment, arraySegment.Count, 0 }; // Start at end, no items
if (arraySegment.Any())
{
yield return new object[] { arraySegment, 1, 0 }; // Start at middle or end, no items
yield return new object[] { arraySegment, 1, arraySegment.Count - 1 }; // Start at middle or end, rest of items
yield return new object[] { arraySegment, arraySegment.Count - 1, 1 }; // Preserve start or start at middle, one item
}
yield return new object[] { arraySegment, 0, arraySegment.Count / 2 }; // Preserve start, multiple items, end at middle
yield return new object[] { arraySegment, arraySegment.Count / 2, arraySegment.Count / 2 }; // Start at middle, multiple items, end at middle (due to integer division truncation) or preserve end
yield return new object[] { arraySegment, arraySegment.Count / 4, arraySegment.Count / 2 }; // Start at middle, multiple items, end at middle
}
}
[Theory]
[MemberData(nameof(Slice_Invalid_TestData))]
public static void Slice_Invalid(ArraySegment<int> arraySegment, int index, int count)
{
if (index + count == arraySegment.Count)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arraySegment.Slice(index));
}
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arraySegment.Slice(index, count));
}
public static IEnumerable<object[]> Slice_Invalid_TestData()
{
var arraySegment = new ArraySegment<int>(new int[3], offset: 1, count: 1);
yield return new object[] { arraySegment, -arraySegment.Offset, arraySegment.Offset };
yield return new object[] { arraySegment, -arraySegment.Offset, arraySegment.Offset + arraySegment.Count };
yield return new object[] { arraySegment, -arraySegment.Offset, arraySegment.Array.Length };
yield return new object[] { arraySegment, 0, arraySegment.Array.Length - arraySegment.Offset };
yield return new object[] { arraySegment, arraySegment.Count, arraySegment.Array.Length - arraySegment.Offset - arraySegment.Count };
}
[Theory]
[MemberData(nameof(ArraySegment_TestData))]
public static void ToArray(ArraySegment<int> arraySegment)
{
// ToList is called here so we copy the data and raise an assert if ToArray modifies the underlying array.
List<int> expected = arraySegment.Array.Skip(arraySegment.Offset).Take(arraySegment.Count).ToList();
Assert.Equal(expected, arraySegment.ToArray());
}
public static IEnumerable<object[]> ArraySegment_TestData()
{
var arraySegments = new (int[] array, int index, int count)[]
{
(array: new int[0], index: 0, 0), // Empty array
(array: new[] { 3, 4, 5, 6 }, index: 0, count: 4), // Full span of non-empty array
(array: new[] { 3, 4, 5, 6 }, index: 0, count: 3), // Starts at beginning, ends in middle
(array: new[] { 3, 4, 5, 6 }, index: 1, count: 3), // Starts in middle, ends at end
(array: new[] { 3, 4, 5, 6 }, index: 1, count: 2), // Starts in middle, ends in middle
(array: new[] { 3, 4, 5, 6 }, index: 1, count: 0) // Non-empty array, count == 0
};
return arraySegments.Select(aseg => new object[] { new ArraySegment<int>(aseg.array, aseg.index, aseg.count) });
}
}
}
| |
/**
* (C) Copyright IBM Corp. 2019, 2021.
*
* 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.Collections.Generic;
using Newtonsoft.Json;
using System;
namespace IBM.Watson.Assistant.V1.Model
{
/// <summary>
/// DialogNode.
/// </summary>
public class DialogNode
{
/// <summary>
/// How the dialog node is processed.
/// </summary>
public class TypeValue
{
/// <summary>
/// Constant STANDARD for standard
/// </summary>
public const string STANDARD = "standard";
/// <summary>
/// Constant EVENT_HANDLER for event_handler
/// </summary>
public const string EVENT_HANDLER = "event_handler";
/// <summary>
/// Constant FRAME for frame
/// </summary>
public const string FRAME = "frame";
/// <summary>
/// Constant SLOT for slot
/// </summary>
public const string SLOT = "slot";
/// <summary>
/// Constant RESPONSE_CONDITION for response_condition
/// </summary>
public const string RESPONSE_CONDITION = "response_condition";
/// <summary>
/// Constant FOLDER for folder
/// </summary>
public const string FOLDER = "folder";
}
/// <summary>
/// How an `event_handler` node is processed.
/// </summary>
public class EventNameValue
{
/// <summary>
/// Constant FOCUS for focus
/// </summary>
public const string FOCUS = "focus";
/// <summary>
/// Constant INPUT for input
/// </summary>
public const string INPUT = "input";
/// <summary>
/// Constant FILLED for filled
/// </summary>
public const string FILLED = "filled";
/// <summary>
/// Constant VALIDATE for validate
/// </summary>
public const string VALIDATE = "validate";
/// <summary>
/// Constant FILLED_MULTIPLE for filled_multiple
/// </summary>
public const string FILLED_MULTIPLE = "filled_multiple";
/// <summary>
/// Constant GENERIC for generic
/// </summary>
public const string GENERIC = "generic";
/// <summary>
/// Constant NOMATCH for nomatch
/// </summary>
public const string NOMATCH = "nomatch";
/// <summary>
/// Constant NOMATCH_RESPONSES_DEPLETED for nomatch_responses_depleted
/// </summary>
public const string NOMATCH_RESPONSES_DEPLETED = "nomatch_responses_depleted";
/// <summary>
/// Constant DIGRESSION_RETURN_PROMPT for digression_return_prompt
/// </summary>
public const string DIGRESSION_RETURN_PROMPT = "digression_return_prompt";
}
/// <summary>
/// Whether this top-level dialog node can be digressed into.
/// </summary>
public class DigressInValue
{
/// <summary>
/// Constant NOT_AVAILABLE for not_available
/// </summary>
public const string NOT_AVAILABLE = "not_available";
/// <summary>
/// Constant RETURNS for returns
/// </summary>
public const string RETURNS = "returns";
/// <summary>
/// Constant DOES_NOT_RETURN for does_not_return
/// </summary>
public const string DOES_NOT_RETURN = "does_not_return";
}
/// <summary>
/// Whether this dialog node can be returned to after a digression.
/// </summary>
public class DigressOutValue
{
/// <summary>
/// Constant ALLOW_RETURNING for allow_returning
/// </summary>
public const string ALLOW_RETURNING = "allow_returning";
/// <summary>
/// Constant ALLOW_ALL for allow_all
/// </summary>
public const string ALLOW_ALL = "allow_all";
/// <summary>
/// Constant ALLOW_ALL_NEVER_RETURN for allow_all_never_return
/// </summary>
public const string ALLOW_ALL_NEVER_RETURN = "allow_all_never_return";
}
/// <summary>
/// Whether the user can digress to top-level nodes while filling out slots.
/// </summary>
public class DigressOutSlotsValue
{
/// <summary>
/// Constant NOT_ALLOWED for not_allowed
/// </summary>
public const string NOT_ALLOWED = "not_allowed";
/// <summary>
/// Constant ALLOW_RETURNING for allow_returning
/// </summary>
public const string ALLOW_RETURNING = "allow_returning";
/// <summary>
/// Constant ALLOW_ALL for allow_all
/// </summary>
public const string ALLOW_ALL = "allow_all";
}
/// <summary>
/// How the dialog node is processed.
/// Constants for possible values can be found using DialogNode.TypeValue
/// </summary>
[JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)]
public string Type { get; set; }
/// <summary>
/// How an `event_handler` node is processed.
/// Constants for possible values can be found using DialogNode.EventNameValue
/// </summary>
[JsonProperty("event_name", NullValueHandling = NullValueHandling.Ignore)]
public string EventName { get; set; }
/// <summary>
/// Whether this top-level dialog node can be digressed into.
/// Constants for possible values can be found using DialogNode.DigressInValue
/// </summary>
[JsonProperty("digress_in", NullValueHandling = NullValueHandling.Ignore)]
public string DigressIn { get; set; }
/// <summary>
/// Whether this dialog node can be returned to after a digression.
/// Constants for possible values can be found using DialogNode.DigressOutValue
/// </summary>
[JsonProperty("digress_out", NullValueHandling = NullValueHandling.Ignore)]
public string DigressOut { get; set; }
/// <summary>
/// Whether the user can digress to top-level nodes while filling out slots.
/// Constants for possible values can be found using DialogNode.DigressOutSlotsValue
/// </summary>
[JsonProperty("digress_out_slots", NullValueHandling = NullValueHandling.Ignore)]
public string DigressOutSlots { get; set; }
/// <summary>
/// The unique ID of the dialog node. This is an internal identifier used to refer to the dialog node from other
/// dialog nodes and in the diagnostic information included with message responses.
///
/// This string can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters.
/// </summary>
[JsonProperty("dialog_node", NullValueHandling = NullValueHandling.Ignore)]
public string _DialogNode { get; set; }
/// <summary>
/// The description of the dialog node. This string cannot contain carriage return, newline, or tab characters.
/// </summary>
[JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)]
public string Description { get; set; }
/// <summary>
/// The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab
/// characters.
/// </summary>
[JsonProperty("conditions", NullValueHandling = NullValueHandling.Ignore)]
public string Conditions { get; set; }
/// <summary>
/// The unique ID of the parent dialog node. This property is omitted if the dialog node has no parent.
/// </summary>
[JsonProperty("parent", NullValueHandling = NullValueHandling.Ignore)]
public string Parent { get; set; }
/// <summary>
/// The unique ID of the previous sibling dialog node. This property is omitted if the dialog node has no
/// previous sibling.
/// </summary>
[JsonProperty("previous_sibling", NullValueHandling = NullValueHandling.Ignore)]
public string PreviousSibling { get; set; }
/// <summary>
/// The output of the dialog node. For more information about how to specify dialog node output, see the
/// [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-overview#dialog-overview-responses).
/// </summary>
[JsonProperty("output", NullValueHandling = NullValueHandling.Ignore)]
public DialogNodeOutput Output { get; set; }
/// <summary>
/// The context for the dialog node.
/// </summary>
[JsonProperty("context", NullValueHandling = NullValueHandling.Ignore)]
public DialogNodeContext Context { get; set; }
/// <summary>
/// The metadata for the dialog node.
/// </summary>
[JsonProperty("metadata", NullValueHandling = NullValueHandling.Ignore)]
public Dictionary<string, object> Metadata { get; set; }
/// <summary>
/// The next step to execute following this dialog node.
/// </summary>
[JsonProperty("next_step", NullValueHandling = NullValueHandling.Ignore)]
public DialogNodeNextStep NextStep { get; set; }
/// <summary>
/// A human-readable name for the dialog node. If the node is included in disambiguation, this title is used to
/// populate the **label** property of the corresponding suggestion in the `suggestion` response type (unless it
/// is overridden by the **user_label** property). The title is also used to populate the **topic** property in
/// the `connect_to_agent` response type.
///
/// This string can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters.
/// </summary>
[JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)]
public string Title { get; set; }
/// <summary>
/// The location in the dialog context where output is stored.
/// </summary>
[JsonProperty("variable", NullValueHandling = NullValueHandling.Ignore)]
public string Variable { get; set; }
/// <summary>
/// An array of objects describing any actions to be invoked by the dialog node.
/// </summary>
[JsonProperty("actions", NullValueHandling = NullValueHandling.Ignore)]
public List<DialogNodeAction> Actions { get; set; }
/// <summary>
/// A label that can be displayed externally to describe the purpose of the node to users. If set, this label is
/// used to identify the node in disambiguation responses (overriding the value of the **title** property).
/// </summary>
[JsonProperty("user_label", NullValueHandling = NullValueHandling.Ignore)]
public string UserLabel { get; set; }
/// <summary>
/// Whether the dialog node should be excluded from disambiguation suggestions. Valid only when
/// **type**=`standard` or `frame`.
/// </summary>
[JsonProperty("disambiguation_opt_out", NullValueHandling = NullValueHandling.Ignore)]
public bool? DisambiguationOptOut { get; set; }
/// <summary>
/// For internal use only.
/// </summary>
[JsonProperty("disabled", NullValueHandling = NullValueHandling.Ignore)]
public virtual bool? Disabled { get; private set; }
/// <summary>
/// The timestamp for creation of the object.
/// </summary>
[JsonProperty("created", NullValueHandling = NullValueHandling.Ignore)]
public virtual DateTime? Created { get; private set; }
/// <summary>
/// The timestamp for the most recent update to the object.
/// </summary>
[JsonProperty("updated", NullValueHandling = NullValueHandling.Ignore)]
public virtual DateTime? Updated { get; private set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
using Internal.Runtime;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;
using Internal.NativeFormat;
using Internal.TypeSystem;
using Internal.TypeSystem.NoMetadata;
namespace Internal.Runtime.TypeLoader
{
//
// Wrap state required by the native layout info parsing in a structure, so that it can be conveniently passed around.
//
internal class NativeLayoutInfoLoadContext
{
public TypeSystemContext _typeSystemContext;
public NativeFormatModuleInfo _module;
private ExternalReferencesTable _staticInfoLookup;
private ExternalReferencesTable _externalReferencesLookup;
public Instantiation _typeArgumentHandles;
public Instantiation _methodArgumentHandles;
private TypeDesc GetInstantiationType(ref NativeParser parser, uint arity)
{
DefType typeDefinition = (DefType)GetType(ref parser);
TypeDesc[] typeArguments = new TypeDesc[arity];
for (uint i = 0; i < arity; i++)
typeArguments[i] = GetType(ref parser);
return _typeSystemContext.ResolveGenericInstantiation(typeDefinition, new Instantiation(typeArguments));
}
private TypeDesc GetModifierType(ref NativeParser parser, TypeModifierKind modifier)
{
TypeDesc typeParameter = GetType(ref parser);
switch (modifier)
{
case TypeModifierKind.Array:
return _typeSystemContext.GetArrayType(typeParameter);
case TypeModifierKind.ByRef:
return _typeSystemContext.GetByRefType(typeParameter);
case TypeModifierKind.Pointer:
return _typeSystemContext.GetPointerType(typeParameter);
default:
parser.ThrowBadImageFormatException();
return null;
}
}
private void InitializeExternalReferencesLookup()
{
if (!_externalReferencesLookup.IsInitialized())
{
bool success = _externalReferencesLookup.InitializeNativeReferences(_module);
Debug.Assert(success);
}
}
private IntPtr GetExternalReferencePointer(uint index)
{
InitializeExternalReferencesLookup();
return _externalReferencesLookup.GetIntPtrFromIndex(index);
}
internal TypeDesc GetExternalType(uint index)
{
InitializeExternalReferencesLookup();
RuntimeTypeHandle rtth = _externalReferencesLookup.GetRuntimeTypeHandleFromIndex(index);
return _typeSystemContext.ResolveRuntimeTypeHandle(rtth);
}
internal IntPtr GetGCStaticInfo(uint index)
{
if (!_staticInfoLookup.IsInitialized())
{
bool success = _staticInfoLookup.InitializeNativeStatics(_module);
Debug.Assert(success);
}
return _staticInfoLookup.GetIntPtrFromIndex(index);
}
private unsafe TypeDesc GetLookbackType(ref NativeParser parser, uint lookback)
{
var lookbackParser = parser.GetLookbackParser(lookback);
return GetType(ref lookbackParser);
}
internal TypeDesc GetType(ref NativeParser parser)
{
uint data;
var kind = parser.GetTypeSignatureKind(out data);
switch (kind)
{
case TypeSignatureKind.Lookback:
return GetLookbackType(ref parser, data);
case TypeSignatureKind.Variable:
uint index = data >> 1;
return (((data & 0x1) != 0) ? _methodArgumentHandles : _typeArgumentHandles)[checked((int)index)];
case TypeSignatureKind.Instantiation:
return GetInstantiationType(ref parser, data);
case TypeSignatureKind.Modifier:
return GetModifierType(ref parser, (TypeModifierKind)data);
case TypeSignatureKind.External:
return GetExternalType(data);
case TypeSignatureKind.MultiDimArray:
{
DefType elementType = (DefType)GetType(ref parser);
int rank = (int)data;
// Skip encoded bounds and lobounds
uint boundsCount = parser.GetUnsigned();
while (boundsCount > 0)
{
parser.GetUnsigned();
boundsCount--;
}
uint loBoundsCount = parser.GetUnsigned();
while (loBoundsCount > 0)
{
parser.GetUnsigned();
loBoundsCount--;
}
return _typeSystemContext.GetArrayType(elementType, rank);
}
case TypeSignatureKind.FunctionPointer:
Debug.Assert(false, "NYI!");
parser.ThrowBadImageFormatException();
return null;
default:
parser.ThrowBadImageFormatException();
return null;
}
}
internal MethodDesc GetMethod(ref NativeParser parser, out RuntimeSignature methodNameSig, out RuntimeSignature methodSig)
{
MethodFlags flags = (MethodFlags)parser.GetUnsigned();
IntPtr functionPointer = IntPtr.Zero;
if ((flags & MethodFlags.HasFunctionPointer) != 0)
functionPointer = GetExternalReferencePointer(parser.GetUnsigned());
DefType containingType = (DefType)GetType(ref parser);
MethodNameAndSignature nameAndSignature = TypeLoaderEnvironment.Instance.GetMethodNameAndSignature(ref parser, _module.Handle, out methodNameSig, out methodSig);
bool unboxingStub = (flags & MethodFlags.IsUnboxingStub) != 0;
MethodDesc retVal = null;
if ((flags & MethodFlags.HasInstantiation) != 0)
{
TypeDesc[] typeArguments = GetTypeSequence(ref parser);
Debug.Assert(typeArguments.Length > 0);
retVal = this._typeSystemContext.ResolveGenericMethodInstantiation(unboxingStub, containingType, nameAndSignature, new Instantiation(typeArguments), functionPointer, (flags & MethodFlags.FunctionPointerIsUSG) != 0);
}
else
{
retVal = this._typeSystemContext.ResolveRuntimeMethod(unboxingStub, containingType, nameAndSignature, functionPointer, (flags & MethodFlags.FunctionPointerIsUSG) != 0);
}
if ((flags & MethodFlags.FunctionPointerIsUSG) != 0)
{
// TODO, consider a change such that if a USG function pointer is passed in, but we have
// a way to get a non-usg pointer, that may be preferable
Debug.Assert(retVal.UsgFunctionPointer != IntPtr.Zero);
}
return retVal;
}
internal MethodDesc GetMethod(ref NativeParser parser)
{
RuntimeSignature methodSig;
RuntimeSignature methodNameSig;
return GetMethod(ref parser, out methodNameSig, out methodSig);
}
internal TypeDesc[] GetTypeSequence(ref NativeParser parser)
{
uint count = parser.GetSequenceCount();
TypeDesc[] sequence = new TypeDesc[count];
for (uint i = 0; i < count; i++)
{
sequence[i] = GetType(ref parser);
}
return sequence;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using Giver;
using Xunit;
namespace DynamicQueryable.Tests {
using Fixture;
using Dyn = System.Linq.Dynamic.DynamicQueryable;
public class ExpressionTests {
private readonly IQueryable<Order> _query;
private readonly double AvgId;
public ExpressionTests() {
var orders = Give<Order>
.ToMe(o => o.Lines = Give<OrderLine>
.ToMe(od => {
od.OrderId = o.Id;
od.Order = o;
od.Product = Give<Product>.ToMe(p => p.Supplier = Give<Company>.Single());
}).Now(new Random().Next(3, 15))
).Now(20);
AvgId = orders.Average(o => o.Id);
_query = orders.AsQueryable();
}
[Fact]
public void ShouldHandleAggregate() {
var query = _query.Select(o => o.Id);
var sumId1 = query.Aggregate((i1, i2) => i1 + i2);
var dynSumId1 = query.Aggregate("(i1, i2) => i1 + i2");
Assert.Equal(sumId1, dynSumId1);
var sumId2 = query.Aggregate(42, (i1, i2) => i1 + i2);
var dynSumId2 = query.Aggregate(42, "(i1, i2) => i1 + i2");
Assert.Equal(sumId2, dynSumId2);
var sumId3 = query.Aggregate(42, (i1, i2) => i1 + i2, i => i.ToString());
var dynSumId3 = query.Aggregate(42, "(i1, i2) => i1 + i2", "i => i.ToString()");
Assert.Throws<ArgumentNullException>(() => Dyn.Aggregate(null, ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Aggregate(_query, ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Aggregate(null, (object)null, ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Aggregate(_query, (object)null, ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Aggregate(_query, 42, ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Aggregate(null, (object)null, "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Aggregate(_query, (object)null, "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Aggregate(_query, 42, "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Aggregate(_query, 42, "Id", ""));
}
[Fact]
public void ShouldHandleAll() {
var all = _query.All(o => o.Id != 42);
var dynAll1 = _query.All("o => o.Id != @0", 42);
var dynAll2 = _query.All("o => o.Id != Meaning", new Dictionary<string, object> { { "Meaning", 42 } });
Assert.Equal(all, dynAll1);
Assert.Equal(all, dynAll2);
}
[Fact]
public void ShouldHandleAny() {
var order = _query.Any(o => o.Id < AvgId);
var dynOrder1 = _query.Any("o => o.Id < @0", AvgId);
var dynOrder2 = _query.Any("o => o.Id < AvgId", new Dictionary<string, object> { { "AvgId", AvgId } });
var dynOrder3 = ((IQueryable)_query).Any();
Assert.Equal(order, dynOrder1);
Assert.Equal(order, dynOrder2);
Assert.Equal(_query.Any(), dynOrder3);
}
[Fact]
public void ShouldHandleAverage() {
var avg = _query.Average(o => o.Price);
var dynAvg = _query.Average("o => o.Price");
Assert.Equal(avg, dynAvg);
}
[Fact]
public void ShouldHandleConcat() {
var orders1 = _query.Skip(1).Take(4).AsQueryable();
var orders2 = _query.Take(2).ToList();
var concat = orders1.Concat(orders2).ToList();
var dynConcat = ((IQueryable)orders1).Concat(orders2).Cast<Order>().ToList();
Assert.Equal(concat, dynConcat);
}
[Fact]
public void ShouldHandleContains() {
var order = _query.Last();
Assert.True(((IQueryable)_query).Contains(order));
}
[Fact]
public void ShouldHandleCount() {
var order = _query.Count(o => o.Id < AvgId);
var dynOrder1 = _query.Count("o => o.Id < @0", AvgId);
var dynOrder2 = _query.Count("o => o.Id < AvgId", new Dictionary<string, object> { { "AvgId", AvgId } });
var dynOrder3 = ((IQueryable)_query).Count();
Assert.Equal(order, dynOrder1);
Assert.Equal(order, dynOrder2);
Assert.Equal(_query.Count(), dynOrder3);
}
[Fact]
public void ShouldHandleDefaultIfEmpty() {
var query = new List<Order>().AsQueryable();
Assert.Equal(query.DefaultIfEmpty(), ((IQueryable)query).DefaultIfEmpty());
var order = new Order();
Assert.Equal(query.DefaultIfEmpty(order), ((IQueryable)query).DefaultIfEmpty(order));
}
[Fact]
public void ShouldHandleDistinct() {
var orders = new List<Order> {
new Order { Id = 1, Price = 1 },
new Order { Id = 2, Price = 1 },
new Order { Id = 3, Price = 2 }
};
orders.Add(orders[1]);
var dynDistinct = ((IQueryable)orders.AsQueryable()).Distinct().Cast<Order>();
Assert.Equal(orders.Distinct(), dynDistinct);
}
[Fact]
public void ShouldHandleElementAt() {
var order1 = _query.ElementAt(4);
var dynOrder1 = ((IQueryable)_query).ElementAt(4);
Assert.Equal(order1, dynOrder1);
Assert.Null(_query.ElementAtOrDefault(42));
}
[Fact]
public void ShouldHandleElementAtOrDefault() {
var order = _query.ElementAtOrDefault(4);
var dynOrder = ((IQueryable)_query).ElementAtOrDefault(4);
Assert.Equal(order, dynOrder);
Assert.Null(((IQueryable)_query).ElementAtOrDefault(42));
}
[Fact]
public void ShouldHandleExcept() {
var orders1 = _query.Take(4).AsQueryable();
var orders2 = _query.Take(2).ToList();
var except = orders1.Except(orders2).ToList();
var dynExcept = ((IQueryable)orders1).Except(orders2).Cast<Order>().ToList();
Assert.Equal(except, dynExcept);
}
[Fact]
public void ShouldHandleFirst() {
var order = _query.First(o => o.Id > AvgId);
var dynOrder1 = _query.First("o => o.Id > @0", AvgId);
var dynOrder2 = _query.First("o => o.Id > AvgId", new Dictionary<string, object> { { "AvgId", AvgId } });
var dynOrder3 = ((IQueryable)_query).First("Id > @0", AvgId);
var dynOrder4 = ((IQueryable)_query).First();
Assert.Equal(order, dynOrder1);
Assert.Equal(order, dynOrder2);
Assert.Equal(order, dynOrder3);
Assert.Equal(_query.First(), dynOrder4);
Assert.Throws<InvalidOperationException>(() => _query.Take(0).First("Id == 1"));
Assert.Throws<InvalidOperationException>(() => ((IQueryable)_query.Take(0)).First());
Assert.Throws<InvalidOperationException>(() => ((IQueryable)_query.Take(0)).First("Id == 1"));
Assert.Throws<ArgumentNullException>(() => Dyn.First(null, "Id > 1"));
}
[Fact]
public void ShouldHandleFirstOrDefault() {
var order = _query.FirstOrDefault(o => o.Id > AvgId);
var dynOrder1 = _query.FirstOrDefault("o => o.Id > AvgId", new Dictionary<string, object> { { "AvgId", AvgId } });
var dynOrder2 = ((IQueryable)_query).FirstOrDefault("Id > @0", AvgId);
var dynOrder3 = ((IQueryable)_query).FirstOrDefault();
Assert.Equal(order, dynOrder1);
Assert.Equal(order, dynOrder2);
Assert.Equal(_query.FirstOrDefault(), dynOrder3);
Assert.Null(_query.Take(0).FirstOrDefault("Id == 1"));
Assert.Null(((IQueryable)_query.Take(0)).FirstOrDefault());
Assert.Null(((IQueryable)_query.Take(0)).FirstOrDefault("Id == 1"));
}
[Fact]
public void ShouldHandleGroupBy() {
var lines = _query.SelectMany(o => o.Lines).ToList().AsQueryable();
var group1 = lines.GroupBy(l => l.OrderId, l => l.Id, (k, lid) => lid.Count()).ToList();
var dynGroup1 = lines.GroupBy("l => l.OrderId", "l => l.Id", "(k, lid) => lid.Count()").Cast<int>().ToList();
var group2 = lines.GroupBy(l => l.OrderId, (k, l) => l.Count()).ToList();
var dynGroup2 = lines.GroupBy("l => l.OrderId", "(k, l) => l.Count()").Cast<int>().ToList();
var group3 = lines.GroupBy(l => l.OrderId).ToList();
var dynGroup3 = lines.GroupBy("l => l.OrderId").Cast<IGrouping<int, OrderLine>>().ToList();
Assert.Equal(group1, dynGroup1);
Assert.Equal(group2, dynGroup2);
Assert.Equal(group3, dynGroup3);
Assert.Throws<ArgumentNullException>(() => Dyn.GroupBy(null, ""));
Assert.Throws<ArgumentNullException>(() => Dyn.GroupBy(_query, ""));
Assert.Throws<ArgumentNullException>(() => Dyn.GroupBy(null, "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.GroupBy(_query, "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.GroupBy(_query, "Id", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.GroupBy(null, "", "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.GroupBy(_query, "", "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.GroupBy(_query, "Id", "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.GroupBy(_query, "Id", "Id", ""));
}
[Fact]
public void ShouldHandleGroupJoin() {
var orders = _query.ToList().AsQueryable();
var lines = _query.SelectMany(o => o.Lines).ToList().AsQueryable();
var groupJoin = orders.GroupJoin(lines, o => o.Id, l => l.OrderId, (o, l) => o.Id + l.Max(x => x.Id)).ToList();
var dynGroupJoin = orders.GroupJoin(lines, "o => o.Id", "l => l.OrderId", "(o, l) => o.Id + l.Max(x => x.Id)").Cast<int>().ToList();
Assert.Equal(groupJoin, dynGroupJoin);
Assert.Throws<ArgumentNullException>(() => Dyn.GroupJoin(null, null, "", "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.GroupJoin(_query, null, "", "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.GroupJoin(_query, _query, "", "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.GroupJoin(_query, _query, "Id", "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.GroupJoin(_query, _query, "Id", "Id", ""));
}
[Fact]
public void ShouldHandleIntersect() {
var orders1 = _query.Take(4).AsQueryable();
var orders2 = _query.Take(2).ToList();
var intersect = orders1.Intersect(orders2).ToList();
var dynIntersect = ((IQueryable)orders1).Intersect(orders2).Cast<Order>().ToList();
Assert.Equal(intersect, dynIntersect);
}
[Fact]
public void ShouldHandleJoin() {
var orders = _query.ToList().AsQueryable();
var lines = _query.SelectMany(o => o.Lines).ToList().AsQueryable();
var join = orders.Join(lines, o => o.Id, l => l.OrderId, (o, l) => o.Id + l.Id).ToList();
var dynJoin = orders.Join(lines, "o => o.Id", "l => l.OrderId", "(o, l) => o.Id + l.Id").Cast<int>().ToList();
Assert.Equal(join, dynJoin);
Assert.Throws<ArgumentNullException>(() => Dyn.Join(null, null, "", "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Join(_query, null, "", "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Join(_query, _query, "", "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Join(_query, _query, "Id", "", ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Join(_query, _query, "Id", "Id", ""));
}
[Fact]
public void ShouldHandleLast() {
var order = _query.Last(o => o.Id < AvgId);
var dynOrder1 = _query.Last("o => o.Id < @0", AvgId);
var dynOrder2 = _query.Last("o => o.Id < AvgId", new Dictionary<string, object> { { "AvgId", AvgId } });
var dynOrder3 = ((IQueryable)_query).Last("Id < @0", AvgId);
var dynOrder4 = ((IQueryable)_query).Last();
Assert.Equal(order, dynOrder1);
Assert.Equal(order, dynOrder2);
Assert.Equal(order, dynOrder3);
Assert.Equal(_query.Last(), dynOrder4);
Assert.Throws<InvalidOperationException>(() => _query.Take(0).Last("Id == 1"));
Assert.Throws<InvalidOperationException>(() => ((IQueryable)_query.Take(0)).Last());
Assert.Throws<InvalidOperationException>(() => ((IQueryable)_query.Take(0)).Last("Id == 1"));
}
[Fact]
public void ShouldHandleLastOrDefault() {
var order = _query.LastOrDefault(o => o.Id < AvgId);
var dynOrder1 = _query.LastOrDefault("o => o.Id < AvgId", new Dictionary<string, object> { { "AvgId", AvgId } });
var dynOrder2 = ((IQueryable)_query).LastOrDefault("Id < @0", AvgId);
var dynOrder3 = ((IQueryable)_query).LastOrDefault();
Assert.Equal(order, dynOrder1);
Assert.Equal(order, dynOrder2);
Assert.Equal(_query.LastOrDefault(), dynOrder3);
Assert.Null(_query.Take(0).LastOrDefault("Id == 1"));
Assert.Null(((IQueryable)_query.Take(0)).LastOrDefault());
Assert.Null(((IQueryable)_query.Take(0).LastOrDefault("Id == 1")));
}
[Fact]
public void ShouldHandleLongCount() {
var order = _query.LongCount(o => o.Id < AvgId);
var dynOrder1 = _query.LongCount("o => o.Id < @0", AvgId);
var dynOrder2 = _query.LongCount("o => o.Id < AvgId", new Dictionary<string, object> { { "AvgId", AvgId } });
var dynOrder3 = ((IQueryable)_query).LongCount();
Assert.Equal(order, dynOrder1);
Assert.Equal(order, dynOrder2);
Assert.Equal(_query.LongCount(), dynOrder3);
}
[Fact]
public void ShouldHandleMax() {
var avg = _query.Max(o => o.Price);
var dynAvg = _query.Max("o => o.Price");
Assert.Equal(avg, dynAvg);
}
[Fact]
public void ShouldHandleMin() {
var avg = _query.Min(o => o.Price);
var dynAvg = _query.Min("o => o.Price");
Assert.Equal(avg, dynAvg);
}
[Fact]
public void ShouldHandleOrderBy() {
var order = _query.OrderBy(o => o.Id).First();
var dynOrder1 = _query.OrderBy("o => o.Id").First();
var dynOrder2 = ((IQueryable)_query).OrderBy("o => o.Id").Cast<object>().First();
Assert.Equal(order, dynOrder1);
Assert.Equal(order, dynOrder2);
}
[Fact]
public void ShouldHandleOrderByDescending() {
var order = _query.OrderByDescending(o => o.Id).First();
var dynOrder1 = _query.OrderByDescending("o => o.Id").First();
var dynOrder2 = ((IQueryable)_query).OrderByDescending("o => o.Id").Cast<object>().First();
Assert.Equal(order, dynOrder1);
Assert.Equal(order, dynOrder2);
}
[Fact]
public void ShouldHandleReverse() {
Assert.Equal(_query.Reverse(), ((IQueryable)_query).Reverse());
}
[Fact]
public void ShouldHandleSelect() {
var order = _query.Select(o => new { Id = o.Id, OrderDate = o.OrderDate }).First();
var dynOrder = _query.Select("o => new { Id = o.Id, OrderDate = o.OrderDate }").Cast<dynamic>().First();
Assert.Equal(order.OrderDate, dynOrder.OrderDate);
}
[Fact]
public void ShouldHandleSelectMany() {
var lines = _query.SelectMany(o => o.Lines).ToList();
var dynLines = _query.SelectMany("o => o.Lines").Cast<OrderLine>().ToList();
Assert.Equal(lines, dynLines);
Assert.Throws<ArgumentNullException>(() => Dyn.SelectMany(null, ""));
Assert.Throws<ArgumentNullException>(() => Dyn.SelectMany(_query, ""));
}
[Fact]
public void ShouldHandleSequenceEqual() {
var orders = _query.Skip(4).Take(2).ToList();
Assert.True(((IQueryable)_query.Skip(4).Take(2)).SequenceEqual(orders));
}
[Fact]
public void ShouldHandleSingle() {
var orders = new List<Order> {
new Order { Id = 1, Price = 1 },
new Order { Id = 2, Price = 1 },
new Order { Id = 3, Price = 2 }
};
var query = orders.AsQueryable();
var dynOrder1 = query.Single("o => o.Id > @0", 2);
var dynOrder2 = ((IQueryable)query).Single("Id > SearchId", new Dictionary<string, object> { { "SearchId", 2 } });
var dynOrder3 = ((IQueryable)query.Take(1)).Single();
Assert.Equal(orders[2], dynOrder1);
Assert.Equal(dynOrder1, dynOrder2);
Assert.Equal(orders[0], dynOrder3);
Assert.Throws<InvalidOperationException>(() => query.Single("o => o.Id > 1"));
Assert.Throws<InvalidOperationException>(() => query.Single("o => o.Id > 3"));
Assert.Throws<InvalidOperationException>(() => ((IQueryable)query.Take(0)).Single());
Assert.Throws<InvalidOperationException>(() => ((IQueryable)query).Single("o => o.Id > 1"));
Assert.Throws<InvalidOperationException>(() => ((IQueryable)query).Single("o => o.Id > 3"));
}
[Fact]
public void ShouldHandleSingleOrDefault() {
var orders = new List<Order> {
new Order { Id = 1, Price = 1 },
new Order { Id = 2, Price = 1 },
new Order { Id = 3, Price = 2 }
};
var query = orders.AsQueryable();
var dynOrder1 = query.SingleOrDefault("o => o.Id > @0", 2);
var dynOrder2 = ((IQueryable)query).SingleOrDefault("Id > SearchId", new Dictionary<string, object> { { "SearchId", 2 } });
var dynOrder3 = ((IQueryable)query.Take(1)).SingleOrDefault();
Assert.Equal(orders[2], dynOrder1);
Assert.Equal(dynOrder1, dynOrder2);
Assert.Equal(orders[0], dynOrder3);
Assert.Null(query.SingleOrDefault("o => o.Id > 3"));
Assert.Null(((IQueryable)query.Take(0)).SingleOrDefault());
Assert.Null(((IQueryable)query).SingleOrDefault("o => o.Id > 3"));
Assert.Throws<InvalidOperationException>(() => query.SingleOrDefault("o => o.Id > 1"));
Assert.Throws<InvalidOperationException>(() => ((IQueryable)query).SingleOrDefault());
Assert.Throws<InvalidOperationException>(() => ((IQueryable)query).SingleOrDefault("o => o.Id > 1"));
}
[Fact]
public void ShouldHandleSkip() {
var orders = _query.Skip(3);
var dynOrders = ((IQueryable)_query).Skip(3);
Assert.Equal(orders, dynOrders);
}
[Fact]
public void ShouldHandleSkipWhile() {
var orders = _query.SkipWhile(o => o.Id > AvgId).ToList();
var dynOrders1 = _query.SkipWhile("o => o.Id > @0", AvgId).ToList();
var dynOrders2 = _query.SkipWhile("o => o.Id > AvgId", new Dictionary<string, object> { { "AvgId", AvgId } }).ToList();
var dynOrders3 = ((IQueryable)_query).SkipWhile("Id > @0", AvgId).Cast<Order>().ToList();
Assert.Equal(orders, dynOrders1);
Assert.Equal(orders, dynOrders2);
}
[Fact]
public void ShouldHandleSum() {
var avg = _query.Sum(o => o.Price);
var dynAvg = _query.Sum("o => o.Price");
Assert.Equal(avg, dynAvg);
}
[Fact]
public void ShouldHandleTake() {
var orders = _query.Take(3);
var dynOrders = ((IQueryable)_query).Take(3);
Assert.Equal(orders, dynOrders);
Assert.Throws<ArgumentNullException>(() => Dyn.Take(null, 1));
}
[Fact]
public void ShouldHandleTakeWhile() {
var orders = _query.TakeWhile(o => o.Id < AvgId).ToList();
var dynOrders1 = _query.TakeWhile("o => o.Id < @0", AvgId).ToList();
var dynOrders2 = _query.TakeWhile("o => o.Id < AvgId", new Dictionary<string, object> { { "AvgId", AvgId } }).ToList();
var dynOrders3 = ((IQueryable)_query).TakeWhile("Id < @0", AvgId).Cast<Order>().ToList();
Assert.Equal(orders, dynOrders1);
Assert.Equal(orders, dynOrders1);
Assert.Equal(orders, dynOrders3);
}
[Fact]
public void ShouldHandleThenBy() {
var order = _query.OrderBy(o => o.Id).ThenBy(o => o.Price).First();
var dynOrder1 = _query.OrderBy(o => o.Id).ThenBy("o => o.Price").First();
var dynOrder2 = ((IQueryable)_query.OrderBy(o => o.Id)).ThenBy("o => o.Price").Cast<object>().First();
Assert.Equal(order, dynOrder1);
Assert.Equal(order, dynOrder2);
}
[Fact]
public void ShouldHandleThenByDescending() {
var order = _query.OrderBy(o => o.Id).ThenByDescending(o => o.Price).First();
var dynOrder1 = _query.OrderBy(o => o.Id).ThenByDescending("o => o.Price").First();
var dynOrder2 = ((IQueryable)_query.OrderBy(o => o.Id)).ThenByDescending("o => o.Price").Cast<object>().First();
Assert.Equal(order, dynOrder1);
Assert.Equal(order, dynOrder2);
}
[Fact]
public void ShouldHandleUnion() {
var orders1 = _query.Skip(1).Take(4).AsQueryable();
var orders2 = _query.Take(2).ToList();
var union = orders1.Union(orders2).ToList();
var dynUnion = ((IQueryable)orders1).Union(orders2).Cast<Order>().ToList();
Assert.Equal(union, dynUnion);
}
[Fact]
public void ShouldHandleWhere() {
var orders = _query.Where(o => o.Id > AvgId).ToList();
var dynOrders1 = _query.Where("o => o.Id > @0", AvgId).ToList();
var dynOrders2 = _query.Where("o => o.Id > AvgId", new Dictionary<string, object> { { "AvgId", AvgId } }).ToList();
var dynOrders3 = ((IQueryable)_query).Where("Id > @0", AvgId).Cast<Order>().ToList();
Assert.Equal(orders, dynOrders1);
Assert.Equal(orders, dynOrders2);
Assert.Equal(orders, dynOrders3);
Assert.Throws<ArgumentNullException>(() => Dyn.Where(_query, ""));
}
[Fact]
public void ShouldHandleZip() {
var lineCounts = _query.Select(o => o.Lines.Count).ToList();
var zip = _query.Zip(lineCounts, (o, l) => o.Id + l).ToList();
var dynZip = _query.Zip(lineCounts, "(o, l) => o.Id + l").Cast<int>().ToList();
Assert.Equal(zip, dynZip);
Assert.Throws<ArgumentNullException>(() => Dyn.Zip<int>(null, (IEnumerable<int>)null, ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Zip<int>(_query, (IEnumerable<int>)null, ""));
Assert.Throws<ArgumentNullException>(() => Dyn.Zip<int>(_query, Enumerable.Empty<int>(), ""));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using NMock;
using NUnit.Framework;
namespace OpenQA.Selenium.Support.PageObjects
{
[TestFixture]
public class PageFactoryTest
{
#if !NETCOREAPP2_0
private MockFactory mocks;
private Mock<ISearchContext> mockDriver;
private Mock<IWebElement> mockElement;
private Mock<IWebDriver> mockExplicitDriver;
[SetUp]
public void SetUp()
{
mocks = new MockFactory();
mockDriver = mocks.CreateMock<ISearchContext>();
mockElement = mocks.CreateMock<IWebElement>();
mockExplicitDriver = mocks.CreateMock<IWebDriver>();
}
[TearDown]
public void TearDown()
{
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void ElementShouldBeNullUntilInitElementsCalled()
{
var page = new Page();
Assert.Null(page.formElement);
PageFactory.InitElements(mockDriver.MockObject, page);
Assert.NotNull(page.formElement);
}
[Test]
public void ElementShouldBeAbleToUseGenericVersionOfInitElements()
{
Mock<IWebDriver> driver = mocks.CreateMock<IWebDriver>();
var page = PageFactory.InitElements<GenericFactoryPage>(driver.MockObject);
Assert.IsInstanceOf<GenericFactoryPage>(page);
Assert.NotNull(page.formElement);
}
[Test]
public void FindsElement()
{
var page = new Page();
AssertFindsElementByExactlyOneLookup(page, () => page.formElement);
}
[Test]
public void FindsElementEachAccess()
{
var page = new Page();
AssertFindsElementByExactlyOneLookup(page, () => page.formElement);
mocks.VerifyAllExpectationsHaveBeenMet();
ExpectOneLookup();
AssertFoundElement(page.formElement);
}
[Test]
public void FindsPrivateElement()
{
var page = new PrivatePage();
AssertFindsElementByExactlyOneLookup(page, page.GetField);
}
[Test]
public void FindsPropertyElement()
{
var page = new ElementAsPropertyPage();
AssertFindsElementByExactlyOneLookup(page, () => page.FormElement);
}
[Test]
public void FindsElementByNameIfUsingIsAbsent()
{
ExpectOneLookup();
var page = new PageWithNameWithoutUsing();
AssertFindsElement(page, () => page.someForm);
}
[Test]
public void FindsElementByIdIfUsingIsAbsent()
{
mockElement.Expects.One.GetProperty(_ => _.TagName).WillReturn("form");
mockDriver.Expects.One.Method(_ => _.FindElement(null)).With(By.Id("someForm")).WillReturn(mockElement.MockObject);
var page = new PageWithIdWithoutUsing();
AssertFindsElement(page, () => page.someForm);
}
[Test]
public void FindsParentAndChildElement()
{
ExpectOneLookup();
var mockElement2 = mocks.CreateMock<IWebElement>();
mockDriver.Expects.One.Method(_ => _.FindElement(null)).With(By.TagName("body")).WillReturn(mockElement2.MockObject);
mockElement2.Expects.One.GetProperty(_ => _.TagName).WillReturn("body");
var page = new ChildPage();
AssertFindsElement(page, () => page.formElement);
AssertFoundElement(page.childElement, "body");
}
[Test]
public void LooksUpPrivateFieldInSuperClass()
{
var page = new SubClassToPrivatePage();
AssertFindsElementByExactlyOneLookup(page, page.GetField);
}
[Test]
public void LooksUpOverridenVirtualParentClassElement()
{
ExpectOneLookup();
var page = new AbstractChild();
AssertFindsElement(page, () => page.element);
}
[Test]
public void FallsBackOnOtherLocatorsOnFailure()
{
mockDriver.Expects.One.Method(_ => _.FindElement(null)).With(By.Name("notthisname")).Will(Throw.Exception(new NoSuchElementException()));
mockDriver.Expects.One.Method(_ => _.FindElement(null)).With(By.TagName("form")).WillReturn(mockElement.MockObject);
mockDriver.Expects.No.Method(_ => _.FindElement(null)).With(By.Id("notthiseither")).WillReturn(mockElement.MockObject);
mockElement.Expects.One.GetProperty(_ => _.TagName).WillReturn("form");
var page = new FallsbackPage();
PageFactory.InitElements(mockDriver.MockObject, page);
AssertFoundElement(page.formElement);
}
[Test]
public void ThrowsIfAllLocatorsFail()
{
mockDriver.Expects.One.Method(_ => _.FindElement(null)).With(By.Name("notthisname")).Will(Throw.Exception(new NoSuchElementException()));
mockDriver.Expects.One.Method(_ => _.FindElement(null)).With(By.TagName("notthiseither")).Will(Throw.Exception(new NoSuchElementException()));
mockDriver.Expects.One.Method(_ => _.FindElement(null)).With(By.Id("stillnotthis")).Will(Throw.Exception(new NoSuchElementException()));
var page = new FailsToFallbackPage();
PageFactory.InitElements(mockDriver.MockObject, page);
Assert.Throws(typeof(NoSuchElementException), page.formElement.Clear);
}
[Test]
public void CachesElement()
{
mockDriver.Expects.One.Method(_ => _.FindElement(null)).With(By.Name("someForm")).WillReturn(mockElement.MockObject);
mockElement.Expects.Exactly(2).GetProperty(_ => _.TagName).WillReturn("form");
var page = new CachedPage();
AssertFindsElement(page, () => page.formElement);
AssertFoundElement(page.formElement);
}
[Test]
public void CachesIfClassMarkedCachedElement()
{
mockDriver.Expects.One.Method(_ => _.FindElement(null)).With(By.Name("someForm")).WillReturn(mockElement.MockObject);
mockElement.Expects.Exactly(2).GetProperty(_ => _.TagName).WillReturn("form");
var page = new CachedClassPage();
AssertFindsElement(page, () => page.formElement);
AssertFoundElement(page.formElement);
}
[Test]
public void UsingCustomBy()
{
mockDriver.Expects.Exactly(1).Method(_ => _.FindElement(null)).With(new CustomBy("customCriteria")).WillReturn(mockElement.MockObject);
mockElement.Expects.Exactly(1).GetProperty(_ => _.TagName).WillReturn("form");
var page = new CustomByPage();
AssertFindsElement(page, () => page.customFoundElement);
}
[Test]
public void UsingCustomByNotFound()
{
mockDriver.Expects.One.Method(_ => _.FindElement(null)).With(new CustomBy("customCriteriaNotFound")).Will(Throw.Exception(new NoSuchElementException()));
var page = new CustomByNotFoundPage();
PageFactory.InitElements(mockDriver.MockObject, page);
Assert.Throws<NoSuchElementException>(page.customFoundElement.Clear);
}
[Test]
public void UsingCustomByWithInvalidSuperClass()
{
var page = new InvalidCustomFinderTypePage();
Assert.Throws<ArgumentException>(() => PageFactory.InitElements(mockDriver.MockObject, page), "descendent of");
}
[Test]
public void UsingCustomByWithNoClass()
{
var page = new NoCustomFinderClassPage();
Assert.Throws<ArgumentException>(() => PageFactory.InitElements(mockDriver.MockObject, page), "How.Custom");
}
[Test]
public void UsingCustomByWithInvalidCtor()
{
var page = new InvalidCtorCustomByPage();
Assert.Throws<ArgumentException>(() => PageFactory.InitElements(mockDriver.MockObject, page), "constructor");
}
[Test]
public void ThrowsIfElementTypeIsInvalid()
{
var page = new InvalidElementTypePage();
Assert.Throws<ArgumentException>(() => PageFactory.InitElements(mockDriver.MockObject, page), "is not IWebElement or IList<IWebElement>");
}
[Test]
public void ThrowsIfElementCollectionTypeIsInvalid()
{
var page = new InvalidCollectionTypePage();
Assert.Throws<ArgumentException>(() => PageFactory.InitElements(mockDriver.MockObject, page), "is not IWebElement or IList<IWebElement>");
}
[Test]
public void ThrowsIfConcreteCollectionTypeIsUsed()
{
var page = new ConcreteCollectionTypePage();
Assert.Throws<ArgumentException>(() => PageFactory.InitElements(mockDriver.MockObject, page), "is not IWebElement or IList<IWebElement>");
}
[Test]
public void CanUseGenericInitElementsWithWebDriverConstructor()
{
WebDriverConstructorPage page = PageFactory.InitElements<WebDriverConstructorPage>(mockExplicitDriver.MockObject);
}
[Test]
public void CanNotUseGenericInitElementWithInvalidConstructor()
{
Assert.Throws<ArgumentException>(() => { InvalidConstructorPage page = PageFactory.InitElements<InvalidConstructorPage>(mockExplicitDriver.MockObject); }, "constructor for the specified class containing a single argument of type IWebDriver");
}
[Test]
public void CanNotUseGenericInitElementWithParameterlessConstructor()
{
Assert.Throws<ArgumentException>(() => { ParameterlessConstructorPage page = PageFactory.InitElements<ParameterlessConstructorPage>(mockExplicitDriver.MockObject); }, "constructor for the specified class containing a single argument of type IWebDriver");
}
#region Test helper methods
private void ExpectOneLookup()
{
mockDriver.Expects.Exactly(1).Method(_ => _.FindElement(null)).With(By.Name("someForm")).WillReturn(mockElement.MockObject);
mockElement.Expects.Exactly(1).GetProperty(_ => _.TagName).WillReturn("form");
}
/// <summary>
/// Asserts that getElement yields an element from page which can be interacted with, by exactly one element lookup
/// </summary>
private void AssertFindsElementByExactlyOneLookup(object page, Func<IWebElement> getElement)
{
ExpectOneLookup();
AssertFindsElement(page, getElement);
}
/// <summary>
/// Asserts that getElement yields an element which can be interacted with, with no constraints on element lookups
/// </summary>
private void AssertFindsElement(object page, Func<IWebElement> getElement)
{
PageFactory.InitElements(mockDriver.MockObject, page);
AssertFoundElement(getElement());
}
/// <summary>
/// Asserts that the element has been found and can be interacted with
/// </summary>
private static void AssertFoundElement(IWebElement element)
{
AssertFoundElement(element, "form");
}
/// <summary>
/// Asserts that the element has been found and has the tagName passed
/// </summary>
private static void AssertFoundElement(IWebElement element, string tagName)
{
Assert.AreEqual(tagName, element.TagName.ToLower());
}
#endregion
#region Page classes for tests
#pragma warning disable 649 //We set fields through reflection, so expect an always-null warning
internal class WebDriverConstructorPage
{
[FindsBy(How = How.Name, Using = "someForm")]
public IWebElement formElement;
public WebDriverConstructorPage(IWebDriver driver)
{
}
}
internal class ParameterlessConstructorPage
{
[FindsBy(How = How.Name, Using = "someForm")]
public IWebElement formElement;
public ParameterlessConstructorPage()
{
}
}
internal class InvalidConstructorPage
{
[FindsBy(How = How.Name, Using = "someForm")]
public IWebElement formElement;
public InvalidConstructorPage(string message)
{
}
}
internal class Page
{
[FindsBy(How = How.Name, Using = "someForm")]
public IWebElement formElement;
}
internal class PageWithNameWithoutUsing
{
[FindsBy(How = How.Name)]
public IWebElement someForm;
}
internal class PageWithIdWithoutUsing
{
[FindsBy(How = How.Id)]
public IWebElement someForm;
}
private class PrivatePage
{
[FindsBy(How = How.Name, Using = "someForm")]
private IWebElement formElement;
public IWebElement GetField()
{
return formElement;
}
}
private class ChildPage : Page
{
[FindsBy(How = How.TagName, Using = "body")]
public IWebElement childElement;
}
private class SubClassToPrivatePage : PrivatePage
{
}
private class AbstractParent
{
[FindsBy(How = How.Name, Using = "someForm")]
public virtual IWebElement element { get; set; }
}
private class AbstractChild : AbstractParent
{
public override IWebElement element { get; set; }
}
private class FallsbackPage
{
[FindsBy(How = How.Name, Using = "notthisname", Priority = 0)]
[FindsBy(How = How.TagName, Using = "form", Priority = 1)]
[FindsBy(How = How.Id, Using = "notthiseither", Priority = 2)]
public IWebElement formElement;
}
private class FailsToFallbackPage
{
[FindsBy(How = How.Name, Using = "notthisname", Priority = 0)]
[FindsBy(How = How.TagName, Using = "notthiseither", Priority = 1)]
[FindsBy(How = How.Id, Using = "stillnotthis", Priority = 2)]
public IWebElement formElement;
}
private class ElementAsPropertyPage
{
[FindsBy(How = How.Name, Using = "someForm")]
public IWebElement FormElement { get; set; }
}
private class CachedPage
{
[FindsBy(How = How.Name, Using = "someForm")]
[CacheLookup]
public IWebElement formElement;
}
[CacheLookup]
private class CachedClassPage
{
[FindsBy(How = How.Name, Using = "someForm")]
public IWebElement formElement;
}
private class CustomBy : By
{
MockFactory mocks = new MockFactory();
private string criteria;
public CustomBy(string customByString)
{
criteria = customByString;
this.FindElementMethod = (context) =>
{
if (this.criteria != "customCriteria")
{
throw new NoSuchElementException();
}
Mock<IWebElement> mockElement = mocks.CreateMock<IWebElement>();
return mockElement.MockObject;
};
}
}
private class CustomByNoCtor : By
{
MockFactory mocks = new MockFactory();
private string criteria;
public CustomByNoCtor()
{
criteria = "customCriteria";
this.FindElementMethod = (context) =>
{
if (this.criteria != "customCriteria")
{
throw new NoSuchElementException();
}
Mock<IWebElement> mockElement = mocks.CreateMock<IWebElement>();
return mockElement.MockObject;
};
}
}
private class CustomByPage
{
[FindsBy(How = How.Custom, Using = "customCriteria", CustomFinderType = typeof(CustomBy))]
public IWebElement customFoundElement;
}
private class CustomByNotFoundPage
{
[FindsBy(How = How.Custom, Using = "customCriteriaNotFound", CustomFinderType = typeof(CustomBy))]
public IWebElement customFoundElement;
}
private class NoCustomFinderClassPage
{
[FindsBy(How = How.Custom, Using = "custom")]
public IWebElement customFoundElement;
}
private class InvalidCustomFinderTypePage
{
[FindsBy(How = How.Custom, Using = "custom", CustomFinderType = typeof(string))]
public IWebElement customFoundElement;
}
private class InvalidCtorCustomByPage
{
[FindsBy(How = How.Custom, Using = "custom", CustomFinderType = typeof(CustomByNoCtor))]
public IWebElement customFoundElement;
}
private class GenericFactoryPage
{
private IWebDriver driver;
public GenericFactoryPage(IWebDriver driver)
{
this.driver = driver;
}
[FindsBy(How = How.Name, Using = "someForm")]
public IWebElement formElement;
}
private class InvalidElementTypePage
{
[FindsBy(How = How.Name, Using = "someForm")]
public string myElement;
}
private class InvalidCollectionTypePage
{
[FindsBy(How = How.Name, Using = "someForm")]
public List<string> myElement;
}
private class ConcreteCollectionTypePage
{
[FindsBy(How = How.Name, Using = "someForm")]
public ReadOnlyCollection<IWebElement> myElement;
}
#pragma warning restore 649
#endregion
#endif
}
}
| |
using System;
using System.Collections.Generic;
using Avalonia.Platform;
using Avalonia.Rendering.SceneGraph;
using Avalonia.Threading;
using Avalonia.Utilities;
using Avalonia.Visuals.Media.Imaging;
namespace Avalonia.Media
{
public sealed class DrawingContext : IDisposable
{
private readonly bool _ownsImpl;
private int _currentLevel;
private static ThreadSafeObjectPool<Stack<PushedState>> StateStackPool { get; } =
ThreadSafeObjectPool<Stack<PushedState>>.Default;
private static ThreadSafeObjectPool<Stack<TransformContainer>> TransformStackPool { get; } =
ThreadSafeObjectPool<Stack<TransformContainer>>.Default;
private Stack<PushedState>? _states = StateStackPool.Get();
private Stack<TransformContainer>? _transformContainers = TransformStackPool.Get();
readonly struct TransformContainer
{
public readonly Matrix LocalTransform;
public readonly Matrix ContainerTransform;
public TransformContainer(Matrix localTransform, Matrix containerTransform)
{
LocalTransform = localTransform;
ContainerTransform = containerTransform;
}
}
public DrawingContext(IDrawingContextImpl impl)
{
PlatformImpl = impl;
_ownsImpl = true;
}
public DrawingContext(IDrawingContextImpl impl, bool ownsImpl)
{
_ownsImpl = ownsImpl;
PlatformImpl = impl;
}
public IDrawingContextImpl PlatformImpl { get; }
private Matrix _currentTransform = Matrix.Identity;
private Matrix _currentContainerTransform = Matrix.Identity;
/// <summary>
/// Gets the current transform of the drawing context.
/// </summary>
public Matrix CurrentTransform
{
get { return _currentTransform; }
private set
{
_currentTransform = value;
var transform = _currentTransform * _currentContainerTransform;
PlatformImpl.Transform = transform;
}
}
//HACK: This is a temporary hack that is used in the render loop
//to update TransformedBounds property
[Obsolete("HACK for render loop, don't use")]
public Matrix CurrentContainerTransform => _currentContainerTransform;
/// <summary>
/// Draws an image.
/// </summary>
/// <param name="source">The image.</param>
/// <param name="rect">The rect in the output to draw to.</param>
public void DrawImage(IImage source, Rect rect)
{
_ = source ?? throw new ArgumentNullException(nameof(source));
DrawImage(source, new Rect(source.Size), rect);
}
/// <summary>
/// Draws an image.
/// </summary>
/// <param name="source">The image.</param>
/// <param name="sourceRect">The rect in the image to draw.</param>
/// <param name="destRect">The rect in the output to draw to.</param>
/// <param name="bitmapInterpolationMode">The bitmap interpolation mode.</param>
public void DrawImage(IImage source, Rect sourceRect, Rect destRect, BitmapInterpolationMode bitmapInterpolationMode = default)
{
_ = source ?? throw new ArgumentNullException(nameof(source));
source.Draw(this, sourceRect, destRect, bitmapInterpolationMode);
}
/// <summary>
/// Draws a line.
/// </summary>
/// <param name="pen">The stroke pen.</param>
/// <param name="p1">The first point of the line.</param>
/// <param name="p2">The second point of the line.</param>
public void DrawLine(IPen pen, Point p1, Point p2)
{
if (PenIsVisible(pen))
{
PlatformImpl.DrawLine(pen, p1, p2);
}
}
/// <summary>
/// Draws a geometry.
/// </summary>
/// <param name="brush">The fill brush.</param>
/// <param name="pen">The stroke pen.</param>
/// <param name="geometry">The geometry.</param>
public void DrawGeometry(IBrush? brush, IPen? pen, Geometry geometry)
{
if (geometry.PlatformImpl is not null)
DrawGeometry(brush, pen, geometry.PlatformImpl);
}
/// <summary>
/// Draws a geometry.
/// </summary>
/// <param name="brush">The fill brush.</param>
/// <param name="pen">The stroke pen.</param>
/// <param name="geometry">The geometry.</param>
public void DrawGeometry(IBrush? brush, IPen? pen, IGeometryImpl geometry)
{
_ = geometry ?? throw new ArgumentNullException(nameof(geometry));
if (brush != null || PenIsVisible(pen))
{
PlatformImpl.DrawGeometry(brush, pen, geometry);
}
}
/// <summary>
/// Draws a rectangle with the specified Brush and Pen.
/// </summary>
/// <param name="brush">The brush used to fill the rectangle, or <c>null</c> for no fill.</param>
/// <param name="pen">The pen used to stroke the rectangle, or <c>null</c> for no stroke.</param>
/// <param name="rect">The rectangle bounds.</param>
/// <param name="radiusX">The radius in the X dimension of the rounded corners.
/// This value will be clamped to the range of 0 to Width/2
/// </param>
/// <param name="radiusY">The radius in the Y dimension of the rounded corners.
/// This value will be clamped to the range of 0 to Height/2
/// </param>
/// <param name="boxShadows">Box shadow effect parameters</param>
/// <remarks>
/// The brush and the pen can both be null. If the brush is null, then no fill is performed.
/// If the pen is null, then no stoke is performed. If both the pen and the brush are null, then the drawing is not visible.
/// </remarks>
public void DrawRectangle(IBrush? brush, IPen? pen, Rect rect, double radiusX = 0, double radiusY = 0,
BoxShadows boxShadows = default)
{
if (brush == null && !PenIsVisible(pen))
{
return;
}
if (!MathUtilities.IsZero(radiusX))
{
radiusX = Math.Min(radiusX, rect.Width / 2);
}
if (!MathUtilities.IsZero(radiusY))
{
radiusY = Math.Min(radiusY, rect.Height / 2);
}
PlatformImpl.DrawRectangle(brush, pen, new RoundedRect(rect, radiusX, radiusY), boxShadows);
}
/// <summary>
/// Draws the outline of a rectangle.
/// </summary>
/// <param name="pen">The pen.</param>
/// <param name="rect">The rectangle bounds.</param>
/// <param name="cornerRadius">The corner radius.</param>
public void DrawRectangle(IPen pen, Rect rect, float cornerRadius = 0.0f)
{
DrawRectangle(null, pen, rect, cornerRadius, cornerRadius);
}
/// <summary>
/// Draws an ellipse with the specified Brush and Pen.
/// </summary>
/// <param name="brush">The brush used to fill the ellipse, or <c>null</c> for no fill.</param>
/// <param name="pen">The pen used to stroke the ellipse, or <c>null</c> for no stroke.</param>
/// <param name="center">The location of the center of the ellipse.</param>
/// <param name="radiusX">The horizontal radius of the ellipse.</param>
/// <param name="radiusY">The vertical radius of the ellipse.</param>
/// <remarks>
/// The brush and the pen can both be null. If the brush is null, then no fill is performed.
/// If the pen is null, then no stoke is performed. If both the pen and the brush are null, then the drawing is not visible.
/// </remarks>
public void DrawEllipse(IBrush? brush, IPen? pen, Point center, double radiusX, double radiusY)
{
if (brush == null && !PenIsVisible(pen))
{
return;
}
var originX = center.X - radiusX;
var originY = center.Y - radiusY;
var width = radiusX * 2;
var height = radiusY * 2;
PlatformImpl.DrawEllipse(brush, pen, new Rect(originX, originY, width, height));
}
/// <summary>
/// Draws a custom drawing operation
/// </summary>
/// <param name="custom">custom operation</param>
public void Custom(ICustomDrawOperation custom) => PlatformImpl.Custom(custom);
/// <summary>
/// Draws text.
/// </summary>
/// <param name="origin">The upper-left corner of the text.</param>
/// <param name="text">The text.</param>
public void DrawText(FormattedText text, Point origin)
{
_ = text ?? throw new ArgumentNullException(nameof(text));
text.Draw(this, origin);
}
/// <summary>
/// Draws a glyph run.
/// </summary>
/// <param name="foreground">The foreground brush.</param>
/// <param name="glyphRun">The glyph run.</param>
public void DrawGlyphRun(IBrush foreground, GlyphRun glyphRun)
{
_ = glyphRun ?? throw new ArgumentNullException(nameof(glyphRun));
if (foreground != null)
{
PlatformImpl.DrawGlyphRun(foreground, glyphRun);
}
}
/// <summary>
/// Draws a filled rectangle.
/// </summary>
/// <param name="brush">The brush.</param>
/// <param name="rect">The rectangle bounds.</param>
/// <param name="cornerRadius">The corner radius.</param>
public void FillRectangle(IBrush brush, Rect rect, float cornerRadius = 0.0f)
{
DrawRectangle(brush, null, rect, cornerRadius, cornerRadius);
}
public readonly struct PushedState : IDisposable
{
private readonly int _level;
private readonly DrawingContext _context;
private readonly Matrix _matrix;
private readonly PushedStateType _type;
public enum PushedStateType
{
None,
Matrix,
Opacity,
Clip,
MatrixContainer,
GeometryClip,
OpacityMask,
}
public PushedState(DrawingContext context, PushedStateType type, Matrix matrix = default(Matrix))
{
if (context._states is null)
throw new ObjectDisposedException(nameof(DrawingContext));
_context = context;
_type = type;
_matrix = matrix;
_level = context._currentLevel += 1;
context._states.Push(this);
}
public void Dispose()
{
if (_type == PushedStateType.None)
return;
if (_context._states is null || _context._transformContainers is null)
throw new ObjectDisposedException(nameof(DrawingContext));
if (_context._currentLevel != _level)
throw new InvalidOperationException("Wrong Push/Pop state order");
_context._currentLevel--;
_context._states.Pop();
if (_type == PushedStateType.Matrix)
_context.CurrentTransform = _matrix;
else if (_type == PushedStateType.Clip)
_context.PlatformImpl.PopClip();
else if (_type == PushedStateType.Opacity)
_context.PlatformImpl.PopOpacity();
else if (_type == PushedStateType.GeometryClip)
_context.PlatformImpl.PopGeometryClip();
else if (_type == PushedStateType.OpacityMask)
_context.PlatformImpl.PopOpacityMask();
else if (_type == PushedStateType.MatrixContainer)
{
var cont = _context._transformContainers.Pop();
_context._currentContainerTransform = cont.ContainerTransform;
_context.CurrentTransform = cont.LocalTransform;
}
}
}
public PushedState PushClip(RoundedRect clip)
{
PlatformImpl.PushClip(clip);
return new PushedState(this, PushedState.PushedStateType.Clip);
}
/// <summary>
/// Pushes a clip rectangle.
/// </summary>
/// <param name="clip">The clip rectangle.</param>
/// <returns>A disposable used to undo the clip rectangle.</returns>
public PushedState PushClip(Rect clip)
{
PlatformImpl.PushClip(clip);
return new PushedState(this, PushedState.PushedStateType.Clip);
}
/// <summary>
/// Pushes a clip geometry.
/// </summary>
/// <param name="clip">The clip geometry.</param>
/// <returns>A disposable used to undo the clip geometry.</returns>
public PushedState PushGeometryClip(Geometry clip)
{
_ = clip ?? throw new ArgumentNullException(nameof(clip));
// HACK: This check was added when nullable annotations pointed out that we're potentially
// pushing a null value for the clip here. Ideally we'd return an empty PushedState here but
// I don't want to make that change as part of adding nullable annotations.
if (clip.PlatformImpl is null)
throw new InvalidOperationException("Cannot push empty geometry clip.");
PlatformImpl.PushGeometryClip(clip.PlatformImpl);
return new PushedState(this, PushedState.PushedStateType.GeometryClip);
}
/// <summary>
/// Pushes an opacity value.
/// </summary>
/// <param name="opacity">The opacity.</param>
/// <returns>A disposable used to undo the opacity.</returns>
public PushedState PushOpacity(double opacity)
//TODO: Eliminate platform-specific push opacity call
{
PlatformImpl.PushOpacity(opacity);
return new PushedState(this, PushedState.PushedStateType.Opacity);
}
/// <summary>
/// Pushes an opacity mask.
/// </summary>
/// <param name="mask">The opacity mask.</param>
/// <param name="bounds">
/// The size of the brush's target area. TODO: Are we sure this is needed?
/// </param>
/// <returns>A disposable to undo the opacity mask.</returns>
public PushedState PushOpacityMask(IBrush mask, Rect bounds)
{
PlatformImpl.PushOpacityMask(mask, bounds);
return new PushedState(this, PushedState.PushedStateType.OpacityMask);
}
/// <summary>
/// Pushes a matrix post-transformation.
/// </summary>
/// <param name="matrix">The matrix</param>
/// <returns>A disposable used to undo the transformation.</returns>
public PushedState PushPostTransform(Matrix matrix) => PushSetTransform(CurrentTransform * matrix);
/// <summary>
/// Pushes a matrix pre-transformation.
/// </summary>
/// <param name="matrix">The matrix</param>
/// <returns>A disposable used to undo the transformation.</returns>
public PushedState PushPreTransform(Matrix matrix) => PushSetTransform(matrix * CurrentTransform);
/// <summary>
/// Sets the current matrix transformation.
/// </summary>
/// <param name="matrix">The matrix</param>
/// <returns>A disposable used to undo the transformation.</returns>
public PushedState PushSetTransform(Matrix matrix)
{
var oldMatrix = CurrentTransform;
CurrentTransform = matrix;
return new PushedState(this, PushedState.PushedStateType.Matrix, oldMatrix);
}
/// <summary>
/// Pushes a new transform context.
/// </summary>
/// <returns>A disposable used to undo the transformation.</returns>
public PushedState PushTransformContainer()
{
if (_transformContainers is null)
throw new ObjectDisposedException(nameof(DrawingContext));
_transformContainers.Push(new TransformContainer(CurrentTransform, _currentContainerTransform));
_currentContainerTransform = CurrentTransform * _currentContainerTransform;
_currentTransform = Matrix.Identity;
return new PushedState(this, PushedState.PushedStateType.MatrixContainer);
}
/// <summary>
/// Disposes of any resources held by the <see cref="DrawingContext"/>.
/// </summary>
public void Dispose()
{
if (_states is null || _transformContainers is null)
throw new ObjectDisposedException(nameof(DrawingContext));
while (_states.Count != 0)
_states.Peek().Dispose();
StateStackPool.Return(_states);
_states = null;
if (_transformContainers.Count != 0)
throw new InvalidOperationException("Transform container stack is non-empty");
TransformStackPool.Return(_transformContainers);
_transformContainers = null;
if (_ownsImpl)
PlatformImpl.Dispose();
}
private static bool PenIsVisible(IPen? pen)
{
return pen?.Brush != null && pen.Thickness > 0;
}
}
}
| |
using System;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.IdentityFramework;
using Abp.Modules;
using Abp.MultiTenancy;
using Abp.TestBase;
using Abp.Zero.SampleApp.EntityFramework;
using Abp.Zero.SampleApp.MultiTenancy;
using Abp.Zero.SampleApp.Roles;
using Abp.Zero.SampleApp.Tests.TestDatas;
using Abp.Zero.SampleApp.Users;
using Castle.MicroKernel.Registration;
using EntityFramework.DynamicFilters;
using Microsoft.AspNet.Identity;
using Shouldly;
namespace Abp.Zero.SampleApp.Tests
{
public abstract class SampleAppTestBase : SampleAppTestBase<SampleAppTestModule>
{
}
public abstract class SampleAppTestBase<TModule> : AbpIntegratedTestBase<TModule>
where TModule : AbpModule
{
protected readonly RoleManager RoleManager;
protected readonly UserManager UserManager;
protected readonly IPermissionManager PermissionManager;
protected readonly IPermissionChecker PermissionChecker;
protected readonly UserStore UserStore;
protected SampleAppTestBase()
{
CreateInitialData();
RoleManager = Resolve<RoleManager>();
UserManager = Resolve<UserManager>();
PermissionManager = Resolve<IPermissionManager>();
PermissionChecker = Resolve<IPermissionChecker>();
UserStore = Resolve<UserStore>();
}
protected override void PreInitialize()
{
base.PreInitialize();
//Fake DbConnection using Effort!
LocalIocManager.IocContainer.Register(
Component.For<DbConnection>()
.UsingFactoryMethod(Effort.DbConnectionFactory.CreateTransient)
.LifestyleSingleton()
);
}
private void CreateInitialData()
{
UsingDbContext(context => new InitialTestDataBuilder(context).Build());
}
public void UsingDbContext(Action<AppDbContext> action)
{
using (var context = LocalIocManager.Resolve<AppDbContext>())
{
context.DisableAllFilters();
action(context);
context.SaveChanges();
}
}
public T UsingDbContext<T>(Func<AppDbContext, T> func)
{
T result;
using (var context = LocalIocManager.Resolve<AppDbContext>())
{
context.DisableAllFilters();
result = func(context);
context.SaveChanges();
}
return result;
}
protected Tenant GetDefaultTenant()
{
return GetTenant(AbpTenantBase.DefaultTenantName);
}
protected Tenant GetTenant(string tenancyName)
{
return UsingDbContext(
context =>
{
return context.Tenants.Single(t => t.TenancyName == tenancyName);
});
}
protected User GetDefaultTenantAdmin()
{
var defaultTenant = GetDefaultTenant();
return UsingDbContext(
context =>
{
return context.Users.Single(u => u.UserName == User.AdminUserName && u.TenantId == defaultTenant.Id);
});
}
protected Role CreateRole(string name)
{
return CreateRole(name, name);
}
protected Role CreateRole(string name, string displayName)
{
var role = new Role(null, name, displayName);
RoleManager.Create(role).Succeeded.ShouldBe(true);
UsingDbContext( context =>
{
var createdRole = context.Roles.FirstOrDefault(r => r.Name == name);
createdRole.ShouldNotBe(null);
});
return role;
}
protected User CreateUser(string userName)
{
var user = new User
{
TenantId = AbpSession.TenantId,
UserName = userName,
Name = userName,
Surname = userName,
EmailAddress = userName + "@aspnetboilerplate.com",
IsEmailConfirmed = true,
Password = "AM4OLBpptxBYmM79lGOX9egzZk3vIQU3d/gFCJzaBjAPXzYIK3tQ2N7X4fcrHtElTw==" //123qwe
};
WithUnitOfWork(()=> UserManager.Create(user).CheckErrors());
UsingDbContext(context =>
{
var createdUser = context.Users.FirstOrDefault(u => u.UserName == userName);
createdUser.ShouldNotBe(null);
});
return user;
}
protected async Task ProhibitPermissionAsync(Role role, string permissionName)
{
await RoleManager.ProhibitPermissionAsync(role, PermissionManager.GetPermission(permissionName));
(await RoleManager.IsGrantedAsync(role.Id, PermissionManager.GetPermission(permissionName))).ShouldBe(false);
}
protected async Task GrantPermissionAsync(Role role, string permissionName)
{
await RoleManager.GrantPermissionAsync(role, PermissionManager.GetPermission(permissionName));
(await RoleManager.IsGrantedAsync(role.Id, PermissionManager.GetPermission(permissionName))).ShouldBe(true);
}
protected async Task GrantPermissionAsync(User user, string permissionName)
{
await UserManager.GrantPermissionAsync(user, PermissionManager.GetPermission(permissionName));
(await UserManager.IsGrantedAsync(user.Id, permissionName)).ShouldBe(true);
}
protected void GrantPermission(User user, string permissionName)
{
GrantPermission(user, PermissionManager.GetPermission(permissionName));
UserManager.IsGranted(user.Id, permissionName).ShouldBe(true);
}
/// <summary>
/// Grants a permission for a user if not already granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
protected void GrantPermission(User user, Permission permission)
{
UserStore.RemovePermission(user, new PermissionGrantInfo(permission.Name, false));
if (UserManager.IsGranted(user.Id, permission))
{
return;
}
UserStore.AddPermission(user, new PermissionGrantInfo(permission.Name, true));
}
protected async Task ProhibitPermissionAsync(User user, string permissionName)
{
await UserManager.ProhibitPermissionAsync(user, PermissionManager.GetPermission(permissionName));
(await UserManager.IsGrantedAsync(user.Id, permissionName)).ShouldBe(false);
}
protected void ProhibitPermission(User user, Permission permission)
{
UserStore.RemovePermission(user, new PermissionGrantInfo(permission.Name, true));
if (!UserManager.IsGranted(user.Id, permission))
{
return;
}
UserStore.AddPermission(user, new PermissionGrantInfo(permission.Name, false));
UserManager.IsGranted(user.Id, permission.Name).ShouldBe(false);
}
}
}
| |
using System;
using Android.OS;
using Android.App;
using Android.Views;
using Android.Widget;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.MobileServices;
using Microsoft.WindowsAzure.MobileServices.Sync;
using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
using System.IO;
using Android.Content;
namespace TodoOffline
{
[Activity (MainLauncher = true,
Icon="@drawable/ic_launcher", Label="@string/app_name",
Theme="@style/AppTheme")]
public class ToDoActivity : Activity
{
//Mobile Service Client reference
private MobileServiceClient client;
//Mobile Service Table used to access data
private IMobileServiceSyncTable<ToDoItem> toDoTable;
//Adapter to sync the items list with the view
private ToDoItemAdapter adapter;
//EditText containing the "New ToDo" text
private EditText textNewToDo;
//Progress spinner to use for table operations
private ProgressBar progressBar;
const string applicationURL = @"https://donnam-zumotest.azure-mobile.net/";
const string applicationKey = @"TTyfjsYztzXcWnhOMCQgboGlLnCCJe65";
protected override async void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Activity_To_Do);
progressBar = FindViewById<ProgressBar> (Resource.Id.loadingProgressBar);
// Initialize the progress bar
progressBar.Visibility = ViewStates.Gone;
// Create ProgressFilter to handle busy state
var progressHandler = new ProgressHandler ();
progressHandler.BusyStateChange += (busy) => {
if (progressBar != null)
progressBar.Visibility = busy ? ViewStates.Visible : ViewStates.Gone;
};
try {
CurrentPlatform.Init ();
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
client = new MobileServiceClient (
applicationURL,
applicationKey, progressHandler);
string path =
Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "localstore.db");
if (!File.Exists(path))
{
File.Create(path).Dispose();
}
var store = new MobileServiceSQLiteStore(path);
store.DefineTable<ToDoItem>();
await client.SyncContext.InitializeAsync(store, new SyncHandler(this));
// Get the Mobile Service Table instance to use
toDoTable = client.GetSyncTable <ToDoItem> ();
textNewToDo = FindViewById<EditText> (Resource.Id.textNewToDo);
// Create an adapter to bind the items with the view
adapter = new ToDoItemAdapter (this, Resource.Layout.Row_List_To_Do);
var listViewToDo = FindViewById<ListView> (Resource.Id.listViewToDo);
listViewToDo.Adapter = adapter;
// Load the items from the Mobile Service
await RefreshItemsFromTableAsync ();
} catch (Java.Net.MalformedURLException) {
CreateAndShowDialog (new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error");
} catch (Exception e) {
CreateAndShowDialog (e, "Error");
}
}
//Initializes the activity menu
public override bool OnCreateOptionsMenu (IMenu menu)
{
MenuInflater.Inflate (Resource.Menu.activity_main, menu);
return true;
}
//Select an option from the menu
public override bool OnOptionsItemSelected (IMenuItem item)
{
if (item.ItemId == Resource.Id.menu_refresh) {
OnRefreshItemsSelected ();
}
return true;
}
// Called when the refresh menu opion is selected
async void OnRefreshItemsSelected ()
{
await client.SyncContext.PushAsync();
await toDoTable.PullAsync("todoItems", toDoTable.CreateQuery());
await RefreshItemsFromTableAsync ();
}
//Refresh the list with the items in the Mobile Service Table
async Task RefreshItemsFromTableAsync ()
{
try {
// Get the items that weren't marked as completed and add them in the
// adapter
var list = await toDoTable
.Where(item => item.Complete == false)
.OrderBy(item => item.Text).ToListAsync ();
adapter.Clear ();
foreach (ToDoItem current in list)
adapter.Add (current);
} catch (Exception e) {
CreateAndShowDialog (e, "Error");
}
}
public async Task CheckItem (ToDoItem item)
{
if (client == null) {
return;
}
// Set the item as completed and update it in the table
try {
item.Complete = true;
await toDoTable.UpdateAsync (item);
adapter.Remove(item);
} catch (Exception e) {
CreateAndShowDialog (e, "Error");
}
}
[Java.Interop.Export()]
public async void AddItem (View view)
{
if (client == null || string.IsNullOrWhiteSpace (textNewToDo.Text)) {
return;
}
// Create a new item
var item = new ToDoItem {
Text = textNewToDo.Text,
Complete = false
};
try {
// Insert the new item
await toDoTable.InsertAsync (item);
if (!item.Complete) {
adapter.Add (item);
}
} catch (Exception e) {
CreateAndShowDialog (e, "Error");
}
textNewToDo.Text = "";
}
void CreateAndShowDialog (Exception exception, String title)
{
CreateAndShowDialog (exception.Message, title);
}
void CreateAndShowDialog (string message, string title)
{
AlertDialog.Builder builder = new AlertDialog.Builder (this);
builder.SetMessage (message);
builder.SetTitle (title);
builder.Create ().Show ();
}
class ProgressHandler : DelegatingHandler
{
int busyCount = 0;
public event Action<bool> BusyStateChange;
#region implemented abstract members of HttpMessageHandler
protected override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
//assumes always executes on UI thread
if (busyCount++ == 0 && BusyStateChange != null)
BusyStateChange (true);
var response = await base.SendAsync (request, cancellationToken);
// assumes always executes on UI thread
if (--busyCount == 0 && BusyStateChange != null)
BusyStateChange (false);
return response;
}
#endregion
}
}
}
| |
// 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 gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="ConversionAdjustmentUploadServiceClient"/> instances.</summary>
public sealed partial class ConversionAdjustmentUploadServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="ConversionAdjustmentUploadServiceSettings"/>.
/// </summary>
/// <returns>A new instance of the default <see cref="ConversionAdjustmentUploadServiceSettings"/>.</returns>
public static ConversionAdjustmentUploadServiceSettings GetDefault() =>
new ConversionAdjustmentUploadServiceSettings();
/// <summary>
/// Constructs a new <see cref="ConversionAdjustmentUploadServiceSettings"/> object with default settings.
/// </summary>
public ConversionAdjustmentUploadServiceSettings()
{
}
private ConversionAdjustmentUploadServiceSettings(ConversionAdjustmentUploadServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
UploadConversionAdjustmentsSettings = existing.UploadConversionAdjustmentsSettings;
OnCopy(existing);
}
partial void OnCopy(ConversionAdjustmentUploadServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ConversionAdjustmentUploadServiceClient.UploadConversionAdjustments</c> and
/// <c>ConversionAdjustmentUploadServiceClient.UploadConversionAdjustmentsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UploadConversionAdjustmentsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="ConversionAdjustmentUploadServiceSettings"/> object.</returns>
public ConversionAdjustmentUploadServiceSettings Clone() => new ConversionAdjustmentUploadServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="ConversionAdjustmentUploadServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class ConversionAdjustmentUploadServiceClientBuilder : gaxgrpc::ClientBuilderBase<ConversionAdjustmentUploadServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ConversionAdjustmentUploadServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ConversionAdjustmentUploadServiceClientBuilder()
{
UseJwtAccessWithScopes = ConversionAdjustmentUploadServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ConversionAdjustmentUploadServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ConversionAdjustmentUploadServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override ConversionAdjustmentUploadServiceClient Build()
{
ConversionAdjustmentUploadServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ConversionAdjustmentUploadServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ConversionAdjustmentUploadServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ConversionAdjustmentUploadServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ConversionAdjustmentUploadServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<ConversionAdjustmentUploadServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ConversionAdjustmentUploadServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ConversionAdjustmentUploadServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
ConversionAdjustmentUploadServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ConversionAdjustmentUploadServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>ConversionAdjustmentUploadService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to upload conversion adjustments.
/// </remarks>
public abstract partial class ConversionAdjustmentUploadServiceClient
{
/// <summary>
/// The default endpoint for the ConversionAdjustmentUploadService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default ConversionAdjustmentUploadService scopes.</summary>
/// <remarks>
/// The default ConversionAdjustmentUploadService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="ConversionAdjustmentUploadServiceClient"/> using the default
/// credentials, endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="ConversionAdjustmentUploadServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ConversionAdjustmentUploadServiceClient"/>.</returns>
public static stt::Task<ConversionAdjustmentUploadServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ConversionAdjustmentUploadServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ConversionAdjustmentUploadServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="ConversionAdjustmentUploadServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ConversionAdjustmentUploadServiceClient"/>.</returns>
public static ConversionAdjustmentUploadServiceClient Create() =>
new ConversionAdjustmentUploadServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ConversionAdjustmentUploadServiceClient"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="ConversionAdjustmentUploadServiceSettings"/>.</param>
/// <returns>The created <see cref="ConversionAdjustmentUploadServiceClient"/>.</returns>
internal static ConversionAdjustmentUploadServiceClient Create(grpccore::CallInvoker callInvoker, ConversionAdjustmentUploadServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ConversionAdjustmentUploadService.ConversionAdjustmentUploadServiceClient grpcClient = new ConversionAdjustmentUploadService.ConversionAdjustmentUploadServiceClient(callInvoker);
return new ConversionAdjustmentUploadServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC ConversionAdjustmentUploadService client</summary>
public virtual ConversionAdjustmentUploadService.ConversionAdjustmentUploadServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual UploadConversionAdjustmentsResponse UploadConversionAdjustments(UploadConversionAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<UploadConversionAdjustmentsResponse> UploadConversionAdjustmentsAsync(UploadConversionAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<UploadConversionAdjustmentsResponse> UploadConversionAdjustmentsAsync(UploadConversionAdjustmentsRequest request, st::CancellationToken cancellationToken) =>
UploadConversionAdjustmentsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer performing the upload.
/// </param>
/// <param name="conversionAdjustments">
/// Required. The conversion adjustments that are being uploaded.
/// </param>
/// <param name="partialFailure">
/// Required. If true, successful operations will be carried out and invalid
/// operations will return errors. If false, all operations will be carried out
/// in one transaction if and only if they are all valid. This should always be
/// set to true.
/// See
/// https://developers.google.com/google-ads/api/docs/best-practices/partial-failures
/// for more information about partial failure.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual UploadConversionAdjustmentsResponse UploadConversionAdjustments(string customerId, scg::IEnumerable<ConversionAdjustment> conversionAdjustments, bool partialFailure, gaxgrpc::CallSettings callSettings = null) =>
UploadConversionAdjustments(new UploadConversionAdjustmentsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
ConversionAdjustments =
{
gax::GaxPreconditions.CheckNotNull(conversionAdjustments, nameof(conversionAdjustments)),
},
PartialFailure = partialFailure,
}, callSettings);
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer performing the upload.
/// </param>
/// <param name="conversionAdjustments">
/// Required. The conversion adjustments that are being uploaded.
/// </param>
/// <param name="partialFailure">
/// Required. If true, successful operations will be carried out and invalid
/// operations will return errors. If false, all operations will be carried out
/// in one transaction if and only if they are all valid. This should always be
/// set to true.
/// See
/// https://developers.google.com/google-ads/api/docs/best-practices/partial-failures
/// for more information about partial failure.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<UploadConversionAdjustmentsResponse> UploadConversionAdjustmentsAsync(string customerId, scg::IEnumerable<ConversionAdjustment> conversionAdjustments, bool partialFailure, gaxgrpc::CallSettings callSettings = null) =>
UploadConversionAdjustmentsAsync(new UploadConversionAdjustmentsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
ConversionAdjustments =
{
gax::GaxPreconditions.CheckNotNull(conversionAdjustments, nameof(conversionAdjustments)),
},
PartialFailure = partialFailure,
}, callSettings);
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer performing the upload.
/// </param>
/// <param name="conversionAdjustments">
/// Required. The conversion adjustments that are being uploaded.
/// </param>
/// <param name="partialFailure">
/// Required. If true, successful operations will be carried out and invalid
/// operations will return errors. If false, all operations will be carried out
/// in one transaction if and only if they are all valid. This should always be
/// set to true.
/// See
/// https://developers.google.com/google-ads/api/docs/best-practices/partial-failures
/// for more information about partial failure.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<UploadConversionAdjustmentsResponse> UploadConversionAdjustmentsAsync(string customerId, scg::IEnumerable<ConversionAdjustment> conversionAdjustments, bool partialFailure, st::CancellationToken cancellationToken) =>
UploadConversionAdjustmentsAsync(customerId, conversionAdjustments, partialFailure, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>ConversionAdjustmentUploadService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to upload conversion adjustments.
/// </remarks>
public sealed partial class ConversionAdjustmentUploadServiceClientImpl : ConversionAdjustmentUploadServiceClient
{
private readonly gaxgrpc::ApiCall<UploadConversionAdjustmentsRequest, UploadConversionAdjustmentsResponse> _callUploadConversionAdjustments;
/// <summary>
/// Constructs a client wrapper for the ConversionAdjustmentUploadService service, with the specified gRPC
/// client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="ConversionAdjustmentUploadServiceSettings"/> used within this client.
/// </param>
public ConversionAdjustmentUploadServiceClientImpl(ConversionAdjustmentUploadService.ConversionAdjustmentUploadServiceClient grpcClient, ConversionAdjustmentUploadServiceSettings settings)
{
GrpcClient = grpcClient;
ConversionAdjustmentUploadServiceSettings effectiveSettings = settings ?? ConversionAdjustmentUploadServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callUploadConversionAdjustments = clientHelper.BuildApiCall<UploadConversionAdjustmentsRequest, UploadConversionAdjustmentsResponse>(grpcClient.UploadConversionAdjustmentsAsync, grpcClient.UploadConversionAdjustments, effectiveSettings.UploadConversionAdjustmentsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callUploadConversionAdjustments);
Modify_UploadConversionAdjustmentsApiCall(ref _callUploadConversionAdjustments);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_UploadConversionAdjustmentsApiCall(ref gaxgrpc::ApiCall<UploadConversionAdjustmentsRequest, UploadConversionAdjustmentsResponse> call);
partial void OnConstruction(ConversionAdjustmentUploadService.ConversionAdjustmentUploadServiceClient grpcClient, ConversionAdjustmentUploadServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ConversionAdjustmentUploadService client</summary>
public override ConversionAdjustmentUploadService.ConversionAdjustmentUploadServiceClient GrpcClient { get; }
partial void Modify_UploadConversionAdjustmentsRequest(ref UploadConversionAdjustmentsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override UploadConversionAdjustmentsResponse UploadConversionAdjustments(UploadConversionAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UploadConversionAdjustmentsRequest(ref request, ref callSettings);
return _callUploadConversionAdjustments.Sync(request, callSettings);
}
/// <summary>
/// Processes the given conversion adjustments.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [PartialFailureError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<UploadConversionAdjustmentsResponse> UploadConversionAdjustmentsAsync(UploadConversionAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UploadConversionAdjustmentsRequest(ref request, ref callSettings);
return _callUploadConversionAdjustments.Async(request, callSettings);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class AddStrStrTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
[ActiveIssue(2769, PlatformID.AnyUnix)]
public void Test01()
{
IntlStrings intl;
NameValueCollection nvc;
// simple string values
string[] values =
{
"",
" ",
"a",
"aA",
"text",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"oNe",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
// [] NameValueCollection is constructed as expected
//-----------------------------------------------------------------
nvc = new NameValueCollection();
// [] add simple strings
//
for (int i = 0; i < values.Length; i++)
{
cnt = nvc.Count;
nvc.Add(keys[i], values[i]);
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1));
}
// verify that collection contains newly added item
//
if (Array.IndexOf(nvc.AllKeys, keys[i]) < 0)
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// access the item
//
if (String.Compare(nvc[keys[i]], values[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[keys[i]], values[i]));
}
}
//
// Intl strings
// [] add Intl strings
//
int len = values.Length;
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
Boolean caseInsensitive = false;
for (int i = 0; i < len * 2; i++)
{
if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
caseInsensitive = true;
}
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
cnt = nvc.Count;
nvc.Add(intlValues[i + len], intlValues[i]);
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1));
}
// verify that collection contains newly added item
//
if (Array.IndexOf(nvc.AllKeys, intlValues[i + len]) < 0)
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// access the item
//
if (String.Compare(nvc[intlValues[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[intlValues[i + len]], intlValues[i]));
}
}
//
// [] Case sensitivity
// Casing doesn't change ( keys are not converted to lower!)
//
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpperInvariant();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLowerInvariant();
}
nvc.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
cnt = nvc.Count;
nvc.Add(intlValues[i + len], intlValues[i]);
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1));
}
// verify that collection contains newly added uppercase item
//
if (Array.IndexOf(nvc.AllKeys, intlValues[i + len]) < 0)
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// access the item
//
if (String.Compare(nvc[intlValues[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[intlValues[i + len]], intlValues[i]));
}
// verify that collection doesn't contains lowercase item
//
if (!caseInsensitive && String.Compare(nvc[intlValuesLower[i + len]], intlValuesLower[i]) == 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" is lowercase after adding uppercase", i, nvc[intlValuesLower[i + len]]));
}
// key is not converted to lower
if (!caseInsensitive && Array.IndexOf(nvc.AllKeys, intlValuesLower[i + len]) >= 0)
{
Assert.False(true, string.Format("Error, key was converted to lower", i));
}
// but search among keys is case-insensitive
if (String.Compare(nvc[intlValuesLower[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, could not find item using differently cased key", i));
}
}
//
// [] Add multiple values with the same key
//
nvc.Clear();
len = values.Length;
string k = "keykey";
for (int i = 0; i < len; i++)
{
nvc.Add(k, "Value" + i);
}
if (nvc.Count != 1)
{
Assert.False(true, string.Format("Error, count is {0} instead of 1}", nvc.Count));
}
if (nvc.AllKeys.Length != 1)
{
Assert.False(true, "Error, should contain only 1 key");
}
// verify that collection contains newly added item
//
if (Array.IndexOf(nvc.AllKeys, k) < 0)
{
Assert.False(true, "Error, collection doesn't contain key of new item");
}
// access the item
//
string[] vals = nvc.GetValues(k);
if (vals.Length != len)
{
Assert.False(true, string.Format("Error, number of values at given key is {0} instead of {1}", vals.Length, len));
}
for (int i = 0; i < len; i++)
{
if (Array.IndexOf(vals, "Value" + i) < 0)
{
Assert.False(true, string.Format("Error, doesn't contain {1}", i, "Value" + i));
}
}
//
// [] Add null value
//
cnt = nvc.Count;
k = "kk";
nvc.Add(k, null);
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + 1));
}
if (Array.IndexOf(nvc.AllKeys, k) < 0)
{
Assert.False(true, "Error, collection doesn't contain key of new item");
}
// verify that collection contains null
//
if (nvc[k] != null)
{
Assert.False(true, "Error, returned non-null on place of null");
}
//
// [] Add item with null key
// Add item with null key - NullReferenceException expected
//
cnt = nvc.Count;
nvc.Add(null, "item");
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + 1));
}
if (Array.IndexOf(nvc.AllKeys, null) < 0)
{
Assert.False(true, "Error, collection doesn't contain null key ");
}
// verify that collection contains null
//
if (nvc[null] != "item")
{
Assert.False(true, "Error, returned wrong value at null key");
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.Client;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Capabilities;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using OSD = OpenMetaverse.StructuredData.OSD;
namespace OpenSim.Region.Framework.Scenes
{
public delegate void KiPrimitiveDelegate(uint localID);
public delegate void RemoveKnownRegionsFromAvatarList(UUID avatarID, List<ulong> regionlst);
/// <summary>
/// Class that Region communications runs through
/// </summary>
public class SceneCommunicationService //one instance per region
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected CommunicationsManager m_commsProvider;
protected IInterregionCommsOut m_interregionCommsOut;
protected RegionInfo m_regionInfo;
protected RegionCommsListener regionCommsHost;
protected List<UUID> m_agentsInTransit;
/// <summary>
/// An agent is crossing into this region
/// </summary>
public event AgentCrossing OnAvatarCrossingIntoRegion;
/// <summary>
/// A user will arrive shortly, set up appropriate credentials so it can connect
/// </summary>
public event ExpectUserDelegate OnExpectUser;
/// <summary>
/// A Prim will arrive shortly
/// </summary>
public event ExpectPrimDelegate OnExpectPrim;
public event CloseAgentConnection OnCloseAgentConnection;
/// <summary>
/// A new prim has arrived
/// </summary>
public event PrimCrossing OnPrimCrossingIntoRegion;
/// <summary>
/// A New Region is up and available
/// </summary>
public event RegionUp OnRegionUp;
/// <summary>
/// We have a child agent for this avatar and we're getting a status update about it
/// </summary>
public event ChildAgentUpdate OnChildAgentUpdate;
//public event RemoveKnownRegionsFromAvatarList OnRemoveKnownRegionFromAvatar;
/// <summary>
/// Time to log one of our users off. Grid Service sends this mostly
/// </summary>
public event LogOffUser OnLogOffUser;
/// <summary>
/// A region wants land data from us!
/// </summary>
public event GetLandData OnGetLandData;
private AgentCrossing handlerAvatarCrossingIntoRegion = null; // OnAvatarCrossingIntoRegion;
private ExpectUserDelegate handlerExpectUser = null; // OnExpectUser;
private ExpectPrimDelegate handlerExpectPrim = null; // OnExpectPrim;
private CloseAgentConnection handlerCloseAgentConnection = null; // OnCloseAgentConnection;
private PrimCrossing handlerPrimCrossingIntoRegion = null; // OnPrimCrossingIntoRegion;
private RegionUp handlerRegionUp = null; // OnRegionUp;
private ChildAgentUpdate handlerChildAgentUpdate = null; // OnChildAgentUpdate;
//private RemoveKnownRegionsFromAvatarList handlerRemoveKnownRegionFromAvatar = null; // OnRemoveKnownRegionFromAvatar;
private LogOffUser handlerLogOffUser = null;
private GetLandData handlerGetLandData = null; // OnGetLandData
public KiPrimitiveDelegate KiPrimitive;
public SceneCommunicationService(CommunicationsManager commsMan)
{
m_commsProvider = commsMan;
m_agentsInTransit = new List<UUID>();
}
/// <summary>
/// Register a region with the grid
/// </summary>
/// <param name="regionInfos"></param>
/// <exception cref="System.Exception">Thrown if region registration fails.</exception>
public void RegisterRegion(IInterregionCommsOut comms_out, RegionInfo regionInfos)
{
m_interregionCommsOut = comms_out;
m_regionInfo = regionInfos;
m_commsProvider.GridService.gdebugRegionName = regionInfos.RegionName;
regionCommsHost = m_commsProvider.GridService.RegisterRegion(m_regionInfo);
if (regionCommsHost != null)
{
//m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: registered with gridservice and got" + regionCommsHost.ToString());
regionCommsHost.debugRegionName = regionInfos.RegionName;
regionCommsHost.OnExpectPrim += IncomingPrimCrossing;
regionCommsHost.OnExpectUser += NewUserConnection;
regionCommsHost.OnAvatarCrossingIntoRegion += AgentCrossing;
regionCommsHost.OnCloseAgentConnection += CloseConnection;
regionCommsHost.OnRegionUp += newRegionUp;
regionCommsHost.OnChildAgentUpdate += ChildAgentUpdate;
regionCommsHost.OnLogOffUser += GridLogOffUser;
regionCommsHost.OnGetLandData += FetchLandData;
}
else
{
//m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: registered with gridservice and got null");
}
}
/// <summary>
/// Returns a region with the name closest to string provided
/// </summary>
/// <param name="name">Partial Region Name for matching</param>
/// <returns>Region Information for the region</returns>
public RegionInfo RequestClosestRegion(string name)
{
return m_commsProvider.GridService.RequestClosestRegion(name);
}
/// <summary>
/// This region is shutting down, de-register all events!
/// De-Register region from Grid!
/// </summary>
public void Close()
{
if (regionCommsHost != null)
{
regionCommsHost.OnLogOffUser -= GridLogOffUser;
regionCommsHost.OnChildAgentUpdate -= ChildAgentUpdate;
regionCommsHost.OnRegionUp -= newRegionUp;
regionCommsHost.OnExpectUser -= NewUserConnection;
regionCommsHost.OnExpectPrim -= IncomingPrimCrossing;
regionCommsHost.OnAvatarCrossingIntoRegion -= AgentCrossing;
regionCommsHost.OnCloseAgentConnection -= CloseConnection;
regionCommsHost.OnGetLandData -= FetchLandData;
try
{
m_commsProvider.GridService.DeregisterRegion(m_regionInfo);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[GRID]: Deregistration of region {0} from the grid failed - {1}. Continuing",
m_regionInfo.RegionName, e);
}
regionCommsHost = null;
}
}
#region CommsManager Event handlers
/// <summary>
/// A New User will arrive shortly, Informs the scene that there's a new user on the way
/// </summary>
/// <param name="agent">Data we need to ensure that the agent can connect</param>
///
protected void NewUserConnection(AgentCircuitData agent)
{
handlerExpectUser = OnExpectUser;
if (handlerExpectUser != null)
{
//m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: OnExpectUser Fired for User:" + agent.firstname + " " + agent.lastname);
handlerExpectUser(agent);
}
}
/// <summary>
/// The Grid has requested us to log-off the user
/// </summary>
/// <param name="AgentID">Unique ID of agent to log-off</param>
/// <param name="RegionSecret">The secret string that the region establishes with the grid when registering</param>
/// <param name="message">The message to send to the user that tells them why they were logged off</param>
protected void GridLogOffUser(UUID AgentID, UUID RegionSecret, string message)
{
handlerLogOffUser = OnLogOffUser;
if (handlerLogOffUser != null)
{
handlerLogOffUser(AgentID, RegionSecret, message);
}
}
/// <summary>
/// A New Region is now available. Inform the scene that there is a new region available.
/// </summary>
/// <param name="region">Information about the new region that is available</param>
/// <returns>True if the event was handled</returns>
protected bool newRegionUp(RegionInfo region)
{
handlerRegionUp = OnRegionUp;
if (handlerRegionUp != null)
{
//m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: newRegionUp Fired for User:" + region.RegionName);
handlerRegionUp(region);
}
return true;
}
/// <summary>
/// Inform the scene that we've got an update about a child agent that we have
/// </summary>
/// <param name="cAgentData"></param>
/// <returns></returns>
protected bool ChildAgentUpdate(ChildAgentDataUpdate cAgentData)
{
handlerChildAgentUpdate = OnChildAgentUpdate;
if (handlerChildAgentUpdate != null)
handlerChildAgentUpdate(cAgentData);
return true;
}
protected void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
{
handlerAvatarCrossingIntoRegion = OnAvatarCrossingIntoRegion;
if (handlerAvatarCrossingIntoRegion != null)
{
handlerAvatarCrossingIntoRegion(agentID, position, isFlying);
}
}
/// <summary>
/// We have a new prim from a neighbor
/// </summary>
/// <param name="primID">unique ID for the primative</param>
/// <param name="objXMLData">XML2 encoded data of the primative</param>
/// <param name="XMLMethod">An Int that represents the version of the XMLMethod</param>
/// <returns>True if the prim was accepted, false if it was not</returns>
protected bool IncomingPrimCrossing(UUID primID, String objXMLData, int XMLMethod)
{
handlerExpectPrim = OnExpectPrim;
if (handlerExpectPrim != null)
{
return handlerExpectPrim(primID, objXMLData, XMLMethod);
}
else
{
return false;
}
}
protected void PrimCrossing(UUID primID, Vector3 position, bool isPhysical)
{
handlerPrimCrossingIntoRegion = OnPrimCrossingIntoRegion;
if (handlerPrimCrossingIntoRegion != null)
{
handlerPrimCrossingIntoRegion(primID, position, isPhysical);
}
}
protected bool CloseConnection(UUID agentID)
{
m_log.Debug("[INTERREGION]: Incoming Agent Close Request for agent: " + agentID);
handlerCloseAgentConnection = OnCloseAgentConnection;
if (handlerCloseAgentConnection != null)
{
return handlerCloseAgentConnection(agentID);
}
return false;
}
protected LandData FetchLandData(uint x, uint y)
{
handlerGetLandData = OnGetLandData;
if (handlerGetLandData != null)
{
return handlerGetLandData(x, y);
}
return null;
}
#endregion
#region Inform Client of Neighbours
private delegate void InformClientOfNeighbourDelegate(
ScenePresence avatar, AgentCircuitData a, SimpleRegionInfo reg, IPEndPoint endPoint, bool newAgent);
private void InformClientOfNeighbourCompleted(IAsyncResult iar)
{
InformClientOfNeighbourDelegate icon = (InformClientOfNeighbourDelegate) iar.AsyncState;
icon.EndInvoke(iar);
}
/// <summary>
/// Async component for informing client of which neighbours exist
/// </summary>
/// <remarks>
/// This needs to run asynchronously, as a network timeout may block the thread for a long while
/// </remarks>
/// <param name="remoteClient"></param>
/// <param name="a"></param>
/// <param name="regionHandle"></param>
/// <param name="endPoint"></param>
private void InformClientOfNeighbourAsync(ScenePresence avatar, AgentCircuitData a, SimpleRegionInfo reg,
IPEndPoint endPoint, bool newAgent)
{
// Let's wait just a little to give time to originating regions to catch up with closing child agents
// after a cross here
Thread.Sleep(500);
uint x, y;
Utils.LongToUInts(reg.RegionHandle, out x, out y);
x = x / Constants.RegionSize;
y = y / Constants.RegionSize;
m_log.Info("[INTERGRID]: Starting to inform client about neighbour " + x + ", " + y + "(" + endPoint.ToString() + ")");
string capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
+ "/CAPS/" + a.CapsPath + "0000/";
string reason = String.Empty;
//bool regionAccepted = m_commsProvider.InterRegion.InformRegionOfChildAgent(reg.RegionHandle, a);
bool regionAccepted = m_interregionCommsOut.SendCreateChildAgent(reg.RegionHandle, a, out reason);
if (regionAccepted && newAgent)
{
IEventQueue eq = avatar.Scene.RequestModuleInterface<IEventQueue>();
if (eq != null)
{
#region IP Translation for NAT
IClientIPEndpoint ipepClient;
if (avatar.ClientView.TryGet(out ipepClient))
{
endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
}
#endregion
eq.EnableSimulator(reg.RegionHandle, endPoint, avatar.UUID);
eq.EstablishAgentCommunication(avatar.UUID, endPoint, capsPath);
m_log.DebugFormat("[CAPS]: Sending new CAPS seed url {0} to client {1} in region {2}",
capsPath, avatar.UUID, avatar.Scene.RegionInfo.RegionName);
}
else
{
avatar.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
// TODO: make Event Queue disablable!
}
m_log.Info("[INTERGRID]: Completed inform client about neighbour " + endPoint.ToString());
}
}
public void RequestNeighbors(RegionInfo region)
{
// List<SimpleRegionInfo> neighbours =
m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
//IPEndPoint blah = new IPEndPoint();
//blah.Address = region.RemotingAddress;
//blah.Port = region.RemotingPort;
}
/// <summary>
/// This informs all neighboring regions about agent "avatar".
/// Calls an asynchronous method to do so.. so it doesn't lag the sim.
/// </summary>
public void EnableNeighbourChildAgents(ScenePresence avatar, List<RegionInfo> lstneighbours)
{
List<SimpleRegionInfo> neighbours = new List<SimpleRegionInfo>();
//m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
for (int i = 0; i < lstneighbours.Count; i++)
{
// We don't want to keep sending to regions that consistently fail on comms.
if (!(lstneighbours[i].commFailTF))
{
neighbours.Add(new SimpleRegionInfo(lstneighbours[i]));
}
}
// we're going to be using the above code once neighbour cache is correct. Currently it doesn't appear to be
// So we're temporarily going back to the old method of grabbing it from the Grid Server Every time :/
if (m_regionInfo != null)
{
neighbours =
m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
}
else
{
m_log.Debug("[ENABLENEIGHBOURCHILDAGENTS]: m_regionInfo was null in EnableNeighbourChildAgents, is this a NPC?");
}
/// We need to find the difference between the new regions where there are no child agents
/// and the regions where there are already child agents. We only send notification to the former.
List<ulong> neighbourHandles = NeighbourHandles(neighbours); // on this region
neighbourHandles.Add(avatar.Scene.RegionInfo.RegionHandle); // add this region too
List<ulong> previousRegionNeighbourHandles ;
if (avatar.Scene.CapsModule != null)
{
previousRegionNeighbourHandles =
new List<ulong>(avatar.Scene.CapsModule.GetChildrenSeeds(avatar.UUID).Keys);
}
else
{
previousRegionNeighbourHandles = new List<ulong>();
}
List<ulong> newRegions = NewNeighbours(neighbourHandles, previousRegionNeighbourHandles);
List<ulong> oldRegions = OldNeighbours(neighbourHandles, previousRegionNeighbourHandles);
//Dump("Current Neighbors", neighbourHandles);
//Dump("Previous Neighbours", previousRegionNeighbourHandles);
//Dump("New Neighbours", newRegions);
//Dump("Old Neighbours", oldRegions);
/// Update the scene presence's known regions here on this region
avatar.DropOldNeighbours(oldRegions);
/// Collect as many seeds as possible
Dictionary<ulong, string> seeds;
if (avatar.Scene.CapsModule != null)
seeds
= new Dictionary<ulong, string>(avatar.Scene.CapsModule.GetChildrenSeeds(avatar.UUID));
else
seeds = new Dictionary<ulong, string>();
//m_log.Debug(" !!! No. of seeds: " + seeds.Count);
if (!seeds.ContainsKey(avatar.Scene.RegionInfo.RegionHandle))
seeds.Add(avatar.Scene.RegionInfo.RegionHandle, avatar.ControllingClient.RequestClientInfo().CapsPath);
/// Create the necessary child agents
List<AgentCircuitData> cagents = new List<AgentCircuitData>();
foreach (SimpleRegionInfo neighbour in neighbours)
{
if (neighbour.RegionHandle != avatar.Scene.RegionInfo.RegionHandle)
{
AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo();
agent.BaseFolder = UUID.Zero;
agent.InventoryFolder = UUID.Zero;
agent.startpos = new Vector3(128, 128, 70);
agent.child = true;
if (newRegions.Contains(neighbour.RegionHandle))
{
agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
avatar.AddNeighbourRegion(neighbour.RegionHandle, agent.CapsPath);
seeds.Add(neighbour.RegionHandle, agent.CapsPath);
}
else
agent.CapsPath = avatar.Scene.CapsModule.GetChildSeed(avatar.UUID, neighbour.RegionHandle);
cagents.Add(agent);
}
}
/// Update all child agent with everyone's seeds
foreach (AgentCircuitData a in cagents)
{
a.ChildrenCapSeeds = new Dictionary<ulong, string>(seeds);
}
if (avatar.Scene.CapsModule != null)
{
// These two are the same thing!
avatar.Scene.CapsModule.SetChildrenSeed(avatar.UUID, seeds);
}
avatar.KnownRegions = seeds;
//avatar.Scene.DumpChildrenSeeds(avatar.UUID);
//avatar.DumpKnownRegions();
bool newAgent = false;
int count = 0;
foreach (SimpleRegionInfo neighbour in neighbours)
{
// Don't do it if there's already an agent in that region
if (newRegions.Contains(neighbour.RegionHandle))
newAgent = true;
else
newAgent = false;
if (neighbour.RegionHandle != avatar.Scene.RegionInfo.RegionHandle)
{
InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
try
{
d.BeginInvoke(avatar, cagents[count], neighbour, neighbour.ExternalEndPoint, newAgent,
InformClientOfNeighbourCompleted,
d);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[REGIONINFO]: Could not resolve external hostname {0} for region {1} ({2}, {3}). {4}",
neighbour.ExternalHostName,
neighbour.RegionHandle,
neighbour.RegionLocX,
neighbour.RegionLocY,
e);
// FIXME: Okay, even though we've failed, we're still going to throw the exception on,
// since I don't know what will happen if we just let the client continue
// XXX: Well, decided to swallow the exception instead for now. Let us see how that goes.
// throw e;
}
}
count++;
}
}
/// <summary>
/// This informs a single neighboring region about agent "avatar".
/// Calls an asynchronous method to do so.. so it doesn't lag the sim.
/// </summary>
public void InformNeighborChildAgent(ScenePresence avatar, SimpleRegionInfo region)
{
AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo();
agent.BaseFolder = UUID.Zero;
agent.InventoryFolder = UUID.Zero;
agent.startpos = new Vector3(128, 128, 70);
agent.child = true;
InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
d.BeginInvoke(avatar, agent, region, region.ExternalEndPoint, true,
InformClientOfNeighbourCompleted,
d);
}
#endregion
public delegate void InformNeighbourThatRegionUpDelegate(INeighbourService nService, RegionInfo region, ulong regionhandle);
private void InformNeighborsThatRegionisUpCompleted(IAsyncResult iar)
{
InformNeighbourThatRegionUpDelegate icon = (InformNeighbourThatRegionUpDelegate) iar.AsyncState;
icon.EndInvoke(iar);
}
/// <summary>
/// Asynchronous call to information neighbouring regions that this region is up
/// </summary>
/// <param name="region"></param>
/// <param name="regionhandle"></param>
private void InformNeighboursThatRegionIsUpAsync(INeighbourService neighbourService, RegionInfo region, ulong regionhandle)
{
m_log.Info("[INTERGRID]: Starting to inform neighbors that I'm here");
//RegionUpData regiondata = new RegionUpData(region.RegionLocX, region.RegionLocY, region.ExternalHostName, region.InternalEndPoint.Port);
//bool regionAccepted =
// m_commsProvider.InterRegion.RegionUp(new SerializableRegionInfo(region), regionhandle);
//bool regionAccepted = m_interregionCommsOut.SendHelloNeighbour(regionhandle, region);
bool regionAccepted = false;
if (neighbourService != null)
regionAccepted = neighbourService.HelloNeighbour(regionhandle, region);
else
m_log.DebugFormat("[SCS]: No neighbour service provided for informing neigbhours of this region");
if (regionAccepted)
{
m_log.Info("[INTERGRID]: Completed informing neighbors that I'm here");
handlerRegionUp = OnRegionUp;
// yes, we're notifying ourselves.
if (handlerRegionUp != null)
handlerRegionUp(region);
}
else
{
m_log.Warn("[INTERGRID]: Failed to inform neighbors that I'm here.");
}
}
/// <summary>
/// Called by scene when region is initialized (not always when it's listening for agents)
/// This is an inter-region message that informs the surrounding neighbors that the sim is up.
/// </summary>
public void InformNeighborsThatRegionisUp(INeighbourService neighbourService, RegionInfo region)
{
//m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: Sending InterRegion Notification that region is up " + region.RegionName);
List<SimpleRegionInfo> neighbours = new List<SimpleRegionInfo>();
// This stays uncached because we don't already know about our neighbors at this point.
neighbours = m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
if (neighbours != null)
{
for (int i = 0; i < neighbours.Count; i++)
{
InformNeighbourThatRegionUpDelegate d = InformNeighboursThatRegionIsUpAsync;
d.BeginInvoke(neighbourService, region, neighbours[i].RegionHandle,
InformNeighborsThatRegionisUpCompleted,
d);
}
}
//bool val = m_commsProvider.InterRegion.RegionUp(new SerializableRegionInfo(region));
}
public delegate void SendChildAgentDataUpdateDelegate(AgentPosition cAgentData, ulong regionHandle);
/// <summary>
/// This informs all neighboring regions about the settings of it's child agent.
/// Calls an asynchronous method to do so.. so it doesn't lag the sim.
///
/// This contains information, such as, Draw Distance, Camera location, Current Position, Current throttle settings, etc.
///
/// </summary>
private void SendChildAgentDataUpdateAsync(AgentPosition cAgentData, ulong regionHandle)
{
//m_log.Info("[INTERGRID]: Informing neighbors about my agent in " + m_regionInfo.RegionName);
try
{
//m_commsProvider.InterRegion.ChildAgentUpdate(regionHandle, cAgentData);
m_interregionCommsOut.SendChildAgentUpdate(regionHandle, cAgentData);
}
catch
{
// Ignore; we did our best
}
//if (regionAccepted)
//{
// //m_log.Info("[INTERGRID]: Completed sending a neighbor an update about my agent");
//}
//else
//{
// //m_log.Info("[INTERGRID]: Failed sending a neighbor an update about my agent");
//}
}
private void SendChildAgentDataUpdateCompleted(IAsyncResult iar)
{
SendChildAgentDataUpdateDelegate icon = (SendChildAgentDataUpdateDelegate) iar.AsyncState;
icon.EndInvoke(iar);
}
public void SendChildAgentDataUpdate(AgentPosition cAgentData, ScenePresence presence)
{
// This assumes that we know what our neighbors are.
try
{
foreach (ulong regionHandle in presence.KnownChildRegionHandles)
{
if (regionHandle != m_regionInfo.RegionHandle)
{
SendChildAgentDataUpdateDelegate d = SendChildAgentDataUpdateAsync;
d.BeginInvoke(cAgentData, regionHandle,
SendChildAgentDataUpdateCompleted,
d);
}
}
}
catch (InvalidOperationException)
{
// We're ignoring a collection was modified error because this data gets old and outdated fast.
}
}
public delegate void SendCloseChildAgentDelegate(UUID agentID, ulong regionHandle);
/// <summary>
/// This Closes child agents on neighboring regions
/// Calls an asynchronous method to do so.. so it doesn't lag the sim.
/// </summary>
protected void SendCloseChildAgentAsync(UUID agentID, ulong regionHandle)
{
m_log.Debug("[INTERGRID]: Sending close agent to " + regionHandle);
// let's do our best, but there's not much we can do if the neighbour doesn't accept.
//m_commsProvider.InterRegion.TellRegionToCloseChildConnection(regionHandle, agentID);
m_interregionCommsOut.SendCloseAgent(regionHandle, agentID);
}
private void SendCloseChildAgentCompleted(IAsyncResult iar)
{
SendCloseChildAgentDelegate icon = (SendCloseChildAgentDelegate)iar.AsyncState;
icon.EndInvoke(iar);
}
public void SendCloseChildAgentConnections(UUID agentID, List<ulong> regionslst)
{
foreach (ulong handle in regionslst)
{
SendCloseChildAgentDelegate d = SendCloseChildAgentAsync;
d.BeginInvoke(agentID, handle,
SendCloseChildAgentCompleted,
d);
}
}
/// <summary>
/// Helper function to request neighbors from grid-comms
/// </summary>
/// <param name="regionHandle"></param>
/// <returns></returns>
public virtual RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle)
{
//m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: Sending Grid Services Request about neighbor " + regionHandle.ToString());
return m_commsProvider.GridService.RequestNeighbourInfo(regionHandle);
}
/// <summary>
/// Helper function to request neighbors from grid-comms
/// </summary>
/// <param name="regionID"></param>
/// <returns></returns>
public virtual RegionInfo RequestNeighbouringRegionInfo(UUID regionID)
{
//m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: Sending Grid Services Request about neighbor " + regionID);
return m_commsProvider.GridService.RequestNeighbourInfo(regionID);
}
/// <summary>
/// Requests map blocks in area of minX, maxX, minY, MaxY in world cordinates
/// </summary>
/// <param name="minX"></param>
/// <param name="minY"></param>
/// <param name="maxX"></param>
/// <param name="maxY"></param>
public virtual void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY)
{
List<MapBlockData> mapBlocks;
mapBlocks = m_commsProvider.GridService.RequestNeighbourMapBlocks(minX - 4, minY - 4, minX + 4, minY + 4);
remoteClient.SendMapBlock(mapBlocks, 0);
}
/// <summary>
/// Try to teleport an agent to a new region.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="RegionHandle"></param>
/// <param name="position"></param>
/// <param name="lookAt"></param>
/// <param name="flags"></param>
public virtual void RequestTeleportToLocation(ScenePresence avatar, ulong regionHandle, Vector3 position,
Vector3 lookAt, uint teleportFlags)
{
if (!avatar.Scene.Permissions.CanTeleport(avatar.UUID))
return;
bool destRegionUp = true;
IEventQueue eq = avatar.Scene.RequestModuleInterface<IEventQueue>();
// Reset animations; the viewer does that in teleports.
avatar.ResetAnimations();
if (regionHandle == m_regionInfo.RegionHandle)
{
m_log.DebugFormat(
"[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation {0} within {1}",
position, m_regionInfo.RegionName);
// Teleport within the same region
if (position.X < 0 || position.X > Constants.RegionSize || position.Y < 0 || position.Y > Constants.RegionSize || position.Z < 0)
{
Vector3 emergencyPos = new Vector3(128, 128, 128);
m_log.WarnFormat(
"[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2}. Substituting {3}",
position, avatar.Name, avatar.UUID, emergencyPos);
position = emergencyPos;
}
// TODO: Get proper AVG Height
float localAVHeight = 1.56f;
float posZLimit = (float)avatar.Scene.Heightmap[(int)position.X, (int)position.Y];
float newPosZ = posZLimit + localAVHeight;
if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
{
position.Z = newPosZ;
}
// Only send this if the event queue is null
if (eq == null)
avatar.ControllingClient.SendTeleportLocationStart();
avatar.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
avatar.Teleport(position);
}
else
{
RegionInfo reg = RequestNeighbouringRegionInfo(regionHandle);
if (reg != null)
{
m_log.DebugFormat(
"[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation to {0} in {1}",
position, reg.RegionName);
if (eq == null)
avatar.ControllingClient.SendTeleportLocationStart();
// Let's do DNS resolution only once in this process, please!
// This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
// it's actually doing a lot of work.
IPEndPoint endPoint = reg.ExternalEndPoint;
if (endPoint.Address == null)
{
// Couldn't resolve the name. Can't TP, because the viewer wants IP addresses.
destRegionUp = false;
}
if (destRegionUp)
{
uint newRegionX = (uint)(reg.RegionHandle >> 40);
uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
uint oldRegionX = (uint)(m_regionInfo.RegionHandle >> 40);
uint oldRegionY = (((uint)(m_regionInfo.RegionHandle)) >> 8);
// Fixing a bug where teleporting while sitting results in the avatar ending up removed from
// both regions
if (avatar.ParentID != (uint)0)
avatar.StandUp();
if (!avatar.ValidateAttachments())
{
avatar.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
return;
}
// the avatar.Close below will clear the child region list. We need this below for (possibly)
// closing the child agents, so save it here (we need a copy as it is Clear()-ed).
//List<ulong> childRegions = new List<ulong>(avatar.GetKnownRegionList());
// Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
// failure at this point (unlike a border crossing failure). So perhaps this can never fail
// once we reach here...
//avatar.Scene.RemoveCapsHandler(avatar.UUID);
string capsPath = String.Empty;
AgentCircuitData agentCircuit = avatar.ControllingClient.RequestClientInfo();
agentCircuit.BaseFolder = UUID.Zero;
agentCircuit.InventoryFolder = UUID.Zero;
agentCircuit.startpos = position;
agentCircuit.child = true;
if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
{
// brand new agent, let's create a new caps seed
agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
}
string reason = String.Empty;
// Let's create an agent there if one doesn't exist yet.
//if (!m_commsProvider.InterRegion.InformRegionOfChildAgent(reg.RegionHandle, agentCircuit))
if (!m_interregionCommsOut.SendCreateChildAgent(reg.RegionHandle, agentCircuit, out reason))
{
avatar.ControllingClient.SendTeleportFailed(String.Format("Destination is not accepting teleports: {0}",
reason));
return;
}
// OK, it got this agent. Let's close some child agents
avatar.CloseChildAgents(newRegionX, newRegionY);
if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
{
#region IP Translation for NAT
IClientIPEndpoint ipepClient;
if (avatar.ClientView.TryGet(out ipepClient))
{
capsPath
= "http://"
+ NetworkUtil.GetHostFor(ipepClient.EndPoint, reg.ExternalHostName)
+ ":"
+ reg.HttpPort
+ CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
}
else
{
capsPath
= "http://"
+ reg.ExternalHostName
+ ":"
+ reg.HttpPort
+ CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
}
#endregion
if (eq != null)
{
#region IP Translation for NAT
// Uses ipepClient above
if (avatar.ClientView.TryGet(out ipepClient))
{
endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
}
#endregion
eq.EnableSimulator(reg.RegionHandle, endPoint, avatar.UUID);
// ES makes the client send a UseCircuitCode message to the destination,
// which triggers a bunch of things there.
// So let's wait
Thread.Sleep(2000);
eq.EstablishAgentCommunication(avatar.UUID, endPoint, capsPath);
}
else
{
avatar.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
}
}
else
{
agentCircuit.CapsPath = avatar.Scene.CapsModule.GetChildSeed(avatar.UUID, reg.RegionHandle);
capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
+ "/CAPS/" + agentCircuit.CapsPath + "0000/";
}
// Expect avatar crossing is a heavy-duty function at the destination.
// That is where MakeRoot is called, which fetches appearance and inventory.
// Plus triggers OnMakeRoot, which spawns a series of asynchronous updates.
//m_commsProvider.InterRegion.ExpectAvatarCrossing(reg.RegionHandle, avatar.ControllingClient.AgentId,
// position, false);
//{
// avatar.ControllingClient.SendTeleportFailed("Problem with destination.");
// // We should close that agent we just created over at destination...
// List<ulong> lst = new List<ulong>();
// lst.Add(reg.RegionHandle);
// SendCloseChildAgentAsync(avatar.UUID, lst);
// return;
//}
SetInTransit(avatar.UUID);
// Let's send a full update of the agent. This is a synchronous call.
AgentData agent = new AgentData();
avatar.CopyTo(agent);
agent.Position = position;
agent.CallbackURI = "http://" + m_regionInfo.ExternalHostName + ":" + m_regionInfo.HttpPort +
"/agent/" + avatar.UUID.ToString() + "/" + avatar.Scene.RegionInfo.RegionHandle.ToString() + "/release/";
m_interregionCommsOut.SendChildAgentUpdate(reg.RegionHandle, agent);
m_log.DebugFormat(
"[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, avatar.UUID);
if (eq != null)
{
eq.TeleportFinishEvent(reg.RegionHandle, 13, endPoint,
4, teleportFlags, capsPath, avatar.UUID);
}
else
{
avatar.ControllingClient.SendRegionTeleport(reg.RegionHandle, 13, endPoint, 4,
teleportFlags, capsPath);
}
// TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
// trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
// that the client contacted the destination before we send the attachments and close things here.
if (!WaitForCallback(avatar.UUID))
{
// Client never contacted destination. Let's restore everything back
avatar.ControllingClient.SendTeleportFailed("Problems connecting to destination.");
ResetFromTransit(avatar.UUID);
// Yikes! We should just have a ref to scene here.
avatar.Scene.InformClientOfNeighbours(avatar);
// Finally, kill the agent we just created at the destination.
m_interregionCommsOut.SendCloseAgent(reg.RegionHandle, avatar.UUID);
return;
}
// Can't go back from here
if (KiPrimitive != null)
{
KiPrimitive(avatar.LocalId);
}
avatar.MakeChildAgent();
// CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
avatar.CrossAttachmentsIntoNewRegion(reg.RegionHandle, true);
// Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
{
Thread.Sleep(5000);
avatar.Close();
CloseConnection(avatar.UUID);
}
else
// now we have a child agent in this region.
avatar.Reset();
// if (teleport success) // seems to be always success here
// the user may change their profile information in other region,
// so the userinfo in UserProfileCache is not reliable any more, delete it
if (avatar.Scene.NeedSceneCacheClear(avatar.UUID))
{
m_commsProvider.UserProfileCacheService.RemoveUser(avatar.UUID);
m_log.DebugFormat(
"[SCENE COMMUNICATION SERVICE]: User {0} is going to another region, profile cache removed",
avatar.UUID);
}
}
else
{
avatar.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
}
}
else
{
// TP to a place that doesn't exist (anymore)
// Inform the viewer about that
avatar.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");
// and set the map-tile to '(Offline)'
uint regX, regY;
Utils.LongToUInts(regionHandle, out regX, out regY);
MapBlockData block = new MapBlockData();
block.X = (ushort)(regX / Constants.RegionSize);
block.Y = (ushort)(regY / Constants.RegionSize);
block.Access = 254; // == not there
List<MapBlockData> blocks = new List<MapBlockData>();
blocks.Add(block);
avatar.ControllingClient.SendMapBlock(blocks, 0);
}
}
}
public bool WaitForCallback(UUID id)
{
int count = 200;
while (m_agentsInTransit.Contains(id) && count-- > 0)
{
//m_log.Debug(" >>> Waiting... " + count);
Thread.Sleep(100);
}
if (count > 0)
return true;
else
return false;
}
public bool ReleaseAgent(UUID id)
{
//m_log.Debug(" >>> ReleaseAgent called <<< ");
return ResetFromTransit(id);
}
public void SetInTransit(UUID id)
{
lock (m_agentsInTransit)
{
if (!m_agentsInTransit.Contains(id))
m_agentsInTransit.Add(id);
}
}
protected bool ResetFromTransit(UUID id)
{
lock (m_agentsInTransit)
{
if (m_agentsInTransit.Contains(id))
{
m_agentsInTransit.Remove(id);
return true;
}
}
return false;
}
private List<ulong> NeighbourHandles(List<SimpleRegionInfo> neighbours)
{
List<ulong> handles = new List<ulong>();
foreach (SimpleRegionInfo reg in neighbours)
{
handles.Add(reg.RegionHandle);
}
return handles;
}
private List<ulong> NewNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
{
return currentNeighbours.FindAll(delegate(ulong handle) { return !previousNeighbours.Contains(handle); });
}
// private List<ulong> CommonNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
// {
// return currentNeighbours.FindAll(delegate(ulong handle) { return previousNeighbours.Contains(handle); });
// }
private List<ulong> OldNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
{
return previousNeighbours.FindAll(delegate(ulong handle) { return !currentNeighbours.Contains(handle); });
}
public void CrossAgentToNewRegion(Scene scene, ScenePresence agent, bool isFlying)
{
Vector3 pos = agent.AbsolutePosition;
Vector3 newpos = new Vector3(pos.X, pos.Y, pos.Z);
uint neighbourx = m_regionInfo.RegionLocX;
uint neighboury = m_regionInfo.RegionLocY;
// distance to edge that will trigger crossing
const float boundaryDistance = 1.7f;
// distance into new region to place avatar
const float enterDistance = 0.1f;
if (pos.X < boundaryDistance)
{
neighbourx--;
newpos.X = Constants.RegionSize - enterDistance;
}
else if (pos.X > Constants.RegionSize - boundaryDistance)
{
neighbourx++;
newpos.X = enterDistance;
}
if (pos.Y < boundaryDistance)
{
neighboury--;
newpos.Y = Constants.RegionSize - enterDistance;
}
else if (pos.Y > Constants.RegionSize - boundaryDistance)
{
neighboury++;
newpos.Y = enterDistance;
}
CrossAgentToNewRegionDelegate d = CrossAgentToNewRegionAsync;
d.BeginInvoke(agent, newpos, neighbourx, neighboury, isFlying, CrossAgentToNewRegionCompleted, d);
}
public delegate ScenePresence CrossAgentToNewRegionDelegate(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, bool isFlying);
/// <summary>
/// This Closes child agents on neighboring regions
/// Calls an asynchronous method to do so.. so it doesn't lag the sim.
/// </summary>
protected ScenePresence CrossAgentToNewRegionAsync(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, bool isFlying)
{
m_log.DebugFormat("[SCENE COMM]: Crossing agent {0} {1} to {2}-{3}", agent.Firstname, agent.Lastname, neighbourx, neighboury);
ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
SimpleRegionInfo neighbourRegion = RequestNeighbouringRegionInfo(neighbourHandle);
if (neighbourRegion != null && agent.ValidateAttachments())
{
pos = pos + (agent.Velocity);
//CachedUserInfo userInfo = m_commsProvider.UserProfileCacheService.GetUserDetails(agent.UUID);
//if (userInfo != null)
//{
// userInfo.DropInventory();
//}
//else
//{
// m_log.WarnFormat("[SCENE COMM]: No cached user info found for {0} {1} on leaving region {2}",
// agent.Name, agent.UUID, agent.Scene.RegionInfo.RegionName);
//}
//bool crossingSuccessful =
// CrossToNeighbouringRegion(neighbourHandle, agent.ControllingClient.AgentId, pos,
//isFlying);
SetInTransit(agent.UUID);
AgentData cAgent = new AgentData();
agent.CopyTo(cAgent);
cAgent.Position = pos;
if (isFlying)
cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
cAgent.CallbackURI = "http://" + m_regionInfo.ExternalHostName + ":" + m_regionInfo.HttpPort +
"/agent/" + agent.UUID.ToString() + "/" + agent.Scene.RegionInfo.RegionHandle.ToString() + "/release/";
m_interregionCommsOut.SendChildAgentUpdate(neighbourHandle, cAgent);
// Next, let's close the child agent connections that are too far away.
agent.CloseChildAgents(neighbourx, neighboury);
//AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo();
agent.ControllingClient.RequestClientInfo();
//m_log.Debug("BEFORE CROSS");
//Scene.DumpChildrenSeeds(UUID);
//DumpKnownRegions();
string agentcaps;
if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps))
{
m_log.ErrorFormat("[SCENE COMM]: No CAPS information for region handle {0}, exiting CrossToNewRegion.",
neighbourRegion.RegionHandle);
return agent;
}
// TODO Should construct this behind a method
string capsPath =
"http://" + neighbourRegion.ExternalHostName + ":" + neighbourRegion.HttpPort
+ "/CAPS/" + agentcaps /*circuitdata.CapsPath*/ + "0000/";
m_log.DebugFormat("[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID);
IEventQueue eq = agent.Scene.RequestModuleInterface<IEventQueue>();
if (eq != null)
{
eq.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
capsPath, agent.UUID, agent.ControllingClient.SessionId);
}
else
{
agent.ControllingClient.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
capsPath);
}
if (!WaitForCallback(agent.UUID))
{
ResetFromTransit(agent.UUID);
// Yikes! We should just have a ref to scene here.
agent.Scene.InformClientOfNeighbours(agent);
return agent;
}
agent.MakeChildAgent();
// now we have a child agent in this region. Request all interesting data about other (root) agents
agent.SendInitialFullUpdateToAllClients();
agent.CrossAttachmentsIntoNewRegion(neighbourHandle, true);
// m_scene.SendKillObject(m_localId);
agent.Scene.NotifyMyCoarseLocationChange();
// the user may change their profile information in other region,
// so the userinfo in UserProfileCache is not reliable any more, delete it
if (agent.Scene.NeedSceneCacheClear(agent.UUID))
{
agent.Scene.CommsManager.UserProfileCacheService.RemoveUser(agent.UUID);
m_log.DebugFormat(
"[SCENE COMM]: User {0} is going to another region, profile cache removed", agent.UUID);
}
}
//m_log.Debug("AFTER CROSS");
//Scene.DumpChildrenSeeds(UUID);
//DumpKnownRegions();
return agent;
}
private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
{
CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
ScenePresence agent = icon.EndInvoke(iar);
// If the cross was successful, this agent is a child agent
if (agent.IsChildAgent)
{
agent.Reset();
}
else // Not successful
{
//CachedUserInfo userInfo = m_commsProvider.UserProfileCacheService.GetUserDetails(agent.UUID);
//if (userInfo != null)
//{
// userInfo.FetchInventory();
//}
agent.RestoreInCurrentScene();
}
// In any case
agent.NotInTransit();
//m_log.DebugFormat("[SCENE COMM]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
}
public Dictionary<string, string> GetGridSettings()
{
return m_commsProvider.GridService.GetGridSettings();
}
public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat)
{
m_commsProvider.LogOffUser(userid, regionid, regionhandle, position, lookat);
}
// deprecated as of 2008-08-27
public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, float posx, float posy, float posz)
{
m_commsProvider.LogOffUser(userid, regionid, regionhandle, posx, posy, posz);
}
public void ClearUserAgent(UUID avatarID)
{
m_commsProvider.UserService.ClearUserAgent(avatarID);
}
public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms)
{
m_commsProvider.AddNewUserFriend(friendlistowner, friend, perms);
}
public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms)
{
m_commsProvider.UpdateUserFriendPerms(friendlistowner, friend, perms);
}
public void RemoveUserFriend(UUID friendlistowner, UUID friend)
{
m_commsProvider.RemoveUserFriend(friendlistowner, friend);
}
public List<FriendListItem> GetUserFriendList(UUID friendlistowner)
{
return m_commsProvider.GetUserFriendList(friendlistowner);
}
public List<MapBlockData> RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY)
{
return m_commsProvider.GridService.RequestNeighbourMapBlocks(minX, minY, maxX, maxY);
}
public List<AvatarPickerAvatar> GenerateAgentPickerRequestResponse(UUID queryID, string query)
{
return m_commsProvider.GenerateAgentPickerRequestResponse(queryID, query);
}
public List<RegionInfo> RequestNamedRegions(string name, int maxNumber)
{
return m_commsProvider.GridService.RequestNamedRegions(name, maxNumber);
}
//private void Dump(string msg, List<ulong> handles)
//{
// m_log.InfoFormat("-------------- HANDLE DUMP ({0}) ---------", msg);
// foreach (ulong handle in handles)
// {
// uint x, y;
// Utils.LongToUInts(handle, out x, out y);
// x = x / Constants.RegionSize;
// y = y / Constants.RegionSize;
// m_log.InfoFormat("({0}, {1})", x, y);
// }
//}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using System.Collections;
using System.Diagnostics;
using AgenaTrader.API;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
using AgenaTrader.Helper;
/// <summary>
/// Version: 1.0.1
/// -------------------------------------------------------------------------
/// Simon Pucher 2016
/// -------------------------------------------------------------------------
/// The indicator was taken from: http://ninjatrader.com/support/forum/showthread.php?t=37759
/// Code was generated by AgenaTrader conversion tool and modified by Simon Pucher.
/// -------------------------------------------------------------------------
/// ****** Important ******
/// To compile this script without any error you also need access to the utility indicator to use these global source code elements.
/// You will find this indicator on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs
/// -------------------------------------------------------------------------
/// Namespace holds all indicators and is required. Do not change it.
/// </summary>
namespace AgenaTrader.UserCode
{
/// <summary>
/// OutputDescriptors horizontal rays at swing highs and lows and removes them once broken.
/// </summary>
[Description("Plots horizontal rays at swing highs and lows and removes them once broken. Returns 1 if a high has broken. Returns -1 if a low has broken. Returns 0 in all other cases.")]
public class SwingRays : UserIndicator
{
public enum enum_swingray_type
{
highlow = 0,
open = 1,
close = 2
}
/// <summary>
/// Object is storing swing ray data
/// </summary>
private class RayObject
{
public RayObject(string tag, int anchor1BarsAgo, double anchor1Y, int anchor2BarsAgo, double anchor2Y) {
this.Tag = tag;
this.BarsAgo1 = anchor1BarsAgo;
this.BarsAgo2 = anchor2BarsAgo;
this.Y1 = anchor1Y;
this.Y2 = anchor2Y;
}
public string Tag { get; set; }
public int BarsAgo1 { get; set; }
public int BarsAgo2 { get; set; }
//Pen Pen { get; set; }
//DateTime X1 { get; set; }
//DateTime X2 { get; set; }
public double Y1 { get; set; }
public double Y2 { get; set; }
}
// Wizard generated variables
private int strength = 5; // number of bars required to left and right of the pivot high/low
// User defined variables (add any user defined variables below)
private Color swingHighColor = Color.Green;
private Color swingLowColor = Color.Red;
private ArrayList lastHighCache;
private ArrayList lastLowCache;
private double lastSwingHighValue = double.MaxValue; // used when testing for price breaks
private double lastSwingLowValue = double.MinValue;
private Stack<RayObject> swingHighRays; // last entry contains nearest swing high; removed when swing is broken
private Stack<RayObject> swingLowRays; // track swing lows in the same manner
private bool enableAlerts = false;
private bool keepBrokenLines = true;
private bool enablesignalline = false;
//input
private Color _signal = Color.Orange;
private int _plot0Width = Const.DefaultLineWidth;
private DashStyle _dash0Style = Const.DefaultIndicatorDashStyle;
private Soundfile _soundfile = Soundfile.Blip;
private enum_swingray_type _type = enum_swingray_type.highlow;
/// <summary>
/// This method is used to configure the indicator and is called once before any bar data is loaded.
/// </summary>
protected override void OnInit()
{
IsShowInDataBox = false;
CalculateOnClosedBar = true;
IsOverlay = false;
PriceTypeSupported = false;
lastHighCache = new ArrayList(); // used to identify swing points; from default Swing indicator
lastLowCache = new ArrayList();
swingHighRays = new Stack<RayObject>(); // LIFO buffer; last entry contains the nearest swing high
swingLowRays = new Stack<RayObject>();
Add(new OutputDescriptor(new Pen(this.Signal, this.Plot0Width), OutputSerieDrawStyle.Line, "Signalline"));
Add(new OutputDescriptor(new Pen(swingHighColor, this.Plot0Width), OutputSerieDrawStyle.Line, "SwingHighs"));
Add(new OutputDescriptor(new Pen(swingLowColor, this.Plot0Width), OutputSerieDrawStyle.Line, "SwingLows"));
Add(new OutputDescriptor(new Pen(this.Signal, this.Plot0Width), OutputSerieDrawStyle.Line, "Priceline"));
}
/// <summary>
/// Called on each bar update event (incoming tick)
/// </summary>
protected override void OnCalculate()
{
int temp_signal_value = 0;
double actualhigh = High[0];
double actuallow = Low[0];
if (this.Type == enum_swingray_type.open)
{
actualhigh = Open[0];
actuallow = Open[0];
}
else if (this.Type == enum_swingray_type.close)
{
actualhigh = Close[0];
actuallow = Close[0];
}
// build up cache of recent High and Low values
// code devised from default Swing Indicator by marqui@BMT, 10-NOV-2010
lastHighCache.Add(actualhigh);
if (lastHighCache.Count > (2 * strength) + 1)
lastHighCache.RemoveAt(0); // if cache is filled, drop the oldest value
lastLowCache.Add(actuallow);
if (lastLowCache.Count > (2 * strength) + 1)
lastLowCache.RemoveAt(0);
//
if (lastHighCache.Count == (2 * strength) + 1) // wait for cache of Highs to be filled
{
// test for swing high
bool isSwingHigh = true;
double swingHighCandidateValue = (double)lastHighCache[strength];
for (int i = 0; i < strength; i++)
if ((double)lastHighCache[i] >= swingHighCandidateValue - double.Epsilon)
isSwingHigh = false; // bar(s) to right of candidate were higher
for (int i = strength + 1; i < lastHighCache.Count; i++)
if ((double)lastHighCache[i] > swingHighCandidateValue - double.Epsilon)
isSwingHigh = false; // bar(s) to left of candidate were higher
// end of test
if (isSwingHigh)
lastSwingHighValue = swingHighCandidateValue;
if (isSwingHigh) // if we have a new swing high then we draw a ray line on the chart
{
AddChartRay("highRay" + (ProcessingBarIndex - strength), false, strength, lastSwingHighValue, 0, lastSwingHighValue, swingHighColor, DashStyle.Solid, 1);
RayObject newRayObject = new RayObject("highRay" + (ProcessingBarIndex - strength), strength, lastSwingHighValue, 0, lastSwingHighValue);
swingHighRays.Push(newRayObject); // store a reference so we can remove it from the chart later
}
else if (actualhigh > lastSwingHighValue) // otherwise, we test to see if price has broken through prior swing high
{
if (swingHighRays.Count > 0) // just to be safe
{
//IRay currentRay = (IRay)swingHighRays.Pop(); // pull current ray from stack
RayObject currentRay = (RayObject)swingHighRays.Pop(); // pull current ray from stack
if (currentRay != null)
{
if (enableAlerts)
{
ShowAlert("Swing High at " + currentRay.Y1 + " broken", GlobalUtilities.GetSoundfile(this.Soundfile));
}
temp_signal_value = 1;
if (keepBrokenLines) // draw a line between swing point and break bar
{
int barsAgo = currentRay.BarsAgo1;
ITrendLine newLine = AddChartLine("highLine" + (ProcessingBarIndex - barsAgo), false, barsAgo, currentRay.Y1, 0, currentRay.Y1, swingHighColor, DashStyle.Dot, 2);
}
RemoveChartDrawing(currentRay.Tag);
if (swingHighRays.Count > 0)
{
//IRay priorRay = (IRay)swingHighRays.Peek();
RayObject priorRay = (RayObject)swingHighRays.Peek();
lastSwingHighValue = priorRay.Y1; // needed when testing the break of the next swing high
}
else
{
lastSwingHighValue = double.MaxValue; // there are no higher swings on the chart; reset to default
}
}
}
}
}
if (lastLowCache.Count == (2 * strength) + 1) // repeat the above for the swing lows
{
// test for swing low
bool isSwingLow = true;
double swingLowCandidateValue = (double)lastLowCache[strength];
for (int i = 0; i < strength; i++)
if ((double)lastLowCache[i] <= swingLowCandidateValue + double.Epsilon)
isSwingLow = false; // bar(s) to right of candidate were lower
for (int i = strength + 1; i < lastLowCache.Count; i++)
if ((double)lastLowCache[i] < swingLowCandidateValue + double.Epsilon)
isSwingLow = false; // bar(s) to left of candidate were lower
// end of test for low
if (isSwingLow)
lastSwingLowValue = swingLowCandidateValue;
if (isSwingLow) // found a new swing low; draw it on the chart
{
AddChartRay("lowRay" + (ProcessingBarIndex - strength), false, strength, lastSwingLowValue, 0, lastSwingLowValue, swingLowColor, DashStyle.Solid, 1);
RayObject newRayObject = new RayObject("lowRay" + (ProcessingBarIndex - strength), strength, lastSwingLowValue, 0, lastSwingLowValue);
swingLowRays.Push(newRayObject);
}
else if (actuallow < lastSwingLowValue) // otherwise test to see if price has broken through prior swing low
{
if (swingLowRays.Count > 0)
{
//IRay currentRay = (IRay)swingLowRays.Pop();
RayObject currentRay = (RayObject)swingLowRays.Pop();
if (currentRay != null)
{
if (enableAlerts)
{
ShowAlert("Swing Low at " + currentRay.Y1 + " broken", GlobalUtilities.GetSoundfile(this.Soundfile));
}
temp_signal_value = -1;
if (keepBrokenLines) // draw a line between swing point and break bar
{
int barsAgo = currentRay.BarsAgo1;
ITrendLine newLine = AddChartLine("highLine" + (ProcessingBarIndex - barsAgo), false, barsAgo, currentRay.Y1, 0, currentRay.Y1, swingLowColor, DashStyle.Dot, 2);
}
RemoveChartDrawing(currentRay.Tag);
if (swingLowRays.Count > 0)
{
//IRay priorRay = (IRay)swingLowRays.Peek();
RayObject priorRay = (RayObject)swingLowRays.Peek();
lastSwingLowValue = priorRay.Y1; // price level of the prior swing low
}
else
{
lastSwingLowValue = double.MinValue; // no swing lows present; set this to default value
}
}
}
}
}
if (enablesignalline)
{
SignalLine.Set(temp_signal_value);
}
else
{
this.SwingHighs.Set(lastSwingHighValue);
this.SwingLows.Set(lastSwingLowValue);
this.PriceLines.Set(InSeries[0]);
}
//Set the color
PlotColors[0][0] = this.Signal;
OutputDescriptors[0].PenStyle = DashStyle.Solid;
OutputDescriptors[0].Pen.Width = this.Plot0Width;
PlotColors[1][0] = this.swingHighColor;
OutputDescriptors[1].PenStyle = DashStyle.Solid;
OutputDescriptors[1].Pen.Width = this.Plot0Width;
PlotColors[2][0] = this.swingLowColor;
OutputDescriptors[2].PenStyle = DashStyle.Solid;
OutputDescriptors[2].Pen.Width = this.Plot0Width;
PlotColors[3][0] = this.Signal;
OutputDescriptors[3].PenStyle = DashStyle.Solid;
OutputDescriptors[3].Pen.Width = this.Plot0Width;
}
public override string ToString()
{
return "SwingRays (I)";
}
public override string DisplayName
{
get
{
return "SwingRays (I)";
}
}
#region InSeries Parameters
[Description("Number of bars before/after each pivot bar")]
[InputParameter]
[DisplayName("Strength")]
public int Strength
{
get { return strength; }
set { strength = Math.Max(2, value); }
}
[Description("Choose the type of swingray")]
[InputParameter]
[DisplayName("SwingRay Type")]
public enum_swingray_type Type {
get { return _type; }
set { _type = value; }
}
[Description("Show Signals if true, when false then show the priceline.")]
[InputParameter]
[DisplayName("Enable signalline")]
public bool EnableSignalline
{
get { return enablesignalline; }
set { enablesignalline = value; }
}
[Description("Alert when swings are broken")]
[InputParameter]
[DisplayName("Enable alerts")]
public bool EnableAlerts
{
get { return enableAlerts; }
set { enableAlerts = value; }
}
[Description("Show broken swing points")]
[InputParameter]
[DisplayName("Keep broken lines")]
public bool KeepBrokenLines
{
get { return keepBrokenLines; }
set { keepBrokenLines = value; }
}
[XmlIgnore()]
[Description("Color for swing highs")]
[InputParameter]
[DisplayName("Swing high color")]
public Color SwingHighColor
{
get { return swingHighColor; }
set { swingHighColor = value; }
}
// Serialize our Color object
[Browsable(false)]
public string SwingHighColorSerialize
{
get { return SerializableColor.ToString(swingHighColor); }
set { swingHighColor = SerializableColor.FromString(value); }
}
[XmlIgnore()]
[Description("Color for swing lows")]
[InputParameter]
[DisplayName("Swing low color")]
public Color SwingLowColor
{
get { return swingLowColor; }
set { swingLowColor = value; }
}
// Serialize our Color object
[Browsable(false)]
public string SwingLowColorSerialize
{
get { return SerializableColor.ToString(swingLowColor); }
set { swingLowColor = SerializableColor.FromString(value); }
}
[XmlIgnore()]
[Description("Select the soundfile for the alert.")]
[InputParameter]
[DisplayName("Soundfile name")]
public Soundfile Soundfile
{
get { return _soundfile; }
set { _soundfile = value; }
}
#endregion
#region InSeries Drawings
[XmlIgnore()]
[Description("Select Color")]
[Category("Drawings")]
[DisplayName("Signalline")]
public Color Signal
{
get { return _signal; }
set { _signal = value; }
}
[Browsable(false)]
public string SignalSerialize
{
get { return SerializableColor.ToString(_signal); }
set { _signal = SerializableColor.FromString(value); }
}
/// <summary>
/// </summary>
[Description("Width for Priceline.")]
[Category("Drawings")]
[DisplayName("Line Width Priceline")]
public int Plot0Width
{
get { return _plot0Width; }
set { _plot0Width = Math.Max(1, value); }
}
/// <summary>
/// </summary>
[Description("DashStyle for Priceline.")]
[Category("Drawings")]
[DisplayName("Dash Style Priceline")]
public DashStyle Dash0Style
{
get { return _dash0Style; }
set { _dash0Style = value; }
}
#endregion
#region Output properties
[Browsable(false)]
[XmlIgnore()]
public DataSeries SignalLine
{
get { return Outputs[0]; }
}
[Browsable(false)]
[XmlIgnore()]
public DataSeries SwingHighs
{
get { return Outputs[1]; }
}
[Browsable(false)]
[XmlIgnore()]
public DataSeries SwingLows
{
get { return Outputs[2]; }
}
[Browsable(false)]
[XmlIgnore()]
public DataSeries PriceLines
{
get { return Outputs[3]; }
}
//[Browsable(false)] // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
// [XmlIgnore()] // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
// public DataSeries HighRay
// {
// get { return Outputs[0]; }
// }
// [Browsable(false)] // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
// [XmlIgnore()] // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
// public DataSeries LowRay
// {
// get { return Outputs[1]; }
// }
// [Browsable(false)] // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
// [XmlIgnore()] // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
// public DataSeries HighLine
// {
// get { return Outputs[2]; }
// }
// [Browsable(false)] // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
// [XmlIgnore()] // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
// public DataSeries LowLine
// {
// get { return Outputs[3]; }
// }
#endregion
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, [email protected], FluorineFx.com
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.Collections;
using System.ComponentModel;
using System.Reflection;
#if !(NET_1_1)
using System.Collections.Generic;
#endif
using FluorineFx;
using FluorineFx.Util;
namespace FluorineFx.AMF3
{
/// <summary>
/// Provides a type converter to convert ArrayCollection objects to and from various other representations.
/// </summary>
#if !SILVERLIGHT
public class ArrayCollectionConverter : ArrayConverter
#else
public class ArrayCollectionConverter : TypeConverter
#endif
{
/// <summary>
/// Overloaded. Returns whether this converter can convert the object to the specified type.
/// </summary>
/// <param name="context">An ITypeDescriptorContext that provides a format context.</param>
/// <param name="destinationType">A Type that represents the type you want to convert to.</param>
/// <returns>true if this converter can perform the conversion; otherwise, false.</returns>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == null)
throw new ArgumentNullException("destinationType");
if( destinationType == typeof(ArrayCollection) )
return true;
if( destinationType.IsArray )
return true;
#if !SILVERLIGHT
if( destinationType == typeof(ArrayList) )
return true;
#endif
if( destinationType == typeof(IList) )
return true;
Type typeIList = destinationType.GetInterface("System.Collections.IList", false);
if(typeIList != null)
return true;
//generic interface
Type typeGenericICollection = destinationType.GetInterface("System.Collections.Generic.ICollection`1", false);
if (typeGenericICollection != null)
return true;
#if !SILVERLIGHT
return base.CanConvertTo(context, destinationType);
#else
return base.CanConvertTo(destinationType);
#endif
}
/// <summary>
/// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// </summary>
/// <param name="context">An ITypeDescriptorContext that provides a format context.</param>
/// <param name="culture">A CultureInfo object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param>
/// <param name="value">The Object to convert.</param>
/// <param name="destinationType">The Type to convert the value parameter to.</param>
/// <returns>An Object that represents the converted value.</returns>
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
ArrayCollection ac = value as ArrayCollection;
ValidationUtils.ArgumentNotNull(ac, "value");
if (destinationType == null)
throw new ArgumentNullException("destinationType");
if( destinationType == typeof(ArrayCollection) )
return value;
if( destinationType.IsArray )
{
return ac.ToArray();
}
#if !SILVERLIGHT
if( destinationType == typeof(ArrayList) )
{
if (ac.List is ArrayList)
return ac.List;
return ArrayList.Adapter(ac.List);
}
#endif
if( destinationType == typeof(IList) )
{
return ac.List;
}
//generic interface
Type typeGenericICollection = destinationType.GetInterface("System.Collections.Generic.ICollection`1", false);
if (typeGenericICollection != null)
{
object obj = TypeHelper.CreateInstance(destinationType);
MethodInfo miAddCollection = typeGenericICollection.GetMethod("Add");
if (miAddCollection != null)
{
ParameterInfo[] parameters = miAddCollection.GetParameters();
if(parameters != null && parameters.Length == 1)
{
Type parameterType = parameters[0].ParameterType;
IList list = (IList) value;
for (int i = 0; i < list.Count; i++)
{
miAddCollection.Invoke(obj, new object[] { TypeHelper.ChangeType(list[i], parameterType) });
}
return obj;
}
}
}
Type typeIList = destinationType.GetInterface("System.Collections.IList", false);
if(typeIList != null)
{
object obj = TypeHelper.CreateInstance(destinationType);
IList list = obj as IList;
for(int i = 0; i < ac.List.Count; i++)
{
list.Add( ac.List[i] );
}
return obj;
}
#if !SILVERLIGHT
return base.ConvertTo (context, culture, value, destinationType);
#else
return base.ConvertTo(value, destinationType);
#endif
}
}
/// <summary>
/// Flex ArrayCollection class. The ArrayCollection class is a wrapper class that exposes an Array as a collection.
/// </summary>
[TypeConverter(typeof(ArrayCollectionConverter))]
[CLSCompliant(false)]
public class ArrayCollection : IExternalizable, IList
{
private IList _list;
/// <summary>
/// Initializes a new instance of the ArrayCollection class.
/// </summary>
public ArrayCollection()
{
#if (NET_1_1)
_list = new ArrayList();
#else
_list = new List<object>();
#endif
}
/// <summary>
/// Creates an ArrayCollection wrapper for a specific IList.
/// </summary>
/// <param name="list">The IList to wrap.</param>
public ArrayCollection(IList list)
{
_list = list;
}
/// <summary>
/// Gets the number of elements contained in the ArrayCollection.
/// </summary>
public int Count
{
get{ return _list == null ? 0 : _list.Count; }
}
/// <summary>
/// Gets the underlying IList.
/// </summary>
public IList List
{
get{ return _list ; }
}
/// <summary>
/// Copies the elements of the ArrayCollection to a new array.
/// </summary>
/// <returns></returns>
public object[] ToArray()
{
if( _list != null )
{
#if !SILVERLIGHT
if( _list is ArrayList )
return ((ArrayList)_list).ToArray();
#endif
#if !(NET_1_1)
if( _list is List<object> )
return ((List<object>)_list).ToArray();
#endif
object[] objArray = new object[_list.Count];
for(int i = 0; i < _list.Count; i++ )
objArray[i] = _list[i];
return objArray;
}
return null;
}
#region IExternalizable Members
/// <summary>
/// Decode the ArrayCollection from a data stream.
/// </summary>
/// <param name="input">IDataInput interface.</param>
public void ReadExternal(IDataInput input)
{
_list = input.ReadObject() as IList;
}
/// <summary>
/// Encode the ArrayCollection for a data stream.
/// </summary>
/// <param name="output">IDataOutput interface.</param>
public void WriteExternal(IDataOutput output)
{
output.WriteObject(ToArray());
}
#endregion
#region IList Members
/// <summary>
/// Gets a value indicating whether the ArrayCollection is read-only.
/// </summary>
public bool IsReadOnly
{
get
{
return _list.IsReadOnly;
}
}
/// <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 object this[int index]
{
get
{
return _list[index];
}
set
{
_list[index] = value;
}
}
/// <summary>
/// Removes the ArrayCollection item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
/// <summary>
/// Inserts an item to the ArrayCollection at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which value should be inserted.</param>
/// <param name="value">The Object to insert into the ArrayCollection.</param>
public void Insert(int index, object value)
{
_list.Insert(index, value);
}
/// <summary>
/// Removes the first occurrence of a specific object from the ArrayCollection.
/// </summary>
/// <param name="value">The Object to remove from the ArrayCollection.</param>
public void Remove(object value)
{
_list.Remove(value);
}
/// <summary>
/// Determines whether the ArrayCollection contains a specific value.
/// </summary>
/// <param name="value">The Object to locate in the ArrayCollection.</param>
/// <returns>true if the Object is found in the ArrayCollection; otherwise, false.</returns>
public bool Contains(object value)
{
return _list.Contains(value);
}
/// <summary>
/// Removes all items from the ArrayCollection.
/// </summary>
public void Clear()
{
_list.Clear();
}
/// <summary>
/// Determines the index of a specific item in the ArrayCollection.
/// </summary>
/// <param name="value">The Object to locate in the ArrayCollection.</param>
/// <returns>The index of value if found in the ArrayCollection; otherwise, -1.</returns>
public int IndexOf(object value)
{
return _list.IndexOf(value);
}
/// <summary>
/// Adds an item to the ArrayCollection.
/// </summary>
/// <param name="value">The Object to add to the ArrayCollection.</param>
/// <returns>The position into which the new element was inserted.</returns>
public int Add(object value)
{
return _list.Add(value);
}
/// <summary>
/// Gets a value indicating whether the ArrayCollection has a fixed size.
/// </summary>
public bool IsFixedSize
{
get
{
return _list.IsFixedSize;
}
}
#endregion
#region ICollection Members
/// <summary>
/// Gets a value indicating whether access to the ArrayCollection is synchronized (thread safe).
/// </summary>
public bool IsSynchronized
{
get
{
return _list.IsSynchronized;
}
}
/// <summary>
/// Copies the elements of the ArrayCollection to an Array, starting at a particular Array index.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied from ArrayCollection. The Array must have zero-based indexing.</param>
/// <param name="index">The zero-based index in array at which copying begins.</param>
public void CopyTo(Array array, int index)
{
_list.CopyTo(array, index);
}
/// <summary>
/// Gets an object that can be used to synchronize access to the ArrayCollection.
/// </summary>
public object SyncRoot
{
get
{
return _list.SyncRoot;
}
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through an ArrayCollection.
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the collection.</returns>
public IEnumerator GetEnumerator()
{
return _list.GetEnumerator();
}
#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.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
namespace System.Configuration
{
internal class ClientConfigPaths
{
internal const string UserConfigFilename = "user.config";
private const string ConfigExtension = ".config";
private const int MaxLengthToUse = 25;
private const string HttpUri = "http://";
private const string StrongNameDesc = "StrongName";
private const string UrlDesc = "Url";
private const string PathDesc = "Path";
private static volatile ClientConfigPaths s_current;
private static volatile bool s_currentIncludesUserConfig;
private readonly bool _includesUserConfig;
private string _companyName;
private ClientConfigPaths(string exePath, bool includeUserConfig)
{
_includesUserConfig = includeUserConfig;
Assembly exeAssembly = null;
string applicationFilename = null;
if (exePath != null)
{
// Exe path was specified, use it
ApplicationUri = Path.GetFullPath(exePath);
if (!File.Exists(ApplicationUri))
{
throw ExceptionUtil.ParameterInvalid(nameof(exePath));
}
applicationFilename = ApplicationUri;
}
else
{
// Exe path wasn't specified, get it from the entry assembly
exeAssembly = Assembly.GetEntryAssembly();
if (exeAssembly == null)
throw new PlatformNotSupportedException();
HasEntryAssembly = true;
// The original NetFX (desktop) code tried to get the local path without using Uri.
// If we ever find a need to do this again be careful with the logic. "file:///" is
// used for local paths and "file://" for UNCs. Simply removing the prefix will make
// local paths relative on Unix (e.g. "file:///home" will become "home" instead of
// "/home").
Uri uri = new Uri(exeAssembly.CodeBase);
if (uri.IsFile)
{
ApplicationUri = uri.LocalPath;
applicationFilename = uri.LocalPath;
}
else
{
ApplicationUri = exeAssembly.EscapedCodeBase;
}
}
ApplicationConfigUri = ApplicationUri + ConfigExtension;
// In the case when exePath was explicitly supplied, we will not be able to
// construct user.config paths, so quit here.
if (exePath != null) return;
// Skip expensive initialization of user config file information if requested.
if (!_includesUserConfig) return;
bool isHttp = StringUtil.StartsWithOrdinalIgnoreCase(ApplicationConfigUri, HttpUri);
SetNamesAndVersion(applicationFilename, exeAssembly, isHttp);
if (isHttp) return;
// Create a directory suffix for local and roaming config of three parts:
// (1) Company name
string part1 = Validate(_companyName, limitSize: true);
// (2) Domain or product name & a application urit hash
string namePrefix = Validate(AppDomain.CurrentDomain.FriendlyName, limitSize: true);
if (string.IsNullOrEmpty(namePrefix))
namePrefix = Validate(ProductName, limitSize: true);
string applicationUriLower = !string.IsNullOrEmpty(ApplicationUri)
? ApplicationUri.ToLower(CultureInfo.InvariantCulture)
: null;
string hashSuffix = GetTypeAndHashSuffix(applicationUriLower);
string part2 = !string.IsNullOrEmpty(namePrefix) && !string.IsNullOrEmpty(hashSuffix)
? namePrefix + hashSuffix
: null;
// (3) The product version
string part3 = Validate(ProductVersion, limitSize: false);
string dirSuffix = CombineIfValid(CombineIfValid(part1, part2), part3);
string roamingFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
if (Path.IsPathRooted(roamingFolderPath))
{
RoamingConfigDirectory = CombineIfValid(roamingFolderPath, dirSuffix);
RoamingConfigFilename = CombineIfValid(RoamingConfigDirectory, UserConfigFilename);
}
string localFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (Path.IsPathRooted(localFolderPath))
{
LocalConfigDirectory = CombineIfValid(localFolderPath, dirSuffix);
LocalConfigFilename = CombineIfValid(LocalConfigDirectory, UserConfigFilename);
}
}
internal static ClientConfigPaths Current => GetPaths(null, true);
internal bool HasEntryAssembly { get; }
internal string ApplicationUri { get; }
internal string ApplicationConfigUri { get; }
internal string RoamingConfigFilename { get; }
internal string RoamingConfigDirectory { get; }
internal bool HasRoamingConfig => (RoamingConfigFilename != null) || !_includesUserConfig;
internal string LocalConfigFilename { get; }
internal string LocalConfigDirectory { get; }
internal bool HasLocalConfig => (LocalConfigFilename != null) || !_includesUserConfig;
internal string ProductName { get; private set; }
internal string ProductVersion { get; private set; }
internal static ClientConfigPaths GetPaths(string exePath, bool includeUserConfig)
{
ClientConfigPaths result;
if (exePath == null)
{
if ((s_current == null) || (includeUserConfig && !s_currentIncludesUserConfig))
{
s_current = new ClientConfigPaths(null, includeUserConfig);
s_currentIncludesUserConfig = includeUserConfig;
}
result = s_current;
}
else result = new ClientConfigPaths(exePath, includeUserConfig);
return result;
}
internal static void RefreshCurrent()
{
s_currentIncludesUserConfig = false;
s_current = null;
}
// Combines path2 with path1 if possible, else returns null.
private static string CombineIfValid(string path1, string path2)
{
if ((path1 == null) || (path2 == null)) return null;
try
{
return Path.Combine(path1, path2);
}
catch
{
return null;
}
}
// Returns a type and hash suffix based on what used to come from app domain evidence.
// The evidence we use, in priority order, is Strong Name, Url and Exe Path. If one of
// these is found, we compute a SHA1 hash of it and return a suffix based on that.
// If none is found, we return null.
private static string GetTypeAndHashSuffix(string exePath)
{
Assembly assembly = Assembly.GetEntryAssembly();
string suffix = null;
string typeName = null;
string hash = null;
if (assembly != null)
{
AssemblyName assemblyName = assembly.GetName();
Uri codeBase = new Uri(assembly.CodeBase);
hash = IdentityHelper.GetNormalizedStrongNameHash(assemblyName);
if (hash != null)
{
typeName = StrongNameDesc;
}
else
{
hash = IdentityHelper.GetNormalizedUriHash(codeBase);
typeName = UrlDesc;
}
}
else if (!string.IsNullOrEmpty(exePath))
{
// Fall back on the exe name
hash = IdentityHelper.GetStrongHashSuitableForObjectName(exePath);
typeName = PathDesc;
}
if (!string.IsNullOrEmpty(hash)) suffix = "_" + typeName + "_" + hash;
return suffix;
}
private void SetNamesAndVersion(string applicationFilename, Assembly exeAssembly, bool isHttp)
{
Type mainType = null;
// Get CompanyName, ProductName, and ProductVersion
// First try custom attributes on the assembly.
if (exeAssembly != null)
{
object[] attrs = exeAssembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
if ((attrs != null) && (attrs.Length > 0))
{
_companyName = ((AssemblyCompanyAttribute)attrs[0]).Company?.Trim();
}
attrs = exeAssembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);
if ((attrs != null) && (attrs.Length > 0))
{
ProductName = ((AssemblyProductAttribute)attrs[0]).Product?.Trim();
}
ProductVersion = exeAssembly.GetName().Version.ToString().Trim();
}
// If we couldn't get custom attributes, fall back on the entry type namespace
if (!isHttp &&
(string.IsNullOrEmpty(_companyName) || string.IsNullOrEmpty(ProductName) ||
string.IsNullOrEmpty(ProductVersion)))
{
if (exeAssembly != null)
{
MethodInfo entryPoint = exeAssembly.EntryPoint;
if (entryPoint != null)
{
mainType = entryPoint.ReflectedType;
}
}
string ns = null;
if (mainType != null) ns = mainType.Namespace;
if (string.IsNullOrEmpty(ProductName))
{
// Try the remainder of the namespace
if (ns != null)
{
int lastDot = ns.LastIndexOf(".", StringComparison.Ordinal);
if ((lastDot != -1) && (lastDot < ns.Length - 1)) ProductName = ns.Substring(lastDot + 1);
else ProductName = ns;
ProductName = ProductName.Trim();
}
// Try the type of the entry assembly
if (string.IsNullOrEmpty(ProductName) && (mainType != null)) ProductName = mainType.Name.Trim();
// give up, return empty string
if (ProductName == null) ProductName = string.Empty;
}
if (string.IsNullOrEmpty(_companyName))
{
// Try the first part of the namespace
if (ns != null)
{
int firstDot = ns.IndexOf(".", StringComparison.Ordinal);
_companyName = firstDot != -1 ? ns.Substring(0, firstDot) : ns;
_companyName = _companyName.Trim();
}
// If that doesn't work, use the product name
if (string.IsNullOrEmpty(_companyName)) _companyName = ProductName;
}
}
// Desperate measures for product version - assume 1.0
if (string.IsNullOrEmpty(ProductVersion)) ProductVersion = "1.0.0.0";
}
// Makes the passed in string suitable to use as a path name by replacing illegal characters
// with underscores. Additionally, we do two things - replace spaces too with underscores and
// limit the resultant string's length to MaxLengthToUse if limitSize is true.
private static string Validate(string str, bool limitSize)
{
string validated = str;
if (string.IsNullOrEmpty(validated)) return validated;
// First replace all illegal characters with underscores
foreach (char c in Path.GetInvalidFileNameChars()) validated = validated.Replace(c, '_');
// Replace all spaces with underscores
validated = validated.Replace(' ', '_');
if (limitSize)
{
validated = validated.Length > MaxLengthToUse
? validated.Substring(0, MaxLengthToUse)
: validated;
}
return validated;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Extensions.Logging;
using Orleans.Metadata;
using Orleans.Runtime.MembershipService;
using Orleans.Versions;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
namespace Orleans.Runtime.Management
{
/// <summary>
/// Implementation class for the Orleans management grain.
/// </summary>
internal class ManagementGrain : Grain, IManagementGrain
{
private readonly IInternalGrainFactory internalGrainFactory;
private readonly ISiloStatusOracle siloStatusOracle;
private readonly IVersionStore versionStore;
private readonly MembershipTableManager membershipTableManager;
private readonly GrainManifest siloManifest;
private readonly ClusterManifest clusterManifest;
private readonly ILogger logger;
private readonly Catalog catalog;
public ManagementGrain(
IInternalGrainFactory internalGrainFactory,
ISiloStatusOracle siloStatusOracle,
IVersionStore versionStore,
ILogger<ManagementGrain> logger,
MembershipTableManager membershipTableManager,
IClusterManifestProvider clusterManifestProvider,
Catalog catalog)
{
this.membershipTableManager = membershipTableManager;
this.siloManifest = clusterManifestProvider.LocalGrainManifest;
this.clusterManifest = clusterManifestProvider.Current;
this.internalGrainFactory = internalGrainFactory;
this.siloStatusOracle = siloStatusOracle;
this.versionStore = versionStore;
this.logger = logger;
this.catalog = catalog;
}
public async Task<Dictionary<SiloAddress, SiloStatus>> GetHosts(bool onlyActive = false)
{
await this.membershipTableManager.Refresh();
return this.siloStatusOracle.GetApproximateSiloStatuses(onlyActive);
}
public async Task<MembershipEntry[]> GetDetailedHosts(bool onlyActive = false)
{
logger.Info("GetDetailedHosts onlyActive={0}", onlyActive);
await this.membershipTableManager.Refresh();
var table = this.membershipTableManager.MembershipTableSnapshot;
MembershipEntry[] result;
if (onlyActive)
{
result = table.Entries
.Where(item => item.Value.Status == SiloStatus.Active)
.Select(x => x.Value)
.ToArray();
}
else
{
result = table.Entries
.Select(x => x.Value)
.ToArray();
}
return result;
}
public Task ForceGarbageCollection(SiloAddress[] siloAddresses)
{
var silos = GetSiloAddresses(siloAddresses);
logger.Info("Forcing garbage collection on {0}", Utils.EnumerableToString(silos));
List<Task> actionPromises = PerformPerSiloAction(silos,
s => GetSiloControlReference(s).ForceGarbageCollection());
return Task.WhenAll(actionPromises);
}
public Task ForceActivationCollection(SiloAddress[] siloAddresses, TimeSpan ageLimit)
{
var silos = GetSiloAddresses(siloAddresses);
return Task.WhenAll(GetSiloAddresses(silos).Select(s =>
GetSiloControlReference(s).ForceActivationCollection(ageLimit)));
}
public async Task ForceActivationCollection(TimeSpan ageLimit)
{
Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true);
SiloAddress[] silos = hosts.Keys.ToArray();
await ForceActivationCollection(silos, ageLimit);
}
public Task ForceRuntimeStatisticsCollection(SiloAddress[] siloAddresses)
{
var silos = GetSiloAddresses(siloAddresses);
logger.Info("Forcing runtime statistics collection on {0}", Utils.EnumerableToString(silos));
List<Task> actionPromises = PerformPerSiloAction(
silos,
s => GetSiloControlReference(s).ForceRuntimeStatisticsCollection());
return Task.WhenAll(actionPromises);
}
public Task<SiloRuntimeStatistics[]> GetRuntimeStatistics(SiloAddress[] siloAddresses)
{
var silos = GetSiloAddresses(siloAddresses);
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("GetRuntimeStatistics on {0}", Utils.EnumerableToString(silos));
var promises = new List<Task<SiloRuntimeStatistics>>();
foreach (SiloAddress siloAddress in silos)
promises.Add(GetSiloControlReference(siloAddress).GetRuntimeStatistics());
return Task.WhenAll(promises);
}
public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(SiloAddress[] hostsIds)
{
var all = GetSiloAddresses(hostsIds).Select(s =>
GetSiloControlReference(s).GetSimpleGrainStatistics()).ToList();
await Task.WhenAll(all);
return all.SelectMany(s => s.Result).ToArray();
}
public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics()
{
Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true);
SiloAddress[] silos = hosts.Keys.ToArray();
return await GetSimpleGrainStatistics(silos);
}
public async Task<DetailedGrainStatistic[]> GetDetailedGrainStatistics(string[] types = null, SiloAddress[] hostsIds = null)
{
if (hostsIds == null)
{
Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true);
hostsIds = hosts.Keys.ToArray();
}
var all = GetSiloAddresses(hostsIds).Select(s =>
GetSiloControlReference(s).GetDetailedGrainStatistics(types)).ToList();
await Task.WhenAll(all);
return all.SelectMany(s => s.Result).ToArray();
}
public async Task<int> GetGrainActivationCount(GrainReference grainReference)
{
Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true);
List<SiloAddress> hostsIds = hosts.Keys.ToList();
var tasks = new List<Task<DetailedGrainReport>>();
foreach (var silo in hostsIds)
tasks.Add(GetSiloControlReference(silo).GetDetailedGrainReport(grainReference.GrainId));
await Task.WhenAll(tasks);
return tasks.Select(s => s.Result).Select(r => r.LocalActivations.Count).Sum();
}
public async Task SetCompatibilityStrategy(CompatibilityStrategy strategy)
{
await SetStrategy(
store => store.SetCompatibilityStrategy(strategy),
siloControl => siloControl.SetCompatibilityStrategy(strategy));
}
public async Task SetSelectorStrategy(VersionSelectorStrategy strategy)
{
await SetStrategy(
store => store.SetSelectorStrategy(strategy),
siloControl => siloControl.SetSelectorStrategy(strategy));
}
public async Task SetCompatibilityStrategy(GrainInterfaceType interfaceType, CompatibilityStrategy strategy)
{
CheckIfIsExistingInterface(interfaceType);
await SetStrategy(
store => store.SetCompatibilityStrategy(interfaceType, strategy),
siloControl => siloControl.SetCompatibilityStrategy(interfaceType, strategy));
}
public async Task SetSelectorStrategy(GrainInterfaceType interfaceType, VersionSelectorStrategy strategy)
{
CheckIfIsExistingInterface(interfaceType);
await SetStrategy(
store => store.SetSelectorStrategy(interfaceType, strategy),
siloControl => siloControl.SetSelectorStrategy(interfaceType, strategy));
}
public async Task<int> GetTotalActivationCount()
{
Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true);
List<SiloAddress> silos = hosts.Keys.ToList();
var tasks = new List<Task<int>>();
foreach (var silo in silos)
tasks.Add(GetSiloControlReference(silo).GetActivationCount());
await Task.WhenAll(tasks);
int sum = 0;
foreach (Task<int> task in tasks)
sum += task.Result;
return sum;
}
public Task<object[]> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg)
{
return ExecutePerSiloCall(isc => isc.SendControlCommandToProvider(providerTypeFullName, providerName, command, arg),
String.Format("SendControlCommandToProvider of type {0} and name {1} command {2}.", providerTypeFullName, providerName, command));
}
public ValueTask<SiloAddress> GetActivationAddress(IAddressable reference)
{
var grainReference = reference as GrainReference;
var grainId = grainReference.GrainId;
GrainProperties grainProperties = default;
if (!siloManifest.Grains.TryGetValue(grainId.Type, out grainProperties))
{
var grainManifest = clusterManifest.AllGrainManifests
.SelectMany(m => m.Grains.Where(g => g.Key == grainId.Type))
.FirstOrDefault();
if (grainManifest.Value != null)
{
grainProperties = grainManifest.Value;
}
else
{
throw new ArgumentException($"Unable to find Grain type '{grainId.Type}'. Make sure it is added to the Application Parts Manager at the Silo configuration.");
}
}
if (grainProperties != default &&
grainProperties.Properties.TryGetValue(WellKnownGrainTypeProperties.PlacementStrategy, out string placementStrategy))
{
if (placementStrategy == nameof(StatelessWorkerPlacement))
{
throw new InvalidOperationException(
$"Grain '{grainReference.ToString()}' is a Stateless Worker. This type of grain can't be looked up by this method"
);
}
}
if (this.catalog.FastLookup(grainId, out var addresses))
{
var placementResult = addresses.FirstOrDefault();
return new ValueTask<SiloAddress>(placementResult?.Silo);
}
return LookupAsync(grainId, catalog);
async ValueTask<SiloAddress> LookupAsync(GrainId grainId, Catalog catalog)
{
var places = await catalog.FullLookup(grainId);
return places.FirstOrDefault()?.Silo;
}
}
private void CheckIfIsExistingInterface(GrainInterfaceType interfaceType)
{
GrainInterfaceType lookupId;
if (GenericGrainInterfaceType.TryParse(interfaceType, out var generic))
{
lookupId = generic.Value;
}
else
{
lookupId = interfaceType;
}
if (!this.siloManifest.Interfaces.TryGetValue(lookupId, out _))
{
throw new ArgumentException($"Interface '{interfaceType} not found", nameof(interfaceType));
}
}
private async Task SetStrategy(Func<IVersionStore, Task> storeFunc, Func<ISiloControl, Task> applyFunc)
{
await storeFunc(versionStore);
var silos = GetSiloAddresses(null);
var actionPromises = PerformPerSiloAction(
silos,
s => applyFunc(GetSiloControlReference(s)));
try
{
await Task.WhenAll(actionPromises);
}
catch (Exception)
{
// ignored: silos that failed to set the new strategy will reload it from the storage
// in the future.
}
}
private async Task<object[]> ExecutePerSiloCall(Func<ISiloControl, Task<object>> action, string actionToLog)
{
var silos = await GetHosts(true);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.Debug("Executing {0} against {1}", actionToLog, Utils.EnumerableToString(silos.Keys));
}
var actionPromises = new List<Task<object>>();
foreach (SiloAddress siloAddress in silos.Keys.ToArray())
actionPromises.Add(action(GetSiloControlReference(siloAddress)));
return await Task.WhenAll(actionPromises);
}
private SiloAddress[] GetSiloAddresses(SiloAddress[] silos)
{
if (silos != null && silos.Length > 0)
return silos;
return this.siloStatusOracle
.GetApproximateSiloStatuses(true).Keys.ToArray();
}
/// <summary>
/// Perform an action for each silo.
/// </summary>
/// <remarks>
/// Because SiloControl contains a reference to a system target, each method call using that reference
/// will get routed either locally or remotely to the appropriate silo instance auto-magically.
/// </remarks>
/// <param name="siloAddresses">List of silos to perform the action for</param>
/// <param name="perSiloAction">The action function to be performed for each silo</param>
/// <returns>Array containing one Task for each silo the action was performed for</returns>
private List<Task> PerformPerSiloAction(SiloAddress[] siloAddresses, Func<SiloAddress, Task> perSiloAction)
{
var requestsToSilos = new List<Task>();
foreach (SiloAddress siloAddress in siloAddresses)
requestsToSilos.Add(perSiloAction(siloAddress));
return requestsToSilos;
}
private static void AddXPathValue(XmlNode xml, IEnumerable<string> path, string value)
{
if (path == null) return;
var first = path.FirstOrDefault();
if (first == null) return;
if (first.StartsWith("@", StringComparison.Ordinal))
{
first = first.Substring(1);
if (path.Count() != 1)
throw new ArgumentException("Attribute " + first + " must be last in path");
var e = xml as XmlElement;
if (e == null)
throw new ArgumentException("Attribute " + first + " must be on XML element");
e.SetAttribute(first, value);
return;
}
foreach (var child in xml.ChildNodes)
{
var e = child as XmlElement;
if (e != null && e.LocalName == first)
{
AddXPathValue(e, path.Skip(1), value);
return;
}
}
var empty = (xml as XmlDocument ?? xml.OwnerDocument).CreateElement(first);
xml.AppendChild(empty);
AddXPathValue(empty, path.Skip(1), value);
}
private ISiloControl GetSiloControlReference(SiloAddress silo)
{
return this.internalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlType, silo);
}
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at [email protected]
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web;
using System.Web.Caching;
using Subtext.Configuration;
using Subtext.Extensibility.Interfaces;
using Subtext.Framework.Components;
using Subtext.Framework.Routing;
using Subtext.Framework.Text;
using Subtext.Framework.Util;
using Subtext.Infrastructure;
using Subtext.Framework.Web;
using Subtext.Extensibility;
namespace Subtext.Framework.Data
{
//TODO: Refactor. Static classes like this are a pain!
/// <summary>
/// Encapsulates obtaining content from the cache.
/// </summary>
public static class Cacher
{
private const string EntriesByCategoryKey = "EC:Count{0}Category{1}BlogId{2}";
private const string EntryKeyId = "Entry{0}BlogId{1}";
private const string EntryKeyName = "EntryName{0}BlogId{1}";
public const int LongDuration = 600;
public const int MediumDuration = 20;
public const int ShortDuration = 10;
private const string EntryDayKey = "EntryDay:Date{0:yyyyMMdd}Blog{1}";
private const string EntryMonthKey = "EntryMonth:Date{0:yyyyMM}Blog{1}";
private const string EntriesByTagKey = "ET:Count{0}Tag{1}BlogId{2}";
private const string CategoryKey = "LC{0}BlogId{1}";
private const string ParentCommentEntryKey = "ParentEntry:Comments:EntryId{0}:BlogId{1}";
private const string TagsKey = "TagsCount{0}BlogId{1}";
public static T GetOrInsert<T>(this ICache cache, string key, Func<T> retrievalFunction, int duration, CacheDependency cacheDependency)
{
var item = cache[key];
if(item == null)
{
item = retrievalFunction();
if(item != null)
{
cache.InsertDuration(key, item, duration, cacheDependency);
}
}
return (T)item;
}
public static T GetOrInsertSliding<T>(this ICache cache, string key, Func<T> retrievalFunction, CacheDependency cacheDependency, int slidingDuration)
{
var item = cache[key];
if(item == null)
{
item = retrievalFunction();
if(item != null)
{
cache.InsertDurationSliding(key, item, cacheDependency, slidingDuration);
}
}
return (T)item;
}
public static T GetOrInsert<T>(this ICache cache, string key, Func<T> retrievalFunction, int duration)
{
return cache.GetOrInsert(key, retrievalFunction, duration, null);
}
public static T GetOrInsert<T>(this ICache cache, string key, Func<T> retrievalFunction)
{
return cache.GetOrInsert(key, retrievalFunction, ShortDuration, null);
}
/// <summary>
/// Gets the entries for the specified month.
/// </summary>
public static ICollection<Entry> GetEntriesForMonth(DateTime dateTime, ISubtextContext context)
{
string key = string.Format(CultureInfo.InvariantCulture, EntryMonthKey, dateTime, context.Blog.Id);
return context.Cache.GetOrInsert(key, () => context.Repository.GetPostsByMonth(dateTime.Month, dateTime.Year), LongDuration);
}
public static EntryDay GetEntriesForDay(DateTime day, ISubtextContext context)
{
string key = string.Format(CultureInfo.InvariantCulture, EntryDayKey, day, context.Blog.Id);
return context.Cache.GetOrInsert(key, () => context.Repository.GetEntryDay(day), LongDuration);
}
public static ICollection<Entry> GetEntriesByCategory(int count, int categoryId, ISubtextContext context)
{
string key = string.Format(EntriesByCategoryKey, count, categoryId, context.Blog.Id);
return context.Cache.GetOrInsert(key, () => context.Repository.GetEntriesByCategory(count, categoryId, true /* activeOnly */));
}
public static ICollection<Entry> GetEntriesByTag(int count, string tag, ISubtextContext context)
{
string key = string.Format(EntriesByTagKey, count, tag, context.Blog.Id);
return context.Cache.GetOrInsert(key, () => context.Repository.GetEntriesByTag(count, tag));
}
/// <summary>
/// Returns a LinkCategory for a single category based on the request url.
/// </summary>
public static LinkCategory SingleCategory(ISubtextContext context)
{
if(context == null)
{
throw new ArgumentNullException("context");
}
string categorySlug = context.RequestContext.GetSlugFromRequest();
if(categorySlug.IsNumeric())
{
int categoryId = Int32.Parse(categorySlug, CultureInfo.InvariantCulture);
return SingleCategory(categoryId, true, context);
}
return SingleCategory(categorySlug, true, context);
}
public static LinkCategory SingleCategory(int categoryId, bool isActive, ISubtextContext context)
{
return SingleCategory(() => context.Repository.GetLinkCategory(categoryId, isActive), categoryId, context);
}
public static LinkCategory SingleCategory(string categoryName, bool isActive, ISubtextContext context)
{
string singleCategoryName = categoryName;
LinkCategory category = SingleCategory(() => context.Repository.GetLinkCategory(singleCategoryName, isActive),
categoryName, context);
if(category != null)
{
return category;
}
if(context.Blog.AutoFriendlyUrlEnabled)
{
string theCategoryName = categoryName;
categoryName = categoryName.Replace(FriendlyUrlSettings.Settings.SeparatingCharacter, " ");
return SingleCategory(() => context.Repository.GetLinkCategory(theCategoryName, isActive), categoryName,
context);
}
return null; //couldn't find category
}
private static LinkCategory SingleCategory<T>(Func<LinkCategory> retrievalDelegate, T categoryKey,
ISubtextContext context)
{
string key = string.Format(CultureInfo.InvariantCulture, CategoryKey, categoryKey, context.Blog.Id);
return context.Cache.GetOrInsert(key, retrievalDelegate);
}
public static ICollection<EntrySummary> GetPreviousNextEntry(int entryId, PostType postType, ISubtextContext context)
{
string cacheKey = string.Format("PrevNext:{0}:{1}", entryId, postType);
return context.Cache.GetOrInsertSliding(cacheKey, () => context.Repository.GetPreviousAndNextEntries(entryId, postType), null, LongDuration);
}
//TODO: This should only be called in one place total. And it needs to be tested.
public static Entry GetEntryFromRequest(bool allowRedirectToEntryName, ISubtextContext context)
{
string slug = context.RequestContext.GetSlugFromRequest();
if(!String.IsNullOrEmpty(slug))
{
return GetEntry(slug, context);
}
int? id = context.RequestContext.GetIdFromRequest();
if(id != null)
{
Entry entry = GetEntry(id.Value, context);
if(entry == null)
{
return null;
}
//TODO: Violation of SRP here!
//Second condition avoids infinite redirect loop. Should never happen.
if(allowRedirectToEntryName && entry.HasEntryName && !entry.EntryName.IsNumeric())
{
HttpResponseBase response = context.HttpContext.Response;
response.RedirectPermanent(context.UrlHelper.EntryUrl(entry).ToFullyQualifiedUrl(context.Blog).ToString());
}
return entry;
}
return null;
}
/// <summary>
/// Retrieves a single entry from the cache by the entry name.
/// If it is not in the cache, gets it from the database and
/// inserts it into the cache.
/// </summary>
public static Entry GetEntry(string entryName, ISubtextContext context)
{
Blog blog = context.Blog;
string key = string.Format(CultureInfo.InvariantCulture, EntryKeyName, entryName, blog.Id);
Func<Entry> retrieval = () => context.Repository.GetEntry(entryName, true /* activeOnly */, true /* includeCategories */);
var cachedEntry = context.Cache.GetOrInsert(key, retrieval, MediumDuration);
if(cachedEntry == null)
{
return null;
}
cachedEntry.Blog = blog;
return cachedEntry.DateSyndicated > blog.TimeZone.Now ? null : cachedEntry;
}
/// <summary>
/// Retrieves a single entry from the cache by the id.
/// If it is not in the cache, gets it from the database and
/// inserts it into the cache.
/// </summary>
public static Entry GetEntry(int entryId, ISubtextContext context)
{
string key = string.Format(CultureInfo.InvariantCulture, EntryKeyId, entryId, context.Blog.Id);
var entry = context.Cache.GetOrInsert(key, () => context.Repository.GetEntry(entryId, true /* activeOnly */, true /* includeCategories */));
if(entry == null)
{
return null;
}
entry.Blog = context.Blog;
return entry;
}
/// <summary>
/// Retrieves the current tags from the cache based on the ItemCount and
/// Blog Id. If it is not in the cache, it gets it from the database and
/// inserts it into the cache.
/// </summary>
public static IEnumerable<Tag> GetTopTags(int itemCount, ISubtextContext context)
{
string key = string.Format(CultureInfo.InvariantCulture, TagsKey, itemCount, context.Blog.Id);
return context.Cache.GetOrInsert(key, () => context.Repository.GetMostUsedTags(itemCount), LongDuration);
}
/// <summary>
/// Clears the comment cache.
/// </summary>
public static void ClearCommentCache(int entryId, ISubtextContext context)
{
string key = string.Format(CultureInfo.InvariantCulture, ParentCommentEntryKey, entryId, context.Blog.Id);
context.Cache.Remove(key);
}
/// <summary>
/// Returns all the feedback for the specified entry. Checks the cache first.
/// </summary>
public static ICollection<FeedbackItem> GetFeedback(Entry parentEntry, ISubtextContext context)
{
string key = GetFeedbackCacheKey(parentEntry, context);
return context.Cache.GetOrInsertSliding(key, () => context.Repository.GetFeedbackForEntry(parentEntry), null, LongDuration);
}
private static string GetFeedbackCacheKey(IIdentifiable parentEntry, ISubtextContext context)
{
return string.Format(CultureInfo.InvariantCulture, ParentCommentEntryKey, parentEntry.Id, context.Blog.Id);
}
public static void InvalidateFeedback(IIdentifiable parentEntry, ISubtextContext context)
{
string key = GetFeedbackCacheKey(parentEntry, context);
context.Cache.Remove(key);
}
public static void InsertDuration(this ICache cache, string key, object value, int duration, CacheDependency cacheDependency)
{
cache.Insert(key, value, cacheDependency, DateTime.Now.AddSeconds(duration), TimeSpan.Zero, CacheItemPriority.Normal, null);
}
public static void InsertDurationSliding(this ICache cache, string key, object value, CacheDependency cacheDependency, int slidingExpiration)
{
cache.Insert(key, value, cacheDependency, DateTime.MaxValue, TimeSpan.FromSeconds(slidingExpiration), CacheItemPriority.Normal, null);
}
}
}
| |
/*
* 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>
/// individual machine serving provisioning (block) data
/// </summary>
public partial class PVS_server : XenObject<PVS_server>
{
public PVS_server()
{
}
public PVS_server(string uuid,
string[] addresses,
long first_port,
long last_port,
XenRef<PVS_site> site)
{
this.uuid = uuid;
this.addresses = addresses;
this.first_port = first_port;
this.last_port = last_port;
this.site = site;
}
/// <summary>
/// Creates a new PVS_server from a Proxy_PVS_server.
/// </summary>
/// <param name="proxy"></param>
public PVS_server(Proxy_PVS_server proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(PVS_server update)
{
uuid = update.uuid;
addresses = update.addresses;
first_port = update.first_port;
last_port = update.last_port;
site = update.site;
}
internal void UpdateFromProxy(Proxy_PVS_server proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
addresses = proxy.addresses == null ? new string[] {} : (string [])proxy.addresses;
first_port = proxy.first_port == null ? 0 : long.Parse((string)proxy.first_port);
last_port = proxy.last_port == null ? 0 : long.Parse((string)proxy.last_port);
site = proxy.site == null ? null : XenRef<PVS_site>.Create(proxy.site);
}
public Proxy_PVS_server ToProxy()
{
Proxy_PVS_server result_ = new Proxy_PVS_server();
result_.uuid = (uuid != null) ? uuid : "";
result_.addresses = addresses;
result_.first_port = first_port.ToString();
result_.last_port = last_port.ToString();
result_.site = (site != null) ? site : "";
return result_;
}
/// <summary>
/// Creates a new PVS_server from a Hashtable.
/// </summary>
/// <param name="table"></param>
public PVS_server(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
addresses = Marshalling.ParseStringArray(table, "addresses");
first_port = Marshalling.ParseLong(table, "first_port");
last_port = Marshalling.ParseLong(table, "last_port");
site = Marshalling.ParseRef<PVS_site>(table, "site");
}
public bool DeepEquals(PVS_server other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._addresses, other._addresses) &&
Helper.AreEqual2(this._first_port, other._first_port) &&
Helper.AreEqual2(this._last_port, other._last_port) &&
Helper.AreEqual2(this._site, other._site);
}
public override string SaveChanges(Session session, string opaqueRef, PVS_server server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given PVS_server.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static PVS_server get_record(Session session, string _pvs_server)
{
return new PVS_server((Proxy_PVS_server)session.proxy.pvs_server_get_record(session.uuid, (_pvs_server != null) ? _pvs_server : "").parse());
}
/// <summary>
/// Get a reference to the PVS_server instance with the specified UUID.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PVS_server> get_by_uuid(Session session, string _uuid)
{
return XenRef<PVS_server>.Create(session.proxy.pvs_server_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Get the uuid field of the given PVS_server.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static string get_uuid(Session session, string _pvs_server)
{
return (string)session.proxy.pvs_server_get_uuid(session.uuid, (_pvs_server != null) ? _pvs_server : "").parse();
}
/// <summary>
/// Get the addresses field of the given PVS_server.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static string[] get_addresses(Session session, string _pvs_server)
{
return (string [])session.proxy.pvs_server_get_addresses(session.uuid, (_pvs_server != null) ? _pvs_server : "").parse();
}
/// <summary>
/// Get the first_port field of the given PVS_server.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static long get_first_port(Session session, string _pvs_server)
{
return long.Parse((string)session.proxy.pvs_server_get_first_port(session.uuid, (_pvs_server != null) ? _pvs_server : "").parse());
}
/// <summary>
/// Get the last_port field of the given PVS_server.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static long get_last_port(Session session, string _pvs_server)
{
return long.Parse((string)session.proxy.pvs_server_get_last_port(session.uuid, (_pvs_server != null) ? _pvs_server : "").parse());
}
/// <summary>
/// Get the site field of the given PVS_server.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static XenRef<PVS_site> get_site(Session session, string _pvs_server)
{
return XenRef<PVS_site>.Create(session.proxy.pvs_server_get_site(session.uuid, (_pvs_server != null) ? _pvs_server : "").parse());
}
/// <summary>
/// introduce new PVS server
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_addresses">IPv4 addresses of the server</param>
/// <param name="_first_port">first UDP port accepted by this server</param>
/// <param name="_last_port">last UDP port accepted by this server</param>
/// <param name="_site">PVS site this server is a part of</param>
public static XenRef<PVS_server> introduce(Session session, string[] _addresses, long _first_port, long _last_port, string _site)
{
return XenRef<PVS_server>.Create(session.proxy.pvs_server_introduce(session.uuid, _addresses, _first_port.ToString(), _last_port.ToString(), (_site != null) ? _site : "").parse());
}
/// <summary>
/// introduce new PVS server
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_addresses">IPv4 addresses of the server</param>
/// <param name="_first_port">first UDP port accepted by this server</param>
/// <param name="_last_port">last UDP port accepted by this server</param>
/// <param name="_site">PVS site this server is a part of</param>
public static XenRef<Task> async_introduce(Session session, string[] _addresses, long _first_port, long _last_port, string _site)
{
return XenRef<Task>.Create(session.proxy.async_pvs_server_introduce(session.uuid, _addresses, _first_port.ToString(), _last_port.ToString(), (_site != null) ? _site : "").parse());
}
/// <summary>
/// forget a PVS server
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static void forget(Session session, string _pvs_server)
{
session.proxy.pvs_server_forget(session.uuid, (_pvs_server != null) ? _pvs_server : "").parse();
}
/// <summary>
/// forget a PVS server
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static XenRef<Task> async_forget(Session session, string _pvs_server)
{
return XenRef<Task>.Create(session.proxy.async_pvs_server_forget(session.uuid, (_pvs_server != null) ? _pvs_server : "").parse());
}
/// <summary>
/// Return a list of all the PVS_servers known to the system.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PVS_server>> get_all(Session session)
{
return XenRef<PVS_server>.Create(session.proxy.pvs_server_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the PVS_server Records at once, in a single XML RPC call
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PVS_server>, PVS_server> get_all_records(Session session)
{
return XenRef<PVS_server>.Create<Proxy_PVS_server>(session.proxy.pvs_server_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// Experimental. First published in .
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// IPv4 addresses of this server
/// Experimental. First published in .
/// </summary>
public virtual string[] addresses
{
get { return _addresses; }
set
{
if (!Helper.AreEqual(value, _addresses))
{
_addresses = value;
Changed = true;
NotifyPropertyChanged("addresses");
}
}
}
private string[] _addresses;
/// <summary>
/// First UDP port accepted by this server
/// Experimental. First published in .
/// </summary>
public virtual long first_port
{
get { return _first_port; }
set
{
if (!Helper.AreEqual(value, _first_port))
{
_first_port = value;
Changed = true;
NotifyPropertyChanged("first_port");
}
}
}
private long _first_port;
/// <summary>
/// Last UDP port accepted by this server
/// Experimental. First published in .
/// </summary>
public virtual long last_port
{
get { return _last_port; }
set
{
if (!Helper.AreEqual(value, _last_port))
{
_last_port = value;
Changed = true;
NotifyPropertyChanged("last_port");
}
}
}
private long _last_port;
/// <summary>
/// PVS site this server is part of
/// Experimental. First published in .
/// </summary>
public virtual XenRef<PVS_site> site
{
get { return _site; }
set
{
if (!Helper.AreEqual(value, _site))
{
_site = value;
Changed = true;
NotifyPropertyChanged("site");
}
}
}
private XenRef<PVS_site> _site;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Versioning;
namespace System.Data.Common
{
internal class DbConnectionOptions
{
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is easier to verify correctness
// without the risk of the objects of the class being modified during execution.
#if DEBUG
private const string ConnectionStringPattern = // may not contain embedded null except trailing last value
"([\\s;]*" // leading whitespace and extra semicolons
+ "(?![\\s;])" // key does not start with space or semicolon
+ "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)" // allow any visible character for keyname except '=' which must quoted as '=='
+ "\\s*=(?!=)\\s*" // the equal sign divides the key and value parts
+ "(?<value>"
+ "(\"([^\"\u0000]|\"\")*\")" // double quoted string, " must be quoted as ""
+ "|"
+ "('([^'\u0000]|'')*')" // single quoted string, ' must be quoted as ''
+ "|"
+ "((?![\"'\\s])" // unquoted value must not start with " or ' or space, would also like = but too late to change
+ "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
+ "(?<![\"']))" // unquoted value must not stop with " or '
+ ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
+ ")*" // repeat the key-value pair
+ "[\\s;]*[\u0000\\s]*" // traling whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
;
private static readonly Regex s_connectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture);
#endif
private const string ConnectionStringValidKeyPattern = "^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$"; // key not allowed to start with semi-colon or space or contain non-visible characters or end with space
private const string ConnectionStringValidValuePattern = "^[^\u0000]*$"; // value not allowed to contain embedded null
private const string ConnectionStringQuoteValuePattern = "^[^\"'=;\\s\\p{Cc}]*$"; // generally do not quote the value if it matches the pattern
internal const string DataDirectory = "|datadirectory|";
private static readonly Regex s_connectionStringValidKeyRegex = new Regex(ConnectionStringValidKeyPattern);
private static readonly Regex s_connectionStringValidValueRegex = new Regex(ConnectionStringValidValuePattern);
private static readonly Regex s_connectionStringQuoteValueRegex = new Regex(ConnectionStringQuoteValuePattern);
// connection string common keywords
private static class KEY
{
internal const string Integrated_Security = "integrated security";
internal const string Password = "password";
internal const string Persist_Security_Info = "persist security info";
internal const string User_ID = "user id";
};
// known connection string common synonyms
private static class SYNONYM
{
internal const string Pwd = "pwd";
internal const string UID = "uid";
};
private readonly string _usersConnectionString;
private readonly Hashtable _parsetable;
internal readonly NameValuePair KeyChain;
internal readonly bool HasPasswordKeyword;
// synonyms hashtable is meant to be read-only translation of parsed string
// keywords/synonyms to a known keyword string
public DbConnectionOptions(string connectionString, Hashtable synonyms)
{
_parsetable = new Hashtable();
_usersConnectionString = ((null != connectionString) ? connectionString : "");
// first pass on parsing, initial syntax check
if (0 < _usersConnectionString.Length)
{
KeyChain = ParseInternal(_parsetable, _usersConnectionString, true, synonyms, false);
HasPasswordKeyword = (_parsetable.ContainsKey(KEY.Password) || _parsetable.ContainsKey(SYNONYM.Pwd));
}
}
protected DbConnectionOptions(DbConnectionOptions connectionOptions)
{ // Clone used by SqlConnectionString
_usersConnectionString = connectionOptions._usersConnectionString;
HasPasswordKeyword = connectionOptions.HasPasswordKeyword;
_parsetable = connectionOptions._parsetable;
KeyChain = connectionOptions.KeyChain;
}
internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string keyValue, bool useOdbcRules)
{
ADP.CheckArgumentNull(builder, "builder");
ADP.CheckArgumentLength(keyName, "keyName");
if ((null == keyName) || !s_connectionStringValidKeyRegex.IsMatch(keyName))
{
throw ADP.InvalidKeyname(keyName);
}
if ((null != keyValue) && !IsValueValidInternal(keyValue))
{
throw ADP.InvalidValue(keyName);
}
if ((0 < builder.Length) && (';' != builder[builder.Length - 1]))
{
builder.Append(";");
}
if (useOdbcRules)
{
builder.Append(keyName);
}
else
{
builder.Append(keyName.Replace("=", "=="));
}
builder.Append("=");
if (null != keyValue)
{ // else <keyword>=;
if (s_connectionStringQuoteValueRegex.IsMatch(keyValue))
{
// <value> -> <value>
builder.Append(keyValue);
}
else if ((-1 != keyValue.IndexOf('\"')) && (-1 == keyValue.IndexOf('\'')))
{
// <val"ue> -> <'val"ue'>
builder.Append('\'');
builder.Append(keyValue);
builder.Append('\'');
}
else
{
// <val'ue> -> <"val'ue">
// <=value> -> <"=value">
// <;value> -> <";value">
// < value> -> <" value">
// <va lue> -> <"va lue">
// <va'"lue> -> <"va'""lue">
builder.Append('\"');
builder.Append(keyValue.Replace("\"", "\"\""));
builder.Append('\"');
}
}
}
static private string GetKeyName(StringBuilder buffer)
{
int count = buffer.Length;
while ((0 < count) && Char.IsWhiteSpace(buffer[count - 1]))
{
count--; // trailing whitespace
}
return buffer.ToString(0, count).ToLowerInvariant();
}
static private string GetKeyValue(StringBuilder buffer, bool trimWhitespace)
{
int count = buffer.Length;
int index = 0;
if (trimWhitespace)
{
while ((index < count) && Char.IsWhiteSpace(buffer[index]))
{
index++; // leading whitespace
}
while ((0 < count) && Char.IsWhiteSpace(buffer[count - 1]))
{
count--; // trailing whitespace
}
}
return buffer.ToString(index, count - index);
}
// transistion states used for parsing
private enum ParserState
{
NothingYet = 1, //start point
Key,
KeyEqual,
KeyEnd,
UnquotedValue,
DoubleQuoteValue,
DoubleQuoteValueQuote,
SingleQuoteValue,
SingleQuoteValueQuote,
BraceQuoteValue,
BraceQuoteValueQuote,
QuotedValueEnd,
NullTermination,
};
static internal int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string keyname, out string keyvalue)
{
int startposition = currentPosition;
buffer.Length = 0;
keyname = null;
keyvalue = null;
char currentChar = '\0';
ParserState parserState = ParserState.NothingYet;
int length = connectionString.Length;
for (; currentPosition < length; ++currentPosition)
{
currentChar = connectionString[currentPosition];
switch (parserState)
{
case ParserState.NothingYet: // [\\s;]*
if ((';' == currentChar) || Char.IsWhiteSpace(currentChar))
{
continue;
}
if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; }
if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
startposition = currentPosition;
if ('=' != currentChar)
{
parserState = ParserState.Key;
break;
}
else
{
parserState = ParserState.KeyEqual;
continue;
}
case ParserState.Key: // (?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)
if ('=' == currentChar) { parserState = ParserState.KeyEqual; continue; }
if (Char.IsWhiteSpace(currentChar)) { break; }
if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.KeyEqual: // \\s*=(?!=)\\s*
if (!useOdbcRules && '=' == currentChar) { parserState = ParserState.Key; break; }
keyname = GetKeyName(buffer);
if (ADP.IsEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); }
buffer.Length = 0;
parserState = ParserState.KeyEnd;
goto case ParserState.KeyEnd;
case ParserState.KeyEnd:
if (Char.IsWhiteSpace(currentChar)) { continue; }
if (useOdbcRules)
{
if ('{' == currentChar) { parserState = ParserState.BraceQuoteValue; break; }
}
else
{
if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; continue; }
if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; continue; }
}
if (';' == currentChar) { goto ParserExit; }
if ('\0' == currentChar) { goto ParserExit; }
if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
parserState = ParserState.UnquotedValue;
break;
case ParserState.UnquotedValue: // "((?![\"'\\s])" + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" + "(?<![\"']))"
if (Char.IsWhiteSpace(currentChar)) { break; }
if (Char.IsControl(currentChar) || ';' == currentChar) { goto ParserExit; }
break;
case ParserState.DoubleQuoteValue: // "(\"([^\"\u0000]|\"\")*\")"
if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValueQuote; continue; }
if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.DoubleQuoteValueQuote:
if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.SingleQuoteValue: // "('([^'\u0000]|'')*')"
if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValueQuote; continue; }
if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.SingleQuoteValueQuote:
if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.BraceQuoteValue: // "(\\{([^\\}\u0000]|\\}\\})*\\})"
if ('}' == currentChar) { parserState = ParserState.BraceQuoteValueQuote; break; }
if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.BraceQuoteValueQuote:
if ('}' == currentChar) { parserState = ParserState.BraceQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.QuotedValueEnd:
if (Char.IsWhiteSpace(currentChar)) { continue; }
if (';' == currentChar) { goto ParserExit; }
if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; }
throw ADP.ConnectionStringSyntax(startposition); // unbalanced single quote
case ParserState.NullTermination: // [\\s;\u0000]*
if ('\0' == currentChar) { continue; }
if (Char.IsWhiteSpace(currentChar)) { continue; }
throw ADP.ConnectionStringSyntax(currentPosition);
default:
throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState1);
}
buffer.Append(currentChar);
}
ParserExit:
switch (parserState)
{
case ParserState.Key:
case ParserState.DoubleQuoteValue:
case ParserState.SingleQuoteValue:
case ParserState.BraceQuoteValue:
// keyword not found/unbalanced double/single quote
throw ADP.ConnectionStringSyntax(startposition);
case ParserState.KeyEqual:
// equal sign at end of line
keyname = GetKeyName(buffer);
if (ADP.IsEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.UnquotedValue:
// unquoted value at end of line
keyvalue = GetKeyValue(buffer, true);
char tmpChar = keyvalue[keyvalue.Length - 1];
if (!useOdbcRules && (('\'' == tmpChar) || ('"' == tmpChar)))
{
throw ADP.ConnectionStringSyntax(startposition); // unquoted value must not end in quote, except for odbc
}
break;
case ParserState.DoubleQuoteValueQuote:
case ParserState.SingleQuoteValueQuote:
case ParserState.BraceQuoteValueQuote:
case ParserState.QuotedValueEnd:
// quoted value at end of line
keyvalue = GetKeyValue(buffer, false);
break;
case ParserState.NothingYet:
case ParserState.KeyEnd:
case ParserState.NullTermination:
// do nothing
break;
default:
throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState2);
}
if ((';' == currentChar) && (currentPosition < connectionString.Length))
{
currentPosition++;
}
return currentPosition;
}
static private bool IsValueValidInternal(string keyvalue)
{
if (null != keyvalue)
{
#if DEBUG
bool compValue = s_connectionStringValidValueRegex.IsMatch(keyvalue);
Debug.Assert((-1 == keyvalue.IndexOf('\u0000')) == compValue, "IsValueValid mismatch with regex");
#endif
return (-1 == keyvalue.IndexOf('\u0000'));
}
return true;
}
static private bool IsKeyNameValid(string keyname)
{
if (null != keyname)
{
#if DEBUG
bool compValue = s_connectionStringValidKeyRegex.IsMatch(keyname);
Debug.Assert(((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000'))) == compValue, "IsValueValid mismatch with regex");
#endif
return ((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000')));
}
return false;
}
#if DEBUG
private static Hashtable SplitConnectionString(string connectionString, Hashtable synonyms, bool firstKey)
{
Hashtable parsetable = new Hashtable();
Debug.Assert(!firstKey, "ODBC rules are not supported in CoreCLR");
Regex parser = s_connectionStringRegex;
const int KeyIndex = 1, ValueIndex = 2;
Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index");
Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index");
if (null != connectionString)
{
Match match = parser.Match(connectionString);
if (!match.Success || (match.Length != connectionString.Length))
{
throw ADP.ConnectionStringSyntax(match.Length);
}
int indexValue = 0;
CaptureCollection keyvalues = match.Groups[ValueIndex].Captures;
foreach (Capture keypair in match.Groups[KeyIndex].Captures)
{
string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLowerInvariant();
string keyvalue = keyvalues[indexValue++].Value;
if (0 < keyvalue.Length)
{
if (!firstKey)
{
switch (keyvalue[0])
{
case '\"':
keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\"\"", "\"");
break;
case '\'':
keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\'\'", "\'");
break;
default:
break;
}
}
}
else
{
keyvalue = null;
}
string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
if (!IsKeyNameValid(realkeyname))
{
throw ADP.KeywordNotSupported(keyname);
}
if (!firstKey || !parsetable.ContainsKey(realkeyname))
{
parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
}
}
}
return parsetable;
}
private static void ParseComparison(Hashtable parsetable, string connectionString, Hashtable synonyms, bool firstKey, Exception e)
{
try
{
Hashtable parsedvalues = SplitConnectionString(connectionString, synonyms, firstKey);
foreach (DictionaryEntry entry in parsedvalues)
{
string keyname = (string)entry.Key;
string value1 = (string)entry.Value;
string value2 = (string)parsetable[keyname];
Debug.Assert(parsetable.Contains(keyname), "ParseInternal code vs. regex mismatch keyname <" + keyname + ">");
Debug.Assert(value1 == value2, "ParseInternal code vs. regex mismatch keyvalue <" + value1 + "> <" + value2 + ">");
}
}
catch (ArgumentException f)
{
if (null != e)
{
string msg1 = e.Message;
string msg2 = f.Message;
const string KeywordNotSupportedMessagePrefix = "Keyword not supported:";
const string WrongFormatMessagePrefix = "Format of the initialization string";
bool isEquivalent = (msg1 == msg2);
if (!isEquivalent)
{
// We also accept cases were Regex parser (debug only) reports "wrong format" and
// retail parsing code reports format exception in different location or "keyword not supported"
if (msg2.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal))
{
if (msg1.StartsWith(KeywordNotSupportedMessagePrefix, StringComparison.Ordinal) || msg1.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal))
{
isEquivalent = true;
}
}
}
Debug.Assert(isEquivalent, "ParseInternal code vs regex message mismatch: <" + msg1 + "> <" + msg2 + ">");
}
else
{
Debug.Assert(false, "ParseInternal code vs regex throw mismatch " + f.Message);
}
e = null;
}
if (null != e)
{
Debug.Assert(false, "ParseInternal code threw exception vs regex mismatch");
}
}
#endif
private static NameValuePair ParseInternal(Hashtable parsetable, string connectionString, bool buildChain, Hashtable synonyms, bool firstKey)
{
Debug.Assert(null != connectionString, "null connectionstring");
StringBuilder buffer = new StringBuilder();
NameValuePair localKeychain = null, keychain = null;
#if DEBUG
try
{
#endif
int nextStartPosition = 0;
int endPosition = connectionString.Length;
while (nextStartPosition < endPosition)
{
int startPosition = nextStartPosition;
string keyname, keyvalue;
nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue);
if (ADP.IsEmpty(keyname))
{
break;
}
#if DEBUG
Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname");
Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue");
#endif
string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
if (!IsKeyNameValid(realkeyname))
{
throw ADP.KeywordNotSupported(keyname);
}
if (!firstKey || !parsetable.Contains(realkeyname))
{
parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
}
if (null != localKeychain)
{
localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
}
else if (buildChain)
{ // first time only - don't contain modified chain from UDL file
keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
}
}
#if DEBUG
}
catch (ArgumentException e)
{
ParseComparison(parsetable, connectionString, synonyms, firstKey, e);
throw;
}
ParseComparison(parsetable, connectionString, synonyms, firstKey, null);
#endif
return keychain;
}
internal static void ValidateKeyValuePair(string keyword, string value)
{
if ((null == keyword) || !s_connectionStringValidKeyRegex.IsMatch(keyword))
{
throw ADP.InvalidKeyname(keyword);
}
if ((null != value) && !s_connectionStringValidValueRegex.IsMatch(value))
{
throw ADP.InvalidValue(keyword);
}
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace Irony.Parsing {
#region About compound terminals
/*
As it turns out, many terminal types in real-world languages have 3-part structure: prefix-body-suffix
The body is essentially the terminal "value", while prefix and suffix are used to specify additional
information (options), while not being a part of the terminal itself.
For example:
1. c# numbers, may have 0x prefix for hex representation, and suffixes specifying
the exact data type of the literal (f, l, m, etc)
2. c# string may have "@" prefix which disables escaping inside the string
3. c# identifiers may have "@" prefix and escape sequences inside - just like strings
4. Python string may have "u" and "r" prefixes, "r" working the same way as @ in c# strings
5. VB string literals may have "c" suffix identifying that the literal is a character, not a string
6. VB number literals and identifiers may have suffixes identifying data type
So it seems like all these terminals have the format "prefix-body-suffix".
The CompoundTerminalBase base class implements base functionality supporting this multi-part structure.
The IdentifierTerminal, NumberLiteral and StringLiteral classes inherit from this base class.
The methods in TerminalFactory static class demonstrate that with this architecture we can define the whole
variety of terminals for c#, Python and VB.NET languages.
*/
#endregion
public class EscapeTable : Dictionary<char, char> { }
public abstract class CompoundTerminalBase : Terminal {
#region Nested classes
protected class ScanFlagTable : Dictionary<string, short> { }
protected class TypeCodeTable : Dictionary<string, TypeCode[]> { }
public class CompoundTokenDetails {
public string Prefix;
public string Body;
public string Suffix;
public string Sign;
public short Flags; //need to be short, because we need to save it in Scanner state for Vs integration
public string Error;
public TypeCode[] TypeCodes;
public string ExponentSymbol; //exponent symbol for Number literal
public string StartSymbol; //string start and end symbols
public string EndSymbol;
public object Value;
//partial token info, used by VS integration
public bool PartialOk;
public bool IsPartial;
public bool PartialContinues;
public byte SubTypeIndex; //used for string literal kind
//Flags helper method
public bool IsSet(short flag) {
return (Flags & flag) != 0;
}
public string Text { get { return Prefix + Body + Suffix; } }
}
#endregion
#region constructors and initialization
protected CompoundTerminalBase(string name) : this(name, TermFlags.None) { }
protected CompoundTerminalBase(string name, TermFlags flags) : base(name) {
SetFlag(flags);
Escapes = GetDefaultEscapes();
}
protected void AddPrefixFlag(string prefix, short flags) {
PrefixFlags.Add(prefix, flags);
Prefixes.Add(prefix);
}
public void AddSuffix(string suffix, params TypeCode[] typeCodes) {
SuffixTypeCodes.Add(suffix, typeCodes);
Suffixes.Add(suffix);
}
#endregion
#region public Properties/Fields
public Char EscapeChar = '\\';
public EscapeTable Escapes = new EscapeTable();
//Case sensitivity for prefixes and suffixes
public bool CaseSensitivePrefixesSuffixes = false;
#endregion
#region private fields
protected readonly ScanFlagTable PrefixFlags = new ScanFlagTable();
protected readonly TypeCodeTable SuffixTypeCodes = new TypeCodeTable();
protected StringList Prefixes = new StringList();
protected StringList Suffixes = new StringList();
CharHashSet _prefixesFirsts; //first chars of all prefixes, for fast prefix detection
CharHashSet _suffixesFirsts; //first chars of all suffixes, for fast suffix detection
#endregion
#region overrides: Init, TryMatch
public override void Init(GrammarData grammarData) {
base.Init(grammarData);
//collect all suffixes, prefixes in lists and create sets of first chars for both
Prefixes.Sort(StringList.LongerFirst);
Suffixes.Sort(StringList.LongerFirst);
_prefixesFirsts = new CharHashSet(CaseSensitivePrefixesSuffixes);
_suffixesFirsts = new CharHashSet(CaseSensitivePrefixesSuffixes);
foreach (string pfx in Prefixes)
_prefixesFirsts.Add(pfx[0]);
foreach (string sfx in Suffixes)
_suffixesFirsts.Add(sfx[0]);
}//method
public override IList<string> GetFirsts() {
return Prefixes;
}
public override Token TryMatch(ParsingContext context, ISourceStream source) {
Token token;
//Try quick parse first, but only if we're not continuing
if (context.VsLineScanState.Value == 0) {
token = QuickParse(context, source);
if (token != null) return token;
source.PreviewPosition = source.Position; //revert the position
}
CompoundTokenDetails details = new CompoundTokenDetails();
InitDetails(context, details);
if (context.VsLineScanState.Value == 0)
ReadPrefix(source, details);
if (!ReadBody(source, details))
return null;
if (details.Error != null)
return context.CreateErrorToken(details.Error);
if (details.IsPartial) {
details.Value = details.Body;
} else {
ReadSuffix(source, details);
if(!ConvertValue(details)) {
if (string.IsNullOrEmpty(details.Error))
details.Error = Resources.ErrInvNumber;
return context.CreateErrorToken(details.Error); // "Failed to convert the value: {0}"
}
}
token = CreateToken(context, source, details);
if (details.IsPartial) {
//Save terminal state so we can continue
context.VsLineScanState.TokenSubType = (byte)details.SubTypeIndex;
context.VsLineScanState.TerminalFlags = (short)details.Flags;
context.VsLineScanState.TerminalIndex = this.MultilineIndex;
} else
context.VsLineScanState.Value = 0;
return token;
}
protected virtual Token CreateToken(ParsingContext context, ISourceStream source, CompoundTokenDetails details) {
var token = source.CreateToken(this.OutputTerminal, details.Value);
token.Details = details;
if (details.IsPartial)
token.Flags |= TokenFlags.IsIncomplete;
return token;
}
protected virtual void InitDetails(ParsingContext context, CompoundTokenDetails details) {
details.PartialOk = (context.Mode == ParseMode.VsLineScan);
details.PartialContinues = (context.VsLineScanState.Value != 0);
}
protected virtual Token QuickParse(ParsingContext context, ISourceStream source) {
return null;
}
protected virtual void ReadPrefix(ISourceStream source, CompoundTokenDetails details) {
if (!_prefixesFirsts.Contains(source.PreviewChar))
return;
var comparisonType = CaseSensitivePrefixesSuffixes ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase;
foreach (string pfx in Prefixes) {
// Prefixes are usually case insensitive, even if language is case-sensitive. So we cannot use source.MatchSymbol here,
// we need case-specific comparison
if (string.Compare(source.Text, source.PreviewPosition, pfx, 0, pfx.Length, comparisonType) != 0)
continue;
//We found prefix
details.Prefix = pfx;
source.PreviewPosition += pfx.Length;
//Set flag from prefix
short pfxFlags;
if (!string.IsNullOrEmpty(details.Prefix) && PrefixFlags.TryGetValue(details.Prefix, out pfxFlags))
details.Flags |= (short) pfxFlags;
return;
}//foreach
}//method
protected virtual bool ReadBody(ISourceStream source, CompoundTokenDetails details) {
return false;
}
protected virtual void ReadSuffix(ISourceStream source, CompoundTokenDetails details) {
if (!_suffixesFirsts.Contains(source.PreviewChar)) return;
var comparisonType = CaseSensitivePrefixesSuffixes ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase;
foreach (string sfx in Suffixes) {
//Suffixes are usually case insensitive, even if language is case-sensitive. So we cannot use source.MatchSymbol here,
// we need case-specific comparison
if (string.Compare(source.Text, source.PreviewPosition, sfx, 0, sfx.Length, comparisonType) != 0)
continue;
//We found suffix
details.Suffix = sfx;
source.PreviewPosition += sfx.Length;
//Set TypeCode from suffix
TypeCode[] codes;
if (!string.IsNullOrEmpty(details.Suffix) && SuffixTypeCodes.TryGetValue(details.Suffix, out codes))
details.TypeCodes = codes;
return;
}//foreach
}//method
protected virtual bool ConvertValue(CompoundTokenDetails details) {
details.Value = details.Body;
return false;
}
#endregion
#region utils: GetDefaultEscapes
public static EscapeTable GetDefaultEscapes() {
EscapeTable escapes = new EscapeTable();
escapes.Add('a', '\u0007');
escapes.Add('b', '\b');
escapes.Add('t', '\t');
escapes.Add('n', '\n');
escapes.Add('v', '\v');
escapes.Add('f', '\f');
escapes.Add('r', '\r');
escapes.Add('"', '"');
escapes.Add('\'', '\'');
escapes.Add('\\', '\\');
escapes.Add(' ', ' ');
escapes.Add('\n', '\n'); //this is a special escape of the linebreak itself,
// when string ends with "\" char and continues on the next line
return escapes;
}
#endregion
}//class
}//namespace
| |
//
// CropEditor.cs
//
// Author:
// Ruben Vermeersch <[email protected]>
//
// Copyright (C) 2008-2010 Novell, Inc.
// Copyright (C) 2008, 2010 Ruben Vermeersch
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using FSpot;
using FSpot.Settings;
using FSpot.UI.Dialog;
using FSpot.Utils;
using Hyena;
using Gdk;
using Gtk;
using Mono.Unix;
namespace FSpot.Editors
{
class CropEditor : Editor
{
TreeStore constraints_store;
ComboBox constraints_combo;
public enum ConstraintType {
Normal,
AddCustom,
SameAsPhoto
}
List<SelectionRatioDialog.SelectionConstraint> custom_constraints;
static SelectionRatioDialog.SelectionConstraint [] default_constraints = {
new SelectionRatioDialog.SelectionConstraint (Catalog.GetString ("4 x 3 (Book)"), 4.0 / 3.0),
new SelectionRatioDialog.SelectionConstraint (Catalog.GetString ("4 x 6 (Postcard)"), 6.0 / 4.0),
new SelectionRatioDialog.SelectionConstraint (Catalog.GetString ("5 x 7 (L, 2L)"), 7.0 / 5.0),
new SelectionRatioDialog.SelectionConstraint (Catalog.GetString ("8 x 10"), 10.0 / 8.0),
new SelectionRatioDialog.SelectionConstraint (Catalog.GetString ("Square"), 1.0)
};
public CropEditor () : base (Catalog.GetString ("Crop"), "crop")
{
NeedsSelection = true;
Preferences.SettingChanged += OnPreferencesChanged;
Initialized += delegate { State.PhotoImageView.PhotoChanged += UpdateSelectionCombo; };
}
void OnPreferencesChanged (object sender, NotifyEventArgs args)
{
LoadPreference (args.Key);
}
void LoadPreference (string key)
{
switch (key) {
case Preferences.CustomCropRatios:
custom_constraints = new List<SelectionRatioDialog.SelectionConstraint> ();
if (Preferences.Get<string[]> (key) != null) {
XmlSerializer serializer = new XmlSerializer (typeof(SelectionRatioDialog.SelectionConstraint));
foreach (string xml in Preferences.Get<string[]> (key))
custom_constraints.Add ((SelectionRatioDialog.SelectionConstraint)serializer.Deserialize (new StringReader (xml)));
}
PopulateConstraints ();
break;
}
}
public override Widget ConfigurationWidget ()
{
VBox vbox = new VBox ();
Label info = new Label (Catalog.GetString ("Select the area that needs cropping."));
constraints_combo = new ComboBox ();
CellRendererText constraint_name_cell = new CellRendererText ();
CellRendererPixbuf constraint_pix_cell = new CellRendererPixbuf ();
constraints_combo.PackStart (constraint_name_cell, true);
constraints_combo.PackStart (constraint_pix_cell, false);
constraints_combo.SetCellDataFunc (constraint_name_cell, new CellLayoutDataFunc (ConstraintNameCellFunc));
constraints_combo.SetCellDataFunc (constraint_pix_cell, new CellLayoutDataFunc (ConstraintPixCellFunc));
constraints_combo.Changed += HandleConstraintsComboChanged;
// FIXME: need tooltip Catalog.GetString ("Constrain the aspect ratio of the selection")
LoadPreference (Preferences.CustomCropRatios);
vbox.Add (info);
vbox.Add (constraints_combo);
return vbox;
}
void PopulateConstraints ()
{
constraints_store = new TreeStore (typeof (string), typeof (string), typeof (double), typeof (ConstraintType));
constraints_combo.Model = constraints_store;
constraints_store.AppendValues (null, Catalog.GetString ("No Constraint"), 0.0, ConstraintType.Normal);
constraints_store.AppendValues (null, Catalog.GetString ("Same as photo"), 0.0, ConstraintType.SameAsPhoto);
foreach (SelectionRatioDialog.SelectionConstraint constraint in custom_constraints)
constraints_store.AppendValues (null, constraint.Label, constraint.XyRatio, ConstraintType.Normal);
foreach (SelectionRatioDialog.SelectionConstraint constraint in default_constraints)
constraints_store.AppendValues (null, constraint.Label, constraint.XyRatio, ConstraintType.Normal);
constraints_store.AppendValues (Stock.Edit, Catalog.GetString ("Custom Ratios..."), 0.0, ConstraintType.AddCustom);
constraints_combo.Active = 0;
}
void UpdateSelectionCombo (object sender, EventArgs e)
{
if (!StateInitialized || constraints_combo == null)
// Don't bomb out on instant-apply.
return;
//constraints_combo.Active = 0;
TreeIter iter;
if (constraints_combo.GetActiveIter (out iter)) {
if (((ConstraintType)constraints_store.GetValue (iter, 3)) == ConstraintType.SameAsPhoto)
constraints_combo.Active = 0;
}
}
void HandleConstraintsComboChanged (object o, EventArgs e)
{
if (State.PhotoImageView == null) {
Log.Debug ("PhotoImageView is null");
return;
}
TreeIter iter;
if (constraints_combo.GetActiveIter (out iter)) {
double ratio = ((double)constraints_store.GetValue (iter, 2));
ConstraintType type = ((ConstraintType)constraints_store.GetValue (iter, 3));
switch (type) {
case ConstraintType.Normal:
State.PhotoImageView.SelectionXyRatio = ratio;
break;
case ConstraintType.AddCustom:
SelectionRatioDialog dialog = new SelectionRatioDialog ();
dialog.Run ();
break;
case ConstraintType.SameAsPhoto:
try {
Pixbuf pb = State.PhotoImageView.CompletePixbuf ();
State.PhotoImageView.SelectionXyRatio = (double)pb.Width / (double)pb.Height;
} catch (System.Exception ex) {
Log.WarningFormat ("Exception in selection ratio's: {0}", ex);
State.PhotoImageView.SelectionXyRatio = 0;
}
break;
default:
State.PhotoImageView.SelectionXyRatio = 0;
break;
}
}
}
void ConstraintNameCellFunc (CellLayout cell_layout, CellRenderer cell, TreeModel tree_model, TreeIter iter)
{
string name = (string)tree_model.GetValue (iter, 1);
(cell as CellRendererText).Text = name;
}
void ConstraintPixCellFunc (CellLayout cell_layout, CellRenderer cell, TreeModel tree_model, TreeIter iter)
{
string stockname = (string)tree_model.GetValue (iter, 0);
if (stockname != null)
(cell as CellRendererPixbuf).Pixbuf = GtkUtil.TryLoadIcon (FSpotConfiguration.IconTheme, stockname, 16, (Gtk.IconLookupFlags)0);
else
(cell as CellRendererPixbuf).Pixbuf = null;
}
protected override Pixbuf Process (Pixbuf input, Cms.Profile input_profile)
{
Rectangle selection = FSpot.Utils.PixbufUtils.TransformOrientation ((int)State.PhotoImageView.PixbufOrientation <= 4 ? input.Width : input.Height,
(int)State.PhotoImageView.PixbufOrientation <= 4 ? input.Height : input.Width,
State.Selection, State.PhotoImageView.PixbufOrientation);
Pixbuf edited = new Pixbuf (input.Colorspace,
input.HasAlpha, input.BitsPerSample,
selection.Width, selection.Height);
input.CopyArea (selection.X, selection.Y,
selection.Width, selection.Height, edited, 0, 0);
return edited;
}
}
}
| |
// This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
// PVS-settings
// PVS-settings end
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace TimetableK
{
class Route
{
public int num;
public int starttime;
public int endtime;
public int interval;
public List<int> stations;
public Route(int n, int s, int e, int i, List<int> st)
{
num = n;
starttime = s;
endtime = e;
interval = i;
stations = st;
}
}
class Schedule : IComparable<Schedule>
{
public int num;
public int dest;
public int time;
public Schedule(int n, int d, int t)
{
num = n;
dest = d;
time = t;
}
public int CompareTo(Schedule another)
{
return this.time - another.time;
}
}
class Program
{
static Dictionary<string, int> stkeyByName;
static List<string> stnameByKey;
static List<Dictionary<int, int>> stDist;
static Dictionary<int, Route> routesByNum;
static List<Route> routesStorage;
static List<List<Route>> routesByStkey;
static void ReadEx(int line)
{
Console.WriteLine("Incorrect format at {0} line", line);
Console.WriteLine("Press any key to exit . . .");
Console.ReadKey(true);
Environment.Exit(1);
}
static List<Schedule> GetScheduleBySt(int station, DateTime time)
{
List<Schedule> result = new List<Schedule>();
List<int> st;
Route rt;
for (int i = 0; i < routesByStkey[station].Count; ++i)
{
int t = time.Hour * 60 + time.Minute;
rt = routesByStkey[station][i];
st = rt.stations;
int pos = st.FindIndex(x => x == station);
int t1 = 0, t2 = 0;
for (int j = 0; j < pos; ++j)
t1 += stDist[st[j]][st[j + 1]];
for (int j = st.Count - 1; j > pos; --j)
t2 += stDist[st[j]][st[j - 1]];
int tt = t - t1;
#region
if (pos < st.Count - 1)
{
if (tt >= rt.starttime && tt <= rt.endtime)
{
result.Add(new Schedule(rt.num, st[st.Count - 1], rt.interval - (tt - rt.starttime + rt.interval - 1) % rt.interval - 1));
}
else if ((tt += 24 * 60) >= rt.starttime && tt <= rt.endtime)
{
result.Add(new Schedule(rt.num, st[st.Count - 1], rt.interval - (tt - rt.starttime + rt.interval - 1) % rt.interval - 1));
}
else
{
tt -= 24 * 60;
if (tt > rt.starttime)
result.Add(new Schedule(rt.num, st[st.Count - 1], rt.starttime + 24 * 60 - tt));
else
result.Add(new Schedule(rt.num, st[st.Count - 1], rt.starttime - tt));
}
}
#endregion
tt = t - t2;
#region
if (pos > 0)
{
if (tt >= rt.starttime && tt <= rt.endtime)
{
result.Add(new Schedule(rt.num, st[0], rt.interval - (tt - rt.starttime + rt.interval - 1) % rt.interval - 1));
}
else if ((tt += 24 * 60) >= rt.starttime && tt <= rt.endtime)
{
result.Add(new Schedule(rt.num, st[0], rt.interval - (tt - rt.starttime + rt.interval - 1) % rt.interval - 1));
}
else
{
tt -= 24 * 60;
if (tt > rt.starttime)
result.Add(new Schedule(rt.num, st[0], rt.starttime + 24 * 60 - tt));
else
result.Add(new Schedule(rt.num, st[0], rt.starttime - tt));
}
}
#endregion
}
result.Sort();
return result;
}
static int GetData()
{
StreamReader filestream = new StreamReader( "../../routes.txt");
stkeyByName = new Dictionary<string, int>();
stnameByKey = new List<string>();
stDist = new List<Dictionary<int, int>>();
routesByNum = new Dictionary<int, Route>();
routesStorage = new List<Route>();
routesByStkey = new List<List<Route>>();
string line;
int l = 1;
while ((line = filestream.ReadLine()) != null && line.StartsWith("//")) ;
try
{
string[] parse = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int m = Convert.ToInt32(parse[0]);
int r = Convert.ToInt32(parse[1]);
++l;
#region
for (int i = 0; i < m; ++i, ++l)
{
line = filestream.ReadLine();
if (line.StartsWith("//"))
{
--i;
--l;
continue;
}
parse = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (parse.Length != 3)
ReadEx(l);
if (!stkeyByName.ContainsKey(parse[0]))
{
stnameByKey.Add(parse[0]);
stkeyByName.Add(parse[0], stnameByKey.Count - 1);
stDist.Add(new Dictionary<int, int>());
routesByStkey.Add(new List<Route>());
}
if (!stkeyByName.ContainsKey(parse[1]))
{
stnameByKey.Add(parse[1]);
stkeyByName.Add(parse[1], stnameByKey.Count - 1);
stDist.Add(new Dictionary<int, int>());
routesByStkey.Add(new List<Route>());
}
int st1 = stkeyByName[parse[0]], st2 = stkeyByName[parse[1]];
int dist = Convert.ToInt32(parse[2]);
stDist[st1].Add(st2, dist);
stDist[st2].Add(st1, dist);
}
#endregion
#region
for (int i = 0; i < r; ++i, ++l)
{
line = filestream.ReadLine();
if (line.StartsWith("//"))
{
--i;
--l;
continue;
}
parse = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (parse.Length != 4)
ReadEx(l);
int rn = Convert.ToInt32(parse[0]);
string[] rt = parse[1].Split(new char[] { ':' });
int rs = Convert.ToInt32(rt[0]) * 60 + Convert.ToInt32(rt[1]);
rt = parse[2].Split(new char[] { ':' });
int re = Convert.ToInt32(rt[0]) * 60 + Convert.ToInt32(rt[1]);
if (re < rs) re += 24 * 60;
int ri = Convert.ToInt32(parse[3]);
++l;
while ((line = filestream.ReadLine()).StartsWith("//")) ;
parse = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
List<int> stList = new List<int>();
for (int j = 0; j < parse.Length; ++j)
stList.Add(stkeyByName[parse[j]]); //TODO check nonexist station
Route nroute = new Route(rn, rs, re, ri, stList);
routesStorage.Add(nroute);
routesByNum.Add(rn, nroute);
foreach (int item in nroute.stations)
routesByStkey[item].Add(nroute);
}
#endregion
}
catch (Exception)
{
ReadEx(l);
}
return 0;
}
static void UI()
{
Console.Write("Enter station: ");
string line;
while ((line = Console.ReadLine()) != "")
{
DateTime time = DateTime.Now;
if (!stkeyByName.ContainsKey(line))
{
Console.WriteLine("No such station!");
Console.Write("Enter station: ");
continue;
}
Console.WriteLine("Current time: {0:00}:{1:00}", time.Hour, time.Minute);
Console.WriteLine("Schedule:");
var sch = GetScheduleBySt(stkeyByName[line], time);
foreach (var item in sch)
{
Console.WriteLine("{0}, destination {1}, {2} min", item.num, stnameByKey[item.dest], item.time);
}
Console.Write("Enter station: ");
}
}
static void Main(string[] args)
{
GetData();
//GetScheduleBySt(1, new DateTime(1, 1, 1, 5, 9, 0));
UI();
}
}
}
| |
using System.Security;
namespace System.IO.IsolatedStorage {
#if FEATURE_CORECLR
#if !FEATURE_LEGACYNETCF
public enum IsolatedStorageSecurityOptions {
GetRootUserDirectory = 0,
GetGroupAndIdForApplication = 1,
GetGroupAndIdForSite = 2,
IncreaseQuotaForGroup = 3,
IncreaseQuotaForApplication = 4,
SetInnerException = 5
}
#else // !FEATURE_LEGACYNETCF
public enum IsolatedStorageSecurityOptions {
GetRootUserDirectory = 0,
GetGroupAndIdForApplication = 1,
GetGroupAndIdForSite = 2,
IncreaseQuotaForGroup = 3,
DefaultQuotaForGroup = 4,
AvailableFreeSpace = 5,
IsolatedStorageFolderName = 6
}
#endif // !FEATURE_LEGACYNETCF
#else // FEATURE_CORECLR
public enum IsolatedStorageSecurityOptions {
IncreaseQuotaForApplication = 4
}
#endif // !FEATURE_CORECLR
[SecurityCritical]
public class IsolatedStorageSecurityState : SecurityState {
private Int64 m_UsedSize;
private Int64 m_Quota;
#if FEATURE_CORECLR
private string m_Id;
private string m_Group;
private string m_RootUserDirectory;
#endif // FEATURE_CORECLR
#if FEATURE_LEGACYNETCF
private string m_IsolatedStorageFolderName;
private Int64 m_AvailableFreeSpace;
private bool m_AvailableFreeSpaceComputed;
#endif // FEATURE_LEGACYNETCF
private IsolatedStorageSecurityOptions m_Options;
#if FEATURE_CORECLR
internal static IsolatedStorageSecurityState CreateStateToGetRootUserDirectory() {
IsolatedStorageSecurityState state = new IsolatedStorageSecurityState();
state.m_Options = IsolatedStorageSecurityOptions.GetRootUserDirectory;
return state;
}
internal static IsolatedStorageSecurityState CreateStateToGetGroupAndIdForApplication() {
IsolatedStorageSecurityState state = new IsolatedStorageSecurityState();
state.m_Options = IsolatedStorageSecurityOptions.GetGroupAndIdForApplication;
return state;
}
internal static IsolatedStorageSecurityState CreateStateToGetGroupAndIdForSite() {
IsolatedStorageSecurityState state = new IsolatedStorageSecurityState();
state.m_Options = IsolatedStorageSecurityOptions.GetGroupAndIdForSite;
return state;
}
internal static IsolatedStorageSecurityState CreateStateToIncreaseQuotaForGroup(String group, Int64 newQuota, Int64 usedSize) {
IsolatedStorageSecurityState state = new IsolatedStorageSecurityState();
state.m_Options = IsolatedStorageSecurityOptions.IncreaseQuotaForGroup;
state.m_Group = group;
state.m_Quota = newQuota;
state.m_UsedSize = usedSize;
return state;
}
#if !FEATURE_LEGACYNETCF
internal static IsolatedStorageSecurityState CreateStateToCheckSetInnerException() {
IsolatedStorageSecurityState state = new IsolatedStorageSecurityState();
state.m_Options = IsolatedStorageSecurityOptions.SetInnerException;
return state;
}
#endif
#if FEATURE_LEGACYNETCF
internal static IsolatedStorageSecurityState CreateStateToGetAvailableFreeSpace() {
IsolatedStorageSecurityState state = new IsolatedStorageSecurityState();
state.m_Options = IsolatedStorageSecurityOptions.AvailableFreeSpace;
return state;
}
internal static IsolatedStorageSecurityState CreateStateForIsolatedStorageFolderName() {
IsolatedStorageSecurityState state = new IsolatedStorageSecurityState();
state.m_Options = IsolatedStorageSecurityOptions.IsolatedStorageFolderName;
return state;
}
#endif
#endif // FEATURE_CORECLR
#if !FEATURE_LEGACYNETCF
internal static IsolatedStorageSecurityState CreateStateToIncreaseQuotaForApplication(Int64 newQuota, Int64 usedSize) {
IsolatedStorageSecurityState state = new IsolatedStorageSecurityState();
state.m_Options = IsolatedStorageSecurityOptions.IncreaseQuotaForApplication;
state.m_Quota = newQuota;
state.m_UsedSize = usedSize;
return state;
}
#endif // !FEATURE_LEGACYNETCF
[SecurityCritical]
private IsolatedStorageSecurityState() {
}
public IsolatedStorageSecurityOptions Options {
get {
return m_Options;
}
}
#if FEATURE_CORECLR
public String Group {
get {
return m_Group;
}
set {
m_Group = value;
}
}
public String Id {
get {
return m_Id;
}
set {
m_Id = value;
}
}
public String RootUserDirectory {
get {
return m_RootUserDirectory;
}
set {
m_RootUserDirectory = value;
}
}
#endif // FEATURE_CORECLR
public Int64 UsedSize {
get {
return m_UsedSize;
}
}
public Int64 Quota {
get {
return m_Quota;
}
set {
m_Quota = value;
}
}
#if FEATURE_LEGACYNETCF
public Int64 AvailableFreeSpace {
get {
return m_AvailableFreeSpace;
}
set {
m_AvailableFreeSpace = value;
m_AvailableFreeSpaceComputed = true;
}
}
public bool AvailableFreeSpaceComputed {
get { return m_AvailableFreeSpaceComputed; }
set { m_AvailableFreeSpaceComputed = value; }
}
public string IsolatedStorageFolderName {
get { return m_IsolatedStorageFolderName; }
set { m_IsolatedStorageFolderName = value; }
}
#endif
[SecurityCritical]
public override void EnsureState() {
if(!IsStateAvailable()) {
throw new IsolatedStorageException(Environment.GetResourceString("IsolatedStorage_Operation"));
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace TestWebApp.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
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);
}
}
}
}
| |
namespace dotless.Test.Specs
{
using System.Collections.Generic;
using NUnit.Framework;
public class VariablesFixture : SpecFixtureBase
{
[Test]
public void VariableOperators()
{
var input = @"
@a: 2;
@x: @a * @a;
@y: @x + 1;
@z: @x * 2 + @y;
.variables {
width: @z + 1cm; // 14cm
}";
var expected = @"
.variables {
width: 14cm;
}";
AssertLess(input, expected);
}
[Test]
public void StringVariables()
{
var input =
@"
@fonts: ""Trebuchet MS"", Verdana, sans-serif;
@f: @fonts;
.variables {
font-family: @f;
}
";
var expected =
@"
.variables {
font-family: ""Trebuchet MS"", Verdana, sans-serif;
}
";
AssertLess(input, expected);
}
[Test]
public void VariablesWithNumbers()
{
var input =
@"@widget-container: widget-container-8675309;
#@{widget-container} {
color: blue;
}";
var expected =
@"
#widget-container-8675309 {
color: blue;
}
";
AssertLess(input, expected);
}
[Test]
public void VariablesChangingUnit()
{
var input =
@"
@a: 2;
@x: @a * @a;
@b: @a * 10;
.variables {
height: @b + @x + 0px; // 24px
}
";
var expected =
@"
.variables {
height: 24px;
}
";
AssertLess(input, expected);
}
[Test]
public void VariablesColor()
{
var input =
@"
@c: #888;
.variables {
color: @c;
}
";
var expected =
@"
.variables {
color: #888888;
}
";
AssertLess(input, expected);
}
[Test]
public void VariablesQuoted()
{
var input =
@"
@quotes: ""~"" ""~"";
@q: @quotes;
.variables {
quotes: @q;
}
";
var expected =
@"
.variables {
quotes: ""~"" ""~"";
}
";
AssertLess(input, expected);
}
[Test]
public void VariableOverridesPreviousValue1()
{
var input = @"
@var: 10px;
.init {
width: @var;
}
@var: 20px;
.overridden {
width: @var;
}
";
var expected = @"
.init {
width: 20px;
}
.overridden {
width: 20px;
}
";
AssertLess(input, expected);
}
[Test]
public void VariableOverridesPreviousValue2()
{
var input = @"
@var: 10px;
.test {
width: @var;
@var: 20px;
height: @var;
}
";
var expected = @"
.test {
width: 20px;
height: 20px;
}
";
AssertLess(input, expected);
}
[Test]
public void VariableOverridesPreviousValue3()
{
var input = @"
@var: 10px;
.test {
@var: 15px;
width: @var;
@var: 20px;
height: @var;
}
";
var expected = @"
.test {
width: 20px;
height: 20px;
}
";
AssertLess(input, expected);
}
[Test]
public void VariableOverridesPreviousValue4()
{
var input = @"
@var: 10px;
.test1 {
@var: 20px;
width: @var;
}
.test2 {
width: @var;
}
";
var expected = @"
.test1 {
width: 20px;
}
.test2 {
width: 10px;
}
";
AssertLess(input, expected);
}
[Test]
public void VariableOverridesPreviousValue5()
{
var input = @"
.mixin(@a) {
width: @a;
}
.test {
@var: 15px;
.mixin(@var);
@var: 20px;
.mixin(@var);
}
";
var expected = @"
.test {
width: 20px;
}
";
AssertLess(input, expected);
}
[Test]
public void Redefine()
{
var input = @"
#redefine {
@var: 4;
@var: 2;
@var: 3;
width: @var;
}
";
var expected = @"
#redefine {
width: 3;
}
";
AssertLess(input, expected);
}
[Test]
public void ThrowsIfNotFound()
{
AssertExpressionError("variable @var is undefined", 0, "@var");
}
[Test]
public void VariablesKeepImportantKeyword()
{
var variables = new Dictionary<string, string>();
variables["a"] = "#335577";
variables["b"] = "#335577 !important";
AssertExpression("#335577 !important", "@a !important", variables);
AssertExpression("#335577 !important", "@b", variables);
}
[Test]
public void VariablesKeepImportantKeyword2()
{
var input = @"
@var: 0 -120px !important;
.mixin(@a) {
background-position: @a;
}
.class1 { .mixin( @var ); }
.class2 { background-position: @var; }
";
var expected = @"
.class1 {
background-position: 0 -120px !important;
}
.class2 {
background-position: 0 -120px !important;
}
";
AssertLess(input, expected);
}
[Test]
public void VariableValuesMulti()
{
var input = @"
.values {
@a: 'Trebuchet';
font-family: @a, @a, @a;
}";
var expected = @"
.values {
font-family: 'Trebuchet', 'Trebuchet', 'Trebuchet';
}";
AssertLess(input, expected);
}
[Test]
public void VariableValuesUrl()
{
var input = @"
.values {
@a: 'Trebuchet';
url: url(@a);
}";
var expected = @"
.values {
url: url('Trebuchet');
}";
AssertLess(input, expected);
}
[Test]
public void VariableValuesImportant()
{
var input = @"
@c: #888;
.values {
color: @c !important;
}";
var expected = @"
.values {
color: #888888 !important;
}";
AssertLess(input, expected);
}
[Test]
public void VariableValuesMultipleValues()
{
var input = @"
.values {
@a: 'Trebuchet';
@multi: 'A', B, C;
multi: something @multi, @a;
}";
var expected = @"
.values {
multi: something 'A', B, C, 'Trebuchet';
}";
AssertLess(input, expected);
}
[Test]
public void VariablesNames()
{
var input = @".variable-names {
@var: 'hello';
@name: 'var';
name: @@name;
}";
var expected = @"
.variable-names {
name: 'hello';
}";
AssertLess(input, expected);
}
[Test]
public void VariableSelector()
{
string input = @"// Variables
@mySelector: banner;
// Usage
.@{mySelector} {
font-weight: bold;
line-height: 40px;
margin: 0 auto;
}
";
string expected = @".banner {
font-weight: bold;
line-height: 40px;
margin: 0 auto;
}
";
AssertLess(input,expected);
}
[Test]
public void SimpleRecursiveVariableDefinition()
{
string input = @"
@var: 1px;
@var: @var + 1;
.rule {
left: @var;
}
";
string expectedError = @"
Recursive variable definition for @var on line 2 in file 'test.less':
[1]: @var: 1px;
[2]: @var: @var + 1;
------^
[3]: ";
AssertError(expectedError, input);
}
[Test]
public void IndirectRecursiveVariableDefinition()
{
string input = @"
@var: 1px;
@var2: @var;
@var: @var2 + 1;
.rule {
left: @var;
}
";
string expectedError = @"
Recursive variable definition for @var on line 2 in file 'test.less':
[1]: @var: 1px;
[2]: @var2: @var;
-------^
[3]: @var: @var2 + 1;";
AssertError(expectedError, input);
}
[Test]
public void VariableDeclarationWithMissingSemicolon() {
var input = @"
@v1:Normal;
@v2:
";
AssertError("missing semicolon in expression", "@v2:", 2, 3, input);
}
[Test]
public void VariablesInAttributeSelectorValue() {
var input = @"
@breakpoint-alias: ""desktop"";
[class*=""@{breakpoint-alias}-rule""] {
margin-top: 0;
zoom: 1;
}";
var expected = @"
[class*=""desktop-rule""] {
margin-top: 0;
zoom: 1;
}";
AssertLess(input, expected);
}
[Test]
public void VariablesAsAttributeName() {
var input = @"
@key: ""desktop"";
[@{key}=""value""] {
margin-top: 0;
zoom: 1;
}";
var expected = @"
[""desktop""=""value""] {
margin-top: 0;
zoom: 1;
}";
AssertLess(input, expected);
}
[Test]
public void VariablesAsPartOfAttributeNameNotAllowed() {
var input = @"
@key: ""desktop"";
[@{key}-something=""value""] {
margin-top: 0;
zoom: 1;
}";
var expected = @"
[""desktop""=""value""] {
margin-top: 0;
zoom: 1;
}";
AssertError("Expected ']' but found '\"'", "[@{key}-something=\"value\"] {", 2, 17, input);
}
[Test]
public void SelectorIsLegalVariableValue() {
var input = @"
@test: .foo;
";
AssertLess(input, "");
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// HttpClientFailure operations.
/// </summary>
public partial interface IHttpClientFailure
{
/// <summary>
/// Return 400 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Head400WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 400 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Get400WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 400 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Put400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 400 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Patch400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 400 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Post400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 400 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Delete400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 401 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Head401WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 402 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Get402WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 403 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Get403WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 404 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Put404WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 405 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Patch405WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 406 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Post406WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 407 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Delete407WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 409 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Put409WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 410 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Head410WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 411 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Get411WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 412 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Get412WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 413 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Put413WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 414 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Patch414WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 415 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Post415WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 416 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Get416WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 417 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Delete417WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 429 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Head429WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using System.Collections.Generic;
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
using GSF.ASN1.Types;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1Choice(Name = "Data")]
public class Data : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Data));
private ICollection<Data> array_;
private bool array_selected;
private long bcd_;
private bool bcd_selected;
private TimeOfDay binary_time_;
private bool binary_time_selected;
private BitString bit_string_;
private bool bit_string_selected;
private BitString booleanArray_;
private bool booleanArray_selected;
private bool boolean_;
private bool boolean_selected;
private FloatingPoint floating_point_;
private bool floating_point_selected;
private string generalized_time_;
private bool generalized_time_selected;
private long integer_;
private bool integer_selected;
private MMSString mMSString_;
private bool mMSString_selected;
private ObjectIdentifier objId_;
private bool objId_selected;
private byte[] octet_string_;
private bool octet_string_selected;
private ICollection<Data> structure_;
private bool structure_selected;
private long unsigned_;
private bool unsigned_selected;
private UtcTime utc_time_;
private bool utc_time_selected;
private string visible_string_;
private bool visible_string_selected;
[ASN1SequenceOf(Name = "array", IsSetOf = false)]
[ASN1_MMSDataArray]
[ASN1Element(Name = "array", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public ICollection<Data> Array
{
get
{
return array_;
}
set
{
selectArray(value);
}
}
[ASN1SequenceOf(Name = "structure", IsSetOf = false)]
[ASN1_MMSDataStructure]
[ASN1Element(Name = "structure", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)]
public ICollection<Data> Structure
{
get
{
return structure_;
}
set
{
selectStructure(value);
}
}
[ASN1Boolean(Name = "")]
[ASN1Element(Name = "boolean", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = false)]
public bool Boolean
{
get
{
return boolean_;
}
set
{
selectBoolean(value);
}
}
[ASN1BitString(Name = "")]
[ASN1Element(Name = "bit-string", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)]
public BitString Bit_string
{
get
{
return bit_string_;
}
set
{
selectBit_string(value);
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "integer", IsOptional = false, HasTag = true, Tag = 5, HasDefaultValue = false)]
public long Integer
{
get
{
return integer_;
}
set
{
selectInteger(value);
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "unsigned", IsOptional = false, HasTag = true, Tag = 6, HasDefaultValue = false)]
public long Unsigned
{
get
{
return unsigned_;
}
set
{
selectUnsigned(value);
}
}
[ASN1Element(Name = "floating-point", IsOptional = false, HasTag = true, Tag = 7, HasDefaultValue = false)]
public FloatingPoint Floating_point
{
get
{
return floating_point_;
}
set
{
selectFloating_point(value);
}
}
[ASN1OctetString(Name = "")]
[ASN1Element(Name = "octet-string", IsOptional = false, HasTag = true, Tag = 9, HasDefaultValue = false)]
public byte[] Octet_string
{
get
{
return octet_string_;
}
set
{
selectOctet_string(value);
}
}
[ASN1String(Name = "",
StringType = UniversalTags.VisibleString, IsUCS = false)]
[ASN1Element(Name = "visible-string", IsOptional = false, HasTag = true, Tag = 10, HasDefaultValue = false)]
public string Visible_string
{
get
{
return visible_string_;
}
set
{
selectVisible_string(value);
}
}
[ASN1String(Name = "",
StringType = UniversalTags.GeneralizedTime, IsUCS = false)]
[ASN1Element(Name = "generalized-time", IsOptional = false, HasTag = true, Tag = 11, HasDefaultValue = false)]
public string Generalized_time
{
get
{
return generalized_time_;
}
set
{
selectGeneralized_time(value);
}
}
[ASN1Element(Name = "binary-time", IsOptional = false, HasTag = true, Tag = 12, HasDefaultValue = false)]
public TimeOfDay Binary_time
{
get
{
return binary_time_;
}
set
{
selectBinary_time(value);
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "bcd", IsOptional = false, HasTag = true, Tag = 13, HasDefaultValue = false)]
public long Bcd
{
get
{
return bcd_;
}
set
{
selectBcd(value);
}
}
[ASN1BitString(Name = "")]
[ASN1Element(Name = "booleanArray", IsOptional = false, HasTag = true, Tag = 14, HasDefaultValue = false)]
public BitString BooleanArray
{
get
{
return booleanArray_;
}
set
{
selectBooleanArray(value);
}
}
[ASN1ObjectIdentifier(Name = "")]
[ASN1Element(Name = "objId", IsOptional = false, HasTag = true, Tag = 15, HasDefaultValue = false)]
public ObjectIdentifier ObjId
{
get
{
return objId_;
}
set
{
selectObjId(value);
}
}
[ASN1Element(Name = "mMSString", IsOptional = false, HasTag = true, Tag = 16, HasDefaultValue = false)]
public MMSString MMSString
{
get
{
return mMSString_;
}
set
{
selectMMSString(value);
}
}
[ASN1Element(Name = "utc-time", IsOptional = false, HasTag = true, Tag = 17, HasDefaultValue = false)]
public UtcTime Utc_time
{
get
{
return utc_time_;
}
set
{
selectUtc_time(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isArraySelected()
{
return array_selected;
}
public void selectArray(ICollection<Data> val)
{
array_ = val;
array_selected = true;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isStructureSelected()
{
return structure_selected;
}
public void selectStructure(ICollection<Data> val)
{
structure_ = val;
structure_selected = true;
array_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isBooleanSelected()
{
return boolean_selected;
}
public void selectBoolean(bool val)
{
boolean_ = val;
boolean_selected = true;
array_selected = false;
structure_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isBit_stringSelected()
{
return bit_string_selected;
}
public void selectBit_string(BitString val)
{
bit_string_ = val;
bit_string_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isIntegerSelected()
{
return integer_selected;
}
public void selectInteger(long val)
{
integer_ = val;
integer_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isUnsignedSelected()
{
return unsigned_selected;
}
public void selectUnsigned(long val)
{
unsigned_ = val;
unsigned_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isFloating_pointSelected()
{
return floating_point_selected;
}
public void selectFloating_point(FloatingPoint val)
{
floating_point_ = val;
floating_point_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isOctet_stringSelected()
{
return octet_string_selected;
}
public void selectOctet_string(byte[] val)
{
octet_string_ = val;
octet_string_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isVisible_stringSelected()
{
return visible_string_selected;
}
public void selectVisible_string(string val)
{
visible_string_ = val;
visible_string_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isGeneralized_timeSelected()
{
return generalized_time_selected;
}
public void selectGeneralized_time(string val)
{
generalized_time_ = val;
generalized_time_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isBinary_timeSelected()
{
return binary_time_selected;
}
public void selectBinary_time(TimeOfDay val)
{
binary_time_ = val;
binary_time_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isBcdSelected()
{
return bcd_selected;
}
public void selectBcd(long val)
{
bcd_ = val;
bcd_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isBooleanArraySelected()
{
return booleanArray_selected;
}
public void selectBooleanArray(BitString val)
{
booleanArray_ = val;
booleanArray_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
objId_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isObjIdSelected()
{
return objId_selected;
}
public void selectObjId(ObjectIdentifier val)
{
objId_ = val;
objId_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
mMSString_selected = false;
utc_time_selected = false;
}
public bool isMMSStringSelected()
{
return mMSString_selected;
}
public void selectMMSString(MMSString val)
{
mMSString_ = val;
mMSString_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
utc_time_selected = false;
}
public bool isUtc_timeSelected()
{
return utc_time_selected;
}
public void selectUtc_time(UtcTime val)
{
utc_time_ = val;
utc_time_selected = true;
array_selected = false;
structure_selected = false;
boolean_selected = false;
bit_string_selected = false;
integer_selected = false;
unsigned_selected = false;
floating_point_selected = false;
octet_string_selected = false;
visible_string_selected = false;
generalized_time_selected = false;
binary_time_selected = false;
bcd_selected = false;
booleanArray_selected = false;
objId_selected = false;
mMSString_selected = false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// String.Trim(char[])
/// </summary>
public class StringTrim2
{
private int c_MINI_STRING_LENGTH = 8;
private int c_MAX_STRING_LENGTH = 256;
// U+200B stops being trimmable http://msdn2.microsoft.com/en-us/library/t97s7bs3.aspx
// U+FEFF has been deprecate as a trimmable space
private string[] spaceStrings = new string[]{"\u0009","\u000A","\u000B","\u000C","\u000D","\u0020",
"\u00A0","\u2000","\u2001","\u2002","\u2003","\u2004","\u2005",
"\u2006","\u2007","\u2008","\u2009","\u200A","\u3000"};
public static int Main()
{
StringTrim2 st2 = new StringTrim2();
TestLibrary.TestFramework.BeginTestCase("StringTrim2");
if (st2.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
return retVal;
}
#region PostiveTesting
public bool PosTest1()
{
bool retVal = true;
string strA;
char[] charA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest1: empty string trim char[]");
try
{
strA = string.Empty;
charA = new char[] {TestLibrary.Generator.GetChar(-55),TestLibrary.Generator.GetChar(-55),TestLibrary.Generator.GetChar(-55) };
ActualResult = strA.Trim(charA);
if (ActualResult != string.Empty)
{
TestLibrary.TestFramework.LogError("001", "empty string trim char[] ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string strA;
char[] charA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest2:normal string trim char[] one");
try
{
strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
char char1 = this.GetChar(0, c_MINI_STRING_LENGTH);
char char2 = this.GetChar(c_MINI_STRING_LENGTH, c_MINI_STRING_LENGTH + 68);
char char3 = this.GetChar(c_MINI_STRING_LENGTH + 68, c_MAX_STRING_LENGTH / 2);
char charEnd = this.GetChar(c_MAX_STRING_LENGTH / 2, c_MAX_STRING_LENGTH);
charA = new char[] { char1, char2, char3 };
string strA1 = char1.ToString() + char3.ToString() + charEnd.ToString() + strA + charEnd.ToString();
ActualResult = strA1.Trim(charA);
if (ActualResult.ToString() != charEnd.ToString() + strA.ToString() + charEnd.ToString())
{
TestLibrary.TestFramework.LogError("003", "normal string trim char[] one ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string strA;
char[] charA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest3:normal string trim char[] two");
try
{
strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
char char1 = this.GetChar(0, c_MINI_STRING_LENGTH);
char char2 = this.GetChar(c_MINI_STRING_LENGTH, c_MINI_STRING_LENGTH + 68);
char char3 = this.GetChar(c_MAX_STRING_LENGTH + 68, c_MAX_STRING_LENGTH / 2);
char charStart = this.GetChar(c_MAX_STRING_LENGTH / 2, c_MAX_STRING_LENGTH);
charA = new char[] { char1, char2, char3 };
string strA1 = charStart.ToString() + strA + charStart.ToString() + char2.ToString() + char3.ToString();
ActualResult = strA1.Trim(charA);
if (ActualResult.ToString() != charStart.ToString() + strA + charStart.ToString())
{
TestLibrary.TestFramework.LogError("005", "normal string trim char[] two ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string strA;
char[] charA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest4:normal string trim char[] three");
try
{
strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
char char1 = this.GetChar(0, c_MINI_STRING_LENGTH);
char char2 = this.GetChar(c_MINI_STRING_LENGTH, c_MINI_STRING_LENGTH + 68);
char char3 = this.GetChar(c_MAX_STRING_LENGTH + 68, c_MAX_STRING_LENGTH / 2);
char charStart = this.GetChar(c_MAX_STRING_LENGTH / 2, c_MAX_STRING_LENGTH);
charA = new char[] { char1, char2, char3 };
string strA1 = char1.ToString() + charStart.ToString() + char2.ToString() + strA + charStart.ToString() + char3.ToString();
ActualResult = strA1.Trim(charA);
if (ActualResult.ToString() != charStart.ToString() + char2.ToString() + strA + charStart.ToString())
{
TestLibrary.TestFramework.LogError("007", "normal string trim char[] three ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string strA;
char[] charA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest5:normal string trim char[] four");
try
{
strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
charA = new char[0];
string strB = spaceStrings[this.GetInt32(0,spaceStrings.Length)];
string strA1 = strB + "H" + strA + "D";
ActualResult = strA1.Trim(charA);
if (ActualResult.ToString() != "H" + strA + "D")
{
TestLibrary.TestFramework.LogError("009", "normal string trim char[] four ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
string strA;
char[] charA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest6:normal string trim char[] five");
try
{
strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
charA = new char[0];
string strB = spaceStrings[this.GetInt32(0, spaceStrings.Length)];
string strA1 = strB + "H" + strB + strA + "D" + strB;
ActualResult = strA1.Trim(charA);
if (ActualResult.ToString() != "H" + strB + strA + "D")
{
TestLibrary.TestFramework.LogError("011", "normal string trim char[] five ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
string strA;
char[] charA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest7:normal string trim char[] six");
try
{
strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
charA = new char[0];
string strB = spaceStrings[this.GetInt32(0, spaceStrings.Length)];
string strA1 = "H" + strA + "D" + strB;
ActualResult = strA1.Trim(charA);
if (ActualResult.ToString() != "H" + strA + "D")
{
TestLibrary.TestFramework.LogError("013", "normal string trim char[] six ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region Help method for geting test data
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
private Char GetChar(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return Convert.ToChar(minValue);
}
if (minValue < maxValue)
{
return Convert.ToChar(Convert.ToInt32(TestLibrary.Generator.GetChar(-55)) % (maxValue - minValue) + minValue);
}
}
catch
{
throw;
}
return Convert.ToChar(minValue);
}
private string GetString(bool ValidPath, Int32 minValue, Int32 maxValue)
{
StringBuilder sVal = new StringBuilder();
string s;
if (0 == minValue && 0 == maxValue) return String.Empty;
if (minValue > maxValue) return null;
if (ValidPath)
{
return TestLibrary.Generator.GetString(-55, ValidPath, minValue, maxValue);
}
else
{
int length = this.GetInt32(minValue, maxValue);
for (int i = 0; length > i; i++)
{
char c = this.GetChar(minValue, maxValue);
sVal.Append(c);
}
s = sVal.ToString();
return s;
}
}
#endregion
}
| |
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember
{
internal abstract partial class AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>
{
internal abstract class SignatureInfo
{
protected readonly SemanticDocument Document;
protected readonly State State;
private ImmutableArray<ITypeParameterSymbol> _typeParameters;
private IDictionary<ITypeSymbol, ITypeParameterSymbol> _typeArgumentToTypeParameterMap;
public SignatureInfo(
SemanticDocument document,
State state)
{
this.Document = document;
this.State = state;
}
public ImmutableArray<ITypeParameterSymbol> DetermineTypeParameters(CancellationToken cancellationToken)
{
return _typeParameters.IsDefault
? (_typeParameters = DetermineTypeParametersWorker(cancellationToken))
: _typeParameters;
}
protected abstract ImmutableArray<ITypeParameterSymbol> DetermineTypeParametersWorker(CancellationToken cancellationToken);
protected abstract bool DetermineReturnsByRef(CancellationToken cancellationToken);
public ITypeSymbol DetermineReturnType(CancellationToken cancellationToken)
{
var type = DetermineReturnTypeWorker(cancellationToken);
if (State.IsInConditionalAccessExpression)
{
type = type.RemoveNullableIfPresent();
}
return FixType(type, cancellationToken);
}
protected abstract ImmutableArray<ITypeSymbol> DetermineTypeArguments(CancellationToken cancellationToken);
protected abstract ITypeSymbol DetermineReturnTypeWorker(CancellationToken cancellationToken);
protected abstract ImmutableArray<RefKind> DetermineParameterModifiers(CancellationToken cancellationToken);
protected abstract ImmutableArray<ITypeSymbol> DetermineParameterTypes(CancellationToken cancellationToken);
protected abstract ImmutableArray<bool> DetermineParameterOptionality(CancellationToken cancellationToken);
protected abstract ImmutableArray<ParameterName> DetermineParameterNames(CancellationToken cancellationToken);
internal IPropertySymbol GenerateProperty(
SyntaxGenerator factory,
bool isAbstract, bool includeSetter,
CancellationToken cancellationToken)
{
var accessibility = DetermineAccessibility(isAbstract);
var getMethod = CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: default(ImmutableArray<AttributeData>),
accessibility: accessibility,
statements: GenerateStatements(factory, isAbstract, cancellationToken));
var setMethod = includeSetter ? getMethod : null;
return CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: default(ImmutableArray<AttributeData>),
accessibility: accessibility,
modifiers: new DeclarationModifiers(isStatic: State.IsStatic, isAbstract: isAbstract),
type: DetermineReturnType(cancellationToken),
returnsByRef: DetermineReturnsByRef(cancellationToken),
explicitInterfaceSymbol: null,
name: this.State.IdentifierToken.ValueText,
parameters: DetermineParameters(cancellationToken),
getMethod: getMethod,
setMethod: setMethod);
}
public IMethodSymbol GenerateMethod(
SyntaxGenerator factory,
bool isAbstract,
CancellationToken cancellationToken)
{
var parameters = DetermineParameters(cancellationToken);
var returnType = DetermineReturnType(cancellationToken);
var isUnsafe = false;
if (!State.IsContainedInUnsafeType)
{
isUnsafe = returnType.IsUnsafe() || parameters.Any(p => p.Type.IsUnsafe());
}
var returnsByRef = DetermineReturnsByRef(cancellationToken);
var method = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default(ImmutableArray<AttributeData>),
accessibility: DetermineAccessibility(isAbstract),
modifiers: new DeclarationModifiers(isStatic: State.IsStatic, isAbstract: isAbstract, isUnsafe: isUnsafe),
returnType: returnType,
returnsByRef: returnsByRef,
explicitInterfaceSymbol: null,
name: this.State.IdentifierToken.ValueText,
typeParameters: DetermineTypeParameters(cancellationToken),
parameters: parameters,
statements: GenerateStatements(factory, isAbstract, cancellationToken),
handlesExpressions: default(ImmutableArray<SyntaxNode>),
returnTypeAttributes: default(ImmutableArray<AttributeData>),
methodKind: State.MethodKind);
// Ensure no conflicts between type parameter names and parameter names.
var languageServiceProvider = this.Document.Project.Solution.Workspace.Services.GetLanguageServices(this.State.TypeToGenerateIn.Language);
var syntaxFacts = languageServiceProvider.GetService<ISyntaxFactsService>();
var equalityComparer = syntaxFacts.IsCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
var reservedParameterNames = this.DetermineParameterNames(cancellationToken)
.Select(p => p.BestNameForParameter)
.ToSet(equalityComparer);
var newTypeParameterNames = NameGenerator.EnsureUniqueness(
method.TypeParameters.Select(t => t.Name).ToList(), n => !reservedParameterNames.Contains(n));
return method.RenameTypeParameters(newTypeParameterNames);
}
private ITypeSymbol FixType(
ITypeSymbol typeSymbol,
CancellationToken cancellationToken)
{
// A type can't refer to a type parameter that isn't available in the type we're
// eventually generating into.
var availableMethodTypeParameters = this.DetermineTypeParameters(cancellationToken);
var availableTypeParameters = this.State.TypeToGenerateIn.GetAllTypeParameters();
var compilation = this.Document.SemanticModel.Compilation;
var allTypeParameters = availableMethodTypeParameters.Concat(availableTypeParameters);
var typeArgumentToTypeParameterMap = this.GetTypeArgumentToTypeParameterMap(cancellationToken);
return typeSymbol.RemoveAnonymousTypes(compilation)
.ReplaceTypeParametersBasedOnTypeConstraints(compilation, allTypeParameters, this.Document.Document.Project.Solution, cancellationToken)
.RemoveUnavailableTypeParameters(compilation, allTypeParameters)
.RemoveUnnamedErrorTypes(compilation)
.SubstituteTypes(typeArgumentToTypeParameterMap, new TypeGenerator());
}
private IDictionary<ITypeSymbol, ITypeParameterSymbol> GetTypeArgumentToTypeParameterMap(
CancellationToken cancellationToken)
{
return _typeArgumentToTypeParameterMap ?? (_typeArgumentToTypeParameterMap = CreateTypeArgumentToTypeParameterMap(cancellationToken));
}
private IDictionary<ITypeSymbol, ITypeParameterSymbol> CreateTypeArgumentToTypeParameterMap(
CancellationToken cancellationToken)
{
var typeArguments = this.DetermineTypeArguments(cancellationToken);
var typeParameters = this.DetermineTypeParameters(cancellationToken);
var result = new Dictionary<ITypeSymbol, ITypeParameterSymbol>();
for(var i = 0; i < typeArguments.Length; i++)
{
if (typeArguments[i] != null)
{
result[typeArguments[i]] = typeParameters[i];
}
}
return result;
}
private ImmutableArray<SyntaxNode> GenerateStatements(
SyntaxGenerator factory,
bool isAbstract,
CancellationToken cancellationToken)
{
var throwStatement = CodeGenerationHelpers.GenerateThrowStatement(factory, this.Document, "System.NotImplementedException", cancellationToken);
return isAbstract || State.TypeToGenerateIn.TypeKind == TypeKind.Interface || throwStatement == null
? default(ImmutableArray<SyntaxNode>)
: ImmutableArray.Create(throwStatement);
}
private ImmutableArray<IParameterSymbol> DetermineParameters(CancellationToken cancellationToken)
{
var modifiers = DetermineParameterModifiers(cancellationToken);
var types = DetermineParameterTypes(cancellationToken).Select(t => FixType(t, cancellationToken)).ToList();
var optionality = DetermineParameterOptionality(cancellationToken);
var names = DetermineParameterNames(cancellationToken);
var result = ArrayBuilder<IParameterSymbol>.GetInstance();
for (var i = 0; i < modifiers.Length; i++)
{
result.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
attributes: default(ImmutableArray<AttributeData>),
refKind: modifiers[i],
isParams: false,
isOptional: optionality[i],
type: types[i],
name: names[i].BestNameForParameter));
}
return result.ToImmutableAndFree();
}
private Accessibility DetermineAccessibility(bool isAbstract)
{
var containingType = this.State.ContainingType;
// If we're generating into an interface, then we don't use any modifiers.
if (State.TypeToGenerateIn.TypeKind != TypeKind.Interface)
{
// Otherwise, figure out what accessibility modifier to use and optionally
// mark it as static.
if (containingType.IsContainedWithin(State.TypeToGenerateIn) && !isAbstract)
{
return Accessibility.Private;
}
else if (DerivesFrom(containingType) && State.IsStatic)
{
// NOTE(cyrusn): We only generate protected in the case of statics. Consider
// the case where we're generating into one of our base types. i.e.:
//
// class B : A { void Foo() { A a; a.Foo(); }
//
// In this case we can *not* mark the method as protected. 'B' can only
// access protected members of 'A' through an instance of 'B' (or a subclass
// of B). It can not access protected members through an instance of the
// superclass. In this case we need to make the method public or internal.
//
// However, this does not apply if the method will be static. i.e.
//
// class B : A { void Foo() { A.Foo(); }
//
// B can access the protected statics of A, and so we generate 'Foo' as
// protected.
// TODO: Code coverage
return Accessibility.Protected;
}
else if (containingType.ContainingAssembly.IsSameAssemblyOrHasFriendAccessTo(State.TypeToGenerateIn.ContainingAssembly))
{
return Accessibility.Internal;
}
else
{
// TODO: Code coverage
return Accessibility.Public;
}
}
return Accessibility.NotApplicable;
}
private bool DerivesFrom(INamedTypeSymbol containingType)
{
return containingType.GetBaseTypes().Select(t => t.OriginalDefinition)
.OfType<INamedTypeSymbol>()
.Contains(State.TypeToGenerateIn);
}
}
}
}
| |
/*
* 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 NUnit.Framework;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Market;
namespace QuantConnect.Tests.Common.Data
{
[TestFixture]
public class TickQuoteBarConsolidatorTests
{
[Test]
public void AggregatesNewQuoteBarProperly()
{
QuoteBar quoteBar = null;
var creator = new TickQuoteBarConsolidator(4);
creator.DataConsolidated += (sender, args) =>
{
quoteBar = args;
};
var reference = DateTime.Today;
var tick1 = new Tick
{
Symbol = Symbols.SPY,
Time = reference,
BidPrice = 10,
BidSize = 20,
TickType = TickType.Quote
};
creator.Update(tick1);
Assert.IsNull(quoteBar);
var tick2 = new Tick
{
Symbol = Symbols.SPY,
Time = reference.AddHours(1),
AskPrice = 20,
AskSize = 10,
TickType = TickType.Quote
};
var badTick = new Tick
{
Symbol = Symbols.SPY,
Time = reference.AddHours(1),
AskPrice = 25,
AskSize = 100,
BidPrice = -100,
BidSize = 2,
Value = 50,
Quantity = 1234,
TickType = TickType.Trade
};
creator.Update(badTick);
Assert.IsNull(quoteBar);
creator.Update(tick2);
Assert.IsNull(quoteBar);
var tick3 = new Tick
{
Symbol = Symbols.SPY,
Time = reference.AddHours(2),
BidPrice = 12,
BidSize = 50,
TickType = TickType.Quote
};
creator.Update(tick3);
Assert.IsNull(quoteBar);
var tick4 = new Tick
{
Symbol = Symbols.SPY,
Time = reference.AddHours(3),
AskPrice = 17,
AskSize = 15,
TickType = TickType.Quote
};
creator.Update(tick4);
Assert.IsNotNull(quoteBar);
Assert.AreEqual(Symbols.SPY, quoteBar.Symbol);
Assert.AreEqual(tick1.Time, quoteBar.Time);
Assert.AreEqual(tick4.EndTime, quoteBar.EndTime);
Assert.AreEqual(tick1.BidPrice, quoteBar.Bid.Open);
Assert.AreEqual(tick1.BidPrice, quoteBar.Bid.Low);
Assert.AreEqual(tick3.BidPrice, quoteBar.Bid.High);
Assert.AreEqual(tick3.BidPrice, quoteBar.Bid.Close);
Assert.AreEqual(tick3.BidSize, quoteBar.LastBidSize);
Assert.AreEqual(tick2.AskPrice, quoteBar.Ask.Open);
Assert.AreEqual(tick4.AskPrice, quoteBar.Ask.Low);
Assert.AreEqual(tick2.AskPrice, quoteBar.Ask.High);
Assert.AreEqual(tick4.AskPrice, quoteBar.Ask.Close);
Assert.AreEqual(tick4.AskSize, quoteBar.LastAskSize);
}
[Test]
public void DoesNotConsolidateDifferentSymbols()
{
var consolidator = new TickQuoteBarConsolidator(2);
var reference = DateTime.Today;
var tick1 = new Tick
{
Symbol = Symbols.AAPL,
Time = reference,
BidPrice = 1000,
BidSize = 20,
TickType = TickType.Quote,
};
var tick2 = new Tick
{
Symbol = Symbols.ZNGA,
Time = reference,
BidPrice = 20,
BidSize = 30,
TickType = TickType.Quote,
};
consolidator.Update(tick1);
Exception ex = Assert.Throws<InvalidOperationException>(() => consolidator.Update(tick2));
Assert.IsTrue(ex.Message.Contains("is not the same"));
}
[Test]
public void LastCloseAndCurrentOpenPriceShouldBeSameConsolidatedOnCount()
{
QuoteBar quoteBar = null;
var creator = new TickQuoteBarConsolidator(2);
creator.DataConsolidated += (sender, args) =>
{
quoteBar = args;
};
var reference = DateTime.Today;
var tick1 = new Tick
{
Symbol = Symbols.SPY,
Time = reference,
TickType = TickType.Quote,
AskPrice = 0,
BidPrice = 24,
};
creator.Update(tick1);
var tick2 = new Tick
{
Symbol = Symbols.SPY,
Time = reference,
TickType = TickType.Quote,
AskPrice = 25,
BidPrice = 0,
};
creator.Update(tick2);
// bar 1 emitted
Assert.AreEqual(tick2.AskPrice, quoteBar.Ask.Open);
Assert.AreEqual(tick1.BidPrice, quoteBar.Bid.Open);
Assert.AreEqual(tick2.AskPrice, quoteBar.Ask.Close);
Assert.AreEqual(tick1.BidPrice, quoteBar.Bid.Close);
var tick3 = new Tick
{
Symbol = Symbols.SPY,
Time = reference.AddSeconds(1),
TickType = TickType.Quote,
AskPrice = 36,
BidPrice = 35,
};
creator.Update(tick3);
creator.Update(tick3);
// bar 2 emitted
// ask is from tick 2
Assert.AreEqual(tick2.AskPrice, quoteBar.Ask.Open, "Ask Open not equal to Previous Close");
// bid is from tick 1
Assert.AreEqual(tick1.BidPrice, quoteBar.Bid.Open, "Bid Open not equal to Previous Close");
Assert.AreEqual(tick3.AskPrice, quoteBar.Ask.Close, "Ask Close incorrect");
Assert.AreEqual(tick3.BidPrice, quoteBar.Bid.Close, "Bid Close incorrect");
}
[Test]
public void LastCloseAndCurrentOpenPriceShouldBeSameConsolidatedOnTimeSpan()
{
QuoteBar quoteBar = null;
var creator = new TickQuoteBarConsolidator(TimeSpan.FromMinutes(1));
creator.DataConsolidated += (sender, args) =>
{
quoteBar = args;
};
var reference = DateTime.Today;
// timeframe 1
var tick1 = new Tick
{
Symbol = Symbols.SPY,
Time = reference,
TickType = TickType.Quote,
AskPrice = 25,
BidPrice = 24,
};
creator.Update(tick1);
var tick2 = new Tick
{
Symbol = Symbols.SPY,
Time = reference.AddSeconds(1),
TickType = TickType.Quote,
AskPrice = 26,
BidPrice = 0,
};
creator.Update(tick2);
var tick3 = new Tick
{
Symbol = Symbols.SPY,
Time = reference.AddSeconds(1),
TickType = TickType.Quote,
AskPrice = 0,
BidPrice = 25,
};
creator.Update(tick3);
// timeframe 2
var tick4 = new Tick
{
Symbol = Symbols.SPY,
Time = reference.AddMinutes(1),
TickType = TickType.Quote,
AskPrice = 36,
BidPrice = 35,
};
creator.Update(tick4);
//force the consolidator to emit DataConsolidated
creator.Scan(reference.AddMinutes(2));
// bid is from tick 2
Assert.AreEqual(tick2.AskPrice, quoteBar.Ask.Open, "Ask Open not equal to Previous Close");
// bid is from tick 3
Assert.AreEqual(tick3.BidPrice, quoteBar.Bid.Open, "Bid Open not equal to Previous Close");
Assert.AreEqual(tick4.AskPrice, quoteBar.Ask.Close, "Ask Close incorrect");
Assert.AreEqual(tick4.BidPrice, quoteBar.Bid.Close, "Bid Close incorrect");
}
}
}
| |
/*
* Copyright (c) 2013 Mario Freitas ([email protected])
*
* 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 UnityEngine;
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace URLClient
{
public enum CachePolicy
{
UseProtocolCachePolicy = 0,
#if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_IPHONE
ReloadIgnoringLocalCacheData = 1,
ReturnCacheDataElseLoad = 2,
ReturnCacheDataDontLoad = 3,
#endif
ReloadIgnoringLocalAndRemoteCacheData = 4,
ReloadRevalidatingCacheData = 5
}
public enum ConnectionState
{
Unknown = 0,
Initialized = 1,
OpeningSourceFile = 2,
OpeningDestinationFile = 3,
SendingRequest = 4,
SentRequest = 5,
AuthenticatingState = 6,
ReceivingData = 7,
Finished = 8,
Cancelled = 9
};
public class Bindings : MonoBehaviour
{
public const string ERROR_DOMAIN = "UnityURLClient";
public const uint INVALID_CONNECTION_ID = 0;
#if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_IPHONE
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern uint _URLClientCreateHTTPConnection(string method,
string url, CachePolicy cachePolicy, float timeout);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
private static extern int _URLClientGetState(uint connectionID);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern string _URLClientGetErrorDomain(uint connectionID);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern long _URLClientGetErrorCode(uint connectionID);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern string _URLClientGetErrorDescription(uint connectionID);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern void _URLClientSetAllowFollowRedirects(
uint connectionID, bool allow, int maxCount);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern void _URLClientSetAllowInvalidSSLCertificate(
uint connectionID, bool allow);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
private static extern void _URLClientSetRequestContent(
uint connectionID, IntPtr src, ulong srcLength);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern void _URLClientSetRequestContentSource(
uint connectionID, string srcPath);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern void _URLClientSetRequestHeader(uint connectionID,
string name, string value);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern void _URLClientSetRequestAuthCredential(
uint connectionID, string user, string password);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern void _URLClientAddAcceptableResponseStatusCodeRange(
uint connectionID, long from, long to);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern void _URLClientSetResponseContentDestination(
uint connectionID, string dstPath, bool allowResume);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern void _URLClientSendRequest(uint connectionID);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern long _URLClientGetResponseStatusCode(
uint connectionID);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern string _URLClientGetResponseHeaderName(
uint connectionID, uint index);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern string _URLClientGetResponseHeaderValue(
uint connectionID, uint index);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern int _URLClientGetResponseRedirectCount(
uint connectionID);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern ulong _URLClientGetResponseContentLengthRead(
uint connectionID);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern long _URLClientGetResponseContentExpectedLength(
uint connectionID);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern ulong _URLClientGetResponseContentLengthResumed(
uint connectionID);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern ulong _URLClientGetPendingResponseContentLength(
uint connectionID);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern bool _URLClientCheckAndResetResponseDirtyFlag(
uint connectionID);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
private static extern ulong _URLClientMovePendingResponseContent(
uint connectionID, IntPtr dst, ulong dstLength);
#if UNITY_EDITOR || UNITY_STANDALONE_OSX
[DllImport("URLClient")]
#else
[DllImport("__Internal")]
#endif
public static extern void _URLClientDestroyConnection(uint connectionID);
#elif UNITY_ANDROID
private static AndroidJavaObject _unityURLClientBindingInstance = null;
private static AndroidJavaObject UnityURLClientBindingInstance
{
get
{
if (_unityURLClientBindingInstance == null)
{
AndroidJavaClass unityURLClientBindingClass;
unityURLClientBindingClass =
new AndroidJavaClass("com.github.imkira.unityurlclient.UnityURLClientBinding");
_unityURLClientBindingInstance =
unityURLClientBindingClass.CallStatic<AndroidJavaObject>("getInstance");
#if DEBUG
if (_unityURLClientBindingInstance != null)
{
_unityURLClientBindingInstance.Call("setDebug", true);
}
#endif
}
return _unityURLClientBindingInstance;
}
}
public static uint _URLClientCreateHTTPConnection(string method,
string url, CachePolicy cachePolicy, float timeout)
{
return (uint)UnityURLClientBindingInstance.Call<int>("createHTTPConnection",
method, url, (int)cachePolicy, timeout);
}
private static int _URLClientGetState(uint connectionID)
{
return UnityURLClientBindingInstance.Call<int>("getState",
(int)connectionID);
}
public static string _URLClientGetErrorDomain(uint connectionID)
{
return UnityURLClientBindingInstance.Call<string>("getErrorDomain",
(int)connectionID);
}
public static long _URLClientGetErrorCode(uint connectionID)
{
return UnityURLClientBindingInstance.Call<long>("getErrorCode",
(int)connectionID);
}
public static string _URLClientGetErrorDescription(uint connectionID)
{
return UnityURLClientBindingInstance.Call<string>("getErrorDescription",
(int)connectionID);
}
public static void _URLClientSetAllowFollowRedirects(
uint connectionID, bool allow, int maxCount)
{
UnityURLClientBindingInstance.Call("setAllowFollowRedirects",
(int)connectionID, allow, maxCount);
}
public static void _URLClientSetAllowInvalidSSLCertificate(
uint connectionID, bool allow)
{
UnityURLClientBindingInstance.Call("setAllowInvalidSSLCertificate",
(int)connectionID, allow);
}
#if false
private static void _URLClientSetRequestContent(
uint connectionID, IntPtr src, ulong srcLength)
{
}
#endif
public static void _URLClientSetRequestContentSource(
uint connectionID, string srcPath)
{
UnityURLClientBindingInstance.Call("setRequestContentSource",
(int)connectionID, srcPath);
}
public static void _URLClientSetRequestHeader(uint connectionID,
string name, string value)
{
UnityURLClientBindingInstance.Call("setRequestHeader",
(int)connectionID, name, value);
}
public static void _URLClientSetRequestAuthCredential(
uint connectionID, string user, string password)
{
UnityURLClientBindingInstance.Call("setRequestAuthCredential",
(int)connectionID, user, password);
}
public static void _URLClientAddAcceptableResponseStatusCodeRange(
uint connectionID, long from, long to)
{
UnityURLClientBindingInstance.Call("addAcceptableResponseStatusCodeRange",
(int)connectionID, from, to);
}
public static void _URLClientSetResponseContentDestination(
uint connectionID, string dstPath, bool allowResume)
{
UnityURLClientBindingInstance.Call("setResponseContentDestination",
(int)connectionID, dstPath, allowResume);
}
public static void _URLClientSendRequest(uint connectionID)
{
UnityURLClientBindingInstance.Call("sendRequest",
(int)connectionID);
}
public static long _URLClientGetResponseStatusCode(
uint connectionID)
{
return UnityURLClientBindingInstance.Call<long>("getResponseStatusCode",
(int)connectionID);
}
public static string _URLClientGetResponseHeaderName(
uint connectionID, uint index)
{
return UnityURLClientBindingInstance.Call<string>("getResponseHeaderName",
(int)connectionID, (int)index);
}
public static string _URLClientGetResponseHeaderValue(
uint connectionID, uint index)
{
return UnityURLClientBindingInstance.Call<string>("getResponseHeaderValue",
(int)connectionID, (int)index);
}
public static int _URLClientGetResponseRedirectCount(
uint connectionID)
{
return UnityURLClientBindingInstance.Call<int>("getResponseRedirectCount",
(int)connectionID);
}
public static ulong _URLClientGetResponseContentLengthRead(
uint connectionID)
{
return (ulong)UnityURLClientBindingInstance.Call<long>("getResponseContentLengthRead",
(int)connectionID);
}
public static long _URLClientGetResponseContentExpectedLength(
uint connectionID)
{
return UnityURLClientBindingInstance.Call<long>("getResponseContentExpectedLength",
(int)connectionID);
}
public static ulong _URLClientGetResponseContentLengthResumed(
uint connectionID)
{
return (ulong)UnityURLClientBindingInstance.Call<long>("getResponseContentLengthResumed",
(int)connectionID);
}
public static ulong _URLClientGetPendingResponseContentLength(
uint connectionID)
{
return (ulong)UnityURLClientBindingInstance.Call<long>("getPendingResponseContentLength",
(int)connectionID);
}
public static bool _URLClientCheckAndResetResponseDirtyFlag(
uint connectionID)
{
return UnityURLClientBindingInstance.Call<bool>("checkAndResetResponseDirtyFlag",
(int)connectionID);
}
#if false
private static ulong _URLClientMovePendingResponseContent(
uint connectionID, IntPtr dst, ulong dstLength)
{
return 0;
}
#endif
public static void _URLClientDestroyConnection(uint connectionID)
{
UnityURLClientBindingInstance.Call("destroyConnection",
(int)connectionID);
}
#else
#endif
public static ConnectionState URLClientGetState(uint connectionID)
{
int state = _URLClientGetState(connectionID);
if ((state < (int)ConnectionState.Initialized) ||
(state > (int)ConnectionState.Cancelled))
{
return ConnectionState.Unknown;
}
return (ConnectionState)state;
}
public static void URLClientSetRequestContent(uint connectionID,
byte[] src, ulong srcLength)
{
#if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_IPHONE
GCHandle pinnedArray = GCHandle.Alloc(src, GCHandleType.Pinned);
IntPtr ptrSrc = pinnedArray.AddrOfPinnedObject();
_URLClientSetRequestContent(connectionID, ptrSrc, srcLength);
pinnedArray.Free();
#elif UNITY_ANDROID
IntPtr rawClass = UnityURLClientBindingInstance.GetRawClass();
IntPtr rawObject = UnityURLClientBindingInstance.GetRawObject();
IntPtr methodPtr = AndroidJNI.GetMethodID(rawClass, "setRequestContent", "(I[BJ)V");
IntPtr v2 = AndroidJNI.ToByteArray( src );
jvalue j1 = new jvalue();
j1.i = (int)connectionID;
jvalue j2 = new jvalue();
j2.l = v2;
jvalue j3 = new jvalue();
j3.j = (long)srcLength;
AndroidJNI.CallVoidMethod( rawObject, methodPtr, new jvalue[]{j1, j2, j3} );
AndroidJNI.DeleteLocalRef(v2);
#endif
}
public static ulong URLClientMovePendingResponseContent(uint connectionID,
byte[] dst, ulong dstLength)
{
ulong length;
#if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_IPHONE
GCHandle pinnedArray = GCHandle.Alloc(dst, GCHandleType.Pinned);
IntPtr ptrDst = pinnedArray.AddrOfPinnedObject();
length = _URLClientMovePendingResponseContent(connectionID, ptrDst,
dstLength);
pinnedArray.Free();
#elif UNITY_ANDROID
IntPtr rawClass = UnityURLClientBindingInstance.GetRawClass();
IntPtr rawObject = UnityURLClientBindingInstance.GetRawObject();
IntPtr methodPtr = AndroidJNI.GetMethodID(rawClass, "movePendingResponseContent", "(I[BJ)J");
IntPtr v2 = AndroidJNI.ToByteArray( dst );
jvalue j1 = new jvalue();
j1.i = (int)connectionID;
jvalue j2 = new jvalue();
j2.l = v2;
jvalue j3 = new jvalue();
j3.j = (long)dstLength;
length = (ulong)AndroidJNI.CallLongMethod( rawObject, methodPtr, new jvalue[]{j1, j2, j3} );
if (dst != null)
{
byte[] resultDst = AndroidJNI.FromByteArray( v2 );
for( ulong n = 0; n < length; ++n ) {
dst[n] = resultDst[n];
}
}
AndroidJNI.DeleteLocalRef(v2);
#endif
return length;
}
}
}
| |
// ----------------------------------------------------------------------------
// <copyright file="PhotonView.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH
// </copyright>
// <summary>
//
// </summary>
// <author>[email protected]</author>
// ----------------------------------------------------------------------------
using System;
using UnityEngine;
using System.Reflection;
using System.Collections.Generic;
using ExitGames.Client.Photon;
#if UNITY_EDITOR
using UnityEditor;
#endif
public enum ViewSynchronization { Off, ReliableDeltaCompressed, Unreliable, UnreliableOnChange }
public enum OnSerializeTransform { OnlyPosition, OnlyRotation, OnlyScale, PositionAndRotation, All }
public enum OnSerializeRigidBody { OnlyVelocity, OnlyAngularVelocity, All }
/// <summary>
/// Options to define how Ownership Transfer is handled per PhotonView.
/// </summary>
/// <remarks>
/// This setting affects how RequestOwnership and TransferOwnership work at runtime.
/// </remarks>
public enum OwnershipOption
{
/// <summary>
/// Ownership is fixed. Instantiated objects stick with their creator, scene objects always belong to the Master Client.
/// </summary>
Fixed,
/// <summary>
/// Ownership can be taken away from the current owner who can't object.
/// </summary>
Takeover,
/// <summary>
/// Ownership can be requested with PhotonView.RequestOwnership but the current owner has to agree to give up ownership.
/// </summary>
/// <remarks>The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.</remarks>
Request
}
/// <summary>
/// PUN's NetworkView replacement class for networking. Use it like a NetworkView.
/// </summary>
/// \ingroup publicApi
[AddComponentMenu("Photon Networking/Photon View &v")]
public class PhotonView : Photon.MonoBehaviour
{
#if UNITY_EDITOR
[ContextMenu("Open PUN Wizard")]
void OpenPunWizard()
{
EditorApplication.ExecuteMenuItem("Window/Photon Unity Networking");
}
#endif
public int ownerId;
public int group = 0;
protected internal bool mixedModeIsReliable = false;
// NOTE: this is now an integer because unity won't serialize short (needed for instantiation). we SEND only a short though!
// NOTE: prefabs have a prefixBackup of -1. this is replaced with any currentLevelPrefix that's used at runtime. instantiated GOs get their prefix set pre-instantiation (so those are not -1 anymore)
public int prefix
{
get
{
if (this.prefixBackup == -1 && PhotonNetwork.networkingPeer != null)
{
this.prefixBackup = PhotonNetwork.networkingPeer.currentLevelPrefix;
}
return this.prefixBackup;
}
set { this.prefixBackup = value; }
}
// this field is serialized by unity. that means it is copied when instantiating a persistent obj into the scene
public int prefixBackup = -1;
/// <summary>
/// This is the instantiationData that was passed when calling PhotonNetwork.Instantiate* (if that was used to spawn this prefab)
/// </summary>
public object[] instantiationData
{
get
{
if (!this.didAwake)
{
// even though viewID and instantiationID are setup before the GO goes live, this data can't be set. as workaround: fetch it if needed
this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId);
}
return this.instantiationDataField;
}
set { this.instantiationDataField = value; }
}
internal object[] instantiationDataField;
/// <summary>
/// For internal use only, don't use
/// </summary>
protected internal object[] lastOnSerializeDataSent = null;
/// <summary>
/// For internal use only, don't use
/// </summary>
protected internal object[] lastOnSerializeDataReceived = null;
public Component observed;
public ViewSynchronization synchronization;
public OnSerializeTransform onSerializeTransformOption = OnSerializeTransform.PositionAndRotation;
public OnSerializeRigidBody onSerializeRigidBodyOption = OnSerializeRigidBody.All;
/// <summary>Defines if ownership of this PhotonView is fixed, can be requested or simply taken.</summary>
/// <remarks>
/// Note that you can't edit this value at runtime.
/// The options are described in enum OwnershipOption.
/// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
/// </remarks>
public OwnershipOption ownershipTransfer = OwnershipOption.Fixed;
public List<Component> ObservedComponents;
Dictionary<Component, MethodInfo> m_OnSerializeMethodInfos = new Dictionary<Component, MethodInfo>();
#if UNITY_EDITOR
// Suppressing compiler warning "this variable is never used". Only used in the CustomEditor, only in Editor
#pragma warning disable 0414
[SerializeField]
bool ObservedComponentsFoldoutOpen = true;
#pragma warning restore 0414
#endif
[SerializeField]
private int viewIdField = 0;
/// <summary>
/// The ID of the PhotonView. Identifies it in a networked game (per room).
/// </summary>
/// <remarks>See: [Network Instantiation](@ref instantiateManual)</remarks>
public int viewID
{
get { return this.viewIdField; }
set
{
// if ID was 0 for an awakened PhotonView, the view should add itself into the networkingPeer.photonViewList after setup
bool viewMustRegister = this.didAwake && this.viewIdField == 0;
// check if this view is in networkingPeer.photonViewList and UPDATE said list (so we don't keep the old viewID with a reference to this object)
// PhotonNetwork.networkingPeer.RemovePhotonView(this, true);
this.ownerId = value / PhotonNetwork.MAX_VIEW_IDS;
this.viewIdField = value;
if (viewMustRegister)
{
PhotonNetwork.networkingPeer.RegisterPhotonView(this);
}
//Debug.Log("Set viewID: " + value + " -> owner: " + this.ownerId + " subId: " + this.subId);
}
}
public int instantiationId; // if the view was instantiated with a GO, this GO has a instantiationID (first view's viewID)
/// <summary>True if the PhotonView was loaded with the scene (game object) or instantiated with InstantiateSceneObject.</summary>
/// <remarks>
/// Scene objects are not owned by a particular player but belong to the scene. Thus they don't get destroyed when their
/// creator leaves the game and the current Master Client can control them (whoever that is).
/// The ownerId is 0 (player IDs are 1 and up).
/// </remarks>
public bool isSceneView
{
get { return this.CreatorActorNr == 0; }
}
/// <summary>
/// The owner of a PhotonView is the player who created the GameObject with that view. Objects in the scene don't have an owner.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
///
/// Ownership can be transferred to another player with PhotonView.TransferOwnership or any player can request
/// ownership by calling the PhotonView's RequestOwnership method.
/// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
/// </remarks>
public PhotonPlayer owner
{
get
{
return PhotonPlayer.Find(this.ownerId);
}
}
public int OwnerActorNr
{
get { return this.ownerId; }
}
public bool isOwnerActive
{
get { return this.ownerId != 0 && PhotonNetwork.networkingPeer.mActors.ContainsKey(this.ownerId); }
}
public int CreatorActorNr
{
get { return this.viewIdField / PhotonNetwork.MAX_VIEW_IDS; }
}
/// <summary>
/// True if the PhotonView is "mine" and can be controlled by this client.
/// </summary>
/// <remarks>
/// PUN has an ownership concept that defines who can control and destroy each PhotonView.
/// True in case the owner matches the local PhotonPlayer.
/// True if this is a scene photonview on the Master client.
/// </remarks>
public bool isMine
{
get
{
return (this.ownerId == PhotonNetwork.player.ID) || (!this.isOwnerActive && PhotonNetwork.isMasterClient);
}
}
protected internal bool didAwake;
[SerializeField]
protected internal bool isRuntimeInstantiated;
protected internal bool removedFromLocalViewList;
internal MonoBehaviour[] RpcMonoBehaviours;
private MethodInfo OnSerializeMethodInfo;
private bool failedToFindOnSerialize;
/// <summary>Called by Unity on start of the application and does a setup the PhotonView.</summary>
protected internal void Awake()
{
if (this.viewID != 0)
{
// registration might be too late when some script (on this GO) searches this view BUT GetPhotonView() can search ALL in that case
PhotonNetwork.networkingPeer.RegisterPhotonView(this);
this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId);
}
this.didAwake = true;
}
/// <summary>
/// Depending on the PhotonView's ownershipTransfer setting, any client can request to become owner of the PhotonView.
/// </summary>
/// <remarks>
/// Requesting ownership can give you control over a PhotonView, if the ownershipTransfer setting allows that.
/// The current owner might have to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
///
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void RequestOwnership()
{
PhotonNetwork.networkingPeer.RequestOwnership(this.viewID, this.ownerId);
}
/// <summary>
/// Transfers the ownership of this PhotonView (and GameObject) to another player.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void TransferOwnership(PhotonPlayer newOwner)
{
this.TransferOwnership(newOwner.ID);
}
/// <summary>
/// Transfers the ownership of this PhotonView (and GameObject) to another player.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void TransferOwnership(int newOwnerId)
{
PhotonNetwork.networkingPeer.TransferOwnership(this.viewID, newOwnerId);
this.ownerId = newOwnerId; // immediately switch ownership locally, to avoid more updates sent from this client.
}
protected internal void OnDestroy()
{
if (!this.removedFromLocalViewList)
{
bool wasInList = PhotonNetwork.networkingPeer.LocalCleanPhotonView(this);
bool loading = false;
#if !UNITY_5 || UNITY_5_0 || UNITY_5_1
loading = Application.isLoadingLevel;
#endif
if (wasInList && !loading && this.instantiationId > 0 && !PhotonHandler.AppQuits && PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
{
Debug.Log("PUN-instantiated '" + this.gameObject.name + "' got destroyed by engine. This is OK when loading levels. Otherwise use: PhotonNetwork.Destroy().");
}
}
}
public void SerializeView(PhotonStream stream, PhotonMessageInfo info)
{
this.SerializeComponent(this.observed, stream, info);
if (this.ObservedComponents != null && this.ObservedComponents.Count > 0)
{
for (int i = 0; i < this.ObservedComponents.Count; ++i)
{
this.SerializeComponent(this.ObservedComponents[i], stream, info);
}
}
}
public void DeserializeView(PhotonStream stream, PhotonMessageInfo info)
{
this.DeserializeComponent(this.observed, stream, info);
if (this.ObservedComponents != null && this.ObservedComponents.Count > 0)
{
for (int i = 0; i < this.ObservedComponents.Count; ++i)
{
this.DeserializeComponent(this.ObservedComponents[i], stream, info);
}
}
}
protected internal void DeserializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info)
{
if (component == null)
{
return;
}
// Use incoming data according to observed type
if (component is MonoBehaviour)
{
this.ExecuteComponentOnSerialize(component, stream, info);
}
else if (component is Transform)
{
Transform trans = (Transform) component;
switch (this.onSerializeTransformOption)
{
case OnSerializeTransform.All:
trans.localPosition = (Vector3) stream.ReceiveNext();
trans.localRotation = (Quaternion) stream.ReceiveNext();
trans.localScale = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyPosition:
trans.localPosition = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyRotation:
trans.localRotation = (Quaternion) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyScale:
trans.localScale = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.PositionAndRotation:
trans.localPosition = (Vector3) stream.ReceiveNext();
trans.localRotation = (Quaternion) stream.ReceiveNext();
break;
}
}
else if (component is Rigidbody)
{
Rigidbody rigidB = (Rigidbody) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
rigidB.velocity = (Vector3) stream.ReceiveNext();
rigidB.angularVelocity = (Vector3) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
rigidB.angularVelocity = (Vector3) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyVelocity:
rigidB.velocity = (Vector3) stream.ReceiveNext();
break;
}
}
else if (component is Rigidbody2D)
{
Rigidbody2D rigidB = (Rigidbody2D) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
rigidB.velocity = (Vector2) stream.ReceiveNext();
rigidB.angularVelocity = (float) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
rigidB.angularVelocity = (float) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyVelocity:
rigidB.velocity = (Vector2) stream.ReceiveNext();
break;
}
}
else
{
Debug.LogError("Type of observed is unknown when receiving.");
}
}
protected internal void SerializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info)
{
if (component == null)
{
return;
}
if (component is MonoBehaviour)
{
this.ExecuteComponentOnSerialize(component, stream, info);
}
else if (component is Transform)
{
Transform trans = (Transform) component;
switch (this.onSerializeTransformOption)
{
case OnSerializeTransform.All:
stream.SendNext(trans.localPosition);
stream.SendNext(trans.localRotation);
stream.SendNext(trans.localScale);
break;
case OnSerializeTransform.OnlyPosition:
stream.SendNext(trans.localPosition);
break;
case OnSerializeTransform.OnlyRotation:
stream.SendNext(trans.localRotation);
break;
case OnSerializeTransform.OnlyScale:
stream.SendNext(trans.localScale);
break;
case OnSerializeTransform.PositionAndRotation:
stream.SendNext(trans.localPosition);
stream.SendNext(trans.localRotation);
break;
}
}
else if (component is Rigidbody)
{
Rigidbody rigidB = (Rigidbody) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
stream.SendNext(rigidB.velocity);
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyVelocity:
stream.SendNext(rigidB.velocity);
break;
}
}
else if (component is Rigidbody2D)
{
Rigidbody2D rigidB = (Rigidbody2D) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
stream.SendNext(rigidB.velocity);
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyVelocity:
stream.SendNext(rigidB.velocity);
break;
}
}
else
{
Debug.LogError("Observed type is not serializable: " + component.GetType());
}
}
protected internal void ExecuteComponentOnSerialize(Component component, PhotonStream stream, PhotonMessageInfo info)
{
if (component != null)
{
if (this.m_OnSerializeMethodInfos.ContainsKey(component) == false)
{
MethodInfo newMethod = null;
bool foundMethod = NetworkingPeer.GetMethod(component as MonoBehaviour, PhotonNetworkingMessage.OnPhotonSerializeView.ToString(), out newMethod);
if (foundMethod == false)
{
Debug.LogError("The observed monobehaviour (" + component.name + ") of this PhotonView does not implement OnPhotonSerializeView()!");
newMethod = null;
}
this.m_OnSerializeMethodInfos.Add(component, newMethod);
}
if (this.m_OnSerializeMethodInfos[component] != null)
{
this.m_OnSerializeMethodInfos[component].Invoke(component, new object[] {stream, info});
}
}
}
/// <summary>
/// Can be used to refesh the list of MonoBehaviours on this GameObject while PhotonNetwork.UseRpcMonoBehaviourCache is true.
/// </summary>
/// <remarks>
/// Set PhotonNetwork.UseRpcMonoBehaviourCache to true to enable the caching.
/// Uses this.GetComponents<MonoBehaviour>() to get a list of MonoBehaviours to call RPCs on (potentially).
///
/// While PhotonNetwork.UseRpcMonoBehaviourCache is false, this method has no effect,
/// because the list is refreshed when a RPC gets called.
/// </remarks>
public void RefreshRpcMonoBehaviourCache()
{
this.RpcMonoBehaviours = this.GetComponents<MonoBehaviour>();
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// RPC calls can target "All" or the "Others".
/// Usually, the target "All" gets executed locally immediately after sending the RPC.
/// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
/// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
/// <param name="target">The group of targets and the way the RPC gets sent.</param>
/// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RPC(string methodName, PhotonTargets target, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, target, false, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// RPC calls can target "All" or the "Others".
/// Usually, the target "All" gets executed locally immediately after sending the RPC.
/// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
///<param name="target">The group of targets and the way the RPC gets sent.</param>
///<param name="encrypt"> </param>
///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RpcSecure(string methodName, PhotonTargets target, bool encrypt, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, target, encrypt, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// This method allows you to make an RPC calls on a specific player's client.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
/// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
/// <param name="targetPlayer">The group of targets and the way the RPC gets sent.</param>
/// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RPC(string methodName, PhotonPlayer targetPlayer, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, targetPlayer, false, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// This method allows you to make an RPC calls on a specific player's client.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
///<param name="targetPlayer">The group of targets and the way the RPC gets sent.</param>
///<param name="encrypt"> </param>
///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RpcSecure(string methodName, PhotonPlayer targetPlayer, bool encrypt, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, targetPlayer, encrypt, parameters);
}
public static PhotonView Get(Component component)
{
return component.GetComponent<PhotonView>();
}
public static PhotonView Get(GameObject gameObj)
{
return gameObj.GetComponent<PhotonView>();
}
public static PhotonView Find(int viewID)
{
return PhotonNetwork.networkingPeer.GetPhotonView(viewID);
}
public override string ToString()
{
return string.Format("View ({3}){0} on {1} {2}", this.viewID, (this.gameObject != null) ? this.gameObject.name : "GO==null", (this.isSceneView) ? "(scene)" : string.Empty, this.prefix);
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// This editor helper class makes it easy to create and show a context menu.
/// It ensures that it's possible to add multiple items with the same name.
/// </summary>
public static class NGUIContextMenu
{
[MenuItem("Help/NGUI Documentation (v.3.7.3)")]
static void ShowHelp0 (MenuCommand command) { NGUIHelp.Show(); }
[MenuItem("Help/NGUI Support Forum")]
static void ShowHelp01 (MenuCommand command) { Application.OpenURL("http://www.tasharen.com/forum/index.php?board=1.0"); }
[MenuItem("CONTEXT/UIWidget/Copy Widget")]
static void CopyStyle (MenuCommand command) { NGUISettings.CopyWidget(command.context as UIWidget); }
[MenuItem("CONTEXT/UIWidget/Paste Widget Values")]
static void PasteStyle (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, true); }
[MenuItem("CONTEXT/UIWidget/Paste Widget Style")]
static void PasteStyle2 (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, false); }
[MenuItem("CONTEXT/UIWidget/Help")]
static void ShowHelp1 (MenuCommand command) { NGUIHelp.Show(command.context); }
[MenuItem("CONTEXT/UIButton/Help")]
static void ShowHelp2 (MenuCommand command) { NGUIHelp.Show(typeof(UIButton)); }
[MenuItem("CONTEXT/UIToggle/Help")]
static void ShowHelp3 (MenuCommand command) { NGUIHelp.Show(typeof(UIToggle)); }
[MenuItem("CONTEXT/UIRoot/Help")]
static void ShowHelp4 (MenuCommand command) { NGUIHelp.Show(typeof(UIRoot)); }
[MenuItem("CONTEXT/UICamera/Help")]
static void ShowHelp5 (MenuCommand command) { NGUIHelp.Show(typeof(UICamera)); }
[MenuItem("CONTEXT/UIAnchor/Help")]
static void ShowHelp6 (MenuCommand command) { NGUIHelp.Show(typeof(UIAnchor)); }
[MenuItem("CONTEXT/UIStretch/Help")]
static void ShowHelp7 (MenuCommand command) { NGUIHelp.Show(typeof(UIStretch)); }
[MenuItem("CONTEXT/UISlider/Help")]
static void ShowHelp8 (MenuCommand command) { NGUIHelp.Show(typeof(UISlider)); }
[MenuItem("CONTEXT/UI2DSprite/Help")]
static void ShowHelp9 (MenuCommand command) { NGUIHelp.Show(typeof(UI2DSprite)); }
[MenuItem("CONTEXT/UIScrollBar/Help")]
static void ShowHelp10 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollBar)); }
[MenuItem("CONTEXT/UIProgressBar/Help")]
static void ShowHelp11 (MenuCommand command) { NGUIHelp.Show(typeof(UIProgressBar)); }
[MenuItem("CONTEXT/UIPopupList/Help")]
static void ShowHelp12 (MenuCommand command) { NGUIHelp.Show(typeof(UIPopupList)); }
[MenuItem("CONTEXT/UIInput/Help")]
static void ShowHelp13 (MenuCommand command) { NGUIHelp.Show(typeof(UIInput)); }
[MenuItem("CONTEXT/UIKeyBinding/Help")]
static void ShowHelp14 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyBinding)); }
[MenuItem("CONTEXT/UIGrid/Help")]
static void ShowHelp15 (MenuCommand command) { NGUIHelp.Show(typeof(UIGrid)); }
[MenuItem("CONTEXT/UITable/Help")]
static void ShowHelp16 (MenuCommand command) { NGUIHelp.Show(typeof(UITable)); }
[MenuItem("CONTEXT/UIPlayTween/Help")]
static void ShowHelp17 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayTween)); }
[MenuItem("CONTEXT/UIPlayAnimation/Help")]
static void ShowHelp18 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); }
[MenuItem("CONTEXT/UIPlaySound/Help")]
static void ShowHelp19 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlaySound)); }
[MenuItem("CONTEXT/UIScrollView/Help")]
static void ShowHelp20 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); }
[MenuItem("CONTEXT/UIDragScrollView/Help")]
static void ShowHelp21 (MenuCommand command) { NGUIHelp.Show(typeof(UIDragScrollView)); }
[MenuItem("CONTEXT/UICenterOnChild/Help")]
static void ShowHelp22 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnChild)); }
[MenuItem("CONTEXT/UICenterOnClick/Help")]
static void ShowHelp23 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnClick)); }
[MenuItem("CONTEXT/UITweener/Help")]
[MenuItem("CONTEXT/UIPlayTween/Help")]
static void ShowHelp24 (MenuCommand command) { NGUIHelp.Show(typeof(UITweener)); }
[MenuItem("CONTEXT/ActiveAnimation/Help")]
[MenuItem("CONTEXT/UIPlayAnimation/Help")]
static void ShowHelp25 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); }
[MenuItem("CONTEXT/UIScrollView/Help")]
[MenuItem("CONTEXT/UIDragScrollView/Help")]
static void ShowHelp26 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); }
[MenuItem("CONTEXT/UIPanel/Help")]
static void ShowHelp27 (MenuCommand command) { NGUIHelp.Show(typeof(UIPanel)); }
[MenuItem("CONTEXT/UILocalize/Help")]
static void ShowHelp28 (MenuCommand command) { NGUIHelp.Show(typeof(UILocalize)); }
[MenuItem("CONTEXT/Localization/Help")]
static void ShowHelp29 (MenuCommand command) { NGUIHelp.Show(typeof(Localization)); }
[MenuItem("CONTEXT/UIKeyNavigation/Help")]
static void ShowHelp30 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyNavigation)); }
[MenuItem("CONTEXT/PropertyBinding/Help")]
static void ShowHelp31 (MenuCommand command) { NGUIHelp.Show(typeof(PropertyBinding)); }
public delegate UIWidget AddFunc (GameObject go);
static List<string> mEntries = new List<string>();
static GenericMenu mMenu;
/// <summary>
/// Clear the context menu list.
/// </summary>
static public void Clear ()
{
mEntries.Clear();
mMenu = null;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddItem (string item, bool isChecked, GenericMenu.MenuFunction2 callback, object param)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.Count; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, callback, param);
}
else AddDisabledItem(item);
}
/// <summary>
/// Wrapper function called by the menu that in turn calls the correct callback.
/// </summary>
static public void AddChild (object obj)
{
AddFunc func = obj as AddFunc;
UIWidget widget = func(Selection.activeGameObject);
if (widget != null) Selection.activeGameObject = widget.gameObject;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddChildWidget (string item, bool isChecked, AddFunc callback)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.Count; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, AddChild, callback);
}
else AddDisabledItem(item);
}
/// <summary>
/// Wrapper function called by the menu that in turn calls the correct callback.
/// </summary>
static public void AddSibling (object obj)
{
AddFunc func = obj as AddFunc;
UIWidget widget = func(Selection.activeTransform.parent.gameObject);
if (widget != null) Selection.activeGameObject = widget.gameObject;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddSiblingWidget (string item, bool isChecked, AddFunc callback)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.Count; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, AddSibling, callback);
}
else AddDisabledItem(item);
}
/// <summary>
/// Add commonly NGUI context menu options.
/// </summary>
static public void AddCommonItems (GameObject target)
{
if (target != null)
{
UIWidget widget = target.GetComponent<UIWidget>();
string myName = string.Format("Selected {0}", (widget != null) ? NGUITools.GetTypeName(widget) : "Object");
AddItem(myName + "/Bring to Front", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.BringForward(Selection.gameObjects[i]);
},
null);
AddItem(myName + "/Push to Back", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.PushBack(Selection.gameObjects[i]);
},
null);
AddItem(myName + "/Nudge Forward", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AdjustDepth(Selection.gameObjects[i], 1);
},
null);
AddItem(myName + "/Nudge Back", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AdjustDepth(Selection.gameObjects[i], -1);
},
null);
if (widget != null)
{
NGUIContextMenu.AddSeparator(myName + "/");
AddItem(myName + "/Make Pixel-Perfect", false, OnMakePixelPerfect, Selection.activeTransform);
if (target.GetComponent<BoxCollider>() != null)
{
AddItem(myName + "/Reset Collider Size", false, OnBoxCollider, target);
}
}
NGUIContextMenu.AddSeparator(myName + "/");
AddItem(myName + "/Delete", false, OnDelete, target);
NGUIContextMenu.AddSeparator("");
if (Selection.activeTransform.parent != null && widget != null)
{
AddChildWidget("Create/Sprite/Child", false, NGUISettings.AddSprite);
AddChildWidget("Create/Label/Child", false, NGUISettings.AddLabel);
AddChildWidget("Create/Invisible Widget/Child", false, NGUISettings.AddWidget);
AddChildWidget("Create/Simple Texture/Child", false, NGUISettings.AddTexture);
AddChildWidget("Create/Unity 2D Sprite/Child", false, NGUISettings.Add2DSprite);
AddSiblingWidget("Create/Sprite/Sibling", false, NGUISettings.AddSprite);
AddSiblingWidget("Create/Label/Sibling", false, NGUISettings.AddLabel);
AddSiblingWidget("Create/Invisible Widget/Sibling", false, NGUISettings.AddWidget);
AddSiblingWidget("Create/Simple Texture/Sibling", false, NGUISettings.AddTexture);
AddSiblingWidget("Create/Unity 2D Sprite/Sibling", false, NGUISettings.Add2DSprite);
}
else
{
AddChildWidget("Create/Sprite", false, NGUISettings.AddSprite);
AddChildWidget("Create/Label", false, NGUISettings.AddLabel);
AddChildWidget("Create/Invisible Widget", false, NGUISettings.AddWidget);
AddChildWidget("Create/Simple Texture", false, NGUISettings.AddTexture);
AddChildWidget("Create/Unity 2D Sprite", false, NGUISettings.Add2DSprite);
}
NGUIContextMenu.AddSeparator("Create/");
AddItem("Create/Panel", false, AddPanel, target);
AddItem("Create/Scroll View", false, AddScrollView, target);
AddItem("Create/Grid", false, AddChild<UIGrid>, target);
AddItem("Create/Table", false, AddChild<UITable>, target);
AddItem("Create/Anchor (Legacy)", false, AddChild<UIAnchor>, target);
if (target.GetComponent<UIPanel>() != null)
{
if (target.GetComponent<UIScrollView>() == null)
{
AddItem("Attach/Scroll View", false, Attach, typeof(UIScrollView));
NGUIContextMenu.AddSeparator("Attach/");
}
}
else if (target.GetComponent<Collider>() == null && target.GetComponent<Collider2D>() == null)
{
AddItem("Attach/Box Collider", false, AttachCollider, null);
NGUIContextMenu.AddSeparator("Attach/");
}
bool header = false;
UIScrollView scrollView = NGUITools.FindInParents<UIScrollView>(target);
if (scrollView != null)
{
if (scrollView.GetComponentInChildren<UICenterOnChild>() == null)
{
AddItem("Attach/Center Scroll View on Child", false, Attach, typeof(UICenterOnChild));
header = true;
}
}
if (target.GetComponent<Collider>() != null || target.GetComponent<Collider2D>() != null)
{
if (scrollView != null)
{
if (target.GetComponent<UIDragScrollView>() == null)
{
AddItem("Attach/Drag Scroll View", false, Attach, typeof(UIDragScrollView));
header = true;
}
if (target.GetComponent<UICenterOnClick>() == null && NGUITools.FindInParents<UICenterOnChild>(target) != null)
{
AddItem("Attach/Center Scroll View on Click", false, Attach, typeof(UICenterOnClick));
header = true;
}
}
if (header) NGUIContextMenu.AddSeparator("Attach/");
AddItem("Attach/Button Script", false, Attach, typeof(UIButton));
AddItem("Attach/Toggle Script", false, Attach, typeof(UIToggle));
AddItem("Attach/Slider Script", false, Attach, typeof(UISlider));
AddItem("Attach/Scroll Bar Script", false, Attach, typeof(UIScrollBar));
AddItem("Attach/Progress Bar Script", false, Attach, typeof(UISlider));
AddItem("Attach/Popup List Script", false, Attach, typeof(UIPopupList));
AddItem("Attach/Input Field Script", false, Attach, typeof(UIInput));
NGUIContextMenu.AddSeparator("Attach/");
if (target.GetComponent<UIDragResize>() == null)
AddItem("Attach/Drag Resize Script", false, Attach, typeof(UIDragResize));
if (target.GetComponent<UIDragScrollView>() == null)
{
for (int i = 0; i < UIPanel.list.Count; ++i)
{
UIPanel pan = UIPanel.list[i];
if (pan.clipping == UIDrawCall.Clipping.None) continue;
UIScrollView dr = pan.GetComponent<UIScrollView>();
if (dr == null) continue;
AddItem("Attach/Drag Scroll View", false, delegate(object obj)
{ target.AddComponent<UIDragScrollView>().scrollView = dr; }, null);
header = true;
break;
}
}
AddItem("Attach/Key Binding Script", false, Attach, typeof(UIKeyBinding));
if (target.GetComponent<UIKeyNavigation>() == null)
AddItem("Attach/Key Navigation Script", false, Attach, typeof(UIKeyNavigation));
NGUIContextMenu.AddSeparator("Attach/");
AddItem("Attach/Play Tween Script", false, Attach, typeof(UIPlayTween));
AddItem("Attach/Play Animation Script", false, Attach, typeof(UIPlayAnimation));
AddItem("Attach/Play Sound Script", false, Attach, typeof(UIPlaySound));
}
AddItem("Attach/Property Binding", false, Attach, typeof(PropertyBinding));
if (target.GetComponent<UILocalize>() == null)
AddItem("Attach/Localization Script", false, Attach, typeof(UILocalize));
if (widget != null)
{
AddMissingItem<TweenAlpha>(target, "Tween/Alpha");
AddMissingItem<TweenColor>(target, "Tween/Color");
AddMissingItem<TweenWidth>(target, "Tween/Width");
AddMissingItem<TweenHeight>(target, "Tween/Height");
}
else if (target.GetComponent<UIPanel>() != null)
{
AddMissingItem<TweenAlpha>(target, "Tween/Alpha");
}
NGUIContextMenu.AddSeparator("Tween/");
AddMissingItem<TweenPosition>(target, "Tween/Position");
AddMissingItem<TweenRotation>(target, "Tween/Rotation");
AddMissingItem<TweenScale>(target, "Tween/Scale");
AddMissingItem<TweenTransform>(target, "Tween/Transform");
if (target.GetComponent<AudioSource>() != null)
AddMissingItem<TweenVolume>(target, "Tween/Volume");
if (target.GetComponent<Camera>() != null)
{
AddMissingItem<TweenFOV>(target, "Tween/Field of View");
AddMissingItem<TweenOrthoSize>(target, "Tween/Orthographic Size");
}
}
}
/// <summary>
/// Helper function that adds a widget collider to the specified object.
/// </summary>
static void AttachCollider (object obj)
{
if (Selection.activeGameObject != null)
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AddWidgetCollider(Selection.gameObjects[i]);
}
/// <summary>
/// Helper function that adds the specified type to all selected game objects. Used with the menu options above.
/// </summary>
static void Attach (object obj)
{
if (Selection.activeGameObject == null) return;
System.Type type = (System.Type)obj;
for (int i = 0; i < Selection.gameObjects.Length; ++i)
{
GameObject go = Selection.gameObjects[i];
if (go.GetComponent(type) != null) continue;
#if !UNITY_3_5
Component cmp = go.AddComponent(type);
Undo.RegisterCreatedObjectUndo(cmp, "Attach " + type);
#endif
}
}
/// <summary>
/// Helper function.
/// </summary>
static void AddMissingItem<T> (GameObject target, string name) where T : MonoBehaviour
{
if (target.GetComponent<T>() == null)
AddItem(name, false, Attach, typeof(T));
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddChild<T> (object obj) where T : MonoBehaviour
{
GameObject go = obj as GameObject;
T t = NGUITools.AddChild<T>(go);
Selection.activeGameObject = t.gameObject;
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddPanel (object obj)
{
GameObject go = obj as GameObject;
if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject;
UIPanel panel = NGUISettings.AddPanel(go);
Selection.activeGameObject = panel.gameObject;
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddScrollView (object obj)
{
GameObject go = obj as GameObject;
if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject;
UIPanel panel = NGUISettings.AddPanel(go);
panel.clipping = UIDrawCall.Clipping.SoftClip;
panel.gameObject.AddComponent<UIScrollView>();
panel.name = "Scroll View";
Selection.activeGameObject = panel.gameObject;
}
/// <summary>
/// Add help options based on the components present on the specified game object.
/// </summary>
static public void AddHelp (GameObject go, bool addSeparator)
{
MonoBehaviour[] comps = Selection.activeGameObject.GetComponents<MonoBehaviour>();
bool addedSomething = false;
for (int i = 0; i < comps.Length; ++i)
{
System.Type type = comps[i].GetType();
string url = NGUIHelp.GetHelpURL(type);
if (url != null)
{
if (addSeparator)
{
addSeparator = false;
AddSeparator("");
}
AddItem("Help/" + type, false, delegate(object obj) { Application.OpenURL(url); }, null);
addedSomething = true;
}
}
if (addedSomething) AddSeparator("Help/");
AddItem("Help/All Topics", false, delegate(object obj) { NGUIHelp.Show(); }, null);
}
static void OnHelp (object obj) { NGUIHelp.Show(obj); }
static void OnMakePixelPerfect (object obj) { NGUITools.MakePixelPerfect(obj as Transform); }
static void OnBoxCollider (object obj) { NGUITools.AddWidgetCollider(obj as GameObject); }
static void OnDelete (object obj)
{
GameObject go = obj as GameObject;
Selection.activeGameObject = go.transform.parent.gameObject;
Undo.DestroyObjectImmediate(go);
}
/// <summary>
/// Add a new disabled context menu entry.
/// </summary>
static public void AddDisabledItem (string item)
{
if (mMenu == null) mMenu = new GenericMenu();
mMenu.AddDisabledItem(new GUIContent(item));
}
/// <summary>
/// Add a separator to the menu.
/// </summary>
static public void AddSeparator (string path)
{
if (mMenu == null) mMenu = new GenericMenu();
// For some weird reason adding separators on OSX causes the entire menu to be disabled. Wtf?
if (Application.platform != RuntimePlatform.OSXEditor)
mMenu.AddSeparator(path);
}
/// <summary>
/// Show the context menu with all the added items.
/// </summary>
static public void Show ()
{
if (mMenu != null)
{
mMenu.ShowAsContext();
mMenu = null;
mEntries.Clear();
}
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.Serialization;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
namespace UIWidgets {
/// <summary>
/// AccordionDirection.
/// </summary>
public enum AccordionDirection {
Horizontal = 0,
Vertical = 1,
}
/// <summary>
/// Accordion.
/// </summary>
[AddComponentMenu("UI/UIWidgets/Accordion")]
public class Accordion : MonoBehaviour {
/// <summary>
/// The items.
/// </summary>
[SerializeField]
[FormerlySerializedAs("Items")]
protected List<AccordionItem> items = new List<AccordionItem>();
/// <summary>
/// Gets the items.
/// </summary>
/// <value>The items.</value>
public List<AccordionItem> Items {
get {
return items;
}
protected set {
if (items!=null)
{
RemoveCallbacks();
}
items = value;
if (items!=null)
{
AddCallbacks();
}
}
}
/// <summary>
/// Only one item can be opened.
/// </summary>
[SerializeField]
public bool OnlyOneOpen = true;
/// <summary>
/// Animate open and close.
/// </summary>
[SerializeField]
public bool Animate = true;
/// <summary>
/// The duration of the animation.
/// </summary>
[SerializeField]
public float AnimationDuration = 0.5f;
/// <summary>
/// The direction.
/// </summary>
[SerializeField]
public AccordionDirection Direction = AccordionDirection.Vertical;
/// <summary>
/// OnToggleItem event.
/// </summary>
[SerializeField]
public AccordionEvent OnToggleItem = new AccordionEvent();
/// <summary>
/// The callbacks.
/// </summary>
protected List<UnityAction> callbacks = new List<UnityAction>();
/// <summary>
/// Start this instance.
/// </summary>
protected virtual void Start()
{
AddCallbacks();
UpdateLayout();
}
/// <summary>
/// Adds the callback.
/// </summary>
/// <param name="item">Item.</param>
protected virtual void AddCallback(AccordionItem item)
{
if (item.Open)
{
Open(item, false);
}
else
{
Close(item, false);
}
UnityAction callback = () => ToggleItem(item);
item.ToggleObject.AddComponent<AccordionItemComponent>().OnClick.AddListener(callback);
item.ContentObjectRect = item.ContentObject.transform as RectTransform;
item.ContentLayoutElement = item.ContentObject.GetComponent<LayoutElement>();
if (item.ContentLayoutElement==null)
{
item.ContentLayoutElement = item.ContentObject.AddComponent<LayoutElement>();
}
item.ContentObjectHeight = item.ContentObjectRect.rect.height;
if (item.ContentObjectHeight==0f)
{
item.ContentObjectHeight = item.ContentLayoutElement.preferredHeight;
}
item.ContentObjectWidth = item.ContentObjectRect.rect.width;
if (item.ContentObjectWidth==0f)
{
item.ContentObjectWidth = item.ContentLayoutElement.preferredWidth;
}
callbacks.Add(callback);
}
/// <summary>
/// Adds the callbacks.
/// </summary>
protected virtual void AddCallbacks()
{
Items.ForEach(AddCallback);
}
/// <summary>
/// Removes the callback.
/// </summary>
/// <param name="item">Item.</param>
/// <param name="index">Index.</param>
protected virtual void RemoveCallback(AccordionItem item, int index)
{
if (item==null)
{
return ;
}
if (item.ToggleObject==null)
{
return ;
}
var component = item.ToggleObject.GetComponent<AccordionItemComponent>();
if ((component!=null) && (index < callbacks.Count))
{
component.OnClick.RemoveListener(callbacks[index]);
}
}
/// <summary>
/// Removes the callbacks.
/// </summary>
protected virtual void RemoveCallbacks()
{
Items.ForEach(RemoveCallback);
callbacks.Clear();
}
/// <summary>
/// This function is called when the MonoBehaviour will be destroyed.
/// </summary>
protected virtual void OnDestroy()
{
RemoveCallbacks();
}
/// <summary>
/// Toggles the item.
/// </summary>
/// <param name="item">Item.</param>
public virtual void ToggleItem(AccordionItem item)
{
if (item.Open)
{
if (!OnlyOneOpen)
{
Close(item);
}
}
else
{
if (OnlyOneOpen)
{
Items.Where(IsOpen).ForEach(Close);
}
Open(item);
}
}
/// <summary>
/// Open the specified item.
/// </summary>
/// <param name="item">Item.</param>
public virtual void Open(AccordionItem item)
{
if (item.Open)
{
return ;
}
if (OnlyOneOpen)
{
Items.Where(IsOpen).ForEach(Close);
}
Open(item, Animate);
}
/// <summary>
/// Close the specified item.
/// </summary>
/// <param name="item">Item.</param>
public virtual void Close(AccordionItem item)
{
if (!item.Open)
{
return ;
}
Close(item, Animate);
}
/// <summary>
/// Determines whether this instance is open the specified item.
/// </summary>
/// <returns><c>true</c> if this instance is open the specified item; otherwise, <c>false</c>.</returns>
/// <param name="item">Item.</param>
protected bool IsOpen(AccordionItem item)
{
return item.Open;
}
/// <summary>
/// Determines whether this instance is horizontal.
/// </summary>
/// <returns><c>true</c> if this instance is horizontal; otherwise, <c>false</c>.</returns>
protected bool IsHorizontal()
{
return Direction==AccordionDirection.Horizontal;
}
/// <summary>
/// Open the specified item and animate.
/// </summary>
/// <param name="item">Item.</param>
/// <param name="animate">If set to <c>true</c> animate.</param>
protected virtual void Open(AccordionItem item, bool animate)
{
if (item.CurrentCorutine!=null)
{
StopCoroutine(item.CurrentCorutine);
if (IsHorizontal())
{
item.ContentObjectRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, item.ContentObjectWidth);
item.ContentLayoutElement.preferredWidth = item.ContentObjectWidth;
}
else
{
item.ContentObjectRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, item.ContentObjectHeight);
item.ContentLayoutElement.preferredHeight = item.ContentObjectHeight;
}
item.ContentObject.SetActive(false);
}
if (animate)
{
item.CurrentCorutine = StartCoroutine(OpenCorutine(item));
}
else
{
item.ContentObject.SetActive(true);
OnToggleItem.Invoke(item);
}
item.ContentObject.SetActive(true);
item.Open = true;
}
/// <summary>
/// Close the specified item and animate.
/// </summary>
/// <param name="item">Item.</param>
/// <param name="animate">If set to <c>true</c> animate.</param>
protected virtual void Close(AccordionItem item, bool animate)
{
if (item.CurrentCorutine!=null)
{
StopCoroutine(item.CurrentCorutine);
item.ContentObject.SetActive(true);
if (IsHorizontal())
{
item.ContentObjectRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, item.ContentObjectWidth);
item.ContentLayoutElement.preferredWidth = item.ContentObjectWidth;
}
else
{
item.ContentObjectRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, item.ContentObjectHeight);
item.ContentLayoutElement.preferredHeight = item.ContentObjectHeight;
}
}
if (item.ContentObjectRect!=null)
{
item.ContentObjectHeight = item.ContentObjectRect.rect.height;
item.ContentObjectWidth = item.ContentObjectRect.rect.width;
}
if (animate)
{
item.CurrentCorutine = StartCoroutine(HideCorutine(item));
}
else
{
item.ContentObject.SetActive(false);
item.Open = false;
OnToggleItem.Invoke(item);
}
}
/// <summary>
/// Opens the corutine.
/// </summary>
/// <returns>The corutine.</returns>
/// <param name="item">Item.</param>
protected virtual IEnumerator OpenCorutine(AccordionItem item)
{
item.ContentObject.SetActive(true);
item.Open = true;
yield return StartCoroutine(Animations.Open(item.ContentObjectRect, AnimationDuration, IsHorizontal()));
UpdateLayout();
OnToggleItem.Invoke(item);
}
/// <summary>
/// Updates the layout.
/// </summary>
protected void UpdateLayout()
{
Utilites.UpdateLayout(GetComponent<LayoutGroup>());
}
/// <summary>
/// Hides the corutine.
/// </summary>
/// <returns>The corutine.</returns>
/// <param name="item">Item.</param>
protected virtual IEnumerator HideCorutine(AccordionItem item)
{
yield return StartCoroutine(Animations.Collapse(item.ContentObjectRect, AnimationDuration, IsHorizontal()));
item.Open = false;
item.ContentObject.SetActive(false);
UpdateLayout();
OnToggleItem.Invoke(item);
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Media.Immutable;
namespace Avalonia.Media
{
/// <summary>
/// Predefined brushes.
/// </summary>
public static class Brushes
{
/// <summary>
/// Initializes static members of the <see cref="Brushes"/> class.
/// </summary>
static Brushes()
{
AliceBlue = new ImmutableSolidColorBrush(Colors.AliceBlue);
AntiqueWhite = new ImmutableSolidColorBrush(Colors.AntiqueWhite);
Aqua = new ImmutableSolidColorBrush(Colors.Aqua);
Aquamarine = new ImmutableSolidColorBrush(Colors.Aquamarine);
Azure = new ImmutableSolidColorBrush(Colors.Azure);
Beige = new ImmutableSolidColorBrush(Colors.Beige);
Bisque = new ImmutableSolidColorBrush(Colors.Bisque);
Black = new ImmutableSolidColorBrush(Colors.Black);
BlanchedAlmond = new ImmutableSolidColorBrush(Colors.BlanchedAlmond);
Blue = new ImmutableSolidColorBrush(Colors.Blue);
BlueViolet = new ImmutableSolidColorBrush(Colors.BlueViolet);
Brown = new ImmutableSolidColorBrush(Colors.Brown);
BurlyWood = new ImmutableSolidColorBrush(Colors.BurlyWood);
CadetBlue = new ImmutableSolidColorBrush(Colors.CadetBlue);
Chartreuse = new ImmutableSolidColorBrush(Colors.Chartreuse);
Chocolate = new ImmutableSolidColorBrush(Colors.Chocolate);
Coral = new ImmutableSolidColorBrush(Colors.Coral);
CornflowerBlue = new ImmutableSolidColorBrush(Colors.CornflowerBlue);
Cornsilk = new ImmutableSolidColorBrush(Colors.Cornsilk);
Crimson = new ImmutableSolidColorBrush(Colors.Crimson);
Cyan = new ImmutableSolidColorBrush(Colors.Cyan);
DarkBlue = new ImmutableSolidColorBrush(Colors.DarkBlue);
DarkCyan = new ImmutableSolidColorBrush(Colors.DarkCyan);
DarkGoldenrod = new ImmutableSolidColorBrush(Colors.DarkGoldenrod);
DarkGray = new ImmutableSolidColorBrush(Colors.DarkGray);
DarkGreen = new ImmutableSolidColorBrush(Colors.DarkGreen);
DarkKhaki = new ImmutableSolidColorBrush(Colors.DarkKhaki);
DarkMagenta = new ImmutableSolidColorBrush(Colors.DarkMagenta);
DarkOliveGreen = new ImmutableSolidColorBrush(Colors.DarkOliveGreen);
DarkOrange = new ImmutableSolidColorBrush(Colors.DarkOrange);
DarkOrchid = new ImmutableSolidColorBrush(Colors.DarkOrchid);
DarkRed = new ImmutableSolidColorBrush(Colors.DarkRed);
DarkSalmon = new ImmutableSolidColorBrush(Colors.DarkSalmon);
DarkSeaGreen = new ImmutableSolidColorBrush(Colors.DarkSeaGreen);
DarkSlateBlue = new ImmutableSolidColorBrush(Colors.DarkSlateBlue);
DarkSlateGray = new ImmutableSolidColorBrush(Colors.DarkSlateGray);
DarkTurquoise = new ImmutableSolidColorBrush(Colors.DarkTurquoise);
DarkViolet = new ImmutableSolidColorBrush(Colors.DarkViolet);
DeepPink = new ImmutableSolidColorBrush(Colors.DeepPink);
DeepSkyBlue = new ImmutableSolidColorBrush(Colors.DeepSkyBlue);
DimGray = new ImmutableSolidColorBrush(Colors.DimGray);
DodgerBlue = new ImmutableSolidColorBrush(Colors.DodgerBlue);
Firebrick = new ImmutableSolidColorBrush(Colors.Firebrick);
FloralWhite = new ImmutableSolidColorBrush(Colors.FloralWhite);
ForestGreen = new ImmutableSolidColorBrush(Colors.ForestGreen);
Fuchsia = new ImmutableSolidColorBrush(Colors.Fuchsia);
Gainsboro = new ImmutableSolidColorBrush(Colors.Gainsboro);
GhostWhite = new ImmutableSolidColorBrush(Colors.GhostWhite);
Gold = new ImmutableSolidColorBrush(Colors.Gold);
Goldenrod = new ImmutableSolidColorBrush(Colors.Goldenrod);
Gray = new ImmutableSolidColorBrush(Colors.Gray);
Green = new ImmutableSolidColorBrush(Colors.Green);
GreenYellow = new ImmutableSolidColorBrush(Colors.GreenYellow);
Honeydew = new ImmutableSolidColorBrush(Colors.Honeydew);
HotPink = new ImmutableSolidColorBrush(Colors.HotPink);
IndianRed = new ImmutableSolidColorBrush(Colors.IndianRed);
Indigo = new ImmutableSolidColorBrush(Colors.Indigo);
Ivory = new ImmutableSolidColorBrush(Colors.Ivory);
Khaki = new ImmutableSolidColorBrush(Colors.Khaki);
Lavender = new ImmutableSolidColorBrush(Colors.Lavender);
LavenderBlush = new ImmutableSolidColorBrush(Colors.LavenderBlush);
LawnGreen = new ImmutableSolidColorBrush(Colors.LawnGreen);
LemonChiffon = new ImmutableSolidColorBrush(Colors.LemonChiffon);
LightBlue = new ImmutableSolidColorBrush(Colors.LightBlue);
LightCoral = new ImmutableSolidColorBrush(Colors.LightCoral);
LightCyan = new ImmutableSolidColorBrush(Colors.LightCyan);
LightGoldenrodYellow = new ImmutableSolidColorBrush(Colors.LightGoldenrodYellow);
LightGray = new ImmutableSolidColorBrush(Colors.LightGray);
LightGreen = new ImmutableSolidColorBrush(Colors.LightGreen);
LightPink = new ImmutableSolidColorBrush(Colors.LightPink);
LightSalmon = new ImmutableSolidColorBrush(Colors.LightSalmon);
LightSeaGreen = new ImmutableSolidColorBrush(Colors.LightSeaGreen);
LightSkyBlue = new ImmutableSolidColorBrush(Colors.LightSkyBlue);
LightSlateGray = new ImmutableSolidColorBrush(Colors.LightSlateGray);
LightSteelBlue = new ImmutableSolidColorBrush(Colors.LightSteelBlue);
LightYellow = new ImmutableSolidColorBrush(Colors.LightYellow);
Lime = new ImmutableSolidColorBrush(Colors.Lime);
LimeGreen = new ImmutableSolidColorBrush(Colors.LimeGreen);
Linen = new ImmutableSolidColorBrush(Colors.Linen);
Magenta = new ImmutableSolidColorBrush(Colors.Magenta);
Maroon = new ImmutableSolidColorBrush(Colors.Maroon);
MediumAquamarine = new ImmutableSolidColorBrush(Colors.MediumAquamarine);
MediumBlue = new ImmutableSolidColorBrush(Colors.MediumBlue);
MediumOrchid = new ImmutableSolidColorBrush(Colors.MediumOrchid);
MediumPurple = new ImmutableSolidColorBrush(Colors.MediumPurple);
MediumSeaGreen = new ImmutableSolidColorBrush(Colors.MediumSeaGreen);
MediumSlateBlue = new ImmutableSolidColorBrush(Colors.MediumSlateBlue);
MediumSpringGreen = new ImmutableSolidColorBrush(Colors.MediumSpringGreen);
MediumTurquoise = new ImmutableSolidColorBrush(Colors.MediumTurquoise);
MediumVioletRed = new ImmutableSolidColorBrush(Colors.MediumVioletRed);
MidnightBlue = new ImmutableSolidColorBrush(Colors.MidnightBlue);
MintCream = new ImmutableSolidColorBrush(Colors.MintCream);
MistyRose = new ImmutableSolidColorBrush(Colors.MistyRose);
Moccasin = new ImmutableSolidColorBrush(Colors.Moccasin);
NavajoWhite = new ImmutableSolidColorBrush(Colors.NavajoWhite);
Navy = new ImmutableSolidColorBrush(Colors.Navy);
OldLace = new ImmutableSolidColorBrush(Colors.OldLace);
Olive = new ImmutableSolidColorBrush(Colors.Olive);
OliveDrab = new ImmutableSolidColorBrush(Colors.OliveDrab);
Orange = new ImmutableSolidColorBrush(Colors.Orange);
OrangeRed = new ImmutableSolidColorBrush(Colors.OrangeRed);
Orchid = new ImmutableSolidColorBrush(Colors.Orchid);
PaleGoldenrod = new ImmutableSolidColorBrush(Colors.PaleGoldenrod);
PaleGreen = new ImmutableSolidColorBrush(Colors.PaleGreen);
PaleTurquoise = new ImmutableSolidColorBrush(Colors.PaleTurquoise);
PaleVioletRed = new ImmutableSolidColorBrush(Colors.PaleVioletRed);
PapayaWhip = new ImmutableSolidColorBrush(Colors.PapayaWhip);
PeachPuff = new ImmutableSolidColorBrush(Colors.PeachPuff);
Peru = new ImmutableSolidColorBrush(Colors.Peru);
Pink = new ImmutableSolidColorBrush(Colors.Pink);
Plum = new ImmutableSolidColorBrush(Colors.Plum);
PowderBlue = new ImmutableSolidColorBrush(Colors.PowderBlue);
Purple = new ImmutableSolidColorBrush(Colors.Purple);
Red = new ImmutableSolidColorBrush(Colors.Red);
RosyBrown = new ImmutableSolidColorBrush(Colors.RosyBrown);
RoyalBlue = new ImmutableSolidColorBrush(Colors.RoyalBlue);
SaddleBrown = new ImmutableSolidColorBrush(Colors.SaddleBrown);
Salmon = new ImmutableSolidColorBrush(Colors.Salmon);
SandyBrown = new ImmutableSolidColorBrush(Colors.SandyBrown);
SeaGreen = new ImmutableSolidColorBrush(Colors.SeaGreen);
SeaShell = new ImmutableSolidColorBrush(Colors.SeaShell);
Sienna = new ImmutableSolidColorBrush(Colors.Sienna);
Silver = new ImmutableSolidColorBrush(Colors.Silver);
SkyBlue = new ImmutableSolidColorBrush(Colors.SkyBlue);
SlateBlue = new ImmutableSolidColorBrush(Colors.SlateBlue);
SlateGray = new ImmutableSolidColorBrush(Colors.SlateGray);
Snow = new ImmutableSolidColorBrush(Colors.Snow);
SpringGreen = new ImmutableSolidColorBrush(Colors.SpringGreen);
SteelBlue = new ImmutableSolidColorBrush(Colors.SteelBlue);
Tan = new ImmutableSolidColorBrush(Colors.Tan);
Teal = new ImmutableSolidColorBrush(Colors.Teal);
Thistle = new ImmutableSolidColorBrush(Colors.Thistle);
Tomato = new ImmutableSolidColorBrush(Colors.Tomato);
Transparent = new ImmutableSolidColorBrush(Colors.Transparent);
Turquoise = new ImmutableSolidColorBrush(Colors.Turquoise);
Violet = new ImmutableSolidColorBrush(Colors.Violet);
Wheat = new ImmutableSolidColorBrush(Colors.Wheat);
White = new ImmutableSolidColorBrush(Colors.White);
WhiteSmoke = new ImmutableSolidColorBrush(Colors.WhiteSmoke);
Yellow = new ImmutableSolidColorBrush(Colors.Yellow);
YellowGreen = new ImmutableSolidColorBrush(Colors.YellowGreen);
}
/// <summary>
/// Gets an <see cref="Colors.AliceBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush AliceBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.AntiqueWhite"/> colored brush.
/// </summary>
public static ISolidColorBrush AntiqueWhite { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.AliceBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush Aqua { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Aquamarine"/> colored brush.
/// </summary>
public static ISolidColorBrush Aquamarine { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Azure"/> colored brush.
/// </summary>
public static ISolidColorBrush Azure { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Beige"/> colored brush.
/// </summary>
public static ISolidColorBrush Beige { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Bisque"/> colored brush.
/// </summary>
public static ISolidColorBrush Bisque { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Black"/> colored brush.
/// </summary>
public static ISolidColorBrush Black { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.BlanchedAlmond"/> colored brush.
/// </summary>
public static ISolidColorBrush BlanchedAlmond { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Blue"/> colored brush.
/// </summary>
public static ISolidColorBrush Blue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.BlueViolet"/> colored brush.
/// </summary>
public static ISolidColorBrush BlueViolet { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Brown"/> colored brush.
/// </summary>
public static ISolidColorBrush Brown { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.BurlyWood"/> colored brush.
/// </summary>
public static ISolidColorBrush BurlyWood { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.CadetBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush CadetBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Chartreuse"/> colored brush.
/// </summary>
public static ISolidColorBrush Chartreuse { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Chocolate"/> colored brush.
/// </summary>
public static ISolidColorBrush Chocolate { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Coral"/> colored brush.
/// </summary>
public static ISolidColorBrush Coral { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.CornflowerBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush CornflowerBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Cornsilk"/> colored brush.
/// </summary>
public static ISolidColorBrush Cornsilk { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Crimson"/> colored brush.
/// </summary>
public static ISolidColorBrush Crimson { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Cyan"/> colored brush.
/// </summary>
public static ISolidColorBrush Cyan { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkCyan"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkCyan { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkGoldenrod"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkGoldenrod { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkGray"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkGray { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkKhaki"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkKhaki { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkMagenta"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkMagenta { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkOliveGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkOliveGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkOrange"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkOrange { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkOrchid"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkOrchid { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkRed"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkRed { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkSalmon"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkSalmon { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkSeaGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkSeaGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkSlateBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkSlateBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkSlateGray"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkSlateGray { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkTurquoise"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkTurquoise { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DarkViolet"/> colored brush.
/// </summary>
public static ISolidColorBrush DarkViolet { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DeepPink"/> colored brush.
/// </summary>
public static ISolidColorBrush DeepPink { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DeepSkyBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush DeepSkyBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DimGray"/> colored brush.
/// </summary>
public static ISolidColorBrush DimGray { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.DodgerBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush DodgerBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Firebrick"/> colored brush.
/// </summary>
public static ISolidColorBrush Firebrick { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.FloralWhite"/> colored brush.
/// </summary>
public static ISolidColorBrush FloralWhite { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.ForestGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush ForestGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Fuchsia"/> colored brush.
/// </summary>
public static ISolidColorBrush Fuchsia { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Gainsboro"/> colored brush.
/// </summary>
public static ISolidColorBrush Gainsboro { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.GhostWhite"/> colored brush.
/// </summary>
public static ISolidColorBrush GhostWhite { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Gold"/> colored brush.
/// </summary>
public static ISolidColorBrush Gold { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Goldenrod"/> colored brush.
/// </summary>
public static ISolidColorBrush Goldenrod { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Gray"/> colored brush.
/// </summary>
public static ISolidColorBrush Gray { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Green"/> colored brush.
/// </summary>
public static ISolidColorBrush Green { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.GreenYellow"/> colored brush.
/// </summary>
public static ISolidColorBrush GreenYellow { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Honeydew"/> colored brush.
/// </summary>
public static ISolidColorBrush Honeydew { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.HotPink"/> colored brush.
/// </summary>
public static ISolidColorBrush HotPink { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.IndianRed"/> colored brush.
/// </summary>
public static ISolidColorBrush IndianRed { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Indigo"/> colored brush.
/// </summary>
public static ISolidColorBrush Indigo { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Ivory"/> colored brush.
/// </summary>
public static ISolidColorBrush Ivory { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Khaki"/> colored brush.
/// </summary>
public static ISolidColorBrush Khaki { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Lavender"/> colored brush.
/// </summary>
public static ISolidColorBrush Lavender { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LavenderBlush"/> colored brush.
/// </summary>
public static ISolidColorBrush LavenderBlush { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LawnGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush LawnGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LemonChiffon"/> colored brush.
/// </summary>
public static ISolidColorBrush LemonChiffon { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush LightBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightCoral"/> colored brush.
/// </summary>
public static ISolidColorBrush LightCoral { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightCyan"/> colored brush.
/// </summary>
public static ISolidColorBrush LightCyan { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightGoldenrodYellow"/> colored brush.
/// </summary>
public static ISolidColorBrush LightGoldenrodYellow { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightGray"/> colored brush.
/// </summary>
public static ISolidColorBrush LightGray { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush LightGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightPink"/> colored brush.
/// </summary>
public static ISolidColorBrush LightPink { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightSalmon"/> colored brush.
/// </summary>
public static ISolidColorBrush LightSalmon { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightSeaGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush LightSeaGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightSkyBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush LightSkyBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightSlateGray"/> colored brush.
/// </summary>
public static ISolidColorBrush LightSlateGray { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightSteelBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush LightSteelBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LightYellow"/> colored brush.
/// </summary>
public static ISolidColorBrush LightYellow { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Lime"/> colored brush.
/// </summary>
public static ISolidColorBrush Lime { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.LimeGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush LimeGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Linen"/> colored brush.
/// </summary>
public static ISolidColorBrush Linen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Magenta"/> colored brush.
/// </summary>
public static ISolidColorBrush Magenta { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Maroon"/> colored brush.
/// </summary>
public static ISolidColorBrush Maroon { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.MediumAquamarine"/> colored brush.
/// </summary>
public static ISolidColorBrush MediumAquamarine { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.MediumBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush MediumBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.MediumOrchid"/> colored brush.
/// </summary>
public static ISolidColorBrush MediumOrchid { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.MediumPurple"/> colored brush.
/// </summary>
public static ISolidColorBrush MediumPurple { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.MediumSeaGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush MediumSeaGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.MediumSlateBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush MediumSlateBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.MediumSpringGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush MediumSpringGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.MediumTurquoise"/> colored brush.
/// </summary>
public static ISolidColorBrush MediumTurquoise { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.MediumVioletRed"/> colored brush.
/// </summary>
public static ISolidColorBrush MediumVioletRed { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.MidnightBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush MidnightBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.MintCream"/> colored brush.
/// </summary>
public static ISolidColorBrush MintCream { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.MistyRose"/> colored brush.
/// </summary>
public static ISolidColorBrush MistyRose { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Moccasin"/> colored brush.
/// </summary>
public static ISolidColorBrush Moccasin { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.NavajoWhite"/> colored brush.
/// </summary>
public static ISolidColorBrush NavajoWhite { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Navy"/> colored brush.
/// </summary>
public static ISolidColorBrush Navy { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.OldLace"/> colored brush.
/// </summary>
public static ISolidColorBrush OldLace { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Olive"/> colored brush.
/// </summary>
public static ISolidColorBrush Olive { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.OliveDrab"/> colored brush.
/// </summary>
public static ISolidColorBrush OliveDrab { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Orange"/> colored brush.
/// </summary>
public static ISolidColorBrush Orange { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.OrangeRed"/> colored brush.
/// </summary>
public static ISolidColorBrush OrangeRed { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Orchid"/> colored brush.
/// </summary>
public static ISolidColorBrush Orchid { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.PaleGoldenrod"/> colored brush.
/// </summary>
public static ISolidColorBrush PaleGoldenrod { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.PaleGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush PaleGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.PaleTurquoise"/> colored brush.
/// </summary>
public static ISolidColorBrush PaleTurquoise { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.PaleVioletRed"/> colored brush.
/// </summary>
public static ISolidColorBrush PaleVioletRed { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.PapayaWhip"/> colored brush.
/// </summary>
public static ISolidColorBrush PapayaWhip { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.PeachPuff"/> colored brush.
/// </summary>
public static ISolidColorBrush PeachPuff { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Peru"/> colored brush.
/// </summary>
public static ISolidColorBrush Peru { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Pink"/> colored brush.
/// </summary>
public static ISolidColorBrush Pink { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Plum"/> colored brush.
/// </summary>
public static ISolidColorBrush Plum { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.PowderBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush PowderBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Purple"/> colored brush.
/// </summary>
public static ISolidColorBrush Purple { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Red"/> colored brush.
/// </summary>
public static ISolidColorBrush Red { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.RosyBrown"/> colored brush.
/// </summary>
public static ISolidColorBrush RosyBrown { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.RoyalBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush RoyalBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.SaddleBrown"/> colored brush.
/// </summary>
public static ISolidColorBrush SaddleBrown { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Salmon"/> colored brush.
/// </summary>
public static ISolidColorBrush Salmon { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.SandyBrown"/> colored brush.
/// </summary>
public static ISolidColorBrush SandyBrown { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.SeaGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush SeaGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.SeaShell"/> colored brush.
/// </summary>
public static ISolidColorBrush SeaShell { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Sienna"/> colored brush.
/// </summary>
public static ISolidColorBrush Sienna { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Silver"/> colored brush.
/// </summary>
public static ISolidColorBrush Silver { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.SkyBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush SkyBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.SlateBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush SlateBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.SlateGray"/> colored brush.
/// </summary>
public static ISolidColorBrush SlateGray { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Snow"/> colored brush.
/// </summary>
public static ISolidColorBrush Snow { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.SpringGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush SpringGreen { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.SteelBlue"/> colored brush.
/// </summary>
public static ISolidColorBrush SteelBlue { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Tan"/> colored brush.
/// </summary>
public static ISolidColorBrush Tan { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Teal"/> colored brush.
/// </summary>
public static ISolidColorBrush Teal { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Thistle"/> colored brush.
/// </summary>
public static ISolidColorBrush Thistle { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Tomato"/> colored brush.
/// </summary>
public static ISolidColorBrush Tomato { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Transparent"/> colored brush.
/// </summary>
public static ISolidColorBrush Transparent { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Turquoise"/> colored brush.
/// </summary>
public static ISolidColorBrush Turquoise { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Violet"/> colored brush.
/// </summary>
public static ISolidColorBrush Violet { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Wheat"/> colored brush.
/// </summary>
public static ISolidColorBrush Wheat { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.White"/> colored brush.
/// </summary>
public static ISolidColorBrush White { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.WhiteSmoke"/> colored brush.
/// </summary>
public static ISolidColorBrush WhiteSmoke { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.Yellow"/> colored brush.
/// </summary>
public static ISolidColorBrush Yellow { get; private set; }
/// <summary>
/// Gets an <see cref="Colors.YellowGreen"/> colored brush.
/// </summary>
public static ISolidColorBrush YellowGreen { get; private set; }
}
}
| |
using System;
using System.Reflection;
/*
* Regression tests for the mono JIT.
*
* Each test needs to be of the form:
*
* static int test_<result>_<name> ();
*
* where <result> is an integer (the value that needs to be returned by
* the method to make it pass.
* <name> is a user-displayed name used to identify the test.
*
* The tests can be driven in two ways:
* *) running the program directly: Main() uses reflection to find and invoke
* the test methods (this is useful mostly to check that the tests are correct)
* *) with the --regression switch of the jit (this is the preferred way since
* all the tests will be run with optimizations on and off)
*
* The reflection logic could be moved to a .dll since we need at least another
* regression test file written in IL code to have better control on how
* the IL code looks.
*/
#if MOBILE
class BasicTests
#else
class Tests
#endif
{
#if !MOBILE
public static int Main (string[] args) {
return TestDriver.RunTests (typeof (Tests), args);
}
#endif
public static int test_0_return () {
return 0;
}
public static int test_100000_return_large () {
return 100000;
}
public static int test_1_load_bool () {
bool a = true;
return a? 1: 0;
}
public static int test_0_load_bool_false () {
bool a = false;
return a? 1: 0;
}
public static int test_200_load_byte () {
byte a = 200;
return a;
}
public static int test_100_load_sbyte () {
sbyte a = 100;
return a;
}
public static int test_200_load_short () {
short a = 200;
return a;
}
public static int test_100_load_ushort () {
ushort a = 100;
return a;
}
public static int test_3_add_simple () {
int a = 1;
int b = 2;
return a + b;
}
public static int test_3_add_imm () {
int a = 1;
return a + 2;
}
public static int test_13407573_add_largeimm () {
int a = 1;
return a + 13407572;
}
public static int test_1_sub_simple () {
int a = 1;
int b = 2;
return b - a;
}
public static int test_1_sub_simple_un () {
uint a = 1;
uint b = 2;
return (int)(b - a);
}
public static int test_1_sub_imm () {
int b = 2;
return b - 1;
}
public static int test_2_sub_large_imm () {
int b = 0xff0f0f;
return b - 0xff0f0d;
}
public static int test_0_sub_inv_imm () {
int b = 2;
return 2 - b;
}
public static int test_2_and () {
int b = 2;
int a = 3;
return b & a;
}
public static int test_0_and_imm () {
int b = 2;
return b & 0x10;
}
public static int test_0_and_large_imm () {
int b = 2;
return b & 0x10000000;
}
public static int test_0_and_large_imm2 () {
int b = 2;
return b & 0x100000f0;
}
public static int test_2_div () {
int b = 6;
int a = 3;
return b / a;
}
public static int test_4_div_imm () {
int b = 12;
return b / 3;
}
public static int test_4_divun_imm () {
uint b = 12;
return (int)(b / 3);
}
public static int test_0_div_fold () {
int b = -1;
return b / 2;
}
public static int test_2_div_fold4 () {
int b = -8;
return -(b / 4);
}
public static int test_2_div_fold16 () {
int b = 32;
return b / 16;
}
public static int test_719177_div_destreg () {
int year = 1970;
return ((365* (year-1)) + ((year-1)/4));
}
public static int test_1_remun_imm () {
uint b = 13;
return (int)(b % 3);
}
public static int test_2_bigremun_imm () {
unchecked {
uint b = (uint)-2;
return (int)(b % 3);
}
}
public static int test_2_rem () {
int b = 5;
int a = 3;
return b % a;
}
public static int test_4_rem_imm () {
int b = 12;
return b % 8;
}
public static int test_0_rem_imm_0 () {
int b = 12;
return b % 1;
}
public static int test_0_rem_imm_0_neg () {
int b = -2;
return b % 1;
}
public static int test_4_rem_big_imm () {
int b = 10004;
return b % 10000;
}
public static int test_9_mul () {
int b = 3;
int a = 3;
return b * a;
}
public static int test_15_mul_imm () {
int b = 3;
return b * 5;
}
public static int test_24_mul () {
int a = 3;
int b = 8;
int res;
res = a * b;
return res;
}
public static int test_24_mul_ovf () {
int a = 3;
int b = 8;
int res;
checked {
res = a * b;
}
return res;
}
public static int test_24_mul_un () {
uint a = 3;
uint b = 8;
uint res;
res = a * b;
return (int)res;
}
public static int test_24_mul_ovf_un () {
uint a = 3;
uint b = 8;
uint res;
checked {
res = a * b;
}
return (int)res;
}
public static int test_0_add_ovf1 () {
int i, j, k;
checked {
i = System.Int32.MinValue;
j = 0;
k = i + j;
}
if (k != System.Int32.MinValue)
return 1;
return 0;
}
public static int test_0_add_ovf2 () {
int i, j, k;
checked {
i = System.Int32.MaxValue;
j = 0;
k = i + j;
}
if (k != System.Int32.MaxValue)
return 2;
return 0;
}
public static int test_0_add_ovf3 () {
int i, j, k;
checked {
i = System.Int32.MinValue;
j = System.Int32.MaxValue;
k = i + j;
}
if (k != -1)
return 3;
return 0;
}
public static int test_0_add_ovf4 () {
int i, j, k;
checked {
i = System.Int32.MaxValue;
j = System.Int32.MinValue;
k = i + j;
}
if (k != -1)
return 4;
return 0;
}
public static int test_0_add_ovf5 () {
int i, j, k;
checked {
i = System.Int32.MinValue + 1234;
j = -1234;
k = i + j;
}
if (k != System.Int32.MinValue)
return 5;
return 0;
}
public static int test_0_add_ovf6 () {
int i, j, k;
checked {
i = System.Int32.MaxValue - 1234;
j = 1234;
k = i + j;
}
if (k != System.Int32.MaxValue)
return 6;
return 0;
}
public static int test_0_add_un_ovf () {
uint n = (uint)134217728 * 16;
uint number = checked (n + (uint)0);
return number == n ? 0 : 1;
}
public static int test_0_sub_ovf1 () {
int i, j, k;
checked {
i = System.Int32.MinValue;
j = 0;
k = i - j;
}
if (k != System.Int32.MinValue)
return 1;
return 0;
}
public static int test_0_sub_ovf2 () {
int i, j, k;
checked {
i = System.Int32.MaxValue;
j = 0;
k = i - j;
}
if (k != System.Int32.MaxValue)
return 2;
return 0;
}
public static int test_0_sub_ovf3 () {
int i, j, k;
checked {
i = System.Int32.MinValue;
j = System.Int32.MinValue + 1234;
k = i - j;
}
if (k != -1234)
return 3;
return 0;
}
public static int test_0_sub_ovf4 () {
int i, j, k;
checked {
i = System.Int32.MaxValue;
j = 1234;
k = i - j;
}
if (k != System.Int32.MaxValue - 1234)
return 4;
return 0;
}
public static int test_0_sub_ovf5 () {
int i, j, k;
checked {
i = System.Int32.MaxValue - 1234;
j = -1234;
k = i - j;
}
if (k != System.Int32.MaxValue)
return 5;
return 0;
}
public static int test_0_sub_ovf6 () {
int i, j, k;
checked {
i = System.Int32.MinValue + 1234;
j = 1234;
k = i - j;
}
if (k != System.Int32.MinValue)
return 6;
return 0;
}
public static int test_0_sub_ovf_un () {
uint i, j, k;
checked {
i = System.UInt32.MaxValue;
j = 0;
k = i - j;
}
if (k != System.UInt32.MaxValue)
return 1;
checked {
i = System.UInt32.MaxValue;
j = System.UInt32.MaxValue;
k = i - j;
}
if (k != 0)
return 2;
return 0;
}
public static int test_3_or () {
int b = 2;
int a = 3;
return b | a;
}
public static int test_3_or_un () {
uint b = 2;
uint a = 3;
return (int)(b | a);
}
public static int test_3_or_short_un () {
ushort b = 2;
ushort a = 3;
return (int)(b | a);
}
public static int test_18_or_imm () {
int b = 2;
return b | 0x10;
}
public static int test_268435458_or_large_imm () {
int b = 2;
return b | 0x10000000;
}
public static int test_268435459_or_large_imm2 () {
int b = 2;
return b | 0x10000001;
}
public static int test_1_xor () {
int b = 2;
int a = 3;
return b ^ a;
}
public static int test_1_xor_imm () {
int b = 2;
return b ^ 3;
}
public static int test_983041_xor_imm_large () {
int b = 2;
return b ^ 0xf0003;
}
public static int test_1_neg () {
int b = -2;
b++;
return -b;
}
public static int test_2_not () {
int b = ~2;
b = ~b;
return b;
}
public static int test_16_shift () {
int b = 2;
int a = 3;
return b << a;
}
public static int test_16_shift_add () {
int b = 2;
int a = 3;
int c = 0;
return b << (a + c);
}
public static int test_16_shift_add2 () {
int b = 2;
int a = 3;
int c = 0;
return (b + c) << a;
}
public static int test_16_shift_imm () {
int b = 2;
return b << 3;
}
public static int test_524288_shift_imm_large () {
int b = 2;
return b << 18;
}
public static int test_12_shift_imm_inv () {
int b = 2;
return 3 << 2;
}
public static int test_12_shift_imm_inv_sbyte () {
sbyte b = 2;
return 3 << 2;
}
public static int test_1_rshift_imm () {
int b = 8;
return b >> 3;
}
public static int test_2_unrshift_imm () {
uint b = 16;
return (int)(b >> 3);
}
public static int test_0_bigunrshift_imm () {
unchecked {
uint b = (uint)-1;
b = b >> 1;
if (b != 0x7fffffff)
return 1;
return 0;
}
}
public static int test_0_bigrshift_imm () {
int b = -1;
b = b >> 1;
if (b != -1)
return 1;
return 0;
}
public static int test_1_rshift () {
int b = 8;
int a = 3;
return b >> a;
}
public static int test_2_unrshift () {
uint b = 16;
int a = 3;
return (int)(b >> a);
}
public static int test_0_bigunrshift () {
unchecked {
uint b = (uint)-1;
int a = 1;
b = b >> a;
if (b != 0x7fffffff)
return 1;
return 0;
}
}
public static int test_0_bigrshift () {
int b = -1;
int a = 1;
b = b >> a;
if (b != -1)
return 1;
return 0;
}
public static int test_2_cond () {
int b = 2, a = 3, c;
if (a == b)
return 0;
return 2;
}
public static int test_2_cond_short () {
short b = 2, a = 3, c;
if (a == b)
return 0;
return 2;
}
public static int test_2_cond_sbyte () {
sbyte b = 2, a = 3, c;
if (a == b)
return 0;
return 2;
}
public static int test_6_cascade_cond () {
int b = 2, a = 3, c;
if (a == b)
return 0;
else if (b > a)
return 1;
else if (b != b)
return 2;
else {
c = 1;
}
return a + b + c;
}
public static int test_6_cascade_short () {
short b = 2, a = 3, c;
if (a == b)
return 0;
else if (b > a)
return 1;
else if (b != b)
return 2;
else {
c = 1;
}
return a + b + c;
}
public static int test_0_short_sign_extend () {
int t1 = 0xffeedd;
short s1 = (short)t1;
int t2 = s1;
if ((uint)t2 != 0xffffeedd)
return 1;
else
return 0;
}
public static int test_127_iconv_to_i1 () {
int i = 0x100017f;
sbyte s = (sbyte)i;
return s;
}
public static int test_384_iconv_to_i2 () {
int i = 0x1000180;
short s = (short)i;
return s;
}
public static int test_15_for_loop () {
int i;
for (i = 0; i < 15; ++i) {
}
return i;
}
public static int test_11_nested_for_loop () {
int i, j = 0; /* mcs bug here if j not set */
for (i = 0; i < 15; ++i) {
for (j = 200; j >= 5; --j) ;
}
return i - j;
}
public static int test_11_several_nested_for_loops () {
int i, j = 0; /* mcs bug here if j not set */
for (i = 0; i < 15; ++i) {
for (j = 200; j >= 5; --j) ;
}
i = j = 0;
for (i = 0; i < 15; ++i) {
for (j = 200; j >= 5; --j) ;
}
return i - j;
}
public static int test_0_conv_ovf_i1 () {
int c;
//for (int j = 0; j < 10000000; j++)
checked {
c = 127;
sbyte b = (sbyte)c;
c = -128;
b = (sbyte)c;
}
return 0;
}
public static int test_0_conv_ovf_i1_un () {
uint c;
checked {
c = 127;
sbyte b = (sbyte)c;
}
return 0;
}
public static int test_0_conv_ovf_i2 () {
int c;
checked {
c = 32767;
Int16 b = (Int16)c;
c = -32768;
b = (Int16)c;
unchecked {
uint u = 0xfffffffd;
c = (int)u;
}
b = (Int16)c;
}
return 0;
}
public static int test_0_conv_ovf_i2_un () {
uint c;
checked {
c = 32767;
Int16 b = (Int16)c;
}
return 0;
}
public static int test_0_conv_ovf_u2 () {
int c;
checked {
c = 65535;
UInt16 b = (UInt16)c;
}
return 0;
}
public static int test_0_conv_ovf_u2_un () {
uint c;
checked {
c = 65535;
UInt16 b = (UInt16)c;
}
return 0;
}
public static int test_0_conv_ovf_u4 () {
int c;
checked {
c = 0x7fffffff;
uint b = (uint)c;
}
return 0;
}
public static int test_0_conv_ovf_i4_un () {
uint c;
checked {
c = 0x7fffffff;
int b = (int)c;
}
return 0;
}
public static int test_0_bool () {
bool val = true;
if (val)
return 0;
return 1;
}
public static int test_1_bool_inverted () {
bool val = true;
if (!val)
return 0;
return 1;
}
public static int test_1_bool_assign () {
bool val = true;
val = !val; // this should produce a ceq
if (val)
return 0;
return 1;
}
public static int test_1_bool_multi () {
bool val = true;
bool val2 = true;
val = !val;
if ((val && !val2) && (!val2 && val))
return 0;
return 1;
}
public static int test_16_spill () {
int a = 1;
int b = 2;
int c = 3;
int d = 4;
int e = 5;
return (1 + (a + (b + (c + (d + e)))));
}
public static int test_1_switch () {
int n = 0;
switch (n) {
case 0: return 1;
case 1: return 2;
case -1: return 3;
default:
return 4;
}
return 1;
}
public static int test_0_switch_constprop () {
int n = -1;
switch (n) {
case 0: return 2;
case 1: return 3;
case 2: return 3;
default:
return 0;
}
return 3;
}
public static int test_0_switch_constprop2 () {
int n = 3;
switch (n) {
case 0: return 2;
case 1: return 3;
case 2: return 3;
default:
return 0;
}
return 3;
}
public static int test_0_while_loop_1 () {
int value = 255;
do {
value = value >> 4;
} while (value != 0);
return 0;
}
public static int test_0_while_loop_2 () {
int value = 255;
int position = 5;
do {
value = value >> 4;
} while (value != 0 && position > 1);
return 0;
}
public static int test_0_char_conv () {
int i = 1;
char tc = (char) ('0' + i);
if (tc != '1')
return 1;
return 0;
}
public static int test_3_shift_regalloc () {
int shift = 8;
int orig = 1;
byte value = 0xfe;
orig &= ~(0xff << shift);
orig |= value << shift;
if (orig == 0xfe01)
return 3;
return 0;
}
enum E {A, B};
public static int test_2_optimize_branches () {
switch (E.A) {
case E.A:
if (E.A == E.B) {
}
break;
}
return 2;
}
public static int test_0_checked_byte_cast () {
int v = 250;
int b = checked ((byte) (v));
if (b != 250)
return 1;
return 0;
}
public static int test_0_checked_byte_cast_un () {
uint v = 250;
uint b = checked ((byte) (v));
if (b != 250)
return 1;
return 0;
}
public static int test_0_checked_short_cast () {
int v = 250;
int b = checked ((ushort) (v));
if (b != 250)
return 1;
return 0;
}
public static int test_0_checked_short_cast_un () {
uint v = 250;
uint b = checked ((ushort) (v));
if (b != 250)
return 1;
return 0;
}
public static int test_1_a_eq_b_plus_a () {
int a = 0, b = 1;
a = b + a;
return a;
}
public static int test_0_comp () {
int a = 0;
int b = -1;
int error = 1;
bool val;
val = a < b;
if (val)
return error;
error++;
val = a > b;
if (!val)
return error;
error ++;
val = a == b;
if (val)
return error;
error ++;
val = a == a;
if (!val)
return error;
error ++;
return 0;
}
public static int test_0_comp_unsigned () {
uint a = 1;
uint b = 0xffffffff;
int error = 1;
bool val;
val = a < b;
if (!val)
return error;
error++;
val = a <= b;
if (!val)
return error;
error++;
val = a == b;
if (val)
return error;
error++;
val = a >= b;
if (val)
return error;
error++;
val = a > b;
if (val)
return error;
error++;
val = b < a;
if (val)
return error;
error++;
val = b <= a;
if (val)
return error;
error++;
val = b == a;
if (val)
return error;
error++;
val = b > a;
if (!val)
return error;
error++;
val = b >= a;
if (!val)
return error;
error++;
return 0;
}
public static int test_16_cmov ()
{
int n = 0;
if (n == 0)
n = 16;
return n;
}
public static int test_0_and_cmp ()
{
/* test esi, imm */
int local = 0x01020304;
if ((local & 0x01020304) == 0)
return 7;
if ((local & 0x00000304) == 0)
return 8;
if ((local & 0x00000004) == 0)
return 9;
if ((local & 0x00000300) == 0)
return 10;
if ((local & 0x00020000) == 0)
return 11;
if ((local & 0x01000000) == 0)
return 12;
return 0;
}
public static int test_0_mul_imm_opt ()
{
int i;
i = 1;
if ((i * 2) != 2)
return 1;
i = -1;
if ((i * 2) != -2)
return 2;
i = 1;
if ((i * 3) != 3)
return 3;
i = -1;
if ((i * 3) != -3)
return 4;
i = 1;
if ((i * 5) != 5)
return 5;
i = -1;
if ((i * 5) != -5)
return 6;
i = 1;
if ((i * 6) != 6)
return 7;
i = -1;
if ((i * 6) != -6)
return 8;
i = 1;
if ((i * 9) != 9)
return 9;
i = -1;
if ((i * 9) != -9)
return 10;
i = 1;
if ((i * 10) != 10)
return 11;
i = -1;
if ((i * 10) != -10)
return 12;
i = 1;
if ((i * 12) != 12)
return 13;
i = -1;
if ((i * 12) != -12)
return 14;
i = 1;
if ((i * 25) != 25)
return 15;
i = -1;
if ((i * 25) != -25)
return 16;
i = 1;
if ((i * 100) != 100)
return 17;
i = -1;
if ((i * 100) != -100)
return 18;
return 0;
}
public static int test_0_cne ()
{
int x = 0;
int y = 1;
bool b = x != y;
bool bb = x != x;
if (!b)
return 1;
if (bb)
return 2;
return 0;
}
public static int test_0_cmp_regvar_zero ()
{
int n = 10;
if (!(n > 0 && n >= 0 && n != 0))
return 1;
if (n < 0 || n <= 0 || n == 0)
return 1;
return 0;
}
public static int test_5_div_un_cfold ()
{
uint i = 10;
uint j = 2;
return (int)(i / j);
}
public static int test_1_rem_un_cfold ()
{
uint i = 11;
uint j = 2;
return (int)(i % j);
}
public static int test_0_div_opt () {
int i;
// Avoid cfolding this
i = 0;
for (int j = 0; j < 567; ++j)
i ++;
i += 1234000;
if ((i / 2) != 617283)
return 1;
if ((i / 4) != 308641)
return 2;
if ((i / 8) != 154320)
return 3;
if ((i / 16) != 77160)
return 4;
// Avoid cfolding this
i = 0;
for (int j = 0; j < 567; ++j)
i --;
i -= 1234000;
if ((i / 2) != -617283)
return 5;
if ((i / 4) != -308641)
return 6;
if ((i / 8) != -154320)
return 7;
if ((i / 16) != -77160)
return 8;
return 0;
}
public static int test_0_rem_opt () {
int i;
// Avoid cfolding this
i = 0;
for (int j = 0; j < 29; ++j)
i ++;
if ((i % 2) != 1)
return 1;
if ((i % 4) != 1)
return 2;
if ((i % 8) != 5)
return 3;
if ((i % 16) != 13)
return 4;
// Avoid cfolding this
i = 0;
for (int j = 0; j < 29; ++j)
i --;
if ((i % 2) != -1)
return 5;
if ((i % 4) != -1)
return 6;
if ((i % 8) != -5)
return 7;
if ((i % 16) != -13)
return 8;
return 0;
}
public static int cmov (int i) {
int j = 0;
if (i > 0)
j = 1;
return j;
}
public static int cmov2 (int i) {
int j = 0;
if (i <= 0)
;
else
j = 1;
return j;
}
public static int test_0_branch_to_cmov_opt () {
if (cmov (0) != 0)
return 1;
if (cmov (1) != 1)
return 2;
if (cmov2 (0) != 0)
return 1;
if (cmov2 (1) != 1)
return 2;
return 0;
}
public static unsafe int test_0_ishr_sign_extend () {
// Check that ishr does sign extension from bit 31 on 64 bit platforms
uint val = 0xF0000000u;
uint *a = &val;
uint ui = (uint)((int)(*a) >> 2);
if (ui != 0xfc000000)
return 1;
// Same with non-immediates
int amount = 2;
ui = (uint)((int)(*a) >> amount);
if (ui != 0xfc000000)
return 2;
return 0;
}
public static unsafe int test_0_ishr_sign_extend_cfold () {
int i = 32768;
int j = i << 16;
int k = j >> 16;
return k == -32768 ? 0 : 1;
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using log4net;
using MindTouch.Dream;
using MindTouch.Tasking;
using MindTouch.Web;
using MindTouch.Xml;
namespace MindTouch.Deki.WikiManagement {
public abstract class InstanceManager {
// --- Constants ---
public const string DEFAULT_WIKI_ID = "default";
const int MIN_SECS_FROM_ACCESS_TO_SHUTDOWN = 60;
// --- Class fields ---
protected static readonly ILog _log = LogUtils.CreateLog();
// --- Class methods ---
public static InstanceManager New(DekiWikiService dekiService) {
InstanceManager mgr = null;
string srcString = dekiService.Config["wikis/@src"].AsText;
if(!string.IsNullOrEmpty(srcString)) {
XUri remoteDirUri = null;
if(!XUri.TryParse(srcString, out remoteDirUri)) {
//TODO: build a specialized exception out of this
throw new ApplicationException(string.Format("Configuration is not valid. wikis/@src ({0})is not a valid url!", srcString));
}
mgr = new RemoteInstanceManager(dekiService, remoteDirUri);
} else {
mgr = new LocalInstanceManager(dekiService);
}
mgr.maxInstances = dekiService.Config["wikis/@max"].AsUInt ?? 0;
uint timeoutSecs = dekiService.Config["wikis/@ttl"].AsUInt ?? uint.MaxValue;
if(timeoutSecs == 0 || timeoutSecs == uint.MaxValue) {
mgr._inactiveInstanceTimeOut = TimeSpan.MaxValue;
} else {
mgr._inactiveInstanceTimeOut = TimeSpan.FromSeconds(timeoutSecs);
}
return mgr;
}
// --- Fields ---
private Dictionary<string, DekiInstance> _instances = new Dictionary<string, DekiInstance>();
private readonly Dictionary<string, TaskTimer> _instanceExpireTimers = new Dictionary<string, TaskTimer>();
private uint maxInstances = uint.MaxValue;
private TimeSpan _inactiveInstanceTimeOut;
protected DekiWikiService _dekiService;
// --- Constructors ---
protected InstanceManager(DekiWikiService dekiService) {
_dekiService = dekiService;
}
// --- Abstract methods ---
public abstract XDoc GetGlobalConfig();
protected abstract XDoc GetConfigForWikiId(string wikiId);
protected abstract string GetWikiIdByHostname(string hostname);
//--- Properties ---
public TimeSpan InactiveInstanceTimeOut { get { return _inactiveInstanceTimeOut; } }
public uint InstancesRunning {
get {
lock(_instances) {
return (uint)_instances.Count;
}
}
}
// --- Methods ---
public IEnumerable<KeyValuePair<string, string>> GetGlobalServices() {
var config = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("services/mailer", _dekiService.Mailer.Uri.AsPublicUri().ToString()),
new KeyValuePair<string, string>("services/luceneindex", _dekiService.LuceneIndex.Uri.AsPublicUri().ToString()),
new KeyValuePair<string, string>("services/pagesubscription", _dekiService.PageSubscription.Uri.AsPublicUri().ToString()),
new KeyValuePair<string, string>("services/packageupdater", _dekiService.PackageUpdater.Uri.AsPublicUri().ToString())
};
return config;
}
public DekiInstance GetWikiInstance(DreamMessage request) {
if(request == null)
return null;
DekiInstance dekiInstance = null;
string hostname = string.Empty;
bool wikiIdFromHeader = true;
string wikiId = null;
string publicUriFromHeader = null;
var wikiIdentityHeader = HttpUtil.ParseNameValuePairs(request.Headers[DekiWikiService.WIKI_IDENTITY_HEADERNAME] ?? "");
wikiIdentityHeader.TryGetValue("id", out wikiId);
wikiIdentityHeader.TryGetValue("uri", out publicUriFromHeader);
if(string.IsNullOrEmpty(wikiId)) {
// get requested hostname and normalize
wikiIdFromHeader = false;
hostname = request.Headers.Host;
if(!string.IsNullOrEmpty(hostname)) {
if(hostname.EndsWith(":80")) {
hostname = hostname.Substring(0, hostname.Length - 3);
}
hostname = hostname.Trim().ToLowerInvariant();
}
wikiId = GetWikiIdByHostname(hostname);
if(string.IsNullOrEmpty(wikiId))
wikiId = DEFAULT_WIKI_ID;
}
dekiInstance = GetWikiInstance(wikiId);
//If an instance doesn't exist or if it was last updated over x minutes ago, refetch the instance config to check for status changes
if(dekiInstance == null || (InactiveInstanceTimeOut != TimeSpan.MaxValue && dekiInstance.InstanceLastUpdateTime.Add(InactiveInstanceTimeOut) < DateTime.UtcNow)) {
XDoc instanceConfig = XDoc.Empty;
try {
instanceConfig = GetConfigForWikiId(wikiId);
if(instanceConfig.IsEmpty && dekiInstance == null) {
if(wikiIdFromHeader) {
throw new DreamAbortException(new DreamMessage(DreamStatus.Gone, null, MimeType.TEXT, string.Format("No wiki exists for provided wikiId '{0}'", wikiId)));
} else {
throw new DreamAbortException(new DreamMessage(DreamStatus.Gone, null, MimeType.TEXT, string.Format("No wiki exists at host '{0}'", hostname)));
}
}
} catch(DreamAbortException e) {
if(e.Response.Status == DreamStatus.Gone) {
ShutdownInstance(wikiId);
throw;
}
if(dekiInstance == null) {
throw;
}
} catch {
if(dekiInstance == null) {
throw;
}
} finally {
if(dekiInstance != null)
dekiInstance.InstanceLastUpdateTime = DateTime.UtcNow;
}
//If a wiki already exists, shut it down if it was updated since it was last created
if(dekiInstance != null && dekiInstance.InstanceCreationTime < (instanceConfig["@updated"].AsDate ?? DateTime.MinValue)) {
ShutdownInstance(wikiId);
dekiInstance = null;
}
// create instance if none exists
if(dekiInstance == null) {
dekiInstance = CreateWikiInstance(wikiId, instanceConfig);
}
}
if(InactiveInstanceTimeOut != TimeSpan.MaxValue) {
lock(_instances) {
TaskTimer timer;
if(_instanceExpireTimers.TryGetValue(wikiId, out timer)) {
timer.Change(InactiveInstanceTimeOut, TaskEnv.Clone());
}
}
}
if(wikiIdFromHeader) {
// the request host does not represent a valid host for public uri generation, so we need to alter the context
XUri publicUriOverride;
if(string.IsNullOrEmpty(publicUriFromHeader) || !XUri.TryParse(publicUriFromHeader, out publicUriOverride)) {
_log.DebugFormat("no public uri provided in wiki header, using canonical uri");
publicUriOverride = dekiInstance.CanonicalUri;
}
// Note (arnec): Propagating a much hard-coded assumption, i.e. that the Api for any Deki instance can be accessed
// at the instances' canonical uri plus @api
publicUriOverride = publicUriOverride.At("@api");
_log.DebugFormat("switching public uri from {0} to {1} for request", DreamContext.Current.PublicUri, publicUriOverride);
DreamContext.Current.SetPublicUriOverride(publicUriOverride);
}
dekiInstance.InstanceLastAccessedTime = DateTime.UtcNow;
return dekiInstance;
}
protected DekiInstance GetWikiInstance(string wikiId) {
DekiInstance di = null;
lock(_instances) {
_log.DebugFormat("retrieving instance for wiki id '{0}'", wikiId);
_instances.TryGetValue(wikiId, out di);
}
return di;
}
protected DekiInstance CreateWikiInstance(string wikiId, XDoc instanceConfig) {
List<KeyValuePair<string, DekiInstance>> instanceList = null;
DekiInstance instance = null;
int instanceCount = 0;
//throw exception if licensing does not allow startup of another wiki instance
MindTouch.Deki.Logic.LicenseBL.IsDekiInstanceStartupAllowed(true);
lock(_instances) {
instance = GetWikiInstance(wikiId);
if(instance == null) {
_instances[wikiId] = instance = new DekiInstance(_dekiService, wikiId, instanceConfig);
instance.InstanceCreationTime = DateTime.UtcNow;
}
//Schedule new instance for shutdown if inactive-instance-timeout enabled.
if(InactiveInstanceTimeOut != TimeSpan.MaxValue) {
TaskTimer timer = new TaskTimer(OnInstanceExpireTimer, wikiId);
_instanceExpireTimers[wikiId] = timer;
}
instanceCount = _instances.Count;
if(maxInstances != 0 && instanceCount > maxInstances) {
instanceList = new List<KeyValuePair<string, DekiInstance>>(_instances);
}
}
//Hit the instance number limit? Look for least recently accessed wiki and shut it down.
if(instanceList != null) {
instanceList.Sort(delegate(KeyValuePair<string, DekiInstance> left, KeyValuePair<string, DekiInstance> right) {
return DateTime.Compare(left.Value.InstanceLastAccessedTime, right.Value.InstanceLastAccessedTime);
});
List<KeyValuePair<string, DekiInstance>> instancesToExamine =
instanceList.GetRange(0, instanceList.Count - (int)maxInstances);
if(instancesToExamine.Count > 0) {
Async.Fork(delegate() {
foreach(KeyValuePair<string, DekiInstance> instancePair in instancesToExamine) {
if((DateTime.UtcNow - instancePair.Value.InstanceLastAccessedTime).TotalSeconds >= MIN_SECS_FROM_ACCESS_TO_SHUTDOWN) {
ShutdownInstance(instancePair.Key);
}
}
}, null);
}
}
return instance;
}
private void ShutdownInstance(string wikiId) {
DekiInstance instance = null;
TaskTimer timer = null;
lock(_instances) {
if(_instances.TryGetValue(wikiId, out instance)) {
_instances.Remove(wikiId);
}
if(_instanceExpireTimers.TryGetValue(wikiId, out timer)) {
_instanceExpireTimers.Remove(wikiId);
}
}
if(instance != null) {
lock(instance) {
if(timer != null)
timer.Cancel();
ShutdownInstance(wikiId, instance);
}
}
}
protected virtual void ShutdownInstance(string wikiid, DekiInstance instance) {
if(instance.Status == DekiInstanceStatus.RUNNING) {
DekiContext dekiContext = new DekiContext(_dekiService, instance, DreamContext.Current.Request);
DreamContext.Current.SetState<DekiContext>(dekiContext);
lock(instance) {
instance.Shutdown();
}
}
}
protected void OnInstanceExpireTimer(TaskTimer timer) {
_log.InfoMethodCall("instance expired", timer.State);
ShutdownInstance((string)timer.State);
}
// --- Virtual methods ---
public virtual void Shutdown() {
lock(_instances) {
foreach(string wikiId in new List<string>(_instances.Keys)) {
ShutdownInstance(wikiId);
}
}
DreamContext.Current.SetState<DekiContext>(null);
_instances = null;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.TypeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType
{
public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseExplicitTypeDiagnosticAnalyzer(), new UseExplicitTypeCodeFixProvider());
private readonly CodeStyleOption<bool> onWithNone = new CodeStyleOption<bool>(true, NotificationOption.None);
private readonly CodeStyleOption<bool> offWithNone = new CodeStyleOption<bool>(false, NotificationOption.None);
private readonly CodeStyleOption<bool> onWithInfo = new CodeStyleOption<bool>(true, NotificationOption.Suggestion);
private readonly CodeStyleOption<bool> offWithInfo = new CodeStyleOption<bool>(false, NotificationOption.Suggestion);
private readonly CodeStyleOption<bool> onWithWarning = new CodeStyleOption<bool>(true, NotificationOption.Warning);
private readonly CodeStyleOption<bool> offWithWarning = new CodeStyleOption<bool>(false, NotificationOption.Warning);
private readonly CodeStyleOption<bool> onWithError = new CodeStyleOption<bool>(true, NotificationOption.Error);
private readonly CodeStyleOption<bool> offWithError = new CodeStyleOption<bool>(false, NotificationOption.Error);
// specify all options explicitly to override defaults.
private IDictionary<OptionKey, object> ExplicitTypeEverywhere() => OptionsSet(
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, offWithInfo),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, offWithInfo),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithInfo));
private IDictionary<OptionKey, object> ExplicitTypeExceptWhereApparent() => OptionsSet(
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, offWithInfo),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, onWithInfo),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithInfo));
private IDictionary<OptionKey, object> ExplicitTypeForBuiltInTypesOnly() => OptionsSet(
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, onWithInfo),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, onWithInfo),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithInfo));
private IDictionary<OptionKey, object> ExplicitTypeEnforcements() => OptionsSet(
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, offWithWarning),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, offWithError),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithInfo));
private IDictionary<OptionKey, object> ExplicitTypeNoneEnforcement() => OptionsSet(
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, offWithNone),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, offWithNone),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithNone));
private IDictionary<OptionKey, object> Options(OptionKey option, object value)
{
var options = new Dictionary<OptionKey, object>();
options.Add(option, value);
return options;
}
#region Error Cases
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldDeclaration()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
[|var|] _myfield = 5;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldLikeEvents()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
public event [|var|] _myevent;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnAnonymousMethodExpression()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] comparer = delegate (string value) {
return value != ""0"";
};
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnLambdaExpression()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = y => y * y;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithMultipleDeclarators()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = 5, y = x;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithoutInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotDuringConflicts()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] p = new var();
}
class var
{
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotIfAlreadyExplicitlyTyped()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|Program|] p = new Program();
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnRHS()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
var c = new [|var|]();
}
}
class var
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorSymbol()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new Foo();
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
#endregion
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDynamic()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|dynamic|] x = 1;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnForEachVarWithAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5).Select(i => new { Value = i });
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnForEachVarWithExplicitType()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}",
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach (int value in values)
{
Console.WriteLine(value.Value);
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new { Amount = 108, Message = ""Hello"" };
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnArrayOfAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new[] { new { name = ""apple"", diam = 4 }, new { name = ""grape"", diam = 1 } };
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
void Method()
{
var products = new List<Product>();
[|var|] productQuery = from prod in products
select new { prod.Color, prod.Price };
}
}
class Product
{
public ConsoleColor Color { get; set; }
public int Price { get; set; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = ""hello"";
}
}",
@"using System;
class C
{
static void M()
{
string s = ""hello"";
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnIntrinsicType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}",
@"using System;
class C
{
static void M()
{
int s = 5;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnFrameworkType()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
static void M()
{
[|var|] c = new List<int>();
}
}",
@"using System.Collections.Generic;
class C
{
static void M()
{
List<int> c = new List<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnUserDefinedType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
[|var|] c = new C();
}
}",
@"using System;
class C
{
void M()
{
C c = new C();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnGenericType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C<T>
{
static void M()
{
[|var|] c = new C<int>();
}
}",
@"using System;
class C<T>
{
static void M()
{
C<int> c = new C<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new int[4] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new int[4] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new[] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}",
@"using System;
class C
{
static void M()
{
int[][] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithObjectInitializer()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] cc = new Customer { City = ""Madras"" };
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
class C
{
static void M()
{
Customer cc = new Customer { City = ""Madras"" };
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] digits = new List<int> { 1, 2, 3 };
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<int> digits = new List<int> { 1, 2, 3 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] cs = new List<Customer>
{
new Customer { City = ""Madras"" }
};
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<Customer> cs = new List<Customer>
{
new Customer { City = ""Madras"" }
};
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
for ([|var|] i = 0; i < 5; i++)
{
}
}
}",
@"using System;
class C
{
static void M()
{
for (int i = 0; i < 5; i++)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForeachStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach ([|var|] item in l)
{
}
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach (int item in l)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnQueryExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
[|var|] expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
IEnumerable<Customer> expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInUsingStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
using ([|var|] r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}",
@"using System;
class C
{
static void M()
{
using (Res r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnInterpolatedString()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] s = $""Hello, {name}""
}
}",
@"using System;
class Program
{
void Method()
{
string s = $""Hello, {name}""
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnExplicitConversion()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
double x = 1234.7;
[|var|] a = (int)x;
}
}",
@"using System;
class C
{
static void M()
{
double x = 1234.7;
int a = (int)x;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnConditionalAccessExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
C obj = new C();
[|var|] anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}",
@"using System;
class C
{
static void M()
{
C obj = new C();
C anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInCheckedExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
[|var|] intNumber = checked((int)number1);
}
}",
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
int intNumber = checked((int)number1);
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInAwaitExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
[|var|] text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
string text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInBuiltInNumericType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = 1;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
int text = 1;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInBuiltInCharType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = GetChar();
}
public char GetChar() => 'c';
}",
@"using System;
class C
{
public void ProcessRead()
{
char text = GetChar();
}
public char GetChar() => 'c';
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_string()
{
// though string isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = string.Empty;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
string text = string.Empty;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_object()
{
// object isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
[|var|] text = j;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
object text = j;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeNotificationLevelNone()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestMissingInRegularAndScriptAsync(source,
new TestParameters(options: ExplicitTypeNoneEnforcement()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeNotificationLevelInfo()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}";
await TestDiagnosticSeverityAndCountAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticCount: 1,
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Info);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeNotificationLevelWarning()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] {2, 4, 6, 8};
}
}";
await TestDiagnosticSeverityAndCountAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticCount: 1,
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Warning);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeNotificationLevelError()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestDiagnosticSeverityAndCountAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticCount: 1,
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Error);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int, string) s = (1, ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, b: ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string b) s = (a: 1, b: ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string) s = (a: 1, ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace GitVersion.Helpers
{
public static class ProcessHelper
{
private static readonly object LockObject = new object();
// http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/f6069441-4ab1-4299-ad6a-b8bb9ed36be3
private static Process Start(ProcessStartInfo startInfo)
{
Process process;
lock (LockObject)
{
using (new ChangeErrorMode(ErrorModes.FailCriticalErrors | ErrorModes.NoGpFaultErrorBox))
{
try
{
process = Process.Start(startInfo);
}
catch (Win32Exception exception)
{
switch ((NativeErrorCode)exception.NativeErrorCode)
{
case NativeErrorCode.Success:
// Success is not a failure.
break;
case NativeErrorCode.FileNotFound:
throw new FileNotFoundException($"The executable file '{startInfo.FileName}' could not be found.",
startInfo.FileName,
exception);
case NativeErrorCode.PathNotFound:
throw new DirectoryNotFoundException($"The path to the executable file '{startInfo.FileName}' could not be found.",
exception);
}
throw;
}
try
{
if (process != null)
{
process.PriorityClass = ProcessPriorityClass.Idle;
}
}
catch
{
// NOTE: It seems like in some situations, setting the priority class will throw a Win32Exception
// with the error code set to "Success", which I think we can safely interpret as a success and
// not an exception.
//
// See: https://travis-ci.org/GitTools/GitVersion/jobs/171288284#L2026
// And: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx
//
// There's also the case where the process might be killed before we try to adjust its priority
// class, in which case it will throw an InvalidOperationException. What we ideally should do
// is start the process in a "suspended" state, adjust the priority class, then resume it, but
// that's not possible in pure .NET.
//
// See: https://travis-ci.org/GitTools/GitVersion/jobs/166709203#L2278
// And: http://www.codeproject.com/Articles/230005/Launch-a-process-suspended
//
// -- @asbjornu
}
}
}
return process;
}
// http://csharptest.net/532/using-processstart-to-capture-console-output/
public static int Run(Action<string> output, Action<string> errorOutput, TextReader input, string exe, string args, string workingDirectory, params KeyValuePair<string, string>[] environmentalVariables)
{
if (string.IsNullOrEmpty(exe))
throw new ArgumentNullException(nameof(exe));
if (output == null)
throw new ArgumentNullException(nameof(output));
workingDirectory ??= System.Environment.CurrentDirectory;
var psi = new ProcessStartInfo
{
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
ErrorDialog = false,
WorkingDirectory = workingDirectory,
FileName = exe,
Arguments = args
};
foreach (var environmentalVariable in environmentalVariables)
{
if (psi.EnvironmentVariables.ContainsKey(environmentalVariable.Key))
{
psi.EnvironmentVariables[environmentalVariable.Key] = environmentalVariable.Value;
}
else
{
psi.EnvironmentVariables.Add(environmentalVariable.Key, environmentalVariable.Value);
}
if (psi.EnvironmentVariables.ContainsKey(environmentalVariable.Key) && environmentalVariable.Value == null)
{
psi.EnvironmentVariables.Remove(environmentalVariable.Key);
}
}
using var process = Start(psi);
using var mreOut = new ManualResetEvent(false);
using var mreErr = new ManualResetEvent(false);
process.EnableRaisingEvents = true;
process.OutputDataReceived += (o, e) =>
{
// ReSharper disable once AccessToDisposedClosure
if (e.Data == null)
mreOut.Set();
else
output(e.Data);
};
process.BeginOutputReadLine();
process.ErrorDataReceived += (o, e) =>
{
// ReSharper disable once AccessToDisposedClosure
if (e.Data == null)
mreErr.Set();
else
errorOutput(e.Data);
};
process.BeginErrorReadLine();
string line;
while (input != null && null != (line = input.ReadLine()))
process.StandardInput.WriteLine(line);
process.StandardInput.Close();
process.WaitForExit();
mreOut.WaitOne();
mreErr.WaitOne();
return process.ExitCode;
}
/// <summary>
/// System error codes.
/// See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx
/// </summary>
private enum NativeErrorCode
{
Success = 0x0,
FileNotFound = 0x2,
PathNotFound = 0x3
}
[Flags]
public enum ErrorModes
{
Default = 0x0,
FailCriticalErrors = 0x1,
NoGpFaultErrorBox = 0x2,
NoAlignmentFaultExcept = 0x4,
NoOpenFileErrorBox = 0x8000
}
private struct ChangeErrorMode : IDisposable
{
private readonly int oldMode;
public ChangeErrorMode(ErrorModes mode)
{
try
{
oldMode = SetErrorMode((int)mode);
}
catch (Exception ex) when (ex is EntryPointNotFoundException || ex is DllNotFoundException)
{
oldMode = (int)mode;
}
}
void IDisposable.Dispose()
{
try
{
SetErrorMode(oldMode);
}
catch (Exception ex) when (ex is EntryPointNotFoundException || ex is DllNotFoundException)
{
// NOTE: Mono doesn't support DllImport("kernel32.dll") and its SetErrorMode method, obviously. @asbjornu
}
}
[DllImport("kernel32.dll")]
private static extern int SetErrorMode(int newMode);
}
}
}
| |
using System;
using FluentAssertions;
using FluentAssertions.Execution;
using ivrToolkit.Core.Enums;
using ivrToolkit.Core.Exceptions;
using ivrToolkit.Core.Interfaces;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
namespace ivrToolkit.Core.Tests
{
public class LineWrapperTests
{
private Mock<IIvrBaseLine> GetMockedLineBase()
{
var line = new Mock<IIvrBaseLine>();
line.Setup(x => x.Management.TriggerDispose());
return line;
}
#region Dial
[Fact]
public void LineWrapper_Dial_throws_DisposingException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.Dial("1", 1000);
act.Should().Throw<DisposingException>();
}
[Fact]
public void LineWrapper_Dial_throws_DisposedException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Dispose();
Action act = () => test.Dial("1", 1000);
act.Should().Throw<DisposedException>();
}
[Fact]
public void LineWrapper_Dial_anseringMachineLengthInMs_999_throws_ArgumentOutOfRangeException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.Dial("1", 999);
act.Should().Throw<ArgumentOutOfRangeException>();
}
[Fact]
public void LineWrapper_Dial_numberIsNull_throws_ArgumentNullException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.Dial(null, 1000);
act.Should().Throw<ArgumentNullException>();
}
[Fact]
public void LineWrapper_Dial_numberIsEmpty_throws_ArgumentException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.Dial("", 1000);
act.Should().Throw<ArgumentException>();
}
[Fact]
public void LineWrapper_Dial_GetAnsweringMachine_lineStatus_connected()
{
var mock = GetMockedLineBase();
mock.Setup(x => x.Dial(It.IsAny<string>(), It.IsAny<int>())).Returns(CallAnalysis.AnsweringMachine);
var test = new LineWrapper(new NullLoggerFactory(), 1, mock.Object);
test.Dial("12223334444", 1000);
test.Status.Should().Be(LineStatusTypes.Connected);
}
[Fact]
public void LineWrapper_Dial_GetConnected_lineStatus_connected()
{
var mock = GetMockedLineBase();
mock.Setup(x => x.Dial(It.IsAny<string>(), It.IsAny<int>())).Returns(CallAnalysis.Connected);
var test = new LineWrapper(new NullLoggerFactory(), 1, mock.Object);
test.Dial("12223334444", 1000);
test.Status.Should().Be(LineStatusTypes.Connected);
}
[Fact]
public void LineWrapper_Dial_GetBusy_lineStatus_onHook()
{
var mock = GetMockedLineBase();
mock.Setup(x => x.Dial(It.IsAny<string>(), It.IsAny<int>())).Returns(CallAnalysis.Busy);
var test = new LineWrapper(new NullLoggerFactory(), 1, mock.Object);
test.Dial("12223334444", 1000);
test.Status.Should().Be(LineStatusTypes.OnHook);
}
[Fact]
public void LineWrapper_Dial_GetStopped_throws_DisposingException()
{
var mock = GetMockedLineBase();
mock.Setup(x => x.Dial(It.IsAny<string>(), It.IsAny<int>())).Returns(CallAnalysis.Stopped);
var test = new LineWrapper(new NullLoggerFactory(), 1, mock.Object);
using (new AssertionScope())
{
Action act = () => test.Dial("12223334444", 1000);
act.Should().Throw<DisposingException>();
test.Status.Should().Be(LineStatusTypes.OffHook);
}
}
#endregion
#region CheckDispose
[Fact]
public void LineWrapper_CheckDispose_throws_DisposingException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.CheckDispose();
act.Should().Throw<DisposingException>();
}
[Fact]
public void LineWrapper_CheckDispose_throws_DisposedException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Dispose();
Action act = () => test.CheckDispose();
act.Should().Throw<DisposedException>();
}
#endregion
#region WaitRings
[Fact]
public void LineWrapper_WaitRings_throws_DisposingException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.WaitRings(1);
act.Should().Throw<DisposingException>();
}
[Fact]
public void LineWrapper_WaitRings_throws_DisposedException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Dispose();
Action act = () => test.WaitRings(1);
act.Should().Throw<DisposedException>();
}
#endregion
#region Hangup
[Fact]
public void LineWrapper_Hangup_throws_DisposingException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.Hangup();
act.Should().Throw<DisposingException>();
}
[Fact]
public void LineWrapper_Hangup_throws_DisposedException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Dispose();
Action act = () => test.Hangup();
act.Should().Throw<DisposedException>();
}
#endregion
#region TakeOffHook
[Fact]
public void LineWrapper_TakeOffHook_throws_DisposingException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.TakeOffHook();
act.Should().Throw<DisposingException>();
}
[Fact]
public void LineWrapper_TakeOffHook_throws_DisposedException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Dispose();
Action act = () => test.TakeOffHook();
act.Should().Throw<DisposedException>();
}
#endregion
#region PlayFile
[Fact]
public void LineWrapper_PlayFile_throws_DisposingException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.PlayFile("");
act.Should().Throw<DisposingException>();
}
[Fact]
public void LineWrapper_PlayFile_throws_DisposedException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Dispose();
Action act = () => test.PlayFile("");
act.Should().Throw<DisposedException>();
}
#endregion
#region RecordToFile
[Fact]
public void LineWrapper_RecordToFile_throws_DisposingException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.RecordToFile("");
act.Should().Throw<DisposingException>();
}
[Fact]
public void LineWrapper_RecordToFile_throws_DisposedException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Dispose();
Action act = () => test.RecordToFile("");
act.Should().Throw<DisposedException>();
}
#endregion
#region GetDigits
[Fact]
public void LineWrapper_GetDigits_throws_DisposingException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.GetDigits(1, "");
act.Should().Throw<DisposingException>();
}
[Fact]
public void LineWrapper_GetDigits_throws_DisposedException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Dispose();
Action act = () => test.GetDigits(1, "");
act.Should().Throw<DisposedException>();
}
#endregion
#region FlushDigitBuffer
[Fact]
public void LineWrapper_FlushDigitBuffer_throws_DisposingException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.FlushDigitBuffer();
act.Should().Throw<DisposingException>();
}
[Fact]
public void LineWrapper_FlushDigitBuffer_throws_DisposedException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Dispose();
Action act = () => test.FlushDigitBuffer();
act.Should().Throw<DisposedException>();
}
#endregion
#region Volume
[Fact]
public void LineWrapper_Volume_throws_DisposingException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Management.TriggerDispose();
Action act = () => test.Volume = 1;
act.Should().Throw<DisposingException>();
}
[Fact]
public void LineWrapper_Volume_throws_DisposedException()
{
var test = new LineWrapper(new NullLoggerFactory(), 1, GetMockedLineBase().Object);
test.Dispose();
Action act = () => test.Volume = 1;
act.Should().Throw<DisposedException>();
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ActorRefSourceSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using Akka.Actor;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using Akka.Util.Internal;
using FluentAssertions;
using Xunit;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class ActorRefSourceSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public ActorRefSourceSpec()
{
var settings = ActorMaterializerSettings.Create(Sys);
Materializer = ActorMaterializer.Create(Sys, settings);
}
[Fact]
public void A_ActorRefSource_must_emit_received_messages_to_the_stream()
{
var s = this.CreateManualSubscriberProbe<int>();
var actorRef = Source.ActorRef<int>(10, OverflowStrategy.Fail)
.To(Sink.FromSubscriber(s))
.Run(Materializer);
var sub = s.ExpectSubscription();
sub.Request(2);
actorRef.Tell(1);
s.ExpectNext(1);
actorRef.Tell(2);
s.ExpectNext(2);
actorRef.Tell(3);
s.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
}
[Fact]
public void A_ActorRefSource_must_buffer_when_needed()
{
var s = this.CreateManualSubscriberProbe<int>();
var actorRef = Source.ActorRef<int>(100, OverflowStrategy.DropHead)
.To(Sink.FromSubscriber(s))
.Run(Materializer);
var sub = s.ExpectSubscription();
Enumerable.Range(1, 20).ForEach(x => actorRef.Tell(x));
sub.Request(10);
Enumerable.Range(1, 10).ForEach(x => s.ExpectNext(x));
sub.Request(10);
Enumerable.Range(11, 10).ForEach(x => s.ExpectNext(x));
Enumerable.Range(200, 200).ForEach(x => actorRef.Tell(x));
sub.Request(100);
Enumerable.Range(300, 100).ForEach(x => s.ExpectNext(x));
}
[Fact]
public void A_ActorRefSource_must_drop_new_when_full_and_with_DropNew_strategy()
{
var t = Source.ActorRef<int>(100, OverflowStrategy.DropNew)
.ToMaterialized(this.SinkProbe<int>(), Keep.Both)
.Run(Materializer);
var actorRef = t.Item1;
var sub = t.Item2;
Enumerable.Range(1, 20).ForEach(x => actorRef.Tell(x));
sub.Request(10);
Enumerable.Range(1, 10).ForEach(x => sub.ExpectNext(x));
sub.Request(10);
Enumerable.Range(11, 10).ForEach(x => sub.ExpectNext(x));
Enumerable.Range(200, 200).ForEach(x => actorRef.Tell(x));
sub.Request(100);
Enumerable.Range(200, 100).ForEach(x => sub.ExpectNext(x));
}
[Fact]
public void A_ActorRefSource_must_terminate_when_the_stream_is_cancelled()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var actorRef = Source.ActorRef<int>(0, OverflowStrategy.Fail)
.To(Sink.FromSubscriber(s))
.Run(Materializer);
Watch(actorRef);
var sub = s.ExpectSubscription();
sub.Cancel();
ExpectTerminated(actorRef);
}, Materializer);
}
[Fact]
public void A_ActorRefSource_must_not_fail_when_0_buffer_space_and_demand_is_signalled()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var actorRef = Source.ActorRef<int>(0, OverflowStrategy.DropHead)
.To(Sink.FromSubscriber(s))
.Run(Materializer);
Watch(actorRef);
var sub = s.ExpectSubscription();
sub.Request(100);
sub.Cancel();
ExpectTerminated(actorRef);
}, Materializer);
}
[Fact]
public void A_ActorRefSource_must_completes_the_stream_immediatly_when_receiving_PoisonPill()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var actorRef = Source.ActorRef<int>(10, OverflowStrategy.Fail)
.To(Sink.FromSubscriber(s))
.Run(Materializer);
s.ExpectSubscription();
actorRef.Tell(PoisonPill.Instance);
s.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_ActorRefSource_must_signal_buffered_elements_and_complete_the_stream_after_receiving_Status_Success()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var actorRef = Source.ActorRef<int>(10, OverflowStrategy.Fail)
.To(Sink.FromSubscriber(s))
.Run(Materializer);
var sub = s.ExpectSubscription();
actorRef.Tell(1);
actorRef.Tell(2);
actorRef.Tell(3);
actorRef.Tell(new Status.Success("ok"));
sub.Request(10);
s.ExpectNext(1, 2, 3);
s.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_ActorRefSource_must_not_buffer_elements_after_receiving_Status_Success()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var actorRef = Source.ActorRef<int>(3, OverflowStrategy.DropBuffer)
.To(Sink.FromSubscriber(s))
.Run(Materializer);
var sub = s.ExpectSubscription();
actorRef.Tell(1);
actorRef.Tell(2);
actorRef.Tell(3);
actorRef.Tell(new Status.Success("ok"));
actorRef.Tell(100);
actorRef.Tell(100);
actorRef.Tell(100);
sub.Request(10);
s.ExpectNext(1, 2, 3);
s.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_ActorRefSource_must_after_receiving_Status_Success_allow_for_earliner_completion_with_PoisonPill()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var actorRef = Source.ActorRef<int>(3, OverflowStrategy.DropBuffer)
.To(Sink.FromSubscriber(s))
.Run(Materializer);
var sub = s.ExpectSubscription();
actorRef.Tell(1);
actorRef.Tell(2);
actorRef.Tell(3);
actorRef.Tell(new Status.Success("ok"));
sub.Request(2); // not all elements drained yet
s.ExpectNext(1, 2);
actorRef.Tell(PoisonPill.Instance);
s.ExpectComplete(); // element `3` not signaled
}, Materializer);
}
[Fact]
public void A_ActorRefSource_must_fail_the_stream_when_receiving_Status_Failure()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
var actorRef = Source.ActorRef<int>(10, OverflowStrategy.Fail)
.To(Sink.FromSubscriber(s))
.Run(Materializer);
s.ExpectSubscription();
var ex = new TestException("testfailure");
actorRef.Tell(new Status.Failure(ex));
s.ExpectError().Should().Be(ex);
}, Materializer);
}
[Fact]
public void A_ActorRefSource_must_set_actor_name_equal_to_stage_name()
{
this.AssertAllStagesStopped(() =>
{
var s = this.CreateManualSubscriberProbe<int>();
const string name = "SomeCustomName";
var actorRef = Source.ActorRef<int>(10, OverflowStrategy.Fail)
.WithAttributes(Attributes.CreateName(name))
.To(Sink.FromSubscriber(s))
.Run(Materializer);
actorRef.Path.ToString().Should().Contain(name);
actorRef.Tell(PoisonPill.Instance);
}, Materializer);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.IO;
namespace Epi.Windows.Dialogs
{
/// <summary>
/// Dialog for selecting views
/// </summary>
public partial class ViewSelectionDialog : DialogBase
{
#region Private Class Members
private int viewId;
private Project currentProject = null;
private bool includeRelatedViews;
// private IProjectManager projectManager = null;
#endregion
#region Constructors
/// <summary>
///
/// </summary>
[Obsolete("Use of default constructor not allowed", true)]
public ViewSelectionDialog()
{
InitializeComponent();
}
/// <summary>
/// Constructor for the class
/// </summary>
/// <param name="frm">The main form</param>
/// <param name="project">Project with views to be loaded</param>
public ViewSelectionDialog(MainForm frm, Project project) : base(frm)
{
InitializeComponent();
currentProject = project;
LoadProject();
if ((String.IsNullOrEmpty(txtCurrentProj.Text.Trim())))
{
btnOK.Enabled = false;
}
btnFindProject.Focus();
}
#endregion Constructors
#region Private Methods
/// <summary>
/// Loads the views on the screen
/// </summary>
private void LoadViews()
{
// DataTable views = currentProject.GetViewsAsDataTable(); dcs0 7/7/2008
//lbxViews.DataSource = currentProject.GetViewNames();
try
{
if (currentProject.GetParentViewNames().Count == 0)
{
//Setting project to new if no rows returned from the SQL Select
//to reset the dialog to its original state -- den4 11/23/2010
currentProject = new Project();
return;
}
lbxViews.DataSource = currentProject.GetParentViewNames();
}
catch (ApplicationException)
{
MsgBox.ShowError("There was a problem loading the project \"" + currentProject.Name + "\". Please make sure the database for this project exists.");
}
//lbxViews.DisplayMember = ColumnNames.NAME;
//lbxViews.ValueMember = ColumnNames.VIEW_ID;
}
/// <summary>
/// Opens a dialog for project selection
/// </summary>
//private void SelectProject()
private bool SetCurrentProject()
{
try
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = SharedStrings.SELECT_PROJECT;
openFileDialog.Filter = "Project Files ( *" + Epi.FileExtensions.EPI_PROJ + ")|*" + Epi.FileExtensions.EPI_PROJ;
openFileDialog.FilterIndex = 1;
openFileDialog.Multiselect = false;
openFileDialog.InitialDirectory = Configuration.GetNewInstance().Directories.Project;
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
if (openFileDialog.FileName.ToLowerInvariant().Trim().EndsWith(Epi.FileExtensions.EPI_PROJ))
{
if (System.IO.File.Exists(openFileDialog.FileName))
{
/*
IProjectManager manager = MainForm.Module.GetService(typeof(IProjectManager)) as IProjectManager;
if (manager == null)
{
throw new GeneralException("Project manager is not registered.");
}*/
currentProject = new Project(openFileDialog.FileName);
if (currentProject.CollectedData.FullName.Contains("MS Access"))
{
string databaseFileName = currentProject.CollectedData.DataSource.Replace("Data Source=".ToLowerInvariant(), string.Empty);
if (System.IO.File.Exists(databaseFileName) == false)
{
MsgBox.ShowError(string.Format(SharedStrings.DATASOURCE_NOT_FOUND, databaseFileName));
return false;
}
}
/*
IProjectHost host = Module.GetService(typeof(IProjectHost)) as IProjectHost;
if (host == null)
{
throw new GeneralException("Project host is not registered.");
}
else
{
host.CurrentProject = currentProject;
}*/
}
else
{
throw new System.IO.FileNotFoundException(string.Empty, openFileDialog.FileName);
}
}
}
else if (result == DialogResult.Cancel)
{
currentProject = null;
}
}
catch (FileNotFoundException ex)
{
MsgBox.ShowException(ex);
return false;
//throw;
}
catch (System.Security.Cryptography.CryptographicException ex)
{
MsgBox.ShowError(string.Format(SharedStrings.ERROR_CRYPTO_KEYS, ex.Message));
return false;
}
finally
{
}
return true;
}
/// <summary>
/// Loads a project
/// </summary>
private void LoadProject()
{
if (currentProject != null)
{
LoadViews();
txtCurrentProj.Text = currentProject.FilePath;
}
}
/// <summary>
/// Saves the user's selection
/// </summary>
private void SaveSettings()
{
string viewName = lbxViews.SelectedValue.ToString();
View view = CurrentProject.Metadata.GetViewByFullName(":" + viewName);
ViewId = view.Id;
}
#endregion
#region Event Handlers
/// <summary>
/// Handles click event of OK button.
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void btnOK_Click(object sender, System.EventArgs e)
{
//ViewId = int.Parse(lbxViews.SelectedValue.ToString());
SaveSettings();
}
/// <summary>
/// Handles click event of Find Project button.
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void btnFindProject_Click(object sender, System.EventArgs e)
{
if (SetCurrentProject() == false)
{
return;
}
LoadProject();
if (!(String.IsNullOrEmpty(txtCurrentProj.Text.Trim())))
{
btnOK.Enabled = true;
btnOK.Focus();
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets a value indicating whether to get related views
/// </summary>
public bool IncludeRelatedViews
{
get
{
return (includeRelatedViews);
}
set
{
includeRelatedViews = value;
}
}
/// <summary>
/// Gets or sets the View Id
/// </summary>
public int ViewId
{
get
{
return (viewId);
}
set
{
viewId = value;
}
}
/// <summary>
/// Get the current project
/// </summary>
public Project CurrentProject
{
get
{
return (currentProject);
}
}
#endregion
private void lbxViews_SelectedIndexChanged(object sender, EventArgs e)
{
if (!(String.IsNullOrEmpty(txtCurrentProj.Text.Trim())))
{
btnOK.Enabled = true;
btnOK.Focus();
}
}
private void lbxViews_DoubleClick(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtCurrentProj.Text) && lbxViews.SelectedItems.Count > 0)
{
SaveSettings();
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
}
}
}
| |
using Moq;
using NodaTime;
using NUnit.Framework;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Net;
using TempoDB.Exceptions;
namespace TempoDB.Tests
{
[TestFixture]
class ReadSingleValueByFilterTest
{
private static DateTimeZone zone = DateTimeZone.Utc;
private static string json = "[{" +
"\"series\":{" +
"\"id\":\"id1\"," +
"\"key\":\"key1\"," +
"\"name\":\"\"," +
"\"tags\":[]," +
"\"attributes\":{}" +
"}," +
"\"data\":{" +
"\"t\":\"2012-01-01T00:00:01.000Z\"," +
"\"v\":12.34" +
"}," +
"\"tz\":\"UTC\"" +
"}]";
private static string json1 = "[" +
"{" +
"\"series\":{" +
"\"id\":\"id1\"," +
"\"key\":\"key1\"," +
"\"name\":\"\"," +
"\"tags\":[]," +
"\"attributes\":{}" +
"}," +
"\"data\":{" +
"\"t\":\"2012-01-01T00:00:01.000Z\"," +
"\"v\":12.34" +
"}," +
"\"tz\":\"UTC\"" +
"}," +
"{" +
"\"series\":{" +
"\"id\":\"id2\"," +
"\"key\":\"key2\"," +
"\"name\":\"\"," +
"\"tags\":[]," +
"\"attributes\":{}" +
"}," +
"\"data\":{" +
"\"t\":\"2012-01-01T00:00:01.000Z\"," +
"\"v\":23.45" +
"}," +
"\"tz\":\"UTC\"" +
"}" +
"]";
private static string json2 = "[" +
"{" +
"\"series\":{" +
"\"id\":\"id3\"," +
"\"key\":\"key3\"," +
"\"name\":\"\"," +
"\"tags\":[]," +
"\"attributes\":{}" +
"}," +
"\"data\":{" +
"\"t\":\"2012-01-01T00:00:01.000Z\"," +
"\"v\":34.56" +
"}," +
"\"tz\":\"UTC\"" +
"}" +
"]";
private static string jsonTz = "[{" +
"\"series\":{" +
"\"id\":\"id1\"," +
"\"key\":\"key1\"," +
"\"name\":\"\"," +
"\"tags\":[]," +
"\"attributes\":{}" +
"}," +
"\"data\":{" +
"\"t\":\"2012-01-01T00:00:01.000-06:00\"," +
"\"v\":12.34" +
"}," +
"\"tz\":\"America/Chicago\"" +
"}]";
private static Series series1 = new Series("key1");
private static Series series2 = new Series("key2");
private static Series series3 = new Series("key3");
private static ZonedDateTime timestamp = zone.AtStrictly(new LocalDateTime(2012, 1, 1, 0, 0, 1));
private static Filter filter = new Filter();
[Test]
public void SmokeTest()
{
var response = TestCommon.GetResponse(200, json);
var client = TestCommon.GetClient(response);
var cursor = client.ReadSingleValue(filter, timestamp, zone, Direction.Exact);
var expected = new List<SingleValue> {
new SingleValue(series1, new DataPoint(timestamp, 12.34))
};
var output = new List<SingleValue>();
foreach(SingleValue value in cursor)
{
output.Add(value);
}
Assert.AreEqual(expected, output);
}
[Test]
public void SmokeTestTz()
{
var zone = DateTimeZoneProviders.Tzdb["America/Chicago"];
var response = TestCommon.GetResponse(200, jsonTz);
var client = TestCommon.GetClient(response);
var cursor = client.ReadSingleValue(filter, timestamp, zone, Direction.Exact);
var expected = new List<SingleValue> {
new SingleValue(series1, new DataPoint(zone.AtStrictly(new LocalDateTime(2012, 1, 1, 0, 0, 1)), 12.34))
};
var output = new List<SingleValue>();
foreach(SingleValue value in cursor)
{
output.Add(value);
}
Assert.AreEqual(expected, output);
}
[Test]
public void MultipleSegmentSmokeTest()
{
var response1 = TestCommon.GetResponse(200, json1);
response1.Headers.Add(new Parameter {
Name = "Link",
Value = "</v1/single/?key=key1&key=2&key=3&ts=2012-01-01T00:00:01+00:00&direction=exact&tz=UTC>; rel=\"next\""
});
var response2 = TestCommon.GetResponse(200, json2);
var calls = 0;
RestResponse[] responses = { response1, response2 };
var mockclient = new Mock<RestClient>();
mockclient.Setup(cl => cl.Execute(It.IsAny<RestRequest>())).Returns(() => responses[calls]).Callback(() => calls++);
var client = TestCommon.GetClient(mockclient.Object);
var cursor = client.ReadSingleValue(filter, timestamp, zone, Direction.Exact);
var expected = new List<SingleValue> {
new SingleValue(series1, new DataPoint(timestamp, 12.34)),
new SingleValue(series2, new DataPoint(timestamp, 23.45)),
new SingleValue(series3, new DataPoint(timestamp, 34.56))
};
var output = new List<SingleValue>();
foreach(SingleValue value in cursor)
{
output.Add(value);
}
Assert.AreEqual(expected, output);
}
[Test]
public void RequestMethod()
{
var response = TestCommon.GetResponse(200, json);
var mockclient = TestCommon.GetMockRestClient(response);
var client = TestCommon.GetClient(mockclient.Object);
client.ReadSingleValue(filter, timestamp, zone, Direction.Exact);
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => req.Method == Method.GET)));
}
[Test]
public void RequestUrl()
{
var response = TestCommon.GetResponse(200, json);
var mockclient = TestCommon.GetMockRestClient(response);
var client = TestCommon.GetClient(mockclient.Object);
client.ReadSingleValue(filter, timestamp, zone, Direction.Exact);
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => req.Resource == "/{version}/single/")));
}
[Test]
public void RequestParameters()
{
var response = TestCommon.GetResponse(200, json);
var mockclient = TestCommon.GetMockRestClient(response);
var client = TestCommon.GetClient(mockclient.Object);
var filter = new Filter()
.AddKeys("key1")
.AddTags("tag1")
.AddAttributes("key1", "value1");
client.ReadSingleValue(filter, timestamp, zone, Direction.Exact);
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "key", "key1"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "tag", "tag1"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "attr[key1]", "value1"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "ts", "2012-01-01T00:00:01+00:00"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "direction", "exact"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "tz", "UTC"))));
}
[Test]
[ExpectedException(typeof(TempoDBException))]
public void Error()
{
var response = TestCommon.GetResponse(403, "You are forbidden");
var client = TestCommon.GetClient(response);
var cursor = client.ReadSingleValue(filter, timestamp, zone, Direction.Exact);
var output = new List<SingleValue>();
foreach(SingleValue value in cursor)
{
output.Add(value);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Runtime.CompilerServices.Tests
{
public static partial class RuntimeHelpersTests
{
[Fact]
public static void GetHashCodeTest()
{
// Int32 RuntimeHelpers.GetHashCode(Object)
object obj1 = new object();
int h1 = RuntimeHelpers.GetHashCode(obj1);
int h2 = RuntimeHelpers.GetHashCode(obj1);
Assert.Equal(h1, h2);
object obj2 = new object();
int h3 = RuntimeHelpers.GetHashCode(obj2);
Assert.NotEqual(h1, h3); // Could potentially clash but very unlikely
int i123 = 123;
int h4 = RuntimeHelpers.GetHashCode(i123);
Assert.NotEqual(i123.GetHashCode(), h4);
int h5 = RuntimeHelpers.GetHashCode(null);
Assert.Equal(h5, 0);
}
public struct TestStruct
{
public int i1;
public int i2;
public override bool Equals(object obj)
{
if (!(obj is TestStruct))
return false;
TestStruct that = (TestStruct)obj;
return i1 == that.i1 && i2 == that.i2;
}
public override int GetHashCode() => i1 ^ i2;
}
[Fact]
public static unsafe void GetObjectValue()
{
// Object RuntimeHelpers.GetObjectValue(Object)
TestStruct t = new TestStruct() { i1 = 2, i2 = 4 };
object tOV = RuntimeHelpers.GetObjectValue(t);
Assert.Equal(t, (TestStruct)tOV);
object o = new object();
object oOV = RuntimeHelpers.GetObjectValue(o);
Assert.Equal(o, oOV);
int i = 3;
object iOV = RuntimeHelpers.GetObjectValue(i);
Assert.Equal(i, (int)iOV);
}
[Fact]
public static unsafe void OffsetToStringData()
{
// RuntimeHelpers.OffsetToStringData
char[] expectedValues = new char[] { 'a', 'b', 'c', 'd', 'e', 'f' };
string s = "abcdef";
fixed (char* values = s) // Compiler will use OffsetToStringData with fixed statements
{
for (int i = 0; i < expectedValues.Length; i++)
{
Assert.Equal(expectedValues[i], values[i]);
}
}
}
[Fact]
public static void InitializeArray()
{
// Void RuntimeHelpers.InitializeArray(Array, RuntimeFieldHandle)
char[] expected = new char[] { 'a', 'b', 'c' }; // Compiler will use RuntimeHelpers.InitializeArrary these
}
[Fact]
public static void RunClassConstructor()
{
RuntimeTypeHandle t = typeof(HasCctor).TypeHandle;
RuntimeHelpers.RunClassConstructor(t);
Assert.Equal(HasCctorReceiver.S, "Hello");
return;
}
internal class HasCctor
{
static HasCctor()
{
HasCctorReceiver.S = "Hello" + (Guid.NewGuid().ToString().Substring(string.Empty.Length, 0)); // Make sure the preinitialization optimization doesn't eat this.
}
}
internal class HasCctorReceiver
{
public static string S;
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void PrepareMethod()
{
foreach (MethodInfo m in typeof(RuntimeHelpersTests).GetMethods())
RuntimeHelpers.PrepareMethod(m.MethodHandle);
Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(default(RuntimeMethodHandle)));
Assert.ThrowsAny<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(IList).GetMethod("Add").MethodHandle));
}
[Fact]
public static void PrepareGenericMethod()
{
Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(default(RuntimeMethodHandle), null));
//
// Type instantiations
//
// Generic definition with instantiation is valid
RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle,
new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle });
// Instantiated method without instantiation is valid
RuntimeHelpers.PrepareMethod(typeof(List<int>).GetMethod("Add").MethodHandle,
null);
// Generic definition without instantiation is invalid
Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle,
null));
// Wrong instantiation
Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle,
new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle, typeof(TestStruct).TypeHandle }));
//
// Method instantiations
//
// Generic definition with instantiation is valid
RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle,
new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle });
// Instantiated method without instantiation is valid
RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize")
.MakeGenericMethod(new Type[] { typeof(TestStruct) }).MethodHandle,
null);
// Generic definition without instantiation is invalid
Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle,
null));
// Wrong instantiation
Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle,
new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle, typeof(TestStruct).TypeHandle }));
}
[Fact]
public static void PrepareDelegate()
{
RuntimeHelpers.PrepareDelegate((Action)(() => { }));
RuntimeHelpers.PrepareDelegate((Func<int>)(() => 1) + (Func<int>)(() => 2));
RuntimeHelpers.PrepareDelegate(null);
}
}
public struct Age
{
public int years;
public int months;
}
public class FixedClass
{
[FixedAddressValueType]
public static Age FixedAge;
public static unsafe IntPtr AddressOfFixedAge()
{
fixed (Age* pointer = &FixedAge)
{
return (IntPtr)pointer;
}
}
}
public static partial class RuntimeHelpersTests
{
[Fact]
public static void FixedAddressValueTypeTest()
{
// Get addresses of static Age fields.
IntPtr fixedPtr1 = FixedClass.AddressOfFixedAge();
// Garbage collection.
GC.Collect(3, GCCollectionMode.Forced, true, true);
GC.WaitForPendingFinalizers();
// Get addresses of static Age fields after garbage collection.
IntPtr fixedPtr2 = FixedClass.AddressOfFixedAge();
Assert.Equal(fixedPtr1, fixedPtr2);
}
}
}
| |
// 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 ExtendToVector256UInt32()
{
var test = new GenericUnaryOpTest__ExtendToVector256UInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class GenericUnaryOpTest__ExtendToVector256UInt32
{
private struct TestStruct
{
public Vector128<UInt32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(GenericUnaryOpTest__ExtendToVector256UInt32 testClass)
{
var result = Avx.ExtendToVector256<UInt32>(_fld);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector128<UInt32> _clsVar;
private Vector128<UInt32> _fld;
private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable;
static GenericUnaryOpTest__ExtendToVector256UInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public GenericUnaryOpTest__ExtendToVector256UInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.ExtendToVector256<UInt32>(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.ExtendToVector256<UInt32>(
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.ExtendToVector256<UInt32>(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256))
.MakeGenericMethod( new Type[] { typeof(UInt32) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256))
.MakeGenericMethod( new Type[] { typeof(UInt32) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256))
.MakeGenericMethod( new Type[] { typeof(UInt32) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.ExtendToVector256<UInt32>(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr);
var result = Avx.ExtendToVector256<UInt32>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Avx.ExtendToVector256<UInt32>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Avx.ExtendToVector256<UInt32>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new GenericUnaryOpTest__ExtendToVector256UInt32();
var result = Avx.ExtendToVector256<UInt32>(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.ExtendToVector256<UInt32>(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.ExtendToVector256(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _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));
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
if (firstOp[0] != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((i < (RetElementCount / 2)) ? firstOp[i] : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.ExtendToVector256)}<UInt32>(Vector128<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
}
}
| |
/**************************************
* FILE: DependenciesConfigXmlTest.cs
* DATE: 05.01.2010 10:22:38
* AUTHOR: Raphael B. Estrada
* AUTHOR URL: http://www.galaktor.net
* AUTHOR E-MAIL: [email protected]
*
* The MIT License
*
* Copyright (c) 2010 Raphael B. Estrada
* Author URL: http://www.galaktor.net
* Author E-Mail: [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* ***********************************/
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using NGin.Core.Configuration.Serialization;
namespace NGin.Core.Test.Unit
{
[TestFixture]
public class DependenciesConfigXmlTest
{
[Test]
public void DependenciesConfigXml_CreateInstance_Success()
{
// arrange
DependenciesConfigXml config;
// act
config = new DependenciesConfigXml();
// assert
Assert.IsNotNull( config );
Assert.IsInstanceOf<DependenciesConfigXml>( config );
}
[Test]
public void Equals_EqualObject_AreEqual()
{
// arrange
DependenciesConfigXml configOne = new DependenciesConfigXml();
DependenciesConfigXml configTwo = new DependenciesConfigXml();
DirectoryXml dir = new DirectoryXml();
dir.Location = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location );
configOne.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
configOne.Dependencies.Add( dir );
configTwo.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
configTwo.Dependencies.Add( dir );
bool areEqual;
// act
areEqual = configOne.Equals( configTwo );
// assert
Assert.IsTrue( areEqual );
}
[Test]
public void Equals_DifferentDependenciesLength_AreNotEqual()
{
// arrange
DependenciesConfigXml configOne = new DependenciesConfigXml();
DependenciesConfigXml configTwo = new DependenciesConfigXml();
DirectoryXml dir = new DirectoryXml();
dir.Location = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location );
configOne.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
configOne.Dependencies.Add( dir );
configTwo.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
configTwo.Dependencies.Add( dir );
configTwo.Dependencies.Add( dir );
bool areEqual;
// act
areEqual = configOne.Equals( configTwo );
// assert
Assert.IsFalse( areEqual );
}
[Test]
public void Equals_DifferentDependencies_AreNotEqual()
{
// arrange
DependenciesConfigXml configOne = new DependenciesConfigXml();
DependenciesConfigXml configTwo = new DependenciesConfigXml();
DirectoryXml dir = new DirectoryXml();
DirectoryXml dirOther = new DirectoryXml();
dir.Location = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location );
dirOther.Location = System.IO.Path.GetPathRoot( dir.Location );
configOne.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
configOne.Dependencies.Add( dir );
configTwo.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
configTwo.Dependencies.Add( dirOther );
bool areEqual;
// act
areEqual = configOne.Equals( configTwo );
// assert
Assert.IsFalse( areEqual );
}
[Test]
public void GetHashCode_EqualObjects_SameHashCodes()
{
// arrange
DependenciesConfigXml configOne = new DependenciesConfigXml();
DependenciesConfigXml configTwo = new DependenciesConfigXml();
DirectoryXml dir = new DirectoryXml();
dir.Location = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location );
configOne.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
configOne.Dependencies.Add( dir );
configTwo.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
configTwo.Dependencies.Add( dir );
int hashCodeOne, hashCodeTwo;
// act
hashCodeOne = configOne.GetHashCode();
hashCodeTwo = configTwo.GetHashCode();
// assert
Assert.AreEqual( hashCodeOne, hashCodeTwo );
}
[Test]
public void GetHashCode_DifferentDependenciesCount_DifferentHashCodes()
{
// arrange
DependenciesConfigXml configOne = new DependenciesConfigXml();
DependenciesConfigXml configTwo = new DependenciesConfigXml();
DirectoryXml dir = new DirectoryXml();
dir.Location = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location );
configOne.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
configOne.Dependencies.Add( dir );
configTwo.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
configTwo.Dependencies.Add( dir );
configTwo.Dependencies.Add( dir );
int hashCodeOne, hashCodeTwo;
// act
hashCodeOne = configOne.GetHashCode();
hashCodeTwo = configTwo.GetHashCode();
// assert
Assert.AreNotEqual( hashCodeOne, hashCodeTwo );
}
[Test]
public void GetHashCode_DifferentDependencies_DifferentHashCodes()
{
// arrange
DependenciesConfigXml configOne = new DependenciesConfigXml();
DependenciesConfigXml configTwo = new DependenciesConfigXml();
DirectoryXml dir = new DirectoryXml();
DirectoryXml dirOther = new DirectoryXml();
dir.Location = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location );
dirOther.Location = System.IO.Path.GetPathRoot( dir.Location );
configOne.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
configOne.Dependencies.Add( dir );
configTwo.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
configTwo.Dependencies.Add( dir );
configTwo.Dependencies.Add( dirOther );
int hashCodeOne, hashCodeTwo;
// act
hashCodeOne = configOne.GetHashCode();
hashCodeTwo = configTwo.GetHashCode();
// assert
Assert.AreNotEqual( hashCodeOne, hashCodeTwo );
}
[Test]
public void Equals_OtherType_AreNotEqual()
{
// arrange
DependenciesConfigXml config = new DependenciesConfigXml();
string other = "notaconfig";
bool areEqual;
// act
areEqual = config.Equals( other );
// assert
Assert.IsFalse( areEqual );
}
[Test]
public void IsInitialized_DependenciesInitialized_ReturnTrue()
{
// arrange
DependenciesConfigXml config = new DependenciesConfigXml();
config.Dependencies = new System.Collections.ObjectModel.Collection<DirectoryXml>();
// act
// assert
Assert.IsTrue( config.IsInitialized );
}
[Test]
public void IsInitialized_DependenciesNull_ReturnFalse()
{
// arrange
DependenciesConfigXml config = new DependenciesConfigXml();
config.Dependencies = null;
// act
// assert
Assert.IsFalse( config.IsInitialized );
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="ThicknessAnimation.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Utility;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using MS.Internal.PresentationFramework;
namespace System.Windows.Media.Animation
{
/// <summary>
/// Animates the value of a Thickness property using linear interpolation
/// between two values. The values are determined by the combination of
/// From, To, or By values that are set on the animation.
/// </summary>
public partial class ThicknessAnimation :
ThicknessAnimationBase
{
#region Data
/// <summary>
/// This is used if the user has specified From, To, and/or By values.
/// </summary>
private Thickness[] _keyValues;
private AnimationType _animationType;
private bool _isAnimationFunctionValid;
#endregion
#region Constructors
/// <summary>
/// Static ctor for ThicknessAnimation establishes
/// dependency properties, using as much shared data as possible.
/// </summary>
static ThicknessAnimation()
{
Type typeofProp = typeof(Thickness?);
Type typeofThis = typeof(ThicknessAnimation);
PropertyChangedCallback propCallback = new PropertyChangedCallback(AnimationFunction_Changed);
ValidateValueCallback validateCallback = new ValidateValueCallback(ValidateFromToOrByValue);
FromProperty = DependencyProperty.Register(
"From",
typeofProp,
typeofThis,
new PropertyMetadata((Thickness?)null, propCallback),
validateCallback);
ToProperty = DependencyProperty.Register(
"To",
typeofProp,
typeofThis,
new PropertyMetadata((Thickness?)null, propCallback),
validateCallback);
ByProperty = DependencyProperty.Register(
"By",
typeofProp,
typeofThis,
new PropertyMetadata((Thickness?)null, propCallback),
validateCallback);
EasingFunctionProperty = DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeofThis);
}
/// <summary>
/// Creates a new ThicknessAnimation with all properties set to
/// their default values.
/// </summary>
public ThicknessAnimation()
: base()
{
}
/// <summary>
/// Creates a new ThicknessAnimation that will animate a
/// Thickness property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public ThicknessAnimation(Thickness toValue, Duration duration)
: this()
{
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new ThicknessAnimation that will animate a
/// Thickness property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public ThicknessAnimation(Thickness toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
/// <summary>
/// Creates a new ThicknessAnimation that will animate a
/// Thickness property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public ThicknessAnimation(Thickness fromValue, Thickness toValue, Duration duration)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new ThicknessAnimation that will animate a
/// Thickness property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public ThicknessAnimation(Thickness fromValue, Thickness toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this ThicknessAnimation
/// </summary>
/// <returns>The copy</returns>
public new ThicknessAnimation Clone()
{
return (ThicknessAnimation)base.Clone();
}
//
// Note that we don't override the Clone virtuals (CloneCore, CloneCurrentValueCore,
// GetAsFrozenCore, and GetCurrentValueAsFrozenCore) even though this class has state
// not stored in a DP.
//
// We don't need to clone _animationType and _keyValues because they are the the cached
// results of animation function validation, which can be recomputed. The other remaining
// field, isAnimationFunctionValid, defaults to false, which causes this recomputation to happen.
//
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new ThicknessAnimation();
}
#endregion
#region Methods
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected override Thickness GetCurrentValueCore(Thickness defaultOriginValue, Thickness defaultDestinationValue, AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (!_isAnimationFunctionValid)
{
ValidateAnimationFunction();
}
double progress = animationClock.CurrentProgress.Value;
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
progress = easingFunction.Ease(progress);
}
Thickness from = new Thickness();
Thickness to = new Thickness();
Thickness accumulated = new Thickness();
Thickness foundation = new Thickness();
// need to validate the default origin and destination values if
// the animation uses them as the from, to, or foundation values
bool validateOrigin = false;
bool validateDestination = false;
switch(_animationType)
{
case AnimationType.Automatic:
from = defaultOriginValue;
to = defaultDestinationValue;
validateOrigin = true;
validateDestination = true;
break;
case AnimationType.From:
from = _keyValues[0];
to = defaultDestinationValue;
validateDestination = true;
break;
case AnimationType.To:
from = defaultOriginValue;
to = _keyValues[0];
validateOrigin = true;
break;
case AnimationType.By:
// According to the SMIL specification, a By animation is
// always additive. But we don't force this so that a
// user can re-use a By animation and have it replace the
// animations that precede it in the list without having
// to manually set the From value to the base value.
to = _keyValues[0];
foundation = defaultOriginValue;
validateOrigin = true;
break;
case AnimationType.FromTo:
from = _keyValues[0];
to = _keyValues[1];
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
case AnimationType.FromBy:
from = _keyValues[0];
to = AnimatedTypeHelpers.AddThickness(_keyValues[0], _keyValues[1]);
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
default:
Debug.Fail("Unknown animation type.");
break;
}
if (validateOrigin
&& !AnimatedTypeHelpers.IsValidAnimationValueThickness(defaultOriginValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"origin",
defaultOriginValue.ToString(CultureInfo.InvariantCulture)));
}
if (validateDestination
&& !AnimatedTypeHelpers.IsValidAnimationValueThickness(defaultDestinationValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"destination",
defaultDestinationValue.ToString(CultureInfo.InvariantCulture)));
}
if (IsCumulative)
{
double currentRepeat = (double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
Thickness accumulator = AnimatedTypeHelpers.SubtractThickness(to, from);
accumulated = AnimatedTypeHelpers.ScaleThickness(accumulator, currentRepeat);
}
}
// return foundation + accumulated + from + ((to - from) * progress)
return AnimatedTypeHelpers.AddThickness(
foundation,
AnimatedTypeHelpers.AddThickness(
accumulated,
AnimatedTypeHelpers.InterpolateThickness(from, to, progress)));
}
private void ValidateAnimationFunction()
{
_animationType = AnimationType.Automatic;
_keyValues = null;
if (From.HasValue)
{
if (To.HasValue)
{
_animationType = AnimationType.FromTo;
_keyValues = new Thickness[2];
_keyValues[0] = From.Value;
_keyValues[1] = To.Value;
}
else if (By.HasValue)
{
_animationType = AnimationType.FromBy;
_keyValues = new Thickness[2];
_keyValues[0] = From.Value;
_keyValues[1] = By.Value;
}
else
{
_animationType = AnimationType.From;
_keyValues = new Thickness[1];
_keyValues[0] = From.Value;
}
}
else if (To.HasValue)
{
_animationType = AnimationType.To;
_keyValues = new Thickness[1];
_keyValues[0] = To.Value;
}
else if (By.HasValue)
{
_animationType = AnimationType.By;
_keyValues = new Thickness[1];
_keyValues[0] = By.Value;
}
_isAnimationFunctionValid = true;
}
#endregion
#region Properties
private static void AnimationFunction_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ThicknessAnimation a = (ThicknessAnimation)d;
a._isAnimationFunctionValid = false;
a.PropertyChanged(e.Property);
}
private static bool ValidateFromToOrByValue(object value)
{
Thickness? typedValue = (Thickness?)value;
if (typedValue.HasValue)
{
return AnimatedTypeHelpers.IsValidAnimationValueThickness(typedValue.Value);
}
else
{
return true;
}
}
/// <summary>
/// FromProperty
/// </summary>
public static readonly DependencyProperty FromProperty;
/// <summary>
/// From
/// </summary>
public Thickness? From
{
get
{
return (Thickness?)GetValue(FromProperty);
}
set
{
SetValueInternal(FromProperty, value);
}
}
/// <summary>
/// ToProperty
/// </summary>
public static readonly DependencyProperty ToProperty;
/// <summary>
/// To
/// </summary>
public Thickness? To
{
get
{
return (Thickness?)GetValue(ToProperty);
}
set
{
SetValueInternal(ToProperty, value);
}
}
/// <summary>
/// ByProperty
/// </summary>
public static readonly DependencyProperty ByProperty;
/// <summary>
/// By
/// </summary>
public Thickness? By
{
get
{
return (Thickness?)GetValue(ByProperty);
}
set
{
SetValueInternal(ByProperty, value);
}
}
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty;
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
/// <summary>
/// If this property is set to true the animation will add its value to
/// the base value instead of replacing it entirely.
/// </summary>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// It this property is set to true, the animation will accumulate its
/// value over repeats. For instance if you have a From value of 0.0 and
/// a To value of 1.0, the animation return values from 1.0 to 2.0 over
/// the second reteat cycle, and 2.0 to 3.0 over the third, etc.
/// </summary>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#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.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.IO.Ports.Tests
{
public class ReadByte_Generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low read will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the read method and the testcase fails.
private static double s_maxPercentageDifference = .15;
private const int NUM_TRYS = 5;
//The number of random bytes to receive
private const int numRndByte = 8;
#region Test Cases
[Fact]
public void ReadWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying read method throws exception without a call to Open()");
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying read method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verifying a read method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void Timeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout);
com.Open();
VerifyTimeout(com);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void SuccessiveReadTimeoutNoData()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
// com.Encoding = new System.Text.UTF7Encoding();
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout);
com.Open();
Assert.Throws<TimeoutException>(() => com.ReadByte());
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void SuccessiveReadTimeoutSomeData()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
var t = new Task(WriteToCom1);
com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Encoding = new UTF8Encoding();
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout);
com1.Open();
//Call WriteToCom1 asynchronously this will write to com1 some time before the following call
//to a read method times out
t.Start();
try
{
com1.ReadByte();
}
catch (TimeoutException)
{
}
TCSupport.WaitForTaskCompletion(t);
//Make sure there is no bytes in the buffer so the next call to read will timeout
com1.DiscardInBuffer();
VerifyTimeout(com1);
}
}
private void WriteToCom1()
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] xmitBuffer = new byte[1];
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.Write(xmitBuffer, 0, xmitBuffer.Length);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DefaultParityReplaceByte()
{
VerifyParityReplaceByte(-1, numRndByte - 2);
}
[ConditionalFact(nameof(HasNullModem))]
public void NoParityReplaceByte()
{
Random rndGen = new Random(-55);
// if(!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndByte - 1), new System.Text.UTF7Encoding())){
VerifyParityReplaceByte('\0', rndGen.Next(0, numRndByte - 1), new UTF32Encoding());
}
[ConditionalFact(nameof(HasNullModem))]
public void RNDParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte(rndGen.Next(0, 128), 0, new UTF8Encoding());
}
[ConditionalFact(nameof(HasNullModem))]
public void ParityErrorOnLastByte()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(15);
byte[] bytesToWrite = new byte[numRndByte];
byte[] expectedBytes = new byte[numRndByte];
byte[] actualBytes = new byte[numRndByte + 1];
int actualByteIndex = 0;
/* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream
We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */
Debug.WriteLine("Verifying default ParityReplace byte with a parity error on the last byte");
//Genrate random characters without an parity error
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedBytes[i] = randByte;
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80);
//Create a parity error on the last byte
expectedBytes[expectedBytes.Length - 1] = com1.ParityReplace;
// Set the last expected byte to be the ParityReplace Byte
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.ReadTimeout = 250;
com1.Open();
com2.Open();
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1);
while (true)
{
int byteRead;
try
{
byteRead = com1.ReadByte();
}
catch (TimeoutException)
{
break;
}
actualBytes[actualByteIndex] = (byte)byteRead;
actualByteIndex++;
}
//Compare the chars that were written with the ones we expected to read
for (int i = 0; i < expectedBytes.Length; i++)
{
if (expectedBytes[i] != actualBytes[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedBytes[i], (int)actualBytes[i]);
}
}
if (1 < com1.BytesToRead)
{
Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]);
Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead);
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F);
//Clear the parity error on the last byte
expectedBytes[expectedBytes.Length - 1] = bytesToWrite[bytesToWrite.Length - 1];
VerifyRead(com1, com2, bytesToWrite, expectedBytes, Encoding.ASCII);
}
}
#endregion
#region Verification for Test Cases
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.ReadTimeout;
int actualTime = 0;
double percentageDifference;
//Warm up read method
Assert.Throws<TimeoutException>(() => com.ReadByte());
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
Assert.Throws<TimeoutException>(() => com.ReadByte());
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (s_maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The read method timed-out in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void VerifyReadException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.ReadByte());
}
private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex)
{
VerifyParityReplaceByte(parityReplace, parityErrorIndex, new ASCIIEncoding());
}
private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex, Encoding encoding)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] byteBuffer = new byte[numRndByte];
byte[] expectedBytes = new byte[numRndByte];
int expectedChar;
//Genrate random bytes without an parity error
for (int i = 0; i < byteBuffer.Length; i++)
{
int randChar = rndGen.Next(0, 128);
byteBuffer[i] = (byte)randChar;
expectedBytes[i] = (byte)randChar;
}
if (-1 == parityReplace)
{
//If parityReplace is -1 and we should just use the default value
expectedChar = com1.ParityReplace;
}
else if ('\0' == parityReplace)
{
//If parityReplace is the null charachater and parity replacement should not occur
com1.ParityReplace = (byte)parityReplace;
expectedChar = expectedBytes[parityErrorIndex];
}
else
{
//Else parityReplace was set to a value and we should expect this value to be returned on a parity error
com1.ParityReplace = (byte)parityReplace;
expectedChar = parityReplace;
}
//Create an parity error by setting the highest order bit to true
byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80);
expectedBytes[parityErrorIndex] = (byte)expectedChar;
Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace,
parityErrorIndex);
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.Open();
com2.Open();
VerifyRead(com1, com2, byteBuffer, expectedBytes, encoding);
}
}
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes,
Encoding encoding)
{
byte[] byteRcvBuffer = new byte[expectedBytes.Length];
int rcvBufferSize = 0;
int i;
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 250;
com1.Encoding = encoding;
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
i = 0;
while (true)
{
int readInt;
try
{
readInt = com1.ReadByte();
}
catch (TimeoutException)
{
break;
}
//While their are more bytes to be read
if (expectedBytes.Length <= i)
{
//If we have read in more bytes then we expecte
Fail("ERROR!!!: We have received more bytes then were sent");
}
byteRcvBuffer[i] = (byte)readInt;
rcvBufferSize++;
if (bytesToWrite.Length - rcvBufferSize != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - rcvBufferSize,
com1.BytesToRead);
}
if (readInt != expectedBytes[i])
{
//If the bytes read is not the expected byte
Fail("ERROR!!!: Expected to read {0} actual read byte {1}", expectedBytes[i], (byte)readInt);
}
i++;
}
if (rcvBufferSize != expectedBytes.Length)
{
Fail("ERROR!!! Expected to read {0} char actually read {1} chars", bytesToWrite.Length, rcvBufferSize);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.Management.TrafficManager
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for EndpointsOperations.
/// </summary>
public static partial class EndpointsOperationsExtensions
{
/// <summary>
/// Update a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the Update operation.
/// </param>
public static Endpoint Update(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).UpdateAsync(resourceGroupName, profileName, endpointType, endpointName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the Update operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> UpdateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointType, endpointName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint.
/// </param>
public static Endpoint Get(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).GetAsync(resourceGroupName, profileName, endpointType, endpointName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> GetAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, endpointType, endpointName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or update a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be created or updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the CreateOrUpdate
/// operation.
/// </param>
public static Endpoint CreateOrUpdate(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).CreateOrUpdateAsync(resourceGroupName, profileName, endpointType, endpointName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or update a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be created or updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the CreateOrUpdate
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> CreateOrUpdateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointType, endpointName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be deleted.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be deleted.
/// </param>
public static void Delete(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName)
{
Task.Factory.StartNew(s => ((IEndpointsOperations)s).DeleteAsync(resourceGroupName, profileName, endpointType, endpointName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be deleted.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointType, endpointName, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G05_SubContinent_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="G05_SubContinent_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="G04_SubContinent"/> collection.
/// </remarks>
[Serializable]
public partial class G05_SubContinent_ReChild : BusinessBase<G05_SubContinent_ReChild>
{
#region State Fields
[NotUndoable]
private byte[] _rowVersion = new byte[] {};
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SubContinent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Countries Child Name");
/// <summary>
/// Gets or sets the Countries Child Name.
/// </summary>
/// <value>The Countries Child Name.</value>
public string SubContinent_Child_Name
{
get { return GetProperty(SubContinent_Child_NameProperty); }
set { SetProperty(SubContinent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G05_SubContinent_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G05_SubContinent_ReChild"/> object.</returns>
internal static G05_SubContinent_ReChild NewG05_SubContinent_ReChild()
{
return DataPortal.CreateChild<G05_SubContinent_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="G05_SubContinent_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="subContinent_ID2">The SubContinent_ID2 parameter of the G05_SubContinent_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="G05_SubContinent_ReChild"/> object.</returns>
internal static G05_SubContinent_ReChild GetG05_SubContinent_ReChild(int subContinent_ID2)
{
return DataPortal.FetchChild<G05_SubContinent_ReChild>(subContinent_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G05_SubContinent_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G05_SubContinent_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G05_SubContinent_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="G05_SubContinent_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="subContinent_ID2">The Sub Continent ID2.</param>
protected void Child_Fetch(int subContinent_ID2)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetG05_SubContinent_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID2", subContinent_ID2).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, subContinent_ID2);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="G05_SubContinent_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name"));
_rowVersion = dr.GetValue("RowVersion") as byte[];
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="G05_SubContinent_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(G04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddG05_SubContinent_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID2", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
_rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value;
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G05_SubContinent_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(G04_SubContinent parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateG05_SubContinent_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID2", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@RowVersion", _rowVersion).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
_rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value;
}
}
}
/// <summary>
/// Self deletes the <see cref="G05_SubContinent_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(G04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteG05_SubContinent_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID2", parent.SubContinent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// XmlAttributeCollectionTests.cs : Tests for the XmlAttributeCollection class
//
// Author: Matt Hunter <[email protected]>
// Author: Martin Willemoes Hansen <[email protected]>
//
// (C) 2002 Matt Hunter
// (C) 2003 Martin Willemoes Hansen
using System;
using System.Xml;
using System.Text;
using System.IO;
using System.Collections;
using NUnit.Framework;
namespace MonoTests.System.Xml
{
[TestFixture]
public class XmlAttributeCollectionTests : Assertion
{
private XmlDocument document;
[SetUp]
public void GetReady()
{
document = new XmlDocument ();
}
[Test]
public void RemoveAll ()
{
StringBuilder xml = new StringBuilder ();
xml.Append ("<?xml version=\"1.0\" ?><library><book type=\"non-fiction\" price=\"34.95\"> ");
xml.Append ("<title type=\"intro\">XML Fun</title> " );
xml.Append ("<author>John Doe</author></book></library>");
MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml.ToString ()));
document = new XmlDocument ();
document.Load (memoryStream);
XmlNodeList bookList = document.GetElementsByTagName ("book");
XmlNode xmlNode = bookList.Item (0);
XmlElement xmlElement = xmlNode as XmlElement;
XmlAttributeCollection attributes = xmlElement.Attributes;
attributes.RemoveAll ();
AssertEquals ("not all attributes removed.", false, xmlElement.HasAttribute ("type"));
}
[Test]
public void Append ()
{
XmlDocument xmlDoc = new XmlDocument ();
XmlElement xmlEl = xmlDoc.CreateElement ("TestElement");
XmlAttribute xmlAttribute = xmlEl.SetAttributeNode ("attr1", "namespace1");
XmlNode xmlNode = xmlDoc.CreateNode (XmlNodeType.Attribute, "attr3", "namespace1");
XmlAttribute xmlAttribute3 = xmlNode as XmlAttribute;
XmlAttributeCollection attributeCol = xmlEl.Attributes;
xmlAttribute3 = attributeCol.Append (xmlAttribute3);
AssertEquals ("attribute name not properly created.", true, xmlAttribute3.Name.Equals ("attr3"));
AssertEquals ("attribute namespace not properly created.", true, xmlAttribute3.NamespaceURI.Equals ("namespace1"));
}
[Test]
public void CopyTo ()
{
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml("<root a1='garnet' a2='amethyst' a3='Bloodstone' a4='diamond' a5='emerald' a6='pearl' a7='ruby' a8='sapphire' a9='moonstone' a10='opal' a11='topaz' a12='turquoize' />");
XmlAttributeCollection col = xmlDoc.DocumentElement.Attributes;
XmlAttribute[] array = new XmlAttribute[24];
col.CopyTo(array, 0);
AssertEquals("garnet", array[0].Value);
AssertEquals("moonstone", array[8].Value);
AssertEquals("turquoize", array[11].Value);
col.CopyTo(array, 12);
AssertEquals("garnet", array[12].Value);
AssertEquals("moonstone", array[20].Value);
AssertEquals("turquoize", array[23].Value);
}
[Test]
public void SetNamedItem ()
{
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml("<root />");
XmlElement el = xmlDoc.DocumentElement;
XmlAttributeCollection col = xmlDoc.DocumentElement.Attributes;
XmlAttribute attr = xmlDoc.CreateAttribute("b3");
attr.Value = "bloodstone";
col.SetNamedItem(attr);
AssertEquals("SetNamedItem.Normal", "bloodstone", el.GetAttribute("b3"));
attr = xmlDoc.CreateAttribute("b3");
attr.Value = "aquamaline";
col.SetNamedItem(attr);
AssertEquals("SetNamedItem.Override", "aquamaline", el.GetAttribute("b3"));
AssertEquals("SetNamedItem.Override.Count.1", 1, el.Attributes.Count);
AssertEquals("SetNamedItem.Override.Count.2", 1, col.Count);
}
[Test]
public void InsertBeforeAfterPrepend ()
{
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml("<root b2='amethyst' />");
XmlElement el = xmlDoc.DocumentElement;
XmlAttributeCollection col = xmlDoc.DocumentElement.Attributes;
XmlAttribute attr = xmlDoc.CreateAttribute("b1");
attr.Value = "garnet";
col.InsertAfter(attr, null);
AssertEquals("InsertAfterNull", "garnet", el.GetAttributeNode("b1").Value);
AssertEquals("InsertAfterNull.Pos", el.GetAttribute("b1"), col[0].Value);
attr = xmlDoc.CreateAttribute("b3");
attr.Value = "bloodstone";
col.InsertAfter(attr, el.GetAttributeNode("b2"));
AssertEquals("InsertAfterAttr", "bloodstone", el.GetAttributeNode("b3").Value);
AssertEquals("InsertAfterAttr.Pos", el.GetAttribute("b3"), col[2].Value);
attr = xmlDoc.CreateAttribute("b4");
attr.Value = "diamond";
col.InsertBefore(attr, null);
AssertEquals("InsertBeforeNull", "diamond", el.GetAttributeNode("b4").Value);
AssertEquals("InsertBeforeNull.Pos", el.GetAttribute("b4"), col[3].Value);
attr = xmlDoc.CreateAttribute("warning");
attr.Value = "mixed modern and traditional;-)";
col.InsertBefore(attr, el.GetAttributeNode("b1"));
AssertEquals("InsertBeforeAttr", "mixed modern and traditional;-)", el.GetAttributeNode("warning").Value);
AssertEquals("InsertBeforeAttr.Pos", el.GetAttributeNode("warning").Value, col[0].Value);
attr = xmlDoc.CreateAttribute("about");
attr.Value = "lists of birthstone.";
col.Prepend(attr);
AssertEquals("Prepend", "lists of birthstone.", col[0].Value);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void InsertAfterError ()
{
this.document.LoadXml ("<root><elem a='1'/></root>");
XmlAttribute attr = document.CreateAttribute ("foo");
attr.Value = "test";
document.DocumentElement.Attributes.InsertAfter (attr, document.DocumentElement.FirstChild.Attributes [0]);
}
[Test]
public void InsertAfterReplacesInCorrectOrder ()
{
XmlDocument testDoc = new XmlDocument ();
XmlElement testElement = testDoc.CreateElement ("TestElement" );
testDoc.AppendChild (testElement);
XmlAttribute testAttr1 = testDoc.CreateAttribute ("TestAttribute1");
testAttr1.Value = "First attribute";
testElement.Attributes.Prepend (testAttr1);
XmlAttribute testAttr2 = testDoc.CreateAttribute ("TestAttribute2");
testAttr2.Value = "Second attribute";
testElement.Attributes.InsertAfter (testAttr2, testAttr1);
XmlAttribute testAttr3 = testDoc.CreateAttribute ("TestAttribute3");
testAttr3.Value = "Third attribute";
testElement.Attributes.InsertAfter (testAttr3, testAttr2);
XmlAttribute outOfOrder = testDoc.CreateAttribute ("TestAttribute2");
outOfOrder.Value = "Should still be second attribute";
testElement.Attributes.InsertAfter (outOfOrder, testElement.Attributes [0]);
AssertEquals ("First attribute", testElement.Attributes [0].Value);
AssertEquals ("Should still be second attribute", testElement.Attributes [1].Value);
AssertEquals ("Third attribute", testElement.Attributes [2].Value);
}
[Test]
public void Remove ()
{
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml("<root a1='garnet' a2='amethyst' a3='bloodstone' a4='diamond' a5='emerald' a6='pearl' a7='ruby' a8='sapphire' a9='moonstone' a10='opal' a11='topaz' a12='turquoize' />");
XmlElement el = xmlDoc.DocumentElement;
XmlAttributeCollection col = el.Attributes;
// Remove
XmlAttribute attr = col.Remove(el.GetAttributeNode("a12"));
AssertEquals("Remove", 11, col.Count);
AssertEquals("Remove.Removed", "a12", attr.Name);
// RemoveAt
attr = col.RemoveAt(5);
AssertEquals("RemoveAt", null, el.GetAttributeNode("a6"));
AssertEquals("Remove.Removed", "pearl", attr.Value);
}
[Test]
public void RemoveDefaultAttribute ()
{
string dtd = "<!DOCTYPE root [<!ELEMENT root EMPTY><!ATTLIST root attr CDATA 'default'>]>";
string xml = dtd + "<root/>";
XmlDocument doc = new XmlDocument();
doc.LoadXml (xml);
doc.DocumentElement.Attributes ["attr"].Value = "modified";
doc.DocumentElement.RemoveAttribute("attr");
XmlAttribute defAttr = doc.DocumentElement.Attributes ["attr"];
AssertNotNull (defAttr);
AssertEquals ("default", defAttr.Value);
defAttr.Value = "default"; // same value as default
AssertEquals (true, defAttr.Specified);
}
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
/*
Copyright 2011 Michael Edwards
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 System.Text;
using Glass.Mapper.Sc.Configuration;
using global::Sitecore.Data;
namespace Glass.Mapper.Sc.CodeFirst
{
/// <summary>
/// Class FieldInfo
/// </summary>
public class FieldInfo
{
/// <summary>
/// Initializes a new instance of the <see cref="FieldInfo"/> class.
/// </summary>
/// <param name="fieldId">The field id.</param>
/// <param name="sectionId">The section id.</param>
/// <param name="name">The name.</param>
/// <param name="type">The type.</param>
/// <param name="customFieldType">The custom field type.</param>
/// <param name="source">The source.</param>
/// <param name="title">The title.</param>
/// <param name="isShared">if set to <c>true</c> [is shared].</param>
/// <param name="isUnversioned">if set to <c>true</c> [is unversioned].</param>
/// <param name="fieldSortOrder">The field sort order.</param>
/// <param name="validationRegularExpression">The validation regular expression.</param>
/// <param name="validationErrorText">The validation error text.</param>
/// <param name="isRequired">if set to <c>true</c> [is required].</param>
public FieldInfo(ID fieldId, ID sectionId, string name, SitecoreFieldType type, string customFieldType, string source, string title, bool isShared, bool isUnversioned, int fieldSortOrder, string validationRegularExpression, string validationErrorText, bool isRequired)
{
FieldId = fieldId;
SectionId = sectionId;
Name = name;
FieldType = type;
CustomFieldType = customFieldType;
Source = source;
Title = title;
IsShared = isShared;
IsUnversioned = isUnversioned;
FieldFieldValues = new Dictionary<ID, string>();
FieldSortOrder = fieldSortOrder;
ValidationRegularExpression = validationRegularExpression;
ValidationErrorText = validationErrorText;
IsRequired = isRequired;
}
/// <summary>
/// Gets or sets the field id.
/// </summary>
/// <value>The field id.</value>
public ID FieldId { get; set; }
/// <summary>
/// Gets or sets the section id.
/// </summary>
/// <value>The section id.</value>
public ID SectionId { get; set; }
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string Name { get; set; }
/// <summary>
/// Gets or sets the custom field type.
/// </summary>
/// <value>The field type.</value>
public SitecoreFieldType FieldType { get; set; }
/// <summary>
/// Gets or sets the field type.
/// </summary>
/// <value>The custom field type.</value>
public string CustomFieldType { get; set; }
/// <summary>
/// Gets or sets the source.
/// </summary>
/// <value>The source.</value>
public string Source { get; set; }
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>The title.</value>
public string Title { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is shared.
/// </summary>
/// <value><c>true</c> if this instance is shared; otherwise, <c>false</c>.</value>
public bool IsShared { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is unversioned.
/// </summary>
/// <value><c>true</c> if this instance is unversioned; otherwise, <c>false</c>.</value>
public bool IsUnversioned { get; set; }
/// <summary>
/// Gets or sets the field field values.
/// </summary>
/// <value>The field field values.</value>
public Dictionary<ID,string> FieldFieldValues { get; protected set; }
/// <summary>
/// Gets or sets the field sort order.
/// </summary>
/// <value>The field sort order.</value>
public int FieldSortOrder { get; set; }
/// <summary>
/// Gets or sets the validation regular expression.
/// </summary>
/// <value>The validation regular expression.</value>
public string ValidationRegularExpression { get; set; }
/// <summary>
/// Gets or sets the validation error text.
/// </summary>
/// <value>The validation error text.</value>
public string ValidationErrorText { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is required.
/// </summary>
/// <value><c>true</c> if this instance is required; otherwise, <c>false</c>.</value>
public bool IsRequired { get; set; }
/// <summary>
/// Gets the type of the field.
/// </summary>
/// <returns>System.String.</returns>
public string GetFieldType()
{
switch (FieldType)
{
case SitecoreFieldType.Checkbox:
return "Checkbox";
case SitecoreFieldType.Date:
return "Date";
case SitecoreFieldType.DateTime:
return "Datetime";
case SitecoreFieldType.File:
return "File";
case SitecoreFieldType.Image:
return "Image";
case SitecoreFieldType.Integer:
return "Integer";
case SitecoreFieldType.MultiLineText:
return "Multi-Line Text";
case SitecoreFieldType.Number:
return "Number";
case SitecoreFieldType.Password:
return "Password";
case SitecoreFieldType.RichText:
return "Rich Text";
case SitecoreFieldType.SingleLineText:
return "Single-Line Text";
case SitecoreFieldType.Checklist:
return "Checklist";
case SitecoreFieldType.Droplist:
return "Droplist";
case SitecoreFieldType.GroupedDroplink:
return "Grouped Droplink";
case SitecoreFieldType.GroupedDroplist:
return "Grouped Droplist";
case SitecoreFieldType.Multilist:
return "Multilist";
case SitecoreFieldType.Treelist:
return "Treelist";
case SitecoreFieldType.TreelistEx:
return "TreelistEx";
case SitecoreFieldType.Droplink:
return "Droplink";
case SitecoreFieldType.DropTree:
return "Droptree";
case SitecoreFieldType.GeneralLink:
return "General Link";
case SitecoreFieldType.Custom:
return CustomFieldType;
default:
return "Single-Line Text";
}
}
}
}
| |
using Microsoft.Azure.ApplicationInsights.Query.Models;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
namespace Microsoft.Azure.ApplicationInsights.Query
{
public partial interface IMetrics
{
/// <summary>
/// Retrieve summary metric data
/// </summary>
/// <remarks>
/// Gets summary metric values for a single metric
/// </remarks>
/// <param name='appId'>
/// ID of the application. This is Application ID from the API Access settings
/// blade in the Azure portal.
/// </param>
/// <param name='metricId'>
/// ID of the metric. This is either a standard AI metric, or an
/// application-specific custom metric. Possible values include:
/// 'requests/count', 'requests/duration', 'requests/failed',
/// 'users/count', 'users/authenticated', 'pageViews/count',
/// 'pageViews/duration', 'client/processingDuration',
/// 'client/receiveDuration', 'client/networkDuration',
/// 'client/sendDuration', 'client/totalDuration',
/// 'dependencies/count', 'dependencies/failed',
/// 'dependencies/duration', 'exceptions/count', 'exceptions/browser',
/// 'exceptions/server', 'sessions/count',
/// 'performanceCounters/requestExecutionTime',
/// 'performanceCounters/requestsPerSecond',
/// 'performanceCounters/requestsInQueue',
/// 'performanceCounters/memoryAvailableBytes',
/// 'performanceCounters/exceptionsPerSecond',
/// 'performanceCounters/processCpuPercentage',
/// 'performanceCounters/processIOBytesPerSecond',
/// 'performanceCounters/processPrivateBytes',
/// 'performanceCounters/processorCpuPercentage',
/// 'availabilityResults/availabilityPercentage',
/// 'availabilityResults/duration', 'billing/telemetryCount',
/// 'customEvents/count'
/// </param>
/// <param name='timespan'>
/// The timespan over which to retrieve metric values. This is an
/// ISO8601 time period value. If timespan is omitted, a default time
/// range of `PT12H` ("last 12 hours") is used. The actual timespan
/// that is queried may be adjusted by the server based. In all cases,
/// the actual time span used for the query is included in the
/// response.
/// </param>
/// <param name='aggregation'>
/// The aggregation to use when computing the metric values. To
/// retrieve more than one aggregation at a time, separate them with a
/// comma. If no aggregation is specified, then the default aggregation
/// for the metric is used.
/// </param>
/// <param name='top'>
/// The number of segments to return. This value is only valid when
/// segment is specified.
/// </param>
/// <param name='orderby'>
/// The aggregation function and direction to sort the segments by.
/// This value is only valid when segment is specified.
/// </param>
/// <param name='filter'>
/// An expression used to filter the results. This value should be a
/// valid OData filter expression where the keys of each clause should
/// be applicable dimensions for the metric you are retrieving.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<MetricsSummaryResult>> GetMetricSummaryWithHttpMessagesAsync(string appId, string metricId, string timespan = default(string), IList<string> aggregation = default(IList<string>),
int? top = default(int?), string orderby = default(string), string filter = default(string), Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve metric data
/// </summary>
/// <remarks>
/// Gets metric values for a single metric
/// </remarks>
/// <param name='appId'>
/// ID of the application. This is Application ID from the API Access settings
/// blade in the Azure portal.
/// </param>
/// <param name='metricId'>
/// ID of the metric. This is either a standard AI metric, or an
/// application-specific custom metric. Possible values include:
/// 'requests/count', 'requests/duration', 'requests/failed',
/// 'users/count', 'users/authenticated', 'pageViews/count',
/// 'pageViews/duration', 'client/processingDuration',
/// 'client/receiveDuration', 'client/networkDuration',
/// 'client/sendDuration', 'client/totalDuration',
/// 'dependencies/count', 'dependencies/failed',
/// 'dependencies/duration', 'exceptions/count', 'exceptions/browser',
/// 'exceptions/server', 'sessions/count',
/// 'performanceCounters/requestExecutionTime',
/// 'performanceCounters/requestsPerSecond',
/// 'performanceCounters/requestsInQueue',
/// 'performanceCounters/memoryAvailableBytes',
/// 'performanceCounters/exceptionsPerSecond',
/// 'performanceCounters/processCpuPercentage',
/// 'performanceCounters/processIOBytesPerSecond',
/// 'performanceCounters/processPrivateBytes',
/// 'performanceCounters/processorCpuPercentage',
/// 'availabilityResults/availabilityPercentage',
/// 'availabilityResults/duration', 'billing/telemetryCount',
/// 'customEvents/count'
/// </param>
/// <param name='timespan'>
/// The timespan over which to retrieve metric values. This is an
/// ISO8601 time period value. If timespan is omitted, a default time
/// range of `PT12H` ("last 12 hours") is used. The actual timespan
/// that is queried may be adjusted by the server based. In all cases,
/// the actual time span used for the query is included in the
/// response.
/// </param>
/// <param name='interval'>
/// The time interval to use when retrieving metric values. This is an
/// ISO8601 duration. If interval is omitted, the metric value is
/// aggregated across the entire timespan. If interval is supplied, the
/// server may adjust the interval to a more appropriate size based on
/// the timespan used for the query. In all cases, the actual interval
/// used for the query is included in the response.
/// </param>
/// <param name='aggregation'>
/// The aggregation to use when computing the metric values. To
/// retrieve more than one aggregation at a time, separate them with a
/// comma. If no aggregation is specified, then the default aggregation
/// for the metric is used.
/// </param>
/// <param name='segment'>
/// The name of the dimension to segment the metric values by. This
/// dimension must be applicable to the metric you are retrieving. To
/// segment by more than one dimension at a time, separate them with a
/// comma (,). In this case, the metric data will be segmented in the
/// order the dimensions are listed in the parameter.
/// </param>
/// <param name='top'>
/// The number of segments to return. This value is only valid when
/// segment is specified.
/// </param>
/// <param name='orderby'>
/// The aggregation function and direction to sort the segments by.
/// This value is only valid when segment is specified.
/// </param>
/// <param name='filter'>
/// An expression used to filter the results. This value should be a
/// valid OData filter expression where the keys of each clause should
/// be applicable dimensions for the metric you are retrieving.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<MetricsIntervaledResult>> GetIntervaledMetricWithHttpMessagesAsync(string appId,
string metricId, string timespan = default(string),
System.TimeSpan? interval = default(System.TimeSpan?), IList<string> aggregation = default(IList<string>),
IList<string> segment = default(IList<string>), int? top = default(int?), string orderby = default(string),
string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve metric data
/// </summary>
/// <remarks>
/// Gets metric values for a single metric
/// </remarks>
/// <param name='appId'>
/// ID of the application. This is Application ID from the API Access settings
/// blade in the Azure portal.
/// </param>
/// <param name='metricId'>
/// ID of the metric. This is either a standard AI metric, or an
/// application-specific custom metric. Possible values include:
/// 'requests/count', 'requests/duration', 'requests/failed',
/// 'users/count', 'users/authenticated', 'pageViews/count',
/// 'pageViews/duration', 'client/processingDuration',
/// 'client/receiveDuration', 'client/networkDuration',
/// 'client/sendDuration', 'client/totalDuration',
/// 'dependencies/count', 'dependencies/failed',
/// 'dependencies/duration', 'exceptions/count', 'exceptions/browser',
/// 'exceptions/server', 'sessions/count',
/// 'performanceCounters/requestExecutionTime',
/// 'performanceCounters/requestsPerSecond',
/// 'performanceCounters/requestsInQueue',
/// 'performanceCounters/memoryAvailableBytes',
/// 'performanceCounters/exceptionsPerSecond',
/// 'performanceCounters/processCpuPercentage',
/// 'performanceCounters/processIOBytesPerSecond',
/// 'performanceCounters/processPrivateBytes',
/// 'performanceCounters/processorCpuPercentage',
/// 'availabilityResults/availabilityPercentage',
/// 'availabilityResults/duration', 'billing/telemetryCount',
/// 'customEvents/count'
/// </param>
/// <param name='timespan'>
/// The timespan over which to retrieve metric values. This is an
/// ISO8601 time period value. If timespan is omitted, a default time
/// range of `PT12H` ("last 12 hours") is used. The actual timespan
/// that is queried may be adjusted by the server based. In all cases,
/// the actual time span used for the query is included in the
/// response.
/// </param>
/// <param name='aggregation'>
/// The aggregation to use when computing the metric values. To
/// retrieve more than one aggregation at a time, separate them with a
/// comma. If no aggregation is specified, then the default aggregation
/// for the metric is used.
/// </param>
/// <param name='segment'>
/// The name of the dimension to segment the metric values by. This
/// dimension must be applicable to the metric you are retrieving. To
/// segment by more than one dimension at a time, separate them with a
/// comma (,). In this case, the metric data will be segmented in the
/// order the dimensions are listed in the parameter.
/// </param>
/// <param name='top'>
/// The number of segments to return. This value is only valid when
/// segment is specified.
/// </param>
/// <param name='orderby'>
/// The aggregation function and direction to sort the segments by.
/// This value is only valid when segment is specified.
/// </param>
/// <param name='filter'>
/// An expression used to filter the results. This value should be a
/// valid OData filter expression where the keys of each clause should
/// be applicable dimensions for the metric you are retrieving.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<MetricsSegmentedResult>> GetSegmentedMetricWithHttpMessagesAsync(string appId, string metricId,
string timespan = default(string), IList<string> aggregation = default(IList<string>),
IList<string> segment = default(IList<string>), int? top = default(int?), string orderby = default(string),
string filter = default(string), Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve metric data
/// </summary>
/// <remarks>
/// Gets metric values for a single metric
/// </remarks>
/// <param name='appId'>
/// ID of the application. This is Application ID from the API Access settings
/// blade in the Azure portal.
/// </param>
/// <param name='metricId'>
/// ID of the metric. This is either a standard AI metric, or an
/// application-specific custom metric. Possible values include:
/// 'requests/count', 'requests/duration', 'requests/failed',
/// 'users/count', 'users/authenticated', 'pageViews/count',
/// 'pageViews/duration', 'client/processingDuration',
/// 'client/receiveDuration', 'client/networkDuration',
/// 'client/sendDuration', 'client/totalDuration',
/// 'dependencies/count', 'dependencies/failed',
/// 'dependencies/duration', 'exceptions/count', 'exceptions/browser',
/// 'exceptions/server', 'sessions/count',
/// 'performanceCounters/requestExecutionTime',
/// 'performanceCounters/requestsPerSecond',
/// 'performanceCounters/requestsInQueue',
/// 'performanceCounters/memoryAvailableBytes',
/// 'performanceCounters/exceptionsPerSecond',
/// 'performanceCounters/processCpuPercentage',
/// 'performanceCounters/processIOBytesPerSecond',
/// 'performanceCounters/processPrivateBytes',
/// 'performanceCounters/processorCpuPercentage',
/// 'availabilityResults/availabilityPercentage',
/// 'availabilityResults/duration', 'billing/telemetryCount',
/// 'customEvents/count'
/// </param>
/// <param name='timespan'>
/// The timespan over which to retrieve metric values. This is an
/// ISO8601 time period value. If timespan is omitted, a default time
/// range of `PT12H` ("last 12 hours") is used. The actual timespan
/// that is queried may be adjusted by the server based. In all cases,
/// the actual time span used for the query is included in the
/// response.
/// </param>
/// <param name='interval'>
/// The time interval to use when retrieving metric values. This is an
/// ISO8601 duration. If interval is omitted, the metric value is
/// aggregated across the entire timespan. If interval is supplied, the
/// server may adjust the interval to a more appropriate size based on
/// the timespan used for the query. In all cases, the actual interval
/// used for the query is included in the response.
/// </param>
/// <param name='aggregation'>
/// The aggregation to use when computing the metric values. To
/// retrieve more than one aggregation at a time, separate them with a
/// comma. If no aggregation is specified, then the default aggregation
/// for the metric is used.
/// </param>
/// <param name='segment'>
/// The name of the dimension to segment the metric values by. This
/// dimension must be applicable to the metric you are retrieving. To
/// segment by more than one dimension at a time, separate them with a
/// comma (,). In this case, the metric data will be segmented in the
/// order the dimensions are listed in the parameter.
/// </param>
/// <param name='top'>
/// The number of segments to return. This value is only valid when
/// segment is specified.
/// </param>
/// <param name='orderby'>
/// The aggregation function and direction to sort the segments by.
/// This value is only valid when segment is specified.
/// </param>
/// <param name='filter'>
/// An expression used to filter the results. This value should be a
/// valid OData filter expression where the keys of each clause should
/// be applicable dimensions for the metric you are retrieving.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<MetricsIntervaledSegmentedResult>> GetIntervaledSegmentedMetricWithHttpMessagesAsync(string appId, string metricId,
string timespan = default(string), System.TimeSpan? interval = default(System.TimeSpan?),
IList<string> aggregation = default(IList<string>), IList<string> segment = default(IList<string>),
int? top = default(int?), string orderby = default(string), string filter = default(string),
Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace HETSAPI.Models
{
/// <summary>
/// Project Database Model
/// </summary>
[MetaData (Description = "A Provincial Project that my from time to time request equipment under the HETS programme from a Service Area.")]
public sealed class Project : AuditableEntity, IEquatable<Project>
{
/// <summary>
/// Project Database Model Constructor (required by entity framework)
/// </summary>
public Project()
{
Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Project" /> class.
/// </summary>
/// <param name="id">A system-generated unique identifier for a Project (required).</param>
/// <param name="district">The District associated with this Project record. (required).</param>
/// <param name="name">A descriptive name for the Project, useful to the HETS Clerk and Project Manager. (required).</param>
/// <param name="status">The status of the project to determine if it is listed when creating new requests (required).</param>
/// <param name="provincialProjectNumber">TO BE REVIEWED WITH THE BUSINESS - The Provincial charge code for the equipment hiring related to this project. This will be the same across multiple service areas that provide equipment for the same Project..</param>
/// <param name="information">Information about the Project needed by the HETS Clerks. Used for capturing varying (project by project) metadata needed to process requests related to the project..</param>
/// <param name="rentalRequests">The Rental Requests associated with this Project.</param>
/// <param name="rentalAgreements">The Rental Agreements associated with this Project.</param>
/// <param name="primaryContact">Link to the designated Primary Contact for the Project - usually the Project Manager requesting to hire equipment..</param>
/// <param name="contacts">Contacts.</param>
/// <param name="notes">Notes.</param>
/// <param name="attachments">Attachments.</param>
/// <param name="history">History.</param>
public Project(int id, District district, string name, string status, string provincialProjectNumber = null,
string information = null, List<RentalRequest> rentalRequests = null, List<RentalAgreement> rentalAgreements = null,
Contact primaryContact = null, List<Contact> contacts = null, List<Note> notes = null, List<Attachment> attachments = null,
List<History> history = null)
{
Id = id;
District = district;
Name = name;
Status = status;
ProvincialProjectNumber = provincialProjectNumber;
Information = information;
RentalRequests = rentalRequests;
RentalAgreements = rentalAgreements;
PrimaryContact = primaryContact;
Contacts = contacts;
Notes = notes;
Attachments = attachments;
History = history;
}
/// <summary>
/// A system generated value to identify if this project's status can be edited in the UI
/// </summary>
/// <value>A system generated value to identify if this project's status can be edited in the UI</value>
[NotMapped]
public bool CanEditStatus { get; set; }
/// <summary>
/// A system-generated unique identifier for a Project
/// </summary>
/// <value>A system-generated unique identifier for a Project</value>
[MetaData (Description = "A system-generated unique identifier for a Project")]
public int Id { get; set; }
/// <summary>
/// The District associated with this Project record.
/// </summary>
/// <value>The District associated with this Project record.</value>
[MetaData (Description = "The District associated with this Project record.")]
public District District { get; set; }
/// <summary>
/// Foreign key for District
/// </summary>
[ForeignKey("District")]
[JsonIgnore]
[MetaData (Description = "The District associated with this Project record.")]
public int? DistrictId { get; set; }
/// <summary>
/// A descriptive name for the Project, useful to the HETS Clerk and Project Manager.
/// </summary>
/// <value>A descriptive name for the Project, useful to the HETS Clerk and Project Manager.</value>
[MetaData (Description = "A descriptive name for the Project, useful to the HETS Clerk and Project Manager.")]
[MaxLength(100)]
public string Name { get; set; }
/// <summary>
/// The status of the project to determine if it is listed when creating new requests
/// </summary>
/// <value>The status of the project to determine if it is listed when creating new requests</value>
[MetaData (Description = "The status of the project to determine if it is listed when creating new requests")]
[MaxLength(50)]
public string Status { get; set; }
/// <summary>
/// TO BE REVIEWED WITH THE BUSINESS - The Provincial charge code for the equipment hiring related to this project. This will be the same across multiple service areas that provide equipment for the same Project.
/// </summary>
/// <value>TO BE REVIEWED WITH THE BUSINESS - The Provincial charge code for the equipment hiring related to this project. This will be the same across multiple service areas that provide equipment for the same Project.</value>
[MetaData (Description = "TO BE REVIEWED WITH THE BUSINESS - The Provincial charge code for the equipment hiring related to this project. This will be the same across multiple service areas that provide equipment for the same Project.")]
[MaxLength(150)]
public string ProvincialProjectNumber { get; set; }
/// <summary>
/// Information about the Project needed by the HETS Clerks. Used for capturing varying (project by project) metadata needed to process requests related to the project.
/// </summary>
/// <value>Information about the Project needed by the HETS Clerks. Used for capturing varying (project by project) metadata needed to process requests related to the project.</value>
[MetaData (Description = "Information about the Project needed by the HETS Clerks. Used for capturing varying (project by project) metadata needed to process requests related to the project.")]
[MaxLength(2048)]
public string Information { get; set; }
/// <summary>
/// The Rental Requests associated with this Project
/// </summary>
/// <value>The Rental Requests associated with this Project</value>
[MetaData (Description = "The Rental Requests associated with this Project")]
public List<RentalRequest> RentalRequests { get; set; }
/// <summary>
/// The Rental Agreements associated with this Project
/// </summary>
/// <value>The Rental Agreements associated with this Project</value>
[MetaData (Description = "The Rental Agreements associated with this Project")]
public List<RentalAgreement> RentalAgreements { get; set; }
/// <summary>
/// Link to the designated Primary Contact for the Project - usually the Project Manager requesting to hire equipment.
/// </summary>
/// <value>Link to the designated Primary Contact for the Project - usually the Project Manager requesting to hire equipment.</value>
[MetaData (Description = "Link to the designated Primary Contact for the Project - usually the Project Manager requesting to hire equipment.")]
public Contact PrimaryContact { get; set; }
/// <summary>
/// Foreign key for PrimaryContact
/// </summary>
[ForeignKey("PrimaryContact")]
[JsonIgnore]
[MetaData (Description = "Link to the designated Primary Contact for the Project - usually the Project Manager requesting to hire equipment.")]
public int? PrimaryContactId { get; set; }
/// <summary>
/// Gets or Sets Contacts
/// </summary>
public List<Contact> Contacts { get; set; }
/// <summary>
/// Gets or Sets Notes
/// </summary>
public List<Note> Notes { get; set; }
/// <summary>
/// Gets or Sets Attachments
/// </summary>
public List<Attachment> Attachments { get; set; }
/// <summary>
/// Gets or Sets History
/// </summary>
public List<History> History { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Project {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" District: ").Append(District).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" ProvincialProjectNumber: ").Append(ProvincialProjectNumber).Append("\n");
sb.Append(" Information: ").Append(Information).Append("\n");
sb.Append(" RentalRequests: ").Append(RentalRequests).Append("\n");
sb.Append(" RentalAgreements: ").Append(RentalAgreements).Append("\n");
sb.Append(" PrimaryContact: ").Append(PrimaryContact).Append("\n");
sb.Append(" Contacts: ").Append(Contacts).Append("\n");
sb.Append(" Notes: ").Append(Notes).Append("\n");
sb.Append(" Attachments: ").Append(Attachments).Append("\n");
sb.Append(" History: ").Append(History).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (obj is null) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
return obj.GetType() == GetType() && Equals((Project)obj);
}
/// <summary>
/// Returns true if Project instances are equal
/// </summary>
/// <param name="other">Instance of Project to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Project other)
{
if (other is null) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
Id == other.Id ||
Id.Equals(other.Id)
) &&
(
District == other.District ||
District != null &&
District.Equals(other.District)
) &&
(
Name == other.Name ||
Name != null &&
Name.Equals(other.Name)
) &&
(
Status == other.Status ||
Status != null &&
Status.Equals(other.Status)
) &&
(
ProvincialProjectNumber == other.ProvincialProjectNumber ||
ProvincialProjectNumber != null &&
ProvincialProjectNumber.Equals(other.ProvincialProjectNumber)
) &&
(
Information == other.Information ||
Information != null &&
Information.Equals(other.Information)
) &&
(
RentalRequests == other.RentalRequests ||
RentalRequests != null &&
RentalRequests.SequenceEqual(other.RentalRequests)
) &&
(
RentalAgreements == other.RentalAgreements ||
RentalAgreements != null &&
RentalAgreements.SequenceEqual(other.RentalAgreements)
) &&
(
PrimaryContact == other.PrimaryContact ||
PrimaryContact != null &&
PrimaryContact.Equals(other.PrimaryContact)
) &&
(
Contacts == other.Contacts ||
Contacts != null &&
Contacts.SequenceEqual(other.Contacts)
) &&
(
Notes == other.Notes ||
Notes != null &&
Notes.SequenceEqual(other.Notes)
) &&
(
Attachments == other.Attachments ||
Attachments != null &&
Attachments.SequenceEqual(other.Attachments)
) &&
(
History == other.History ||
History != null &&
History.SequenceEqual(other.History)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + Id.GetHashCode();
if (District != null)
{
hash = hash * 59 + District.GetHashCode();
}
if (Name != null)
{
hash = hash * 59 + Name.GetHashCode();
}
if (Status != null)
{
hash = hash * 59 + Status.GetHashCode();
}
if (ProvincialProjectNumber != null)
{
hash = hash * 59 + ProvincialProjectNumber.GetHashCode();
}
if (Information != null)
{
hash = hash * 59 + Information.GetHashCode();
}
if (RentalRequests != null)
{
hash = hash * 59 + RentalRequests.GetHashCode();
}
if (RentalAgreements != null)
{
hash = hash * 59 + RentalAgreements.GetHashCode();
}
if (PrimaryContact != null)
{
hash = hash * 59 + PrimaryContact.GetHashCode();
}
if (Contacts != null)
{
hash = hash * 59 + Contacts.GetHashCode();
}
if (Notes != null)
{
hash = hash * 59 + Notes.GetHashCode();
}
if (Attachments != null)
{
hash = hash * 59 + Attachments.GetHashCode();
}
if (History != null)
{
hash = hash * 59 + History.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(Project left, Project right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(Project left, Project right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Services;
using Umbraco.Web.Models.ContentEditing;
using umbraco;
namespace Umbraco.Web.Models.Mapping
{
/// <summary>
/// Creates the tabs collection with properties assigned for display models
/// </summary>
internal class TabsAndPropertiesResolver : ValueResolver<IContentBase, IEnumerable<Tab<ContentPropertyDisplay>>>
{
private readonly ILocalizedTextService _localizedTextService;
protected IEnumerable<string> IgnoreProperties { get; set; }
public TabsAndPropertiesResolver(ILocalizedTextService localizedTextService)
{
if (localizedTextService == null) throw new ArgumentNullException("localizedTextService");
_localizedTextService = localizedTextService;
IgnoreProperties = new List<string>();
}
public TabsAndPropertiesResolver(ILocalizedTextService localizedTextService, IEnumerable<string> ignoreProperties)
: this(localizedTextService)
{
if (ignoreProperties == null) throw new ArgumentNullException("ignoreProperties");
IgnoreProperties = ignoreProperties;
}
/// <summary>
/// Maps properties on to the generic properties tab
/// </summary>
/// <param name="content"></param>
/// <param name="display"></param>
/// <param name="localizedTextService"></param>
/// <param name="customProperties">
/// Any additional custom properties to assign to the generic properties tab.
/// </param>
/// <param name="onGenericPropertiesMapped"></param>
/// <remarks>
/// The generic properties tab is mapped during AfterMap and is responsible for
/// setting up the properties such as Created date, updated date, template selected, etc...
/// </remarks>
public static void MapGenericProperties<TPersisted>(
TPersisted content,
ContentItemDisplayBase<ContentPropertyDisplay, TPersisted> display,
ILocalizedTextService localizedTextService,
IEnumerable<ContentPropertyDisplay> customProperties = null,
Action<List<ContentPropertyDisplay>> onGenericPropertiesMapped = null)
where TPersisted : IContentBase
{
var genericProps = display.Tabs.Single(x => x.Id == 0);
//store the current props to append to the newly inserted ones
var currProps = genericProps.Properties.ToArray();
var labelEditor = PropertyEditorResolver.Current.GetByAlias(Constants.PropertyEditors.NoEditAlias).ValueEditor.View;
var contentProps = new List<ContentPropertyDisplay>
{
new ContentPropertyDisplay
{
Alias = string.Format("{0}id", Constants.PropertyEditors.InternalGenericPropertiesPrefix),
Label = "Id",
Value = Convert.ToInt32(display.Id).ToInvariantString() + "<br/><small class='muted'>" + display.Key + "</small>",
View = labelEditor
},
new ContentPropertyDisplay
{
Alias = string.Format("{0}creator", Constants.PropertyEditors.InternalGenericPropertiesPrefix),
Label = localizedTextService.Localize("content/createBy"),
Description = localizedTextService.Localize("content/createByDesc"),
Value = display.Owner.Name,
View = labelEditor
},
new ContentPropertyDisplay
{
Alias = string.Format("{0}createdate", Constants.PropertyEditors.InternalGenericPropertiesPrefix),
Label = localizedTextService.Localize("content/createDate"),
Description = localizedTextService.Localize("content/createDateDesc"),
Value = display.CreateDate.ToIsoString(),
View = labelEditor
},
new ContentPropertyDisplay
{
Alias = string.Format("{0}updatedate", Constants.PropertyEditors.InternalGenericPropertiesPrefix),
Label = localizedTextService.Localize("content/updateDate"),
Description = localizedTextService.Localize("content/updateDateDesc"),
Value = display.UpdateDate.ToIsoString(),
View = labelEditor
}
};
if (customProperties != null)
{
//add the custom ones
contentProps.AddRange(customProperties);
}
//now add the user props
contentProps.AddRange(currProps);
//callback
if (onGenericPropertiesMapped != null)
{
onGenericPropertiesMapped(contentProps);
}
//re-assign
genericProps.Properties = contentProps;
}
/// <summary>
/// Adds the container (listview) tab to the document
/// </summary>
/// <typeparam name="TPersisted"></typeparam>
/// <param name="display"></param>
/// <param name="entityType">This must be either 'content' or 'media'</param>
/// <param name="dataTypeService"></param>
/// <param name="localizedTextService"></param>
internal static void AddListView<TPersisted>(TabbedContentItem<ContentPropertyDisplay, TPersisted> display, string entityType, IDataTypeService dataTypeService, ILocalizedTextService localizedTextService)
where TPersisted : IContentBase
{
int dtdId;
var customDtdName = Constants.Conventions.DataTypes.ListViewPrefix + display.ContentTypeAlias;
switch (entityType)
{
case "content":
dtdId = Constants.System.DefaultContentListViewDataTypeId;
break;
case "media":
dtdId = Constants.System.DefaultMediaListViewDataTypeId;
break;
case "member":
dtdId = Constants.System.DefaultMembersListViewDataTypeId;
break;
default:
throw new ArgumentOutOfRangeException("entityType does not match a required value");
}
//first try to get the custom one if there is one
var dt = dataTypeService.GetDataTypeDefinitionByName(customDtdName)
?? dataTypeService.GetDataTypeDefinitionById(dtdId);
if (dt == null)
{
throw new InvalidOperationException("No list view data type was found for this document type, ensure that the default list view data types exists and/or that your custom list view data type exists");
}
var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dt.Id);
var editor = PropertyEditorResolver.Current.GetByAlias(dt.PropertyEditorAlias);
if (editor == null)
{
throw new NullReferenceException("The property editor with alias " + dt.PropertyEditorAlias + " does not exist");
}
var listViewTab = new Tab<ContentPropertyDisplay>();
listViewTab.Alias = Constants.Conventions.PropertyGroups.ListViewGroupName;
listViewTab.Label = localizedTextService.Localize("content/childItems");
listViewTab.Id = 25;
listViewTab.IsActive = true;
var listViewConfig = editor.PreValueEditor.ConvertDbToEditor(editor.DefaultPreValues, preVals);
//add the entity type to the config
listViewConfig["entityType"] = entityType;
var listViewProperties = new List<ContentPropertyDisplay>();
listViewProperties.Add(new ContentPropertyDisplay
{
Alias = string.Format("{0}containerView", Constants.PropertyEditors.InternalGenericPropertiesPrefix),
Label = "",
Value = null,
View = editor.ValueEditor.View,
HideLabel = true,
Config = listViewConfig
});
listViewTab.Properties = listViewProperties;
SetChildItemsTabPosition(display, listViewConfig, listViewTab);
}
private static void SetChildItemsTabPosition<TPersisted>(TabbedContentItem<ContentPropertyDisplay, TPersisted> display,
IDictionary<string, object> listViewConfig,
Tab<ContentPropertyDisplay> listViewTab)
where TPersisted : IContentBase
{
// Find position of tab from config
var tabIndexForChildItems = 0;
if (listViewConfig["displayAtTabNumber"] != null && int.TryParse((string)listViewConfig["displayAtTabNumber"], out tabIndexForChildItems))
{
// Tab position is recorded 1-based but we insert into collection 0-based
tabIndexForChildItems--;
// Ensure within bounds
if (tabIndexForChildItems < 0)
{
tabIndexForChildItems = 0;
}
if (tabIndexForChildItems > display.Tabs.Count())
{
tabIndexForChildItems = display.Tabs.Count();
}
}
// Recreate tab list with child items tab at configured position
var tabs = new List<Tab<ContentPropertyDisplay>>();
tabs.AddRange(display.Tabs);
tabs.Insert(tabIndexForChildItems, listViewTab);
display.Tabs = tabs;
}
protected override IEnumerable<Tab<ContentPropertyDisplay>> ResolveCore(IContentBase content)
{
var tabs = new List<Tab<ContentPropertyDisplay>>();
// add the tabs, for properties that belong to a tab
// need to aggregate the tabs, as content.PropertyGroups contains all the composition tabs,
// and there might be duplicates (content does not work like contentType and there is no
// content.CompositionPropertyGroups).
var groupsGroupsByName = content.PropertyGroups.OrderBy(x => x.SortOrder).GroupBy(x => x.Name);
foreach (var groupsByName in groupsGroupsByName)
{
var properties = new List<ContentPropertyDisplay>();
// merge properties for groups with the same name
foreach (var group in groupsByName)
{
var groupProperties = content.GetPropertiesForGroup(group)
.Where(x => IgnoreProperties.Contains(x.Alias) == false); // skip ignored
properties.AddRange(Mapper.Map<IEnumerable<Property>, IEnumerable<ContentPropertyDisplay>>(groupProperties));
}
if (properties.Count == 0)
continue;
TranslateProperties(properties);
// add the tab
// we need to pick an identifier... there is no "right" way...
var g = groupsByName.FirstOrDefault(x => x.Id == content.ContentTypeId) // try local
?? groupsByName.First(); // else pick one randomly
var groupId = g.Id;
var groupName = groupsByName.Key;
tabs.Add(new Tab<ContentPropertyDisplay>
{
Id = groupId,
Alias = groupName,
Label = _localizedTextService.UmbracoDictionaryTranslate(groupName),
Properties = properties,
IsActive = false
});
}
// add the generic properties tab, for properties that don't belong to a tab
// get the properties, map and translate them, then add the tab
var noGroupProperties = content.GetNonGroupedProperties()
.Where(x => IgnoreProperties.Contains(x.Alias) == false); // skip ignored
var genericproperties = Mapper.Map<IEnumerable<Property>, IEnumerable<ContentPropertyDisplay>>(noGroupProperties).ToList();
TranslateProperties(genericproperties);
tabs.Add(new Tab<ContentPropertyDisplay>
{
Id = 0,
Label = _localizedTextService.Localize("general/properties"),
Alias = "Generic properties",
Properties = genericproperties
});
// activate the first tab
tabs.First().IsActive = true;
return tabs;
}
private void TranslateProperties(IEnumerable<ContentPropertyDisplay> properties)
{
// Not sure whether it's a good idea to add this to the ContentPropertyDisplay mapper
foreach (var prop in properties)
{
prop.Label = _localizedTextService.UmbracoDictionaryTranslate(prop.Label);
prop.Description = _localizedTextService.UmbracoDictionaryTranslate(prop.Description);
}
}
}
}
| |
// The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei [email protected]
//
// 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 SLua
{
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Linq;
public class ObjectCache
{
static Dictionary<IntPtr, ObjectCache> multiState = new Dictionary<IntPtr, ObjectCache>();
static IntPtr oldl = IntPtr.Zero;
static internal ObjectCache oldoc = null;
#if SLUA_DEBUG || UNITY_EDITOR
public static List<string> GetAllManagedObjectNames(){
List<string> names = new List<string>();
foreach(var cache in multiState.Values){
foreach(var o in cache.objMap.Keys){
names.Add(cache.objNameDebugs[o]);
}
}
return names;
}
public static List<string> GetAlreadyDestroyedObjectNames(){
List<string> names = new List<string>();
foreach(var cache in multiState.Values){
foreach(var o in cache.objMap.Keys){
if(o is Object &&(o as Object).Equals(null)){
names.Add(cache.objNameDebugs[o]);
}
}
}
return names;
}
#endif
public static ObjectCache get(IntPtr l)
{
if (oldl == l)
return oldoc;
ObjectCache oc;
if (multiState.TryGetValue(l, out oc))
{
oldl = l;
oldoc = oc;
return oc;
}
LuaDLL.lua_getglobal(l, "__main_state");
if (LuaDLL.lua_isnil(l, -1))
{
LuaDLL.lua_pop(l, 1);
return null;
}
IntPtr nl = LuaDLL.lua_touserdata(l, -1);
LuaDLL.lua_pop(l, 1);
if (nl != l)
return get(nl);
return null;
}
class FreeList : Dictionary<int, object>
{
private int id = 1;
public int add(object o)
{
Add(id, o);
return id++;
}
public void del(int i)
{
this.Remove(i);
}
public bool get(int i, out object o)
{
return TryGetValue(i, out o);
}
public object get(int i)
{
object o;
if (TryGetValue(i, out o))
return o;
return null;
}
public void set(int i, object o)
{
this[i] = o;
}
}
FreeList cache = new FreeList();
public class ObjEqualityComparer : IEqualityComparer<object>
{
public new bool Equals(object x, object y)
{
return ReferenceEquals(x, y);
}
public int GetHashCode(object obj)
{
return RuntimeHelpers.GetHashCode(obj);
}
}
Dictionary<object, int> objMap = new Dictionary<object, int>(new ObjEqualityComparer());
public Dictionary<object, int>.KeyCollection Objs { get { return objMap.Keys; } }
#if SLUA_DEBUG || UNITY_EDITOR
Dictionary<object,string> objNameDebugs = new Dictionary<object, string>(new ObjEqualityComparer());
private static string getDebugFullName(UnityEngine.Transform transform){
if (transform.parent == null) {
return transform.gameObject.ToString();
}
return getDebugName (transform.parent) + "/" + transform.name;
}
private static string getDebugName(object o ){
if (o is UnityEngine.GameObject) {
var go = o as UnityEngine.GameObject;
return getDebugFullName (go.transform);
} else if (o is UnityEngine.Component) {
var comp = o as UnityEngine.Component;
return getDebugFullName (comp.transform);
}
return o.ToString ();
}
#endif
int udCacheRef = 0;
public ObjectCache(IntPtr l)
{
LuaDLL.lua_newtable(l);
LuaDLL.lua_newtable(l);
LuaDLL.lua_pushstring(l, "v");
LuaDLL.lua_setfield(l, -2, "__mode");
LuaDLL.lua_setmetatable(l, -2);
udCacheRef = LuaDLL.luaL_ref(l, LuaIndexes.LUA_REGISTRYINDEX);
}
static public void clear()
{
oldl = IntPtr.Zero;
oldoc = null;
}
internal static void del(IntPtr l)
{
multiState.Remove(l);
}
internal static void make(IntPtr l)
{
ObjectCache oc = new ObjectCache(l);
multiState[l] = oc;
oldl = l;
oldoc = oc;
}
public int size()
{
return objMap.Count;
}
internal void gc(int index)
{
object o;
if (cache.get(index, out o))
{
int oldindex;
if (isGcObject(o) && objMap.TryGetValue(o,out oldindex) && oldindex==index)
{
objMap.Remove(o);
#if SLUA_DEBUG || UNITY_EDITOR
objNameDebugs.Remove(o);
#endif
}
cache.del(index);
}
}
#if !SLUA_STANDALONE
internal void gc(UnityEngine.Object o)
{
int index;
if(objMap.TryGetValue(o, out index))
{
objMap.Remove(o);
cache.del(index);
#if SLUA_DEBUG || UNITY_EDITOR
objNameDebugs.Remove(o);
#endif
}
}
#endif
internal int add(object o)
{
int objIndex = cache.add(o);
if (isGcObject(o))
{
objMap[o] = objIndex;
#if SLUA_DEBUG || UNITY_EDITOR
objNameDebugs[o] = getDebugName(o);
#endif
}
return objIndex;
}
internal void destoryObject(IntPtr l, int p) {
int index = LuaDLL.luaS_rawnetobj(l, p);
gc(index);
}
internal object get(IntPtr l, int p)
{
int index = LuaDLL.luaS_rawnetobj(l, p);
object o;
if (index != -1 && cache.get(index, out o))
{
return o;
}
return null;
}
internal void setBack(IntPtr l, int p, object o)
{
int index = LuaDLL.luaS_rawnetobj(l, p);
if (index != -1)
{
cache.set(index, o);
}
}
internal void push(IntPtr l, object o)
{
push(l, o, true);
}
internal void push(IntPtr l, Array o)
{
int index = allocID (l, o);
if (index < 0)
return;
LuaDLL.luaS_pushobject(l, index, "LuaArray", true, udCacheRef);
}
internal int allocID(IntPtr l,object o) {
int index = -1;
if (o == null)
{
LuaDLL.lua_pushnil(l);
return index;
}
bool gco = isGcObject(o);
bool found = gco && objMap.TryGetValue(o, out index);
if (found)
{
if (LuaDLL.luaS_getcacheud(l, index, udCacheRef) == 1)
return -1;
}
index = add(o);
return index;
}
internal void pushInterface(IntPtr l, object o, Type t)
{
int index = allocID(l, o);
if (index < 0)
return;
LuaDLL.luaS_pushobject(l, index, getAQName(t), true, udCacheRef);
}
internal void push(IntPtr l, object o, bool checkReflect)
{
int index = allocID (l, o);
if (index < 0)
return;
bool gco = isGcObject(o);
#if SLUA_CHECK_REFLECTION
int isReflect = LuaDLL.luaS_pushobject(l, index, getAQName(o), gco, udCacheRef);
if (isReflect != 0 && checkReflect && !(o is LuaClassObject))
{
Logger.LogWarning(string.Format("{0} not exported, using reflection instead", o.ToString()));
}
#else
LuaDLL.luaS_pushobject(l, index, getAQName(o), gco, udCacheRef);
#endif
}
static Dictionary<Type, string> aqnameMap = new Dictionary<Type, string>();
static string getAQName(object o)
{
Type t = o.GetType();
return getAQName(t);
}
internal static string getAQName(Type t)
{
string name;
if (aqnameMap.TryGetValue(t, out name))
{
return name;
}
name = t.AssemblyQualifiedName;
aqnameMap[t] = name;
return name;
}
bool isGcObject(object obj)
{
return obj.GetType().IsValueType == false;
}
public bool isObjInLua(object obj)
{
return objMap.ContainsKey(obj);
}
// find type in current domain
static Type getTypeInGlobal(string name) {
Type t = Type.GetType(name);
if (t!=null) return t;
Assembly[] ams = AppDomain.CurrentDomain.GetAssemblies();
for (int n = 0; n < ams.Length; n++)
{
Assembly a = ams[n];
Type[] ts = null;
try
{
ts = a.GetExportedTypes();
for (int k = 0; k < ts.Length; k++)
{
t = ts[k];
if (t.Name == name)
return t;
}
}
catch
{
continue;
}
}
return null;
}
static Type typeofLD;
WeakDictionary<Type, MethodInfo> methodCache = new WeakDictionary<Type, MethodInfo>();
internal MethodInfo getDelegateMethod(Type t) {
MethodInfo mi;
if (methodCache.TryGetValue(t, out mi))
return mi;
if (typeofLD == null)
typeofLD = getTypeInGlobal("LuaDelegation");
if (typeofLD == null) return null;
MethodInfo[] mis = typeofLD.GetMethods(BindingFlags.Static|BindingFlags.NonPublic);
for (int n = 0; n < mis.Length;n++) {
mi = mis[n];
if (isMethodCompatibleWithDelegate(mi, t))
{
methodCache.Add(t,mi);
return mi;
}
}
return null;
}
static bool isMethodCompatibleWithDelegate(MethodInfo target,Type dt)
{
MethodInfo ds = dt.GetMethod("Invoke");
bool parametersEqual = ds
.GetParameters()
.Select(x => x.ParameterType)
.SequenceEqual(target.GetParameters().Skip(1)
.Select(x => x.ParameterType));
return ds.ReturnType == target.ReturnType &&
parametersEqual;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using Dbg = System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// A command that adds the parent and child parts of a path together
/// with the appropriate path separator.
/// </summary>
[Cmdlet(VerbsCommon.Join, "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096811")]
[OutputType(typeof(string))]
public class JoinPathCommand : CoreCommandWithCredentialsBase
{
#region Parameters
/// <summary>
/// Gets or sets the path parameter to the command.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[Alias("PSPath")]
public string[] Path { get; set; }
/// <summary>
/// Gets or sets the childPath parameter to the command.
/// </summary>
[Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)]
[AllowNull]
[AllowEmptyString]
public string ChildPath { get; set; }
/// <summary>
/// Gets or sets additional childPaths to the command.
/// </summary>
[Parameter(Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromRemainingArguments = true)]
[AllowNull]
[AllowEmptyString]
[AllowEmptyCollection]
public string[] AdditionalChildPath { get; set; } = Array.Empty<string>();
/// <summary>
/// Determines if the path should be resolved after being joined.
/// </summary>
/// <value></value>
[Parameter]
public SwitchParameter Resolve { get; set; }
#endregion Parameters
#region Command code
/// <summary>
/// Parses the specified path and returns the portion determined by the
/// boolean parameters.
/// </summary>
protected override void ProcessRecord()
{
Dbg.Diagnostics.Assert(
Path != null,
"Since Path is a mandatory parameter, paths should never be null");
string combinedChildPath = ChildPath;
// join the ChildPath elements
if (AdditionalChildPath != null)
{
foreach (string childPath in AdditionalChildPath)
{
combinedChildPath = SessionState.Path.Combine(combinedChildPath, childPath, CmdletProviderContext);
}
}
foreach (string path in Path)
{
// First join the path elements
string joinedPath = null;
try
{
joinedPath =
SessionState.Path.Combine(path, combinedChildPath, CmdletProviderContext);
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
continue;
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
continue;
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
continue;
}
catch (ItemNotFoundException pathNotFound)
{
WriteError(
new ErrorRecord(
pathNotFound.ErrorRecord,
pathNotFound));
continue;
}
if (Resolve)
{
// Resolve the paths. The default API (GetResolvedPSPathFromPSPath)
// does not allow non-existing paths.
Collection<PathInfo> resolvedPaths = null;
try
{
resolvedPaths =
SessionState.Path.GetResolvedPSPathFromPSPath(joinedPath, CmdletProviderContext);
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
continue;
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
continue;
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
continue;
}
catch (ItemNotFoundException pathNotFound)
{
WriteError(
new ErrorRecord(
pathNotFound.ErrorRecord,
pathNotFound));
continue;
}
for (int index = 0; index < resolvedPaths.Count; ++index)
{
try
{
if (resolvedPaths[index] != null)
{
WriteObject(resolvedPaths[index].Path);
}
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
continue;
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
continue;
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
continue;
}
catch (ItemNotFoundException pathNotFound)
{
WriteError(
new ErrorRecord(
pathNotFound.ErrorRecord,
pathNotFound));
continue;
}
}
}
else
{
if (joinedPath != null)
{
WriteObject(joinedPath);
}
}
}
}
#endregion Command code
}
}
| |
using System;
using System.IO;
using NUnit.Framework;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.IO;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Asn1.Tests
{
[TestFixture]
public class CmsTest
: ITest
{
//
// compressed data object
//
private static readonly byte[] compData = Base64.Decode(
"MIAGCyqGSIb3DQEJEAEJoIAwgAIBADANBgsqhkiG9w0BCRADCDCABgkqhkiG9w0BBwGggCSABIIC"
+ "Hnic7ZRdb9owFIbvK/k/5PqVYPFXGK12YYyboVFASSp1vQtZGiLRACZE49/XHoUW7S/0tXP8Efux"
+ "fU5ivWnasml72XFb3gb5druui7ytN803M570nii7C5r8tfwR281hy/p/KSM3+jzH5s3+pbQ90xSb"
+ "P3VT3QbLusnt8WPIuN5vN/vaA2+DulnXTXkXvNTr8j8ouZmkCmGI/UW+ZS/C8zP0bz2dz0zwLt+1"
+ "UEk2M8mlaxjRMByAhZTj0RGYg4TvogiRASROsZgjpVcJCb1KV6QzQeDJ1XkoQ5Jm+C5PbOHZZGRi"
+ "v+ORAcshOGeCcdFJyfgFxdtCdEcmOrbinc/+BBMzRThEYpwl+jEBpciSGWQkI0TSlREmD/eOHb2D"
+ "SGLuESm/iKUFt1y4XHBO2a5oq0IKJKWLS9kUZTA7vC5LSxYmgVL46SIWxIfWBQd6AdrnjLmH94UT"
+ "vGxVibLqRCtIpp4g2qpdtqK1LiOeolpVK5wVQ5P7+QjZAlrh0cePYTx/gNZuB9Vhndtgujl9T/tg"
+ "W9ogK+3rnmg3YWygnTuF5GDS+Q/jIVLnCcYZFc6Kk/+c80wKwZjwdZIqDYWRH68MuBQSXLgXYXj2"
+ "3CAaYOBNJMliTl0X7eV5DnoKIFSKYdj3cRpD/cK/JWTHJRe76MUXnfBW8m7Hd5zhQ4ri2NrVF/WL"
+ "+kV1/3AGSlJ32bFPd2BsQD8uSzIx6lObkjdz95c0AAAAAAAAAAAAAAAA");
//
// enveloped data
//
private static readonly byte[] envDataKeyTrns = Base64.Decode(
"MIAGCSqGSIb3DQEHA6CAMIACAQAxgcQwgcECAQAwKjAlMRYwFAYDVQQKEw1Cb3Vu"
+ "Y3kgQ2FzdGxlMQswCQYDVQQGEwJBVQIBCjANBgkqhkiG9w0BAQEFAASBgC5vdGrB"
+ "itQSGwifLf3KwPILjaB4WEXgT/IIO1KDzrsbItCJsMA0Smq2y0zptxT0pSRL6JRg"
+ "NMxLk1ySnrIrvGiEPLMR1zjxlT8yQ6VLX+kEoK43ztd1aaLw0oBfrcXcLN7BEpZ1"
+ "TIdjlBfXIOx1S88WY1MiYqJJFc3LMwRUaTEDMIAGCSqGSIb3DQEHATAdBglghkgB"
+ "ZQMEARYEEAfxLMWeaBOTTZQwUq0Y5FuggAQgwOJhL04rjSZCBCSOv5i5XpFfGsOd"
+ "YSHSqwntGpFqCx4AAAAAAAAAAAAA");
private static readonly byte[] envDataKEK = Base64.Decode(
"MIAGCSqGSIb3DQEHA6CAMIACAQIxUqJQAgEEMAcEBQECAwQFMBAGCyqGSIb3DQEJE"
+ "AMHAgE6BDC7G/HyUPilIrin2Yeajqmj795VoLWETRnZAAFcAiQdoQWyz+oCh6WY/H"
+ "jHHi+0y+cwgAYJKoZIhvcNAQcBMBQGCCqGSIb3DQMHBAiY3eDBBbF6naCABBiNdzJb"
+ "/v6+UZB3XXKipxFDUpz9GyjzB+gAAAAAAAAAAAAA");
private static readonly byte[] envDataNestedNDEF = Base64.Decode(
"MIAGCSqGSIb3DQEHA6CAMIACAQAxge8wgewCAQAwgZUwgY8xKDAmBgNVBAoMH1RoZSBMZWdpb24g"
+ "b2YgdGhlIEJvdW5jeSBDYXN0bGUxLzAtBgkqhkiG9w0BCQEWIGZlZWRiYWNrLWNyeXB0b0Bib3Vu"
+ "Y3ljYXN0bGUub3JnMREwDwYDVQQIDAhWaWN0b3JpYTESMBAGA1UEBwwJTWVsYm91cm5lMQswCQYD"
+ "VQQGEwJBVQIBATANBgkqhkiG9w0BAQEFAARABIXMd8xiTyWDKO/LQfvdGYTPW3I9oSQWwtm4OIaN"
+ "VINpfY2lfwTvbmE6VXiLKeALC0dMBV8z7DEM9hE0HVmvLDCABgkqhkiG9w0BBwEwHQYJYIZIAWUD"
+ "BAECBBB32ko6WrVxDTqwUYEpV6IUoIAEggKgS6RowrhNlmWWI13zxD/lryxkZ5oWXPUfNiUxYX/P"
+ "r5iscW3s8VKJKUpJ4W5SNA7JGL4l/5LmSnJ4Qu/xzxcoH4r4vmt75EDE9p2Ob2Xi1NuSFAZubJFc"
+ "Zlnp4e05UHKikmoaz0PbiAi277sLQlK2FcVsntTYVT00y8+IwuuQu0ATVqkXC+VhfjV/sK6vQZnw"
+ "2rQKedZhLB7B4dUkmxCujb/UAq4lgSpLMXg2P6wMimTczXyQxRiZxPeI4ByCENjkafXbfcJft2eD"
+ "gv1DEDdYM5WrW9Z75b4lmJiOJ/xxDniHCvum7KGXzpK1d1mqTlpzPC2xoz08/MO4lRf5Mb0bYdq6"
+ "CjMaYqVwGsYryp/2ayX+d8H+JphEG+V9Eg8uPcDoibwhDI4KkoyGHstPw5bxcy7vVFt7LXUdNjJc"
+ "K1wxaUKEXDGKt9Vj93FnBTLMX0Pc9HpueV5o1ipX34dn/P3HZB9XK8ScbrE38B1VnIgylStnhVFO"
+ "Cj9s7qSVqI2L+xYHJRHsxaMumIRnmRuOqdXDfIo28EZAnFtQ/b9BziMGVvAW5+A8h8s2oazhSmK2"
+ "23ftV7uv98ScgE8fCd3PwT1kKJM83ThTYyBzokvMfPYCCvsonMV+kTWXhWcwjYTS4ukrpR452ZdW"
+ "l3aJqDnzobt5FK4T8OGciOj+1PxYFZyRmCuafm2Dx6o7Et2Tu/T5HYvhdY9jHyqtDl2PXH4CTnVi"
+ "gA1YOAArjPVmsZVwAM3Ml46uyXXhcsXwQ1X0Tv4D+PSa/id4UQ2cObOw8Cj1eW2GB8iJIZVqkZaU"
+ "XBexqgWYOIoxjqODSeoZKiBsTK3c+oOUBqBDueY1i55swE2o6dDt95FluX6iyr/q4w2wLt3upY1J"
+ "YL+TuvZxAKviuAczMS1bAAAAAAAAAAAAAA==");
//
// signed data
//
private static readonly byte[] signedData = Base64.Decode(
"MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAaCA"
+ "JIAEDEhlbGxvIFdvcmxkIQAAAAAAAKCCBGIwggINMIIBdqADAgECAgEBMA0GCSqG"
+ "SIb3DQEBBAUAMCUxFjAUBgNVBAoTDUJvdW5jeSBDYXN0bGUxCzAJBgNVBAYTAkFV"
+ "MB4XDTA0MTAyNDA0MzA1OFoXDTA1MDIwMTA0MzA1OFowJTEWMBQGA1UEChMNQm91"
+ "bmN5IENhc3RsZTELMAkGA1UEBhMCQVUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ"
+ "AoGBAJj3OAshAOgDmPcYZ1jdNSuhOHRH9VhC/PG17FdiInVGc2ulJhEifEQga/uq"
+ "ZCpSd1nHsJUZKm9k1bVneWzC0941i9Znfxgb2jnXXsa5kwB2KEVESrOWsRjSRtnY"
+ "iLgqBG0rzpaMn5A5ntu7N0406EesBhe19cjZAageEHGZDbufAgMBAAGjTTBLMB0G"
+ "A1UdDgQWBBR/iHNKOo6f4ByWFFywRNZ65XSr1jAfBgNVHSMEGDAWgBR/iHNKOo6f"
+ "4ByWFFywRNZ65XSr1jAJBgNVHRMEAjAAMA0GCSqGSIb3DQEBBAUAA4GBAFMJJ7QO"
+ "pHo30bnlQ4Ny3PCnK+Se+Gw3TpaYGp84+a8fGD9Dme78G6NEsgvpFGTyoLxvJ4CB"
+ "84Kzys+1p2HdXzoZiyXAer5S4IwptE3TxxFwKyj28cRrM6dK47DDyXUkV0qwBAMN"
+ "luwnk/no4K7ilzN2MZk5l7wXyNa9yJ6CHW6dMIICTTCCAbagAwIBAgIBAjANBgkq"
+ "hkiG9w0BAQQFADAlMRYwFAYDVQQKEw1Cb3VuY3kgQ2FzdGxlMQswCQYDVQQGEwJB"
+ "VTAeFw0wNDEwMjQwNDMwNTlaFw0wNTAyMDEwNDMwNTlaMGUxGDAWBgNVBAMTD0Vy"
+ "aWMgSC4gRWNoaWRuYTEkMCIGCSqGSIb3DQEJARYVZXJpY0Bib3VuY3ljYXN0bGUu"
+ "b3JnMRYwFAYDVQQKEw1Cb3VuY3kgQ2FzdGxlMQswCQYDVQQGEwJBVTCBnzANBgkq"
+ "hkiG9w0BAQEFAAOBjQAwgYkCgYEAm+5CnGU6W45iUpCsaGkn5gDruZv3j/o7N6ag"
+ "mRZhikaLG2JF6ECaX13iioVJfmzBsPKxAACWwuTXCoSSXG8viK/qpSHwJpfQHYEh"
+ "tcC0CxIqlnltv3KQAGwh/PdwpSPvSNnkQBGvtFq++9gnXDBbynfP8b2L2Eis0X9U"
+ "2y6gFiMCAwEAAaNNMEswHQYDVR0OBBYEFEAmOksnF66FoQm6IQBVN66vJo1TMB8G"
+ "A1UdIwQYMBaAFH+Ic0o6jp/gHJYUXLBE1nrldKvWMAkGA1UdEwQCMAAwDQYJKoZI"
+ "hvcNAQEEBQADgYEAEeIjvNkKMPU/ZYCu1TqjGZPEqi+glntg2hC/CF0oGyHFpMuG"
+ "tMepF3puW+uzKM1s61ar3ahidp3XFhr/GEU/XxK24AolI3yFgxP8PRgUWmQizTQX"
+ "pWUmhlsBe1uIKVEfNAzCgtYfJQ8HJIKsUCcdWeCKVKs4jRionsek1rozkPExggEv"
+ "MIIBKwIBATAqMCUxFjAUBgNVBAoTDUJvdW5jeSBDYXN0bGUxCzAJBgNVBAYTAkFV"
+ "AgECMAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqG"
+ "SIb3DQEJBTEPFw0wNDEwMjQwNDMwNTlaMCMGCSqGSIb3DQEJBDEWBBQu973mCM5U"
+ "BOl9XwQvlfifHCMocTANBgkqhkiG9w0BAQEFAASBgGHbe3/jcZu6b/erRhc3PEji"
+ "MUO8mEIRiNYBr5/vFNhkry8TrGfOpI45m7gu1MS0/vdas7ykvidl/sNZfO0GphEI"
+ "UaIjMRT3U6yuTWF4aLpatJbbRsIepJO/B2kdIAbV5SCbZgVDJIPOR2qnruHN2wLF"
+ "a+fEv4J8wQ8Xwvk0C8iMAAAAAAAA");
private static void Touch(object o)
{
}
private ITestResult CompressionTest()
{
try
{
ContentInfo info = ContentInfo.GetInstance(
Asn1Object.FromByteArray(compData));
CompressedData data = CompressedData.GetInstance(info.Content);
data = new CompressedData(data.CompressionAlgorithmIdentifier, data.EncapContentInfo);
info = new ContentInfo(CmsObjectIdentifiers.CompressedData, data);
if (!Arrays.AreEqual(info.GetEncoded(), compData))
{
return new SimpleTestResult(false, Name + ": CMS compression failed to re-encode");
}
return new SimpleTestResult(true, Name + ": Okay");
}
catch (Exception e)
{
return new SimpleTestResult(false, Name + ": CMS compression failed - " + e.ToString(), e);
}
}
private ITestResult EnvelopedTest()
{
try
{
// Key trans
ContentInfo info = ContentInfo.GetInstance(
Asn1Object.FromByteArray(envDataKeyTrns));
EnvelopedData envData = EnvelopedData.GetInstance(info.Content);
Asn1Set s = envData.RecipientInfos;
if (s.Count != 1)
{
return new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped, wrong number of recipients");
}
RecipientInfo recip = RecipientInfo.GetInstance(s[0]);
if (recip.Info is KeyTransRecipientInfo)
{
KeyTransRecipientInfo inf = KeyTransRecipientInfo.GetInstance(recip.Info);
inf = new KeyTransRecipientInfo(inf.RecipientIdentifier, inf.KeyEncryptionAlgorithm, inf.EncryptedKey);
s = new DerSet(new RecipientInfo(inf));
}
else
{
return new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped, wrong recipient type");
}
envData = new EnvelopedData(envData.OriginatorInfo, s, envData.EncryptedContentInfo, envData.UnprotectedAttrs);
info = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, envData);
if (!Arrays.AreEqual(info.GetEncoded(), envDataKeyTrns))
{
return new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped failed to re-encode");
}
// KEK
info = ContentInfo.GetInstance(
Asn1Object.FromByteArray(envDataKEK));
envData = EnvelopedData.GetInstance(info.Content);
s = envData.RecipientInfos;
if (s.Count != 1)
{
return new SimpleTestResult(false, Name + ": CMS KEK enveloped, wrong number of recipients");
}
recip = RecipientInfo.GetInstance(s[0]);
if (recip.Info is KekRecipientInfo)
{
KekRecipientInfo inf = KekRecipientInfo.GetInstance(recip.Info);
inf = new KekRecipientInfo(inf.KekID, inf.KeyEncryptionAlgorithm, inf.EncryptedKey);
s = new DerSet(new RecipientInfo(inf));
}
else
{
return new SimpleTestResult(false, Name + ": CMS KEK enveloped, wrong recipient type");
}
envData = new EnvelopedData(envData.OriginatorInfo, s, envData.EncryptedContentInfo, envData.UnprotectedAttrs);
info = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, envData);
if (!Arrays.AreEqual(info.GetEncoded(), envDataKEK))
{
return new SimpleTestResult(false, Name + ": CMS KEK enveloped failed to re-encode");
}
// Nested NDEF problem
Asn1StreamParser asn1In = new Asn1StreamParser(new MemoryStream(envDataNestedNDEF, false));
ContentInfoParser ci = new ContentInfoParser((Asn1SequenceParser)asn1In.ReadObject());
EnvelopedDataParser ed = new EnvelopedDataParser((Asn1SequenceParser)ci
.GetContent(Asn1Tags.Sequence));
Touch(ed.Version);
ed.GetOriginatorInfo();
ed.GetRecipientInfos().ToAsn1Object();
EncryptedContentInfoParser eci = ed.GetEncryptedContentInfo();
Touch(eci.ContentType);
Touch(eci.ContentEncryptionAlgorithm);
Stream dataIn = ((Asn1OctetStringParser)eci.GetEncryptedContent(Asn1Tags.OctetString))
.GetOctetStream();
Streams.Drain(dataIn);
dataIn.Close();
// Test data doesn't have unprotected attrs, bug was being thrown by this call
Asn1SetParser upa = ed.GetUnprotectedAttrs();
if (upa != null)
{
upa.ToAsn1Object();
}
return new SimpleTestResult(true, Name + ": Okay");
}
catch (Exception e)
{
return new SimpleTestResult(false, Name + ": CMS enveloped failed - " + e.ToString(), e);
}
}
private ITestResult SignedTest()
{
try
{
ContentInfo info = ContentInfo.GetInstance(
Asn1Object.FromByteArray(signedData));
SignedData sData = SignedData.GetInstance(info.Content);
sData = new SignedData(sData.DigestAlgorithms, sData.EncapContentInfo, sData.Certificates, sData.CRLs, sData.SignerInfos);
info = new ContentInfo(CmsObjectIdentifiers.SignedData, sData);
if (!Arrays.AreEqual(info.GetEncoded(), signedData))
{
return new SimpleTestResult(false, Name + ": CMS signed failed to re-encode");
}
return new SimpleTestResult(true, Name + ": Okay");
}
catch (Exception e)
{
return new SimpleTestResult(false, Name + ": CMS signed failed - " + e.ToString(), e);
}
}
public ITestResult Perform()
{
ITestResult res = CompressionTest();
if (!res.IsSuccessful())
{
return res;
}
res = EnvelopedTest();
if (!res.IsSuccessful())
{
return res;
}
return SignedTest();
}
public string Name
{
get { return "CMS"; }
}
public static void Main(
string[] args)
{
ITest test = new CmsTest();
ITestResult result = test.Perform();
Console.WriteLine(result);
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
using System;
using System.IO;
using System.Collections;
namespace DesignScript.Editor.Core {
public class Token {
public int kind; // token kind
public int pos; // token position in bytes in the source text (starting at 0)
public int charPos; // token position in characters in the source text (starting at 0)
public int col; // token column (starting at 1)
public int line; // token line (starting at 1)
public string val; // token value
public Token next; // ML 2005-03-11 Tokens are kept in linked list
}
//-----------------------------------------------------------------------------------
// Buffer
//-----------------------------------------------------------------------------------
public class Buffer {
// This Buffer supports the following cases:
// 1) seekable stream (file)
// a) whole stream in buffer
// b) part of stream in buffer
// 2) non seekable stream (network, console)
public const int EOF = char.MaxValue + 1;
const int MIN_BUFFER_LENGTH = 1024; // 1KB
const int MAX_BUFFER_LENGTH = MIN_BUFFER_LENGTH * 64; // 64KB
byte[] buf; // input buffer
int bufStart; // position of first byte in buffer relative to input stream
int bufLen; // length of buffer
int fileLen; // length of input stream (may change if the stream is no file)
int bufPos; // current position in buffer
Stream stream; // input stream (seekable)
bool isUserStream; // was the stream opened by the user?
public Buffer (Stream s, bool isUserStream) {
stream = s; this.isUserStream = isUserStream;
if (stream.CanSeek) {
fileLen = (int) stream.Length;
bufLen = Math.Min(fileLen, MAX_BUFFER_LENGTH);
bufStart = Int32.MaxValue; // nothing in the buffer so far
} else {
fileLen = bufLen = bufStart = 0;
}
buf = new byte[(bufLen>0) ? bufLen : MIN_BUFFER_LENGTH];
if (fileLen > 0) Pos = 0; // setup buffer to position 0 (start)
else bufPos = 0; // index 0 is already after the file, thus Pos = 0 is invalid
if (bufLen == fileLen && stream.CanSeek) Close();
}
protected Buffer(Buffer b) { // called in UTF8Buffer constructor
buf = b.buf;
bufStart = b.bufStart;
bufLen = b.bufLen;
fileLen = b.fileLen;
bufPos = b.bufPos;
stream = b.stream;
// keep destructor from closing the stream
b.stream = null;
isUserStream = b.isUserStream;
}
~Buffer() { Close(); }
protected void Close() {
if (!isUserStream && stream != null) {
stream.Close();
stream = null;
}
}
public virtual int Read () {
if (bufPos < bufLen) {
return buf[bufPos++];
} else if (Pos < fileLen) {
Pos = Pos; // shift buffer start to Pos
return buf[bufPos++];
} else if (stream != null && !stream.CanSeek && ReadNextStreamChunk() > 0) {
return buf[bufPos++];
} else {
return EOF;
}
}
public int Peek () {
int curPos = Pos;
int ch = Read();
Pos = curPos;
return ch;
}
// beg .. begin, zero-based, inclusive, in byte
// end .. end, zero-based, exclusive, in byte
public string GetString (int beg, int end) {
int len = 0;
char[] buf = new char[end - beg];
int oldPos = Pos;
Pos = beg;
while (Pos < end) buf[len++] = (char) Read();
Pos = oldPos;
return new String(buf, 0, len);
}
public int Pos {
get { return bufPos + bufStart; }
set {
if (value >= fileLen && stream != null && !stream.CanSeek) {
// Wanted position is after buffer and the stream
// is not seek-able e.g. network or console,
// thus we have to read the stream manually till
// the wanted position is in sight.
while (value >= fileLen && ReadNextStreamChunk() > 0);
}
if (value < 0 || value > fileLen) {
throw new FatalError("buffer out of bounds access, position: " + value);
}
if (value >= bufStart && value < bufStart + bufLen) { // already in buffer
bufPos = value - bufStart;
} else if (stream != null) { // must be swapped in
stream.Seek(value, SeekOrigin.Begin);
bufLen = stream.Read(buf, 0, buf.Length);
bufStart = value; bufPos = 0;
} else {
// set the position to the end of the file, Pos will return fileLen.
bufPos = fileLen - bufStart;
}
}
}
// Read the next chunk of bytes from the stream, increases the buffer
// if needed and updates the fields fileLen and bufLen.
// Returns the number of bytes read.
private int ReadNextStreamChunk() {
int free = buf.Length - bufLen;
if (free == 0) {
// in the case of a growing input stream
// we can neither seek in the stream, nor can we
// foresee the maximum length, thus we must adapt
// the buffer size on demand.
byte[] newBuf = new byte[bufLen * 2];
Array.Copy(buf, newBuf, bufLen);
buf = newBuf;
free = bufLen;
}
int read = stream.Read(buf, bufLen, free);
if (read > 0) {
fileLen = bufLen = (bufLen + read);
return read;
}
// end of stream reached
return 0;
}
}
//-----------------------------------------------------------------------------------
// UTF8Buffer
//-----------------------------------------------------------------------------------
public class UTF8Buffer: Buffer {
public UTF8Buffer(Buffer b): base(b) {}
public override int Read() {
int ch;
do {
ch = base.Read();
// until we find a utf8 start (0xxxxxxx or 11xxxxxx)
} while ((ch >= 128) && ((ch & 0xC0) != 0xC0) && (ch != EOF));
if (ch < 128 || ch == EOF) {
// nothing to do, first 127 chars are the same in ascii and utf8
// 0xxxxxxx or end of file character
} else if ((ch & 0xF0) == 0xF0) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x07; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F; ch = base.Read();
int c4 = ch & 0x3F;
ch = (((((c1 << 6) | c2) << 6) | c3) << 6) | c4;
} else if ((ch & 0xE0) == 0xE0) {
// 1110xxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x0F; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F;
ch = (((c1 << 6) | c2) << 6) | c3;
} else if ((ch & 0xC0) == 0xC0) {
// 110xxxxx 10xxxxxx
int c1 = ch & 0x1F; ch = base.Read();
int c2 = ch & 0x3F;
ch = (c1 << 6) | c2;
}
return ch;
}
}
//-----------------------------------------------------------------------------------
// Scanner
//-----------------------------------------------------------------------------------
public class Scanner {
const char EOL = '\n';
const int eofSym = 0; /* pdt */
const int maxT = 48;
const int noSym = 48;
public Buffer buffer; // scanner buffer
Token t; // current token
int ch; // current input character
int pos; // byte position of current character
int charPos; // position by unicode characters starting with 0
int col; // column number of current character
int line; // line number of current character
int oldEols; // EOLs that appeared in a comment;
static readonly Hashtable start; // maps first token character to start state
Token tokens; // list of tokens already peeked (first token is a dummy)
Token pt; // current peek token
char[] tval = new char[128]; // text of current token
int tlen; // length of current token
static Scanner() {
start = new Hashtable(128);
for (int i = 65; i <= 90; ++i) start[i] = 1;
for (int i = 95; i <= 95; ++i) start[i] = 1;
for (int i = 97; i <= 122; ++i) start[i] = 1;
for (int i = 48; i <= 57; ++i) start[i] = 30;
start[34] = 7;
start[46] = 31;
start[91] = 9;
start[93] = 10;
start[40] = 11;
start[41] = 12;
start[33] = 32;
start[45] = 13;
start[124] = 33;
start[60] = 34;
start[62] = 35;
start[61] = 16;
start[59] = 19;
start[38] = 21;
start[47] = 36;
start[42] = 26;
start[13] = 28;
start[Buffer.EOF] = -1;
}
public Scanner (string fileName) {
try {
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
buffer = new Buffer(stream, false);
Init();
} catch (IOException) {
throw new FatalError("Cannot open file " + fileName);
}
}
public Scanner (Stream s) {
buffer = new Buffer(s, true);
Init();
}
void Init() {
pos = -1; line = 1; col = 0; charPos = -1;
oldEols = 0;
NextCh();
if (ch == 0xEF) { // check optional byte order mark for UTF-8
NextCh(); int ch1 = ch;
NextCh(); int ch2 = ch;
if (ch1 != 0xBB || ch2 != 0xBF) {
throw new FatalError(String.Format("illegal byte order mark: EF {0,2:X} {1,2:X}", ch1, ch2));
}
buffer = new UTF8Buffer(buffer); col = 0; charPos = -1;
NextCh();
}
pt = tokens = new Token(); // first token is a dummy
}
void NextCh() {
if (oldEols > 0) { ch = EOL; oldEols--; }
else {
pos = buffer.Pos;
// buffer reads unicode chars, if UTF8 has been detected
ch = buffer.Read(); col++; charPos++;
// replace isolated '\r' by '\n' in order to make
// eol handling uniform across Windows, Unix and Mac
if (ch == '\r' && buffer.Peek() != '\n') ch = EOL;
if (ch == EOL) { line++; col = 0; }
}
}
void AddCh() {
if (tlen >= tval.Length) {
char[] newBuf = new char[2 * tval.Length];
Array.Copy(tval, 0, newBuf, 0, tval.Length);
tval = newBuf;
}
if (ch != Buffer.EOF) {
tval[tlen++] = (char) ch;
NextCh();
}
}
void CheckLiteral() {
switch (t.val) {
case "native": t.kind = 27; break;
case "class": t.kind = 28; break;
case "constructor": t.kind = 29; break;
case "def": t.kind = 30; break;
case "external": t.kind = 31; break;
case "extends": t.kind = 32; break;
case "__heap": t.kind = 33; break;
case "if": t.kind = 34; break;
case "elseif": t.kind = 35; break;
case "else": t.kind = 36; break;
case "while": t.kind = 37; break;
case "for": t.kind = 38; break;
case "import": t.kind = 39; break;
case "prefix": t.kind = 40; break;
case "from": t.kind = 41; break;
case "break": t.kind = 42; break;
case "continue": t.kind = 43; break;
case "static": t.kind = 44; break;
case "true": t.kind = 45; break;
case "false": t.kind = 46; break;
case "null": t.kind = 47; break;
default: break;
}
}
Token NextToken() {
//while (ch == ' ' ||
// false
//) NextCh();
int recKind = noSym;
int recEnd = pos;
t = new Token();
t.pos = pos; t.col = col; t.line = line; t.charPos = charPos;
int state;
if (start.ContainsKey(ch)) { state = (int) start[ch]; }
else { state = 0; }
tlen = 0; AddCh();
switch (state) {
case -1: { t.kind = eofSym; break; } // NextCh already done
case 0: {
if (recKind != noSym) {
tlen = recEnd - t.pos;
SetScannerBehindT();
}
t.kind = recKind; break;
} // NextCh already done
case 1:
recEnd = pos; recKind = 1;
if (ch >= '0' && ch <= '9' || ch >= '@' && ch <= 'Z' || ch == '_' || ch >= 'a' && ch <= 'z') {AddCh(); goto case 1;}
else {t.kind = 1; t.val = new String(tval, 0, tlen); CheckLiteral(); return t;}
case 2:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 3;}
else {goto case 0;}
case 3:
recEnd = pos; recKind = 3;
if (ch >= '0' && ch <= '9') {AddCh(); goto case 3;}
else if (ch == 'E' || ch == 'e') {AddCh(); goto case 4;}
else {t.kind = 3; break;}
case 4:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 6;}
else if (ch == '+' || ch == '-') {AddCh(); goto case 5;}
else {goto case 0;}
case 5:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 6;}
else {goto case 0;}
case 6:
recEnd = pos; recKind = 3;
if (ch >= '0' && ch <= '9') {AddCh(); goto case 6;}
else {t.kind = 3; break;}
case 7:
if (ch <= '!' || ch >= '#' && ch <= 65535) {AddCh(); goto case 7;}
else if (ch == '"') {AddCh(); goto case 8;}
else {goto case 0;}
case 8:
{t.kind = 4; break;}
case 9:
{t.kind = 6; break;}
case 10:
{t.kind = 7; break;}
case 11:
{t.kind = 8; break;}
case 12:
{t.kind = 9; break;}
case 13:
{t.kind = 11; break;}
case 14:
{t.kind = 15; break;}
case 15:
{t.kind = 16; break;}
case 16:
if (ch == '=') {AddCh(); goto case 17;}
else {goto case 0;}
case 17:
{t.kind = 17; break;}
case 18:
{t.kind = 18; break;}
case 19:
{t.kind = 19; break;}
case 20:
{t.kind = 20; break;}
case 21:
if (ch == '&') {AddCh(); goto case 22;}
else {goto case 0;}
case 22:
{t.kind = 21; break;}
case 23:
{t.kind = 22; break;}
case 24:
{t.kind = 23; break;}
case 25:
{t.kind = 24; break;}
case 26:
if (ch == '/') {AddCh(); goto case 27;}
else {goto case 0;}
case 27:
{t.kind = 25; break;}
case 28:
if (ch == 10) {AddCh(); goto case 29;}
else {goto case 0;}
case 29:
{t.kind = 26; break;}
case 30:
recEnd = pos; recKind = 2;
if (ch >= '0' && ch <= '9') {AddCh(); goto case 30;}
else if (ch == '.') {AddCh(); goto case 2;}
else {t.kind = 2; break;}
case 31:
recEnd = pos; recKind = 5;
if (ch == '.') {AddCh(); goto case 20;}
else {t.kind = 5; break;}
case 32:
recEnd = pos; recKind = 10;
if (ch == '=') {AddCh(); goto case 18;}
else {t.kind = 10; break;}
case 33:
recEnd = pos; recKind = 12;
if (ch == '|') {AddCh(); goto case 23;}
else {t.kind = 12; break;}
case 34:
recEnd = pos; recKind = 13;
if (ch == '=') {AddCh(); goto case 14;}
else {t.kind = 13; break;}
case 35:
recEnd = pos; recKind = 14;
if (ch == '=') {AddCh(); goto case 15;}
else {t.kind = 14; break;}
case 36:
if (ch == '/') {AddCh(); goto case 24;}
else if (ch == '*') {AddCh(); goto case 25;}
else {goto case 0;}
}
t.val = new String(tval, 0, tlen);
return t;
}
private void SetScannerBehindT() {
buffer.Pos = t.pos;
NextCh();
line = t.line; col = t.col; charPos = t.charPos;
for (int i = 0; i < tlen; i++) NextCh();
}
// get the next token (possibly a token already seen during peeking)
public Token Scan () {
if (tokens.next == null) {
return NextToken();
} else {
pt = tokens = tokens.next;
return tokens;
}
}
// peek for the next token, ignore pragmas
public Token Peek () {
do {
if (pt.next == null) {
pt.next = NextToken();
}
pt = pt.next;
} while (pt.kind > maxT); // skip pragmas
return pt;
}
// make sure that peeking starts at the current scan position
public void ResetPeek () { pt = tokens; }
} // end Scanner
}
| |
#region MIT License
/*
* Copyright (c) 2009-2010 Nick Gravelyn ([email protected]), Markus Ewald ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
namespace RelhaxModpack.AtlasesCreator
{
/// <summary>Rectangle packer using an algorithm by Javier Arevalo</summary>
/// <remarks>
/// <para>
/// Original code by Javier Arevalo (jare at iguanademos dot com). Rewritten
/// to C# / .NET by Markus Ewald (cygon at nuclex dot org). The following comments
/// were written by the original author when he published his algorithm.
/// </para>
/// <para>
/// You have a bunch of rectangular pieces. You need to arrange them in a
/// rectangular surface so that they don't overlap, keeping the total area of the
/// rectangle as small as possible. This is fairly common when arranging characters
/// in a bitmapped font, lightmaps for a 3D engine, and I guess other situations as
/// well.
/// </para>
/// <para>
/// The idea of this algorithm is that, as we add rectangles, we can pre-select
/// "interesting" places where we can try to add the next rectangles. For optimal
/// results, the rectangles should be added in order. I initially tried using area
/// as a sorting criteria, but it didn't work well with very tall or very flat
/// rectangles. I then tried using the longest dimension as a selector, and it
/// worked much better. So much for intuition...
/// </para>
/// <para>
/// These "interesting" places are just to the right and just below the currently
/// added rectangle. The first rectangle, obviously, goes at the top left, the next
/// one would go either to the right or below this one, and so on. It is a weird way
/// to do it, but it seems to work very nicely.
/// </para>
/// <para>
/// The way we search here is fairly brute-force, the fact being that for most
/// offline purposes the performance seems more than adequate. I have generated a
/// japanese font with around 8500 characters and all the time was spent generating
/// the bitmaps.
/// </para>
/// <para>
/// Also, for all we care, we could grow the parent rectangle in a different way
/// than power of two. It just happens that power of 2 is very convenient for
/// graphics hardware textures.
/// </para>
/// <para>
/// I'd be interested in hearing of other approaches to this problem. Make sure
/// to post them on http://www.flipcode.com
/// </para>
/// </remarks>
internal class ArevaloRectanglePacker : RectanglePacker
{
#region class AnchorRankComparer
/// <summary>Compares the 'rank' of anchoring points</summary>
/// <remarks>
/// Anchoring points are potential locations for the placement of new rectangles.
/// Each time a rectangle is inserted, an anchor point is generated on its upper
/// right end and another one at its lower left end. The anchor points are kept
/// in a list that is ordered by their closeness to the upper left corner of the
/// packing area (their 'rank') so the packer favors positions that are closer to
/// the upper left for new rectangles.
/// </remarks>
private class AnchorRankComparer : IComparer<Point>
{
/// <summary>Provides a default instance for the anchor rank comparer</summary>
public static readonly AnchorRankComparer Default = new AnchorRankComparer();
#region IComparer<Point> Members
/// <summary>Compares the rank of two anchors against each other</summary>
/// <param name="left">Left anchor point that will be compared</param>
/// <param name="right">Right anchor point that will be compared</param>
/// <returns>The relation of the two anchor point's ranks to each other</returns>
public int Compare(Point left, Point right)
{
//return Math.Min(left.X, left.Y) - Math.Min(right.X, right.Y);
return (left.X + left.Y) - (right.X + right.Y);
}
#endregion
}
#endregion
/// <summary>Current height of the packing area</summary>
private int actualPackingAreaHeight = 1;
/// <summary>Current width of the packing area</summary>
private int actualPackingAreaWidth = 1;
/// <summary>Anchoring points where new rectangles can potentially be placed</summary>
private readonly List<Point> anchors = new List<Point> { new Point(0, 0) };
/// <summary>Rectangles contained in the packing area</summary>
private readonly List<Rectangle> packedRectangles = new List<Rectangle>();
/// <summary>Initializes a new rectangle packer</summary>
/// <param name="packingAreaWidth">Maximum width of the packing area</param>
/// <param name="packingAreaHeight">Maximum height of the packing area</param>
public ArevaloRectanglePacker(int packingAreaWidth, int packingAreaHeight)
: base(packingAreaWidth, packingAreaHeight)
{
}
/// <summary>Tries to allocate space for a rectangle in the packing area</summary>
/// <param name="rectangleWidth">Width of the rectangle to allocate</param>
/// <param name="rectangleHeight">Height of the rectangle to allocate</param>
/// <param name="placement">Output parameter receiving the rectangle's placement</param>
/// <returns>True if space for the rectangle could be allocated</returns>
public override bool TryPack(int rectangleWidth, int rectangleHeight, out Point placement)
{
// Try to find an anchor where the rectangle fits in, enlarging the packing
// area and repeating the search recursively until it fits or the
// maximum allowed size is exceeded.
int anchorIndex = SelectAnchorRecursive(rectangleWidth, rectangleHeight, actualPackingAreaWidth, actualPackingAreaHeight);
// No anchor could be found at which the rectangle did fit in
if (anchorIndex == -1)
{
placement = new Point();
return false;
}
placement = anchors[anchorIndex];
// Move the rectangle either to the left or to the top until it collides with
// a neightbouring rectangle. This is done to combat the effect of lining up
// rectangles with gaps to the left or top of them because the anchor that
// would allow placement there has been blocked by another rectangle
OptimizePlacement(ref placement, rectangleWidth, rectangleHeight);
// Remove the used anchor and add new anchors at the upper right and lower left
// positions of the new rectangle
// The anchor is only removed if the placement optimization didn't
// move the rectangle so far that the anchor isn't blocked anymore
bool blocksAnchor =
((placement.X + rectangleWidth) > anchors[anchorIndex].X) &&
((placement.Y + rectangleHeight) > anchors[anchorIndex].Y);
if (blocksAnchor)
anchors.RemoveAt(anchorIndex);
// Add new anchors at the upper right and lower left coordinates of the rectangle
InsertAnchor(new Point(placement.X + rectangleWidth, placement.Y));
InsertAnchor(new Point(placement.X, placement.Y + rectangleHeight));
// Finally, we can add the rectangle to our packed rectangles list
packedRectangles.Add(new Rectangle(placement.X, placement.Y, rectangleWidth, rectangleHeight));
return true;
}
/// <summary>
/// Optimizes the rectangle's placement by moving it either left or up to fill
/// any gaps resulting from rectangles blocking the anchors of the most optimal
/// placements.
/// </summary>
/// <param name="placement">Placement to be optimized</param>
/// <param name="rectangleWidth">Width of the rectangle to be optimized</param>
/// <param name="rectangleHeight">Height of the rectangle to be optimized</param>
private void OptimizePlacement(ref Point placement, int rectangleWidth, int rectangleHeight)
{
var rectangle = new Rectangle(placement.X, placement.Y, rectangleWidth, rectangleHeight);
// Try to move the rectangle to the left as far as possible
int leftMost = placement.X;
while (IsFree(ref rectangle, PackingAreaWidth, PackingAreaHeight))
{
leftMost = rectangle.X;
--rectangle.X;
}
// Reset rectangle to original position
rectangle.X = placement.X;
// Try to move the rectangle upwards as far as possible
int topMost = placement.Y;
while (IsFree(ref rectangle, PackingAreaWidth, PackingAreaHeight))
{
topMost = rectangle.Y;
--rectangle.Y;
}
// Use the dimension in which the rectangle could be moved farther
if ((placement.X - leftMost) > (placement.Y - topMost))
placement.X = leftMost;
else
placement.Y = topMost;
}
/// <summary>
/// Searches for a free anchor and recursively enlarges the packing area
/// if none can be found.
/// </summary>
/// <param name="rectangleWidth">Width of the rectangle to be placed</param>
/// <param name="rectangleHeight">Height of the rectangle to be placed</param>
/// <param name="testedPackingAreaWidth">Width of the tested packing area</param>
/// <param name="testedPackingAreaHeight">Height of the tested packing area</param>
/// <returns>
/// Index of the anchor the rectangle is to be placed at or -1 if the rectangle
/// does not fit in the packing area anymore.
/// </returns>
private int SelectAnchorRecursive(int rectangleWidth, int rectangleHeight, int testedPackingAreaWidth, int testedPackingAreaHeight)
{
// Try to locate an anchor point where the rectangle fits in
int freeAnchorIndex = FindFirstFreeAnchor(rectangleWidth, rectangleHeight, testedPackingAreaWidth, testedPackingAreaHeight);
// If a the rectangle fits without resizing packing area (any further in case
// of a recursive call), take over the new packing area size and return the
// anchor at which the rectangle can be placed.
if (freeAnchorIndex != -1)
{
actualPackingAreaWidth = testedPackingAreaWidth;
actualPackingAreaHeight = testedPackingAreaHeight;
return freeAnchorIndex;
}
//
// If we reach this point, the rectangle did not fit in the current packing
// area and our only choice is to try and enlarge the packing area.
//
// For readability, determine whether the packing area can be enlarged
// any further in its width and in its height
bool canEnlargeWidth = (testedPackingAreaWidth < PackingAreaWidth);
bool canEnlargeHeight = (testedPackingAreaHeight < PackingAreaHeight);
bool shouldEnlargeHeight = (!canEnlargeWidth) || (testedPackingAreaHeight < testedPackingAreaWidth);
// Try to enlarge the smaller of the two dimensions first (unless the smaller
// dimension is already at its maximum size). 'shouldEnlargeHeight' is true
// when the height was the smaller dimension or when the width is maxed out.
if (canEnlargeHeight && shouldEnlargeHeight)
{
// Try to double the height of the packing area
return SelectAnchorRecursive(rectangleWidth, rectangleHeight, testedPackingAreaWidth, Math.Min(testedPackingAreaHeight * 2, PackingAreaHeight));
}
if (canEnlargeWidth)
{
// Try to double the width of the packing area
return SelectAnchorRecursive(rectangleWidth, rectangleHeight, Math.Min(testedPackingAreaWidth * 2, PackingAreaWidth), testedPackingAreaHeight);
}
// Both dimensions are at their maximum sizes and the rectangle still
// didn't fit. We give up!
return -1;
}
/// <summary>Locates the first free anchor at which the rectangle fits</summary>
/// <param name="rectangleWidth">Width of the rectangle to be placed</param>
/// <param name="rectangleHeight">Height of the rectangle to be placed</param>
/// <param name="testedPackingAreaWidth">Total width of the packing area</param>
/// <param name="testedPackingAreaHeight">Total height of the packing area</param>
/// <returns>The index of the first free anchor or -1 if none is found</returns>
private int FindFirstFreeAnchor(int rectangleWidth, int rectangleHeight, int testedPackingAreaWidth, int testedPackingAreaHeight)
{
var potentialLocation = new Rectangle(0, 0, rectangleWidth, rectangleHeight);
// Walk over all anchors (which are ordered by their distance to the
// upper left corner of the packing area) until one is discovered that
// can house the new rectangle.
for (int index = 0; index < anchors.Count; ++index)
{
potentialLocation.X = anchors[index].X;
potentialLocation.Y = anchors[index].Y;
// See if the rectangle would fit in at this anchor point
if (IsFree(ref potentialLocation, testedPackingAreaWidth, testedPackingAreaHeight))
return index;
}
// No anchor points were found where the rectangle would fit in
return -1;
}
/// <summary>
/// Determines whether the rectangle can be placed in the packing area
/// at its current location.
/// </summary>
/// <param name="rectangle">Rectangle whose position to check</param>
/// <param name="testedPackingAreaWidth">Total width of the packing area</param>
/// <param name="testedPackingAreaHeight">Total height of the packing area</param>
/// <returns>True if the rectangle can be placed at its current position</returns>
private bool IsFree(ref Rectangle rectangle, int testedPackingAreaWidth, int testedPackingAreaHeight)
{
// If the rectangle is partially or completely outside of the packing
// area, it can't be placed at its current location
bool leavesPackingArea = (rectangle.X < 0) || (rectangle.Y < 0) || (rectangle.Right > testedPackingAreaWidth) || (rectangle.Bottom > testedPackingAreaHeight);
if (leavesPackingArea)
return false;
// Brute-force search whether the rectangle touches any of the other
// rectangles already in the packing area
for (int index = 0; index < packedRectangles.Count; ++index)
{
if (packedRectangles[index].IntersectsWith(rectangle))
return false;
}
// Success! The rectangle is inside the packing area and doesn't overlap
// with any other rectangles that have already been packed.
return true;
}
/// <summary>Inserts a new anchor point into the anchor list</summary>
/// <param name="anchor">Anchor point that will be inserted</param>
/// <remarks>
/// This method tries to keep the anchor list ordered by ranking the anchors
/// depending on the distance from the top left corner in the packing area.
/// </remarks>
private void InsertAnchor(Point anchor)
{
// Find out where to insert the new anchor based on its rank (which is
// calculated based on the anchor's distance to the top left corner of
// the packing area).
//
// From MSDN on BinarySearch():
// "If the List does not contain the specified value, the method returns
// a negative integer. You can apply the bitwise complement operation (~) to
// this negative integer to get the index of the first element that is
// larger than the search value."
int insertIndex = anchors.BinarySearch(anchor, AnchorRankComparer.Default);
if (insertIndex < 0)
insertIndex = ~insertIndex;
// Insert the anchor at the index matching its rank
anchors.Insert(insertIndex, anchor);
}
}
}
| |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Automatonymous
{
using System;
using Activities;
using Binders;
using MassTransit;
public static class SchedulerExtensions
{
public static EventActivityBinder<TInstance> Schedule<TInstance, TMessage>(this EventActivityBinder<TInstance> source,
Schedule<TInstance, TMessage> schedule, TMessage message)
where TInstance : class, SagaStateMachineInstance
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TMessage>(x => message, schedule, x => schedule.Delay));
}
public static EventActivityBinder<TInstance> Schedule<TInstance, TMessage>(this EventActivityBinder<TInstance> source,
Schedule<TInstance, TMessage> schedule, TMessage message, ScheduleDelayProvider<TInstance> delayProvider)
where TInstance : class, SagaStateMachineInstance
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TMessage>(x => message, schedule, delayProvider));
}
public static EventActivityBinder<TInstance> Schedule<TInstance, TMessage>(this EventActivityBinder<TInstance> source,
Schedule<TInstance, TMessage> schedule, TMessage message, Action<SendContext> contextCallback)
where TInstance : class, SagaStateMachineInstance
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TMessage>(x => message, schedule, contextCallback, x => schedule.Delay));
}
public static EventActivityBinder<TInstance> Schedule<TInstance, TMessage>(this EventActivityBinder<TInstance> source,
Schedule<TInstance, TMessage> schedule, TMessage message, Action<SendContext> contextCallback, ScheduleDelayProvider<TInstance> delayProvider)
where TInstance : class, SagaStateMachineInstance
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TMessage>(x => message, schedule, contextCallback, delayProvider));
}
public static EventActivityBinder<TInstance> Schedule<TInstance, TMessage>(this EventActivityBinder<TInstance> source,
Schedule<TInstance, TMessage> schedule, EventMessageFactory<TInstance, TMessage> messageFactory)
where TInstance : class, SagaStateMachineInstance
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TMessage>(messageFactory, schedule, x => schedule.Delay));
}
public static EventActivityBinder<TInstance> Schedule<TInstance, TMessage>(this EventActivityBinder<TInstance> source,
Schedule<TInstance, TMessage> schedule, EventMessageFactory<TInstance, TMessage> messageFactory, ScheduleDelayProvider<TInstance> delayProvider)
where TInstance : class, SagaStateMachineInstance
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TMessage>(messageFactory, schedule, delayProvider));
}
public static EventActivityBinder<TInstance> Schedule<TInstance, TMessage>(this EventActivityBinder<TInstance> source,
Schedule<TInstance, TMessage> schedule, EventMessageFactory<TInstance, TMessage> messageFactory, Action<SendContext> contextCallback)
where TInstance : class, SagaStateMachineInstance
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TMessage>(messageFactory, schedule, contextCallback, x => schedule.Delay));
}
public static EventActivityBinder<TInstance> Schedule<TInstance, TMessage>(this EventActivityBinder<TInstance> source,
Schedule<TInstance, TMessage> schedule, EventMessageFactory<TInstance, TMessage> messageFactory, Action<SendContext> contextCallback,
ScheduleDelayProvider<TInstance> delayProvider)
where TInstance : class, SagaStateMachineInstance
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TMessage>(messageFactory, schedule, contextCallback, delayProvider));
}
public static EventActivityBinder<TInstance, TData> Schedule<TInstance, TData, TMessage>(
this EventActivityBinder<TInstance, TData> source, Schedule<TInstance, TMessage> schedule, TMessage message)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TData, TMessage>(x => message, schedule, x => schedule.Delay));
}
public static EventActivityBinder<TInstance, TData> Schedule<TInstance, TData, TMessage>(
this EventActivityBinder<TInstance, TData> source, Schedule<TInstance, TMessage> schedule, TMessage message,
ScheduleDelayProvider<TInstance, TData> delayProvider)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TData, TMessage>(x => message, schedule, delayProvider));
}
public static EventActivityBinder<TInstance, TData> Schedule<TInstance, TData, TMessage>(
this EventActivityBinder<TInstance, TData> source, Schedule<TInstance, TMessage> schedule, TMessage message,
Action<SendContext> contextCallback)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TData, TMessage>(x => message, schedule, x => schedule.Delay));
}
public static EventActivityBinder<TInstance, TData> Schedule<TInstance, TData, TMessage>(
this EventActivityBinder<TInstance, TData> source, Schedule<TInstance, TMessage> schedule, TMessage message,
Action<SendContext> contextCallback, ScheduleDelayProvider<TInstance, TData> delayProvider)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TData, TMessage>(x => message, schedule, contextCallback, delayProvider));
}
public static EventActivityBinder<TInstance, TData> Schedule<TInstance, TData, TMessage>(
this EventActivityBinder<TInstance, TData> source, Schedule<TInstance, TMessage> schedule,
EventMessageFactory<TInstance, TData, TMessage> messageFactory)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TData, TMessage>(messageFactory, schedule, x => schedule.Delay));
}
public static EventActivityBinder<TInstance, TData> Schedule<TInstance, TData, TMessage>(
this EventActivityBinder<TInstance, TData> source, Schedule<TInstance, TMessage> schedule,
EventMessageFactory<TInstance, TData, TMessage> messageFactory, ScheduleDelayProvider<TInstance, TData> delayProvider)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TData, TMessage>(messageFactory, schedule, delayProvider));
}
public static EventActivityBinder<TInstance, TData> Schedule<TInstance, TData, TMessage>(
this EventActivityBinder<TInstance, TData> source, Schedule<TInstance, TMessage> schedule,
EventMessageFactory<TInstance, TData, TMessage> messageFactory,
Action<SendContext> contextCallback)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TData, TMessage>(messageFactory, schedule, contextCallback, x => schedule.Delay));
}
public static EventActivityBinder<TInstance, TData> Schedule<TInstance, TData, TMessage>(
this EventActivityBinder<TInstance, TData> source, Schedule<TInstance, TMessage> schedule,
EventMessageFactory<TInstance, TData, TMessage> messageFactory,
Action<SendContext> contextCallback, ScheduleDelayProvider<TInstance, TData> delayProvider)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TMessage : class
{
return source.Add(new ScheduleActivity<TInstance, TData, TMessage>(messageFactory, schedule, contextCallback, delayProvider));
}
public static ExceptionActivityBinder<TInstance, TData, TException> Schedule<TInstance, TData, TException, TMessage>(
this ExceptionActivityBinder<TInstance, TData, TException> source, Schedule<TInstance, TMessage> schedule, TMessage message)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TException : Exception
where TMessage : class
{
return source.Add(new FaultedScheduleActivity<TInstance, TData, TException, TMessage>(x => message, schedule, x => schedule.Delay));
}
public static ExceptionActivityBinder<TInstance, TData, TException> Schedule<TInstance, TData, TException, TMessage>(
this ExceptionActivityBinder<TInstance, TData, TException> source, Schedule<TInstance, TMessage> schedule, TMessage message,
ScheduleDelayProvider<TInstance, TData, TException> delayProvider)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TException : Exception
where TMessage : class
{
return source.Add(new FaultedScheduleActivity<TInstance, TData, TException, TMessage>(x => message, schedule, delayProvider));
}
public static ExceptionActivityBinder<TInstance, TData, TException> Schedule<TInstance, TData, TException, TMessage>(
this ExceptionActivityBinder<TInstance, TData, TException> source, Schedule<TInstance, TMessage> schedule, TMessage message,
Action<SendContext> contextCallback)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TException : Exception
where TMessage : class
{
return source.Add(new FaultedScheduleActivity<TInstance, TData, TException, TMessage>(x => message, schedule, contextCallback, x => schedule.Delay));
}
public static ExceptionActivityBinder<TInstance, TData, TException> Schedule<TInstance, TData, TException, TMessage>(
this ExceptionActivityBinder<TInstance, TData, TException> source, Schedule<TInstance, TMessage> schedule, TMessage message,
Action<SendContext> contextCallback, ScheduleDelayProvider<TInstance, TData, TException> delayProvider)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TException : Exception
where TMessage : class
{
return source.Add(new FaultedScheduleActivity<TInstance, TData, TException, TMessage>(x => message, schedule, contextCallback, delayProvider));
}
public static ExceptionActivityBinder<TInstance, TData, TException> Schedule<TInstance, TData, TException, TMessage>(
this ExceptionActivityBinder<TInstance, TData, TException> source, Schedule<TInstance, TMessage> schedule,
EventExceptionMessageFactory<TInstance, TData, TException, TMessage> messageFactory)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TException : Exception
where TMessage : class
{
return source.Add(new FaultedScheduleActivity<TInstance, TData, TException, TMessage>(messageFactory, schedule, x => schedule.Delay));
}
public static ExceptionActivityBinder<TInstance, TData, TException> Schedule<TInstance, TData, TException, TMessage>(
this ExceptionActivityBinder<TInstance, TData, TException> source, Schedule<TInstance, TMessage> schedule,
EventExceptionMessageFactory<TInstance, TData, TException, TMessage> messageFactory,
Action<SendContext> contextCallback, ScheduleDelayProvider<TInstance, TData, TException> delayProvider)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TException : Exception
where TMessage : class
{
return source.Add(new FaultedScheduleActivity<TInstance, TData, TException, TMessage>(messageFactory, schedule, contextCallback, delayProvider));
}
/// <summary>
/// Unschedule a message, if the message was scheduled.
/// </summary>
/// <typeparam name="TInstance"></typeparam>
/// <typeparam name="TData"></typeparam>
/// <param name="source"></param>
/// <param name="schedule"></param>
/// <returns></returns>
public static EventActivityBinder<TInstance, TData> Unschedule<TInstance, TData>(
this EventActivityBinder<TInstance, TData> source, Schedule<TInstance> schedule)
where TInstance : class, SagaStateMachineInstance
where TData : class
{
return source.Add(new UnscheduleActivity<TInstance>(schedule));
}
/// <summary>
/// Unschedule a message, if the message was scheduled.
/// </summary>
/// <param name="source"></param>
/// <param name="schedule"></param>
/// <returns></returns>
public static ExceptionActivityBinder<TInstance, TData, TException> Unschedule<TInstance, TData, TException>(
this ExceptionActivityBinder<TInstance, TData, TException> source, Schedule<TInstance> schedule)
where TInstance : class, SagaStateMachineInstance
where TData : class
where TException : Exception
{
return source.Add(new FaultedUnscheduleActivity<TInstance>(schedule));
}
/// <summary>
/// Unschedule a message, if the message was scheduled.
/// </summary>
/// <typeparam name="TInstance"></typeparam>
/// <param name="source"></param>
/// <param name="schedule"></param>
/// <returns></returns>
public static EventActivityBinder<TInstance> Unschedule<TInstance>(
this EventActivityBinder<TInstance> source, Schedule<TInstance> schedule)
where TInstance : class, SagaStateMachineInstance
{
return source.Add(new UnscheduleActivity<TInstance>(schedule));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Composition.Diagnostics;
using Microsoft.Internal;
namespace System.Composition.Convention
{
/// <summary>
/// Configures a type as a MEF part.
/// </summary>
public class PartConventionBuilder
{
private readonly Type[] _emptyTypeArray = EmptyArray<Type>.Value;
private static List<Attribute> s_onImportsSatisfiedAttributeList;
private readonly static List<Attribute> s_importingConstructorList = new List<Attribute>() { new ImportingConstructorAttribute() };
private readonly static Type s_exportAttributeType = typeof(ExportAttribute);
private readonly List<ExportConventionBuilder> _typeExportBuilders;
private readonly List<ImportConventionBuilder> _constructorImportBuilders;
private bool _isShared;
private string _sharingBoundary;
// Metadata selection
private List<Tuple<string, object>> _metadataItems;
private List<Tuple<string, Func<Type, object>>> _metadataItemFuncs;
// Constructor selector / configuration
private Func<IEnumerable<ConstructorInfo>, ConstructorInfo> _constructorFilter;
private Action<ParameterInfo, ImportConventionBuilder> _configureConstuctorImports;
//Property Import/Export selection and configuration
private readonly List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ExportConventionBuilder>, Type>> _propertyExports;
private readonly List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ImportConventionBuilder>>> _propertyImports;
private readonly List<Tuple<Predicate<Type>, Action<Type, ExportConventionBuilder>>> _interfaceExports;
private readonly List<Predicate<MethodInfo>> _methodImportsSatisfiedNotifications;
internal Predicate<Type> SelectType { get; private set; }
internal PartConventionBuilder(Predicate<Type> selectType)
{
SelectType = selectType;
_typeExportBuilders = new List<ExportConventionBuilder>();
_constructorImportBuilders = new List<ImportConventionBuilder>();
_propertyExports = new List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ExportConventionBuilder>, Type>>();
_propertyImports = new List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ImportConventionBuilder>>>();
_interfaceExports = new List<Tuple<Predicate<Type>, Action<Type, ExportConventionBuilder>>>();
_methodImportsSatisfiedNotifications = new List<Predicate<MethodInfo>>();
}
/// <summary>
/// Export the part using its own concrete type as the contract.
/// </summary>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder Export()
{
var exportBuilder = new ExportConventionBuilder();
_typeExportBuilders.Add(exportBuilder);
return this;
}
/// <summary>
/// Export the part.
/// </summary>
/// <param name="exportConfiguration">Configuration action for the export.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder Export(Action<ExportConventionBuilder> exportConfiguration)
{
Requires.NotNull(exportConfiguration, nameof(exportConfiguration));
var exportBuilder = new ExportConventionBuilder();
exportConfiguration(exportBuilder);
_typeExportBuilders.Add(exportBuilder);
return this;
}
/// <summary>
/// Export the part using <typeparamref name="T"/> as the contract.
/// </summary>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder Export<T>()
{
var exportBuilder = new ExportConventionBuilder().AsContractType<T>();
_typeExportBuilders.Add(exportBuilder);
return this;
}
/// <summary>
/// Export the class using <typeparamref name="T"/> as the contract.
/// </summary>
/// <param name="exportConfiguration">Configuration action for the export.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder Export<T>(Action<ExportConventionBuilder> exportConfiguration)
{
Requires.NotNull(exportConfiguration, nameof(exportConfiguration));
var exportBuilder = new ExportConventionBuilder().AsContractType<T>();
exportConfiguration(exportBuilder);
_typeExportBuilders.Add(exportBuilder);
return this;
}
/// <summary>
/// Select which of the available constructors will be used to instantiate the part.
/// </summary>
/// <param name="constructorSelector">Filter that selects a single constructor.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder SelectConstructor(Func<IEnumerable<ConstructorInfo>, ConstructorInfo> constructorSelector)
{
Requires.NotNull(constructorSelector, nameof(constructorSelector));
_constructorFilter = constructorSelector;
return this;
}
/// <summary>
/// Select which of the available constructors will be used to instantiate the part.
/// </summary>
/// <param name="constructorSelector">Filter that selects a single constructor.</param>
/// <param name="importConfiguration">Action configuring the parameters of the selected constructor.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder SelectConstructor(
Func<IEnumerable<ConstructorInfo>, ConstructorInfo> constructorSelector,
Action<ParameterInfo, ImportConventionBuilder> importConfiguration)
{
Requires.NotNull(importConfiguration, nameof(importConfiguration));
SelectConstructor(constructorSelector);
_configureConstuctorImports = importConfiguration;
return this;
}
/// <summary>
/// Select the interfaces on the part type that will be exported.
/// </summary>
/// <param name="interfaceFilter">Filter for interfaces.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder ExportInterfaces(Predicate<Type> interfaceFilter)
{
Requires.NotNull(interfaceFilter, nameof(interfaceFilter));
return ExportInterfacesImpl(interfaceFilter, null);
}
/// <summary>
/// Export all interfaces implemented by the part.
/// </summary>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder ExportInterfaces()
{
return ExportInterfaces(t => true);
}
/// <summary>
/// Select the interfaces on the part type that will be exported.
/// </summary>
/// <param name="interfaceFilter">Filter for interfaces.</param>
/// <param name="exportConfiguration">Action to configure selected interfaces.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder ExportInterfaces(
Predicate<Type> interfaceFilter,
Action<Type, ExportConventionBuilder> exportConfiguration)
{
Requires.NotNull(interfaceFilter, nameof(interfaceFilter));
Requires.NotNull(exportConfiguration, nameof(exportConfiguration));
return ExportInterfacesImpl(interfaceFilter, exportConfiguration);
}
private PartConventionBuilder ExportInterfacesImpl(
Predicate<Type> interfaceFilter,
Action<Type, ExportConventionBuilder> exportConfiguration)
{
_interfaceExports.Add(Tuple.Create(interfaceFilter, exportConfiguration));
return this;
}
/// <summary>
/// Select properties on the part to export.
/// </summary>
/// <param name="propertyFilter">Selector for exported properties.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder ExportProperties(Predicate<PropertyInfo> propertyFilter)
{
Requires.NotNull(propertyFilter, nameof(propertyFilter));
return ExportPropertiesImpl(propertyFilter, null);
}
/// <summary>
/// Select properties on the part to export.
/// </summary>
/// <param name="propertyFilter">Selector for exported properties.</param>
/// <param name="exportConfiguration">Action to configure selected properties.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder ExportProperties(
Predicate<PropertyInfo> propertyFilter,
Action<PropertyInfo, ExportConventionBuilder> exportConfiguration)
{
Requires.NotNull(propertyFilter, nameof(propertyFilter));
Requires.NotNull(exportConfiguration, nameof(exportConfiguration));
return ExportPropertiesImpl(propertyFilter, exportConfiguration);
}
private PartConventionBuilder ExportPropertiesImpl(
Predicate<PropertyInfo> propertyFilter,
Action<PropertyInfo, ExportConventionBuilder> exportConfiguration)
{
_propertyExports.Add(Tuple.Create(propertyFilter, exportConfiguration, default(Type)));
return this;
}
/// <summary>
/// Select properties to export from the part.
/// </summary>
/// <typeparam name="T">Contract type to export.</typeparam>
/// <param name="propertyFilter">Filter to select matching properties.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder ExportProperties<T>(Predicate<PropertyInfo> propertyFilter)
{
Requires.NotNull(propertyFilter, nameof(propertyFilter));
return ExportPropertiesImpl<T>(propertyFilter, null);
}
/// <summary>
/// Select properties to export from the part.
/// </summary>
/// <typeparam name="T">Contract type to export.</typeparam>
/// <param name="propertyFilter">Filter to select matching properties.</param>
/// <param name="exportConfiguration">Action to configure selected properties.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder ExportProperties<T>(
Predicate<PropertyInfo> propertyFilter,
Action<PropertyInfo, ExportConventionBuilder> exportConfiguration)
{
Requires.NotNull(propertyFilter, nameof(propertyFilter));
Requires.NotNull(exportConfiguration, nameof(exportConfiguration));
return ExportPropertiesImpl<T>(propertyFilter, exportConfiguration);
}
private PartConventionBuilder ExportPropertiesImpl<T>(
Predicate<PropertyInfo> propertyFilter,
Action<PropertyInfo, ExportConventionBuilder> exportConfiguration)
{
_propertyExports.Add(Tuple.Create(propertyFilter, exportConfiguration, typeof(T)));
return this;
}
/// <summary>
/// Select properties to import into the part.
/// </summary>
/// <param name="propertyFilter">Filter to select matching properties.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder ImportProperties(Predicate<PropertyInfo> propertyFilter)
{
Requires.NotNull(propertyFilter, nameof(propertyFilter));
return ImportPropertiesImpl(propertyFilter, null);
}
/// <summary>
/// Select properties to import into the part.
/// </summary>
/// <param name="propertyFilter">Filter to select matching properties.</param>
/// <param name="importConfiguration">Action to configure selected properties.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder ImportProperties(
Predicate<PropertyInfo> propertyFilter,
Action<PropertyInfo, ImportConventionBuilder> importConfiguration)
{
Requires.NotNull(propertyFilter, nameof(propertyFilter));
Requires.NotNull(importConfiguration, nameof(importConfiguration));
return ImportPropertiesImpl(propertyFilter, importConfiguration);
}
private PartConventionBuilder ImportPropertiesImpl(
Predicate<PropertyInfo> propertyFilter,
Action<PropertyInfo, ImportConventionBuilder> importConfiguration)
{
_propertyImports.Add(Tuple.Create(propertyFilter, importConfiguration));
return this;
}
/// <summary>
/// Select properties to import into the part.
/// </summary>
/// <typeparam name="T">Property type to import.</typeparam>
/// <param name="propertyFilter">Filter to select matching properties.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder ImportProperties<T>(Predicate<PropertyInfo> propertyFilter)
{
Requires.NotNull(propertyFilter, nameof(propertyFilter));
return ImportPropertiesImpl<T>(propertyFilter, null);
}
/// <summary>
/// Select properties to import into the part.
/// </summary>
/// <typeparam name="T">Property type to import.</typeparam>
/// <param name="propertyFilter">Filter to select matching properties.</param>
/// <param name="importConfiguration">Action to configure selected properties.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder ImportProperties<T>(
Predicate<PropertyInfo> propertyFilter,
Action<PropertyInfo, ImportConventionBuilder> importConfiguration)
{
Requires.NotNull(propertyFilter, nameof(propertyFilter));
Requires.NotNull(importConfiguration, nameof(importConfiguration));
return ImportPropertiesImpl<T>(propertyFilter, importConfiguration);
}
private PartConventionBuilder ImportPropertiesImpl<T>(
Predicate<PropertyInfo> propertyFilter,
Action<PropertyInfo, ImportConventionBuilder> importConfiguration)
{
Predicate<PropertyInfo> typedFilter = pi => pi.PropertyType.Equals(typeof(T)) && (propertyFilter == null || propertyFilter(pi));
_propertyImports.Add(Tuple.Create(typedFilter, importConfiguration));
return this;
}
/// <summary>
/// Mark the part as being shared within the entire composition.
/// </summary>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder NotifyImportsSatisfied(Predicate<MethodInfo> methodFilter)
{
_methodImportsSatisfiedNotifications.Add(methodFilter);
return this;
}
/// <summary>
/// Mark the part as being shared within the entire composition.
/// </summary>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder Shared()
{
return SharedImpl(null);
}
/// <summary>
/// Mark the part as being shared within the specified boundary.
/// </summary>
/// <param name="sharingBoundary">Name of the sharing boundary.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder Shared(string sharingBoundary)
{
Requires.NotNullOrEmpty(sharingBoundary, nameof(sharingBoundary));
return SharedImpl(sharingBoundary);
}
private PartConventionBuilder SharedImpl(string sharingBoundary)
{
_isShared = true;
_sharingBoundary = sharingBoundary;
return this;
}
/// <summary>
/// Add the specified metadata to the part.
/// </summary>
/// <param name="name">The metadata name.</param>
/// <param name="value">The metadata value.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder AddPartMetadata(string name, object value)
{
Requires.NotNullOrEmpty(name, nameof(name));
if (_metadataItems == null)
{
_metadataItems = new List<Tuple<string, object>>();
}
_metadataItems.Add(Tuple.Create(name, value));
return this;
}
/// <summary>
/// Add the specified metadata to the part.
/// </summary>
/// <param name="name">The metadata name.</param>
/// <param name="getValueFromPartType">A function mapping the part type to the metadata value.</param>
/// <returns>A part builder allowing further configuration of the part.</returns>
public PartConventionBuilder AddPartMetadata(string name, Func<Type, object> getValueFromPartType)
{
Requires.NotNullOrEmpty(name, nameof(name));
Requires.NotNull(getValueFromPartType, nameof(getValueFromPartType));
if (_metadataItemFuncs == null)
{
_metadataItemFuncs = new List<Tuple<string, Func<Type, object>>>();
}
_metadataItemFuncs.Add(Tuple.Create(name, getValueFromPartType));
return this;
}
private static bool MemberHasExportMetadata(MemberInfo member)
{
foreach (var attr in member.GetAttributes<Attribute>())
{
var provider = attr as ExportMetadataAttribute;
if (provider != null)
{
return true;
}
else
{
Type attrType = attr.GetType();
// Perf optimization, relies on short circuit evaluation, often a property attribute is an ExportAttribute
if (attrType != PartConventionBuilder.s_exportAttributeType && attrType.GetTypeInfo().IsAttributeDefined<MetadataAttributeAttribute>(true))
{
return true;
}
}
}
return false;
}
internal IEnumerable<Attribute> BuildTypeAttributes(Type type)
{
var attributes = new List<Attribute>();
if (_typeExportBuilders != null)
{
bool isConfigured = type.GetTypeInfo().GetFirstAttribute<ExportAttribute>() != null || MemberHasExportMetadata(type.GetTypeInfo());
if (isConfigured)
{
CompositionTrace.Registration_TypeExportConventionOverridden(type);
}
else
{
foreach (var export in _typeExportBuilders)
{
export.BuildAttributes(type, ref attributes);
}
}
}
if (_isShared)
{
// Check if there is already a SharedAttribute. If found Trace a warning and do not add this Shared
// otherwise add new one
bool isConfigured = type.GetTypeInfo().GetFirstAttribute<SharedAttribute>() != null;
if (isConfigured)
{
CompositionTrace.Registration_PartCreationConventionOverridden(type);
}
else
{
attributes.Add(_sharingBoundary == null ?
new SharedAttribute() :
new SharedAttribute(_sharingBoundary));
}
}
//Add metadata attributes from direct specification
if (_metadataItems != null)
{
bool isConfigured = type.GetTypeInfo().GetFirstAttribute<PartMetadataAttribute>() != null;
if (isConfigured)
{
CompositionTrace.Registration_PartMetadataConventionOverridden(type);
}
else
{
foreach (var item in _metadataItems)
{
attributes.Add(new PartMetadataAttribute(item.Item1, item.Item2));
}
}
}
//Add metadata attributes from func specification
if (_metadataItemFuncs != null)
{
bool isConfigured = type.GetTypeInfo().GetFirstAttribute<PartMetadataAttribute>() != null;
if (isConfigured)
{
CompositionTrace.Registration_PartMetadataConventionOverridden(type);
}
else
{
foreach (var item in _metadataItemFuncs)
{
var name = item.Item1;
var value = (item.Item2 != null) ? item.Item2(type) : null;
attributes.Add(new PartMetadataAttribute(name, value));
}
}
}
if (_interfaceExports.Any())
{
if (_typeExportBuilders != null)
{
bool isConfigured = type.GetTypeInfo().GetFirstAttribute<ExportAttribute>() != null || MemberHasExportMetadata(type.GetTypeInfo());
if (isConfigured)
{
CompositionTrace.Registration_TypeExportConventionOverridden(type);
}
else
{
foreach (var iface in type.GetTypeInfo().ImplementedInterfaces)
{
if (iface == typeof(IDisposable))
{
continue;
}
// Run through the export specifications see if any match
foreach (var exportSpecification in _interfaceExports)
{
if (exportSpecification.Item1 != null && exportSpecification.Item1(iface))
{
ExportConventionBuilder exportBuilder = new ExportConventionBuilder();
exportBuilder.AsContractType(iface);
if (exportSpecification.Item2 != null)
{
exportSpecification.Item2(iface, exportBuilder);
}
exportBuilder.BuildAttributes(iface, ref attributes);
}
}
}
}
}
}
return attributes;
}
internal bool BuildConstructorAttributes(Type type, ref List<Tuple<object, List<Attribute>>> configuredMembers)
{
IEnumerable<ConstructorInfo> constructors = type.GetTypeInfo().DeclaredConstructors;
// First see if any of these constructors have the ImportingConstructorAttribute if so then we are already done
foreach (var ci in constructors)
{
// We have a constructor configuration we must log a warning then not bother with ConstructorAttributes
IEnumerable<Attribute> attributes = ci.GetCustomAttributes(typeof(ImportingConstructorAttribute), false);
if (attributes.Count() != 0)
{
CompositionTrace.Registration_ConstructorConventionOverridden(type);
return true;
}
}
if (_constructorFilter != null)
{
ConstructorInfo constructorInfo = _constructorFilter(constructors);
if (constructorInfo != null)
{
ConfigureConstructorAttributes(constructorInfo, ref configuredMembers, _configureConstuctorImports);
}
return true;
}
else if (_configureConstuctorImports != null)
{
bool configured = false;
foreach (var constructorInfo in FindLongestConstructors(constructors))
{
ConfigureConstructorAttributes(constructorInfo, ref configuredMembers, _configureConstuctorImports);
configured = true;
}
return configured;
}
return false;
}
internal static void BuildDefaultConstructorAttributes(Type type, ref List<Tuple<object, List<Attribute>>> configuredMembers)
{
IEnumerable<ConstructorInfo> constructors = type.GetTypeInfo().DeclaredConstructors;
foreach (var constructorInfo in FindLongestConstructors(constructors))
{
ConfigureConstructorAttributes(constructorInfo, ref configuredMembers, null);
}
}
private static void ConfigureConstructorAttributes(ConstructorInfo constructorInfo, ref List<Tuple<object, List<Attribute>>> configuredMembers, Action<ParameterInfo, ImportConventionBuilder> configureConstuctorImports)
{
if (configuredMembers == null)
{
configuredMembers = new List<Tuple<object, List<Attribute>>>();
}
// Make its attribute
configuredMembers.Add(Tuple.Create((object)constructorInfo, s_importingConstructorList));
//Okay we have the constructor now we can configure the ImportBuilders
var parameterInfos = constructorInfo.GetParameters();
foreach (var pi in parameterInfos)
{
bool isConfigured = pi.GetFirstAttribute<ImportAttribute>() != null || pi.GetFirstAttribute<ImportManyAttribute>() != null;
if (isConfigured)
{
CompositionTrace.Registration_ParameterImportConventionOverridden(pi, constructorInfo);
}
else
{
var importBuilder = new ImportConventionBuilder();
// Let the developer alter them if they specified to do so
if (configureConstuctorImports != null)
{
configureConstuctorImports(pi, importBuilder);
}
// Generate the attributes
List<Attribute> attributes = null;
importBuilder.BuildAttributes(pi.ParameterType, ref attributes);
configuredMembers.Add(Tuple.Create((object)pi, attributes));
}
}
}
internal void BuildOnImportsSatisfiedNotification(Type type, ref List<Tuple<object, List<Attribute>>> configuredMembers)
{
//Add OnImportsSatisfiedAttribute where specified
if (_methodImportsSatisfiedNotifications != null)
{
foreach (var mi in type.GetRuntimeMethods())
{
//We are only interested in void methods with no arguments
if (mi.ReturnParameter.ParameterType == typeof(void)
&& mi.GetParameters().Length == 0)
{
MethodInfo underlyingMi = mi.DeclaringType.GetRuntimeMethod(mi.Name, _emptyTypeArray);
if (underlyingMi != null)
{
bool checkedIfConfigured = false;
bool isConfigured = false;
foreach (var notification in _methodImportsSatisfiedNotifications)
{
if (notification(underlyingMi))
{
if (!checkedIfConfigured)
{
isConfigured = mi.GetFirstAttribute<OnImportsSatisfiedAttribute>() != null;
checkedIfConfigured = true;
}
if (isConfigured)
{
CompositionTrace.Registration_OnSatisfiedImportNotificationOverridden(type, mi);
break;
}
else
{
// We really only need to create this list once and then cache it, it never goes back to null
// Its perfectly okay if we make a list a few times on different threads, effectively though once we have
// cached one we will never make another.
if (PartConventionBuilder.s_onImportsSatisfiedAttributeList == null)
{
var onImportsSatisfiedAttributeList = new List<Attribute>();
onImportsSatisfiedAttributeList.Add(new OnImportsSatisfiedAttribute());
PartConventionBuilder.s_onImportsSatisfiedAttributeList = onImportsSatisfiedAttributeList;
}
configuredMembers.Add(new Tuple<object, List<Attribute>>(mi, PartConventionBuilder.s_onImportsSatisfiedAttributeList));
}
}
}
}
}
}
}
}
internal void BuildPropertyAttributes(Type type, ref List<Tuple<object, List<Attribute>>> configuredMembers)
{
if (_propertyImports.Any() || _propertyExports.Any())
{
foreach (var pi in type.GetRuntimeProperties())
{
List<Attribute> attributes = null;
int importsBuilt = 0;
bool checkedIfConfigured = false;
bool isConfigured = false;
PropertyInfo underlyingPi = null;
// Run through the import specifications see if any match
foreach (var importSpecification in _propertyImports)
{
if (underlyingPi == null)
{
underlyingPi = pi.DeclaringType.GetRuntimeProperty(pi.Name);
}
if (importSpecification.Item1 != null && importSpecification.Item1(underlyingPi))
{
var importBuilder = new ImportConventionBuilder();
if (importSpecification.Item2 != null)
{
importSpecification.Item2(pi, importBuilder);
}
if (!checkedIfConfigured)
{
isConfigured = pi.GetFirstAttribute<ImportAttribute>() != null || pi.GetFirstAttribute<ImportManyAttribute>() != null;
checkedIfConfigured = true;
}
if (isConfigured)
{
CompositionTrace.Registration_MemberImportConventionOverridden(type, pi);
break;
}
else
{
importBuilder.BuildAttributes(pi.PropertyType, ref attributes);
++importsBuilt;
}
}
if (importsBuilt > 1)
{
CompositionTrace.Registration_MemberImportConventionMatchedTwice(type, pi);
}
}
checkedIfConfigured = false;
isConfigured = false;
// Run through the export specifications see if any match
foreach (var exportSpecification in _propertyExports)
{
if (underlyingPi == null)
{
underlyingPi = pi.DeclaringType.GetRuntimeProperty(pi.Name);
}
if (exportSpecification.Item1 != null && exportSpecification.Item1(underlyingPi))
{
var exportBuilder = new ExportConventionBuilder();
if (exportSpecification.Item3 != null)
{
exportBuilder.AsContractType(exportSpecification.Item3);
}
if (exportSpecification.Item2 != null)
{
exportSpecification.Item2(pi, exportBuilder);
}
if (!checkedIfConfigured)
{
isConfigured = pi.GetFirstAttribute<ExportAttribute>() != null || MemberHasExportMetadata(pi);
checkedIfConfigured = true;
}
if (isConfigured)
{
CompositionTrace.Registration_MemberExportConventionOverridden(type, pi);
break;
}
else
{
exportBuilder.BuildAttributes(pi.PropertyType, ref attributes);
}
}
}
if (attributes != null)
{
if (configuredMembers == null)
{
configuredMembers = new List<Tuple<object, List<Attribute>>>();
}
configuredMembers.Add(Tuple.Create((object)pi, attributes));
}
}
}
return;
}
private static IEnumerable<ConstructorInfo> FindLongestConstructors(IEnumerable<ConstructorInfo> constructors)
{
ConstructorInfo longestConstructor = null;
int argumentsCount = 0;
int constructorsFound = 0;
foreach (var candidateConstructor in constructors)
{
int length = candidateConstructor.GetParameters().Length;
if (length != 0)
{
if (length > argumentsCount)
{
longestConstructor = candidateConstructor;
argumentsCount = length;
constructorsFound = 1;
}
else if (length == argumentsCount)
{
++constructorsFound;
}
}
}
if (constructorsFound > 1)
{
foreach (var candidateConstructor in constructors)
{
int length = candidateConstructor.GetParameters().Length;
if (length == argumentsCount)
{
yield return candidateConstructor;
}
}
}
else if (constructorsFound == 1)
{
yield return longestConstructor;
}
yield break;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Runtime;
using System.ServiceModel.Channels;
using System.Text;
using System.Xml;
namespace System.ServiceModel
{
public abstract class HttpBindingBase : Binding, IBindingRuntimePreferences
{
// private BindingElements
private HttpTransportBindingElement _httpTransport;
private HttpsTransportBindingElement _httpsTransport;
private TextMessageEncodingBindingElement _textEncoding;
internal HttpBindingBase()
{
_httpTransport = new HttpTransportBindingElement();
_httpsTransport = new HttpsTransportBindingElement();
_textEncoding = new TextMessageEncodingBindingElement();
_textEncoding.MessageVersion = MessageVersion.Soap11;
_httpsTransport.WebSocketSettings = _httpTransport.WebSocketSettings;
}
[DefaultValue(HttpTransportDefaults.AllowCookies)]
public bool AllowCookies
{
get
{
return _httpTransport.AllowCookies;
}
set
{
_httpTransport.AllowCookies = value;
_httpsTransport.AllowCookies = value;
}
}
[DefaultValue(HttpTransportDefaults.HostNameComparisonMode)]
public HostNameComparisonMode HostNameComparisonMode
{
get
{
return _httpTransport.HostNameComparisonMode;
}
set
{
_httpTransport.HostNameComparisonMode = value;
_httpsTransport.HostNameComparisonMode = value;
}
}
[DefaultValue(TransportDefaults.MaxBufferSize)]
public int MaxBufferSize
{
get
{
return _httpTransport.MaxBufferSize;
}
set
{
_httpTransport.MaxBufferSize = value;
_httpsTransport.MaxBufferSize = value;
}
}
[DefaultValue(TransportDefaults.MaxBufferPoolSize)]
public long MaxBufferPoolSize
{
get
{
return _httpTransport.MaxBufferPoolSize;
}
set
{
_httpTransport.MaxBufferPoolSize = value;
_httpsTransport.MaxBufferPoolSize = value;
}
}
[DefaultValue(TransportDefaults.MaxReceivedMessageSize)]
public long MaxReceivedMessageSize
{
get
{
return _httpTransport.MaxReceivedMessageSize;
}
set
{
_httpTransport.MaxReceivedMessageSize = value;
_httpsTransport.MaxReceivedMessageSize = value;
}
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
return _textEncoding.ReaderQuotas;
}
set
{
if (value == null)
{
throw FxTrace.Exception.ArgumentNull("value");
}
value.CopyTo(_textEncoding.ReaderQuotas);
this.SetReaderQuotas(value);
}
}
public override string Scheme
{
get
{
return this.GetTransport().Scheme;
}
}
public EnvelopeVersion EnvelopeVersion
{
get { return this.GetEnvelopeVersion(); }
}
public Encoding TextEncoding
{
get
{
return _textEncoding.WriteEncoding;
}
set
{
_textEncoding.WriteEncoding = value;
}
}
[DefaultValue(HttpTransportDefaults.TransferMode)]
public TransferMode TransferMode
{
get
{
return _httpTransport.TransferMode;
}
set
{
_httpTransport.TransferMode = value;
_httpsTransport.TransferMode = value;
}
}
public bool UseDefaultWebProxy
{
get
{
return _httpTransport.UseDefaultWebProxy;
}
}
bool IBindingRuntimePreferences.ReceiveSynchronously
{
get { return false; }
}
internal TextMessageEncodingBindingElement TextMessageEncodingBindingElement
{
get
{
return _textEncoding;
}
}
internal abstract BasicHttpSecurity BasicHttpSecurity
{
get;
}
internal WebSocketTransportSettings InternalWebSocketSettings
{
get
{
return _httpTransport.WebSocketSettings;
}
}
internal static bool GetSecurityModeFromTransport(HttpTransportBindingElement http, HttpTransportSecurity transportSecurity, out UnifiedSecurityMode mode)
{
mode = UnifiedSecurityMode.None;
if (http == null)
{
return false;
}
Fx.Assert(http.AuthenticationScheme.IsSingleton(), "authenticationScheme used in an Http(s)ChannelFactory must be a singleton value.");
if (http is HttpsTransportBindingElement)
{
mode = UnifiedSecurityMode.Transport | UnifiedSecurityMode.TransportWithMessageCredential;
BasicHttpSecurity.EnableTransportSecurity((HttpsTransportBindingElement)http, transportSecurity);
}
else if (HttpTransportSecurity.IsDisabledTransportAuthentication(http))
{
mode = UnifiedSecurityMode.Message | UnifiedSecurityMode.None;
}
else if (!BasicHttpSecurity.IsEnabledTransportAuthentication(http, transportSecurity))
{
return false;
}
else
{
mode = UnifiedSecurityMode.TransportCredentialOnly;
}
return true;
}
internal TransportBindingElement GetTransport()
{
Fx.Assert(this.BasicHttpSecurity != null, "this.BasicHttpSecurity should not return null from a derived class.");
BasicHttpSecurity basicHttpSecurity = this.BasicHttpSecurity;
if (basicHttpSecurity.Mode == BasicHttpSecurityMode.Transport || basicHttpSecurity.Mode == BasicHttpSecurityMode.TransportWithMessageCredential)
{
basicHttpSecurity.EnableTransportSecurity(_httpsTransport);
return _httpsTransport;
}
else if (basicHttpSecurity.Mode == BasicHttpSecurityMode.TransportCredentialOnly)
{
basicHttpSecurity.EnableTransportAuthentication(_httpTransport);
return _httpTransport;
}
else
{
// ensure that there is no transport security
basicHttpSecurity.DisableTransportAuthentication(_httpTransport);
return _httpTransport;
}
}
internal abstract EnvelopeVersion GetEnvelopeVersion();
internal virtual void SetReaderQuotas(XmlDictionaryReaderQuotas readerQuotas)
{
}
// In the Win8 profile, some settings for the binding security are not supported.
internal virtual void CheckSettings()
{
BasicHttpSecurity security = this.BasicHttpSecurity;
if (security == null)
{
return;
}
BasicHttpSecurityMode mode = security.Mode;
if (mode == BasicHttpSecurityMode.None)
{
return;
}
else if (mode == BasicHttpSecurityMode.Message || mode == BasicHttpSecurityMode.TransportWithMessageCredential)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Mode", mode)));
}
// Transport.ClientCredentialType = InheritedFromHost are not supported.
Fx.Assert(
(mode == BasicHttpSecurityMode.Transport) || (mode == BasicHttpSecurityMode.TransportCredentialOnly),
"Unexpected BasicHttpSecurityMode value: " + mode);
HttpTransportSecurity transport = security.Transport;
if (transport != null && transport.ClientCredentialType == HttpClientCredentialType.InheritedFromHost)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Transport.ClientCredentialType", transport.ClientCredentialType)));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Lib3DDraw
{
public class Matrix3
{
public float[,] M = new float[4, 4];
public Matrix3()
{
Identity3();
}
public Matrix3(float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33)
{
M[0, 0] = m00;
M[0, 1] = m01;
M[0, 2] = m02;
M[0, 3] = m03;
M[1, 0] = m10;
M[1, 1] = m11;
M[1, 2] = m12;
M[1, 3] = m13;
M[2, 0] = m20;
M[2, 1] = m21;
M[2, 2] = m22;
M[2, 3] = m23;
M[3, 0] = m30;
M[3, 1] = m31;
M[3, 2] = m32;
M[3, 3] = m33;
}
// Define a Identity matrix:
public void Identity3()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (i == j)
{
M[i, j] = 1;
}
else
{
M[i, j] = 0;
}
}
}
}
// Multiply two matrices together:
public static Matrix3 operator *(Matrix3 m1, Matrix3 m2)
{
Matrix3 result = new Matrix3();
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
float element = 0;
for (int k = 0; k < 4; k++)
{
element += m1.M[i, k] * m2.M[k, j];
}
result.M[i, j] = element;
}
}
return result;
}
// Apply a transformation to a vector (point):
public float[] VectorMultiply(float[] vector)
{
float[] result = new float[4];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
result[i] += M[i, j] * vector[j];
}
}
return result;
}
// Create a scaling matrix:
public static Matrix3 Scale3(float sx, float sy, float sz)
{
Matrix3 result = new Matrix3();
result.M[0, 0] = sx;
result.M[1, 1] = sy;
result.M[2, 2] = sz;
return result;
}
// Create a translation matrix
public static Matrix3 Translate3(float dx, float dy, float dz)
{
Matrix3 result = new Matrix3();
result.M[0, 3] = dx;
result.M[1, 3] = dy;
result.M[2, 3] = dz;
return result;
}
// Create a rotation matrix around the x axis:
public static Matrix3 Rotate3X(float theta)
{
theta = theta * (float)Math.PI / 180.0f;
float sn = (float)Math.Sin(theta);
float cn = (float)Math.Cos(theta);
Matrix3 result = new Matrix3();
result.M[1, 1] = cn;
result.M[1, 2] = -sn;
result.M[2, 1] = sn;
result.M[2, 2] = cn;
return result;
}
// Create a rotation matrix around the y axis:
public static Matrix3 Rotate3Y(float theta)
{
theta = theta * (float)Math.PI / 180.0f;
float sn = (float)Math.Sin(theta);
float cn = (float)Math.Cos(theta);
Matrix3 result = new Matrix3();
result.M[0, 0] = cn;
result.M[0, 2] = sn;
result.M[2, 0] = -sn;
result.M[2, 2] = cn;
return result;
}
// Create a rotation matrix around the z axis:
public static Matrix3 Rotate3Z(float theta)
{
theta = theta * (float)Math.PI / 180.0f;
float sn = (float)Math.Sin(theta);
float cn = (float)Math.Cos(theta);
Matrix3 result = new Matrix3();
result.M[0, 0] = cn;
result.M[0, 1] = -sn;
result.M[1, 0] = sn;
result.M[1, 1] = cn;
return result;
}
// Front view projection matrix:
public static Matrix3 FrontView()
{
Matrix3 result = new Matrix3();
result.M[2, 2] = 0;
return result;
}
// Side view projection matrix:
public static Matrix3 SideView()
{
Matrix3 result = new Matrix3();
result.M[0, 0] = 0;
result.M[2, 2] = 0;
result.M[0, 2] = -1;
return result;
}
// Top view projection matrix:
public static Matrix3 TopView()
{
Matrix3 result = new Matrix3();
result.M[1, 1] = 0;
result.M[2, 2] = 0;
result.M[1, 2] = -1;
return result;
}
// Axonometric projection matrix:
public static Matrix3 Axonometric(float alpha, float beta)
{
Matrix3 result = new Matrix3();
float sna = (float)Math.Sin(alpha * Math.PI / 180);
float cna = (float)Math.Cos(alpha * Math.PI / 180);
float snb = (float)Math.Sin(beta * Math.PI / 180);
float cnb = (float)Math.Cos(beta * Math.PI / 180);
result.M[0, 0] = cnb;
result.M[0, 2] = snb;
result.M[1, 0] = sna * snb;
result.M[1, 1] = cna;
result.M[1, 2] = -sna * cnb;
result.M[2, 2] = 0;
return result;
}
// Oblique projection matrix:
public static Matrix3 Oblique(float alpha, float theta)
{
Matrix3 result = new Matrix3();
float ta = (float)Math.Tan(alpha * Math.PI / 180);
float snt = (float)Math.Sin(theta * Math.PI / 180);
float cnt = (float)Math.Cos(theta * Math.PI / 180);
result.M[0, 2] = -cnt / ta;
result.M[1, 2] = -snt / ta;
result.M[2, 2] = 0;
return result;
}
// Perspective projection matrix:
public static Matrix3 Perspective(float d)
{
Matrix3 result = new Matrix3();
result.M[3, 2] = -1 / d;
return result;
}
public Point3 Cylindrical(float r, float theta, float y)
{
Point3 pt = new Point3();
float sn = (float)Math.Sin(theta * Math.PI / 180);
float cn = (float)Math.Cos(theta * Math.PI / 180);
pt.X = r * cn;
pt.Y = y;
pt.Z = -r * sn;
pt.W = 1;
return pt;
}
public Point3 Spherical(float r, float theta, float phi)
{
Point3 pt = new Point3();
float snt = (float)Math.Sin(theta * Math.PI / 180);
float cnt = (float)Math.Cos(theta * Math.PI / 180);
float snp = (float)Math.Sin(phi * Math.PI / 180);
float cnp = (float)Math.Cos(phi * Math.PI / 180);
pt.X = r * snt * cnp;
pt.Y = r * cnt;
pt.Z = -r * snt * snp;
pt.W = 1;
return pt;
}
public static Matrix3 Euler(float alpha, float beta, float gamma)
{
Matrix3 result = new Matrix3();
alpha = alpha * (float)Math.PI / 180.0f;
float sna = (float)Math.Sin(alpha);
float cna = (float)Math.Cos(alpha);
beta = beta * (float)Math.PI / 180.0f;
float snb = (float)Math.Sin(beta);
float cnb = (float)Math.Cos(beta);
gamma = gamma * (float)Math.PI / 180.0f;
float sng = (float)Math.Sin(gamma);
float cng = (float)Math.Cos(gamma);
result.M[0, 0] = cna * cng - sna * snb * sng;
result.M[0, 1] = -snb * sng;
result.M[0, 2] = sna * cng - cna * cnb * sng;
result.M[1, 0] = -sna * snb;
result.M[1, 1] = cnb;
result.M[1, 2] = cna * snb;
result.M[2, 0] = -cna * sng - sna * cnb * cng;
result.M[2, 1] = -snb * cng;
result.M[2, 2] = cna * cnb * cng - sna * snb;
return result;
}
public static Matrix3 AzimuthElevation(float elevation, float azimuth, float oneOverd)
{
Matrix3 result = new Matrix3();
Matrix3 rotate = new Matrix3();
// make sure elevation in the range of [-90, 90]:
if (elevation > 90)
elevation = 90;
else if (elevation < -90)
elevation = -90;
// Make sure azimuth in the range of [-180, 180]:
if (azimuth > 180)
azimuth = 180;
else if (azimuth < -180)
azimuth = -180;
elevation = elevation * (float)Math.PI / 180.0f;
float sne = (float)Math.Sin(elevation);
float cne = (float)Math.Cos(elevation);
azimuth = azimuth * (float)Math.PI / 180.0f;
float sna = (float)Math.Sin(azimuth);
float cna = (float)Math.Cos(azimuth);
rotate.M[0, 0] = cna;
rotate.M[0, 1] = sna;
rotate.M[0, 2] = 0;
rotate.M[1, 0] = -sne * sna;
rotate.M[1, 1] = sne * cna;
rotate.M[1, 2] = cne;
rotate.M[2, 0] = cne * sna;
rotate.M[2, 1] = -cne * cna;
rotate.M[2, 2] = sne;
if (oneOverd <= 0)
result = rotate;
else if (oneOverd > 0)
{
Matrix3 perspective = Matrix3.Perspective(1 / oneOverd);
result = perspective * rotate;
}
return result;
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Account.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
using Frapid.WebApi;
namespace Frapid.Account.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Reset Requests.
/// </summary>
[RoutePrefix("api/v1.0/account/reset-request")]
public class ResetRequestController : FrapidApiController
{
/// <summary>
/// The ResetRequest repository.
/// </summary>
private IResetRequestRepository ResetRequestRepository;
public ResetRequestController()
{
}
public ResetRequestController(IResetRequestRepository repository)
{
this.ResetRequestRepository = repository;
}
protected override void Initialize(HttpControllerContext context)
{
base.Initialize(context);
if (this.ResetRequestRepository == null)
{
this.ResetRequestRepository = new Frapid.Account.DataAccess.ResetRequest
{
_Catalog = this.MetaUser.Catalog,
_LoginId = this.MetaUser.LoginId,
_UserId = this.MetaUser.UserId
};
}
}
/// <summary>
/// Creates meta information of "reset request" entity.
/// </summary>
/// <returns>Returns the "reset request" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/account/reset-request/meta")]
[RestAuthorize]
public EntityView GetEntityView()
{
return new EntityView
{
PrimaryKey = "request_id",
Columns = new List<EntityColumn>()
{
new EntityColumn
{
ColumnName = "request_id",
PropertyName = "RequestId",
DataType = "System.Guid",
DbDataType = "uuid",
IsNullable = false,
IsPrimaryKey = true,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "user_id",
PropertyName = "UserId",
DataType = "int",
DbDataType = "int4",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "email",
PropertyName = "Email",
DataType = "string",
DbDataType = "text",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "name",
PropertyName = "Name",
DataType = "string",
DbDataType = "text",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "requested_on",
PropertyName = "RequestedOn",
DataType = "DateTime",
DbDataType = "timestamptz",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "expires_on",
PropertyName = "ExpiresOn",
DataType = "DateTime",
DbDataType = "timestamptz",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "browser",
PropertyName = "Browser",
DataType = "string",
DbDataType = "text",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "ip_address",
PropertyName = "IpAddress",
DataType = "string",
DbDataType = "varchar",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 50
},
new EntityColumn
{
ColumnName = "confirmed",
PropertyName = "Confirmed",
DataType = "bool",
DbDataType = "bool",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "confirmed_on",
PropertyName = "ConfirmedOn",
DataType = "DateTime",
DbDataType = "timestamptz",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
}
}
};
}
/// <summary>
/// Counts the number of reset requests.
/// </summary>
/// <returns>Returns the count of the reset requests.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/account/reset-request/count")]
[RestAuthorize]
public long Count()
{
try
{
return this.ResetRequestRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of reset request.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/account/reset-request/all")]
[RestAuthorize]
public IEnumerable<Frapid.Account.Entities.ResetRequest> GetAll()
{
try
{
return this.ResetRequestRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of reset request for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/account/reset-request/export")]
[RestAuthorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.ResetRequestRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of reset request.
/// </summary>
/// <param name="requestId">Enter RequestId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{requestId}")]
[Route("~/api/account/reset-request/{requestId}")]
[RestAuthorize]
public Frapid.Account.Entities.ResetRequest Get(System.Guid requestId)
{
try
{
return this.ResetRequestRepository.Get(requestId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/account/reset-request/get")]
[RestAuthorize]
public IEnumerable<Frapid.Account.Entities.ResetRequest> Get([FromUri] System.Guid[] requestIds)
{
try
{
return this.ResetRequestRepository.Get(requestIds);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of reset request.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/account/reset-request/first")]
[RestAuthorize]
public Frapid.Account.Entities.ResetRequest GetFirst()
{
try
{
return this.ResetRequestRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of reset request.
/// </summary>
/// <param name="requestId">Enter RequestId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{requestId}")]
[Route("~/api/account/reset-request/previous/{requestId}")]
[RestAuthorize]
public Frapid.Account.Entities.ResetRequest GetPrevious(System.Guid requestId)
{
try
{
return this.ResetRequestRepository.GetPrevious(requestId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of reset request.
/// </summary>
/// <param name="requestId">Enter RequestId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{requestId}")]
[Route("~/api/account/reset-request/next/{requestId}")]
[RestAuthorize]
public Frapid.Account.Entities.ResetRequest GetNext(System.Guid requestId)
{
try
{
return this.ResetRequestRepository.GetNext(requestId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of reset request.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/account/reset-request/last")]
[RestAuthorize]
public Frapid.Account.Entities.ResetRequest GetLast()
{
try
{
return this.ResetRequestRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 reset requests on each page, sorted by the property RequestId.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/account/reset-request")]
[RestAuthorize]
public IEnumerable<Frapid.Account.Entities.ResetRequest> GetPaginatedResult()
{
try
{
return this.ResetRequestRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 reset requests on each page, sorted by the property RequestId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/account/reset-request/page/{pageNumber}")]
[RestAuthorize]
public IEnumerable<Frapid.Account.Entities.ResetRequest> GetPaginatedResult(long pageNumber)
{
try
{
return this.ResetRequestRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of reset requests using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered reset requests.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/account/reset-request/count-where")]
[RestAuthorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.ResetRequestRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 reset requests on each page, sorted by the property RequestId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/account/reset-request/get-where/{pageNumber}")]
[RestAuthorize]
public IEnumerable<Frapid.Account.Entities.ResetRequest> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.ResetRequestRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of reset requests using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered reset requests.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/account/reset-request/count-filtered/{filterName}")]
[RestAuthorize]
public long CountFiltered(string filterName)
{
try
{
return this.ResetRequestRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 reset requests on each page, sorted by the property RequestId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/account/reset-request/get-filtered/{pageNumber}/{filterName}")]
[RestAuthorize]
public IEnumerable<Frapid.Account.Entities.ResetRequest> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.ResetRequestRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of reset requests.
/// </summary>
/// <returns>Returns an enumerable key/value collection of reset requests.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/account/reset-request/display-fields")]
[RestAuthorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.ResetRequestRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for reset requests.
/// </summary>
/// <returns>Returns an enumerable custom field collection of reset requests.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/account/reset-request/custom-fields")]
[RestAuthorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.ResetRequestRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for reset requests.
/// </summary>
/// <returns>Returns an enumerable custom field collection of reset requests.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/account/reset-request/custom-fields/{resourceId}")]
[RestAuthorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.ResetRequestRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of ResetRequest class.
/// </summary>
/// <param name="resetRequest">Your instance of reset requests class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/account/reset-request/add-or-edit")]
[RestAuthorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic resetRequest = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (resetRequest == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.ResetRequestRepository.AddOrEdit(resetRequest, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of ResetRequest class.
/// </summary>
/// <param name="resetRequest">Your instance of reset requests class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{resetRequest}")]
[Route("~/api/account/reset-request/add/{resetRequest}")]
[RestAuthorize]
public void Add(Frapid.Account.Entities.ResetRequest resetRequest)
{
if (resetRequest == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.ResetRequestRepository.Add(resetRequest);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of ResetRequest class.
/// </summary>
/// <param name="resetRequest">Your instance of ResetRequest class to edit.</param>
/// <param name="requestId">Enter the value for RequestId in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{requestId}")]
[Route("~/api/account/reset-request/edit/{requestId}")]
[RestAuthorize]
public void Edit(System.Guid requestId, [FromBody] Frapid.Account.Entities.ResetRequest resetRequest)
{
if (resetRequest == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.ResetRequestRepository.Update(resetRequest, requestId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of ResetRequest class.
/// </summary>
/// <param name="collection">Your collection of ResetRequest class to bulk import.</param>
/// <returns>Returns list of imported requestIds.</returns>
/// <exception cref="DataAccessException">Thrown when your any ResetRequest class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/account/reset-request/bulk-import")]
[RestAuthorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> resetRequestCollection = this.ParseCollection(collection);
if (resetRequestCollection == null || resetRequestCollection.Count.Equals(0))
{
return null;
}
try
{
return this.ResetRequestRepository.BulkImport(resetRequestCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of ResetRequest class via RequestId.
/// </summary>
/// <param name="requestId">Enter the value for RequestId in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{requestId}")]
[Route("~/api/account/reset-request/delete/{requestId}")]
[RestAuthorize]
public void Delete(System.Guid requestId)
{
try
{
this.ResetRequestRepository.Delete(requestId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
}
}
| |
/*
* 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 OpenMetaverse;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace OpenSim.Framework.Console
{
public class ConsoleUtil
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Used by modules to display stock co-ordinate help, though possibly this should be under some general section
/// rather than in each help summary.
/// </summary>
public const string CoordHelp
= @"Each component of the coord is comma separated. There must be no spaces between the commas.
If you don't care about the z component you can simply omit it.
If you don't care about the x or y components then you can leave them blank (though a comma is still required)
If you want to specify the maximum value of a component then you can use ~ instead of a number
If you want to specify the minimum value of a component then you can use -~ instead of a number
e.g.
show object pos 20,20,20 to 40,40,40
delete object pos 20,20 to 40,40
show object pos ,20,20 to ,40,40
delete object pos ,,30 to ,,~
show object pos ,,-~ to ,,30";
public const int LocalIdNotFound = 0;
public const string MaxRawConsoleVectorValue = "~";
public const string MinRawConsoleVectorValue = "-~";
public const string VectorSeparator = ",";
public static char[] VectorSeparatorChars = VectorSeparator.ToCharArray();
/// <summary>
/// Check if the given file path exists.
/// </summary>
/// <remarks>If not, warning is printed to the given console.</remarks>
/// <returns>true if the file does not exist, false otherwise.</returns>
/// <param name='console'></param>
/// <param name='path'></param>
public static bool CheckFileDoesNotExist(ICommandConsole console, string path)
{
if (File.Exists(path))
{
console.OutputFormat("File {0} already exists. Please move or remove it.", path);
return false;
}
return true;
}
/// <summary>
/// Convert a console integer to an int, automatically complaining if a console is given.
/// </summary>
/// <param name='console'>Can be null if no console is available.</param>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleBool(ICommandConsole console, string rawConsoleString, out bool b)
{
if (!bool.TryParse(rawConsoleString, out b))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a true or false value", rawConsoleString);
return false;
}
return true;
}
/// <summary>
/// Tries to parse the input as either a UUID or a local ID.
/// </summary>
/// <returns>true if parsing succeeded, false otherwise.</returns>
/// <param name='console'></param>
/// <param name='rawId'></param>
/// <param name='uuid'></param>
/// <param name='localId'>
/// Will be set to ConsoleUtil.LocalIdNotFound if parsing result was a UUID or no parse succeeded.
/// </param>
public static bool TryParseConsoleId(ICommandConsole console, string rawId, out UUID uuid, out uint localId)
{
if (TryParseConsoleUuid(null, rawId, out uuid))
{
localId = LocalIdNotFound;
return true;
}
if (TryParseConsoleLocalId(null, rawId, out localId))
{
return true;
}
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid UUID or local id", rawId);
return false;
}
/// <summary>
/// Convert a console integer to an int, automatically complaining if a console is given.
/// </summary>
/// <param name='console'>Can be null if no console is available.</param>
/// <param name='rawConsoleInt'>/param>
/// <param name='i'></param>
/// <returns></returns>
public static bool TryParseConsoleInt(ICommandConsole console, string rawConsoleInt, out int i)
{
if (!int.TryParse(rawConsoleInt, out i))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid integer", rawConsoleInt);
return false;
}
return true;
}
public static bool TryParseConsoleLocalId(ICommandConsole console, string rawLocalId, out uint localId)
{
if (!uint.TryParse(rawLocalId, out localId))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid local id", localId);
return false;
}
if (localId == 0)
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid local id - it must be greater than 0", localId);
return false;
}
return true;
}
/// <summary>
/// Convert a maximum vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleMaxVector(string rawConsoleVector, out Vector3 vector)
{
return TryParseConsoleVector(rawConsoleVector, c => float.MaxValue.ToString(), out vector);
}
/// <summary>
/// Convert a minimum vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleMinVector(string rawConsoleVector, out Vector3 vector)
{
return TryParseConsoleVector(rawConsoleVector, c => float.MinValue.ToString(), out vector);
}
/// <summary>
/// Convert a console integer to a natural int, automatically complaining if a console is given.
/// </summary>
/// <param name='console'>Can be null if no console is available.</param>
/// <param name='rawConsoleInt'>/param>
/// <param name='i'></param>
/// <returns></returns>
public static bool TryParseConsoleNaturalInt(ICommandConsole console, string rawConsoleInt, out int i)
{
if (TryParseConsoleInt(console, rawConsoleInt, out i))
{
if (i < 0)
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a positive integer", rawConsoleInt);
return false;
}
return true;
}
return false;
}
/// <summary>
/// Try to parse a console UUID from the console.
/// </summary>
/// <remarks>
/// Will complain to the console if parsing fails.
/// </remarks>
/// <returns></returns>
/// <param name='console'>If null then no complaint is printed.</param>
/// <param name='rawUuid'></param>
/// <param name='uuid'></param>
public static bool TryParseConsoleUuid(ICommandConsole console, string rawUuid, out UUID uuid)
{
if (!UUID.TryParse(rawUuid, out uuid))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid uuid", rawUuid);
return false;
}
return true;
}
/// <summary>
/// Convert a vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>
/// A string in the form <x>,<y>,<z> where there is no space between values.
/// Any component can be missing (e.g. ,,40). blankComponentFunc is invoked to replace the blank with a suitable value
/// Also, if the blank component is at the end, then the comma can be missed off entirely (e.g. 40,30 or 40)
/// The strings "~" and "-~" are valid in components. The first substitutes float.MaxValue whilst the second is float.MinValue
/// Other than that, component values must be numeric.
/// </param>
/// <param name='blankComponentFunc'></param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleVector(
string rawConsoleVector, Func<string, string> blankComponentFunc, out Vector3 vector)
{
List<string> components = rawConsoleVector.Split(VectorSeparatorChars).ToList();
if (components.Count < 1 || components.Count > 3)
{
vector = Vector3.Zero;
return false;
}
for (int i = components.Count; i < 3; i++)
components.Add("");
List<string> semiDigestedComponents
= components.ConvertAll<string>(
c =>
{
if (c == "")
return blankComponentFunc.Invoke(c);
else if (c == MaxRawConsoleVectorValue)
return float.MaxValue.ToString();
else if (c == MinRawConsoleVectorValue)
return float.MinValue.ToString();
else
return c;
});
string semiDigestedConsoleVector = string.Join(VectorSeparator, semiDigestedComponents.ToArray());
// m_log.DebugFormat("[CONSOLE UTIL]: Parsing {0} into OpenMetaverse.Vector3", semiDigestedConsoleVector);
return Vector3.TryParse(semiDigestedConsoleVector, out vector);
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.LambdaSimplifier
{
// [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.SimplifyLambda)]
internal partial class LambdaSimplifierCodeRefactoringProvider : CodeRefactoringProvider
{
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
var textSpan = context.Span;
var cancellationToken = context.CancellationToken;
if (cancellationToken.IsCancellationRequested)
{
return;
}
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var lambda = semanticDocument.Root.FindToken(textSpan.Start).GetAncestor(n =>
n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax);
if (lambda == null || !lambda.Span.IntersectsWith(textSpan.Start))
{
return;
}
if (!CanSimplify(semanticDocument, lambda as SimpleLambdaExpressionSyntax, cancellationToken) &&
!CanSimplify(semanticDocument, lambda as ParenthesizedLambdaExpressionSyntax, cancellationToken))
{
return;
}
context.RegisterRefactoring(
new MyCodeAction(
CSharpFeaturesResources.SimplifyLambdaExpression,
(c) => SimplifyLambdaAsync(document, lambda, c)));
context.RegisterRefactoring(
new MyCodeAction(
CSharpFeaturesResources.SimplifyAllOccurrences,
(c) => SimplifyAllLambdasAsync(document, c)));
}
private async Task<Document> SimplifyLambdaAsync(
Document document,
SyntaxNode lambda,
CancellationToken cancellationToken)
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var rewriter = new Rewriter(this, semanticDocument, (n) => n == lambda, cancellationToken);
var result = rewriter.Visit(semanticDocument.Root);
return document.WithSyntaxRoot(result);
}
private async Task<Document> SimplifyAllLambdasAsync(
Document document,
CancellationToken cancellationToken)
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var rewriter = new Rewriter(this, semanticDocument, (n) => true, cancellationToken);
var result = rewriter.Visit(semanticDocument.Root);
return document.WithSyntaxRoot(result);
}
private static bool CanSimplify(
SemanticDocument document,
SimpleLambdaExpressionSyntax node,
CancellationToken cancellationToken)
{
if (node == null)
{
return false;
}
var paramName = node.Parameter.Identifier;
var invocation = TryGetInvocationExpression(node.Body);
return CanSimplify(document, node, new List<SyntaxToken>() { paramName }, invocation, cancellationToken);
}
private static bool CanSimplify(
SemanticDocument document,
ParenthesizedLambdaExpressionSyntax node,
CancellationToken cancellationToken)
{
if (node == null)
{
return false;
}
var paramNames = node.ParameterList.Parameters.Select(p => p.Identifier).ToList();
var invocation = TryGetInvocationExpression(node.Body);
return CanSimplify(document, node, paramNames, invocation, cancellationToken);
}
private static bool CanSimplify(
SemanticDocument document,
ExpressionSyntax lambda,
List<SyntaxToken> paramNames,
InvocationExpressionSyntax invocation,
CancellationToken cancellationToken)
{
if (invocation == null)
{
return false;
}
if (invocation.ArgumentList.Arguments.Count != paramNames.Count)
{
return false;
}
for (var i = 0; i < paramNames.Count; i++)
{
var argument = invocation.ArgumentList.Arguments[i];
if (argument.NameColon != null ||
argument.RefOrOutKeyword.Kind() != SyntaxKind.None ||
!argument.Expression.IsKind(SyntaxKind.IdentifierName))
{
return false;
}
var identifierName = (IdentifierNameSyntax)argument.Expression;
if (identifierName.Identifier.ValueText != paramNames[i].ValueText)
{
return false;
}
}
var semanticModel = document.SemanticModel;
var lambdaSemanticInfo = semanticModel.GetSymbolInfo(lambda, cancellationToken);
var invocationSemanticInfo = semanticModel.GetSymbolInfo(invocation, cancellationToken);
if (lambdaSemanticInfo.Symbol == null ||
invocationSemanticInfo.Symbol == null)
{
// Don't offer this if there are any errors or ambiguities.
return false;
}
var lambdaMethod = lambdaSemanticInfo.Symbol as IMethodSymbol;
var invocationMethod = invocationSemanticInfo.Symbol as IMethodSymbol;
if (lambdaMethod == null || invocationMethod == null)
{
return false;
}
// TODO(cyrusn): Handle extension methods as well.
if (invocationMethod.IsExtensionMethod)
{
return false;
}
// Check if any of the parameter is of Type Dynamic
foreach (var parameter in lambdaMethod.Parameters)
{
if (parameter.Type != null && parameter.Type.Kind == SymbolKind.DynamicType)
{
return false;
}
}
// Check if the parameter and return types match between the lambda and the
// invocation. Note: return types can be covariant and argument types can be
// contravariant.
if (lambdaMethod.ReturnsVoid != invocationMethod.ReturnsVoid ||
lambdaMethod.Parameters.Length != invocationMethod.Parameters.Length)
{
return false;
}
if (!lambdaMethod.ReturnsVoid)
{
// Return type has to be covariant.
var conversion = document.SemanticModel.Compilation.ClassifyConversion(
invocationMethod.ReturnType, lambdaMethod.ReturnType);
if (!conversion.IsIdentityOrImplicitReference())
{
return false;
}
}
// Parameter types have to be contravariant.
for (int i = 0; i < lambdaMethod.Parameters.Length; i++)
{
var conversion = document.SemanticModel.Compilation.ClassifyConversion(
lambdaMethod.Parameters[i].Type, invocationMethod.Parameters[i].Type);
if (!conversion.IsIdentityOrImplicitReference())
{
return false;
}
}
if (WouldCauseAmbiguity(lambda, invocation, semanticModel, cancellationToken))
{
return false;
}
// Looks like something we can simplify.
return true;
}
// Ensure that if we replace the invocation with its expression that its expression will
// bind unambiguously. This can happen with awesome cases like:
#if false
static void Foo<T>(T x) where T : class { }
static void Bar(Action<int> x) { }
static void Bar(Action<string> x) { }
static void Main()
{
Bar(x => Foo(x)); // error CS0121: The call is ambiguous between the following methods or properties: 'A.Bar(System.Action<int>)' and 'A.Bar(System.Action<string>)'
}
#endif
private static bool WouldCauseAmbiguity(
ExpressionSyntax lambda,
InvocationExpressionSyntax invocation,
SemanticModel oldSemanticModel,
CancellationToken cancellationToken)
{
var annotation = new SyntaxAnnotation();
// In order to check if there will be a problem, we actually make the change, fork the
// compilation, and then verify that the new expression bound unambiguously.
var oldExpression = invocation.Expression.WithAdditionalAnnotations(annotation);
var oldCompilation = oldSemanticModel.Compilation;
var oldTree = oldSemanticModel.SyntaxTree;
var oldRoot = oldTree.GetRoot(cancellationToken);
var newRoot = oldRoot.ReplaceNode(lambda, oldExpression);
var newTree = oldTree.WithRootAndOptions(newRoot, oldTree.Options);
var newCompilation = oldCompilation.ReplaceSyntaxTree(oldTree, newTree);
var newExpression = newTree.GetRoot(cancellationToken).GetAnnotatedNodesAndTokens(annotation).First().AsNode();
var newSemanticModel = newCompilation.GetSemanticModel(newTree);
var info = newSemanticModel.GetSymbolInfo(newExpression, cancellationToken);
return info.CandidateReason != CandidateReason.None;
}
private static InvocationExpressionSyntax TryGetInvocationExpression(
SyntaxNode lambdaBody)
{
if (lambdaBody is ExpressionSyntax)
{
return ((ExpressionSyntax)lambdaBody).WalkDownParentheses() as InvocationExpressionSyntax;
}
else if (lambdaBody is BlockSyntax)
{
var block = (BlockSyntax)lambdaBody;
if (block.Statements.Count == 1)
{
var statement = block.Statements.First();
if (statement is ReturnStatementSyntax)
{
return ((ReturnStatementSyntax)statement).Expression.WalkDownParentheses() as InvocationExpressionSyntax;
}
else if (statement is ExpressionStatementSyntax)
{
return ((ExpressionStatementSyntax)statement).Expression.WalkDownParentheses() as InvocationExpressionSyntax;
}
}
}
return null;
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) :
base(title, createChangedDocument)
{
}
}
}
}
| |
//
// 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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Encog.Util.Logging;
namespace Encog.Cloud.Indicator.Server
{
/// <summary>
/// The Encog Indicator server. This allows the Encog Framework Indicator to be
/// used in a trading platform, such as NinjaTrader or MT4/5. The remote indicator
/// is always created in whatever native language the trading platform requires. Then
/// a socketed connection is made back to Encog.
/// </summary>
public class IndicatorServer
{
/// <summary>
/// The default port.
/// </summary>
public const int StandardEncogPort = 5128;
/// <summary>
/// The connections that have been made to the server.
/// </summary>
private readonly IList<HandleClient> _connections = new List<HandleClient>();
/// <summary>
/// The indicator factories by name.
/// </summary>
private readonly IDictionary<string, IIndicatorFactory> _factoryMap = new Dictionary<String, IIndicatorFactory>();
/// <summary>
/// All registered listeners.
/// </summary>
private readonly IList<IIndicatorConnectionListener> _listeners = new List<IIndicatorConnectionListener>();
/// <summary>
/// The port actually being used.
/// </summary>
private readonly int _port;
/// <summary>
/// The socket that we are listening on.
/// </summary>
private Socket _listenSocket;
/// <summary>
/// True, if the server is running.
/// </summary>
private bool _running;
/// <summary>
/// The background thread used to listen.
/// </summary>
private Thread _thread;
/// <summary>
/// Construct a server.
/// </summary>
/// <param name="p">The port.</param>
public IndicatorServer(int p)
{
_port = p;
}
/// <summary>
/// Construct a server, and use the standard port (5128).
/// </summary>
public IndicatorServer()
: this(StandardEncogPort)
{
}
/// <summary>
/// The port the server is listening on.
/// </summary>
public int Port
{
get { return _port; }
}
/// <summary>
/// The connections.
/// </summary>
public IList<HandleClient> Connections
{
get { return _connections; }
}
/// <summary>
/// The connection listeners.
/// </summary>
public IList<IIndicatorConnectionListener> Listeners
{
get { return _listeners; }
}
/// <summary>
/// Background thread.
/// </summary>
public void Run()
{
try
{
_running = true;
_listenSocket.Listen(5);
while (_running)
{
try
{
EncogLogging.Log(EncogLogging.LevelDebug, "Begin listen");
Socket connectionSocket = _listenSocket.Accept();
EncogLogging.Log(EncogLogging.LevelDebug, "Connection from: " + connectionSocket.RemoteEndPoint);
var link = new IndicatorLink(this, connectionSocket);
NotifyListenersConnections(link, true);
var hc = new HandleClient(this, link);
_connections.Add(hc);
var t = new Thread(hc.Run);
t.Start();
}
catch (SocketException)
{
// just accept timing out
Thread.Sleep(100);
}
catch (IOException ex)
{
throw new IndicatorError(ex);
}
}
try
{
_listenSocket.Close();
}
catch (IOException ex)
{
throw new IndicatorError(ex);
}
}
finally
{
_running = false;
}
}
/// <summary>
/// Start the server.
/// </summary>
public void Start()
{
try
{
_running = true;
_listenSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
_listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, _port));
_listenSocket.Blocking = false;
_thread = new Thread(Run);
_thread.Start();
}
catch (IOException ex)
{
throw new IndicatorError(ex);
}
}
/// <summary>
/// Shutdown the server.
/// </summary>
public void Shutdown()
{
_running = false;
}
/// <summary>
/// Add a listener.
/// </summary>
/// <param name="listener">The listener to add.</param>
public void AddListener(IIndicatorConnectionListener listener)
{
_listeners.Add(listener);
}
/// <summary>
/// Remove a listener.
/// </summary>
/// <param name="listener">The listener to remove.</param>
public void RemoveListener(IIndicatorConnectionListener listener)
{
_listeners.Remove(listener);
}
/// <summary>
/// Clear the listeners.
/// </summary>
public void ClearListeners()
{
_listeners.Clear();
}
/// <summary>
/// Notify connection listeners.
/// </summary>
/// <param name="link">The link.</param>
/// <param name="hasOpened">Is a connection open?</param>
public void NotifyListenersConnections(IndicatorLink link, bool hasOpened)
{
Object[] list = _listeners.ToArray();
foreach (object t in list)
{
var listener = (IIndicatorConnectionListener) t;
listener.NotifyConnections(link, hasOpened);
}
}
/// <summary>
/// Add an indicator factory.
/// </summary>
/// <param name="ind">The factory to add.</param>
public void AddIndicatorFactory(IIndicatorFactory ind)
{
_factoryMap[ind.Name] = ind;
}
/// <summary>
/// Wait for an indicator to first startup, and then return when that
/// indicator completes. Block until all of this completes.
/// </summary>
public void WaitForIndicatorCompletion()
{
// first wait for at least one indicator to start up
while (_connections.Count == 0)
{
Thread.Sleep(1000);
}
// now wait for indicators to go to zero
while (_connections.Count != 0)
{
Thread.Sleep(1000);
}
// shutdown
Shutdown();
}
/// <summary>
/// Create the specified indicator, if indicatorName is "default" and there is only
/// one indicator, then use that indicator.
/// </summary>
/// <param name="indicatorName">The name of the indicator.</param>
/// <returns>The indicator.</returns>
public IIndicatorListener ResolveIndicator(String indicatorName)
{
if (_factoryMap.Count == 0)
{
throw new IndicatorError("No indicators defined.");
}
if (string.Compare(indicatorName, "default") == 0)
{
if (_factoryMap.Count > 1)
{
throw new IndicatorError("Default indicator requested, but more than one indicator defined.");
}
return _factoryMap.Values.First().Create();
}
if (!_factoryMap.ContainsKey(indicatorName))
{
throw new IndicatorError("Unknown indicator: " + indicatorName);
}
return _factoryMap[indicatorName].Create();
}
/// <summary>
/// Wait for the server to shutdown.
/// </summary>
public void WaitForShutdown()
{
while (_running)
{
Thread.Sleep(1000);
}
}
}
}
| |
/*****************************************************************************
* Ngaro for Mono / .NET
*
* Copyright (c) 2009 - 2011, Simon Waite and Charles Childers
*
* Please compile with `gmcs` as `mcs` seems to have a
* simple Console.in implementation.
*****************************************************************************/
using System;
using System.IO;
using System.Text;
namespace Retro.Ngaro
{
public class VM
{
/* Registers */
int sp, rsp, ip, shrink;
int[] data, address, ports, memory;
/* Input Stack */
string[] inputs;
int[] lengths;
int isp, offset;
/* Opcodes recognized by the VM */
enum OpCodes {
VM_NOP, VM_LIT, VM_DUP,
VM_DROP, VM_SWAP, VM_PUSH,
VM_POP, VM_LOOP, VM_JUMP,
VM_RETURN, VM_GT_JUMP, VM_LT_JUMP,
VM_NE_JUMP, VM_EQ_JUMP, VM_FETCH,
VM_STORE, VM_ADD, VM_SUB,
VM_MUL, VM_DIVMOD, VM_AND,
VM_OR, VM_XOR, VM_SHL,
VM_SHR, VM_ZERO_EXIT, VM_INC,
VM_DEC, VM_IN, VM_OUT,
VM_WAIT
}
/* Initialize the VM */
public VM() {
sp = 0;
rsp = 0;
ip = 0;
data = new int[128];
address = new int[1024];
ports = new int[12];
memory = new int[1000000];
inputs = new string[12];
lengths = new int[12];
isp = 0;
offset = 0;
loadImage();
if (memory[0] == 0) {
Console.Write("Sorry, unable to find retroImage\n");
Environment.Exit(0);
}
}
/* Load the 'retroImage' into memory */
public void loadImage() {
int i = 0;
if (!File.Exists("retroImage"))
return;
BinaryReader binReader = new BinaryReader(File.Open("retroImage", FileMode.Open));
FileInfo f = new FileInfo("retroImage");
long s = f.Length / 4;
try {
while (i < s) { memory[i] = binReader.ReadInt32(); i++; }
}
catch(EndOfStreamException e) {
Console.WriteLine("{0} caught and ignored." , e.GetType().Name);
}
finally {
binReader.Close();
}
}
/* Save the image */
public void saveImage() {
int i = 0, j = 1000000;
BinaryWriter binWriter = new BinaryWriter(File.Open("retroImage", FileMode.Create));
try {
if (shrink != 0)
j = memory[3];
while (i < j) { binWriter.Write(memory[i]); i++; }
}
catch(EndOfStreamException e) {
Console.WriteLine("{0} caught and ignored." , e.GetType().Name);
}
finally {
binWriter.Close();
}
}
/* Read a key */
public int read_key() {
int a = 0;
/* Check to see if we need to move to the next input source */
if (isp > 0 && offset == lengths[isp]) {
isp--;
offset = 0;
}
if (isp > 0) { /* Read from a file */
a = (int)inputs[isp][offset];
offset++;
}
else { /* Read from Console */
ConsoleKeyInfo cki = Console.ReadKey();
a = (int)cki.KeyChar;
if (cki.Key == ConsoleKey.Backspace) {
a = 8;
Console.Write((char)32);
}
if ( a >= 32)
Console.Write((char)8);
}
return a;
}
/* Handle I/O device emulation */
public void HandleDevices() {
if (ports[0] == 1)
return;
ports[0] = 1;
/* Read from input source */
if (ports[1] == 1) {
int a = read_key();
ports[1] = a;
}
/* Write to display */
if (ports[2] == 1) {
char c = (char)data[sp];
if (data[sp] < 0)
Console.Clear();
else
Console.Write(c);
sp--;
ports[2] = 0;
}
/* File Operations: Save Image */
if (ports[4] == 1) {
saveImage();
ports[4] = 0;
}
/* File Operations: Add to Input Stack */
if (ports[4] == 2) {
ports[4] = 0;
int i = 0;
char[] s = new char[1024];
int name = data[sp]; sp--;
while(memory[name] != 0) {
s[i] = (char)memory[name];
i++; name++;
}
isp++;
inputs[isp] = System.IO.File.ReadAllText(new String(s,0,i));
lengths[isp] = inputs[isp].Length;
}
/* Capabilities */
if (ports[5] == -1)
ports[5] = 1000000;
if (ports[5] == -2)
ports[5] = 0;
if (ports[5] == -3)
ports[5] = 0;
if (ports[5] == -4)
ports[5] = 0;
if (ports[5] == -5)
ports[5] = sp;
if (ports[5] == -6)
ports[5] = rsp;
if (ports[5] == -7)
ports[5] = 0;
if (ports[5] == -8) {
int unixTime = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
ports[5] = unixTime;
}
if (ports[5] == -9) {
ports[5] = 0;
ip = 1000000;
}
if (ports[5] == -10) {
char[] s = new char[1024];
int name = data[sp]; sp--;
int i = 0;
while(memory[name] != 0) {
s[i] = (char)memory[name];
i++; name++;
}
byte[] array = Encoding.ASCII.GetBytes(Environment.GetEnvironmentVariable(new String(s,0,i)));
name = data[sp]; sp--;
foreach (byte element in array) {
memory[name] = (int)element;
name++;
}
memory[name] = 0;
ports[5] = 0;
}
if (ports[5] == -11)
ports[5] = Console.WindowWidth;
if (ports[5] == -12)
ports[5] = Console.WindowHeight;
}
/* Process the current opcode */
public void Process() {
int x, y;
switch((OpCodes)memory[ip])
{
case OpCodes.VM_NOP:
break;
case OpCodes.VM_LIT:
sp++; ip++; data[sp] = memory[ip];
break;
case OpCodes.VM_DUP:
sp++; data[sp] = data[sp-1];
break;
case OpCodes.VM_DROP:
data[sp] = 0; sp--;
break;
case OpCodes.VM_SWAP:
x = data[sp];
y = data[sp-1];
data[sp] = y;
data[sp-1] = x;
break;
case OpCodes.VM_PUSH:
rsp++;
address[rsp] = data[sp];
sp--;
break;
case OpCodes.VM_POP:
sp++;
data[sp] = address[rsp];
rsp--;
break;
case OpCodes.VM_LOOP:
data[sp]--;
if (data[sp] != 0 && data[sp] > -1)
ip = memory[ip + 1] - 1;
else {
ip++;
sp--;
}
break;
case OpCodes.VM_JUMP:
ip++;
ip = memory[ip] - 1;
if (memory[ip+1] == 0)
ip++;
if (memory[ip+1] == 0)
ip++;
break;
case OpCodes.VM_RETURN:
ip = address[rsp]; rsp--;
break;
case OpCodes.VM_GT_JUMP:
ip++;
if (data[sp-1] > data[sp])
ip = memory[ip] - 1;
sp = sp - 2;
break;
case OpCodes.VM_LT_JUMP:
ip++;
if (data[sp-1] < data[sp])
ip = memory[ip] - 1;
sp = sp - 2;
break;
case OpCodes.VM_NE_JUMP:
ip++;
if (data[sp-1] != data[sp])
ip = memory[ip] - 1;
sp = sp - 2;
break;
case OpCodes.VM_EQ_JUMP:
ip++;
if (data[sp-1] == data[sp])
ip = memory[ip] - 1;
sp = sp - 2;
break;
case OpCodes.VM_FETCH:
x = data[sp];
data[sp] = memory[x];
break;
case OpCodes.VM_STORE:
memory[data[sp]] = data[sp-1];
sp = sp - 2;
break;
case OpCodes.VM_ADD:
data[sp-1] += data[sp]; data[sp] = 0; sp--;
break;
case OpCodes.VM_SUB:
data[sp-1] -= data[sp]; data[sp] = 0; sp--;
break;
case OpCodes.VM_MUL:
data[sp-1] *= data[sp]; data[sp] = 0; sp--;
break;
case OpCodes.VM_DIVMOD:
x = data[sp];
y = data[sp-1];
data[sp] = y / x;
data[sp-1] = y % x;
break;
case OpCodes.VM_AND:
x = data[sp];
y = data[sp-1];
sp--;
data[sp] = x & y;
break;
case OpCodes.VM_OR:
x = data[sp];
y = data[sp-1];
sp--;
data[sp] = x | y;
break;
case OpCodes.VM_XOR:
x = data[sp];
y = data[sp-1];
sp--;
data[sp] = x ^ y;
break;
case OpCodes.VM_SHL:
x = data[sp];
y = data[sp-1];
sp--;
data[sp] = y << x;
break;
case OpCodes.VM_SHR:
x = data[sp];
y = data[sp-1];
sp--;
data[sp] = y >>= x;
break;
case OpCodes.VM_ZERO_EXIT:
if (data[sp] == 0) {
sp--;
ip = address[rsp]; rsp--;
}
break;
case OpCodes.VM_INC:
data[sp]++;
break;
case OpCodes.VM_DEC:
data[sp]--;
break;
case OpCodes.VM_IN:
x = data[sp];
data[sp] = ports[x];
ports[x] = 0;
break;
case OpCodes.VM_OUT:
ports[data[sp]] = data[sp-1];
sp = sp - 2;
break;
case OpCodes.VM_WAIT:
HandleDevices();
break;
default:
rsp++;
address[rsp] = ip;
ip = memory[ip] - 1;
if (memory[ip+1] == 0)
ip++;
if (memory[ip+1] == 0)
ip++;
break;
}
}
/* Process the image until the IP reaches the end of memory */
public void Execute() {
for (; ip < 1000000; ip++)
Process();
}
/* Main entry point */
/* Calls all the other stuff and process the command line */
public static void Main(string [] args) {
VM vm = new VM();
vm.shrink = 0;
for (int i = 0; i < args.Length; i++) {
if (args[i] == "--shrink")
vm.shrink = 1;
if (args[i] == "--about") {
Console.Write("Retro Language [VM: C#, .NET]\n\n");
Environment.Exit(0);
}
if (args[i] == "--with") {
i++;
vm.isp++;
vm.inputs[vm.isp] = System.IO.File.ReadAllText(args[i]);
vm.lengths[vm.isp] = vm.inputs[vm.isp].Length;
}
}
vm.Execute();
}
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Swashbuckle.SwaggerGen.Annotations;
using SchoolBusAPI.Models;
using SchoolBusAPI.ViewModels;
using SchoolBusAPI.Services;
using SchoolBusAPI.Authorization;
namespace SchoolBusAPI.Controllers
{
/// <summary>
///
/// </summary>
public partial class RoleController : Controller
{
private readonly IRoleService _service;
/// <summary>
/// Create a controller and set the service
/// </summary>
public RoleController(IRoleService service)
{
_service = service;
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
/// <response code="201">Role created</response>
[HttpPost]
[Route("/api/rolepermissions/bulk")]
[SwaggerOperation("RolepermissionsBulkPost")]
[RequiresPermission(Permission.ADMIN)]
public virtual IActionResult RolepermissionsBulkPost([FromBody]RolePermission[] items)
{
return this._service.RolepermissionsBulkPostAsync(items);
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
/// <response code="201">Role created</response>
[HttpPost]
[Route("/api/roles/bulk")]
[SwaggerOperation("RolesBulkPost")]
[RequiresPermission(Permission.ADMIN)]
public virtual IActionResult RolesBulkPost([FromBody]Role[] items)
{
return this._service.RolesBulkPostAsync(items);
}
/// <summary>
///
/// </summary>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/roles")]
[SwaggerOperation("RolesGet")]
[SwaggerResponse(200, type: typeof(List<RoleViewModel>))]
public virtual IActionResult RolesGet()
{
return this._service.RolesGetAsync();
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Role to delete</param>
/// <response code="200">OK</response>
/// <response code="404">Role not found</response>
[HttpPost]
[Route("/api/roles/{id}/delete")]
[SwaggerOperation("RolesIdDeletePost")]
public virtual IActionResult RolesIdDeletePost([FromRoute]int id)
{
return this._service.RolesIdDeletePostAsync(id);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Role to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">Role not found</response>
[HttpGet]
[Route("/api/roles/{id}")]
[SwaggerOperation("RolesIdGet")]
[SwaggerResponse(200, type: typeof(RoleViewModel))]
public virtual IActionResult RolesIdGet([FromRoute]int id)
{
return this._service.RolesIdGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Get all the permissions for a role</remarks>
/// <param name="id">id of Role to fetch</param>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/roles/{id}/permissions")]
[SwaggerOperation("RolesIdPermissionsGet")]
[SwaggerResponse(200, type: typeof(List<PermissionViewModel>))]
public virtual IActionResult RolesIdPermissionsGet([FromRoute]int id)
{
return this._service.RolesIdPermissionsGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Adds a permissions to a role</remarks>
/// <param name="id">id of Role to update</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">Role not found</response>
[HttpPost]
[Route("/api/roles/{id}/permissions")]
[SwaggerOperation("RolesIdPermissionsPost")]
[SwaggerResponse(200, type: typeof(List<PermissionViewModel>))]
[RequiresPermission(Permission.ADMIN)]
public virtual IActionResult RolesIdPermissionsPost([FromRoute]int id, [FromBody]PermissionViewModel item)
{
return this._service.RolesIdPermissionsPostAsync(id, item);
}
/// <summary>
///
/// </summary>
/// <remarks>Updates the permissions for a role</remarks>
/// <param name="id">id of Role to update</param>
/// <param name="items"></param>
/// <response code="200">OK</response>
/// <response code="404">Role not found</response>
[HttpPut]
[Route("/api/roles/{id}/permissions")]
[SwaggerOperation("RolesIdPermissionsPut")]
[SwaggerResponse(200, type: typeof(List<PermissionViewModel>))]
[RequiresPermission(Permission.ADMIN)]
public virtual IActionResult RolesIdPermissionsPut([FromRoute]int id, [FromBody]PermissionViewModel[] items)
{
return this._service.RolesIdPermissionsPutAsync(id, items);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Role to fetch</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">Role not found</response>
[HttpPut]
[Route("/api/roles/{id}")]
[SwaggerOperation("RolesIdPut")]
[SwaggerResponse(200, type: typeof(RoleViewModel))]
public virtual IActionResult RolesIdPut([FromRoute]int id, [FromBody]RoleViewModel item)
{
return this._service.RolesIdPutAsync(id, item);
}
/// <summary>
///
/// </summary>
/// <remarks>Gets all the users for a role</remarks>
/// <param name="id">id of Role to fetch</param>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/roles/{id}/users")]
[SwaggerOperation("RolesIdUsersGet")]
[SwaggerResponse(200, type: typeof(List<UserRoleViewModel>))]
public virtual IActionResult RolesIdUsersGet([FromRoute]int id)
{
return this._service.RolesIdUsersGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Updates the users for a role</remarks>
/// <param name="id">id of Role to update</param>
/// <param name="items"></param>
/// <response code="200">OK</response>
/// <response code="404">Role not found</response>
[HttpPut]
[Route("/api/roles/{id}/users")]
[SwaggerOperation("RolesIdUsersPut")]
[SwaggerResponse(200, type: typeof(List<UserRoleViewModel>))]
[RequiresPermission(Permission.ADMIN)]
public virtual IActionResult RolesIdUsersPut([FromRoute]int id, [FromBody]UserRoleViewModel[] items)
{
return this._service.RolesIdUsersPutAsync(id, items);
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <response code="201">Role created</response>
[HttpPost]
[Route("/api/roles")]
[SwaggerOperation("RolesPost")]
[SwaggerResponse(200, type: typeof(RoleViewModel))]
public virtual IActionResult RolesPost([FromBody]RoleViewModel item)
{
return this._service.RolesPostAsync(item);
}
}
}
| |
//! \file ImageAJP.cs
//! \date Mon Sep 12 21:25:27 2016
//! \brief AliceSoft JPEG image.
//
// Copyright (C) 2016-2018 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Compression;
using GameRes.Utility;
namespace GameRes.Formats.AliceSoft
{
internal class AjpMetaData : ImageMetaData
{
public uint ImageOffset;
public uint ImageSize;
public uint AlphaOffset;
public uint AlphaSize;
public uint AlphaUnpacked;
}
[Export(typeof(ImageFormat))]
public class AjpFormat : ImageFormat
{
public override string Tag { get { return "AJP"; } }
public override string Description { get { return "AliceSoft JPEG image format"; } }
public override uint Signature { get { return 0x504A41; } } // 'AJP'
internal static byte[] Key = {
0x5D, 0x91, 0xAE, 0x87, 0x4A, 0x56, 0x41, 0xCD, 0x83, 0xEC, 0x4C, 0x92, 0xB5, 0xCB, 0x16, 0x34
};
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = stream.ReadHeader (0x24);
int version = header.ToInt32 (4);
if (version < 0)
return null;
var info = new AjpMetaData
{
Width = header.ToUInt32 (0xC),
Height = header.ToUInt32 (0x10),
BPP = 32,
ImageOffset = header.ToUInt32 (0x14),
ImageSize = header.ToUInt32 (0x18),
AlphaOffset = header.ToUInt32 (0x1C),
AlphaSize = header.ToUInt32 (0x20),
};
if (version > 0)
info.AlphaUnpacked = stream.ReadUInt32();
return info;
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
var meta = (AjpMetaData)info;
int stride = (int)meta.Width * 4;
byte[] pixels;
using (var jpeg = DecryptStream (stream.AsStream, meta.ImageOffset, meta.ImageSize))
{
var decoder = new JpegBitmapDecoder (jpeg,
BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
BitmapSource bitmap = decoder.Frames[0];
if (0 == meta.AlphaOffset || 0 == meta.AlphaSize)
{
bitmap.Freeze();
return new ImageData (bitmap, info);
}
if (bitmap.Format.BitsPerPixel != 32)
bitmap = new FormatConvertedBitmap (bitmap, PixelFormats.Bgr32, null, 0);
pixels = new byte[stride * (int)meta.Height];
bitmap.CopyPixels (pixels, stride, 0);
}
Stream mask = DecryptStream (stream.AsStream, meta.AlphaOffset, meta.AlphaSize);
byte[] alpha;
if (meta.AlphaUnpacked != 0)
{
using (mask = new ZLibStream (mask, CompressionMode.Decompress))
{
alpha = new byte[meta.AlphaUnpacked];
mask.Read (alpha, 0, alpha.Length);
}
}
else
{
using (mask)
{
alpha = ReadMask (mask);
}
}
int src = 0;
for (int dst = 3; dst < pixels.Length; dst += 4)
{
pixels[dst] = alpha[src++];
}
return ImageData.Create (info, PixelFormats.Bgra32, null, pixels, stride);
}
Stream DecryptStream (Stream input, uint offset, uint size)
{
var header = new byte[Key.Length];
input.Position = offset;
input.Read (header, 0, header.Length);
for (int i = 0; i < header.Length; ++i)
header[i] ^= Key[i];
if (size > header.Length)
{
var rest = new StreamRegion (input, input.Position, size - header.Length, true);
return new PrefixStream (header, rest);
}
else
return new MemoryStream (header, 0, (int)size);
}
byte[] ReadMask (Stream input)
{
var header = new byte[0x40];
input.Read (header, 0, header.Length);
int width = LittleEndian.ToInt32 (header, 0x18);
int height = LittleEndian.ToInt32 (header, 0x1C);
int data_offset = LittleEndian.ToInt32 (header, 0x20);
int pal_offset = LittleEndian.ToInt32 (header, 0x24);
var pixels = new byte[width * height];
int dst = 0;
input.Position = data_offset;
while (dst < pixels.Length)
{
int c = input.ReadByte();
if (-1 == c)
break;
if (c < 0xF8)
{
pixels[dst++] = (byte)c;
continue;
}
int count = 0;
switch (c)
{
case 0xF8:
pixels[dst++] = (byte)input.ReadByte();
break;
case 0xFC:
count = input.ReadByte();
input.Read (pixels, dst, 2);
count = count * 2 + 4;
Binary.CopyOverlapped (pixels, dst, dst+2, count);
dst += count+2;
break;
case 0xFD:
count = input.ReadByte() + 4;
byte b = (byte)input.ReadByte();
while (count --> 0)
pixels[dst++] = b;
break;
case 0xFE:
count = input.ReadByte() + 3;
Binary.CopyOverlapped (pixels, dst - width*2, dst, count);
dst += count;
break;
case 0xFF:
count = input.ReadByte() + 3;
Binary.CopyOverlapped (pixels, dst - width, dst, count);
dst += count;
break;
default:
throw new InvalidFormatException();
}
}
input.Position = pal_offset;
var index = ReadGrayPalette (input);
for (int i = 0; i < pixels.Length; ++i)
pixels[i] = index[pixels[i]];
return pixels;
}
byte[] ReadGrayPalette (Stream input)
{
var palette = new byte[0x300];
if (0x300 != input.Read (palette, 0, 0x300))
throw new EndOfStreamException();
var gray = new byte[0x100];
for (int i = 0; i < 0x100; ++i)
{
int c = i * 3;
gray[i] = (byte)((palette[c] + palette[c+1] + palette[c+2]) / 3);
}
return gray;
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("AjpFormat.Write not implemented");
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using System;
using System.Threading;
using Common.Logging;
using Quartz.Impl;
namespace Quartz.Examples.Example2
{
/// <summary>
/// This Example will demonstrate all of the basics of scheduling capabilities
/// of Quartz using Simple Triggers.
/// </summary>
/// <author>Bill Kratzer</author>
/// <author>Marko Lahma (.NET)</author>
public class SimpleTriggerExample : IExample
{
public string Name
{
get { return GetType().Name; }
}
public virtual void Run()
{
ILog log = LogManager.GetLogger(typeof (SimpleTriggerExample));
log.Info("------- Initializing -------------------");
// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory();
IScheduler sched = sf.GetScheduler();
log.Info("------- Initialization Complete --------");
log.Info("------- Scheduling Jobs ----------------");
// jobs can be scheduled before sched.start() has been called
// get a "nice round" time a few seconds in the future...
DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 15);
// job1 will only fire once at date/time "ts"
IJobDetail job = JobBuilder.Create<SimpleJob>()
.WithIdentity("job1", "group1")
.Build();
ISimpleTrigger trigger = (ISimpleTrigger) TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartAt(startTime)
.Build();
// schedule it to run!
DateTimeOffset? ft = sched.ScheduleJob(job, trigger);
log.Info(job.Key +
" will run at: " + ft +
" and repeat: " + trigger.RepeatCount +
" times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");
// job2 will only fire once at date/time "ts"
job = JobBuilder.Create<SimpleJob>()
.WithIdentity("job2", "group1")
.Build();
trigger = (ISimpleTrigger) TriggerBuilder.Create()
.WithIdentity("trigger2", "group1")
.StartAt(startTime)
.Build();
ft = sched.ScheduleJob(job, trigger);
log.Info(job.Key +
" will run at: " + ft +
" and repeat: " + trigger.RepeatCount +
" times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");
// job3 will run 11 times (run once and repeat 10 more times)
// job3 will repeat every 10 seconds
job = JobBuilder.Create<SimpleJob>()
.WithIdentity("job3", "group1")
.Build();
trigger = (ISimpleTrigger) TriggerBuilder.Create()
.WithIdentity("trigger3", "group1")
.StartAt(startTime)
.WithSimpleSchedule(x => x.WithIntervalInSeconds(10).WithRepeatCount(10))
.Build();
ft = sched.ScheduleJob(job, trigger);
log.Info(job.Key +
" will run at: " + ft +
" and repeat: " + trigger.RepeatCount +
" times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");
// the same job (job3) will be scheduled by a another trigger
// this time will only repeat twice at a 70 second interval
trigger = (ISimpleTrigger) TriggerBuilder.Create()
.WithIdentity("trigger3", "group2")
.StartAt(startTime)
.WithSimpleSchedule(x => x.WithIntervalInSeconds(10).WithRepeatCount(2))
.ForJob(job)
.Build();
ft = sched.ScheduleJob(trigger);
log.Info(job.Key +
" will [also] run at: " + ft +
" and repeat: " + trigger.RepeatCount +
" times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");
// job4 will run 6 times (run once and repeat 5 more times)
// job4 will repeat every 10 seconds
job = JobBuilder.Create<SimpleJob>()
.WithIdentity("job4", "group1")
.Build();
trigger = (ISimpleTrigger) TriggerBuilder.Create()
.WithIdentity("trigger4", "group1")
.StartAt(startTime)
.WithSimpleSchedule(x => x.WithIntervalInSeconds(10).WithRepeatCount(5))
.Build();
ft = sched.ScheduleJob(job, trigger);
log.Info(job.Key +
" will run at: " + ft +
" and repeat: " + trigger.RepeatCount +
" times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");
// job5 will run once, five minutes in the future
job = JobBuilder.Create<SimpleJob>()
.WithIdentity("job5", "group1")
.Build();
trigger = (ISimpleTrigger) TriggerBuilder.Create()
.WithIdentity("trigger5", "group1")
.StartAt(DateBuilder.FutureDate(5, IntervalUnit.Minute))
.Build();
ft = sched.ScheduleJob(job, trigger);
log.Info(job.Key +
" will run at: " + ft +
" and repeat: " + trigger.RepeatCount +
" times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");
// job6 will run indefinitely, every 40 seconds
job = JobBuilder.Create<SimpleJob>()
.WithIdentity("job6", "group1")
.Build();
trigger = (ISimpleTrigger) TriggerBuilder.Create()
.WithIdentity("trigger6", "group1")
.StartAt(startTime)
.WithSimpleSchedule(x => x.WithIntervalInSeconds(40).RepeatForever())
.Build();
ft = sched.ScheduleJob(job, trigger);
log.Info(job.Key +
" will run at: " + ft +
" and repeat: " + trigger.RepeatCount +
" times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");
log.Info("------- Starting Scheduler ----------------");
// All of the jobs have been added to the scheduler, but none of the jobs
// will run until the scheduler has been started
sched.Start();
log.Info("------- Started Scheduler -----------------");
// jobs can also be scheduled after start() has been called...
// job7 will repeat 20 times, repeat every five minutes
job = JobBuilder.Create<SimpleJob>()
.WithIdentity("job7", "group1")
.Build();
trigger = (ISimpleTrigger) TriggerBuilder.Create()
.WithIdentity("trigger7", "group1")
.StartAt(startTime)
.WithSimpleSchedule(x => x.WithIntervalInMinutes(5).WithRepeatCount(20))
.Build();
ft = sched.ScheduleJob(job, trigger);
log.Info(job.Key +
" will run at: " + ft +
" and repeat: " + trigger.RepeatCount +
" times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");
// jobs can be fired directly... (rather than waiting for a trigger)
job = JobBuilder.Create<SimpleJob>()
.WithIdentity("job8", "group1")
.StoreDurably()
.Build();
sched.AddJob(job, true);
log.Info("'Manually' triggering job8...");
sched.TriggerJob(new JobKey("job8", "group1"));
log.Info("------- Waiting 30 seconds... --------------");
try
{
// wait 30 seconds to show jobs
Thread.Sleep(TimeSpan.FromSeconds(30));
// executing...
}
catch (ThreadInterruptedException)
{
}
// jobs can be re-scheduled...
// job 7 will run immediately and repeat 10 times for every second
log.Info("------- Rescheduling... --------------------");
trigger = (ISimpleTrigger) TriggerBuilder.Create()
.WithIdentity("trigger7", "group1")
.StartAt(startTime)
.WithSimpleSchedule(x => x.WithIntervalInMinutes(5).WithRepeatCount(20))
.Build();
ft = sched.RescheduleJob(trigger.Key, trigger);
log.Info("job7 rescheduled to run at: " + ft);
log.Info("------- Waiting five minutes... ------------");
try
{
// wait five minutes to show jobs
Thread.Sleep(TimeSpan.FromMinutes(5));
// executing...
}
catch (ThreadInterruptedException)
{
}
log.Info("------- Shutting Down ---------------------");
sched.Shutdown(true);
log.Info("------- Shutdown Complete -----------------");
// display some stats about the schedule that just ran
SchedulerMetaData metaData = sched.GetMetaData();
log.Info(string.Format("Executed {0} jobs.", metaData.NumberOfJobsExecuted));
}
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace UnrealBuildTool
{
public class CodeLiteProject : ProjectFile
{
public CodeLiteProject( string InitFilePath ) : base(InitFilePath)
{
}
// Check if the XElement is empty.
bool IsEmpty(IEnumerable<XElement> en)
{
foreach(var c in en) { return false; }
return true;
}
string GetPathRelativeTo(string BasePath, string ToPath)
{
Uri path1 = new Uri(BasePath);
Uri path2 = new Uri(ToPath);
Uri diff = path1.MakeRelativeUri(path2);
return diff.ToString();
}
public override bool WriteProjectFile(List<UnrealTargetPlatform> InPlatforms, List<UnrealTargetConfiguration> InConfigurations)
{
bool bSuccess = false;
string ProjectPath = ProjectFilePath;
string ProjectExtension = Path.GetExtension (ProjectFilePath);
string ProjectPlatformName = BuildHostPlatform.Current.Platform.ToString();
string ProjectRelativeFilePath = this.RelativeProjectFilePath;
// Get the output directory
string EngineRootDirectory = Path.GetFullPath(ProjectFileGenerator.EngineRelativePath);
//
// Build the working directory of the Game executable.
//
string GameWorkingDirectory = "";
if (UnrealBuildTool.HasUProjectFile ())
{
GameWorkingDirectory = Path.Combine (Path.GetDirectoryName (UnrealBuildTool.GetUProjectFile ()), "Binaries", ProjectPlatformName);
}
//
// Build the working directory of the UE4Editor executable.
//
string UE4EditorWorkingDirectory = Path.Combine(EngineRootDirectory, "Binaries", ProjectPlatformName);
//
// Create the folder where the project files goes if it does not exist
//
String FilePath = Path.GetDirectoryName(ProjectFilePath);
if( (FilePath.Length > 0) && !Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
string GameProjectFile = UnrealBuildTool.GetUProjectFile();
//
// Write all targets which will be separate projects.
//
foreach (ProjectTarget target in ProjectTargets)
{
string[] tmp = target.ToString ().Split ('.');
string ProjectTargetFileName = Path.GetDirectoryName (ProjectFilePath) + "/" + tmp [0] + ProjectExtension;
String ProjectName = tmp [0];
var ProjectTargetType = target.TargetRules.Type;
//
// Create the CodeLites root element.
//
XElement CodeLiteProject = new XElement("CodeLite_Project");
XAttribute CodeLiteProjectAttributeName = new XAttribute("Name", ProjectName);
CodeLiteProject.Add(CodeLiteProjectAttributeName);
//
// Select only files we want to add.
// TODO Maybe skipping those files directly in the following foreach loop is faster?
//
List<SourceFile> FilterSourceFile = SourceFiles.FindAll(s => (
Path.GetExtension(s.FilePath).Equals(".h")
|| Path.GetExtension(s.FilePath).Equals(".cpp")
|| Path.GetExtension(s.FilePath).Equals(".cs")
|| Path.GetExtension(s.FilePath).Equals(".uproject")
|| Path.GetExtension(s.FilePath).Equals(".ini")
|| Path.GetExtension(s.FilePath).Equals(".usf")
));
//
// Find/Create the correct virtual folder and place the file into it.
//
foreach(var CurrentFile in FilterSourceFile)
{
//
// Try to get the correct relative folder representation for the project.
//
String CurrentFilePath = "";
// TODO It seems that the full pathname doesn't work for some files like .ini, .usf
if ((ProjectTargetType == TargetRules.TargetType.Client) ||
(ProjectTargetType == TargetRules.TargetType.Editor) ||
(ProjectTargetType == TargetRules.TargetType.Server) )
{
if(ProjectName.Contains("UE4"))
{
int Idx = Path.GetFullPath(ProjectFileGenerator.EngineRelativePath).Length;
CurrentFilePath = Path.GetDirectoryName(Path.GetFullPath(CurrentFile.FilePath)).Substring(Idx);
}
else
{
int IdxProjectName = ProjectName.IndexOf("Editor");
string ProjectNameRaw = ProjectName;
if (IdxProjectName > 0)
{
ProjectNameRaw = ProjectName.Substring(0, IdxProjectName);
}
int Idx = Path.GetDirectoryName(Path.GetFullPath(CurrentFile.FilePath)).IndexOf(ProjectNameRaw) + ProjectNameRaw.Length;
CurrentFilePath = Path.GetDirectoryName(Path.GetFullPath(CurrentFile.FilePath)).Substring(Idx);
}
}
else if (ProjectTargetType == TargetRules.TargetType.Program)
{
//
// We do not need all the editors subfolders to show the content. Find the correct programs subfolder.
//
int Idx = Path.GetDirectoryName(Path.GetFullPath(CurrentFile.FilePath)).IndexOf(ProjectName) + ProjectName.Length;
CurrentFilePath = Path.GetFullPath(Path.GetDirectoryName(CurrentFile.FilePath)).Substring(Idx);
}
else if (ProjectTargetType == TargetRules.TargetType.Game)
{
// int lengthOfProjectRootPath = Path.GetFullPath(ProjectFileGenerator.MasterProjectRelativePath).Length;
// CurrentFilePath = Path.GetDirectoryName(Path.GetFullPath(CurrentFile.FilePath)).Substring(lengthOfProjectRootPath);
// int lengthOfProjectRootPath = EngineRootDirectory.Length;
int Idx = Path.GetDirectoryName(Path.GetFullPath(CurrentFile.FilePath)).IndexOf(ProjectName) + ProjectName.Length;
CurrentFilePath = Path.GetDirectoryName(Path.GetFullPath(CurrentFile.FilePath)).Substring(Idx);
}
string [] SplitFolders = CurrentFilePath.Split('/');
//
// Set the CodeLite root folder again.
//
XElement root = CodeLiteProject;
//
// Iterate through all XElement virtual folders until we find the right place to put the file.
// TODO this looks more like a hack to me.
//
foreach (var FolderName in SplitFolders)
{
if (FolderName.Equals(""))
{
continue;
}
//
// Let's look if there is a virtual folder withint the current XElement.
//
IEnumerable<XElement> tests = root.Elements("VirtualDirectory");
if (IsEmpty(tests))
{
//
// No, then we have to create.
//
XElement vf = new XElement("VirtualDirectory");
XAttribute vfn = new XAttribute("Name", FolderName);
vf.Add(vfn);
root.Add(vf);
root = vf;
}
else
{
//
// Yes, then let's find the correct sub XElement.
//
bool notfound = true;
//
// We have some virtual directories let's find the correct one.
//
foreach (var element in tests)
{
//
// Look the the following folder
XAttribute attribute = element.Attribute("Name");
if (attribute.Value == FolderName)
{
// Ok, we found the folder as subfolder, let's use it.
root = element;
notfound = false;
break;
}
}
//
// If we are here we didn't find any XElement with that subfolder, then we have to create.
//
if (notfound)
{
XElement vf = new XElement("VirtualDirectory");
XAttribute vfn = new XAttribute("Name", FolderName);
vf.Add(vfn);
root.Add(vf);
root = vf;
}
}
}
//
// If we are at this point we found the correct XElement folder
//
XElement file = new XElement("File");
XAttribute fileAttribute = new XAttribute("Name", Path.GetFullPath(CurrentFile.FilePath));
file.Add(fileAttribute);
root.Add(file);
}
XElement CodeLiteSettings = new XElement("Settings");
CodeLiteProject.Add(CodeLiteSettings);
XElement CodeLiteGlobalSettings = new XElement("GlobalSettings");
CodeLiteSettings.Add(CodeLiteSettings);
foreach (var CurConf in InConfigurations)
{
XElement CodeLiteConfiguration = new XElement("Configuration");
XAttribute CodeLiteConfigurationName = new XAttribute("Name", CurConf.ToString());
CodeLiteConfiguration.Add(CodeLiteConfigurationName);
//
// Create Configuration General part.
//
XElement CodeLiteConfigurationGeneral = new XElement("General");
//
// Create the executable filename.
//
string ExecutableToRun = "";
string PlatformConfiguration = "-" + ProjectPlatformName + "-" + CurConf.ToString ();
switch (BuildHostPlatform.Current.Platform)
{
case UnrealTargetPlatform.Linux:
{
ExecutableToRun = "./" + ProjectName;
if ( (ProjectTargetType == TargetRules.TargetType.Game) || (ProjectTargetType == TargetRules.TargetType.Program))
{
if (CurConf != UnrealTargetConfiguration.Development)
{
ExecutableToRun += PlatformConfiguration;
}
}
else if (ProjectTargetType == TargetRules.TargetType.Editor)
{
ExecutableToRun = "./UE4Editor";
}
}
break;
case UnrealTargetPlatform.Mac:
{
ExecutableToRun = "./" + ProjectName;
if ((ProjectTargetType == TargetRules.TargetType.Game) || (ProjectTargetType == TargetRules.TargetType.Program))
{
if (CurConf != UnrealTargetConfiguration.Development)
{
ExecutableToRun += PlatformConfiguration;
}
ExecutableToRun += ".app/Contents/MacOS/" + ProjectName;
if (CurConf != UnrealTargetConfiguration.Development)
{
ExecutableToRun += PlatformConfiguration;
}
}
else if (ProjectTargetType == TargetRules.TargetType.Editor)
{
ExecutableToRun = "./UE4Editor";
if (CurConf != UnrealTargetConfiguration.Development)
{
ExecutableToRun += PlatformConfiguration;
}
ExecutableToRun += ".app/Contents/MacOS/UE4Editor";
if (CurConf != UnrealTargetConfiguration.Development)
{
ExecutableToRun += PlatformConfiguration;
}
}
}
break;
case UnrealTargetPlatform.Win64:
case UnrealTargetPlatform.Win32:
{
ExecutableToRun = ProjectName;
if ((ProjectTargetType == TargetRules.TargetType.Game) || (ProjectTargetType == TargetRules.TargetType.Program))
{
if (CurConf != UnrealTargetConfiguration.Development)
{
ExecutableToRun += PlatformConfiguration;
}
}
else if (ProjectTargetType == TargetRules.TargetType.Editor)
{
ExecutableToRun = "UE4Editor";
}
ExecutableToRun += ".exe";
}
break;
default:
throw new BuildException("Unsupported platform.");
}
// Is this project a Game type?
XAttribute GeneralExecutableToRun = new XAttribute("Command", ExecutableToRun);
if (ProjectTargetType == TargetRules.TargetType.Game)
{
if (CurConf.ToString ().Contains ("Debug"))
{
string commandArguments = " -debug";
XAttribute GeneralExecutableToRunArguments = new XAttribute("CommandArguments", commandArguments);
CodeLiteConfigurationGeneral.Add(GeneralExecutableToRunArguments);
}
if (ProjectName.Equals ("UE4Game")) {
XAttribute GeneralExecutableWorkingDirectory = new XAttribute("WorkingDirectory", UE4EditorWorkingDirectory);
CodeLiteConfigurationGeneral.Add(GeneralExecutableWorkingDirectory);
} else {
XAttribute GeneralExecutableWorkingDirectory = new XAttribute("WorkingDirectory", GameWorkingDirectory);
CodeLiteConfigurationGeneral.Add(GeneralExecutableWorkingDirectory);
}
}
else if (ProjectTargetType == TargetRules.TargetType.Editor)
{
if (ProjectName != "UE4Editor")
{
string commandArguments = "\"" + GameProjectFile + "\"" + " -game";
XAttribute CommandArguments = new XAttribute("CommandArguments", commandArguments);
CodeLiteConfigurationGeneral.Add(CommandArguments);
}
XAttribute WorkingDirectory = new XAttribute("WorkingDirectory", UE4EditorWorkingDirectory);
CodeLiteConfigurationGeneral.Add(WorkingDirectory);
}
else if (ProjectTargetType == TargetRules.TargetType.Program)
{
XAttribute WorkingDirectory = new XAttribute("WorkingDirectory", UE4EditorWorkingDirectory);
CodeLiteConfigurationGeneral.Add(WorkingDirectory);
}
else if (ProjectTargetType == TargetRules.TargetType.Client)
{
XAttribute WorkingDirectory = new XAttribute("WorkingDirectory", UE4EditorWorkingDirectory);
CodeLiteConfigurationGeneral.Add(WorkingDirectory);
}
else if (ProjectTargetType == TargetRules.TargetType.Server)
{
XAttribute WorkingDirectory = new XAttribute("WorkingDirectory", UE4EditorWorkingDirectory);
CodeLiteConfigurationGeneral.Add(WorkingDirectory);
}
CodeLiteConfigurationGeneral.Add(GeneralExecutableToRun);
CodeLiteConfiguration.Add(CodeLiteConfigurationGeneral);
//
// End of Create Configuration General part.
//
//
// Create Configuration Custom Build part.
//
XElement CodeLiteConfigurationCustomBuild = new XElement("CustomBuild");
CodeLiteConfiguration.Add(CodeLiteConfigurationGeneral);
XAttribute CodeLiteConfigurationCustomBuildEnabled = new XAttribute("Enabled", "yes");
CodeLiteConfigurationCustomBuild.Add(CodeLiteConfigurationCustomBuildEnabled);
//
// Add the working directory for the custom build commands.
//
XElement CustomBuildWorkingDirectory = new XElement("WorkingDirectory");
XText CustuomBuildWorkingDirectory = new XText(Path.GetDirectoryName(UnrealBuildTool.GetUBTPath()));
CustomBuildWorkingDirectory.Add(CustuomBuildWorkingDirectory);
CodeLiteConfigurationCustomBuild.Add(CustomBuildWorkingDirectory);
//
// End of Add the working directory for the custom build commands.
//
//
// Make Build Target.
//
XElement CustomBuildCommand = new XElement("BuildCommand");
CodeLiteConfigurationCustomBuild.Add(CustomBuildCommand);
string BuildTarget = Path.GetFileName(UnrealBuildTool.GetUBTPath()) + " " + ProjectName + " " + ProjectPlatformName + " " + CurConf.ToString();
if( (BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Win64) &&
(BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Win32))
{
BuildTarget = "mono " + BuildTarget;
}
if (GameProjectFile.Length > 0)
{
BuildTarget += " -project=" + "\"" + GameProjectFile + "\"";
}
XText commandLine = new XText(BuildTarget);
CustomBuildCommand.Add(commandLine);
//
// End of Make Build Target
//
//
// Clean Build Target.
//
XElement CustomCleanCommand = new XElement("CleanCommand");
CodeLiteConfigurationCustomBuild.Add(CustomCleanCommand);
string CleanTarget = BuildTarget + " -clean";
XText CleanCommandLine = new XText(CleanTarget);
CustomCleanCommand.Add(CleanCommandLine);
//
// End of Clean Build Target.
//
//
// Rebuild Build Target.
//
XElement CustomRebuildCommand = new XElement("RebuildCommand");
CodeLiteConfigurationCustomBuild.Add(CustomRebuildCommand);
string RebuildTarget = CleanTarget + "\n" + BuildTarget;
XText RebuildCommandLine = new XText(RebuildTarget);
CustomRebuildCommand.Add(RebuildCommandLine);
//
// End of Clean Build Target.
//
//
// Some other fun Custom Targets.
//
if (ProjectTargetType == TargetRules.TargetType.Game)
{
string CookGameCommandLine = "mono AutomationTool.exe BuildCookRun ";
// Projects filename
CookGameCommandLine += "-project=\"" + UnrealBuildTool.GetUProjectFile () + "\" ";
// Disables Perforce functionality
CookGameCommandLine += "-noP4 ";
// Do not kill any spawned processes on exit
CookGameCommandLine += "-nokill ";
CookGameCommandLine += "-clientconfig=" + CurConf.ToString() + " ";
CookGameCommandLine += "-serverconfig=" + CurConf.ToString() + " ";
CookGameCommandLine += "-platform=" + ProjectPlatformName + " ";
CookGameCommandLine += "-targetplatform=" + ProjectPlatformName + " "; // TODO Maybe I can add all the supported one.
CookGameCommandLine += "-nocompile ";
CookGameCommandLine += "-compressed -stage -deploy";
//
// Cook Game.
//
XElement CookGame = new XElement("Target");
XAttribute CookGameName = new XAttribute("Name", "Cook Game");
XText CookGameCommand = new XText(CookGameCommandLine + " -cook");
CookGame.Add(CookGameName);
CookGame.Add(CookGameCommand);
CodeLiteConfigurationCustomBuild.Add(CookGame);
XElement CookGameOnTheFly = new XElement("Target");
XAttribute CookGameNameOnTheFlyName = new XAttribute("Name", "Cook Game on the fly");
XText CookGameOnTheFlyCommand = new XText(CookGameCommandLine + " -cookonthefly");
CookGameOnTheFly.Add(CookGameNameOnTheFlyName);
CookGameOnTheFly.Add(CookGameOnTheFlyCommand);
CodeLiteConfigurationCustomBuild.Add(CookGameOnTheFly);
XElement SkipCook = new XElement("Target");
XAttribute SkipCookName = new XAttribute("Name", "Skip Cook Game");
XText SkipCookCommand = new XText(CookGameCommandLine + " -skipcook");
SkipCook.Add(SkipCookName);
SkipCook.Add(SkipCookCommand);
CodeLiteConfigurationCustomBuild.Add(SkipCook);
}
//
// End of Some other fun Custom Targets.
//
CodeLiteConfiguration.Add(CodeLiteConfigurationCustomBuild);
//
// End of Create Configuration Custom Build part.
//
CodeLiteSettings.Add(CodeLiteConfiguration);
}
CodeLiteSettings.Add(CodeLiteGlobalSettings);
//
// Save the XML file.
//
CodeLiteProject.Save(ProjectTargetFileName);
bSuccess = true;
}
return bSuccess;
}
}
}
| |
/*
* CodeGenerator.cs - Implementation of the
* System.CodeDom.Compiler.CodeGenerator class.
*
* Copyright (C) 2002, 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.CodeDom.Compiler
{
#if CONFIG_CODEDOM
using System.IO;
using System.Reflection;
using System.Globalization;
public abstract class CodeGenerator : ICodeGenerator
{
// Internal state.
private CodeTypeMember currentMember;
private CodeTypeDeclaration currentType;
private IndentedTextWriter writer;
private CodeGeneratorOptions options;
// Constructor.
protected CodeGenerator()
{
}
// Determine if an identifier is valid for language-independent use.
public static bool IsValidLanguageIndependentIdentifier(String value)
{
if(value == null || value.Length == 0)
{
return false;
}
int posn = 0;
if(Char.GetUnicodeCategory(value[0]) ==
UnicodeCategory.DecimalDigitNumber)
{
return false;
}
for(posn = 0; posn < value.Length; ++posn)
{
switch(Char.GetUnicodeCategory(value[posn]))
{
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.SpacingCombiningMark:
case UnicodeCategory.DecimalDigitNumber:
case UnicodeCategory.ConnectorPunctuation: break;
default: return false;
}
}
return true;
}
// Get the current class member.
protected CodeTypeMember CurrentMember
{
get
{
return currentMember;
}
}
// Get the current class member's name.
protected String CurrentMemberName
{
get
{
if(currentMember != null)
{
return currentMember.Name;
}
else
{
return "<% unknown %>";
}
}
}
// Get the current class type's name.
protected String CurrentTypeName
{
get
{
if(currentType != null)
{
return currentType.Name;
}
else
{
return "<% unknown %>";
}
}
}
// Get or set the current indent level.
protected int Indent
{
get
{
return writer.Indent;
}
set
{
writer.Indent = value;
}
}
// Determine if the current type is a class.
protected bool IsCurrentClass
{
get
{
return (currentType != null &&
!(currentType is CodeTypeDelegate) &&
currentType.IsClass);
}
}
// Determine if the current type is a delegate.
protected bool IsCurrentDelegate
{
get
{
return (currentType != null &&
currentType is CodeTypeDelegate);
}
}
// Determine if the current type is an enumeration.
protected bool IsCurrentEnum
{
get
{
return (currentType != null &&
!(currentType is CodeTypeDelegate) &&
currentType.IsEnum);
}
}
// Determine if the current type is an interface.
protected bool IsCurrentInterface
{
get
{
return (currentType != null &&
!(currentType is CodeTypeDelegate) &&
currentType.IsInterface);
}
}
// Determine if the current type is a struct.
protected bool IsCurrentStruct
{
get
{
return (currentType != null &&
!(currentType is CodeTypeDelegate) &&
currentType.IsStruct);
}
}
// Get the token for "null".
protected abstract String NullToken { get; }
// Get the current code generation options.
protected CodeGeneratorOptions Options
{
get
{
if(options == null)
{
options = new CodeGeneratorOptions();
}
return options;
}
}
// Get the output text writer.
protected TextWriter Output
{
get
{
return writer;
}
}
// Output a continuation on a new line if the language requires it.
protected virtual void ContinueOnNewLine(String st)
{
writer.WriteLine(st);
}
// Create an escaped identifier if "value" is a language keyword.
protected abstract String CreateEscapedIdentifier(String value);
// Create a valid identifier if "value" is a language keyword.
protected abstract String CreateValidIdentifier(String value);
// Generate various expression categories.
protected abstract void GenerateArgumentReferenceExpression
(CodeArgumentReferenceExpression e);
protected abstract void GenerateArrayCreateExpression
(CodeArrayCreateExpression e);
protected abstract void GenerateArrayIndexerExpression
(CodeArrayIndexerExpression e);
protected abstract void GenerateBaseReferenceExpression
(CodeBaseReferenceExpression e);
protected abstract void GenerateCastExpression
(CodeCastExpression e);
protected abstract void GenerateDelegateCreateExpression
(CodeDelegateCreateExpression e);
protected abstract void GenerateDelegateInvokeExpression
(CodeDelegateInvokeExpression e);
protected abstract void GenerateEventReferenceExpression
(CodeEventReferenceExpression e);
protected abstract void GenerateFieldReferenceExpression
(CodeFieldReferenceExpression e);
protected abstract void GenerateIndexerExpression
(CodeIndexerExpression e);
protected abstract void GenerateMethodInvokeExpression
(CodeMethodInvokeExpression e);
protected abstract void GenerateMethodReferenceExpression
(CodeMethodReferenceExpression e);
protected abstract void GenerateObjectCreateExpression
(CodeObjectCreateExpression e);
protected abstract void GeneratePropertyReferenceExpression
(CodePropertyReferenceExpression e);
protected abstract void GeneratePropertySetValueReferenceExpression
(CodePropertySetValueReferenceExpression e);
protected abstract void GenerateSnippetExpression
(CodeSnippetExpression e);
protected abstract void GenerateThisReferenceExpression
(CodeThisReferenceExpression e);
protected abstract void GenerateVariableReferenceExpression
(CodeVariableReferenceExpression e);
// Generate various statement categories.
protected abstract void GenerateAssignStatement
(CodeAssignStatement e);
protected abstract void GenerateAttachEventStatement
(CodeAttachEventStatement e);
protected abstract void GenerateConditionStatement
(CodeConditionStatement e);
protected abstract void GenerateExpressionStatement
(CodeExpressionStatement e);
protected abstract void GenerateGotoStatement
(CodeGotoStatement e);
protected abstract void GenerateIterationStatement
(CodeIterationStatement e);
protected abstract void GenerateLabeledStatement
(CodeLabeledStatement e);
protected abstract void GenerateMethodReturnStatement
(CodeMethodReturnStatement e);
protected abstract void GenerateRemoveEventStatement
(CodeRemoveEventStatement e);
protected abstract void GenerateThrowExceptionStatement
(CodeThrowExceptionStatement e);
protected abstract void GenerateTryCatchFinallyStatement
(CodeTryCatchFinallyStatement e);
protected abstract void GenerateVariableDeclarationStatement
(CodeVariableDeclarationStatement e);
// Generate various declaration categories.
protected abstract void GenerateAttributeDeclarationsStart
(CodeAttributeDeclarationCollection attributes);
protected abstract void GenerateAttributeDeclarationsEnd
(CodeAttributeDeclarationCollection attributes);
protected abstract void GenerateConstructor
(CodeConstructor e, CodeTypeDeclaration c);
protected abstract void GenerateEntryPointMethod
(CodeEntryPointMethod e, CodeTypeDeclaration c);
protected abstract void GenerateEvent
(CodeMemberEvent e, CodeTypeDeclaration c);
protected abstract void GenerateField(CodeMemberField e);
protected abstract void GenerateMethod
(CodeMemberMethod e, CodeTypeDeclaration c);
protected abstract void GenerateProperty
(CodeMemberProperty e, CodeTypeDeclaration c);
protected abstract void GenerateNamespaceStart(CodeNamespace e);
protected abstract void GenerateNamespaceEnd(CodeNamespace e);
protected abstract void GenerateNamespaceImport(CodeNamespaceImport e);
protected abstract void GenerateSnippetMember
(CodeSnippetTypeMember e);
protected abstract void GenerateTypeConstructor
(CodeTypeConstructor e);
protected abstract void GenerateTypeStart(CodeTypeDeclaration e);
protected abstract void GenerateTypeEnd(CodeTypeDeclaration e);
// Generate various misc categories.
protected abstract void GenerateComment(CodeComment e);
protected abstract void GenerateLinePragmaStart(CodeLinePragma e);
protected abstract void GenerateLinePragmaEnd(CodeLinePragma e);
protected abstract String GetTypeOutput(CodeTypeReference value);
// Generate code for a binary operator expression.
protected virtual void GenerateBinaryOperatorExpression
(CodeBinaryOperatorExpression e)
{
Output.Write("(");
GenerateExpression(e.Left);
Output.Write(" ");
OutputOperator(e.Operator);
Output.Write(" ");
GenerateExpression(e.Right);
Output.Write(")");
}
// Generate code for comment statements.
protected virtual void GenerateCommentStatement
(CodeCommentStatement e)
{
GenerateComment(e.Comment);
}
protected virtual void GenerateCommentStatements
(CodeCommentStatementCollection e)
{
foreach(CodeCommentStatement comment in e)
{
GenerateCommentStatement(comment);
}
}
// Generate code for a compilation unit.
protected virtual void GenerateCompileUnit(CodeCompileUnit e)
{
GenerateCompileUnitStart(e);
GenerateNamespaces(e);
GenerateCompileUnitEnd(e);
}
protected virtual void GenerateCompileUnitStart(CodeCompileUnit e)
{
// Nothing to do here.
}
protected virtual void GenerateCompileUnitEnd(CodeCompileUnit e)
{
// Nothing to do here.
}
// Generate code for constants.
protected virtual void GenerateDecimalValue(Decimal d)
{
writer.Write(d.ToString(CultureInfo.InvariantCulture));
}
protected virtual void GenerateDoubleValue(double d)
{
writer.Write(d.ToString("R", CultureInfo.InvariantCulture));
}
protected virtual void GenerateSingleFloatValue(float s)
{
writer.Write(s.ToString(CultureInfo.InvariantCulture));
}
// Generate code for an expression.
protected void GenerateExpression(CodeExpression e)
{
if(e is CodeArrayCreateExpression)
{
GenerateArrayCreateExpression
((CodeArrayCreateExpression)e);
}
else if(e is CodeCastExpression)
{
GenerateCastExpression((CodeCastExpression)e);
}
else if(e is CodeMethodInvokeExpression)
{
GenerateMethodInvokeExpression
((CodeMethodInvokeExpression)e);
}
else if(e is CodeObjectCreateExpression)
{
GenerateObjectCreateExpression
((CodeObjectCreateExpression)e);
}
else if(e is CodeParameterDeclarationExpression)
{
GenerateParameterDeclarationExpression
((CodeParameterDeclarationExpression)e);
}
else if(e is CodeTypeOfExpression)
{
GenerateTypeOfExpression
((CodeTypeOfExpression)e);
}
else if(e is CodeTypeReferenceExpression)
{
GenerateTypeReferenceExpression
((CodeTypeReferenceExpression)e);
}
else if(e is CodeArgumentReferenceExpression)
{
GenerateArgumentReferenceExpression
((CodeArgumentReferenceExpression)e);
}
else if(e is CodeArrayIndexerExpression)
{
GenerateArrayIndexerExpression
((CodeArrayIndexerExpression)e);
}
else if(e is CodeBaseReferenceExpression)
{
GenerateBaseReferenceExpression
((CodeBaseReferenceExpression)e);
}
else if(e is CodeBinaryOperatorExpression)
{
GenerateBinaryOperatorExpression
((CodeBinaryOperatorExpression)e);
}
else if(e is CodeDelegateCreateExpression)
{
GenerateDelegateCreateExpression
((CodeDelegateCreateExpression)e);
}
else if(e is CodeDelegateInvokeExpression)
{
GenerateDelegateInvokeExpression
((CodeDelegateInvokeExpression)e);
}
else if(e is CodeDirectionExpression)
{
GenerateDirectionExpression
((CodeDirectionExpression)e);
}
else if(e is CodeEventReferenceExpression)
{
GenerateEventReferenceExpression
((CodeEventReferenceExpression)e);
}
else if(e is CodeFieldReferenceExpression)
{
GenerateFieldReferenceExpression
((CodeFieldReferenceExpression)e);
}
else if(e is CodeIndexerExpression)
{
GenerateIndexerExpression
((CodeIndexerExpression)e);
}
else if(e is CodeMethodReferenceExpression)
{
GenerateMethodReferenceExpression
((CodeMethodReferenceExpression)e);
}
else if(e is CodePrimitiveExpression)
{
GeneratePrimitiveExpression
((CodePrimitiveExpression)e);
}
else if(e is CodePropertyReferenceExpression)
{
GeneratePropertyReferenceExpression
((CodePropertyReferenceExpression)e);
}
else if(e is CodePropertySetValueReferenceExpression)
{
GeneratePropertySetValueReferenceExpression
((CodePropertySetValueReferenceExpression)e);
}
else if(e is CodeSnippetExpression)
{
GenerateSnippetExpression
((CodeSnippetExpression)e);
}
else if(e is CodeThisReferenceExpression)
{
GenerateThisReferenceExpression
((CodeThisReferenceExpression)e);
}
else if(e is CodeVariableReferenceExpression)
{
GenerateVariableReferenceExpression
((CodeVariableReferenceExpression)e);
}
else
{
throw new ArgumentException
(S._("Arg_InvalidCodeDom"), "e");
}
}
// Helper methods for line pragmas.
private void LinePragmaStart(CodeLinePragma pragma)
{
if(pragma != null)
{
GenerateLinePragmaStart(pragma);
}
}
private void LinePragmaEnd(CodeLinePragma pragma)
{
if(pragma != null)
{
GenerateLinePragmaEnd(pragma);
}
}
// Generate code for namespace information.
protected virtual void GenerateNamespace(CodeNamespace e)
{
GenerateCommentStatements(e.Comments);
GenerateNamespaceStart(e);
GenerateNamespaceImports(e);
Output.WriteLine();
GenerateTypes(e);
GenerateNamespaceEnd(e);
}
protected void GenerateNamespaceImports(CodeNamespace e)
{
foreach(CodeNamespaceImport ns in e.Imports)
{
LinePragmaStart(ns.LinePragma);
GenerateNamespaceImport(ns);
LinePragmaEnd(ns.LinePragma);
}
}
protected void GenerateNamespaces(CodeCompileUnit e)
{
foreach(CodeNamespace ns in e.Namespaces)
{
((ICodeGenerator)this).GenerateCodeFromNamespace
(ns, writer.InnerWriter, Options);
}
}
// Generate a parameter declaration expression.
protected virtual void GenerateParameterDeclarationExpression
(CodeParameterDeclarationExpression e)
{
if(e.CustomAttributes.Count != 0)
{
OutputAttributeDeclarations(e.CustomAttributes);
Output.Write(" ");
}
OutputDirection(e.Direction);
OutputTypeNamePair(e.Type, e.Name);
}
// Hex characters for encoding "char" constants.
private static readonly String hexchars = "0123456789abcdef";
// Generate code for a primitive expression.
protected virtual void GeneratePrimitiveExpression
(CodePrimitiveExpression e)
{
Object value = e.Value;
if(value == null)
{
Output.Write(NullToken);
}
else if(value is String)
{
Output.Write(QuoteSnippetString((String)value));
}
else if(value is Char)
{
char ch = (char)value;
String chvalue;
switch(ch)
{
case '\'': chvalue = "'\\''"; break;
case '\\': chvalue = "'\\\\'"; break;
case '\n': chvalue = "'\\n'"; break;
case '\r': chvalue = "'\\r'"; break;
case '\t': chvalue = "'\\t'"; break;
case '\f': chvalue = "'\\f'"; break;
case '\v': chvalue = "'\\v'"; break;
case '\a': chvalue = "'\\a'"; break;
case '\b': chvalue = "'\\b'"; break;
default:
{
if(ch >= ' ' && ch <= 0x7E)
{
chvalue = "\"" + ch.ToString() + "\"";
}
else if(ch < 0x0100)
{
chvalue = "\"\\x" +
hexchars[(ch >> 4) & 0x0F] +
hexchars[ch & 0x0F] + "\"";
}
else
{
chvalue = "\"\\u" +
hexchars[(ch >> 12) & 0x0F] +
hexchars[(ch >> 8) & 0x0F] +
hexchars[(ch >> 4) & 0x0F] +
hexchars[ch & 0x0F] + "\"";
}
}
break;
}
Output.Write(chvalue);
}
else if(value is SByte)
{
Output.Write((int)(sbyte)value);
}
else if(value is Byte)
{
Output.Write((int)(byte)value);
}
else if(value is Int16)
{
Output.Write((int)(short)value);
}
else if(value is UInt16)
{
Output.Write((int)(ushort)value);
}
else if(value is Int32)
{
Output.Write((int)value);
}
else if(value is UInt32)
{
Output.Write((uint)value);
}
else if(value is Int64)
{
Output.Write((long)value);
}
else if(value is UInt64)
{
Output.Write((ulong)value);
}
else if(value is Single)
{
GenerateSingleFloatValue((float)value);
}
else if(value is Double)
{
GenerateDoubleValue((double)value);
}
else if(value is Decimal)
{
GenerateDecimalValue((Decimal)value);
}
else if(value is Boolean)
{
if((bool)value)
{
Output.Write("true");
}
else
{
Output.Write("false");
}
}
else
{
throw new ArgumentException
(S._("Arg_InvalidCodeDom"), "e");
}
}
// Generate a compile unit snippet.
protected virtual void GenerateSnippetCompileUnit
(CodeSnippetCompileUnit e)
{
LinePragmaStart(e.LinePragma);
Output.WriteLine(e.Value);
LinePragmaEnd(e.LinePragma);
}
// Generate a code statement snippet.
protected virtual void GenerateSnippetStatement(CodeSnippetStatement e)
{
Output.WriteLine(e.Value);
}
// Generate code for a statement.
protected void GenerateStatement(CodeStatement e)
{
LinePragmaStart(e.LinePragma);
if(e is CodeAttachEventStatement)
{
GenerateAttachEventStatement
((CodeAttachEventStatement)e);
}
else if(e is CodeCommentStatement)
{
GenerateCommentStatement
((CodeCommentStatement)e);
}
else if(e is CodeConditionStatement)
{
GenerateConditionStatement
((CodeConditionStatement)e);
}
else if(e is CodeRemoveEventStatement)
{
GenerateRemoveEventStatement
((CodeRemoveEventStatement)e);
}
else if(e is CodeVariableDeclarationStatement)
{
GenerateVariableDeclarationStatement
((CodeVariableDeclarationStatement)e);
}
else if(e is CodeAssignStatement)
{
GenerateAssignStatement
((CodeAssignStatement)e);
}
else if(e is CodeExpressionStatement)
{
GenerateExpressionStatement
((CodeExpressionStatement)e);
}
else if(e is CodeGotoStatement)
{
GenerateGotoStatement
((CodeGotoStatement)e);
}
else if(e is CodeIterationStatement)
{
GenerateIterationStatement
((CodeIterationStatement)e);
}
else if(e is CodeLabeledStatement)
{
GenerateLabeledStatement
((CodeLabeledStatement)e);
}
else if(e is CodeMethodReturnStatement)
{
GenerateMethodReturnStatement
((CodeMethodReturnStatement)e);
}
else if(e is CodeSnippetStatement)
{
GenerateSnippetStatement
((CodeSnippetStatement)e);
}
else if(e is CodeThrowExceptionStatement)
{
GenerateThrowExceptionStatement
((CodeThrowExceptionStatement)e);
}
else if(e is CodeTryCatchFinallyStatement)
{
GenerateTryCatchFinallyStatement
((CodeTryCatchFinallyStatement)e);
}
else
{
throw new ArgumentException
(S._("Arg_InvalidCodeDom"), "e");
}
LinePragmaEnd(e.LinePragma);
}
// Generate code for a statement collection.
protected void GenerateStatements(CodeStatementCollection e)
{
if(e == null)
{
return;
}
foreach(CodeStatement stmt in e)
{
((ICodeGenerator)this).GenerateCodeFromStatement
(stmt, writer.InnerWriter, Options);
}
}
// Generate a typeof expression.
protected virtual void GenerateTypeOfExpression
(CodeTypeOfExpression e)
{
Output.Write("typeof(");
OutputType(e.Type);
Output.Write(")");
}
// Generate a type reference expression.
protected virtual void GenerateTypeReferenceExpression
(CodeTypeReferenceExpression e)
{
OutputType(e.Type);
}
// Generate various categories of type member.
private void TypeMemberStart(CodeTypeMember member)
{
currentMember = member;
if(options.BlankLinesBetweenMembers)
{
Output.WriteLine();
}
GenerateCommentStatements(member.Comments);
LinePragmaStart(member.LinePragma);
}
private void TypeMemberEnd(CodeTypeMember member)
{
LinePragmaEnd(member.LinePragma);
currentMember = null;
}
private void TypeFields(CodeTypeDeclaration e)
{
foreach(CodeTypeMember member in e.Members)
{
if(member is CodeMemberField)
{
TypeMemberStart(member);
GenerateField((CodeMemberField)member);
TypeMemberEnd(member);
}
}
}
private void TypeSnippets(CodeTypeDeclaration e)
{
foreach(CodeTypeMember member in e.Members)
{
if(member is CodeSnippetTypeMember)
{
TypeMemberStart(member);
GenerateSnippetMember((CodeSnippetTypeMember)member);
TypeMemberEnd(member);
}
}
}
private void TypeStaticConstructors(CodeTypeDeclaration e)
{
foreach(CodeTypeMember member in e.Members)
{
if(member is CodeTypeConstructor)
{
TypeMemberStart(member);
GenerateTypeConstructor((CodeTypeConstructor)member);
TypeMemberEnd(member);
}
}
}
private void TypeConstructors(CodeTypeDeclaration e)
{
foreach(CodeTypeMember member in e.Members)
{
if(member is CodeConstructor)
{
TypeMemberStart(member);
GenerateConstructor((CodeConstructor)member, e);
TypeMemberEnd(member);
}
}
}
private void TypeProperties(CodeTypeDeclaration e)
{
foreach(CodeTypeMember member in e.Members)
{
if(member is CodeMemberProperty)
{
TypeMemberStart(member);
GenerateProperty((CodeMemberProperty)member, e);
TypeMemberEnd(member);
}
}
}
private void TypeEvents(CodeTypeDeclaration e)
{
foreach(CodeTypeMember member in e.Members)
{
if(member is CodeMemberEvent)
{
TypeMemberStart(member);
GenerateEvent((CodeMemberEvent)member, e);
TypeMemberEnd(member);
}
}
}
private void TypeMethods(CodeTypeDeclaration e)
{
foreach(CodeTypeMember member in e.Members)
{
if(member is CodeMemberMethod &&
!(member is CodeConstructor) &&
!(member is CodeTypeConstructor))
{
TypeMemberStart(member);
GenerateMethod((CodeMemberMethod)member, e);
TypeMemberEnd(member);
}
}
}
private void TypeNestedTypes(CodeTypeDeclaration e)
{
foreach(CodeTypeMember member in e.Members)
{
if(member is CodeTypeDeclaration)
{
if(options.BlankLinesBetweenMembers)
{
Output.WriteLine();
}
((ICodeGenerator)this).GenerateCodeFromType
((CodeTypeDeclaration)member,
writer.InnerWriter, Options);
}
}
currentType = e;
}
// Generate a particular type declaration.
private void GenerateType(CodeTypeDeclaration e)
{
currentType = e;
GenerateCommentStatements(e.Comments);
GenerateTypeStart(e);
TypeFields(e);
TypeSnippets(e);
TypeStaticConstructors(e);
TypeConstructors(e);
TypeProperties(e);
TypeEvents(e);
TypeMethods(e);
TypeNestedTypes(e);
GenerateTypeEnd(e);
currentType = null;
}
// Generate the types in a namespace.
protected void GenerateTypes(CodeNamespace e)
{
foreach(CodeTypeDeclaration type in e.Types)
{
if(options.BlankLinesBetweenMembers)
{
Output.WriteLine();
}
((ICodeGenerator)this).GenerateCodeFromType
(type, writer.InnerWriter, Options);
}
}
// Determine if "value" is a valid identifier.
protected abstract bool IsValidIdentifier(String value);
// Output an attribute argument.
protected virtual void OutputAttributeArgument
(CodeAttributeArgument arg)
{
if(arg.Name != null)
{
OutputIdentifier(arg.Name);
Output.Write("=");
}
((ICodeGenerator)this).GenerateCodeFromExpression
(arg.Value, writer.InnerWriter, Options);
}
// Output attribute declarations.
protected virtual void OutputAttributeDeclarations
(CodeAttributeDeclarationCollection attributes)
{
OutputAttributeDeclarations(null, attributes);
}
internal void OutputAttributeDeclarations
(String prefix, CodeAttributeDeclarationCollection attributes)
{
if(attributes.Count == 0)
{
return;
}
bool first = true;
bool first2;
CodeAttributeArgumentCollection args;
GenerateAttributeDeclarationsStart(attributes);
foreach(CodeAttributeDeclaration attr in attributes)
{
if(!first)
{
ContinueOnNewLine(", ");
}
else
{
first = false;
}
if(prefix != null)
{
Output.Write(prefix);
}
Output.Write(attr.Name);
args = attr.Arguments;
if(args.Count != 0)
{
Output.Write("(");
first2 = true;
foreach(CodeAttributeArgument arg in args)
{
if(!first2)
{
Output.Write(", ");
}
else
{
first2 = false;
}
OutputAttributeArgument(arg);
}
Output.Write(")");
}
}
GenerateAttributeDeclarationsEnd(attributes);
}
// Generate a direction expression.
protected virtual void GenerateDirectionExpression
(CodeDirectionExpression e)
{
OutputDirection(e.Direction);
GenerateExpression(e.Expression);
}
// Output a field direction value.
protected virtual void OutputDirection(FieldDirection dir)
{
if(dir == FieldDirection.Out)
{
Output.Write("out ");
}
else if(dir == FieldDirection.Ref)
{
Output.Write("ref ");
}
}
// Output an expression list.
protected virtual void OutputExpressionList
(CodeExpressionCollection expressions)
{
OutputExpressionList(expressions, false);
}
protected virtual void OutputExpressionList
(CodeExpressionCollection expressions,
bool newlineBetweenItems)
{
writer.Indent += 1;
bool first = true;
foreach(CodeExpression expr in expressions)
{
if(!first)
{
if(newlineBetweenItems)
{
ContinueOnNewLine(",");
}
else
{
Output.Write(", ");
}
}
else
{
first = false;
}
((ICodeGenerator)this).GenerateCodeFromExpression
(expr, writer.InnerWriter, Options);
}
writer.Indent -= 1;
}
// Output a field scope modifier.
protected virtual void OutputFieldScopeModifier
(MemberAttributes attributes)
{
if((attributes & MemberAttributes.VTableMask) ==
MemberAttributes.New)
{
Output.Write("new ");
}
if((attributes & MemberAttributes.ScopeMask) ==
MemberAttributes.Static)
{
Output.Write("static ");
}
else if((attributes & MemberAttributes.ScopeMask) ==
MemberAttributes.Const)
{
Output.Write("const ");
}
}
// Output an identifier.
protected virtual void OutputIdentifier(String ident)
{
Output.Write(ident);
}
// Output a member access modifier.
protected virtual void OutputMemberAccessModifier
(MemberAttributes attributes)
{
String access;
switch(attributes & MemberAttributes.AccessMask)
{
case MemberAttributes.Assembly:
access = "internal "; break;
case MemberAttributes.FamilyAndAssembly:
access = "/*FamANDAssem*/ internal "; break;
case MemberAttributes.Family:
access = "protected "; break;
case MemberAttributes.FamilyOrAssembly:
access = "protected internal "; break;
case MemberAttributes.Private:
access = "private "; break;
case MemberAttributes.Public:
access = "public "; break;
default: return;
}
Output.Write(access);
}
// Output a member scope modifier.
protected virtual void OutputMemberScopeModifier
(MemberAttributes attributes)
{
if((attributes & MemberAttributes.VTableMask) ==
MemberAttributes.New)
{
Output.Write("new ");
}
switch(attributes & MemberAttributes.ScopeMask)
{
case MemberAttributes.Abstract:
Output.Write("abstract "); break;;
case MemberAttributes.Final:
break;;
case MemberAttributes.Static:
Output.Write("static "); break;;
case MemberAttributes.Override:
Output.Write("override "); break;;
default:
{
if((attributes & MemberAttributes.AccessMask) ==
MemberAttributes.Public ||
(attributes & MemberAttributes.AccessMask) ==
MemberAttributes.Family)
{
Output.Write("virtual ");
}
}
break;
}
}
// Output a binary operator.
protected virtual void OutputOperator(CodeBinaryOperatorType op)
{
String oper;
switch(op)
{
case CodeBinaryOperatorType.Add:
oper = "+"; break;
case CodeBinaryOperatorType.Subtract:
oper = "-"; break;
case CodeBinaryOperatorType.Multiply:
oper = "*"; break;
case CodeBinaryOperatorType.Divide:
oper = "/"; break;
case CodeBinaryOperatorType.Modulus:
oper = "%"; break;
case CodeBinaryOperatorType.Assign:
oper = "="; break;
case CodeBinaryOperatorType.IdentityInequality:
oper = "!="; break;
case CodeBinaryOperatorType.IdentityEquality:
oper = "=="; break;
case CodeBinaryOperatorType.ValueEquality:
oper = "=="; break;
case CodeBinaryOperatorType.BitwiseOr:
oper = "|"; break;
case CodeBinaryOperatorType.BitwiseAnd:
oper = "&"; break;
case CodeBinaryOperatorType.BooleanOr:
oper = "||"; break;
case CodeBinaryOperatorType.BooleanAnd:
oper = "&&"; break;
case CodeBinaryOperatorType.LessThan:
oper = "<"; break;
case CodeBinaryOperatorType.LessThanOrEqual:
oper = "<="; break;
case CodeBinaryOperatorType.GreaterThan:
oper = ">"; break;
case CodeBinaryOperatorType.GreaterThanOrEqual:
oper = ">="; break;
default: return;
}
Output.Write(oper);
}
// Output a list of parameters.
protected virtual void OutputParameters
(CodeParameterDeclarationExpressionCollection parameters)
{
bool splitLines = (parameters.Count >= 16);
bool first = true;
if(splitLines)
{
writer.Indent += 1;
}
foreach(CodeParameterDeclarationExpression expr in parameters)
{
if(!first)
{
Output.Write(", ");
if(splitLines)
{
ContinueOnNewLine("");
}
}
else
{
first = false;
}
GenerateParameterDeclarationExpression(expr);
}
if(splitLines)
{
writer.Indent -= 1;
}
}
// Output a type.
protected abstract void OutputType(CodeTypeReference typeRef);
// Output the attributes for a type.
protected virtual void OutputTypeAttributes
(TypeAttributes attributes, bool isStruct, bool isEnum)
{
switch(attributes & TypeAttributes.VisibilityMask)
{
case TypeAttributes.NestedPrivate:
Output.Write("private "); break;
case TypeAttributes.Public:
case TypeAttributes.NestedPublic:
Output.Write("public "); break;
}
if(isStruct)
{
Output.Write("struct ");
}
else if(isEnum)
{
Output.Write("enum ");
}
else
{
if((attributes & TypeAttributes.ClassSemanticsMask) ==
TypeAttributes.Interface)
{
Output.Write("interface ");
}
else
{
if((attributes & TypeAttributes.Sealed) != 0)
{
Output.Write("sealed ");
}
if((attributes & TypeAttributes.Abstract) != 0)
{
Output.Write("abstract ");
}
Output.Write("class ");
}
}
}
// Output a type name pair.
protected virtual void OutputTypeNamePair
(CodeTypeReference typeRef, String name)
{
OutputType(typeRef);
Output.Write(" ");
OutputIdentifier(name);
}
// Quote a snippet string.
protected abstract String QuoteSnippetString(String value);
// Determine if this code generator supports a particular
// set of generator options.
protected abstract bool Supports(GeneratorSupport supports);
// Validate an identifier and throw an exception if not valid.
protected virtual void ValidateIdentifier(String value)
{
if(!IsValidIdentifier(value))
{
throw new ArgumentException(S._("Arg_InvalidIdentifier"));
}
}
// Validate all identifiers in a CodeDom tree.
public static void ValidateIdentifiers(CodeObject e)
{
Validator.Validate(e);
}
// Create an escaped identifier if "value" is a language keyword.
String ICodeGenerator.CreateEscapedIdentifier(String value)
{
return CreateEscapedIdentifier(value);
}
// Create a valid identifier if "value" is a language keyword.
String ICodeGenerator.CreateValidIdentifier(String value)
{
return CreateValidIdentifier(value);
}
// Set up this object for code generation.
private bool SetupForCodeGeneration(TextWriter w, CodeGeneratorOptions o)
{
if(writer != null)
{
if(writer.InnerWriter != w)
{
throw new InvalidOperationException
(S._("Invalid_CGWriterExists"));
}
return false;
}
else
{
if(o != null)
{
options = o;
}
else
{
options = new CodeGeneratorOptions();
}
writer = new IndentedTextWriter(w, options.IndentString);
return true;
}
}
// Finalize code generation.
private void FinalizeCodeGeneration(bool initialized)
{
if(initialized)
{
writer = null;
options = null;
}
}
// Generate code from a CodeDom compile unit.
void ICodeGenerator.GenerateCodeFromCompileUnit(CodeCompileUnit e,
TextWriter w,
CodeGeneratorOptions o)
{
bool initialized = SetupForCodeGeneration(w, o);
try
{
if(e is CodeSnippetCompileUnit)
{
GenerateSnippetCompileUnit((CodeSnippetCompileUnit)e);
}
else
{
GenerateCompileUnit(e);
}
}
finally
{
FinalizeCodeGeneration(initialized);
}
}
// Generate code from a CodeDom expression.
void ICodeGenerator.GenerateCodeFromExpression(CodeExpression e,
TextWriter w,
CodeGeneratorOptions o)
{
bool initialized = SetupForCodeGeneration(w, o);
try
{
GenerateExpression(e);
}
finally
{
FinalizeCodeGeneration(initialized);
}
}
// Generate code from a CodeDom namespace.
void ICodeGenerator.GenerateCodeFromNamespace(CodeNamespace e,
TextWriter w,
CodeGeneratorOptions o)
{
bool initialized = SetupForCodeGeneration(w, o);
try
{
GenerateNamespace(e);
}
finally
{
FinalizeCodeGeneration(initialized);
}
}
// Generate code from a CodeDom statement.
void ICodeGenerator.GenerateCodeFromStatement(CodeStatement e,
TextWriter w,
CodeGeneratorOptions o)
{
bool initialized = SetupForCodeGeneration(w, o);
try
{
GenerateStatement(e);
}
finally
{
FinalizeCodeGeneration(initialized);
}
}
// Generate code from a CodeDom type declaration.
void ICodeGenerator.GenerateCodeFromType(CodeTypeDeclaration e,
TextWriter w,
CodeGeneratorOptions o)
{
bool initialized = SetupForCodeGeneration(w, o);
try
{
GenerateType(e);
}
finally
{
FinalizeCodeGeneration(initialized);
}
}
// Get the type indicated by a CodeDom type reference.
String ICodeGenerator.GetTypeOutput(CodeTypeReference type)
{
return GetTypeOutput(type);
}
// Determine if "value" is a valid identifier.
bool ICodeGenerator.IsValidIdentifier(String value)
{
return IsValidIdentifier(value);
}
// Determine if this code generator supports a particular
// set of generator options.
bool ICodeGenerator.Supports(GeneratorSupport supports)
{
return Supports(supports);
}
// Validate an identifier and throw an exception if not valid.
void ICodeGenerator.ValidateIdentifier(String value)
{
ValidateIdentifier(value);
}
}; // class CodeGenerator
#endif // CONFIG_CODEDOM
}; // namespace System.CodeDom.Compiler
| |
//
// 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.Collections.Generic;
using System.Linq;
using System.Text;
using Encog.Util;
using Encog.Util.CSV;
namespace Encog.ML.Bayesian.Parse
{
/// <summary>
/// Parse a probability string.
/// </summary>
public class ParseProbability
{
/// <summary>
/// The network used.
/// </summary>
private readonly BayesianNetwork network;
/// <summary>
/// Parse the probability for the specified network.
/// </summary>
/// <param name="theNetwork">The network to parse for.</param>
public ParseProbability(BayesianNetwork theNetwork)
{
this.network = theNetwork;
}
/// <summary>
/// Add events, as they are pased.
/// </summary>
/// <param name="parser">The parser.</param>
/// <param name="results">The events found.</param>
/// <param name="delim">The delimiter to use.</param>
private void AddEvents(SimpleParser parser, IList<ParsedEvent> results, String delim)
{
bool done = false;
StringBuilder l = new StringBuilder();
while (!done && !parser.EOL())
{
char ch = parser.Peek();
if (delim.IndexOf(ch) != -1)
{
if (ch == ')' || ch == '|')
done = true;
ParsedEvent parsedEvent;
// deal with a value specified by + or -
if (l.Length > 0 && l[0] == '+')
{
String l2 = l.ToString().Substring(1);
parsedEvent = new ParsedEvent(l2.Trim());
parsedEvent.Value = "true";
}
else if (l.Length > 0 && l[0] == '-')
{
String l2 = l.ToString().Substring(1);
parsedEvent = new ParsedEvent(l2.Trim());
parsedEvent.Value = "false";
}
else
{
String l2 = l.ToString();
parsedEvent = new ParsedEvent(l2.Trim());
}
// parse choices
if (ch == '[')
{
parser.Advance();
int index = 0;
while (ch != ']' && !parser.EOL())
{
String labelName = parser.ReadToChars(":,]");
if (parser.Peek() == ':')
{
parser.Advance();
parser.EatWhiteSpace();
double min = double.Parse(parser.ReadToWhiteSpace());
parser.EatWhiteSpace();
if (!parser.LookAhead("to", true))
{
throw new BayesianError("Expected \"to\" in probability choice range.");
}
parser.Advance(2);
double max = CSVFormat.EgFormat.Parse(parser.ReadToChars(",]"));
parsedEvent.ChoiceList.Add(new ParsedChoice(labelName, min, max));
}
else
{
parsedEvent.ChoiceList.Add(new ParsedChoice(labelName, index++));
}
parser.EatWhiteSpace();
ch = parser.Peek();
if (ch == ',')
{
parser.Advance();
}
}
}
// deal with a value specified by =
if (parser.Peek() == '=')
{
parser.ReadChar();
String value = parser.ReadToChars(delim);
// BayesianEvent evt = this.network.getEvent(parsedEvent.getLabel());
parsedEvent.Value = value;
}
if (ch == ',')
{
parser.Advance();
}
if (ch == ']')
{
parser.Advance();
}
if (parsedEvent.Label.Length > 0)
{
results.Add(parsedEvent);
}
l.Length = 0;
}
else
{
parser.Advance();
l.Append(ch);
}
}
}
/// <summary>
/// Parse the given line.
/// </summary>
/// <param name="line">The line to parse.</param>
/// <returns>The parsed probability.</returns>
public ParsedProbability Parse(String line)
{
ParsedProbability result = new ParsedProbability();
SimpleParser parser = new SimpleParser(line);
parser.EatWhiteSpace();
if (!parser.LookAhead("P(", true))
{
throw new EncogError("Bayes table lines must start with P(");
}
parser.Advance(2);
// handle base
AddEvents(parser, result.BaseEvents, "|,)=[]");
// handle conditions
if (parser.Peek() == '|')
{
parser.Advance();
AddEvents(parser, result.GivenEvents, ",)=[]");
}
if (parser.Peek() != ')')
{
throw new BayesianError("Probability not properly terminated.");
}
return result;
}
/// <summary>
/// Parse a probability list.
/// </summary>
/// <param name="network">The network to parse for.</param>
/// <param name="line">The line to parse.</param>
/// <returns>The parsed list.</returns>
public static IList<ParsedProbability> ParseProbabilityList(BayesianNetwork network, String line)
{
IList<ParsedProbability> result = new List<ParsedProbability>();
StringBuilder prob = new StringBuilder();
for (int i = 0; i < line.Length; i++)
{
char ch = line[i];
if (ch == ')')
{
prob.Append(ch);
ParseProbability parse = new ParseProbability(network);
ParsedProbability parsedProbability = parse.Parse(prob.ToString());
result.Add(parsedProbability);
prob.Length = 0;
}
else
{
prob.Append(ch);
}
}
return result;
}
}
}
| |
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT License
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Internal;
using MySqlConnector;
using System;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Pomelo.Extensions.Caching.MySql
{
internal class DatabaseOperations : IDatabaseOperations
{
/// <summary>
/// Since there is no specific exception type representing a 'duplicate key' error, we are relying on
/// the following message number which represents the following text in MySql Server database.
/// "Violation of %ls constraint '%.*ls'. Cannot insert duplicate key in object '%.*ls'.
/// The duplicate key value is %ls."
/// You can find the list of system messages by executing the following query:
/// "SELECT * FROM sys.messages WHERE [text] LIKE '%duplicate%'"
/// </summary>
private const int DuplicateKeyErrorId = (int)MySqlErrorCode.DuplicateKey;
protected const string GetTableSchemaErrorText =
"Could not retrieve information of table with schema '{0}' and " +
"name '{1}'. Make sure you have the table setup and try again. " +
"Connection string: {2}";
public DatabaseOperations(
string readConnectionString, string writeConnectionString, string schemaName, string tableName, ISystemClock systemClock)
{
ReadConnectionString = readConnectionString;
WriteConnectionString = writeConnectionString;
SchemaName = schemaName;
TableName = tableName;
SystemClock = systemClock;
MySqlQueries = new MySqlQueries(schemaName, tableName);
}
protected MySqlQueries MySqlQueries { get; }
protected string ReadConnectionString { get; }
protected string WriteConnectionString { get; }
protected string SchemaName { get; }
protected string TableName { get; }
protected ISystemClock SystemClock { get; }
public void DeleteCacheItem(string key)
{
using (var connection = new MySqlConnection(WriteConnectionString))
{
using (var command = new MySqlCommand(MySqlQueries.DeleteCacheItem, connection))
{
command.Parameters.AddCacheItemId(key);
connection.Open();
command.ExecuteNonQuery();
}
}
}
public async Task DeleteCacheItemAsync(string key, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
using (var connection = new MySqlConnection(WriteConnectionString))
{
using (var command = new MySqlCommand(MySqlQueries.DeleteCacheItem, connection))
{
command.Parameters.AddCacheItemId(key);
await connection.OpenAsync(token);
await command.ExecuteNonQueryAsync(token);
}
}
}
public virtual byte[] GetCacheItem(string key)
{
return GetCacheItem(key, includeValue: true);
}
public virtual async Task<byte[]> GetCacheItemAsync(string key, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
return await GetCacheItemAsync(key, includeValue: true, token: token);
}
public void RefreshCacheItem(string key)
{
GetCacheItem(key, includeValue: false);
}
public async Task RefreshCacheItemAsync(string key, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
await GetCacheItemAsync(key, includeValue: false, token: token);
}
public int DeleteExpiredCacheItems()
{
var utcNow = SystemClock.UtcNow;
using (var connection = new MySqlConnection(WriteConnectionString))
{
using (var command = new MySqlCommand(MySqlQueries.DeleteExpiredCacheItems, connection))
{
command.Parameters.AddWithValue("UtcNow", MySqlDbType.DateTime, utcNow.UtcDateTime);
connection.Open();
var affectedRowCount = command.ExecuteNonQuery();
return affectedRowCount;
}
}
}
public async Task<int> DeleteExpiredCacheItemsAsync()
{
var utcNow = SystemClock.UtcNow;
using (var connection = new MySqlConnection(WriteConnectionString))
{
using (var command = new MySqlCommand(MySqlQueries.DeleteExpiredCacheItems, connection))
{
command.Parameters.AddWithValue("UtcNow", MySqlDbType.DateTime, utcNow.UtcDateTime);
await connection.OpenAsync();
var affectedRowCount = await command.ExecuteNonQueryAsync();
return affectedRowCount;
}
}
}
public virtual void SetCacheItem(string key, byte[] value, DistributedCacheEntryOptions options)
{
var utcNow = SystemClock.UtcNow;
var absoluteExpiration = GetAbsoluteExpiration(utcNow, options);
ValidateOptions(options.SlidingExpiration, absoluteExpiration);
var _absoluteExpiration = absoluteExpiration?.DateTime;
using (var connection = new MySqlConnection(WriteConnectionString))
{
using (var upsertCommand = new MySqlCommand(MySqlQueries.SetCacheItem, connection))
{
upsertCommand.Parameters
.AddCacheItemId(key)
.AddCacheItemValue(value)
.AddSlidingExpirationInSeconds(options.SlidingExpiration)
.AddAbsoluteExpiration(_absoluteExpiration)
.AddWithValue("UtcNow", MySqlDbType.DateTime, utcNow.UtcDateTime);
connection.Open();
try
{
upsertCommand.ExecuteNonQuery();
}
catch (MySqlException ex)
{
if (IsDuplicateKeyException(ex))
{
// There is a possibility that multiple requests can try to add the same item to the cache, in
// which case we receive a 'duplicate key' exception on the primary key column.
}
else
{
throw;
}
}
}
}
}
public virtual async Task SetCacheItemAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
var utcNow = SystemClock.UtcNow;
var absoluteExpiration = GetAbsoluteExpiration(utcNow, options);
ValidateOptions(options.SlidingExpiration, absoluteExpiration);
var _absoluteExpiration = absoluteExpiration?.DateTime;
using (var connection = new MySqlConnection(WriteConnectionString))
{
using (var upsertCommand = new MySqlCommand(MySqlQueries.SetCacheItem, connection))
{
upsertCommand.Parameters
.AddCacheItemId(key)
.AddCacheItemValue(value)
.AddSlidingExpirationInSeconds(options.SlidingExpiration)
.AddAbsoluteExpiration(_absoluteExpiration)
.AddWithValue("UtcNow", MySqlDbType.DateTime, utcNow.UtcDateTime);
await connection.OpenAsync(token);
try
{
await upsertCommand.ExecuteNonQueryAsync(token);
}
catch (MySqlException ex)
{
if (IsDuplicateKeyException(ex))
{
// There is a possibility that multiple requests can try to add the same item to the cache, in
// which case we receive a 'duplicate key' exception on the primary key column.
}
else
{
throw;
}
}
}
}
}
protected virtual byte[] GetCacheItem(string key, bool includeValue)
{
var utcNow = SystemClock.UtcNow;
string query;
if (includeValue)
{
query = MySqlQueries.GetCacheItem;
}
else
{
query = MySqlQueries.GetCacheItemWithoutValue;
}
byte[] value = null;
//TimeSpan? slidingExpiration = null;
//DateTimeOffset? absoluteExpiration = null;
//DateTimeOffset expirationTime;
using (var connection = new MySqlConnection(WriteConnectionString))
{
using (var command = new MySqlCommand(query, connection))
{
command.Parameters
.AddCacheItemId(key)
.AddWithValue("UtcNow", MySqlDbType.DateTime, utcNow.UtcDateTime);
connection.Open();
using (var reader = command.ExecuteReader(
CommandBehavior.SequentialAccess | CommandBehavior.SingleRow | CommandBehavior.SingleResult))
{
if (reader.Read())
{
/*var id = reader.GetFieldValue<string>(Columns.Indexes.CacheItemIdIndex);
expirationTime = reader.GetFieldValue<DateTime>(Columns.Indexes.ExpiresAtTimeIndex);
if (!reader.IsDBNull(Columns.Indexes.SlidingExpirationInSecondsIndex))
{
slidingExpiration = TimeSpan.FromSeconds(
reader.GetFieldValue<long>(Columns.Indexes.SlidingExpirationInSecondsIndex));
}
if (!reader.IsDBNull(Columns.Indexes.AbsoluteExpirationIndex))
{
absoluteExpiration = reader.GetFieldValue<DateTimeOffset>(
Columns.Indexes.AbsoluteExpirationIndex);
}*/
if (includeValue)
{
value = reader.GetFieldValue<byte[]>(Columns.Indexes.CacheItemValueIndex);
}
}
else
{
return null;
}
}
}
return value;
}
}
protected virtual async Task<byte[]> GetCacheItemAsync(string key, bool includeValue, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
var utcNow = SystemClock.UtcNow;
string query;
if (includeValue)
{
query = MySqlQueries.GetCacheItem;
}
else
{
query = MySqlQueries.GetCacheItemWithoutValue;
}
byte[] value = null;
//TimeSpan? slidingExpiration = null;
//DateTime? absoluteExpiration = null;
//DateTime expirationTime;
using (var connection = new MySqlConnection(WriteConnectionString))
{
using (var command = new MySqlCommand(query, connection))
{
command.Parameters
.AddCacheItemId(key)
.AddWithValue("UtcNow", MySqlDbType.DateTime, utcNow.UtcDateTime);
await connection.OpenAsync(token);
using (var reader = await command.ExecuteReaderAsync(
CommandBehavior.SequentialAccess | CommandBehavior.SingleRow | CommandBehavior.SingleResult,
token))
{
if (await reader.ReadAsync(token))
{
/*var id = await reader.GetFieldValueAsync<string>(Columns.Indexes.CacheItemIdIndex);
expirationTime = await reader.GetFieldValueAsync<DateTime>(
Columns.Indexes.ExpiresAtTimeIndex);
if (!await reader.IsDBNullAsync(Columns.Indexes.SlidingExpirationInSecondsIndex))
{
slidingExpiration = TimeSpan.FromSeconds(
await reader.GetFieldValueAsync<long>(Columns.Indexes.SlidingExpirationInSecondsIndex));
}
if (!await reader.IsDBNullAsync(Columns.Indexes.AbsoluteExpirationIndex))
{
absoluteExpiration = await reader.GetFieldValueAsync<DateTime>(
Columns.Indexes.AbsoluteExpirationIndex);
}*/
if (includeValue)
{
value = await reader.GetFieldValueAsync<byte[]>(Columns.Indexes.CacheItemValueIndex, token);
}
}
else
{
return null;
}
}
}
return value;
}
}
protected bool IsDuplicateKeyException(MySqlException ex)
{
return ex.Number == DuplicateKeyErrorId;
}
protected DateTimeOffset? GetAbsoluteExpiration(DateTimeOffset utcNow, DistributedCacheEntryOptions options)
{
// calculate absolute expiration
DateTimeOffset? absoluteExpiration = null;
if (options.AbsoluteExpirationRelativeToNow.HasValue)
{
absoluteExpiration = utcNow.Add(options.AbsoluteExpirationRelativeToNow.Value);
}
else if (options.AbsoluteExpiration.HasValue)
{
if (options.AbsoluteExpiration.Value <= utcNow)
{
throw new InvalidOperationException("The absolute expiration value must be in the future.");
}
absoluteExpiration = options.AbsoluteExpiration.Value;
}
return absoluteExpiration;
}
protected void ValidateOptions(TimeSpan? slidingExpiration, DateTimeOffset? absoluteExpiration)
{
if (!slidingExpiration.HasValue && !absoluteExpiration.HasValue)
{
throw new InvalidOperationException("Either absolute or sliding expiration needs " +
"to be provided.");
}
}
}
}
| |
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/Other/SMAA")]
public class AntiAliasing : MonoBehaviour
{
public enum DebugDisplay
{
Off,
Edges,
Weights,
Depth
}
public enum EdgeType
{
Luminance,
Color,
Depth
}
public enum TemporalType
{
Off,
SMAA_2x,
Standard_2x,
Standard_4x,
Standard_8x,
Standard_16x
}
private enum Passes
{
Copy = 0,
LumaDetection = 1,
ClearToBlack = 2,
WeightCalculation = 3,
WeightsAndBlend1 = 4,
WeightsAndBlend2 = 5,
ColorDetection = 6,
MergeFrames = 7,
DepthDetection = 8,
DebugDepth = 9
}
public DebugDisplay displayType = DebugDisplay.Off;
// we could make this public, but color and luma are less reliable so we can
// hardcode this to depth for now
public EdgeType edgeType = EdgeType.Depth;
public Texture2D areaTex;
public Texture2D searchTex;
// temporal AA parameters
private Matrix4x4 m_BaseProjectionMatrix;
private Matrix4x4 m_PrevViewProjMat;
private Camera m_AACamera;
private int m_SampleIndex;
public TemporalType temporalType = TemporalType.Off;
[Range(0, 1)] public float temporalAccumulationWeight = 0.3f;
// This should be hidden from view when EdgeType is not Depth
[Range(0.01f, 1.0f)] public float depthThreshold = 0.1f;
private static Matrix4x4 CalculateViewProjection(Camera camera, Matrix4x4 prjMatrix)
{
Matrix4x4 viewMat = camera.worldToCameraMatrix;
Matrix4x4 projMat = GL.GetGPUProjectionMatrix(prjMatrix, true);
return projMat * viewMat;
}
private void StoreBaseProjectionMatrix(Matrix4x4 prjMatrix)
{
m_BaseProjectionMatrix = prjMatrix;
}
private void StorePreviousViewProjMatrix(Matrix4x4 viewPrjMatrix)
{
m_PrevViewProjMat = viewPrjMatrix;
}
private Camera aaCamera
{
get
{
if (m_AACamera == null)
m_AACamera = GetComponent<Camera>();
return m_AACamera;
}
}
public void UpdateSampleIndex()
{
int numSamples = 1;
if (temporalType == TemporalType.SMAA_2x || temporalType == TemporalType.Standard_2x)
{
numSamples = 2;
}
else if (temporalType == TemporalType.Standard_4x)
{
numSamples = 4;
}
else if (temporalType == TemporalType.Standard_8x)
{
numSamples = 8;
}
else if (temporalType == TemporalType.Standard_16x)
{
numSamples = 16;
}
m_SampleIndex = (m_SampleIndex + 1) % numSamples;
}
private Vector2 GetJitterStandard2X()
{
int[,] samples =
{
{4, 4},
{-4, -4},
};
int sampleX = samples[m_SampleIndex, 0];
int sampleY = samples[m_SampleIndex, 1];
float v0 = sampleX / 16.0f;
float v1 = sampleY / 16.0f;
return new Vector2(v0, v1);
}
private Vector2 GetJitterStandard4X()
{
int[,] samples =
{
{-2, -6},
{6, -2},
{-6, 2},
{2, 6}
};
int sampleX = samples[m_SampleIndex, 0];
int sampleY = samples[m_SampleIndex, 1];
float v0 = sampleX / 16.0f;
float v1 = sampleY / 16.0f;
return new Vector2(v0, v1);
}
private Vector2 GetJitterStandard8X()
{
int[,] samples =
{
{7, -7},
{-3, -5},
{3, 7},
{-7, -1},
{5, 1},
{-1, 3},
{1, -3},
{-5, 5}
};
int sampleX = samples[m_SampleIndex, 0];
int sampleY = samples[m_SampleIndex, 1];
float v0 = sampleX / 16.0f;
float v1 = sampleY / 16.0f;
return new Vector2(v0, v1);
}
private Vector2 GetJitterStandard16X()
{
int[,] samples =
{
{7, -4},
{-1, -3},
{3, -5},
{-5, -2},
{6, 7},
{-2, 6},
{2, 5},
{-6, -4},
{4, -1},
{-3, 2},
{1, 1},
{-8, 0},
{5, 3},
{-4, -6},
{0, -7},
{-7, -8}
};
int sampleX = samples[m_SampleIndex, 0];
int sampleY = samples[m_SampleIndex, 1];
float v0 = (sampleX + .5f) / 16.0f;
float v1 = (sampleY + .5f) / 16.0f;
return new Vector2(v0, v1);
}
private Vector2 GetJitterSMAAX2()
{
float jitterAmount = .25f;
jitterAmount *= (m_SampleIndex == 0) ? -1.0f : 1.0f;
//Debug.Log("Jitter");
//jitterAmount = 0.0f;
float v0 = jitterAmount;
float v1 = -jitterAmount;
return new Vector2(v0, v1);
}
private Vector2 GetCurrentJitter()
{
// add a quarter pixel diagonal translation
Vector2 jitterOffset = new Vector2(0.0f, 0.0f);
if (temporalType == TemporalType.SMAA_2x)
{
jitterOffset = GetJitterSMAAX2();
}
else if (temporalType == TemporalType.Standard_2x)
{
jitterOffset = GetJitterStandard2X();
}
else if (temporalType == TemporalType.Standard_4x)
{
jitterOffset = GetJitterStandard4X();
}
else if (temporalType == TemporalType.Standard_8x)
{
jitterOffset = GetJitterStandard8X();
}
else if (temporalType == TemporalType.Standard_16x)
{
jitterOffset = GetJitterStandard16X();
}
return jitterOffset;
}
private void OnPreCull()
{
StoreBaseProjectionMatrix(aaCamera.projectionMatrix);
if (temporalType != TemporalType.Off)
{
// flip
UpdateSampleIndex();
Vector2 jitterOffset = GetCurrentJitter();
Matrix4x4 offset = Matrix4x4.identity;
offset.m03 = jitterOffset.x * 2.0f / aaCamera.pixelWidth;
offset.m13 = jitterOffset.y * 2.0f / aaCamera.pixelHeight;
var offsetMatrix = offset * m_BaseProjectionMatrix;
aaCamera.projectionMatrix = offsetMatrix;
}
}
private void OnPostRender()
{
aaCamera.ResetProjectionMatrix();
}
// usual & internal stuff
public Shader smaaShader = null;
private Material m_SmaaMaterial;
public Material smaaMaterial
{
get
{
//if (m_SmaaMaterial == null)
// m_SmaaMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(smaaShader);
return m_SmaaMaterial;
}
}
// accumulation render texture
private RenderTexture m_RtAccum;
protected void OnEnable()
{
if (smaaShader == null)
smaaShader = Shader.Find("Hidden/SMAA");
//if (!ImageEffectHelper.IsSupported(smaaShader, true, true, this))
//{
// enabled = false;
// Debug.LogWarning("The image effect " + ToString() + " has been disabled as it's not supported on the current platform.");
// return;
//}
aaCamera.depthTextureMode |= DepthTextureMode.Depth;
}
private void OnDisable()
{
aaCamera.ResetProjectionMatrix();
if (m_SmaaMaterial)
{
DestroyImmediate(m_SmaaMaterial);
m_SmaaMaterial = null;
}
if (m_RtAccum)
{
DestroyImmediate(m_RtAccum);
m_RtAccum = null;
}
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (smaaMaterial == null)
{
Graphics.Blit(source, destination);
return;
}
bool isFirst = false;
// relying on short-circuit evaluation here
if (m_RtAccum == null || (m_RtAccum.width != source.width || m_RtAccum.height != source.height))
{
if (m_RtAccum != null)
RenderTexture.ReleaseTemporary(m_RtAccum);
m_RtAccum = RenderTexture.GetTemporary(source.width, source.height, 0, source.format);
m_RtAccum.hideFlags = HideFlags.DontSave;
isFirst = true;
}
// the values for jitter offset are hardcoded based on the SMAA shader
int actualJitterOffset = 0;
if (temporalType == TemporalType.SMAA_2x)
actualJitterOffset = m_SampleIndex < 1 ? 1 : 2;
var sizeX = source.width;
var sizeY = source.height;
// should this always be RGBA8?
const RenderTextureFormat rtFormat = RenderTextureFormat.ARGB32;
var rtEdges = RenderTexture.GetTemporary(sizeX, sizeY, 0, rtFormat);
var rtWeights = RenderTexture.GetTemporary(sizeX, sizeY, 0, rtFormat);
// motion blur matrix
var matrix = CalculateViewProjection(aaCamera, m_BaseProjectionMatrix);
Matrix4x4 invViewPrj = Matrix4x4.Inverse(matrix);
smaaMaterial.SetMatrix("_ToPrevViewProjCombined", m_PrevViewProjMat * invViewPrj);
smaaMaterial.SetInt("_JitterOffset", actualJitterOffset);
smaaMaterial.SetTexture("areaTex", areaTex);
smaaMaterial.SetTexture("searchTex", searchTex);
smaaMaterial.SetTexture("colorTex", source);
smaaMaterial.SetVector("_PixelSize", new Vector4(1.0f / source.width, 1.0f / source.height, 0.0f, 0.0f));
Vector2 pixelOffset = GetCurrentJitter();
smaaMaterial.SetVector("_PixelOffset", new Vector4(pixelOffset.x / source.width, pixelOffset.y / source.height, 0.0f, 0.0f));
smaaMaterial.SetTexture("edgesTex", rtEdges);
smaaMaterial.SetTexture("blendTex", rtWeights);
smaaMaterial.SetFloat("_TemporalAccum", temporalAccumulationWeight);
// clear
Graphics.Blit(source, rtEdges, smaaMaterial, (int)Passes.ClearToBlack);
if (edgeType == EdgeType.Luminance)
{
// luma detect
Graphics.Blit(source, rtEdges, smaaMaterial, (int)Passes.LumaDetection);
}
else if (edgeType == EdgeType.Color)
{
// color detect
Graphics.Blit(source, rtEdges, smaaMaterial, (int)Passes.ColorDetection);
}
else
{
smaaMaterial.SetFloat("_DepthThreshold", 0.01f * depthThreshold);
// depth detect
Graphics.Blit(source, rtEdges, smaaMaterial, (int)Passes.DepthDetection);
}
// calculate weights
Graphics.Blit(rtEdges, rtWeights, smaaMaterial, (int)Passes.WeightCalculation);
if (temporalType == TemporalType.Off)
{
Graphics.Blit(source, destination, smaaMaterial, (int)Passes.WeightsAndBlend1);
}
else
{
// temporal blending
RenderTexture rtTemp = RenderTexture.GetTemporary(source.width, source.height, 0, source.format);
// render for this frame
if (temporalType == TemporalType.SMAA_2x)
{
// set the accumulation texture
smaaMaterial.SetTexture("accumTex", m_RtAccum);
if (isFirst)
{
// if we are the first frame, just copy
Graphics.Blit(source, rtTemp, smaaMaterial, (int)Passes.WeightsAndBlend1);
}
else
{
// if not first, then blend with accumulation
Graphics.Blit(source, rtTemp, smaaMaterial, (int)Passes.WeightsAndBlend2);
}
// copy to accumulation
Graphics.Blit(rtTemp, m_RtAccum, smaaMaterial, (int)Passes.Copy);
// copy to destination
Graphics.Blit(rtTemp, destination, smaaMaterial, (int)Passes.Copy);
}
else
{
// solve SMAA as 1x
Graphics.Blit(source, rtTemp, smaaMaterial, 4);
if (isFirst)
{
Graphics.Blit(rtTemp, m_RtAccum, smaaMaterial, 0);
}
// set the accumulation texture
smaaMaterial.SetTexture("accumTex", m_RtAccum);
smaaMaterial.SetTexture("smaaTex", rtTemp);
rtTemp.filterMode = FilterMode.Bilinear;
RenderTexture rtTemp2 = RenderTexture.GetTemporary(source.width, source.height, 0, source.format);
// copy to accumulation
Graphics.Blit(rtTemp, rtTemp2, smaaMaterial, (int)Passes.MergeFrames);
// copy to accumulation
Graphics.Blit(rtTemp2, m_RtAccum, smaaMaterial, (int)Passes.Copy);
// copy to destination
Graphics.Blit(rtTemp2, destination, smaaMaterial, (int)Passes.Copy);
RenderTexture.ReleaseTemporary(rtTemp2);
}
RenderTexture.ReleaseTemporary(rtTemp);
}
if (displayType == DebugDisplay.Edges)
{
// copy to accumulation
Graphics.Blit(rtEdges, destination, smaaMaterial, (int)Passes.Copy);
}
else if (displayType == DebugDisplay.Weights)
{
// copy to accumulation
Graphics.Blit(rtWeights, destination, smaaMaterial, (int)Passes.Copy);
}
else if (displayType == DebugDisplay.Depth)
{
Graphics.Blit(null, destination, smaaMaterial, (int)Passes.DebugDepth);
}
RenderTexture.ReleaseTemporary(rtEdges);
RenderTexture.ReleaseTemporary(rtWeights);
// store matrix for next frame
StorePreviousViewProjMatrix(matrix);
}
}
}
| |
/*
* ASN1Builder.cs - Implementation of the
* "System.Security.Cryptography.ASN1Builder" class.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Security.Cryptography
{
#if CONFIG_CRYPTO
using System;
using System.Text;
using System.Collections;
// This class is used to help with building byte arrays that are
// stored in the Abstract Syntax Notation One (ASN.1) encoding.
internal class ASN1Builder
{
// Internal state.
protected ASN1Type type;
protected ArrayList list;
// Constructors.
public ASN1Builder() : this(ASN1Type.Sequence) {}
public ASN1Builder(ASN1Type type)
{
this.type = type;
this.list = new ArrayList();
}
protected ASN1Builder(ASN1Type type, int dummy)
{
this.type = type;
this.list = null;
}
// Add a container to this builder.
public ASN1Builder AddContainer(ASN1Type type)
{
ASN1Builder container = new ASN1Builder(type);
list.Add(container);
return container;
}
// Add a sequence to this builder.
public ASN1Builder AddSequence(ASN1Type type)
{
return AddContainer(type);
}
public ASN1Builder AddSequence()
{
return AddContainer(ASN1Type.Sequence);
}
// Add a set to this builder.
public ASN1Builder AddSet(ASN1Type type)
{
return AddContainer(type);
}
public ASN1Builder AddSet()
{
return AddContainer(ASN1Type.Set);
}
// Add a byte array field to this builder.
public void AddByteArray(ASN1Type type, byte[] value)
{
list.Add(new ASN1ByteBuilder(type, value));
}
// Add a bit string to this builder.
public void AddBitString(ASN1Type type, byte[] value)
{
list.Add(new ASN1BitStringBuilder(type, value));
}
public void AddBitString(byte[] value)
{
list.Add(new ASN1BitStringBuilder(ASN1Type.BitString, value));
}
public ASN1Builder AddBitStringContents()
{
return new ASN1BitStringContentsBuilder(ASN1Type.BitString);
}
// Add a string to this builder.
public void AddString(ASN1Type type, String value)
{
list.Add(new ASN1ByteBuilder
(type, Encoding.UTF8.GetBytes(value)));
}
public void AddString(String value)
{
AddString(ASN1Type.IA5String, value);
}
public void AddPrintableString(String value)
{
AddString(ASN1Type.PrintableString, value);
}
// Add a 32-bit integer to this builder.
public void AddInt32(ASN1Type type, int value)
{
list.Add(new ASN1Int32Builder(type, value));
}
public void AddInt32(int value)
{
AddInt32(ASN1Type.Integer, value);
}
// Add a 64-bit integer to this builder.
public void AddInt64(ASN1Type type, long value)
{
list.Add(new ASN1Int64Builder(type, value));
}
public void AddInt64(long value)
{
AddInt64(ASN1Type.Integer, value);
}
// Add a big integer to this builder.
public void AddBigInt(ASN1Type type, byte[] value)
{
list.Add(new ASN1BigIntBuilder(type, value));
}
public void AddBigInt(byte[] value)
{
AddBigInt(ASN1Type.Integer, value);
}
// Add an object identifier to this builder.
public void AddObjectIdentifier(ASN1Type type, byte[] value)
{
AddByteArray(type, value);
}
public void AddObjectIdentifier(byte[] value)
{
AddByteArray(ASN1Type.ObjectIdentifier, value);
}
// Add an octet string to this builder.
public void AddOctetString(ASN1Type type, byte[] value)
{
AddByteArray(type, value);
}
public void AddOctetString(byte[] value)
{
AddByteArray(ASN1Type.OctetString, value);
}
// Add a UTCTime value to this builder.
public void AddUTCTime(ASN1Type type, String value)
{
AddString(type, value);
}
public void AddUTCTime(String value)
{
AddString(ASN1Type.UTCTime, value);
}
// Add a null value to this builder.
public void AddNull()
{
AddByteArray(ASN1Type.Null, new byte [0]);
}
// Convert this builder into a byte array.
public byte[] ToByteArray()
{
int length = GetLength();
byte[] result = new byte [length];
Encode(result, 0);
return result;
}
// Get the length of this builder when it is encoded using DER.
protected virtual int GetLength()
{
int len = 0;
foreach(ASN1Builder builder in list)
{
len += builder.GetLength();
}
return 1 + GetBytesForLength(len) + len;
}
// Encode this builder in a byte array as DER. Returns the length.
protected virtual int Encode(byte[] result, int offset)
{
int start = offset;
int len = 0;
foreach(ASN1Builder builder in list)
{
len += builder.GetLength();
}
result[offset++] = (byte)type;
offset += EncodeLength(result, offset, len);
foreach(ASN1Builder builder in list)
{
offset += builder.Encode(result, offset);
}
return offset - start;
}
// Get the number of bytes that are needed to store a length value.
private static int GetBytesForLength(int length)
{
if(length < (1 << 7))
{
return 1;
}
else if(length < (1 << 14))
{
return 2;
}
else if(length < (1 << 21))
{
return 3;
}
else if(length < (1 << 28))
{
return 4;
}
else
{
return 5;
}
}
// Encode a length value and return the number of bytes used.
private static int EncodeLength(byte[] result, int offset, int length)
{
if(length < (1 << 7))
{
result[offset] = (byte)length;
return 1;
}
else if(length < (1 << 14))
{
result[offset] = (byte)(0x80 | (length >> 7));
result[offset + 1] = (byte)(length & 0x7F);
return 2;
}
else if(length < (1 << 21))
{
result[offset] = (byte)(0x80 | (length >> 14));
result[offset + 1] = (byte)((length >> 7) | 0x80);
result[offset + 2] = (byte)(length & 0x7F);
return 3;
}
else if(length < (1 << 28))
{
result[offset] = (byte)(0x80 | (length >> 21));
result[offset + 1] = (byte)((length >> 14) | 0x80);
result[offset + 2] = (byte)((length >> 7) | 0x80);
result[offset + 3] = (byte)(length & 0x7F);
return 4;
}
else
{
result[offset] = (byte)(0x80 | (length >> 28));
result[offset + 1] = (byte)((length >> 21) | 0x80);
result[offset + 2] = (byte)((length >> 14) | 0x80);
result[offset + 3] = (byte)((length >> 7) | 0x80);
result[offset + 4] = (byte)(length & 0x7F);
return 5;
}
}
// Builder node that stores a byte array.
private class ASN1ByteBuilder : ASN1Builder
{
// Internal state.
private byte[] value;
// Constructor.
public ASN1ByteBuilder(ASN1Type type, byte[] value)
: base(type, 0)
{
this.value = value;
}
// Get the length of this builder when it is encoded using DER.
protected override int GetLength()
{
return 1 + GetBytesForLength(value.Length) + value.Length;
}
// Encode this builder in a byte array as DER. Returns the length.
protected override int Encode(byte[] result, int offset)
{
int start = offset;
result[offset++] = (byte)type;
offset += EncodeLength(result, offset, value.Length);
Array.Copy(value, 0, result, offset, value.Length);
return (offset + value.Length - start);
}
}; // class ASN1ByteBuilder
// Builder node that stores a 32-bit integer.
private class ASN1Int32Builder : ASN1Builder
{
// Internal state.
private int value;
// Constructor.
public ASN1Int32Builder(ASN1Type type, int value)
: base(type, 0)
{
this.value = value;
}
// Get the length of this builder when it is encoded using DER.
protected override int GetLength()
{
if(value >= -0x80 && value < 0x80)
{
return 3;
}
else if(value >= -0x8000 && value < 0x8000)
{
return 4;
}
else if(value >= -0x800000 && value < 0x800000)
{
return 5;
}
else
{
return 6;
}
}
// Encode this builder in a byte array as DER. Returns the length.
protected override int Encode(byte[] result, int offset)
{
if(value >= -0x80 && value < 0x80)
{
result[offset] = (byte)type;
result[offset + 1] = (byte)1;
result[offset + 2] = (byte)value;
return 3;
}
else if(value >= -0x8000 && value < 0x8000)
{
result[offset] = (byte)type;
result[offset + 1] = (byte)2;
result[offset + 2] = (byte)(value >> 8);
result[offset + 3] = (byte)value;
return 4;
}
else if(value >= -0x800000 && value < 0x800000)
{
result[offset] = (byte)type;
result[offset + 1] = (byte)3;
result[offset + 2] = (byte)(value >> 16);
result[offset + 3] = (byte)(value >> 8);
result[offset + 4] = (byte)value;
return 5;
}
else
{
result[offset] = (byte)type;
result[offset + 1] = (byte)4;
result[offset + 2] = (byte)(value >> 24);
result[offset + 3] = (byte)(value >> 16);
result[offset + 4] = (byte)(value >> 8);
result[offset + 5] = (byte)value;
return 6;
}
}
}; // class ASN1Int32Builder
// Builder node that stores a 64-bit integer.
private class ASN1Int64Builder : ASN1Builder
{
// Internal state.
private long value;
// Constructor.
public ASN1Int64Builder(ASN1Type type, long value)
: base(type, 0)
{
this.value = value;
}
// Get the length of this builder when it is encoded using DER.
protected override int GetLength()
{
if(value >= -0x80L && value < 0x80L)
{
return 3;
}
else if(value >= -0x8000L && value < 0x8000L)
{
return 4;
}
else if(value >= -0x800000L && value < 0x800000L)
{
return 5;
}
else if(value >= -0x80000000L && value < 0x80000000L)
{
return 6;
}
else if(value >= -0x8000000000L && value < 0x8000000000L)
{
return 7;
}
else if(value >= -0x800000000000L && value < 0x800000000000L)
{
return 8;
}
else if(value >= -0x80000000000000L &&
value < 0x80000000000000L)
{
return 9;
}
else
{
return 10;
}
}
// Encode this builder in a byte array as DER. Returns the length.
protected override int Encode(byte[] result, int offset)
{
if(value >= -0x80L && value < 0x80L)
{
result[offset] = (byte)type;
result[offset + 1] = (byte)1;
result[offset + 2] = (byte)value;
return 3;
}
else if(value >= -0x8000L && value < 0x8000L)
{
result[offset] = (byte)type;
result[offset + 1] = (byte)2;
result[offset + 2] = (byte)(value >> 8);
result[offset + 3] = (byte)value;
return 4;
}
else if(value >= -0x800000L && value < 0x800000L)
{
result[offset] = (byte)type;
result[offset + 1] = (byte)3;
result[offset + 2] = (byte)(value >> 16);
result[offset + 3] = (byte)(value >> 8);
result[offset + 4] = (byte)value;
return 5;
}
else if(value >= -0x80000000L && value < 0x80000000L)
{
result[offset] = (byte)type;
result[offset + 1] = (byte)4;
result[offset + 2] = (byte)(value >> 24);
result[offset + 3] = (byte)(value >> 16);
result[offset + 4] = (byte)(value >> 8);
result[offset + 5] = (byte)value;
return 6;
}
else if(value >= -0x8000000000L && value < 0x8000000000L)
{
result[offset] = (byte)type;
result[offset + 1] = (byte)5;
result[offset + 2] = (byte)(value >> 32);
result[offset + 3] = (byte)(value >> 24);
result[offset + 4] = (byte)(value >> 16);
result[offset + 5] = (byte)(value >> 8);
result[offset + 6] = (byte)value;
return 7;
}
else if(value >= -0x800000000000L && value < 0x800000000000L)
{
result[offset] = (byte)type;
result[offset + 1] = (byte)6;
result[offset + 2] = (byte)(value >> 40);
result[offset + 3] = (byte)(value >> 32);
result[offset + 4] = (byte)(value >> 24);
result[offset + 5] = (byte)(value >> 16);
result[offset + 6] = (byte)(value >> 8);
result[offset + 7] = (byte)value;
return 8;
}
else if(value >= -0x80000000000000L &&
value < 0x80000000000000L)
{
result[offset] = (byte)type;
result[offset + 1] = (byte)7;
result[offset + 2] = (byte)(value >> 48);
result[offset + 3] = (byte)(value >> 40);
result[offset + 4] = (byte)(value >> 32);
result[offset + 5] = (byte)(value >> 24);
result[offset + 6] = (byte)(value >> 16);
result[offset + 7] = (byte)(value >> 8);
result[offset + 8] = (byte)value;
return 9;
}
else
{
result[offset] = (byte)type;
result[offset + 1] = (byte)8;
result[offset + 2] = (byte)(value >> 56);
result[offset + 3] = (byte)(value >> 48);
result[offset + 4] = (byte)(value >> 40);
result[offset + 5] = (byte)(value >> 32);
result[offset + 6] = (byte)(value >> 24);
result[offset + 7] = (byte)(value >> 16);
result[offset + 8] = (byte)(value >> 8);
result[offset + 9] = (byte)value;
return 10;
}
}
}; // class ASN1Int64Builder
// Builder node that stores a big integer.
private class ASN1BigIntBuilder : ASN1Builder
{
// Internal state.
private byte[] value;
// Constructor.
public ASN1BigIntBuilder(ASN1Type type, byte[] value)
: base(type, 0)
{
this.value = value;
}
// Get the length of this builder when it is encoded using DER.
protected override int GetLength()
{
if((value[0] & 0x80) != 0)
{
// We need to add an extra leading zero byte.
return 2 + GetBytesForLength(value.Length) + value.Length;
}
else
{
// No leading zero required.
return 1 + GetBytesForLength(value.Length) + value.Length;
}
}
// Encode this builder in a byte array as DER. Returns the length.
protected override int Encode(byte[] result, int offset)
{
int start = offset;
result[offset++] = (byte)type;
if((value[0] & 0x80) != 0)
{
// We need to add an extra leading zero byte.
offset += EncodeLength(result, offset, value.Length + 1);
result[offset] = (byte)0;
Array.Copy(value, 0, result, offset + 1, value.Length);
offset += value.Length + 1;
}
else
{
// No leading zero required.
offset += EncodeLength(result, offset, value.Length);
Array.Copy(value, 0, result, offset, value.Length);
offset += value.Length;
}
return (offset - start);
}
}; // class ASN1BigIntBuilder
// Builder node that stores a bit string.
private class ASN1BitStringBuilder : ASN1Builder
{
// Internal state.
private byte[] value;
// Constructor.
public ASN1BitStringBuilder(ASN1Type type, byte[] value)
: base(type, 0)
{
this.value = value;
}
// Get the length of this builder when it is encoded using DER.
protected override int GetLength()
{
return 2 + GetBytesForLength(value.Length) + value.Length;
}
// Encode this builder in a byte array as DER. Returns the length.
protected override int Encode(byte[] result, int offset)
{
int start = offset;
result[offset++] = (byte)type;
offset += EncodeLength(result, offset, value.Length + 1);
result[offset] = (byte)0;
Array.Copy(value, 0, result, offset + 1, value.Length);
offset += value.Length + 1;
return (offset - start);
}
}; // class ASN1BitStringBuilder
// Builder node that stores a bit string in "contents" mode.
private class ASN1BitStringContentsBuilder : ASN1Builder
{
// Constructor.
public ASN1BitStringContentsBuilder(ASN1Type type) : base(type) {}
// Get the length of this builder when it is encoded using DER.
protected override int GetLength()
{
int len = 1;
foreach(ASN1Builder builder in list)
{
len += builder.GetLength();
}
return 1 + GetBytesForLength(len) + len;
}
// Encode this builder in a byte array as DER. Returns the length.
protected override int Encode(byte[] result, int offset)
{
int start = offset;
int len = 1;
foreach(ASN1Builder builder in list)
{
len += builder.GetLength();
}
result[offset++] = (byte)type;
offset += EncodeLength(result, offset, len);
result[offset++] = (byte)0;
foreach(ASN1Builder builder in list)
{
offset += builder.Encode(result, offset);
}
return offset - start;
}
}; // class ASN1BitStringContentsBuilder
}; // class ASN1Builder
#endif // CONFIG_CRYPTO
}; // namespace System.Security.Cryptography
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Globalization
{
public static class __JulianCalendar
{
public static IObservable<System.DateTime> AddMonths(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.DateTime> time,
IObservable<System.Int32> months)
{
return Observable.Zip(JulianCalendarValue, time, months,
(JulianCalendarValueLambda, timeLambda, monthsLambda) =>
JulianCalendarValueLambda.AddMonths(timeLambda, monthsLambda));
}
public static IObservable<System.DateTime> AddYears(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.DateTime> time,
IObservable<System.Int32> years)
{
return Observable.Zip(JulianCalendarValue, time, years,
(JulianCalendarValueLambda, timeLambda, yearsLambda) =>
JulianCalendarValueLambda.AddYears(timeLambda, yearsLambda));
}
public static IObservable<System.Int32> GetDayOfMonth(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.DateTime> time)
{
return Observable.Zip(JulianCalendarValue, time,
(JulianCalendarValueLambda, timeLambda) => JulianCalendarValueLambda.GetDayOfMonth(timeLambda));
}
public static IObservable<System.DayOfWeek> GetDayOfWeek(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.DateTime> time)
{
return Observable.Zip(JulianCalendarValue, time,
(JulianCalendarValueLambda, timeLambda) => JulianCalendarValueLambda.GetDayOfWeek(timeLambda));
}
public static IObservable<System.Int32> GetDayOfYear(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.DateTime> time)
{
return Observable.Zip(JulianCalendarValue, time,
(JulianCalendarValueLambda, timeLambda) => JulianCalendarValueLambda.GetDayOfYear(timeLambda));
}
public static IObservable<System.Int32> GetDaysInMonth(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> month, IObservable<System.Int32> era)
{
return Observable.Zip(JulianCalendarValue, year, month, era,
(JulianCalendarValueLambda, yearLambda, monthLambda, eraLambda) =>
JulianCalendarValueLambda.GetDaysInMonth(yearLambda, monthLambda, eraLambda));
}
public static IObservable<System.Int32> GetDaysInYear(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> era)
{
return Observable.Zip(JulianCalendarValue, year, era,
(JulianCalendarValueLambda, yearLambda, eraLambda) =>
JulianCalendarValueLambda.GetDaysInYear(yearLambda, eraLambda));
}
public static IObservable<System.Int32> GetEra(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.DateTime> time)
{
return Observable.Zip(JulianCalendarValue, time,
(JulianCalendarValueLambda, timeLambda) => JulianCalendarValueLambda.GetEra(timeLambda));
}
public static IObservable<System.Int32> GetMonth(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.DateTime> time)
{
return Observable.Zip(JulianCalendarValue, time,
(JulianCalendarValueLambda, timeLambda) => JulianCalendarValueLambda.GetMonth(timeLambda));
}
public static IObservable<System.Int32> GetMonthsInYear(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> era)
{
return Observable.Zip(JulianCalendarValue, year, era,
(JulianCalendarValueLambda, yearLambda, eraLambda) =>
JulianCalendarValueLambda.GetMonthsInYear(yearLambda, eraLambda));
}
public static IObservable<System.Int32> GetYear(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.DateTime> time)
{
return Observable.Zip(JulianCalendarValue, time,
(JulianCalendarValueLambda, timeLambda) => JulianCalendarValueLambda.GetYear(timeLambda));
}
public static IObservable<System.Boolean> IsLeapDay(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> month, IObservable<System.Int32> day, IObservable<System.Int32> era)
{
return Observable.Zip(JulianCalendarValue, year, month, day, era,
(JulianCalendarValueLambda, yearLambda, monthLambda, dayLambda, eraLambda) =>
JulianCalendarValueLambda.IsLeapDay(yearLambda, monthLambda, dayLambda, eraLambda));
}
public static IObservable<System.Int32> GetLeapMonth(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> era)
{
return Observable.Zip(JulianCalendarValue, year, era,
(JulianCalendarValueLambda, yearLambda, eraLambda) =>
JulianCalendarValueLambda.GetLeapMonth(yearLambda, eraLambda));
}
public static IObservable<System.Boolean> IsLeapMonth(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> month, IObservable<System.Int32> era)
{
return Observable.Zip(JulianCalendarValue, year, month, era,
(JulianCalendarValueLambda, yearLambda, monthLambda, eraLambda) =>
JulianCalendarValueLambda.IsLeapMonth(yearLambda, monthLambda, eraLambda));
}
public static IObservable<System.Boolean> IsLeapYear(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> era)
{
return Observable.Zip(JulianCalendarValue, year, era,
(JulianCalendarValueLambda, yearLambda, eraLambda) =>
JulianCalendarValueLambda.IsLeapYear(yearLambda, eraLambda));
}
public static IObservable<System.DateTime> ToDateTime(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.Int32> year,
IObservable<System.Int32> month, IObservable<System.Int32> day, IObservable<System.Int32> hour,
IObservable<System.Int32> minute, IObservable<System.Int32> second, IObservable<System.Int32> millisecond,
IObservable<System.Int32> era)
{
return Observable.Zip(JulianCalendarValue, year, month, day, hour, minute, second, millisecond, era,
(JulianCalendarValueLambda, yearLambda, monthLambda, dayLambda, hourLambda, minuteLambda, secondLambda,
millisecondLambda, eraLambda) =>
JulianCalendarValueLambda.ToDateTime(yearLambda, monthLambda, dayLambda, hourLambda, minuteLambda,
secondLambda, millisecondLambda, eraLambda));
}
public static IObservable<System.Int32> ToFourDigitYear(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.Int32> year)
{
return Observable.Zip(JulianCalendarValue, year,
(JulianCalendarValueLambda, yearLambda) => JulianCalendarValueLambda.ToFourDigitYear(yearLambda));
}
public static IObservable<System.DateTime> get_MinSupportedDateTime(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue)
{
return Observable.Select(JulianCalendarValue,
(JulianCalendarValueLambda) => JulianCalendarValueLambda.MinSupportedDateTime);
}
public static IObservable<System.DateTime> get_MaxSupportedDateTime(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue)
{
return Observable.Select(JulianCalendarValue,
(JulianCalendarValueLambda) => JulianCalendarValueLambda.MaxSupportedDateTime);
}
public static IObservable<System.Globalization.CalendarAlgorithmType> get_AlgorithmType(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue)
{
return Observable.Select(JulianCalendarValue,
(JulianCalendarValueLambda) => JulianCalendarValueLambda.AlgorithmType);
}
public static IObservable<System.Int32[]> get_Eras(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue)
{
return Observable.Select(JulianCalendarValue, (JulianCalendarValueLambda) => JulianCalendarValueLambda.Eras);
}
public static IObservable<System.Int32> get_TwoDigitYearMax(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue)
{
return Observable.Select(JulianCalendarValue,
(JulianCalendarValueLambda) => JulianCalendarValueLambda.TwoDigitYearMax);
}
public static IObservable<System.Reactive.Unit> set_TwoDigitYearMax(
this IObservable<System.Globalization.JulianCalendar> JulianCalendarValue, IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(JulianCalendarValue, value,
(JulianCalendarValueLambda, valueLambda) => JulianCalendarValueLambda.TwoDigitYearMax = valueLambda);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using Orleans.Messaging;
namespace Orleans.Runtime
{
internal class MessagingStatisticsGroup
{
internal class PerSocketDirectionStats
{
private readonly AverageValueStatistic averageBatchSize;
private readonly HistogramValueStatistic batchSizeBytesHistogram;
internal PerSocketDirectionStats(bool sendOrReceive, SocketDirection direction)
{
StatisticNameFormat batchSizeStatName = sendOrReceive ? StatisticNames.MESSAGING_SENT_BATCH_SIZE_PER_SOCKET_DIRECTION : StatisticNames.MESSAGING_RECEIVED_BATCH_SIZE_PER_SOCKET_DIRECTION;
StatisticNameFormat batchHistogramStatName = sendOrReceive ? StatisticNames.MESSAGING_SENT_BATCH_SIZE_BYTES_HISTOGRAM_PER_SOCKET_DIRECTION : StatisticNames.MESSAGING_RECEIVED_BATCH_SIZE_BYTES_HISTOGRAM_PER_SOCKET_DIRECTION;
averageBatchSize = AverageValueStatistic.FindOrCreate(new StatisticName(batchSizeStatName, Enum.GetName(typeof(SocketDirection), direction)));
batchSizeBytesHistogram = ExponentialHistogramValueStatistic.Create_ExponentialHistogram(
new StatisticName(batchHistogramStatName, Enum.GetName(typeof(SocketDirection), direction)),
NUM_MSG_SIZE_HISTOGRAM_CATEGORIES);
}
internal void OnMessage(int numMsgsInBatch, int totalBytes)
{
averageBatchSize.AddValue(numMsgsInBatch);
batchSizeBytesHistogram.AddData(totalBytes);
}
}
internal static CounterStatistic MessagesSentTotal;
internal static CounterStatistic[] MessagesSentPerDirection;
internal static CounterStatistic TotalBytesSent;
internal static CounterStatistic HeaderBytesSent;
internal static CounterStatistic MessagesReceived;
internal static CounterStatistic[] MessagesReceivedPerDirection;
private static CounterStatistic totalBytesReceived;
private static CounterStatistic headerBytesReceived;
internal static CounterStatistic LocalMessagesSent;
internal static CounterStatistic[] FailedSentMessages;
internal static CounterStatistic[] DroppedSentMessages;
internal static CounterStatistic[] RejectedMessages;
internal static CounterStatistic[] ReroutedMessages;
private static CounterStatistic expiredAtSendCounter;
private static CounterStatistic expiredAtReceiveCounter;
private static CounterStatistic expiredAtDispatchCounter;
private static CounterStatistic expiredAtInvokeCounter;
private static CounterStatistic expiredAtRespondCounter;
internal static CounterStatistic ConnectedClientCount;
private static PerSocketDirectionStats[] perSocketDirectionStatsSend;
private static PerSocketDirectionStats[] perSocketDirectionStatsReceive;
private static ConcurrentDictionary<string, CounterStatistic> perSiloSendCounters;
private static ConcurrentDictionary<string, CounterStatistic> perSiloReceiveCounters;
private static ConcurrentDictionary<string, CounterStatistic> perSiloPingSendCounters;
private static ConcurrentDictionary<string, CounterStatistic> perSiloPingReceiveCounters;
private static ConcurrentDictionary<string, CounterStatistic> perSiloPingReplyReceivedCounters;
private static ConcurrentDictionary<string, CounterStatistic> perSiloPingReplyMissedCounters;
internal enum Phase
{
Send,
Receive,
Dispatch,
Invoke,
Respond,
}
// Histogram of sent message size, starting from 0 in multiples of 2
// (1=2^0, 2=2^2, ... , 256=2^8, 512=2^9, 1024==2^10, ... , up to ... 2^30=1GB)
private static HistogramValueStatistic sentMsgSizeHistogram;
private static HistogramValueStatistic receiveMsgSizeHistogram;
private const int NUM_MSG_SIZE_HISTOGRAM_CATEGORIES = 31;
internal static void Init(bool silo)
{
if (silo)
{
LocalMessagesSent = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_SENT_LOCALMESSAGES);
ConnectedClientCount = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_CONNECTED_CLIENTS, false);
}
MessagesSentTotal = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_SENT_MESSAGES_TOTAL);
MessagesSentPerDirection = new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length];
foreach (var direction in Enum.GetValues(typeof(Message.Directions)))
{
MessagesSentPerDirection[(int)direction] = CounterStatistic.FindOrCreate(
new StatisticName(StatisticNames.MESSAGING_SENT_MESSAGES_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction)));
}
MessagesReceived = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_RECEIVED_MESSAGES_TOTAL);
MessagesReceivedPerDirection = new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length];
foreach (var direction in Enum.GetValues(typeof(Message.Directions)))
{
MessagesReceivedPerDirection[(int)direction] = CounterStatistic.FindOrCreate(
new StatisticName(StatisticNames.MESSAGING_RECEIVED_MESSAGES_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction)));
}
TotalBytesSent = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_SENT_BYTES_TOTAL);
totalBytesReceived = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_RECEIVED_BYTES_TOTAL);
HeaderBytesSent = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_SENT_BYTES_HEADER);
headerBytesReceived = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_RECEIVED_BYTES_HEADER);
FailedSentMessages = new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length];
DroppedSentMessages = new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length];
RejectedMessages = new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length];
ReroutedMessages = new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length];
foreach (var direction in Enum.GetValues(typeof(Message.Directions)))
{
ReroutedMessages[(int)direction] = CounterStatistic.FindOrCreate(
new StatisticName(StatisticNames.MESSAGING_REROUTED_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction)));
}
sentMsgSizeHistogram = ExponentialHistogramValueStatistic.Create_ExponentialHistogram(StatisticNames.MESSAGING_SENT_MESSAGESIZEHISTOGRAM, NUM_MSG_SIZE_HISTOGRAM_CATEGORIES);
receiveMsgSizeHistogram = ExponentialHistogramValueStatistic.Create_ExponentialHistogram(StatisticNames.MESSAGING_RECEIVED_MESSAGESIZEHISTOGRAM, NUM_MSG_SIZE_HISTOGRAM_CATEGORIES);
expiredAtSendCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATSENDER);
expiredAtReceiveCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATRECEIVER);
expiredAtDispatchCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATDISPATCH);
expiredAtInvokeCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATINVOKE);
expiredAtRespondCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATRESPOND);
perSocketDirectionStatsSend = new PerSocketDirectionStats[Enum.GetValues(typeof(SocketDirection)).Length];
perSocketDirectionStatsReceive = new PerSocketDirectionStats[Enum.GetValues(typeof(SocketDirection)).Length];
if (silo)
{
perSocketDirectionStatsSend[(int)SocketDirection.SiloToSilo] = new PerSocketDirectionStats(true, SocketDirection.SiloToSilo);
perSocketDirectionStatsSend[(int)SocketDirection.GatewayToClient] = new PerSocketDirectionStats(true, SocketDirection.GatewayToClient);
perSocketDirectionStatsReceive[(int)SocketDirection.SiloToSilo] = new PerSocketDirectionStats(false, SocketDirection.SiloToSilo);
perSocketDirectionStatsReceive[(int)SocketDirection.GatewayToClient] = new PerSocketDirectionStats(false, SocketDirection.GatewayToClient);
}
else
{
perSocketDirectionStatsSend[(int)SocketDirection.ClientToGateway] = new PerSocketDirectionStats(true, SocketDirection.ClientToGateway);
perSocketDirectionStatsReceive[(int)SocketDirection.ClientToGateway] = new PerSocketDirectionStats(false, SocketDirection.ClientToGateway);
}
perSiloSendCounters = new ConcurrentDictionary<string, CounterStatistic>();
perSiloReceiveCounters = new ConcurrentDictionary<string, CounterStatistic>();
perSiloPingSendCounters = new ConcurrentDictionary<string, CounterStatistic>();
perSiloPingReceiveCounters = new ConcurrentDictionary<string, CounterStatistic>();
perSiloPingReplyReceivedCounters = new ConcurrentDictionary<string, CounterStatistic>();
perSiloPingReplyMissedCounters = new ConcurrentDictionary<string, CounterStatistic>();
}
internal static void OnMessageSend(SiloAddress targetSilo, Message.Directions direction, int numTotalBytes, int headerBytes, SocketDirection socketDirection)
{
if (numTotalBytes < 0)
throw new ArgumentException(String.Format("OnMessageSend(numTotalBytes={0})", numTotalBytes), "numTotalBytes");
OnMessageSend_Impl(targetSilo, direction, numTotalBytes, headerBytes, 1);
}
internal static void OnMessageBatchSend(SiloAddress targetSilo, Message.Directions direction, int numTotalBytes, int headerBytes, SocketDirection socketDirection, int numMsgsInBatch)
{
if (numTotalBytes < 0)
throw new ArgumentException(String.Format("OnMessageBatchSend(numTotalBytes={0})", numTotalBytes), "numTotalBytes");
OnMessageSend_Impl(targetSilo, direction, numTotalBytes, headerBytes, numMsgsInBatch);
perSocketDirectionStatsSend[(int)socketDirection].OnMessage(numMsgsInBatch, numTotalBytes);
}
private static void OnMessageSend_Impl(SiloAddress targetSilo, Message.Directions direction, int numTotalBytes, int headerBytes, int numMsgsInBatch)
{
MessagesSentTotal.IncrementBy(numMsgsInBatch);
MessagesSentPerDirection[(int)direction].IncrementBy(numMsgsInBatch);
TotalBytesSent.IncrementBy(numTotalBytes);
HeaderBytesSent.IncrementBy(headerBytes);
sentMsgSizeHistogram.AddData(numTotalBytes);
FindCounter(perSiloSendCounters, new StatisticName(StatisticNames.MESSAGING_SENT_MESSAGES_PER_SILO, (targetSilo != null ? targetSilo.ToString() : "Null")), CounterStorage.LogOnly).IncrementBy(numMsgsInBatch);
}
private static CounterStatistic FindCounter(ConcurrentDictionary<string, CounterStatistic> counters, StatisticName name, CounterStorage storage)
{
CounterStatistic stat;
if (counters.TryGetValue(name.Name, out stat))
{
return stat;
}
stat = CounterStatistic.FindOrCreate(name, storage);
counters.TryAdd(name.Name, stat);
return stat;
}
internal static void OnMessageReceive(Message msg, int headerBytes, int bodyBytes)
{
MessagesReceived.Increment();
MessagesReceivedPerDirection[(int)msg.Direction].Increment();
totalBytesReceived.IncrementBy(headerBytes + bodyBytes);
headerBytesReceived.IncrementBy(headerBytes);
receiveMsgSizeHistogram.AddData(headerBytes + bodyBytes);
SiloAddress addr = msg.SendingSilo;
FindCounter(perSiloReceiveCounters, new StatisticName(StatisticNames.MESSAGING_RECEIVED_MESSAGES_PER_SILO, (addr != null ? addr.ToString() : "Null")), CounterStorage.LogOnly).Increment();
}
internal static void OnMessageBatchReceive(SocketDirection socketDirection, int numMsgsInBatch, int totalBytes)
{
perSocketDirectionStatsReceive[(int)socketDirection].OnMessage(numMsgsInBatch, totalBytes);
}
internal static void OnMessageExpired(Phase phase)
{
switch (phase)
{
case Phase.Send:
expiredAtSendCounter.Increment();
break;
case Phase.Receive:
expiredAtReceiveCounter.Increment();
break;
case Phase.Dispatch:
expiredAtDispatchCounter.Increment();
break;
case Phase.Invoke:
expiredAtInvokeCounter.Increment();
break;
case Phase.Respond:
expiredAtRespondCounter.Increment();
break;
}
}
internal static void OnPingSend(SiloAddress destination)
{
FindCounter(perSiloPingSendCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_SENT_PER_SILO, destination.ToString()), CounterStorage.LogOnly).Increment();
}
internal static void OnPingReceive(SiloAddress destination)
{
FindCounter(perSiloPingReceiveCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_RECEIVED_PER_SILO, destination.ToString()), CounterStorage.LogOnly).Increment();
}
internal static void OnPingReplyReceived(SiloAddress replier)
{
FindCounter(perSiloPingReplyReceivedCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_REPLYRECEIVED_PER_SILO, replier.ToString()), CounterStorage.LogOnly).Increment();
}
internal static void OnPingReplyMissed(SiloAddress replier)
{
FindCounter(perSiloPingReplyMissedCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_REPLYMISSED_PER_SILO, replier.ToString()), CounterStorage.LogOnly).Increment();
}
internal static void OnFailedSentMessage(Message msg)
{
if (msg == null || !msg.ContainsHeader(Message.Header.DIRECTION)) return;
int direction = (int)msg.Direction;
if (FailedSentMessages[direction] == null)
{
FailedSentMessages[direction] = CounterStatistic.FindOrCreate(
new StatisticName(StatisticNames.MESSAGING_SENT_FAILED_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction)));
}
FailedSentMessages[direction].Increment();
}
internal static void OnDroppedSentMessage(Message msg)
{
if (msg == null || !msg.ContainsHeader(Message.Header.DIRECTION)) return;
int direction = (int)msg.Direction;
if (DroppedSentMessages[direction] == null)
{
DroppedSentMessages[direction] = CounterStatistic.FindOrCreate(
new StatisticName(StatisticNames.MESSAGING_SENT_DROPPED_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction)));
}
DroppedSentMessages[direction].Increment();
}
internal static void OnRejectedMessage(Message msg)
{
if (msg == null || !msg.ContainsHeader(Message.Header.DIRECTION)) return;
int direction = (int)msg.Direction;
if (RejectedMessages[direction] == null)
{
RejectedMessages[direction] = CounterStatistic.FindOrCreate(
new StatisticName(StatisticNames.MESSAGING_REJECTED_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction)));
}
RejectedMessages[direction].Increment();
}
internal static void OnMessageReRoute(Message msg)
{
ReroutedMessages[(int)msg.Direction].Increment();
}
}
}
| |
// <copyright file="RetryContext.ActionsAndFuncs.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using IX.StandardExtensions.Contracts;
namespace IX.Retry.Contexts
{
#pragma warning disable SA1402 // File may only contain a single type
#pragma warning disable SA1649 // File name should match first type name
internal sealed class ActionWith1ParamRetryContext<TParam1> : RetryContext
{
private readonly Action<TParam1> action;
private readonly TParam1 param1;
internal ActionWith1ParamRetryContext(Action<TParam1> action, TParam1 param1, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in action, nameof(action));
this.action = action;
this.param1 = param1;
}
private protected override void Invoke() => this.action(this.param1);
}
internal sealed class FuncWith1ParamRetryContext<TParam1, TReturn> : RetryContextWithReturnValue<TReturn>
{
private readonly Func<TParam1, TReturn> func;
private readonly TParam1 param1;
private TReturn returnValue;
internal FuncWith1ParamRetryContext(Func<TParam1, TReturn> func, TParam1 param1, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in func, nameof(func));
this.func = func;
this.param1 = param1;
}
internal override TReturn GetReturnValue() => this.returnValue;
private protected override void Invoke() => this.returnValue = this.func(this.param1);
}
internal sealed class ActionWith2ParamRetryContext<TParam1, TParam2> : RetryContext
{
private readonly Action<TParam1, TParam2> action;
private readonly TParam1 param1;
private readonly TParam2 param2;
internal ActionWith2ParamRetryContext(Action<TParam1, TParam2> action, TParam1 param1, TParam2 param2, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in action, nameof(action));
this.action = action;
this.param1 = param1;
this.param2 = param2;
}
private protected override void Invoke() => this.action(this.param1, this.param2);
}
internal sealed class FuncWith2ParamRetryContext<TParam1, TParam2, TReturn> : RetryContextWithReturnValue<TReturn>
{
private readonly Func<TParam1, TParam2, TReturn> func;
private readonly TParam1 param1;
private readonly TParam2 param2;
private TReturn returnValue;
internal FuncWith2ParamRetryContext(Func<TParam1, TParam2, TReturn> func, TParam1 param1, TParam2 param2, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in func, nameof(func));
this.func = func;
this.param1 = param1;
this.param2 = param2;
}
internal override TReturn GetReturnValue() => this.returnValue;
private protected override void Invoke() => this.returnValue = this.func(this.param1, this.param2);
}
internal sealed class ActionWith3ParamRetryContext<TParam1, TParam2, TParam3> : RetryContext
{
private readonly Action<TParam1, TParam2, TParam3> action;
private readonly TParam1 param1;
private readonly TParam2 param2;
private readonly TParam3 param3;
internal ActionWith3ParamRetryContext(Action<TParam1, TParam2, TParam3> action, TParam1 param1, TParam2 param2, TParam3 param3, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in action, nameof(action));
this.action = action;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
}
private protected override void Invoke() => this.action(this.param1, this.param2, this.param3);
}
internal sealed class FuncWith3ParamRetryContext<TParam1, TParam2, TParam3, TReturn> : RetryContextWithReturnValue<TReturn>
{
private readonly Func<TParam1, TParam2, TParam3, TReturn> func;
private readonly TParam1 param1;
private readonly TParam2 param2;
private readonly TParam3 param3;
private TReturn returnValue;
internal FuncWith3ParamRetryContext(Func<TParam1, TParam2, TParam3, TReturn> func, TParam1 param1, TParam2 param2, TParam3 param3, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in func, nameof(func));
this.func = func;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
}
internal override TReturn GetReturnValue() => this.returnValue;
private protected override void Invoke() => this.returnValue = this.func(this.param1, this.param2, this.param3);
}
internal sealed class ActionWith4ParamRetryContext<TParam1, TParam2, TParam3, TParam4> : RetryContext
{
private readonly Action<TParam1, TParam2, TParam3, TParam4> action;
private readonly TParam1 param1;
private readonly TParam2 param2;
private readonly TParam3 param3;
private readonly TParam4 param4;
internal ActionWith4ParamRetryContext(Action<TParam1, TParam2, TParam3, TParam4> action, TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in action, nameof(action));
this.action = action;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
}
private protected override void Invoke() => this.action(this.param1, this.param2, this.param3, this.param4);
}
internal sealed class FuncWith4ParamRetryContext<TParam1, TParam2, TParam3, TParam4, TReturn> : RetryContextWithReturnValue<TReturn>
{
private readonly Func<TParam1, TParam2, TParam3, TParam4, TReturn> func;
private readonly TParam1 param1;
private readonly TParam2 param2;
private readonly TParam3 param3;
private readonly TParam4 param4;
private TReturn returnValue;
internal FuncWith4ParamRetryContext(Func<TParam1, TParam2, TParam3, TParam4, TReturn> func, TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in func, nameof(func));
this.func = func;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
}
internal override TReturn GetReturnValue() => this.returnValue;
private protected override void Invoke() => this.returnValue = this.func(this.param1, this.param2, this.param3, this.param4);
}
internal sealed class ActionWith5ParamRetryContext<TParam1, TParam2, TParam3, TParam4, TParam5> : RetryContext
{
private readonly Action<TParam1, TParam2, TParam3, TParam4, TParam5> action;
private readonly TParam1 param1;
private readonly TParam2 param2;
private readonly TParam3 param3;
private readonly TParam4 param4;
private readonly TParam5 param5;
internal ActionWith5ParamRetryContext(Action<TParam1, TParam2, TParam3, TParam4, TParam5> action, TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in action, nameof(action));
this.action = action;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
this.param5 = param5;
}
private protected override void Invoke() => this.action(this.param1, this.param2, this.param3, this.param4, this.param5);
}
internal sealed class FuncWith5ParamRetryContext<TParam1, TParam2, TParam3, TParam4, TParam5, TReturn> : RetryContextWithReturnValue<TReturn>
{
private readonly Func<TParam1, TParam2, TParam3, TParam4, TParam5, TReturn> func;
private readonly TParam1 param1;
private readonly TParam2 param2;
private readonly TParam3 param3;
private readonly TParam4 param4;
private readonly TParam5 param5;
private TReturn returnValue;
internal FuncWith5ParamRetryContext(Func<TParam1, TParam2, TParam3, TParam4, TParam5, TReturn> func, TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in func, nameof(func));
this.func = func;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
this.param5 = param5;
}
internal override TReturn GetReturnValue() => this.returnValue;
private protected override void Invoke() => this.returnValue = this.func(this.param1, this.param2, this.param3, this.param4, this.param5);
}
internal sealed class ActionWith6ParamRetryContext<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6> : RetryContext
{
private readonly Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6> action;
private readonly TParam1 param1;
private readonly TParam2 param2;
private readonly TParam3 param3;
private readonly TParam4 param4;
private readonly TParam5 param5;
private readonly TParam6 param6;
internal ActionWith6ParamRetryContext(Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6> action, TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in action, nameof(action));
this.action = action;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
this.param5 = param5;
this.param6 = param6;
}
private protected override void Invoke() => this.action(this.param1, this.param2, this.param3, this.param4, this.param5, this.param6);
}
internal sealed class FuncWith6ParamRetryContext<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TReturn> : RetryContextWithReturnValue<TReturn>
{
private readonly Func<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TReturn> func;
private readonly TParam1 param1;
private readonly TParam2 param2;
private readonly TParam3 param3;
private readonly TParam4 param4;
private readonly TParam5 param5;
private readonly TParam6 param6;
private TReturn returnValue;
internal FuncWith6ParamRetryContext(Func<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TReturn> func, TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in func, nameof(func));
this.func = func;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
this.param5 = param5;
this.param6 = param6;
}
internal override TReturn GetReturnValue() => this.returnValue;
private protected override void Invoke() => this.returnValue = this.func(this.param1, this.param2, this.param3, this.param4, this.param5, this.param6);
}
internal sealed class ActionWith7ParamRetryContext<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7> : RetryContext
{
private readonly Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7> action;
private readonly TParam1 param1;
private readonly TParam2 param2;
private readonly TParam3 param3;
private readonly TParam4 param4;
private readonly TParam5 param5;
private readonly TParam6 param6;
private readonly TParam7 param7;
internal ActionWith7ParamRetryContext(Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7> action, TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in action, nameof(action));
this.action = action;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
this.param5 = param5;
this.param6 = param6;
this.param7 = param7;
}
private protected override void Invoke() => this.action(this.param1, this.param2, this.param3, this.param4, this.param5, this.param6, this.param7);
}
internal sealed class FuncWith7ParamRetryContext<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TReturn> : RetryContextWithReturnValue<TReturn>
{
private readonly Func<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TReturn> func;
private readonly TParam1 param1;
private readonly TParam2 param2;
private readonly TParam3 param3;
private readonly TParam4 param4;
private readonly TParam5 param5;
private readonly TParam6 param6;
private readonly TParam7 param7;
private TReturn returnValue;
internal FuncWith7ParamRetryContext(Func<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TReturn> func, TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in func, nameof(func));
this.func = func;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
this.param5 = param5;
this.param6 = param6;
this.param7 = param7;
}
internal override TReturn GetReturnValue() => this.returnValue;
private protected override void Invoke() => this.returnValue = this.func(this.param1, this.param2, this.param3, this.param4, this.param5, this.param6, this.param7);
}
internal sealed class ActionWith8ParamRetryContext<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8> : RetryContext
{
private readonly Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8> action;
private readonly TParam1 param1;
private readonly TParam2 param2;
private readonly TParam3 param3;
private readonly TParam4 param4;
private readonly TParam5 param5;
private readonly TParam6 param6;
private readonly TParam7 param7;
private readonly TParam8 param8;
internal ActionWith8ParamRetryContext(Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8> action, TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in action, nameof(action));
this.action = action;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
this.param5 = param5;
this.param6 = param6;
this.param7 = param7;
this.param8 = param8;
}
private protected override void Invoke() => this.action(this.param1, this.param2, this.param3, this.param4, this.param5, this.param6, this.param7, this.param8);
}
internal sealed class FuncWith8ParamRetryContext<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TReturn> : RetryContextWithReturnValue<TReturn>
{
private readonly Func<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TReturn> func;
private readonly TParam1 param1;
private readonly TParam2 param2;
private readonly TParam3 param3;
private readonly TParam4 param4;
private readonly TParam5 param5;
private readonly TParam6 param6;
private readonly TParam7 param7;
private readonly TParam8 param8;
private TReturn returnValue;
internal FuncWith8ParamRetryContext(Func<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TReturn> func, TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8, RetryOptions retryOptions)
: base(retryOptions)
{
Contract.RequiresNotNullPrivate(in func, nameof(func));
this.func = func;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
this.param5 = param5;
this.param6 = param6;
this.param7 = param7;
this.param8 = param8;
}
internal override TReturn GetReturnValue() => this.returnValue;
private protected override void Invoke() => this.returnValue = this.func(this.param1, this.param2, this.param3, this.param4, this.param5, this.param6, this.param7, this.param8);
}
#pragma warning restore SA1649 // File name should match first type name
#pragma warning restore SA1402 // File may only contain a single type
}
| |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using RTSMiner.Other;
using RTSMiner.Resources;
using RTSMiner.Units;
using System;
using System.Collections.Generic;
using VoidEngine.Particles;
using VoidEngine.VGame;
using VoidEngine.VGenerator;
using VoidEngine.VGUI;
namespace RTSMiner.Managers
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class GameManager : Microsoft.Xna.Framework.DrawableGameComponent
{
/// <summary>
/// The game that this manager runs off of.
/// </summary>
Game1 myGame;
/// <summary>
/// The sprite batch to draw the sprites with.
/// </summary>
SpriteBatch spriteBatch;
/// <summary>
/// Used to control the game's screen.
/// </summary>
public Camera Camera;
/// <summary>
/// Used to get random real numbers.
/// </summary>
public Random Random = new Random();
/// <summary>
/// Used to get the current state of the keyboard.
/// </summary>
public KeyboardState KeyboardState, PreviousKeyboardState;
/// <summary>
/// Used to control the state of the cursor.
/// </summary>
public MouseState MouseState, PreviousMouseState;
#region Textures
/// <summary>
/// The textures for the resources.
/// </summary>
public Texture2D StoneTileTexture, UraniumTileTexture, IronTileTexture, GoldTileTexture;
/// <summary>
/// The textures for the boundries of the map.
/// </summary>
public Texture2D VoidTileTexture, SpaceTileTexture, AsteroidTileTexture;
/// <summary>
/// The texture of the buttons on the screen.
/// </summary>
public Texture2D ButtonTexture, ButtonWindowTexture, ProgressBarTexture;
/// <summary>
/// The texture of the particles on the screen.
/// </summary>
public Texture2D ParticalTexture;
/// <summary>
/// The heavyMetal background textures.
/// </summary>
public Texture2D BackgroundHeavyTexture;
public Texture2D HQTexture;
public Texture2D HQOverlayTexture;
public Texture2D HarvesterTexture;
#endregion
#region Tile Stuff
/// <summary>
/// The main map array.
/// </summary>
public int[,] MapArray;
/// <summary>
/// The list of tiles.
/// </summary>
public List<Tile> TileList = new List<Tile>();
/// <summary>
/// The list of resources in the game.
/// </summary>
public List<Resource> ResourceList = new List<Resource>();
/// <summary>
/// The list of boundries in the game.
/// </summary>
public List<Tile> BoundryTiles = new List<Tile>();
#endregion
#region Unit Stuff
public List<Unit> UnitList = new List<Unit>();
public int SelectedResource
{
get;
set;
}
public int SelectedUnit
{
get;
set;
}
public bool HarvesterPlaced
{
get;
set;
}
public bool HQPlaced
{
get;
set;
}
public int UraniumStored
{
get;
set;
}
public int StoneStored
{
get;
set;
}
public int IronStored
{
get;
set;
}
public int GoldStored
{
get;
set;
}
public int AsteroidsStored
{
get;
set;
}
#endregion
#region Level & Transition Stuff
/// <summary>
/// The parallax for whatever it's used for?
/// </summary>
Vector2 Parallax = Vector2.One;
public bool MapLoaded
{
get;
set;
}
#endregion
#region Partical System
/// <summary>
/// The list of the particles.
/// </summary>
List<Particle> ParticleList = new List<Particle>();
/// <summary>
/// Gets or sets the blood's minimum radius.
/// </summary>
public float PartMinRadius
{
get;
set;
}
/// <summary>
/// Gets or sets the blood's maximum radius.
/// </summary>
public float PartMaxRadius
{
get;
set;
}
#endregion
#region GUI Stuff
public List<Button> ButtonList = new List<Button>();
#endregion
/// <summary>
/// Creates the game manager
/// </summary>
/// <param name="game">The game that the manager is running off of.</param>
public GameManager(Game1 game)
: base(game)
{
// Set the default game.
myGame = game;
// Start to Initialize the game.
Initialize();
}
/// <summary>
/// Allows the game component to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load content.
/// </summary>
public override void Initialize()
{
// TODO: Add your initialization code here
base.Initialize();
}
/// <summary>
/// Loads the game component's content.
/// </summary>
protected override void LoadContent()
{
// Create the sprite batch.
spriteBatch = new SpriteBatch(myGame.GraphicsDevice);
// Load all the images.
LoadImages();
// Load the background.
myGame.GenerateBackground();
// Create the camera.
Camera = new Camera(myGame.GraphicsDevice.Viewport, new Point(myGame.WindowSize.X, myGame.WindowSize.Y), 1.0f);
base.LoadContent();
}
protected virtual void LoadImages()
{
VoidTileTexture = Game.Content.Load<Texture2D>(@"images\tilesets\void");
SpaceTileTexture = Game.Content.Load<Texture2D>(@"images\tilesets\space");
AsteroidTileTexture = Game.Content.Load<Texture2D>(@"images\tilesets\asteroids");
StoneTileTexture = Game.Content.Load<Texture2D>(@"images\tilesets\stone");
UraniumTileTexture = Game.Content.Load<Texture2D>(@"images\tilesets\uranium");
IronTileTexture = Game.Content.Load<Texture2D>(@"images\tilesets\iron");
GoldTileTexture = Game.Content.Load<Texture2D>(@"images\tilesets\gold");
BackgroundHeavyTexture = Game.Content.Load<Texture2D>(@"images\gui\backgroundHeavy");
HQTexture = Game.Content.Load<Texture2D>(@"images\buildings\hq1");
HQOverlayTexture = Game.Content.Load<Texture2D>(@"images\buildings\hq1-overlay");
HarvesterTexture = Game.Content.Load<Texture2D>(@"images\units\harvester1");
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
// Get the states of the keyboard and mouse.
KeyboardState = Keyboard.GetState();
MouseState = Mouse.GetState();
if (KeyboardState.IsKeyDown(Keys.Escape))
{
myGame.SetCurrentLevel(Game1.GameLevels.MENU);
}
#region Update Tiles and Objects
myGame.cursor.Update(gameTime);
foreach (Tile t in TileList)
{
// Update all tiles.
t.Update(gameTime);
}
foreach (Resource r in ResourceList)
{
// Update all the resources.
r.Update(gameTime);
}
foreach (Tile t in BoundryTiles)
{
// Update the boundry tiles.
t.Update(gameTime);
}
foreach (Tile t in myGame.BackgroundTilesList)
{
// Update all the background tiles.
t.Update(gameTime);
}
for (int i = 0; i < UnitList.Count; i++)
{
if (UnitList[i].IsDead)
{
UnitList.RemoveAt(i);
i--;
}
else
{
if (UnitList[i].IsUnitClicked() && SelectedUnit != i)
{
SelectedUnit = i;
SelectedResource = -1;
//SetUnitButtons(i);
}
UnitList[i].Update(gameTime);
}
}
#endregion
#region Camera Controls
float MoveSpeed = 5;
float MoveRadius = 10;
// Move the camera up.
if (KeyboardState.IsKeyDown(Keys.Up))
{
Camera.Position -= new Vector2(0, 5);
}
// Move the camera to the left.
if (KeyboardState.IsKeyDown(Keys.Left))
{
Camera.Position -= new Vector2(5, 0);
}
// Reset the camera.
if (KeyboardState.IsKeyDown(Keys.NumPad5))
{
Camera.Position = new Vector2(0, 0);
}
// Move the camera to the right.
if (KeyboardState.IsKeyDown(Keys.Right))
{
Camera.Position += new Vector2(5, 0);
}
// Move the camera down.
if (KeyboardState.IsKeyDown(Keys.Down))
{
Camera.Position += new Vector2(0, 5);
}
Camera.Position += new Vector2(0, 0);
// Move the camera if the mouse is at a specific area.
if (Game.IsActive)
{
if (MouseState.X > 0 && MouseState.X < myGame.WindowSize.X && MouseState.Y > 0 && MouseState.Y < myGame.WindowSize.Y)
{
// Move the camera down.
if (MouseState.Y + MoveRadius >= myGame.WindowSize.Y)
{
Camera.Position += new Vector2(0, MoveSpeed);
}
// Move the camera up.
if (MouseState.Y <= MoveRadius)
{
Camera.Position -= new Vector2(0, MoveSpeed);
}
// Move the camera to the right.
if (MouseState.X + MoveRadius >= myGame.WindowSize.X)
{
Camera.Position += new Vector2(MoveSpeed, 0);
}
// Move the camera to the left.
if (MouseState.X <= MoveRadius)
{
Camera.Position -= new Vector2(MoveSpeed, 0);
}
}
}
#endregion
#region Map Loading Stuff
if (!MapLoaded)
{
RenegerateMap();
}
// Tell if the letter 'U' is pressed so we can regenerate the starmap.
if (KeyboardState.IsKeyUp(Keys.U) && PreviousKeyboardState.IsKeyDown(Keys.U))
{
RenegerateMap();
}
#endregion
#region Debug Stuff
if (myGame.GameDebug)
{
// Update the debug label.
myGame.debugLabel.Update(gameTime);
myGame.debugStrings[0] = "harvesterCount=" + RTSMiner.Other.MapHelper.PlacedBlueHarvesters + " HQCount=" + RTSMiner.Other.MapHelper.PlacedBlueHQs;
myGame.debugStrings[1] = "cameraSize=(" + Camera.viewportSize.X + "," + Camera.viewportSize.Y + ")";
myGame.debugStrings[2] = "windowSize=(" + myGame.WindowSize.X + "," + myGame.WindowSize.Y + ")";
myGame.debugStrings[3] = "cameraPosi=(" + Camera.Position.X + "," + Camera.Position.Y + ")";
}
if (myGame.isOptionsChanged > myGame.OldIsOptionsChanged)
{
Camera.viewportSize = new Vector2(myGame.WindowSize.X, myGame.WindowSize.Y);
}
#endregion
base.Update(gameTime);
// Set the previous mouse and keyboard states.
PreviousKeyboardState = KeyboardState;
PreviousMouseState = MouseState;
}
#region Load the map
protected void RenegerateMap()
{
TileList.RemoveRange(0, TileList.Count);
ResourceList.RemoveRange(0, ResourceList.Count);
UnitList.RemoveRange(0, UnitList.Count);
HarvesterPlaced = false;
HQPlaced = false;
RTSMiner.Other.MapHelper.PlacedBlueHarvesters = 1;
RTSMiner.Other.MapHelper.PlacedBlueHQs = 0;
// Loads the map once.
LoadMap();
Camera.Size = new Point(MapArray.GetLength(1) * 30, MapArray.GetLength(0) * 30);
Camera.screenCenter = new Vector2(myGame.GraphicsDevice.Viewport.Width, myGame.GraphicsDevice.Viewport.Height);
Camera.origin = Camera.screenCenter / Camera.Zoom;
foreach (Unit u in UnitList)
{
if (u is BlueHarvester)
{
Camera.Position = u.Position;
}
}
Camera.Position += new Vector2(0, 0);
MapLoaded = true;
}
protected void LoadMap()
{
// Create the map
MapArray = RTSMiner.Other.MapHelper.SaveMap(MapGenerator.CreateMap(100, 100, 10, 0.03f), 3);
// Create the unit map.
int[,] UnitArray = Maps.Level1UnitMapGen();
// Calculate out the map.
for (int x = 0; x < MapArray.GetLength(0); x++)
{
for (int y = 0; y < MapArray.GetLength(1); y++)
{
switch (MapArray[x, y])
{
case 1: // "Cliff" Tiles
ResourceList.Add(new StoneResource(new Vector2(x * 30, y * 30), StoneTileTexture, 10, new Point(MapArray.GetLength(0) * 30, MapArray.GetLength(1) * 30), ResourceList));
break;
case 2: // "Uranium" Tiles
ResourceList.Add(new UraniumResource(new Vector2(x * 30, y * 30), UraniumTileTexture, 15, new Point(MapArray.GetLength(0) * 30, MapArray.GetLength(1) * 30), ResourceList));
break;
case 3: // "Iron" Tiles
ResourceList.Add(new IronResource(new Vector2(x * 30, y * 30), IronTileTexture, 15, new Point(MapArray.GetLength(0) * 30, MapArray.GetLength(1) * 30), ResourceList));
break;
case 4: // "Gold" Tiles
ResourceList.Add(new GoldResource(new Vector2(x * 30, y * 30), GoldTileTexture, 15, new Point(MapArray.GetLength(0) * 30, MapArray.GetLength(1) * 30), ResourceList));
break;
case 5: // "Asteroid" Tiles
ResourceList.Add(new AsteroidResource(new Vector2(x * 30, y * 30), AsteroidTileTexture, 100, new Point(MapArray.GetLength(0) * 30, MapArray.GetLength(1) * 30), ResourceList));
break;
case -2:
UnitList.Add(new BlueHarvester(new Vector2(x * 30 + 5, y * 30 + 5), HarvesterTexture, myGame));
HarvesterPlaced = true;
break;
case -3:
UnitList.Add(new BlueHQ(HQTexture, new Vector2(x * 30, y * 30), HQOverlayTexture, new Color(0, 124, 255), myGame));
HQPlaced = true;
break;
}
TileList.Add(new Tile(SpaceTileTexture, new Vector2(x * 30, y * 30), 0, Random.Next(998524), Color.White));
}
}
foreach (Resource r in ResourceList)
{
r.UpdateConnections();
}
}
#endregion
/// <summary>
/// Draws the game component's content.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Draw(GameTime gameTime)
{
#region Draw Background
// Draw the back stage.
spriteBatch.Begin();
{
foreach (Tile t in myGame.BackgroundTilesList)
{
// Draw all the background tiles.
t.Draw(gameTime, spriteBatch);
}
}
spriteBatch.End();
#endregion
#region Draw everything in the camera
// Draw in the frame of the camera.
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, Camera.GetTransformation());
{
foreach (Tile t in TileList)
{
if (Camera.IsInView(t.Position, new Vector2(30, 30)))
{
// Draw all the tiles.
t.Draw(gameTime, spriteBatch);
}
}
foreach (Resource r in ResourceList)
{
if (Camera.IsInView(r.Position, new Vector2(30, 30)))
{
// Draw all the resources.
r.Draw(gameTime, spriteBatch);
}
}
foreach (Tile t in BoundryTiles)
{
if (Camera.IsInView(t.Position, new Vector2(30, 30)))
{
// Draw the boundry tiles.
t.Draw(gameTime, spriteBatch);
}
}
foreach (Unit u in UnitList)
{
if (Camera.IsInView(u.Position, new Vector2(u.CurrentAnimation.frameSize.X, u.CurrentAnimation.frameSize.Y)))
{
// Draw all of the Units.
u.Draw(gameTime, spriteBatch);
}
}
}
spriteBatch.End();
#endregion
#region Draw Cursor and debug stuff
// Draw outside the frame of the camera.
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null);
{
myGame.cursor.Draw(gameTime, spriteBatch);
// Tell if the game is in debug mode.
if (myGame.GameDebug)
{
// Draw the debug label.
myGame.debugLabel.Draw(gameTime, spriteBatch);
}
}
spriteBatch.End();
#endregion
base.Draw(gameTime);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.