context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\EnvironmentQuery\EnvQueryGenerator.h:21
namespace UnrealEngine
{
[ManageType("ManageEnvQueryGenerator")]
public partial class ManageEnvQueryGenerator : UEnvQueryGenerator, IManageWrapper
{
public ManageEnvQueryGenerator(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_UpdateNodeVersion(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
public override void UpdateNodeVersion()
=> E__Supper__UEnvQueryGenerator_UpdateNodeVersion(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__UEnvQueryGenerator_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__UEnvQueryGenerator_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__UEnvQueryGenerator_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__UEnvQueryGenerator_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__UEnvQueryGenerator_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__UEnvQueryGenerator_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__UEnvQueryGenerator_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__UEnvQueryGenerator_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__UEnvQueryGenerator_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__UEnvQueryGenerator_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__UEnvQueryGenerator_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__UEnvQueryGenerator_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__UEnvQueryGenerator_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__UEnvQueryGenerator_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__UEnvQueryGenerator_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageEnvQueryGenerator self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageEnvQueryGenerator(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageEnvQueryGenerator>(PtrDesc);
}
}
}
| |
/*
* PostscriptImage.cs - Implementation of images for System.Drawing.
*
* Copyright (C) 2003 Free Software Foundation, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Drawing.Toolkit
{
using System;
using DotGNU.Images;
public class PostscriptImage : ToolkitImageBase
{
// Internal state.
private String imageDataDict;
private String imageData;
private String maskDataDict;
private String maskDataStream;
// Constructor.
public PostscriptImage(Image image, int frame)
: base(image, frame)
{
ImageChanged();
}
// Returns the LanguageLevel2 postscript for this image.
public String LevelTwo
{
get
{
if(imageDataDict == null) { return String.Empty; }
return String.Format
("/DeviceRGB setcolorspace " +
"1 dict begin {0} {1} end ",
imageDataDict, imageData);
}
}
// Returns the LanguageLevel3 postscript for this image.
public String LevelThree
{
get
{
if(imageDataDict == null) { return String.Empty; }
return String.Format
("/DeviceRGB setcolorspace " +
"4 dict begin " +
"{0} {1} {2} " +
"/ImageDict 4 dict def " +
"ImageDict begin " +
"/ImageType 3 def " +
"/DataDict ImageDataDict def " +
"/MaskDict MaskDataDict def " +
"/InterleaveType 3 def " +
"end " +
"ImageDict image " +
"{4} ",
maskDataStream, maskDataDict, imageDataDict, imageData);
}
}
public override void ImageChanged()
{
Frame f = null;
if(image == null || (f = image.GetFrame(frame)) == null)
{
imageDataDict = null;
imageData = null;
maskDataDict = null;
maskDataStream = null;
}
imageDataDict = String.Format
("/ImageDataDict 8 dict def " +
"ImageDataDict begin " +
"/ImageType 1 def " +
"/Width {0} def " +
"/Height {1} def " +
"/ImageMatrix [1 0 0 -1 0 {1}] def " +
"/DataSource currentfile /ASCII85Decode filter def " +
"/BitsPerComponent 8 def " +
"/Decode [0 1 0 1 0 1] def " +
"/Interpolation true def " +
"end ",
f.Width, f.Height);
maskDataDict = String.Format
("/MaskDataDict 8 dict def " +
"MaskDataDict begin " +
"/ImageType 1 def " +
"/Width {0} def " +
"/Height {1} def " +
"/ImageMatrix [1 0 0 -1 0 {1}] def " +
"/DataSource maskstream def " +
"/BitsPerComponent 1 def " +
"/Decode [0 1] def " +
"/Interpolation true def " +
"end ",
f.Width, f.Height);
CompileFrameData(f);
}
// Dispose of this image.
protected override void Dispose(bool disposing)
{
imageDataDict = null;
imageData = null;
maskDataDict = null;
maskDataStream = null;
}
private void CompileFrameData(Frame f)
{
int width = f.Width;
int height = f.Height;
int stride = f.Stride;
int fMaskStride = f.MaskStride;
int transparentPixel = f.TransparentPixel;
int[] fPalette = f.Palette;
byte[] fData = f.Data;
byte[] fMask = f.Mask;
PixelFormat pixelFormat = f.PixelFormat;
int maskStride = (width + 7) / 8;
byte[] mask = new byte[height*maskStride];
if(fMask != null)
{
// the mask in the frame is padded to 4-bytes, while the
// masks in postscript are padded to 1-byte, so perform a
// conversion if necessary, but direct copy if possible
if(maskStride == fMaskStride)
{
Array.Copy(fMask, 0, mask, 0, mask.Length);
}
else
{
int i = 0;
int j = 0;
int k = 0;
while(i < height)
{
Array.Copy(fMask, j, mask, k, maskStride);
++i;
j += fMaskStride;
k += maskStride;
}
}
}
byte[] data = new byte[width*3*height];
int offset = 0;
int maskOffset = 0;
for(int y = 0, i = 0; y < height; ++y)
{
for(int x = 0, ptr = offset; x < width; ++x)
{
switch(pixelFormat)
{
case PixelFormat.Format64bppPArgb:
{
byte a = fData[ptr+7];
if(a != 0)
{
data[i+2] = (byte)((fData[ptr+1] * 255) / a);
data[i+1] = (byte)((fData[ptr+3] * 255) / a);
data[i] = (byte)((fData[ptr+5] * 255) / a);
}
i += 3;
ptr += 8;
}
break;
case PixelFormat.Format64bppArgb:
{
data[i+2] = fData[ptr+1];
data[i+1] = fData[ptr+3];
data[i] = fData[ptr+5];
i += 3;
ptr += 8;
}
break;
case PixelFormat.Format48bppRgb:
{
data[i+2] = fData[ptr+1];
data[i+1] = fData[ptr+3];
data[i] = fData[ptr+5];
i += 3;
ptr += 6;
}
break;
case PixelFormat.Format32bppPArgb:
{
byte a = fData[ptr+3];
if(a != 0)
{
data[i+2] = (byte)((fData[ptr] * 255) / a);
data[i+1] = (byte)((fData[ptr+1] * 255) / a);
data[i] = (byte)((fData[ptr+2] * 255) / a);
}
i += 3;
ptr += 4;
}
break;
case PixelFormat.Format32bppArgb:
{
data[i+2] = fData[ptr++];
data[i+1] = fData[ptr++];
data[i] = fData[ptr++];
i += 3;
++ptr;
}
break;
case PixelFormat.Format24bppRgb:
{
data[i+2] = fData[ptr++];
data[i+1] = fData[ptr++];
data[i] = fData[ptr++];
i += 3;
}
break;
case PixelFormat.Format16bppRgb565:
{
int g = fData[ptr++];
int r = fData[ptr++];
int b = (g & 0x1F) * 255 / 31;
g = (r << 3 & 0x38 | g >> 5 & 0x07) * 255 / 63;
r = (r >> 3) * 255 / 31;
data[i++] = (byte)r;
data[i++] = (byte)g;
data[i++] = (byte)b;
}
break;
case PixelFormat.Format16bppRgb555:
{
int g = fData[ptr++];
int r = fData[ptr++];
int b = (g & 0x1F) * 255 / 31;
g =( r << 3 & 0x18 | g >> 5 & 0x07) * 255 / 31;
r = ( r >> 2 & 0x1F) * 255 / 31;
data[i++] = (byte)r;
data[i++] = (byte)g;
data[i++] = (byte)b;
}
break;
case (PixelFormat.Format16bppGrayScale):
{
++ptr;
byte all = data[ptr++];
data[i++] = (byte)all;
data[i++] = (byte)all;
data[i++] = (byte)all;
}
break;
case PixelFormat.Format8bppIndexed:
{
int idx = fData[ptr++];
int color = fPalette[idx];
data[i++] = (byte)(color >> 16);
data[i++] = (byte)(color >> 8);
data[i++] = (byte)(color);
if(transparentPixel == idx)
{
int mptr = maskOffset + x/8;
mask[mptr] |= (byte)(1 << (7 - (x & 0x07)));
}
}
break;
case PixelFormat.Format4bppIndexed:
{
int idx = fData[ptr++] >> 4;
int color = fPalette[idx];
data[i++] = (byte)(color >> 16);
data[i++] = (byte)(color >> 8);
data[i++] = (byte)(color);
if(transparentPixel == idx)
{
int mptr = maskOffset + x/8;
mask[mptr] |= (byte)(1 << (7 - (x & 0x07)));
}
++x;
if(x < width)
{
idx = fData[ptr++] & 0x0F;
color = fPalette[idx];
data[i++] = (byte)(color >> 16);
data[i++] = (byte)(color >> 8);
data[i++] = (byte)(color);
if(transparentPixel == idx)
{
int mptr = maskOffset + x/8;
mask[mptr] |= (byte)(1 << (7 - (x & 0x07)));
}
}
}
break;
case PixelFormat.Format1bppIndexed:
{
byte r0 = (byte)(fPalette[0] >> 16);
byte g0 = (byte)(fPalette[0] >> 8);
byte b0 = (byte)(fPalette[0]);
byte r1 = (byte)(fPalette[1] >> 16);
byte g1 = (byte)(fPalette[1] >> 8);
byte b1 = (byte)(fPalette[1]);
byte val = fData[ptr++];
byte m = 0x80;
int j = 0;
int limit = ((width - x) < 8) ? (width - x) : 8;
int mptr = ptr-1;
while(j < limit)
{
m = (byte)(m >> j);
if((val & m) == 0)
{
data[i++] = r0;
data[i++] = g0;
data[i++] = b0;
if(transparentPixel == 0)
{
mask[mptr] |= (byte)(1 << j);
}
}
else
{
data[i++] = r1;
data[i++] = g1;
data[i++] = b1;
if(transparentPixel == 1)
{
mask[mptr] |= (byte)(1 << j);
}
}
++j;
}
x += j;
}
break;
default:
{
imageDataDict = null;
imageData = null;
maskDataDict = null;
maskDataStream = null;
return;
}
// Not reached.
}
offset += stride;
maskOffset += maskStride;
}
}
imageData = PostscriptGraphics.ASCII85Encode(data);
maskDataStream = String.Format
("currentfile /ASCII85Decode filter " +
"/ReusableStreamDecode filter " +
"{0} /maskstream exch def ",
PostscriptGraphics.ASCII85Encode(mask));
}
}; // class PostscriptImage
}; // namespace System.Drawing.Toolkit
| |
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Defines properties for known folders that identify the path of standard known folders.
/// </summary>
public static class KnownFolders
{
/// <summary>
/// Gets a strongly-typed read-only collection of all the registered known folders.
/// </summary>
public static ICollection<IKnownFolder> All
{
get
{
return GetAllFolders();
}
}
private static ReadOnlyCollection<IKnownFolder> GetAllFolders()
{
// Should this method be thread-safe?? (It'll take a while
// to get a list of all the known folders, create the managed wrapper
// and return the read-only collection.
IList<IKnownFolder> foldersList = new List<IKnownFolder>();
uint count;
IntPtr folders;
IKnownFolderManager knownFolderManager = (IKnownFolderManager)new KnownFolderManagerClass();
knownFolderManager.GetFolderIds(out folders, out count);
if (count > 0 && folders != IntPtr.Zero)
{
// Loop through all the KnownFolderID elements
for (int i = 0; i < count; i++)
{
// Read the current pointer
IntPtr current = new IntPtr(folders.ToInt64() + (Marshal.SizeOf(typeof(Guid)) * i));
// Convert to Guid
Guid knownFolderID = (Guid)Marshal.PtrToStructure(current, typeof(Guid));
IKnownFolder kf = null;
// Get the known folder
kf = KnownFolderHelper.FromKnownFolderIdInternal(knownFolderID);
// Add to our collection if it's not null (some folders might not exist on the system
// or we could have an exception that resulted in the null return from above method call
if (kf != null)
foldersList.Add(kf);
}
}
Marshal.FreeCoTaskMem(folders);
return new ReadOnlyCollection<IKnownFolder>(foldersList);
}
private static IKnownFolder GetKnownFolder(Guid guid)
{
return KnownFolderHelper.FromKnownFolderId(guid);
}
#region Default Known Folders
/// <summary>
/// Gets the metadata for the <b>Computer</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Computer
{
get
{
return GetKnownFolder(
FolderIdentifiers.Computer);
}
}
/// <summary>
/// Gets the metadata for the <b>Conflict</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Conflict
{
get
{
return GetKnownFolder(
FolderIdentifiers.Conflict);
}
}
/// <summary>
/// Gets the metadata for the <b>ControlPanel</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder ControlPanel
{
get
{
return GetKnownFolder(
FolderIdentifiers.ControlPanel);
}
}
/// <summary>
/// Gets the metadata for the <b>Desktop</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Desktop
{
get
{
return GetKnownFolder(
FolderIdentifiers.Desktop);
}
}
/// <summary>
/// Gets the metadata for the <b>Internet</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Internet
{
get
{
return GetKnownFolder(
FolderIdentifiers.Internet);
}
}
/// <summary>
/// Gets the metadata for the <b>Network</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Network
{
get
{
return GetKnownFolder(
FolderIdentifiers.Network);
}
}
/// <summary>
/// Gets the metadata for the <b>Printers</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Printers
{
get
{
return GetKnownFolder(
FolderIdentifiers.Printers);
}
}
/// <summary>
/// Gets the metadata for the <b>SyncManager</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SyncManager
{
get
{
return GetKnownFolder(
FolderIdentifiers.SyncManager);
}
}
/// <summary>
/// Gets the metadata for the <b>Connections</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Connections
{
get
{
return GetKnownFolder(
FolderIdentifiers.Connections);
}
}
/// <summary>
/// Gets the metadata for the <b>SyncSetup</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SyncSetup
{
get
{
return GetKnownFolder(
FolderIdentifiers.SyncSetup);
}
}
/// <summary>
/// Gets the metadata for the <b>SyncResults</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SyncResults
{
get
{
return GetKnownFolder(
FolderIdentifiers.SyncResults);
}
}
/// <summary>
/// Gets the metadata for the <b>RecycleBin</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder RecycleBin
{
get
{
return GetKnownFolder(
FolderIdentifiers.RecycleBin);
}
}
/// <summary>
/// Gets the metadata for the <b>Fonts</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Fonts
{
get
{
return GetKnownFolder(FolderIdentifiers.Fonts);
}
}
/// <summary>
/// Gets the metadata for the <b>Startup</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Startup
{
get
{
return GetKnownFolder(FolderIdentifiers.Startup);
}
}
/// <summary>
/// Gets the metadata for the <b>Programs</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Programs
{
get
{
return GetKnownFolder(FolderIdentifiers.Programs);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>StartMenu</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder StartMenu
{
get
{
return GetKnownFolder(FolderIdentifiers.StartMenu);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>Recent</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Recent
{
get
{
return GetKnownFolder(FolderIdentifiers.Recent);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>SendTo</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SendTo
{
get
{
return GetKnownFolder(FolderIdentifiers.SendTo);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>Documents</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Documents
{
get
{
return GetKnownFolder(FolderIdentifiers.Documents);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>Favorites</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Favorites
{
get
{
return GetKnownFolder(FolderIdentifiers.Favorites);
}
}
/// <summary>
/// Gets the metadata for the <b>NetHood</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder NetHood
{
get
{
return GetKnownFolder(FolderIdentifiers.NetHood);
}
}
/// <summary>
/// Gets the metadata for the <b>PrintHood</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder PrintHood
{
get
{
return GetKnownFolder(FolderIdentifiers.PrintHood);
}
}
/// <summary>
/// Gets the metadata for the <b>Templates</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Templates
{
get
{
return GetKnownFolder(FolderIdentifiers.Templates);
}
}
/// <summary>
/// Gets the metadata for the <b>CommonStartup</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder CommonStartup
{
get
{
return GetKnownFolder(FolderIdentifiers.CommonStartup);
}
}
/// <summary>
/// Gets the metadata for the <b>CommonPrograms</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder CommonPrograms
{
get
{
return GetKnownFolder(FolderIdentifiers.CommonPrograms);
}
}
/// <summary>
/// Gets the metadata for the <b>CommonStartMenu</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder CommonStartMenu
{
get
{
return GetKnownFolder(FolderIdentifiers.CommonStartMenu);
}
}
/// <summary>
/// Gets the metadata for the <b>PublicDesktop</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder PublicDesktop
{
get
{
return GetKnownFolder(FolderIdentifiers.PublicDesktop);
}
}
/// <summary>
/// Gets the metadata for the <b>ProgramData</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder ProgramData
{
get
{
return GetKnownFolder(FolderIdentifiers.ProgramData);
}
}
/// <summary>
/// Gets the metadata for the <b>CommonTemplates</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder CommonTemplates
{
get
{
return GetKnownFolder(FolderIdentifiers.CommonTemplates);
}
}
/// <summary>
/// Gets the metadata for the <b>PublicDocuments</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder PublicDocuments
{
get
{
return GetKnownFolder(FolderIdentifiers.PublicDocuments);
}
}
/// <summary>
/// Gets the metadata for the <b>RoamingAppData</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder RoamingAppData
{
get
{
return GetKnownFolder(FolderIdentifiers.RoamingAppData);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>LocalAppData</b>
/// folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder LocalAppData
{
get
{
return GetKnownFolder(FolderIdentifiers.LocalAppData);
}
}
/// <summary>
/// Gets the metadata for the <b>LocalAppDataLow</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder LocalAppDataLow
{
get
{
return GetKnownFolder(FolderIdentifiers.LocalAppDataLow);
}
}
/// <summary>
/// Gets the metadata for the <b>InternetCache</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder InternetCache
{
get
{
return GetKnownFolder(FolderIdentifiers.InternetCache);
}
}
/// <summary>
/// Gets the metadata for the <b>Cookies</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Cookies
{
get
{
return GetKnownFolder(FolderIdentifiers.Cookies);
}
}
/// <summary>
/// Gets the metadata for the <b>History</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder History
{
get
{
return GetKnownFolder(FolderIdentifiers.History);
}
}
/// <summary>
/// Gets the metadata for the <b>System</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder System
{
get
{
return GetKnownFolder(FolderIdentifiers.System);
}
}
/// <summary>
/// Gets the metadata for the <b>SystemX86</b>
/// folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SystemX86
{
get
{
return GetKnownFolder(FolderIdentifiers.SystemX86);
}
}
/// <summary>
/// Gets the metadata for the <b>Windows</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Windows
{
get
{
return GetKnownFolder(FolderIdentifiers.Windows);
}
}
/// <summary>
/// Gets the metadata for the <b>Profile</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Profile
{
get
{
return GetKnownFolder(FolderIdentifiers.Profile);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>Pictures</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Pictures
{
get
{
return GetKnownFolder(FolderIdentifiers.Pictures);
}
}
/// <summary>
/// Gets the metadata for the <b>ProgramFilesX86</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder ProgramFilesX86
{
get
{
return GetKnownFolder(FolderIdentifiers.ProgramFilesX86);
}
}
/// <summary>
/// Gets the metadata for the <b>ProgramFilesCommonX86</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder ProgramFilesCommonX86
{
get
{
return GetKnownFolder(FolderIdentifiers.ProgramFilesCommonX86);
}
}
/// <summary>
/// Gets the metadata for the <b>ProgramsFilesX64</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder ProgramFilesX64
{
get
{
return GetKnownFolder(FolderIdentifiers.ProgramFilesX64);
}
}
/// <summary>
/// Gets the metadata for the <b> ProgramFilesCommonX64</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder ProgramFilesCommonX64
{
get
{
return GetKnownFolder(FolderIdentifiers.ProgramFilesCommonX64);
}
}
/// <summary>
/// Gets the metadata for the <b>ProgramFiles</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder ProgramFiles
{
get
{
return GetKnownFolder(FolderIdentifiers.ProgramFiles);
}
}
/// <summary>
/// Gets the metadata for the <b>ProgramFilesCommon</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder ProgramFilesCommon
{
get
{
return GetKnownFolder(FolderIdentifiers.ProgramFilesCommon);
}
}
/// <summary>
/// Gets the metadata for the <b>AdminTools</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder AdminTools
{
get
{
return GetKnownFolder(FolderIdentifiers.AdminTools);
}
}
/// <summary>
/// Gets the metadata for the <b>CommonAdminTools</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder CommonAdminTools
{
get
{
return GetKnownFolder(FolderIdentifiers.CommonAdminTools);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>Music</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Music
{
get
{
return GetKnownFolder(FolderIdentifiers.Music);
}
}
/// <summary>
/// Gets the metadata for the <b>Videos</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Videos
{
get
{
return GetKnownFolder(FolderIdentifiers.Videos);
}
}
/// <summary>
/// Gets the metadata for the <b>PublicPictures</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder PublicPictures
{
get
{
return GetKnownFolder(FolderIdentifiers.PublicPictures);
}
}
/// <summary>
/// Gets the metadata for the <b>PublicMusic</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder PublicMusic
{
get
{
return GetKnownFolder(FolderIdentifiers.PublicMusic);
}
}
/// <summary>
/// Gets the metadata for the <b>PublicVideos</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder PublicVideos
{
get
{
return GetKnownFolder(FolderIdentifiers.PublicVideos);
}
}
/// <summary>
/// Gets the metadata for the <b>ResourceDir</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder ResourceDir
{
get
{
return GetKnownFolder(FolderIdentifiers.ResourceDir);
}
}
/// <summary>
/// Gets the metadata for the <b>LocalizedResourcesDir</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder LocalizedResourcesDir
{
get
{
return GetKnownFolder(FolderIdentifiers.LocalizedResourcesDir);
}
}
/// <summary>
/// Gets the metadata for the <b>CommonOEMLinks</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "OEM", Justification = "This is following the native API")]
public static IKnownFolder CommonOEMLinks
{
get
{
return GetKnownFolder(FolderIdentifiers.CommonOEMLinks);
}
}
/// <summary>
/// Gets the metadata for the <b>CDBurning</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder CDBurning
{
get
{
return GetKnownFolder(FolderIdentifiers.CDBurning);
}
}
/// <summary>
/// Gets the metadata for the <b>UserProfiles</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder UserProfiles
{
get
{
return GetKnownFolder(FolderIdentifiers.UserProfiles);
}
}
/// <summary>
/// Gets the metadata for the <b>Playlists</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Playlists", Justification = "This is following the native API")]
public static IKnownFolder Playlists
{
get
{
return GetKnownFolder(FolderIdentifiers.Playlists);
}
}
/// <summary>
/// Gets the metadata for the <b>SamplePlaylists</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Playlists", Justification = "This is following the native API")]
public static IKnownFolder SamplePlaylists
{
get
{
return GetKnownFolder(FolderIdentifiers.SamplePlaylists);
}
}
/// <summary>
/// Gets the metadata for the <b>SampleMusic</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SampleMusic
{
get
{
return GetKnownFolder(FolderIdentifiers.SampleMusic);
}
}
/// <summary>
/// Gets the metadata for the <b>SamplePictures</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SamplePictures
{
get
{
return GetKnownFolder(FolderIdentifiers.SamplePictures);
}
}
/// <summary>
/// Gets the metadata for the <b>SampleVideos</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SampleVideos
{
get
{
return GetKnownFolder(FolderIdentifiers.SampleVideos);
}
}
/// <summary>
/// Gets the metadata for the <b>PhotoAlbums</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder PhotoAlbums
{
get
{
return GetKnownFolder(FolderIdentifiers.PhotoAlbums);
}
}
/// <summary>
/// Gets the metadata for the <b>Public</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Public
{
get
{
return GetKnownFolder(FolderIdentifiers.Public);
}
}
/// <summary>
/// Gets the metadata for the <b>ChangeRemovePrograms</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder ChangeRemovePrograms
{
get
{
return GetKnownFolder(FolderIdentifiers.ChangeRemovePrograms);
}
}
/// <summary>
/// Gets the metadata for the <b>AppUpdates</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder AppUpdates
{
get
{
return GetKnownFolder(FolderIdentifiers.AppUpdates);
}
}
/// <summary>
/// Gets the metadata for the <b>AddNewPrograms</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder AddNewPrograms
{
get
{
return GetKnownFolder(FolderIdentifiers.AddNewPrograms);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>Downloads</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Downloads
{
get
{
return GetKnownFolder(FolderIdentifiers.Downloads);
}
}
/// <summary>
/// Gets the metadata for the <b>PublicDownloads</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder PublicDownloads
{
get
{
return GetKnownFolder(FolderIdentifiers.PublicDownloads);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>SavedSearches</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SavedSearches
{
get
{
return GetKnownFolder(FolderIdentifiers.SavedSearches);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>QuickLaunch</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder QuickLaunch
{
get
{
return GetKnownFolder(FolderIdentifiers.QuickLaunch);
}
}
/// <summary>
/// Gets the metadata for the <b>Contacts</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Contacts
{
get
{
return GetKnownFolder(FolderIdentifiers.Contacts);
}
}
/// <summary>
/// Gets the metadata for the <b>SidebarParts</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SidebarParts
{
get
{
return GetKnownFolder(FolderIdentifiers.SidebarParts);
}
}
/// <summary>
/// Gets the metadata for the <b>SidebarDefaultParts</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SidebarDefaultParts
{
get
{
return GetKnownFolder(FolderIdentifiers.SidebarDefaultParts);
}
}
/// <summary>
/// Gets the metadata for the <b>TreeProperties</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder TreeProperties
{
get
{
return GetKnownFolder(FolderIdentifiers.TreeProperties);
}
}
/// <summary>
/// Gets the metadata for the <b>PublicGameTasks</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder PublicGameTasks
{
get
{
return GetKnownFolder(FolderIdentifiers.PublicGameTasks);
}
}
/// <summary>
/// Gets the metadata for the <b>GameTasks</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder GameTasks
{
get
{
return GetKnownFolder(FolderIdentifiers.GameTasks);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>SavedGames</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SavedGames
{
get
{
return GetKnownFolder(FolderIdentifiers.SavedGames);
}
}
/// <summary>
/// Gets the metadata for the <b>Games</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Games
{
get
{
return GetKnownFolder(FolderIdentifiers.Games);
}
}
/// <summary>
/// Gets the metadata for the <b>RecordedTV</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
/// <remarks>This folder is not used.</remarks>
public static IKnownFolder RecordedTV
{
get
{
return GetKnownFolder(FolderIdentifiers.RecordedTV);
}
}
/// <summary>
/// Gets the metadata for the <b>SearchMapi</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SearchMapi
{
get
{
return GetKnownFolder(FolderIdentifiers.SearchMapi);
}
}
/// <summary>
/// Gets the metadata for the <b>SearchCsc</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Csc", Justification = "This is following the native API")]
public static IKnownFolder SearchCsc
{
get
{
return GetKnownFolder(FolderIdentifiers.SearchCsc);
}
}
/// <summary>
/// Gets the metadata for the per-user <b>Links</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder Links
{
get
{
return GetKnownFolder(FolderIdentifiers.Links);
}
}
/// <summary>
/// Gets the metadata for the <b>UsersFiles</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder UsersFiles
{
get
{
return GetKnownFolder(FolderIdentifiers.UsersFiles);
}
}
/// <summary>
/// Gets the metadata for the <b>SearchHome</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder SearchHome
{
get
{
return GetKnownFolder(FolderIdentifiers.SearchHome);
}
}
/// <summary>
/// Gets the metadata for the <b>OriginalImages</b> folder.
/// </summary>
/// <value>An <see cref="IKnownFolder"/> object.</value>
public static IKnownFolder OriginalImages
{
get
{
return GetKnownFolder(FolderIdentifiers.OriginalImages);
}
}
/// <summary>
/// Gets the metadata for the <b>UserProgramFiles</b> folder.
/// </summary>
public static IKnownFolder UserProgramFiles
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.UserProgramFiles);
}
}
/// <summary>
/// Gets the metadata for the <b>UserProgramFilesCommon</b> folder.
/// </summary>
public static IKnownFolder UserProgramFilesCommon
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.UserProgramFilesCommon);
}
}
/// <summary>
/// Gets the metadata for the <b>Ringtones</b> folder.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ringtones", Justification = "This is following the native API")]
public static IKnownFolder Ringtones
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.Ringtones);
}
}
/// <summary>
/// Gets the metadata for the <b>PublicRingtones</b> folder.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ringtones", Justification = "This is following the native API")]
public static IKnownFolder PublicRingtones
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.PublicRingtones);
}
}
/// <summary>
/// Gets the metadata for the <b>UsersLibraries</b> folder.
/// </summary>
public static IKnownFolder UsersLibraries
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.UsersLibraries);
}
}
/// <summary>
/// Gets the metadata for the <b>DocumentsLibrary</b> folder.
/// </summary>
public static IKnownFolder DocumentsLibrary
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.DocumentsLibrary);
}
}
/// <summary>
/// Gets the metadata for the <b>MusicLibrary</b> folder.
/// </summary>
public static IKnownFolder MusicLibrary
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.MusicLibrary);
}
}
/// <summary>
/// Gets the metadata for the <b>PicturesLibrary</b> folder.
/// </summary>
public static IKnownFolder PicturesLibrary
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.PicturesLibrary);
}
}
/// <summary>
/// Gets the metadata for the <b>VideosLibrary</b> folder.
/// </summary>
public static IKnownFolder VideosLibrary
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.VideosLibrary);
}
}
/// <summary>
/// Gets the metadata for the <b>RecordedTVLibrary</b> folder.
/// </summary>
public static IKnownFolder RecordedTVLibrary
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.RecordedTVLibrary);
}
}
/// <summary>
/// Gets the metadata for the <b>OtherUsers</b> folder.
/// </summary>
public static IKnownFolder OtherUsers
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.OtherUsers);
}
}
/// <summary>
/// Gets the metadata for the <b>DeviceMetadataStore</b> folder.
/// </summary>
public static IKnownFolder DeviceMetadataStore
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.DeviceMetadataStore);
}
}
/// <summary>
/// Gets the metadata for the <b>Libraries</b> folder.
/// </summary>
public static IKnownFolder Libraries
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.Libraries);
}
}
/// <summary>
///Gets the metadata for the <b>UserPinned</b> folder.
/// </summary>
public static IKnownFolder UserPinned
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.UserPinned);
}
}
/// <summary>
/// Gets the metadata for the <b>ImplicitAppShortcuts</b> folder.
/// </summary>
public static IKnownFolder ImplicitAppShortcuts
{
get
{
CoreHelpers.ThrowIfNotWin7();
return GetKnownFolder(FolderIdentifiers.ImplicitAppShortcuts);
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmProceduresProcedures.
/// </summary>
public partial class frmServicesPeople : System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
Load_Plans();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.processCommand);
}
#endregion
private void Load_Plans()
{
lblOrg1.Text=(Session["OrgName"]).ToString();
if (!IsPostBack)
{
loadData();
}
}
private void loadData()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_RetrieveServices";
cmd.Connection=this.epsDbConn;
if (Session["CallerServices"].ToString() == "frmPeopleCourses")
{
cmd.Parameters.Add ("@DomainId",SqlDbType.Int);
cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString();
cmd.Parameters.Add ("@Caller",SqlDbType.NVarChar);
cmd.Parameters["@Caller"].Value="frmPeopleCourses";
}
else if ((Session["CallerServices"].ToString() == "frmPeopleStatus"))
{
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
cmd.Parameters.Add ("@Caller",SqlDbType.NVarChar);
cmd.Parameters["@Caller"].Value="frmPeopleStatus";
}
else if ((Session["CallerServices"].ToString() == "frmRoleSkills"))
{
/*cmd.Parameters.Add ("@RoleId",SqlDbType.Int);
cmd.Parameters["@RoleId"].Value=Session["RoleId"].ToString();
cmd.Parameters.Add ("@ResourceId",SqlDbType.Int);
cmd.Parameters["@Caller"].Value="Role";*/
}
else if ((Session["CallerServices"].ToString() == "frmOrgs"))
{
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgIdt"].ToString();
cmd.Parameters.Add ("@Caller",SqlDbType.NVarChar);
cmd.Parameters["@Caller"].Value=Session["CallerServices"].ToString();
}
else if ((Session["CallerServices"].ToString() == "frmMainOrgs"))
{
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
cmd.Parameters.Add ("@Caller",SqlDbType.NVarChar);
cmd.Parameters["@Caller"].Value=Session["CallerServices"].ToString();
}
else if ((Session["CallerServices"].ToString() == "frmMainTrg"))
{
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
cmd.Parameters.Add ("@Caller",SqlDbType.NVarChar);
cmd.Parameters["@Caller"].Value=Session["CallerServices"].ToString();
}
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"Outputs");
Session["ds"]=ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
gridSet();
}
private void gridSet()
{
if (Session["CallerServices"].ToString() == "frmOrgs")
{
lblContent1.Text="Service List";
gridSet2();
}
else if ((Session["CallerServices"].ToString() == "frmPeopleRoles")
|| (Session["CallerServices"].ToString() == "frmPeopleCourses"))
{
lblContent1.Text="Available Courses";
gridSet3();
}
else if (Session["CallerServices"].ToString() == "frmMainTrg")
{
lblContent1.Text="Available Courses";
gridSet2();
}
else
{
lblContent1.Text="Service List";
gridSet2();
}
}
private void gridSet1()
{
foreach (DataGridItem i in DataGrid1.Items)
{
Button bItem = (Button)(i.Cells[6].FindControl("btnItems"));
bItem.Visible=true;
if (i.Cells[9].Text.StartsWith("&") == true)
{
bItem.Enabled=false;
bItem.Text="";
}
else
{
bItem.Text = i.Cells[9].Text;
}
Button bEm = (Button)(i.Cells[8].FindControl("btnProcedures"));
bEm.Visible=false;
Button bRg = (Button)(i.Cells[8].FindControl("btnRegular"));
bRg.Visible=false;
}
}
private void gridSet2()
{
DataGrid1.Columns[1].ItemStyle.Width=300;
DataGrid1.Columns[6].ItemStyle.Width=300;
DataGrid1.Columns[7].ItemStyle.Width=90;
DataGrid1.Columns[8].ItemStyle.Width=100;
DataGrid1.Width=850;
foreach (DataGridItem i in DataGrid1.Items)
{
Button bItem = (Button)(i.Cells[6].FindControl("btnItems"));
if (i.Cells[9].Text.StartsWith("&") == true)
{
bItem.Enabled=false;
bItem.Text="";
}
else
{
bItem.Visible=true;
bItem.Text=i.Cells[9].Text;
/*Button bIt = (Button)(i.Cells[8].FindControl("btnItems"));
bIt.Visible=false;*/
}
}
}
private void gridSet3()
{
DataGrid1.Columns[6].Visible=true;
DataGrid1.Columns[7].Visible=false;
DataGrid1.Columns[8].Visible=false;
DataGrid1.Width=510;
DataGrid1.Columns[6].HeaderStyle.Width=100;
foreach (DataGridItem i in DataGrid1.Items)
{
Button bItem = (Button)(i.Cells[6].FindControl("btnItems"));
if (i.Cells[9].Text.StartsWith("&") == true)
{
bItem.Enabled=false;
bItem.Text="";
}
else
{
bItem.Visible=true;
bItem.Text=i.Cells[9].Text;
}
Button bEm = (Button)(i.Cells[6].FindControl("btnUpdate"));
bEm.Visible=false;
Button bRg = (Button)(i.Cells[6].FindControl("btnDelete"));
bRg.Visible=false;
}
}
protected void btnAdd_Click(object sender, System.EventArgs e)
{
Response.Redirect (strURL + "frmUpdServices.aspx?"
+ "&btnAction=" + "Add"
+ "&SupplierOrg=" + Session["OrgId"].ToString());
}
private void processCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == "BIA")
{
Response.Redirect (strURL + "frmCommitments.aspx?"
+ "&ResourceId=" + e.Item.Cells[0].Text
+ "&OutputName=" + e.Item.Cells[1].Text );
}
else if (e.CommandName == "Update")
{
Response.Redirect (strURL + "frmUpdServices.aspx?"
+ "&btnAction=" + "Update"
+ "&ResourceId=" + e.Item.Cells[0].Text
+ "&Name=" + e.Item.Cells[1].Text
+ "&Desc=" + e.Item.Cells[2].Text
+ "&Vis=" + e.Item.Cells[3].Text
+ "&Type=" + e.Item.Cells[4].Text
+ "&SupplierOrg=" + e.Item.Cells[5].Text);
}
else if (e.CommandName == "Procedures")
{
Session["CallerServiceSteps"]="frmServices";
Session["ServiceName"]=e.Item.Cells[1].Text;
Session["ResourceId"]=e.Item.Cells[0].Text;
//Session["StepType"]="";
Response.Redirect (strURL + "frmServiceSteps.aspx?");
}
/*else if (e.CommandName == "Regular")
{
Session["CallerServiceSteps"]="frmServices";
Session["ServiceName"]=e.Item.Cells[1].Text;
Session["ResourceId"]=e.Item.Cells[0].Text;
Session["StepType"]="Regular";
Response.Redirect (strURL + "frmServiceSteps.aspx?");
}*/
else if (e.CommandName == "Items")
{
Session["CallerActivations"]="frmServices";
Session["ActivationName"]=e.Item.Cells[9].Text;
Session["ServiceName"]=e.Item.Cells[1].Text;
Session["ResourceId"]=e.Item.Cells[0].Text;
Session["Timetable"]=e.Item.Cells[10].Text;
Session["OrgIdt"]=e.Item.Cells[5].Text;
Session["OrgNamet"]=e.Item.Cells[12].Text;
Session["Mode"]="Actual";
//Session["Activity"]=38;
Response.Redirect (strURL + "frmActivations.aspx?");
}
else if (e.CommandName == "Delete")
{
try
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_DeleteOutput";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value=Int32.Parse (e.Item.Cells[0].Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
catch(SqlException err)
{
if (err.Message.StartsWith ("DELETE statement conflicted with COLUMN REFERENCE constraint 'FK_ServiceSteps_Resources'."))
lblContent1.Text = "This service has procedures linked to it.";
else lblContent1.Text = err.Message;
}
}
}
protected void btnExit_Click(object sender, System.EventArgs e)
{
Response.Redirect (strURL + Session["CallerServices"].ToString() + ".aspx?");
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using Aurora.ScriptEngine.AuroraDotNetEngine.APIs.Interfaces;
using Aurora.ScriptEngine.AuroraDotNetEngine.Plugins;
using Aurora.ScriptEngine.AuroraDotNetEngine.Runtime;
using log4net;
namespace Aurora.ScriptEngine.AuroraDotNetEngine
{
/// <summary>
/// This manages app domains and controls what app domains are created/destroyed
/// </summary>
public class AppDomainManager
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private int maxScriptsPerAppDomain = 1;
private bool loadAllScriptsIntoCurrentDomain = false;
private bool loadAllScriptsIntoOneDomain = true;
private string m_PermissionLevel = "Internet";
public string PermissionLevel
{
get { return m_PermissionLevel; }
}
public int NumberOfAppDomains
{
get { return appDomains.Count; }
}
// Internal list of all AppDomains
private List<AppDomainStructure> appDomains =
new List<AppDomainStructure>();
// Structure to keep track of data around AppDomain
private class AppDomainStructure
{
// The AppDomain itself
public AppDomain CurrentAppDomain;
// Number of scripts loaded into AppDomain
public int ScriptsLoaded;
// Number of dead scripts
public int ScriptsWaitingUnload;
}
// Current AppDomain
private AppDomainStructure currentAD;
//This is the main lock for this class
private object m_appDomainLock = new object();
private int AppDomainNameCount;
private ScriptEngine m_scriptEngine;
public AppDomainManager(ScriptEngine scriptEngine)
{
m_scriptEngine = scriptEngine;
ReadConfig();
}
public void ReadConfig()
{
maxScriptsPerAppDomain = m_scriptEngine.ScriptConfigSource.GetInt(
"ScriptsPerAppDomain", 1);
m_PermissionLevel = m_scriptEngine.ScriptConfigSource.GetString(
"AppDomainPermissions", "Internet");
loadAllScriptsIntoCurrentDomain = m_scriptEngine.ScriptConfigSource.GetBoolean("LoadAllScriptsIntoCurrentAppDomain", false);
loadAllScriptsIntoOneDomain = m_scriptEngine.ScriptConfigSource.GetBoolean("LoadAllScriptsIntoOneAppDomain", true);
}
// Find a free AppDomain, creating one if necessary
private AppDomainStructure GetFreeAppDomain()
{
if (loadAllScriptsIntoCurrentDomain)
{
if (currentAD != null)
return currentAD;
else
{
lock (m_appDomainLock)
{
currentAD = new AppDomainStructure();
currentAD.CurrentAppDomain = AppDomain.CurrentDomain;
AppDomain.CurrentDomain.AssemblyResolve += m_scriptEngine.AssemblyResolver.OnAssemblyResolve;
return currentAD;
}
}
}
lock (m_appDomainLock)
{
if (loadAllScriptsIntoOneDomain)
{
if (currentAD == null)
{
// Create a new current AppDomain
currentAD = new AppDomainStructure();
currentAD.CurrentAppDomain = PrepareNewAppDomain();
}
}
else
{
// Current full?
if (currentAD != null &&
currentAD.ScriptsLoaded >= maxScriptsPerAppDomain)
{
// Add it to AppDomains list and empty current
lock (m_appDomainLock)
{
appDomains.Add(currentAD);
}
currentAD = null;
}
// No current
if (currentAD == null)
{
// Create a new current AppDomain
currentAD = new AppDomainStructure();
currentAD.CurrentAppDomain = PrepareNewAppDomain();
}
}
}
return currentAD;
}
// Create and prepare a new AppDomain for scripts
private AppDomain PrepareNewAppDomain()
{
// Create and prepare a new AppDomain
AppDomainNameCount++;
// Construct and initialize settings for a second AppDomain.
AppDomainSetup ads = new AppDomainSetup();
ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
ads.DisallowBindingRedirects = true;
ads.DisallowCodeDownload = true;
ads.LoaderOptimization = LoaderOptimization.MultiDomainHost;
ads.ShadowCopyFiles = "false"; // Disable shadowing
ads.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
AppDomain AD = CreateRestrictedDomain(m_PermissionLevel,
"ScriptAppDomain_" + AppDomainNameCount, ads);
AD.AssemblyResolve += m_scriptEngine.AssemblyResolver.OnAssemblyResolve;
// Return the new AppDomain
return AD;
}
/// From MRMModule.cs by Adam Frisby
/// <summary>
/// Create an AppDomain that contains policy restricting code to execute
/// with only the permissions granted by a named permission set
/// </summary>
/// <param name="permissionSetName">name of the permission set to restrict to</param>
/// <param name="appDomainName">'friendly' name of the appdomain to be created</param>
/// <exception cref="ArgumentNullException">
/// if <paramref name="permissionSetName"/> is null
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// if <paramref name="permissionSetName"/> is empty
/// </exception>
/// <returns>AppDomain with a restricted security policy</returns>
/// <remarks>Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
/// Valid permissionSetName values are:
/// * FullTrust
/// * SkipVerification
/// * Execution
/// * Nothing
/// * LocalIntranet
/// * Internet
/// * Everything
/// </remarks>
public AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName, AppDomainSetup ads)
{
if (permissionSetName == null)
throw new ArgumentNullException("permissionSetName");
if (permissionSetName.Length == 0)
throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
"Cannot have an empty permission set name");
// Default to all code getting everything
PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);
AppDomain restrictedDomain = null;
SecurityZone zone = SecurityZone.MyComputer;
try
{
zone = (SecurityZone)Enum.Parse(typeof(SecurityZone), permissionSetName);
}
catch
{
zone = SecurityZone.MyComputer;
}
Evidence ev = new Evidence();
ev.AddHostEvidence(new Zone(zone));
setIntersection = SecurityManager.GetStandardSandbox(ev);
setIntersection.AddPermission(new System.Net.SocketPermission(PermissionState.Unrestricted));
setIntersection.AddPermission(new System.Net.WebPermission(PermissionState.Unrestricted));
setIntersection.AddPermission(new System.Security.Permissions.SecurityPermission(PermissionState.Unrestricted));
// create an AppDomain where this policy will be in effect
restrictedDomain = AppDomain.CreateDomain(appDomainName, ev, ads, setIntersection, null);
return restrictedDomain;
}
// Unload appdomains that are full and have only dead scripts
private void UnloadAppDomains()
{
lock (m_appDomainLock)
{
// Go through all
foreach (AppDomainStructure ads in appDomains)
{
// Don't process current AppDomain
if (ads.CurrentAppDomain != currentAD.CurrentAppDomain)
{
// Not current AppDomain
// Is number of unloaded bigger or equal to number of loaded?
if (ads.ScriptsLoaded <= ads.ScriptsWaitingUnload)
{
// Remove from internal list
appDomains.Remove(ads);
try
{
// Unload
AppDomain.Unload(ads.CurrentAppDomain);
}
catch { }
ads.CurrentAppDomain = null;
}
}
}
}
}
public IScript LoadScript(string FileName, string TypeName, out AppDomain ad)
{
// Find next available AppDomain to put it in
AppDomainStructure FreeAppDomain = GetFreeAppDomain();
IScript mbrt = (IScript)
FreeAppDomain.CurrentAppDomain.CreateInstanceFromAndUnwrap(
FileName, TypeName);
FreeAppDomain.ScriptsLoaded++;
ad = FreeAppDomain.CurrentAppDomain;
return mbrt;
}
// Increase "dead script" counter for an AppDomain
public void UnloadScriptAppDomain(AppDomain ad)
{
lock (m_appDomainLock)
{
// Check if it is current AppDomain
if (currentAD.CurrentAppDomain == ad)
{
// Yes - increase
currentAD.ScriptsWaitingUnload++;
return;
}
// Lopp through all AppDomains
foreach (AppDomainStructure ads in appDomains)
{
if (ads.CurrentAppDomain == ad)
{
// Found it
ads.ScriptsWaitingUnload++;
break;
}
}
}
UnloadAppDomains(); // Outsite lock, has its own GetLock
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.Text;
using Infrastructure.Common;
using Xunit;
public partial class HttpsTests : ConditionalWcfTest
{
// Client: CustomBinding set MessageVersion to Soap11
// Server: BasicHttpsBinding default value is Soap11
[WcfFact]
[OuterLoop]
[Condition(nameof(Root_Certificate_Installed),
nameof(SSL_Available))]
public static void CrossBinding_Soap11_EchoString()
{
string variationDetails = "Client:: CustomBinding/MessageVersion=Soap11\nServer:: BasicHttpsBinding/DefaultValues";
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
bool success = false;
try
{
CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpsTransportBindingElement());
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Https_DefaultBinding_Address));
IWcfService serviceProxy = factory.CreateChannel();
string result = serviceProxy.Echo(testString);
success = string.Equals(result, testString);
if (!success)
{
errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));
}
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString()));
for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
{
errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
}
}
Assert.True(errorBuilder.Length == 0, "Test case FAILED with errors: " + errorBuilder.ToString());
}
// Client and Server bindings setup exactly the same using default settings.
[WcfFact]
[Condition(nameof(Root_Certificate_Installed),
nameof(SSL_Available))]
[OuterLoop]
public static void SameBinding_DefaultSettings_EchoString()
{
string variationDetails = "Client:: CustomBinding/DefaultValues\nServer:: CustomBinding/DefaultValues";
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
bool success = false;
try
{
CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(), new HttpsTransportBindingElement());
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpsSoap12_Address));
IWcfService serviceProxy = factory.CreateChannel();
string result = serviceProxy.Echo(testString);
success = string.Equals(result, testString);
if (!success)
{
errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));
}
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString()));
for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
{
errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
}
}
Assert.True(errorBuilder.Length == 0, "Test case FAILED with errors: " + errorBuilder.ToString());
}
// Client and Server bindings setup exactly the same using Soap11
[WcfFact]
[Condition(nameof(Root_Certificate_Installed),
nameof(SSL_Available))]
[OuterLoop]
public static void SameBinding_Soap11_EchoString()
{
string variationDetails = "Client:: CustomBinding/MessageVersion=Soap11\nServer:: CustomBinding/MessageVersion=Soap11";
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
bool success = false;
try
{
CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpsTransportBindingElement());
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpsSoap11_Address));
IWcfService serviceProxy = factory.CreateChannel();
string result = serviceProxy.Echo(testString);
success = string.Equals(result, testString);
if (!success)
{
errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));
}
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString()));
for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
{
errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
}
}
Assert.True(errorBuilder.Length == 0, "Test case FAILED with errors: " + errorBuilder.ToString());
}
// Client and Server bindings setup exactly the same using Soap12
[WcfFact]
[Condition(nameof(Root_Certificate_Installed),
nameof(SSL_Available))]
[OuterLoop]
public static void SameBinding_Soap12_EchoString()
{
string variationDetails = "Client:: CustomBinding/MessageVersion=Soap12\nServer:: CustomBinding/MessageVersion=Soap12";
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
bool success = false;
try
{
CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8), new HttpsTransportBindingElement());
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpsSoap12_Address));
IWcfService serviceProxy = factory.CreateChannel();
string result = serviceProxy.Echo(testString);
success = string.Equals(result, testString);
if (!success)
{
errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));
}
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString()));
for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
{
errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
}
}
Assert.True(errorBuilder.Length == 0, "Test case FAILED with errors: " + errorBuilder.ToString());
}
[WcfFact]
[Issue(2870, OS = OSID.AnyOSX)]
[Condition(nameof(Root_Certificate_Installed),
nameof(Client_Certificate_Installed),
nameof(SSL_Available))]
[OuterLoop]
public static void ServerCertificateValidation_EchoString()
{
string clientCertThumb = null;
EndpointAddress endpointAddress = null;
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpsTransportBindingElement());
endpointAddress = new EndpointAddress(new Uri(Endpoints.Https_DefaultBinding_Address));
clientCertThumb = ServiceUtilHelper.ClientCertificate.Thumbprint;
factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
factory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication();
factory.Credentials.ServiceCertificate.SslCertificateAuthentication.CertificateValidationMode = X509CertificateValidationMode.Custom;
MyX509CertificateValidator myX509CertificateValidator = new MyX509CertificateValidator(ScenarioTestHelpers.CertificateIssuerName);
factory.Credentials.ServiceCertificate.SslCertificateAuthentication.CustomCertificateValidator = myX509CertificateValidator;
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.True(myX509CertificateValidator.validateMethodWasCalled, "The Validate method of the X509CertificateValidator was NOT called.");
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Issue(2870, OS = OSID.AnyOSX)]
[Condition(nameof(Root_Certificate_Installed),
nameof(Client_Certificate_Installed),
nameof(Server_Accepts_Certificates),
nameof(SSL_Available))]
[OuterLoop]
public static void ClientCertificate_EchoString()
{
string clientCertThumb = null;
EndpointAddress endpointAddress = null;
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
BasicHttpsBinding basicHttpsBinding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
basicHttpsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
endpointAddress = new EndpointAddress(new Uri(Endpoints.Https_ClientCertificateAuth_Address));
clientCertThumb = ServiceUtilHelper.ClientCertificate.Thumbprint;
factory = new ChannelFactory<IWcfService>(basicHttpsBinding, endpointAddress);
factory.Credentials.ClientCertificate.SetCertificate(
StoreLocation.CurrentUser,
StoreName.My,
X509FindType.FindByThumbprint,
clientCertThumb);
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Issue(2870, OS = OSID.AnyOSX)]
[Condition(nameof(Root_Certificate_Installed),
nameof(Client_Certificate_Installed),
nameof(Server_Accepts_Certificates),
nameof(SSL_Available))]
[OuterLoop]
public static void HttpExpect100Continue_ClientCertificate_True()
{
string clientCertThumb = null;
EndpointAddress endpointAddress = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
BasicHttpsBinding basicHttpsBinding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
basicHttpsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
endpointAddress = new EndpointAddress(new Uri(Endpoints.Https_ClientCertificateAuth_Address));
clientCertThumb = ServiceUtilHelper.ClientCertificate.Thumbprint;
factory = new ChannelFactory<IWcfService>(basicHttpsBinding, endpointAddress);
factory.Credentials.ClientCertificate.SetCertificate(
StoreLocation.CurrentUser,
StoreName.My,
X509FindType.FindByThumbprint,
clientCertThumb);
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
Dictionary<string, string> requestHeaders = serviceProxy.GetRequestHttpHeaders();
// *** VALIDATE *** \\
bool expectHeaderSent = requestHeaders.TryGetValue("Expect", out var expectHeader);
Assert.True(expectHeaderSent, "Expect header should have been sent but wasn't");
Assert.Equal("100-Continue", expectHeader, StringComparer.OrdinalIgnoreCase);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.DirectoryServices.Protocols;
using System.IO;
using System.Linq;
using System.Net.Test.Common;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
public abstract class HttpClientHandler_Cancellation_Test : HttpClientHandlerTestBase
{
public HttpClientHandler_Cancellation_Test(ITestOutputHelper output) : base(output) { }
[Theory]
[InlineData(false, CancellationMode.Token)]
[InlineData(true, CancellationMode.Token)]
public async Task PostAsync_CancelDuringRequestContentSend_TaskCanceledQuickly(bool chunkedTransfer, CancellationMode mode)
{
if (!UseSocketsHttpHandler)
{
// Issue #27063: hangs / doesn't cancel
return;
}
if (LoopbackServerFactory.IsHttp2 && chunkedTransfer)
{
// There is no chunked encoding in HTTP/2
return;
}
var serverRelease = new TaskCompletionSource<bool>();
await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
{
try
{
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
var waitToSend = new TaskCompletionSource<bool>();
var contentSending = new TaskCompletionSource<bool>();
var req = new HttpRequestMessage(HttpMethod.Post, uri) { Version = VersionFromUseHttp2 };
req.Content = new ByteAtATimeContent(int.MaxValue, waitToSend.Task, contentSending, millisecondDelayBetweenBytes: 1);
req.Headers.TransferEncodingChunked = chunkedTransfer;
Task<HttpResponseMessage> resp = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
waitToSend.SetResult(true);
await contentSending.Task;
Cancel(mode, client, cts);
await ValidateClientCancellationAsync(() => resp);
}
}
finally
{
serverRelease.SetResult(true);
}
}, async server =>
{
try
{
await server.AcceptConnectionAsync(connection => serverRelease.Task);
}
catch { }; // Ignore any closing errors since we did not really process anything.
});
}
[Theory]
[MemberData(nameof(TwoBoolsAndCancellationMode))]
public async Task GetAsync_CancelDuringResponseHeadersReceived_TaskCanceledQuickly(bool chunkedTransfer, bool connectionClose, CancellationMode mode)
{
if (LoopbackServerFactory.IsHttp2 && connectionClose)
{
// There is no Connection header in HTTP/2
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
var partialResponseHeadersSent = new TaskCompletionSource<bool>();
var clientFinished = new TaskCompletionSource<bool>();
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestDataAsync();
await connection.SendResponseAsync(HttpStatusCode.OK, content: null, isFinal: false);
partialResponseHeadersSent.TrySetResult(true);
await clientFinished.Task;
});
await ValidateClientCancellationAsync(async () =>
{
var req = new HttpRequestMessage(HttpMethod.Get, url) { Version = VersionFromUseHttp2 };
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> getResponse = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
await partialResponseHeadersSent.Task;
Cancel(mode, client, cts);
await getResponse;
});
try
{
clientFinished.SetResult(true);
await serverTask;
} catch { }
});
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Test needs to be rewritten to work on UAP due to WinRT differences")]
[Theory]
[MemberData(nameof(TwoBoolsAndCancellationMode))]
public async Task GetAsync_CancelDuringResponseBodyReceived_Buffered_TaskCanceledQuickly(bool chunkedTransfer, bool connectionClose, CancellationMode mode)
{
if (LoopbackServerFactory.IsHttp2 && (chunkedTransfer || connectionClose))
{
// There is no chunked encoding or connection header in HTTP/2
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
var responseHeadersSent = new TaskCompletionSource<bool>();
var clientFinished = new TaskCompletionSource<bool>();
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
var headers = new List<HttpHeaderData>();
headers.Add(chunkedTransfer ? new HttpHeaderData("Transfer-Encoding", "chunked") : new HttpHeaderData("Content-Length", "20"));
if (connectionClose)
{
headers.Add(new HttpHeaderData("Connection", "close"));
}
await connection.ReadRequestDataAsync();
await connection.SendResponseAsync(HttpStatusCode.OK, headers: headers, content: "123", isFinal: false);
responseHeadersSent.TrySetResult(true);
await clientFinished.Task;
});
await ValidateClientCancellationAsync(async () =>
{
var req = new HttpRequestMessage(HttpMethod.Get, url) { Version = VersionFromUseHttp2 };
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> getResponse = client.SendAsync(req, HttpCompletionOption.ResponseContentRead, cts.Token);
await responseHeadersSent.Task;
await Task.Delay(1); // make it more likely that client will have started processing response body
Cancel(mode, client, cts);
await getResponse;
});
try
{
clientFinished.SetResult(true);
await serverTask;
} catch { }
});
}
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // [ActiveIssue(38547)]
[MemberData(nameof(ThreeBools))]
public async Task GetAsync_CancelDuringResponseBodyReceived_Unbuffered_TaskCanceledQuickly(bool chunkedTransfer, bool connectionClose, bool readOrCopyToAsync)
{
if (IsCurlHandler)
{
// doesn't cancel
return;
}
if (LoopbackServerFactory.IsHttp2 && (chunkedTransfer || connectionClose))
{
// There is no chunked encoding or connection header in HTTP/2
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
var clientFinished = new TaskCompletionSource<bool>();
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
var headers = new List<HttpHeaderData>();
headers.Add(chunkedTransfer ? new HttpHeaderData("Transfer-Encoding", "chunked") : new HttpHeaderData("Content-Length", "20"));
if (connectionClose)
{
headers.Add(new HttpHeaderData("Connection", "close"));
}
await connection.ReadRequestDataAsync();
await connection.SendResponseAsync(HttpStatusCode.OK, headers: headers, isFinal: false);
await clientFinished.Task;
});
var req = new HttpRequestMessage(HttpMethod.Get, url) { Version = VersionFromUseHttp2 };
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> getResponse = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
await ValidateClientCancellationAsync(async () =>
{
HttpResponseMessage resp = await getResponse;
Stream respStream = await resp.Content.ReadAsStreamAsync();
Task readTask = readOrCopyToAsync ?
respStream.ReadAsync(new byte[1], 0, 1, cts.Token) :
respStream.CopyToAsync(Stream.Null, 10, cts.Token);
cts.Cancel();
await readTask;
});
try
{
clientFinished.SetResult(true);
await serverTask;
} catch { }
});
}
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "cancellation timing is different on UAP, sensitive to race conditions")]
[InlineData(CancellationMode.CancelPendingRequests, false)]
[InlineData(CancellationMode.DisposeHttpClient, true)]
[InlineData(CancellationMode.CancelPendingRequests, false)]
[InlineData(CancellationMode.DisposeHttpClient, true)]
public async Task GetAsync_CancelPendingRequests_DoesntCancelReadAsyncOnResponseStream(CancellationMode mode, bool copyToAsync)
{
if (IsCurlHandler)
{
// Issue #27065
// throws OperationCanceledException from Stream.CopyToAsync/ReadAsync
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
var clientReadSomeBody = new TaskCompletionSource<bool>();
var clientFinished = new TaskCompletionSource<bool>();
var responseContentSegment = new string('s', 3000);
int responseSegments = 4;
int contentLength = responseContentSegment.Length * responseSegments;
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestDataAsync();
await connection.SendResponseAsync(HttpStatusCode.OK, headers: new HttpHeaderData[] { new HttpHeaderData("Content-Length", contentLength.ToString()) }, isFinal: false);
for (int i = 0; i < responseSegments; i++)
{
await connection.SendResponseBodyAsync(responseContentSegment, isFinal: i == responseSegments - 1);
if (i == 0)
{
await clientReadSomeBody.Task;
}
}
await clientFinished.Task;
});
using (HttpResponseMessage resp = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
using (Stream respStream = await resp.Content.ReadAsStreamAsync())
{
var result = new MemoryStream();
int b = respStream.ReadByte();
Assert.NotEqual(-1, b);
result.WriteByte((byte)b);
Cancel(mode, client, null); // should not cancel the operation, as using ResponseHeadersRead
clientReadSomeBody.SetResult(true);
if (copyToAsync)
{
await respStream.CopyToAsync(result, 10, new CancellationTokenSource().Token);
}
else
{
byte[] buffer = new byte[10];
int bytesRead;
while ((bytesRead = await respStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
result.Write(buffer, 0, bytesRead);
}
}
Assert.Equal(contentLength, result.Length);
}
clientFinished.SetResult(true);
await serverTask;
});
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "WinRT stack can't set MaxConnectionsPerServer < 2")]
[ConditionalFact]
public async Task MaxConnectionsPerServer_WaitingConnectionsAreCancelable()
{
if (IsCurlHandler)
{
// With CurlHandler, this test sometimes hangs.
throw new SkipTestException("Skipping on unstable platform handler");
}
if (LoopbackServerFactory.IsHttp2)
{
// HTTP/2 does not use connection limits.
throw new SkipTestException("Not supported on HTTP/2");
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = CreateHttpClient(handler))
{
handler.MaxConnectionsPerServer = 1;
client.Timeout = Timeout.InfiniteTimeSpan;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var serverAboutToBlock = new TaskCompletionSource<bool>();
var blockServerResponse = new TaskCompletionSource<bool>();
Task serverTask1 = server.AcceptConnectionAsync(async connection1 =>
{
await connection1.ReadRequestHeaderAsync();
await connection1.Writer.WriteAsync($"HTTP/1.1 200 OK\r\nConnection: close\r\nDate: {DateTimeOffset.UtcNow:R}\r\n");
serverAboutToBlock.SetResult(true);
await blockServerResponse.Task;
await connection1.Writer.WriteAsync("Content-Length: 5\r\n\r\nhello");
});
Task get1 = client.GetAsync(url);
await serverAboutToBlock.Task;
var cts = new CancellationTokenSource();
Task get2 = ValidateClientCancellationAsync(() => client.GetAsync(url, cts.Token));
Task get3 = ValidateClientCancellationAsync(() => client.GetAsync(url, cts.Token));
Task get4 = client.GetAsync(url);
cts.Cancel();
await get2;
await get3;
blockServerResponse.SetResult(true);
await new[] { get1, serverTask1 }.WhenAllOrAnyFailed();
Task serverTask4 = server.AcceptConnectionSendResponseAndCloseAsync();
await new[] { get4, serverTask4 }.WhenAllOrAnyFailed();
});
}
}
[Fact]
public async Task SendAsync_Cancel_CancellationTokenPropagates()
{
TaskCompletionSource<bool> clientCanceled = new TaskCompletionSource<bool>();
await LoopbackServerFactory.CreateClientAndServerAsync(
async uri =>
{
var cts = new CancellationTokenSource();
cts.Cancel();
using (HttpClient client = CreateHttpClient())
{
OperationCanceledException ex = null;
try
{
await client.GetAsync(uri, cts.Token);
}
catch(OperationCanceledException e)
{
ex = e;
}
Assert.True(ex != null, "Expected OperationCancelledException, but no exception was thrown.");
Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested");
// .NET Framework has bug where it doesn't propagate token information.
Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested");
clientCanceled.SetResult(true);
}
},
async server =>
{
Task serverTask = server.HandleRequestAsync();
await clientCanceled.Task;
});
}
public static IEnumerable<object[]> PostAsync_Cancel_CancellationTokenPassedToContent_MemberData()
{
// Note: For HTTP2, the actual token will be a linked token and will not be an exact match for the original token.
// Verify that it behaves as expected by cancelling it and validating that cancellation propagates.
// StreamContent
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
var actualToken = new StrongBox<CancellationToken>();
bool called = false;
var content = new StreamContent(new DelegateStream(
canReadFunc: () => true,
readAsyncFunc: (buffer, offset, count, cancellationToken) =>
{
int result = 1;
if (called)
{
result = 0;
Assert.False(cancellationToken.IsCancellationRequested);
tokenSource.Cancel();
Assert.True(cancellationToken.IsCancellationRequested);
}
called = true;
return Task.FromResult(result);
}
));
yield return new object[] { content, tokenSource };
}
// MultipartContent
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
var actualToken = new StrongBox<CancellationToken>();
bool called = false;
var content = new MultipartContent();
content.Add(new StreamContent(new DelegateStream(
canReadFunc: () => true,
canSeekFunc: () => true,
lengthFunc: () => 1,
positionGetFunc: () => 0,
positionSetFunc: _ => {},
readAsyncFunc: (buffer, offset, count, cancellationToken) =>
{
int result = 1;
if (called)
{
result = 0;
Assert.False(cancellationToken.IsCancellationRequested);
tokenSource.Cancel();
Assert.True(cancellationToken.IsCancellationRequested);
}
called = true;
return Task.FromResult(result);
}
)));
yield return new object[] { content, tokenSource };
}
// MultipartFormDataContent
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
var actualToken = new StrongBox<CancellationToken>();
bool called = false;
var content = new MultipartFormDataContent();
content.Add(new StreamContent(new DelegateStream(
canReadFunc: () => true,
canSeekFunc: () => true,
lengthFunc: () => 1,
positionGetFunc: () => 0,
positionSetFunc: _ => {},
readAsyncFunc: (buffer, offset, count, cancellationToken) =>
{
int result = 1;
if (called)
{
result = 0;
Assert.False(cancellationToken.IsCancellationRequested);
tokenSource.Cancel();
Assert.True(cancellationToken.IsCancellationRequested);
}
called = true;
return Task.FromResult(result);
}
)));
yield return new object[] { content, tokenSource };
}
}
[OuterLoop("Uses Task.Delay")]
[Theory]
[MemberData(nameof(PostAsync_Cancel_CancellationTokenPassedToContent_MemberData))]
public async Task PostAsync_Cancel_CancellationTokenPassedToContent(HttpContent content, CancellationTokenSource cancellationTokenSource)
{
if (IsUapHandler)
{
// HttpHandlerToFilter doesn't flow the token into the request body.
return;
}
await LoopbackServerFactory.CreateClientAndServerAsync(
async uri =>
{
using (var invoker = new HttpMessageInvoker(CreateHttpClientHandler()))
using (var req = new HttpRequestMessage(HttpMethod.Post, uri) { Content = content, Version = VersionFromUseHttp2 })
try
{
using (HttpResponseMessage resp = await invoker.SendAsync(req, cancellationTokenSource.Token))
{
Assert.Equal("Hello World", await resp.Content.ReadAsStringAsync());
}
}
catch (OperationCanceledException) { }
},
async server =>
{
try
{
await server.HandleRequestAsync(content: "Hello World");
}
catch (Exception) { }
});
}
private async Task ValidateClientCancellationAsync(Func<Task> clientBodyAsync)
{
var stopwatch = Stopwatch.StartNew();
Exception error = await Record.ExceptionAsync(clientBodyAsync);
stopwatch.Stop();
Assert.NotNull(error);
Assert.True(
error is OperationCanceledException,
"Expected cancellation exception, got:" + Environment.NewLine + error);
Assert.True(stopwatch.Elapsed < new TimeSpan(0, 0, 60), $"Elapsed time {stopwatch.Elapsed} should be less than 60 seconds, was {stopwatch.Elapsed.TotalSeconds}");
}
private static void Cancel(CancellationMode mode, HttpClient client, CancellationTokenSource cts)
{
if ((mode & CancellationMode.Token) != 0)
{
cts?.Cancel();
}
if ((mode & CancellationMode.CancelPendingRequests) != 0)
{
client?.CancelPendingRequests();
}
if ((mode & CancellationMode.DisposeHttpClient) != 0)
{
client?.Dispose();
}
}
[Flags]
public enum CancellationMode
{
Token = 0x1,
CancelPendingRequests = 0x2,
DisposeHttpClient = 0x4
}
private static readonly bool[] s_bools = new[] { true, false };
public static IEnumerable<object[]> TwoBoolsAndCancellationMode() =>
from first in s_bools
from second in s_bools
from mode in new[] { CancellationMode.Token, CancellationMode.CancelPendingRequests, CancellationMode.DisposeHttpClient, CancellationMode.Token | CancellationMode.CancelPendingRequests }
select new object[] { first, second, mode };
public static IEnumerable<object[]> ThreeBools() =>
from first in s_bools
from second in s_bools
from third in s_bools
select new object[] { first, second, third };
}
}
| |
namespace android.os
{
[global::MonoJavaBridge.JavaClass()]
public partial class DropBoxManager : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static DropBoxManager()
{
InitJNI();
}
protected DropBoxManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public partial class Entry : java.lang.Object, Parcelable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Entry()
{
InitJNI();
}
protected Entry(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _close6377;
public virtual void close()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry._close6377);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._close6377);
}
internal static global::MonoJavaBridge.MethodId _getInputStream6378;
public virtual global::java.io.InputStream getInputStream()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry._getInputStream6378)) as java.io.InputStream;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._getInputStream6378)) as java.io.InputStream;
}
internal static global::MonoJavaBridge.MethodId _getTag6379;
public virtual global::java.lang.String getTag()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry._getTag6379)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._getTag6379)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getText6380;
public virtual global::java.lang.String getText(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry._getText6380, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._getText6380, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _writeToParcel6381;
public virtual void writeToParcel(android.os.Parcel arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry._writeToParcel6381, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._writeToParcel6381, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _describeContents6382;
public virtual int describeContents()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry._describeContents6382);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._describeContents6382);
}
internal static global::MonoJavaBridge.MethodId _getFlags6383;
public virtual int getFlags()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry._getFlags6383);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._getFlags6383);
}
internal static global::MonoJavaBridge.MethodId _getTimeMillis6384;
public virtual long getTimeMillis()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry._getTimeMillis6384);
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._getTimeMillis6384);
}
internal static global::MonoJavaBridge.MethodId _Entry6385;
public Entry(java.lang.String arg0, long arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._Entry6385, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Entry6386;
public Entry(java.lang.String arg0, long arg1, java.lang.String arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._Entry6386, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Entry6387;
public Entry(java.lang.String arg0, long arg1, byte[] arg2, int arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._Entry6387, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Entry6388;
public Entry(java.lang.String arg0, long arg1, android.os.ParcelFileDescriptor arg2, int arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._Entry6388, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Entry6389;
public Entry(java.lang.String arg0, long arg1, java.io.File arg2, int arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.DropBoxManager.Entry.staticClass, global::android.os.DropBoxManager.Entry._Entry6389, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _CREATOR6390;
public static global::android.os.Parcelable_Creator CREATOR
{
get
{
return default(global::android.os.Parcelable_Creator);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.os.DropBoxManager.Entry.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/DropBoxManager$Entry"));
global::android.os.DropBoxManager.Entry._close6377 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "close", "()V");
global::android.os.DropBoxManager.Entry._getInputStream6378 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "getInputStream", "()Ljava/io/InputStream;");
global::android.os.DropBoxManager.Entry._getTag6379 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "getTag", "()Ljava/lang/String;");
global::android.os.DropBoxManager.Entry._getText6380 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "getText", "(I)Ljava/lang/String;");
global::android.os.DropBoxManager.Entry._writeToParcel6381 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V");
global::android.os.DropBoxManager.Entry._describeContents6382 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "describeContents", "()I");
global::android.os.DropBoxManager.Entry._getFlags6383 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "getFlags", "()I");
global::android.os.DropBoxManager.Entry._getTimeMillis6384 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "getTimeMillis", "()J");
global::android.os.DropBoxManager.Entry._Entry6385 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "<init>", "(Ljava/lang/String;J)V");
global::android.os.DropBoxManager.Entry._Entry6386 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "<init>", "(Ljava/lang/String;JLjava/lang/String;)V");
global::android.os.DropBoxManager.Entry._Entry6387 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "<init>", "(Ljava/lang/String;J[BI)V");
global::android.os.DropBoxManager.Entry._Entry6388 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "<init>", "(Ljava/lang/String;JLandroid/os/ParcelFileDescriptor;I)V");
global::android.os.DropBoxManager.Entry._Entry6389 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.Entry.staticClass, "<init>", "(Ljava/lang/String;JLjava/io/File;I)V");
}
}
internal static global::MonoJavaBridge.MethodId _getNextEntry6391;
public virtual global::android.os.DropBoxManager.Entry getNextEntry(java.lang.String arg0, long arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.DropBoxManager._getNextEntry6391, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.os.DropBoxManager.Entry;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.DropBoxManager.staticClass, global::android.os.DropBoxManager._getNextEntry6391, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.os.DropBoxManager.Entry;
}
internal static global::MonoJavaBridge.MethodId _addText6392;
public virtual void addText(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.DropBoxManager._addText6392, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.DropBoxManager.staticClass, global::android.os.DropBoxManager._addText6392, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _addData6393;
public virtual void addData(java.lang.String arg0, byte[] arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.DropBoxManager._addData6393, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.DropBoxManager.staticClass, global::android.os.DropBoxManager._addData6393, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _addFile6394;
public virtual void addFile(java.lang.String arg0, java.io.File arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.DropBoxManager._addFile6394, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.DropBoxManager.staticClass, global::android.os.DropBoxManager._addFile6394, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _isTagEnabled6395;
public virtual bool isTagEnabled(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.DropBoxManager._isTagEnabled6395, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.DropBoxManager.staticClass, global::android.os.DropBoxManager._isTagEnabled6395, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _DropBoxManager6396;
protected DropBoxManager() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.DropBoxManager.staticClass, global::android.os.DropBoxManager._DropBoxManager6396);
Init(@__env, handle);
}
public static int IS_EMPTY
{
get
{
return 1;
}
}
public static int IS_TEXT
{
get
{
return 2;
}
}
public static int IS_GZIPPED
{
get
{
return 4;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.os.DropBoxManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/DropBoxManager"));
global::android.os.DropBoxManager._getNextEntry6391 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.staticClass, "getNextEntry", "(Ljava/lang/String;J)Landroid/os/DropBoxManager$Entry;");
global::android.os.DropBoxManager._addText6392 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.staticClass, "addText", "(Ljava/lang/String;Ljava/lang/String;)V");
global::android.os.DropBoxManager._addData6393 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.staticClass, "addData", "(Ljava/lang/String;[BI)V");
global::android.os.DropBoxManager._addFile6394 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.staticClass, "addFile", "(Ljava/lang/String;Ljava/io/File;I)V");
global::android.os.DropBoxManager._isTagEnabled6395 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.staticClass, "isTagEnabled", "(Ljava/lang/String;)Z");
global::android.os.DropBoxManager._DropBoxManager6396 = @__env.GetMethodIDNoThrow(global::android.os.DropBoxManager.staticClass, "<init>", "()V");
}
}
}
| |
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
namespace System.Runtime.Intrinsics.Arm.Arm64
{
/// <summary>
/// This class provides access to the Arm64 AdvSIMD intrinsics
///
/// Arm64 CPU indicate support for this feature by setting
/// ID_AA64PFR0_EL1.AdvSIMD == 0 or better.
/// </summary>
[CLSCompliant(false)]
public static class Simd
{
/// <summary>
/// IsSupported property indicates whether any method provided
/// by this class is supported by the current runtime.
/// </summary>
public static bool IsSupported { get => IsSupported; }
/// <summary>
/// Vector abs
/// Corresponds to vector forms of ARM64 ABS & FABS
/// </summary>
public static Vector64<byte> Abs(Vector64<sbyte> value) => Abs(value);
public static Vector64<ushort> Abs(Vector64<short> value) => Abs(value);
public static Vector64<uint> Abs(Vector64<int> value) => Abs(value);
public static Vector64<float> Abs(Vector64<float> value) => Abs(value);
public static Vector128<byte> Abs(Vector128<sbyte> value) => Abs(value);
public static Vector128<ushort> Abs(Vector128<short> value) => Abs(value);
public static Vector128<uint> Abs(Vector128<int> value) => Abs(value);
public static Vector128<ulong> Abs(Vector128<long> value) => Abs(value);
public static Vector128<float> Abs(Vector128<float> value) => Abs(value);
public static Vector128<double> Abs(Vector128<double> value) => Abs(value);
/// <summary>
/// Vector add
/// Corresponds to vector forms of ARM64 ADD & FADD
/// </summary>
public static Vector64<T> Add<T>(Vector64<T> left, Vector64<T> right) where T : struct => Add(left, right);
public static Vector128<T> Add<T>(Vector128<T> left, Vector128<T> right) where T : struct => Add(left, right);
/// <summary>
/// Vector and
/// Corresponds to vector forms of ARM64 AND
/// </summary>
public static Vector64<T> And<T>(Vector64<T> left, Vector64<T> right) where T : struct => And(left, right);
public static Vector128<T> And<T>(Vector128<T> left, Vector128<T> right) where T : struct => And(left, right);
/// <summary>
/// Vector and not
/// Corresponds to vector forms of ARM64 BIC
/// </summary>
public static Vector64<T> AndNot<T>(Vector64<T> left, Vector64<T> right) where T : struct => AndNot(left, right);
public static Vector128<T> AndNot<T>(Vector128<T> left, Vector128<T> right) where T : struct => AndNot(left, right);
/// <summary>
/// Vector BitwiseSelect
/// For each bit in the vector result[bit] = sel[bit] ? left[bit] : right[bit]
/// Corresponds to vector forms of ARM64 BSL (Also BIF & BIT)
/// </summary>
public static Vector64<T> BitwiseSelect<T>(Vector64<T> sel, Vector64<T> left, Vector64<T> right) where T : struct => BitwiseSelect(sel, left, right);
public static Vector128<T> BitwiseSelect<T>(Vector128<T> sel, Vector128<T> left, Vector128<T> right) where T : struct => BitwiseSelect(sel, left, right);
/// <summary>
/// Vector CompareEqual
/// For each element result[elem] = (left[elem] == right[elem]) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMEQ & FCMEQ
/// </summary>
public static Vector64<T> CompareEqual<T>(Vector64<T> left, Vector64<T> right) where T : struct => CompareEqual(left, right);
public static Vector128<T> CompareEqual<T>(Vector128<T> left, Vector128<T> right) where T : struct => CompareEqual(left, right);
/// <summary>
/// Vector CompareEqualZero
/// For each element result[elem] = (left[elem] == 0) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMEQ & FCMEQ
/// </summary>
public static Vector64<T> CompareEqualZero<T>(Vector64<T> value) where T : struct => CompareEqualZero(value);
public static Vector128<T> CompareEqualZero<T>(Vector128<T> value) where T : struct => CompareEqualZero(value);
/// <summary>
/// Vector CompareGreaterThan
/// For each element result[elem] = (left[elem] > right[elem]) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMGT/CMHI & FCMGT
/// </summary>
public static Vector64<T> CompareGreaterThan<T>(Vector64<T> left, Vector64<T> right) where T : struct => CompareGreaterThan(left, right);
public static Vector128<T> CompareGreaterThan<T>(Vector128<T> left, Vector128<T> right) where T : struct => CompareGreaterThan(left, right);
/// <summary>
/// Vector CompareGreaterThanZero
/// For each element result[elem] = (left[elem] > 0) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMGT & FCMGT
/// </summary>
public static Vector64<T> CompareGreaterThanZero<T>(Vector64<T> value) where T : struct => CompareGreaterThanZero(value);
public static Vector128<T> CompareGreaterThanZero<T>(Vector128<T> value) where T : struct => CompareGreaterThanZero(value);
/// <summary>
/// Vector CompareGreaterThanOrEqual
/// For each element result[elem] = (left[elem] >= right[elem]) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMGE/CMHS & FCMGE
/// </summary>
public static Vector64<T> CompareGreaterThanOrEqual<T>(Vector64<T> left, Vector64<T> right) where T : struct => CompareGreaterThanOrEqual(left, right);
public static Vector128<T> CompareGreaterThanOrEqual<T>(Vector128<T> left, Vector128<T> right) where T : struct => CompareGreaterThanOrEqual(left, right);
/// <summary>
/// Vector CompareGreaterThanOrEqualZero
/// For each element result[elem] = (left[elem] >= 0) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMGE & FCMGE
/// </summary>
public static Vector64<T> CompareGreaterThanOrEqualZero<T>(Vector64<T> value) where T : struct => CompareGreaterThanOrEqualZero(value);
public static Vector128<T> CompareGreaterThanOrEqualZero<T>(Vector128<T> value) where T : struct => CompareGreaterThanOrEqualZero(value);
/// <summary>
/// Vector CompareLessThanZero
/// For each element result[elem] = (left[elem] < 0) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMGT & FCMGT
/// </summary>
public static Vector64<T> CompareLessThanZero<T>(Vector64<T> value) where T : struct => CompareLessThanZero(value);
public static Vector128<T> CompareLessThanZero<T>(Vector128<T> value) where T : struct => CompareLessThanZero(value);
/// <summary>
/// Vector CompareLessThanOrEqualZero
/// For each element result[elem] = (left[elem] < 0) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMGT & FCMGT
/// </summary>
public static Vector64<T> CompareLessThanOrEqualZero<T>(Vector64<T> value) where T : struct => CompareLessThanOrEqualZero(value);
public static Vector128<T> CompareLessThanOrEqualZero<T>(Vector128<T> value) where T : struct => CompareLessThanOrEqualZero(value);
/// <summary>
/// Vector CompareTest
/// For each element result[elem] = (left[elem] & right[elem]) ? ~0 : 0
/// Corresponds to vector forms of ARM64 CMTST
/// </summary>
public static Vector64<T> CompareTest<T>(Vector64<T> left, Vector64<T> right) where T : struct => CompareTest(left, right);
public static Vector128<T> CompareTest<T>(Vector128<T> left, Vector128<T> right) where T : struct => CompareTest(left, right);
/// TBD Convert...
/// <summary>
/// Vector Divide
/// Corresponds to vector forms of ARM64 FDIV
/// </summary>
public static Vector64<float> Divide(Vector64<float> left, Vector64<float> right) => Divide(left, right);
public static Vector128<float> Divide(Vector128<float> left, Vector128<float> right) => Divide(left, right);
public static Vector128<double> Divide(Vector128<double> left, Vector128<double> right) => Divide(left, right);
/// <summary>
/// Vector extract item
///
/// result = vector[index]
///
/// Note: In order to be inlined, index must be a JIT time const expression which can be used to
/// populate the literal immediate field. Use of a non constant will result in generation of a switch table
///
/// Corresponds to vector forms of ARM64 MOV
/// </summary>
public static T Extract<T>(Vector64<T> vector, byte index) where T : struct => Extract(vector, index);
public static T Extract<T>(Vector128<T> vector, byte index) where T : struct => Extract(vector, index);
/// <summary>
/// Vector insert item
///
/// result = vector;
/// result[index] = data;
///
/// Note: In order to be inlined, index must be a JIT time const expression which can be used to
/// populate the literal immediate field. Use of a non constant will result in generation of a switch table
///
/// Corresponds to vector forms of ARM64 INS
/// </summary>
public static Vector64<T> Insert<T>(Vector64<T> vector, byte index, T data) where T : struct => Insert(vector, index, data);
public static Vector128<T> Insert<T>(Vector128<T> vector, byte index, T data) where T : struct => Insert(vector, index, data);
/// <summary>
/// Vector LeadingSignCount
/// Corresponds to vector forms of ARM64 CLS
/// </summary>
public static Vector64<sbyte> LeadingSignCount(Vector64<sbyte> value) => LeadingSignCount(value);
public static Vector64<short> LeadingSignCount(Vector64<short> value) => LeadingSignCount(value);
public static Vector64<int> LeadingSignCount(Vector64<int> value) => LeadingSignCount(value);
public static Vector128<sbyte> LeadingSignCount(Vector128<sbyte> value) => LeadingSignCount(value);
public static Vector128<short> LeadingSignCount(Vector128<short> value) => LeadingSignCount(value);
public static Vector128<int> LeadingSignCount(Vector128<int> value) => LeadingSignCount(value);
/// <summary>
/// Vector LeadingZeroCount
/// Corresponds to vector forms of ARM64 CLZ
/// </summary>
public static Vector64<byte> LeadingZeroCount(Vector64<byte> value) => LeadingZeroCount(value);
public static Vector64<sbyte> LeadingZeroCount(Vector64<sbyte> value) => LeadingZeroCount(value);
public static Vector64<ushort> LeadingZeroCount(Vector64<ushort> value) => LeadingZeroCount(value);
public static Vector64<short> LeadingZeroCount(Vector64<short> value) => LeadingZeroCount(value);
public static Vector64<uint> LeadingZeroCount(Vector64<uint> value) => LeadingZeroCount(value);
public static Vector64<int> LeadingZeroCount(Vector64<int> value) => LeadingZeroCount(value);
public static Vector128<byte> LeadingZeroCount(Vector128<byte> value) => LeadingZeroCount(value);
public static Vector128<sbyte> LeadingZeroCount(Vector128<sbyte> value) => LeadingZeroCount(value);
public static Vector128<ushort> LeadingZeroCount(Vector128<ushort> value) => LeadingZeroCount(value);
public static Vector128<short> LeadingZeroCount(Vector128<short> value) => LeadingZeroCount(value);
public static Vector128<uint> LeadingZeroCount(Vector128<uint> value) => LeadingZeroCount(value);
public static Vector128<int> LeadingZeroCount(Vector128<int> value) => LeadingZeroCount(value);
/// <summary>
/// Vector max
/// Corresponds to vector forms of ARM64 SMAX, UMAX & FMAX
/// </summary>
public static Vector64<byte> Max(Vector64<byte> left, Vector64<byte> right) => Max(left, right);
public static Vector64<sbyte> Max(Vector64<sbyte> left, Vector64<sbyte> right) => Max(left, right);
public static Vector64<ushort> Max(Vector64<ushort> left, Vector64<ushort> right) => Max(left, right);
public static Vector64<short> Max(Vector64<short> left, Vector64<short> right) => Max(left, right);
public static Vector64<uint> Max(Vector64<uint> left, Vector64<uint> right) => Max(left, right);
public static Vector64<int> Max(Vector64<int> left, Vector64<int> right) => Max(left, right);
public static Vector64<float> Max(Vector64<float> left, Vector64<float> right) => Max(left, right);
public static Vector128<byte> Max(Vector128<byte> left, Vector128<byte> right) => Max(left, right);
public static Vector128<sbyte> Max(Vector128<sbyte> left, Vector128<sbyte> right) => Max(left, right);
public static Vector128<ushort> Max(Vector128<ushort> left, Vector128<ushort> right) => Max(left, right);
public static Vector128<short> Max(Vector128<short> left, Vector128<short> right) => Max(left, right);
public static Vector128<uint> Max(Vector128<uint> left, Vector128<uint> right) => Max(left, right);
public static Vector128<int> Max(Vector128<int> left, Vector128<int> right) => Max(left, right);
public static Vector128<float> Max(Vector128<float> left, Vector128<float> right) => Max(left, right);
public static Vector128<double> Max(Vector128<double> left, Vector128<double> right) => Max(left, right);
/// <summary>
/// Vector min
/// Corresponds to vector forms of ARM64 SMIN, UMIN & FMIN
/// </summary>
public static Vector64<byte> Min(Vector64<byte> left, Vector64<byte> right) => Min(left, right);
public static Vector64<sbyte> Min(Vector64<sbyte> left, Vector64<sbyte> right) => Min(left, right);
public static Vector64<ushort> Min(Vector64<ushort> left, Vector64<ushort> right) => Min(left, right);
public static Vector64<short> Min(Vector64<short> left, Vector64<short> right) => Min(left, right);
public static Vector64<uint> Min(Vector64<uint> left, Vector64<uint> right) => Min(left, right);
public static Vector64<int> Min(Vector64<int> left, Vector64<int> right) => Min(left, right);
public static Vector64<float> Min(Vector64<float> left, Vector64<float> right) => Min(left, right);
public static Vector128<byte> Min(Vector128<byte> left, Vector128<byte> right) => Min(left, right);
public static Vector128<sbyte> Min(Vector128<sbyte> left, Vector128<sbyte> right) => Min(left, right);
public static Vector128<ushort> Min(Vector128<ushort> left, Vector128<ushort> right) => Min(left, right);
public static Vector128<short> Min(Vector128<short> left, Vector128<short> right) => Min(left, right);
public static Vector128<uint> Min(Vector128<uint> left, Vector128<uint> right) => Min(left, right);
public static Vector128<int> Min(Vector128<int> left, Vector128<int> right) => Min(left, right);
public static Vector128<float> Min(Vector128<float> left, Vector128<float> right) => Min(left, right);
public static Vector128<double> Min(Vector128<double> left, Vector128<double> right) => Min(left, right);
/// TBD MOV, FMOV
/// <summary>
/// Vector multiply
///
/// For each element result[elem] = left[elem] * right[elem]
///
/// Corresponds to vector forms of ARM64 MUL & FMUL
/// </summary>
public static Vector64<byte> Multiply(Vector64<byte> left, Vector64<byte> right) => Multiply(left, right);
public static Vector64<sbyte> Multiply(Vector64<sbyte> left, Vector64<sbyte> right) => Multiply(left, right);
public static Vector64<ushort> Multiply(Vector64<ushort> left, Vector64<ushort> right) => Multiply(left, right);
public static Vector64<short> Multiply(Vector64<short> left, Vector64<short> right) => Multiply(left, right);
public static Vector64<uint> Multiply(Vector64<uint> left, Vector64<uint> right) => Multiply(left, right);
public static Vector64<int> Multiply(Vector64<int> left, Vector64<int> right) => Multiply(left, right);
public static Vector64<float> Multiply(Vector64<float> left, Vector64<float> right) => Multiply(left, right);
public static Vector128<byte> Multiply(Vector128<byte> left, Vector128<byte> right) => Multiply(left, right);
public static Vector128<sbyte> Multiply(Vector128<sbyte> left, Vector128<sbyte> right) => Multiply(left, right);
public static Vector128<ushort> Multiply(Vector128<ushort> left, Vector128<ushort> right) => Multiply(left, right);
public static Vector128<short> Multiply(Vector128<short> left, Vector128<short> right) => Multiply(left, right);
public static Vector128<uint> Multiply(Vector128<uint> left, Vector128<uint> right) => Multiply(left, right);
public static Vector128<int> Multiply(Vector128<int> left, Vector128<int> right) => Multiply(left, right);
public static Vector128<float> Multiply(Vector128<float> left, Vector128<float> right) => Multiply(left, right);
public static Vector128<double> Multiply(Vector128<double> left, Vector128<double> right) => Multiply(left, right);
/// <summary>
/// Vector negate
/// Corresponds to vector forms of ARM64 NEG & FNEG
/// </summary>
public static Vector64<sbyte> Negate(Vector64<sbyte> value) => Negate(value);
public static Vector64<short> Negate(Vector64<short> value) => Negate(value);
public static Vector64<int> Negate(Vector64<int> value) => Negate(value);
public static Vector64<float> Negate(Vector64<float> value) => Negate(value);
public static Vector128<sbyte> Negate(Vector128<sbyte> value) => Negate(value);
public static Vector128<short> Negate(Vector128<short> value) => Negate(value);
public static Vector128<int> Negate(Vector128<int> value) => Negate(value);
public static Vector128<long> Negate(Vector128<long> value) => Negate(value);
public static Vector128<float> Negate(Vector128<float> value) => Negate(value);
public static Vector128<double> Negate(Vector128<double> value) => Negate(value);
/// <summary>
/// Vector not
/// Corresponds to vector forms of ARM64 NOT
/// </summary>
public static Vector64<T> Not<T>(Vector64<T> value) where T : struct => Not(value);
public static Vector128<T> Not<T>(Vector128<T> value) where T : struct => Not(value);
/// <summary>
/// Vector or
/// Corresponds to vector forms of ARM64 ORR
/// </summary>
public static Vector64<T> Or<T>(Vector64<T> left, Vector64<T> right) where T : struct => Or(left, right);
public static Vector128<T> Or<T>(Vector128<T> left, Vector128<T> right) where T : struct => Or(left, right);
/// <summary>
/// Vector or not
/// Corresponds to vector forms of ARM64 ORN
/// </summary>
public static Vector64<T> OrNot<T>(Vector64<T> left, Vector64<T> right) where T : struct => OrNot(left, right);
public static Vector128<T> OrNot<T>(Vector128<T> left, Vector128<T> right) where T : struct => OrNot(left, right);
/// <summary>
/// Vector PopCount
/// Corresponds to vector forms of ARM64 CNT
/// </summary>
public static Vector64<byte> PopCount(Vector64<byte> value) => PopCount(value);
public static Vector64<sbyte> PopCount(Vector64<sbyte> value) => PopCount(value);
public static Vector128<byte> PopCount(Vector128<byte> value) => PopCount(value);
public static Vector128<sbyte> PopCount(Vector128<sbyte> value) => PopCount(value);
/// <summary>
/// SetVector* Fill vector elements by replicating element value
///
/// Corresponds to vector forms of ARM64 DUP (general), DUP (element 0), FMOV (vector, immediate)
/// </summary>
public static Vector64<T> SetAllVector64<T>(T value) where T : struct => SetAllVector64(value);
public static Vector128<T> SetAllVector128<T>(T value) where T : struct => SetAllVector128(value);
/// <summary>
/// Vector square root
/// Corresponds to vector forms of ARM64 FRSQRT
/// </summary>
public static Vector64<float> Sqrt(Vector64<float> value) => Sqrt(value);
public static Vector128<float> Sqrt(Vector128<float> value) => Sqrt(value);
public static Vector128<double> Sqrt(Vector128<double> value) => Sqrt(value);
/// <summary>
/// Vector subtract
/// Corresponds to vector forms of ARM64 SUB & FSUB
/// </summary>
public static Vector64<T> Subtract<T>(Vector64<T> left, Vector64<T> right) where T : struct => Subtract(left, right);
public static Vector128<T> Subtract<T>(Vector128<T> left, Vector128<T> right) where T : struct => Subtract(left, right);
/// <summary>
/// Vector exclusive or
/// Corresponds to vector forms of ARM64 EOR
/// </summary>
public static Vector64<T> Xor<T>(Vector64<T> left, Vector64<T> right) where T : struct => Xor(left, right);
public static Vector128<T> Xor<T>(Vector128<T> left, Vector128<T> right) where T : struct => Xor(left, right);
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataPagerFieldCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Web;
using System.Web.Resources;
using System.Web.Security;
using System.Web.UI;
namespace System.Web.UI.WebControls {
/// <summary>
/// Summary description for DataPagerFieldCollection
/// </summary>
public class DataPagerFieldCollection : StateManagedCollection {
private DataPager _dataPager;
private static readonly Type[] knownTypes = new Type[] {
typeof(NextPreviousPagerField),
typeof(NumericPagerField),
typeof(TemplatePagerField)
};
public event EventHandler FieldsChanged;
public DataPagerFieldCollection(DataPager dataPager) {
_dataPager = dataPager;
}
/// <devdoc>
/// <para>Gets a <see cref='System.Web.UI.WebControls.DataPagerField'/> at the specified index in the
/// collection.</para>
/// </devdoc>
[
Browsable(false)
]
public DataPagerField this[int index] {
get {
return ((IList)this)[index] as DataPagerField;
}
}
/// <devdoc>
/// <para>Appends a <see cref='System.Web.UI.WebControls.DataPagerField'/> to the collection.</para>
/// </devdoc>
public void Add(DataPagerField field) {
((IList)this).Add(field);
}
/// <devdoc>
/// <para>Provides a deep copy of the collection. Used mainly by design time dialogs to implement "cancel" rollback behavior.</para>
/// </devdoc>
public DataPagerFieldCollection CloneFields(DataPager pager) {
DataPagerFieldCollection fields = new DataPagerFieldCollection(pager);
foreach (DataPagerField field in this) {
fields.Add(field.CloneField());
}
return fields;
}
/// <devdoc>
/// <para>Returns whether a DataPagerField is a member of the collection.</para>
/// </devdoc>
public bool Contains(DataPagerField field) {
return ((IList)this).Contains(field);
}
/// <devdoc>
/// <para>Copies the contents of the entire collection into an <see cref='System.Array' qualify='true'/> appending at
/// the specified index of the <see cref='System.Array' qualify='true'/>.</para>
/// </devdoc>
public void CopyTo(DataPagerField[] array, int index) {
((IList)this).CopyTo(array, index);
return;
}
/// <devdoc>
/// <para>Creates a known type of DataPagerField.</para>
/// </devdoc>
protected override object CreateKnownType(int index) {
switch (index) {
case 0:
return new NextPreviousPagerField();
case 1:
return new NumericPagerField();
case 2:
return new TemplatePagerField();
default:
throw new ArgumentOutOfRangeException(AtlasWeb.PagerFieldCollection_InvalidTypeIndex);
}
}
/// <devdoc>
/// <para>Returns an ArrayList of known DataPagerField types.</para>
/// </devdoc>
protected override Type[] GetKnownTypes() {
return knownTypes;
}
/// <devdoc>
/// <para>Returns the index of the first occurrence of a value in a <see cref='System.Web.UI.WebControls.DataPagerField'/>.</para>
/// </devdoc>
public int IndexOf(DataPagerField field) {
return ((IList)this).IndexOf(field);
}
/// <devdoc>
/// <para>Inserts a <see cref='System.Web.UI.WebControls.DataPagerField'/> to the collection
/// at the specified index.</para>
/// </devdoc>
public void Insert(int index, DataPagerField field) {
((IList)this).Insert(index, field);
}
/// <devdoc>
/// Called when the Clear() method is complete.
/// </devdoc>
protected override void OnClearComplete() {
OnFieldsChanged();
}
/// <devdoc>
/// </devdoc>
void OnFieldChanged(object sender, EventArgs e) {
OnFieldsChanged();
}
/// <devdoc>
/// </devdoc>
void OnFieldsChanged() {
if (FieldsChanged != null) {
FieldsChanged(this, EventArgs.Empty);
}
}
/// <devdoc>
/// Called when the Insert() method is complete.
/// </devdoc>
protected override void OnInsertComplete(int index, object value) {
DataPagerField field = value as DataPagerField;
if (field != null) {
field.FieldChanged += new EventHandler(OnFieldChanged);
}
field.SetDataPager(_dataPager);
OnFieldsChanged();
}
/// <devdoc>
/// Called when the Remove() method is complete.
/// </devdoc>
protected override void OnRemoveComplete(int index, object value) {
DataPagerField field = value as DataPagerField;
if (field != null) {
field.FieldChanged -= new EventHandler(OnFieldChanged);
}
OnFieldsChanged();
}
/// <devdoc>
/// <para>Validates that an object is a HotSpot.</para>
/// </devdoc>
protected override void OnValidate(object o) {
base.OnValidate(o);
if (!(o is DataPagerField))
throw new ArgumentException(AtlasWeb.PagerFieldCollection_InvalidType);
}
/// <devdoc>
/// <para>Removes a <see cref='System.Web.UI.WebControls.DataPagerField'/> from the collection at the specified
/// index.</para>
/// </devdoc>
public void RemoveAt(int index) {
((IList)this).RemoveAt(index);
}
/// <devdoc>
/// <para>Removes the specified <see cref='System.Web.UI.WebControls.DataPagerField'/> from the collection.</para>
/// </devdoc>
public void Remove(DataPagerField field) {
((IList)this).Remove(field);
}
/// <devdoc>
/// <para>Marks a DataPagerField as dirty so that it will record its entire state into view state.</para>
/// </devdoc>
protected override void SetDirtyObject(object o) {
((DataPagerField)o).SetDirty();
}
}
}
| |
// <copyright file=BlobManager.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:58 PM</date>
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using HciLab.motionEAP.InterfacesAndDataModel.Data;
using HciLab.Utilities;
using HciLab.Utilities.Mathematics.Core;
using HciLab.Utilities.Mathematics.Geometry2D;
using motionEAPAdmin.Database;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace motionEAPAdmin.Backend
{
public class BlobManager
{
private static BlobManager m_Instance;
private static Bgra BLUE = new Bgra(255, 0, 0, 0);
private static Bgra RED = new Bgra(0, 0, 255, 0);
private static Bgra GREEN = new Bgra(0, 255, 0, 0);
private static bool m_LastWasCorrupted = false;
private int m_Id = 10;
private List<BlobObject> m_MasterBlob = new List<BlobObject>();
private BlobManager() { }
public List<BlobObject> MasterBlob
{
get { return m_MasterBlob; }
set { m_MasterBlob = value; }
}
public int Id
{
get { return m_Id; }
set { m_Id = value; }
}
public static BlobManager Instance
{
get
{
if (m_Instance == null)
{
m_Instance = new BlobManager();
}
return m_Instance;
}
}
/// <summary>
///
/// </summary>
/// <param name="pImage"></param>
/// <param name="pDetectRemoval"></param>
/// <param name="pMinArea"></param>
/// <param name="pValueThreshold"></param>
/// <returns></returns>
public static List<BlobBound> FindAllBlob(Image<Gray, Int32> pImage, bool pDetectRemoval, double pMinArea = 0.0, double pValueThreshold = 0.0)
{
List<BlobBound> retList = new List<BlobBound>();
//Arbitray factor to compensate biger value bandwith of new Image formate
Image<Bgra, Byte> outputImage = pImage.Convert<Bgra, Byte>();
outputImage._GammaCorrect(0.5);
#region using contour
//only RETR_TYPE.CV_RETR_CCOMP dose work with Int32
for (Contour<System.Drawing.Point> contours = pImage.FindContours(Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE, Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_CCOMP); contours != null; contours = contours.HNext)
{
Seq<System.Drawing.Point> convexHull = contours.GetConvexHull(ORIENTATION.CV_CLOCKWISE);
if (contours.BoundingRectangle.Width > 0 && contours.BoundingRectangle.Height > 0 && convexHull.Area > pMinArea)
{
//Approximiere Kontur durch ein Polygon
//using (MemStorage storage = new MemStorage()) //allocate storage for contour approximation
//Contour<Point> currentContour = contours.ApproxPoly(contours.Perimeter * 0.05, storage);
Polygon poly = new Polygon();
foreach (Point p in convexHull)
{
poly.Points.Add(new Vector2(p.X, p.Y));
}
Rectangle bounds = contours.BoundingRectangle;
double summedValues = 0;
int area = 0;
bool[,] mask = new bool[bounds.Width, bounds.Height];
Array.Clear(mask, 0, mask.Length);
for (int y = bounds.Y; y < bounds.Height + bounds.Y; y++)
{
for (int x = bounds.X; x < bounds.Width + bounds.X; x++)
{
if (pImage.Data[y, x, 0] > 0 && convexHull.InContour(new PointF(x, y)) > 0)
{
summedValues += pImage.Data[y, x, 0];
area++;
mask[x - bounds.X, y - bounds.Y] = true;
}
}
}
if (area > 0 && summedValues / area > pValueThreshold)
{
BlobBound bbound = new BlobBound(bounds, area, (int)summedValues, mask, poly);
retList.Add(bbound);
//outputImage.Draw(bbound.Points, GREEN, 1);
outputImage.Draw(bounds, BLUE, 1);
outputImage.Draw(convexHull, RED, 1);
}
}
}
#endregion
CvInvoke.cvShowImage(pDetectRemoval.ToString() + "-DepthChanges", outputImage.Ptr);
retList.Sort((a, b) => a.Area.CompareTo(b.Area));
retList.Reverse();
return retList;
}
/// <summary>
///
/// </summary>
/// <param name="openCVImg"></param>
/// <param name="masterBlobs"></param>
/// <param name="colorBS"></param>
/// <param name="mode"></param>
/// <returns></returns>
public static List<BlobObject> FindAllBlob(Image<Gray, Int32> openCVImg,
List<BlobObject> masterBlobs,
Image<Bgra, byte> colorBS,
bool mode)
{
List<BlobObject> retList = new List<BlobObject>();
try
{
Image<Gray, byte> gray_image = openCVImg.Convert<Gray, byte>();
List<BlobObject> newBlobs = new List<BlobObject>();
if (mode == false)
{
#region using cvBlob
Emgu.CV.Cvb.CvBlobs resultingBlobs = new Emgu.CV.Cvb.CvBlobs();
Emgu.CV.Cvb.CvBlobDetector bDetect = new Emgu.CV.Cvb.CvBlobDetector();
uint numWebcamBlobsFound = bDetect.Detect(gray_image, resultingBlobs);
using (MemStorage stor = new MemStorage())
{
foreach (Emgu.CV.Cvb.CvBlob targetBlob in resultingBlobs.Values)
{
if (targetBlob.Area > 200)
{
var contour = targetBlob.GetContour(stor);
MCvBox2D box = contour.GetMinAreaRect();
PointF[] boxCorner = UtilitiesImage.ToPercent(contour.GetMinAreaRect().GetVertices(), gray_image.Width, gray_image.Height);
PointF center = UtilitiesImage.ToPercent(contour.GetMinAreaRect().center, gray_image.Width, gray_image.Height);
RectangleF rect = UtilitiesImage.ToPercent(targetBlob.BoundingBox, gray_image.Width, gray_image.Height);
Image<Gray, byte> newCropImg = UtilitiesImage.CropImage(colorBS.Convert<Gray, byte>(), rect);
newBlobs.Add(new BlobObject(newCropImg, null, boxCorner, rect, center, 0, 0, 0 + ""));
//stor.Clear();
}
}
}
#endregion
}
else
{
#region using contour
using (MemStorage storage = new MemStorage())
{
//Find contours with no holes try CV_RETR_EXTERNAL to find holes
Contour<System.Drawing.Point> contours = gray_image.FindContours(
Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE,
Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_EXTERNAL,
storage);
for (int i = 0; contours != null; contours = contours.HNext)
{
i++;
//double area = contours.Area;
if (contours.Area > 200)
{
PointF[] boxCorner = UtilitiesImage.ToPercent(contours.GetMinAreaRect().GetVertices(), gray_image.Width, gray_image.Height);
PointF center = UtilitiesImage.ToPercent(contours.GetMinAreaRect().center, gray_image.Width, gray_image.Height);
RectangleF rect = UtilitiesImage.ToPercent(contours.BoundingRectangle, gray_image.Width, gray_image.Height);
Image<Bgra, byte> newCropImg = UtilitiesImage.CropImage(colorBS, rect);
newBlobs.Add(new BlobObject(newCropImg.Convert<Gray, byte>(), null, boxCorner, rect, center, 0, 0, 0 + ""));
}
}
}
#endregion
}
// read objects from database now
List<TrackableObject> objects = DatabaseManager.Instance.Objects.ToList();
if (objects.Count == 0)
{
foreach (BlobObject b in newBlobs)
{
retList.Add(new BlobObject(b.Image, null, b.CornerPoints, b.Rect, b.Center, 0, 0, 0 + ""));
}
}
else
{
#region
// size and position werden abgeglichen
List<Tuple<double, double, int, int>> trackInfo = new List<Tuple<double, double, int, int>>();
for (int newblob = 0; newblob < newBlobs.Count; newblob++)
{
for (int master = 0; master < masterBlobs.Count; master++)
{
double d = UtilitiesImage.Distance(newBlobs[newblob].Center, masterBlobs[master].Center);
double s = UtilitiesImage.DiffSize(newBlobs[newblob].Rect.Size, masterBlobs[master].Rect.Size);
trackInfo.Add(new Tuple<double, double, int, int>(d, s, master, newblob));
}
}
trackInfo.Sort((x, y) => x.Item1.CompareTo(y.Item1));
List<int> newItem = new List<int>();
if (!m_LastWasCorrupted)
{
while (trackInfo.Count != 0)
{
if (trackInfo[0].Item2 < 0.2)
{
int masterId = trackInfo[0].Item3;
int newId = trackInfo[0].Item4;
BlobObject newObject = new BlobObject(newBlobs[newId].Image, newBlobs[newId].DepthStructur, newBlobs[newId].CornerPoints, newBlobs[newId].Rect, newBlobs[newId].Center, masterBlobs[masterId].Hits, masterBlobs[masterId].Id, masterBlobs[masterId].Name);
retList.Add(newObject);
trackInfo.RemoveAll(item => item.Item3 == masterId);
trackInfo.RemoveAll(item => item.Item4 == newId);
newItem.Add(newId);
}
else
{
trackInfo.RemoveAt(0);
}
}
newItem.Sort();
//}
// check the images based on their features
for (int i = newBlobs.Count - 1; i >= 0; i--)
{
if (newItem.Count != 0 && i == newItem.Last())
{
newItem.RemoveAt(newItem.Count - 1);
}
else
{
// set the name according to the recognized object
string currentBlobId = RecognizeObject(newBlobs[i], objects);
newBlobs[i].Name = currentBlobId;
retList.Add(newBlobs[i]);
}
}
}
}
}
catch (CvException e)
{
Logger.Instance.Log(e.Message, Logger.LoggerState.ERROR);
return retList;
}
catch (Exception e)
{
Logger.Instance.Log(e.Message, Logger.LoggerState.ERROR);
//mark a flag that the last frame was corrupt
m_LastWasCorrupted = true;
}
#endregion
return retList;
}
/// <summary>
/// Find an object in a object list
/// </summary>
/// <param name="currentBlob"></param>
/// <param name="viBlobs"></param>
/// <returns>BlobID</returns>
public static string RecognizeObject(BlobObject currentBlob, List<TrackableObject> dbObjects)
{
bool isDetect = false;
string blobId = "not identified";
bool careAboutWorkflow = false;
if (WorkflowManager.Instance.LoadedWorkflow != null)
{
careAboutWorkflow = true;
}
if (dbObjects.Count != 0)
{
foreach (TrackableObject obj in dbObjects)
{
if (careAboutWorkflow)
{
// first check if object belongs to current workingstep
if (obj.Category == "" + WorkflowManager.Instance.CurrentWorkingStep.StepNumber)
{
// MFunk: Run this a couple of times to get more robust
int numRuns = 3;
for (int i = 0; i < numRuns; i++)
{
isDetect = UtilitiesImage.MatchIsSame(obj.EmguImage, currentBlob.Image);
if (isDetect)
{
break;
}
}
if (isDetect)
{
WorkflowManager.Instance.OnObjectRecognized(obj);
blobId = obj.Name;
break;
}
else
{
isDetect = UtilitiesImage.MatchIsSame(obj.EmguImage.Canny(10, 50).Convert<Gray, Int32>(), currentBlob.Image.Canny(10, 50).Convert<Gray, Int32>());
if (isDetect)
{
isDetect = true;
blobId = obj.Name;
WorkflowManager.Instance.OnObjectRecognized(obj);
break;
}
else
{
blobId = "not identified";
}
}
if (isDetect)
{
m_LastWasCorrupted = false;
}
}
}
else
{
// do not care about workflow
// MFunk: Run this a couple of times to get more robust
int numRuns = 3;
for (int i = 0; i < numRuns; i++)
{
isDetect = UtilitiesImage.MatchIsSame(obj.EmguImage, currentBlob.Image);
if (isDetect)
{
break;
}
}
if (isDetect)
{
WorkflowManager.Instance.OnObjectRecognized(obj);
blobId = obj.Name;
break;
}
else
{
isDetect = UtilitiesImage.MatchIsSame(obj.EmguImage.Canny(10, 50).Convert<Gray, Int32>(), currentBlob.Image.Canny(10, 50).Convert<Gray, Int32>());
if (isDetect)
{
isDetect = true;
blobId = obj.Name;
WorkflowManager.Instance.OnObjectRecognized(obj);
break;
}
else
{
blobId = "not identified";
}
}
}
}
}
if (isDetect)
{
m_LastWasCorrupted = false;
}
return blobId;
}
/// <summary>
/// Calculate the rotation of an object from image
/// </summary>
/// <param name="colorBS"></param>
/// <param name="currentBlob"></param>
/// <param name="viBlobs"></param>
/// <returns>angle degree</returns>
public static float GetRotation(Image<Bgra, byte> colorBS, BlobObject currentBlob, List<BlobObject> viBlobs)
{
Image<Bgra, byte> observedImage = UtilitiesImage.CropImage(colorBS, currentBlob.Rect);
//observedImage.Save("current.jpg");
float degree = 360;
if (viBlobs.Count == 0)
{
return degree;
}
else
{
VectorOfKeyPoint keypoints1;
VectorOfKeyPoint keypoints2;
Matrix<float> symMatches;
foreach (BlobObject viblob in viBlobs)
{
//viblob.Image.Save(viblob.Id + ".jpg");
bool isDetect = UtilitiesImage.MatchIsSame(viblob.Image, observedImage.Convert<Gray, byte>(), out keypoints1, out keypoints2, out symMatches);
if (isDetect)
{
degree = UtilitiesImage.GetRotationDiff(symMatches, keypoints1, keypoints2);
}
}
return degree;
}
}
}
}
| |
#region USINGZ
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using YAMLParser;
#endregion
namespace FauxMessages
{
public class SrvsFile
{
private string GUTS;
public string GeneratedDictHelper;
public bool HasHeader;
public string Name;
public string Namespace = "Messages";
public MsgsFile Request, Response;
public List<SingleType> Stuff = new List<SingleType>();
public string backhalf;
public string classname;
private List<string> def = new List<string>();
public string dimensions = "";
public string fronthalf;
//private string memoizedcontent;
private bool meta;
public string requestbackhalf;
public string requestfronthalf;
public string responsebackhalf;
public string resposonebackhalf;
public SrvsFile(string filename)
{
//read in srv file
string[] lines = File.ReadAllLines(filename);
string[] sp = filename.Replace(Program.inputdir, "").Replace(".srv", "").Split('\\');
//Parse The file name to get the classname;
classname = sp[sp.Length - 1];
//Parse for the Namespace
Namespace += "." + filename.Replace(Program.inputdir, "").Replace(".srv", "");
Namespace = Namespace.Replace("\\", ".").Replace("..", ".");
//split up Namespace and put it back together without the last part, aka. classname
string[] sp2 = Namespace.Split('.');
Namespace = "";
for (int i = 0; i < sp2.Length - 2; i++)
Namespace += sp2[i] + ".";
Namespace += sp2[sp2.Length - 2];
//THIS IS BAD!
//Name set to Namespace + classname
classname = classname.Replace("/", ".");
Name = Namespace.Replace("Messages", "").TrimStart('.') + "." + classname;
Name = Name.TrimStart('.');
classname = Name.Split('.').Length > 1 ? Name.Split('.')[1] : Name;
Namespace = Namespace.Trim('.');
//def is the list of all lines in the file
def = new List<string>();
int mid = 0;
bool found = false;
List<string> request = new List<string>(), response = new List<string>();
//Search through for the "---" separator between request and response
for (; mid < lines.Length; mid++)
{
lines[mid] = lines[mid].Replace("\"", "\\\"");
if (lines[mid].Contains('#'))
{
lines[mid] = lines[mid].Substring(0, lines[mid].IndexOf('#'));
}
lines[mid] = lines[mid].Trim();
if (lines[mid].Length == 0)
{
continue;
}
def.Add(lines[mid]);
if (lines[mid].Contains("---"))
{
found = true;
continue;
}
if (found)
response.Add(lines[mid]);
else
request.Add(lines[mid]);
}
//add lines aproprietly
Request = new MsgsFile(filename, true, request, "\t");
Response = new MsgsFile(filename, false, response, "\t");
}
public void Write(string outdir)
{
string[] chunks = Name.Split('.');
for (int i = 0; i < chunks.Length - 1; i++)
outdir += "\\" + chunks[i];
if (!Directory.Exists(outdir))
Directory.CreateDirectory(outdir);
string localcn = classname;
localcn = classname.Replace("Request", "").Replace("Response", "");
File.WriteAllText(outdir + "\\" + localcn + ".cs", ToString().Replace("FauxMessages", "Messages"));
Thread.Sleep(10);
}
public override string ToString()
{
if (requestfronthalf == null)
{
requestfronthalf = "";
requestbackhalf = "";
string[] lines = File.ReadAllLines("TemplateProject\\SrvPlaceHolder._cs");
int section = 0;
for (int i = 0; i < lines.Length; i++)
{
//read until you find public class request... do everything once.
//then, do it again response
if (lines[i].Contains("$$REQUESTDOLLADOLLABILLS"))
{
section++;
continue;
}
if (lines[i].Contains("namespace"))
{
//requestfronthalf +=
// "\nusing Messages.std_msgs;\nusing Messages.geometry_msgs;\nusing Messages.nav_msgs;\nusing String=Messages.std_msgs.String;\n\n"; //\nusing Messages.roscsharp;
requestfronthalf += "namespace " + Namespace + "\n";
continue;
}
if (lines[i].Contains("$$RESPONSEDOLLADOLLABILLS"))
{
section++;
continue;
}
switch (section)
{
case 0:
requestfronthalf += lines[i] + "\n";
break;
case 1:
requestbackhalf += lines[i] + "\n";
break;
case 2:
responsebackhalf += lines[i] + "\n";
break;
}
}
}
GUTS = requestfronthalf + Request.GetSrvHalf() + requestbackhalf + Response.GetSrvHalf() + "\n" +
responsebackhalf;
/***********************************/
/* CODE BLOCK DUMP */
/***********************************/
#region definitions
for (int i = 0; i < def.Count; i++)
{
while (def[i].Contains("\t"))
def[i] = def[i].Replace("\t", " ");
while (def[i].Contains("\n\n"))
def[i] = def[i].Replace("\n\n", "\n");
def[i] = def[i].Replace('\t', ' ');
while (def[i].Contains(" "))
def[i] = def[i].Replace(" ", " ");
def[i] = def[i].Replace(" = ", "=");
def[i] = def[i].Replace("\"", "\"\"");
}
StringBuilder md = new StringBuilder();
StringBuilder reqd = new StringBuilder();
StringBuilder resd = null;
foreach (string s in def)
{
if (s == "---")
{
//only put this string in md, because the subclass defs don't contain it
md.AppendLine(s);
//we've hit the middle... move from the request to the response by making responsedefinition not null.
resd = new StringBuilder();
continue;
}
//add every line to MessageDefinition for whole service
md.AppendLine(s);
//before we hit ---, add lines to request Definition. Otherwise, add them to response.
if (resd == null)
reqd.AppendLine(s);
else
resd.AppendLine(s);
}
string MessageDefinition = md.ToString().Trim();
string RequestDefinition = reqd.ToString().Trim();
string ResponseDefinition = resd.ToString().Trim();
#endregion
#region THE SERVICE
GUTS = GUTS.Replace("$WHATAMI", classname);
GUTS = GUTS.Replace("$MYSRVTYPE", "SrvTypes." + Namespace.Replace("Messages.", "") + "__" + classname);
GUTS = GUTS.Replace("$MYSERVICEDEFINITION", "@\"" + MessageDefinition + "\"");
#endregion
#region request
string RequestDict = Request.GenFields();
meta = Request.meta;
GUTS = GUTS.Replace("$REQUESTMYISMETA", meta.ToString().ToLower());
GUTS = GUTS.Replace("$REQUESTMYMSGTYPE", "MsgTypes." + Namespace.Replace("Messages.", "") + "__" + classname);
GUTS = GUTS.Replace("$REQUESTMYMESSAGEDEFINITION", "@\"" + RequestDefinition + "\"");
GUTS = GUTS.Replace("$REQUESTMYHASHEADER", Request.HasHeader.ToString().ToLower());
GUTS = GUTS.Replace("$REQUESTMYFIELDS", RequestDict.Length > 5 ? "{{" + RequestDict + "}}" : "()");
GUTS = GUTS.Replace("$REQUESTNULLCONSTBODY", "");
GUTS = GUTS.Replace("$REQUESTEXTRACONSTRUCTOR", "");
#endregion
#region response
string ResponseDict = Response.GenFields();
GUTS = GUTS.Replace("$RESPONSEMYISMETA", Response.meta.ToString().ToLower());
GUTS = GUTS.Replace("$RESPONSEMYMSGTYPE", "MsgTypes." + Namespace.Replace("Messages.", "") + "__" + classname);
GUTS = GUTS.Replace("$RESPONSEMYMESSAGEDEFINITION", "@\"" + ResponseDefinition + "\"");
GUTS = GUTS.Replace("$RESPONSEMYHASHEADER", Response.HasHeader.ToString().ToLower());
GUTS = GUTS.Replace("$RESPONSEMYFIELDS", ResponseDict.Length > 5 ? "{{" + ResponseDict + "}}" : "()");
GUTS = GUTS.Replace("$RESPONSENULLCONSTBODY", "");
GUTS = GUTS.Replace("$RESPONSEEXTRACONSTRUCTOR", "");
#endregion
/********END BLOCK**********/
return GUTS;
}
}
public class MsgsFile
{
private const string stfmat = "name: {0}\n\ttype: {1}\n\trostype: {2}\n\tisliteral: {3}\n\tisconst: {4}\n\tconstvalue: {5}\n\tisarray: {6}\n\tlength: {7}\n\tismeta: {8}\n";
public static Dictionary<string, List<string>> resolver;
private string GUTS;
public string GeneratedDictHelper;
public bool HasHeader;
public string Name;
public string Namespace = "Messages";
public List<SingleType> Stuff = new List<SingleType>();
public string backhalf;
public string classname;
private List<string> def = new List<string>();
public string dimensions = "";
public string fronthalf;
private string memoizedcontent;
public bool meta;
public ServiceMessageType serviceMessageType = ServiceMessageType.Not;
public void resolve(string package, ref string type)
{
if (resolver.Keys.Contains(type))
{
string same_pkg = null;
if (resolver[type].Count > 1)
{
for (int i = 0; i < resolver[type].Count; i++)
{
if (package.Length > 0 && resolver[type][i].Contains(package))
{
type = resolver[type][i];
return;
}
if (resolver[type][i].Contains(Namespace))
{
same_pkg = resolver[type][i];
}
}
if (same_pkg != null)
{
type = same_pkg;
return;
}
throw new Exception("Could not resolve " + type);
}
type = resolver[type][0];
}
}
public MsgsFile(string filename, bool isrequest, List<string> lines)
: this(filename, isrequest, lines, "")
{
}
public
MsgsFile(string filename, bool isrequest, List<string> lines, string extraindent)
{
if (resolver == null) resolver = new Dictionary<string, List<string>>();
serviceMessageType = isrequest ? ServiceMessageType.Request : ServiceMessageType.Response;
filename = filename.Replace(".srv", ".msg");
if (!filename.Contains(".msg"))
throw new Exception("" + filename + " IS NOT A VALID SRV FILE!");
string[] sp = filename.Replace(Program.inputdir, "").Replace(".msg", "").Split('\\');
classname = sp[sp.Length - 1];
Namespace += "." + filename.Replace(Program.inputdir, "").Replace(".msg", "");
Namespace = Namespace.Replace("\\", ".").Replace("..", ".");
string[] sp2 = Namespace.Split('.');
Namespace = "";
for (int i = 0; i < sp2.Length - 2; i++)
Namespace += sp2[i] + ".";
Namespace += sp2[sp2.Length - 2];
//THIS IS BAD!
classname = classname.Replace("/", ".");
Name = Namespace.Replace("Messages", "").TrimStart('.') + "." + classname;
Name = Name.TrimStart('.');
classname = Name.Split('.').Length > 1 ? Name.Split('.')[1] : Name;
classname += (isrequest ? "Request" : "Response");
Namespace = Namespace.Trim('.');
def = new List<string>();
for (int i = 0; i < lines.Count; i++)
{
if (lines[i].Trim().Length == 0)
{
continue;
}
def.Add(lines[i]);
if (Name.ToLower() == "string")
lines[i].Replace("String", "string");
SingleType test = KnownStuff.WhatItIs(this, lines[i], extraindent);
if (test != null)
Stuff.Add(test);
}
}
public MsgsFile(string filename)
: this(filename, "")
{
}
public MsgsFile(string filename, string extraindent)
{
if (resolver == null) resolver = new Dictionary<string, List<string>>();
if (!filename.Contains(".msg"))
throw new Exception("" + filename + " IS NOT A VALID MSG FILE!");
string[] sp = filename.Replace(Program.inputdir, "").Replace(".msg", "").Split('\\');
classname = sp[sp.Length - 1];
Namespace += "." + filename.Replace(Program.inputdir, "").Replace(".msg", "");
Namespace = Namespace.Replace("\\", ".").Replace("..", ".");
string[] sp2 = Namespace.Split('.');
Namespace = "";
for (int i = 0; i < sp2.Length - 2; i++)
Namespace += sp2[i] + ".";
Namespace += sp2[sp2.Length - 2];
//THIS IS BAD!
classname = classname.Replace("/", ".");
Name = Namespace.Replace("Messages", "").TrimStart('.') + "." + classname;
Name = Name.TrimStart('.');
classname = Name.Split('.').Length > 1 ? Name.Split('.')[1] : Name;
Namespace = Namespace.Trim('.');
if (!resolver.Keys.Contains(classname) && Namespace != "Messages.std_msgs")
resolver.Add(classname, new List<string>(){Namespace + "." + classname});
else if (Namespace != "Messages.std_msgs")
resolver[classname].Add(Namespace + "." + classname);
List<string> lines = new List<string>(File.ReadAllLines(filename));
lines = lines.Where(st => (!st.Contains('#') || st.Split('#')[0].Length != 0)).ToList();
for (int i = 0; i < lines.Count; i++)
lines[i] = lines[i].Split('#')[0].Trim();
//lines = lines.Where((st) => (st.Length > 0)).ToList();
lines.ForEach(s =>
{
if (s.Contains('#') && s.Split('#')[0].Length != 0)
s = s.Split('#')[0];
if (s.Contains('#'))
s = "";
});
lines = lines.Where(st => (st.Length > 0)).ToList();
def = new List<string>();
for (int i = 0; i < lines.Count; i++)
{
def.Add(lines[i]);
if (Name.ToLower() == "string")
lines[i].Replace("String", "string");
SingleType test = KnownStuff.WhatItIs(this, lines[i], extraindent);
if (test != null)
Stuff.Add(test);
}
}
public string GetSrvHalf()
{
string wholename = classname.Replace("Request", ".Request").Replace("Response", ".Response");
classname = classname.Contains("Request") ? "Request" : "Response";
if (memoizedcontent == null)
{
memoizedcontent = "";
for (int i = 0; i < Stuff.Count; i++)
{
SingleType thisthing = Stuff[i];
if (thisthing.Type == "Header")
{
HasHeader = true;
}
else if (classname == "String")
{
thisthing.input = thisthing.input.Replace("String", "string");
thisthing.Type = thisthing.Type.Replace("String", "string");
thisthing.output = thisthing.output.Replace("String", "string");
}
else if (classname == "Time")
{
thisthing.input = thisthing.input.Replace("Time", "TimeData");
thisthing.Type = thisthing.Type.Replace("Time", "TimeData");
thisthing.output = thisthing.output.Replace("Time", "TimeData");
}
else if (classname == "Duration")
{
thisthing.input = thisthing.input.Replace("Duration", "TimeData");
thisthing.Type = thisthing.Type.Replace("Duration", "TimeData");
thisthing.output = thisthing.output.Replace("Duration", "TimeData");
}
meta |= thisthing.meta;
memoizedcontent += "\t" + thisthing.output + "\n";
}
if (classname.ToLower() == "string")
{
memoizedcontent +=
"\n\n\t\t\t\t\tpublic String(string s){ data = s; }\n\t\t\t\t\tpublic String(){ data = \"\"; }\n\n";
}
else if (classname == "Time")
{
memoizedcontent +=
"\n\n\t\t\t\t\tpublic Time(uint s, uint ns) : this(new TimeData{ sec=s, nsec = ns}){}\n\t\t\t\t\tpublic Time(TimeData s){ data = s; }\n\t\t\t\t\tpublic Time() : this(0,0){}\n\n";
}
else if (classname == "Duration")
{
memoizedcontent +=
"\n\n\t\t\t\t\tpublic Duration(uint s, uint ns) : this(new TimeData{ sec=s, nsec = ns}){}\n\t\t\t\t\tpublic Duration(TimeData s){ data = s; }\n\t\t\t\t\tpublic Duration() : this(0,0){}\n\n";
}
while (memoizedcontent.Contains("DataData"))
memoizedcontent = memoizedcontent.Replace("DataData", "Data");
}
string ns = Namespace.Replace("Messages.", "");
if (ns == "Messages")
ns = "";
GeneratedDictHelper = "";
foreach (SingleType S in Stuff)
GeneratedDictHelper += MessageFieldHelper.Generate(S);
GUTS = fronthalf + memoizedcontent + "\n" +
backhalf;
return GUTS;
}
public string GenFields()
{
string ret = "\n\t\t\t\t";
for (int i = 0; i < Stuff.Count; i++)
{
Stuff[i].refinalize(this, Stuff[i].Type);
ret += ((i > 0) ? "}, \n\t\t\t\t{" : "") + MessageFieldHelper.Generate(Stuff[i]);
}
return ret;
}
public override string ToString()
{
//bool wasnull = false;
if (fronthalf == null)
{
//wasnull = true;
fronthalf = "";
backhalf = "";
string[] lines = File.ReadAllLines("TemplateProject\\PlaceHolder._cs");
bool hitvariablehole = false;
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains("$$DOLLADOLLABILLS"))
{
hitvariablehole = true;
continue;
}
if (lines[i].Contains("namespace"))
{
fronthalf +=
"using Messages.std_msgs;using String=Messages.std_msgs.String;\n\n"; //\nusing Messages.roscsharp;
fronthalf += "namespace " + Namespace + "\n";
continue;
}
if (!hitvariablehole)
fronthalf += lines[i] + "\n";
else
backhalf += lines[i] + "\n";
}
}
if (memoizedcontent == null)
{
memoizedcontent = "";
for (int i = 0; i < Stuff.Count; i++)
{
SingleType thisthing = Stuff[i];
if (thisthing.Type == "Header")
{
HasHeader = true;
}
else if (classname == "String")
{
thisthing.input = thisthing.input.Replace("String", "string");
thisthing.Type = thisthing.Type.Replace("String", "string");
thisthing.output = thisthing.output.Replace("String", "string");
}
else if (classname == "Time")
{
thisthing.input = thisthing.input.Replace("Time", "TimeData");
thisthing.Type = thisthing.Type.Replace("Time", "TimeData");
thisthing.output = thisthing.output.Replace("Time", "TimeData");
}
else if (classname == "Duration")
{
thisthing.input = thisthing.input.Replace("Duration", "TimeData");
thisthing.Type = thisthing.Type.Replace("Duration", "TimeData");
thisthing.output = thisthing.output.Replace("Duration", "TimeData");
}
meta |= thisthing.meta;
memoizedcontent += "\t" + thisthing.output + "\n";
}
string ns = Namespace.Replace("Messages.", "");
if (ns == "Messages")
ns = "";
while (memoizedcontent.Contains("DataData"))
memoizedcontent = memoizedcontent.Replace("DataData", "Data");
//if (GeneratedDictHelper == null)
// GeneratedDictHelper = TypeInfo.Generate(classname, ns, HasHeader, meta, def, Stuff);
GeneratedDictHelper = GenFields();
string GeneratedDeserializationCode = "";
//bool literal = false;
StringBuilder DEF = new StringBuilder();
foreach (string s in def)
DEF.AppendLine(s);
if (!meta && Stuff.Count == 1 && Stuff[0].Name == "data")
{
Console.WriteLine(DEF);
}
for (int i = 0; i < Stuff.Count; i++)
GeneratedDeserializationCode += GenerateDeserializationCode(Stuff[i]);
}
GUTS = (serviceMessageType != ServiceMessageType.Response ? fronthalf : "") + "\n" + memoizedcontent + "\n" +
(serviceMessageType != ServiceMessageType.Request ? backhalf : "");
if (classname.ToLower() == "string")
{
GUTS = GUTS.Replace("$NULLCONSTBODY", "if (data == null)\n\t\t\tdata = \"\";\n");
GUTS = GUTS.Replace("$EXTRACONSTRUCTOR", "\n\t\tpublic $WHATAMI(string d) : base($MYMSGTYPE, $MYMESSAGEDEFINITION, $MYHASHEADER, $MYISMETA, new Dictionary<string, MsgFieldInfo>$MYFIELDS)\n\t\t{\n\t\t\tdata = d;\n\t\t}\n");
}
else if (classname == "Time" || classname == "Duration")
{
GUTS = GUTS.Replace("$EXTRACONSTRUCTOR", "\n\t\tpublic $WHATAMI(TimeData d) : base($MYMSGTYPE, $MYMESSAGEDEFINITION, $MYHASHEADER, $MYISMETA, new Dictionary<string, MsgFieldInfo>$MYFIELDS)\n\t\t{\n\t\t\tdata = d;\n\t\t}\n");
}
GUTS = GUTS.Replace("$WHATAMI", classname);
GUTS = GUTS.Replace("$MYISMETA", meta.ToString().ToLower());
GUTS = GUTS.Replace("$MYMSGTYPE", "MsgTypes." + Namespace.Replace("Messages.", "") + "__" + classname);
for (int i = 0; i < def.Count; i++)
{
while (def[i].Contains("\t"))
def[i] = def[i].Replace("\t", " ");
while (def[i].Contains("\n\n"))
def[i] = def[i].Replace("\n\n", "\n");
def[i] = def[i].Replace('\t', ' ');
while (def[i].Contains(" "))
def[i] = def[i].Replace(" ", " ");
def[i] = def[i].Replace(" = ", "=");
}
GUTS = GUTS.Replace("$MYMESSAGEDEFINITION", "@\"" + def.Aggregate("", (current, d) => current + (d + "\n")).Trim('\n') + "\"");
GUTS = GUTS.Replace("$MYHASHEADER", HasHeader.ToString().ToLower());
GUTS = GUTS.Replace("$MYFIELDS", GeneratedDictHelper.Length > 5 ? "{{" + GeneratedDictHelper + "}}" : "()");
GUTS = GUTS.Replace("$NULLCONSTBODY", "");
GUTS = GUTS.Replace("$EXTRACONSTRUCTOR", "");
return GUTS;
}
public string GenerateDeserializationCode(SingleType st)
{
//Console.WriteLine(stfmat, st.Name, st.Type, st.rostype, st.IsLiteral, st.Const, st.ConstValue, st.IsArray, st.length, st.meta);
//if (!st.IsLiteral)
// Console.WriteLine(st.Name);
return "";
}
public void Write(string outdir)
{
string[] chunks = Name.Split('.');
for (int i = 0; i < chunks.Length - 1; i++)
outdir += "\\" + chunks[i];
if (!Directory.Exists(outdir))
Directory.CreateDirectory(outdir);
string localcn = classname;
if (serviceMessageType != ServiceMessageType.Not)
localcn = classname.Replace("Request", "").Replace("Response", "");
if (serviceMessageType == ServiceMessageType.Response)
File.AppendAllText(outdir + "\\" + localcn + ".cs", ToString().Replace("FauxMessages", "Messages"));
else
File.WriteAllText(outdir + "\\" + localcn + ".cs", ToString().Replace("FauxMessages", "Messages"));
Thread.Sleep(10);
}
}
public static class KnownStuff
{
private static char[] spliter = {' '};
public static Dictionary<string, string> KnownTypes = new Dictionary<string, string>
{
{"float64", "double"},
{"float32", "Single"},
{"uint64", "ulong"},
{"uint32", "uint"},
{"uint16", "ushort"},
{"uint8", "byte"},
{"int64", "long"},
{"int32", "int"},
{"int16", "short"},
{"int8", "sbyte"},
{"byte", "byte"},
{"bool", "bool"},
{"char", "char"},
{"time", "Time"},
{"string", "String"},
{"duration", "Duration"}
};
public static string GetConstTypesAffix(string type)
{
switch (type.ToLower())
{
case "decimal":
return "m";
//break;
case "single":
case "float":
return "f";
//break;
case "long":
return "l";
//break;
case "ulong":
return "ul";
//break;
case "uint":
return "ui";
//break;
default:
return "";
}
}
public static SingleType WhatItIs(MsgsFile parent, string s, string extraindent)
{
string[] pieces = s.Split('/');
string package = "";
if (pieces.Length > 1)
{
for (int i = 0; i < pieces.Length - 1; i++)
{
if (i > 0 && i < pieces.Length - 2)
package += "/";
package += pieces[i];
}
s = pieces[pieces.Length - 1];
}
return WhatItIs(parent, new SingleType(package, s, extraindent));
}
public static SingleType WhatItIs(MsgsFile parent, SingleType t)
{
foreach (KeyValuePair<string, string> test in KnownTypes)
{
if (t.Test(test))
{
t.rostype = t.Type;
return t.FinalizeType(parent, test);
}
}
return t.FinalizeType(parent, t.input.Split(spliter, StringSplitOptions.RemoveEmptyEntries), false);
}
}
public class SingleType
{
public bool Const;
public string ConstValue = "";
public bool IsArray;
public bool IsLiteral;
public string Name;
public string Type;
private string[] backup;
public string input;
public string length = "";
public string lowestindent = "\t\t";
public bool meta;
public string output;
public string rostype = "";
public string Package;
public SingleType(string s)
: this("", s, "")
{
}
public SingleType(string package, string s, string extraindent)
{
Package = package;
lowestindent += extraindent;
if (s.Contains('[') && s.Contains(']'))
{
string front = "";
string back = "";
string[] parts = s.Split('[');
front = parts[0];
parts = parts[1].Split(']');
length = parts[0];
back = parts[1];
IsArray = true;
s = front + back;
}
input = s;
}
public bool Test(KeyValuePair<string, string> candidate)
{
return (input.Split(' ')[0].ToLower().Equals(candidate.Key));
}
public SingleType FinalizeType(MsgsFile parent, KeyValuePair<string, string> csharptype)
{
string[] PARTS = input.Split(' ');
rostype = PARTS[0];
if (!KnownStuff.KnownTypes.ContainsKey(rostype))
meta = true;
PARTS[0] = csharptype.Value;
return FinalizeType(parent, PARTS, true);
}
public SingleType FinalizeType(MsgsFile parent, string[] s, bool isliteral)
{
backup = new string[s.Length];
Array.Copy(s, backup, s.Length);
bool isconst = false;
IsLiteral = isliteral;
string type = s[0];
string name = s[1];
string otherstuff = "";
if (name.Contains('='))
{
string[] parts = name.Split('=');
isconst = true;
name = parts[0];
otherstuff = " = " + parts[1];
}
for (int i = 2; i < s.Length; i++)
otherstuff += " " + s[i];
if (otherstuff.Contains('=')) isconst = true;
parent.resolve(Package, ref type);
if (!IsArray)
{
if (otherstuff.Contains('=') && type.Equals("string", StringComparison.CurrentCultureIgnoreCase))
{
otherstuff = otherstuff.Replace("\\", "\\\\");
otherstuff = otherstuff.Replace("\"", "\\\"");
string[] split = otherstuff.Split('=');
otherstuff = split[0] + " = " + split[1].Trim() + "";
}
if (otherstuff.Contains('=') && type == "bool")
{
otherstuff = otherstuff.Replace("0", "false").Replace("1", "true");
}
if (otherstuff.Contains('=') && type == "byte")
{
otherstuff = otherstuff.Replace("-1", "255");
}
Const = isconst;
bool wantsconstructor = false;
if (otherstuff.Contains("="))
{
string[] chunks = otherstuff.Split('=');
ConstValue = chunks[chunks.Length - 1].Trim();
if (type.Equals("string", StringComparison.InvariantCultureIgnoreCase))
{
otherstuff = chunks[0] + " = new String(\"" + chunks[1].Trim() + "\")";
}
}
string prefix = "", suffix = "";
if (isconst)
{
if (!type.Equals("string", StringComparison.InvariantCultureIgnoreCase))
{
prefix = "const ";
}
}
if (otherstuff.Contains('='))
if (wantsconstructor)
if (type == "string")
suffix = " = \"\"";
else
suffix = " = new " + type + "()";
else
suffix = KnownStuff.GetConstTypesAffix(type);
output = lowestindent + "public " + prefix + type + " " + name + otherstuff + suffix + ";";
}
else
{
if (length.Length > 0)
IsLiteral = type != "string";
if (otherstuff.Contains('='))
{
string[] split = otherstuff.Split('=');
otherstuff = split[0] + " = (" + type + ")" + split[1];
}
if (length.Length > 0)
output = lowestindent + "public " + type + "[] " + name + otherstuff + " = new " + type + "[" + length + "];";
else
output = lowestindent + "public " + "" + type + "[] " + name + otherstuff + ";";
}
Type = type;
if (!KnownStuff.KnownTypes.ContainsKey(rostype))
meta = true;
Name = name.Length == 0 ? otherstuff.Trim() : name;
if (Name.Contains('='))
{
Name = Name.Substring(0, Name.IndexOf("=")).Trim();
}
return this;
}
public void refinalize(MsgsFile parent, string REALTYPE)
{
bool isconst = false;
string type = REALTYPE;
string name = backup[1];
string otherstuff = "";
if (name.Contains('='))
{
string[] parts = name.Split('=');
isconst = true;
name = parts[0];
otherstuff = " = " + parts[1];
}
for (int i = 2; i < backup.Length; i++)
otherstuff += " " + backup[i];
if (otherstuff.Contains('=')) isconst = true;
parent.resolve(Package, ref type);
if (!IsArray)
{
if (otherstuff.Contains('=') && type.Equals("string", StringComparison.CurrentCultureIgnoreCase))
{
otherstuff = otherstuff.Replace("\\", "\\\\");
otherstuff = otherstuff.Replace("\"", "\\\"");
string[] split = otherstuff.Split('=');
otherstuff = split[0] + " = \"" + split[1].Trim() + "\"";
}
if (otherstuff.Contains('=') && type == "bool")
{
otherstuff = otherstuff.Replace("0", "false").Replace("1", "true");
}
if (otherstuff.Contains('=') && type == "byte")
{
otherstuff = otherstuff.Replace("-1", "255");
}
Const = isconst;
bool wantsconstructor = false;
if (otherstuff.Contains("="))
{
string[] chunks = otherstuff.Split('=');
ConstValue = chunks[chunks.Length - 1].Trim();
if (type.Equals("string", StringComparison.InvariantCultureIgnoreCase))
{
otherstuff = chunks[0] + " = new String(\"" + chunks[1].Trim().Replace("\"","") + "\")";
}
}
else if (!type.Equals("String"))
{
wantsconstructor = true;
}
string prefix = "",suffix="";
if (isconst)
{
if (!type.Equals("string", StringComparison.InvariantCultureIgnoreCase))
{
prefix = "const ";
}
}
if (otherstuff.Contains('='))
if (wantsconstructor)
if (type == "string")
suffix = " = \"\"";
else
suffix = " = new " + type + "()";
else
suffix = KnownStuff.GetConstTypesAffix(type);
output = lowestindent + "public " + prefix + type + " " + name + otherstuff + suffix + ";";
}
else
{
if (length.Length != 0)
IsLiteral = type != "string";
if (otherstuff.Contains('='))
{
string[] split = otherstuff.Split('=');
otherstuff = split[0] + " = (" + type + ")" + split[1];
}
if (length.Length != 0)
output = lowestindent + "public " + type + "[] " + name + otherstuff + " = new " + type + "[" + length + "];";
else
output = lowestindent + "public " + "" + type + "[] " + name + otherstuff + ";";
}
Type = type;
if (!KnownStuff.KnownTypes.ContainsKey(rostype))
meta = true;
Name = name.Length == 0 ? otherstuff.Split('=')[0].Trim() : name;
}
}
public static class MessageFieldHelper
{
public static string Generate(SingleType members)
{
string mt = "MsgTypes.Unknown";
if (members.meta)
{
string t = members.Type.Replace("Messages.", "");
if (!t.Contains('.'))
t = "std_msgs." + t;
mt = "MsgTypes."+t.Replace(".", "__");
if (mt.Contains("ColorRGBA"))
Console.WriteLine(mt);
}
return String.Format
("\"{0}\", new MsgFieldInfo(\"{0}\", {1}, {2}, {3}, \"{4}\", {5}, \"{6}\", {7}, {8})",
members.Name,
members.IsLiteral.ToString().ToLower(),
("typeof(" + members.Type + ")"),
members.Const.ToString().ToLower(),
members.ConstValue.TrimStart('"').TrimEnd('"'),
//members.Type.Equals("string", StringComparison.InvariantCultureIgnoreCase) ? ("new String("+members.ConstValue+")") : ("\""+members.ConstValue+"\""),
members.IsArray.ToString().ToLower(),
members.length,
//FIX MEEEEEEEE
members.meta.ToString().ToLower(),
mt);
}
}
public class MsgFieldInfo
{
public string ConstVal;
public bool IsArray;
public bool IsConst;
public bool IsLiteral;
public bool IsMetaType;
public int Length = -1;
public string Name;
public Type Type;
public MsgTypes message_type;
[DebuggerStepThrough]
public MsgFieldInfo(string name, bool isliteral, Type type, bool isconst, string constval, bool isarray,
string lengths, bool meta, MsgTypes mt)
{
Name = name;
IsArray = isarray;
Type = type;
IsLiteral = isliteral;
IsMetaType = meta;
IsConst = isconst;
ConstVal = constval;
if (lengths == null) return;
if (lengths.Length > 0)
{
Length = int.Parse(lengths);
}
message_type = mt;
}
}
public enum ServiceMessageType
{
Not,
Request,
Response
}
}
| |
#region License
// The MIT License
//
// Copyright (c) 2006-2008 DevDefined Limited.
//
// 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.IO;
using System.Net;
//using DevDefined.OAuth.Provider;
namespace DevDefined.OAuth.Framework
{
public static class Error
{
public static Exception MissingRequiredOAuthParameter(IOAuthContext context, string parameterName)
{
var exception = new OAuthException(context, OAuthProblems.ParameterAbset,
string.Format("Missing required parameter : {0}", parameterName));
exception.Report.ParametersAbsent.Add(parameterName);
return exception;
}
public static Exception OAuthAuthenticationFailure(string errorMessage)
{
return new Exception(string.Format("OAuth authentication failed, message was: {0}", errorMessage));
}
public static Exception TokenCanNoLongerBeUsed(string token)
{
return new Exception(string.Format("Token \"{0}\" is no longer valid", token));
}
public static Exception FailedToParseResponse(string parameters)
{
return new Exception(string.Format("Failed to parse response string \"{0}\"", parameters));
}
public static Exception UnknownSignatureMethod(string signatureMethod)
{
return new Exception(string.Format("Unknown signature method \"{0}\"", signatureMethod));
}
public static Exception ForRsaSha1SignatureMethodYouMustSupplyAssymetricKeyParameter()
{
return
new Exception(
"For the RSASSA-PKCS1-v1_5 signature method you must use the constructor which takes an additional AssymetricAlgorithm \"key\" parameter");
}
public static Exception RequestFailed(WebException innerException)
{
var response = innerException.Response as HttpWebResponse;
if (response != null)
{
using (var reader = new StreamReader(innerException.Response.GetResponseStream()))
{
string body = reader.ReadToEnd();
return
new Exception(
string.Format(
"Request for uri: {0} failed.\r\nstatus code: {1}\r\nheaders: {2}\r\nbody:\r\n{3}",
response.ResponseUri, response.StatusCode, response.Headers, body), innerException);
}
}
return innerException;
}
public static Exception EmptyConsumerKey()
{
throw new Exception("Consumer key is null or empty");
}
public static Exception RequestMethodHasNotBeenAssigned(string parameter)
{
return new Exception(string.Format("The RequestMethod parameter \"{0}\" is null or empty.", parameter));
}
public static Exception FailedToValidateSignature(IOAuthContext context)
{
return new OAuthException(context, OAuthProblems.SignatureInvalid, "Failed to validate signature");
}
public static Exception UnknownConsumerKey(IOAuthContext context)
{
return new OAuthException(context, OAuthProblems.ConsumerKeyUnknown,
string.Format("Unknown Consumer (Realm: {0}, Key: {1})", context.Realm,
context.ConsumerKey));
}
public static Exception AlgorithmPropertyNotSetOnSigningContext()
{
return
new Exception(
"Algorithm Property must be set on SingingContext when using an Assymetric encryption method such as RSA-SHA1");
}
public static Exception SuppliedTokenWasNotIssuedToThisConsumer(string expectedConsumerKey,
string actualConsumerKey)
{
return
new Exception(
string.Format("Supplied token was not issued to this consumer, expected key: {0}, actual key: {1}",
expectedConsumerKey, actualConsumerKey));
}
/*public static Exception F(AccessOutcome outcome)
{
Uri uri = outcome.Context.GenerateUri();
if (string.IsNullOrEmpty(outcome.AdditionalInfo))
{
return new AccessDeniedException(outcome, string.Format("Access to resource \"{0}\" was denied", uri));
}
return new AccessDeniedException(outcome,
string.Format("Access to resource: {0} was denied, additional info: {1}",
uri, outcome.AdditionalInfo));
}*/
public static Exception ConsumerHasNotBeenGrantedAccessYet(IOAuthContext context)
{
return new OAuthException(context, OAuthProblems.PermissionUnknown,
"The decision to give access to the consumer has yet to be made, please try again later.");
}
public static Exception ConsumerHasBeenDeniedAccess(IOAuthContext context)
{
return new OAuthException(context, OAuthProblems.PermissionDenied,
"The consumer was denied access to this resource.");
}
public static Exception CantBuildProblemReportWhenProblemEmpty()
{
return new Exception("Can't build problem report when \"Problem\" property is null or empty");
}
public static Exception NonceHasAlreadyBeenUsed(IOAuthContext context)
{
return new OAuthException(context, OAuthProblems.NonceUsed,
string.Format("The nonce value \"{0}\" has already been used", context.Nonce));
}
public static Exception ThisConsumerRequestHasAlreadyBeenSigned()
{
return new Exception("The consumer request for consumer \"{0}\" has already been signed");
}
public static Exception CallbackWasNotConfirmed()
{
return new Exception("Callback was not confirmed");
}
public static Exception RejectedRequiredOAuthParameter(IOAuthContext context, string parameter)
{
return new OAuthException(context, OAuthProblems.ParameterRejected, string.Format("The parameter \"{0}\" was rejected", parameter));
}
public static Exception UnknownToken(IOAuthContext context, string token)
{
return new OAuthException(context, OAuthProblems.TokenRejected, string.Format("Unknown or previously rejected token \"{0}\"", token));
}
public static Exception UnknownToken(IOAuthContext context, string token, Exception exception)
{
return new OAuthException(context, OAuthProblems.TokenRejected, string.Format("Unknown or previously rejected token \"{0}\"", token), exception);
}
public static Exception RequestForTokenMustNotIncludeTokenInContext(IOAuthContext context)
{
throw new OAuthException(context, OAuthProblems.ParameterRejected, "When obtaining a request token, you must not supply the oauth_token parameter");
}
public static Exception IfModifiedSinceHeaderOutOfRange(DateTime ifModifiedSince)
{
return new ArgumentOutOfRangeException("ifModifiedSince", string.Format("Supplied value of If-Modified-Since header is too small: {0}", ifModifiedSince.ToString("s")));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
namespace FlatRedBall.Math
{
#region XML Docs
/// <summary>
/// A list of IAttachables which is by default two-way.
/// </summary>
/// <typeparam name="T">Type of the list which is of IAttachable.</typeparam>
#endregion
public class AttachableList<T> : IAttachableRemovable, INotifyCollectionChanged, IList, IList<T> where T : IAttachable // Don't limit T to be a class because this creates bad IL. This is a bug in .NET 2.0
{
#region Fields
string mName;
// made internal for performance
// May 27, 2012
// A user asked me
// why the AttachableList
// class doesn't inherit from
// IList. The reason is because
// if we want the AttachableList to
// have two-way functionality then we
// need custom code in Add and Remove (and
// a few other methods). If AttachableList
// inherited from List, then these methods that
// need custom logic would have to be "new"-ed because
// they are not marked as "virtual" in List. This means
// that if the AttachableList were casted to an IList, it
// would lose its two-way functionality. We don't want that,
// so instead we inherit from IList so that the Add/Remove methods
// work properly regardless of the cast of AttachableList.
internal List<T> mInternalList;
internal IList mInternalListAsIList;
#endregion
#region Properties
#region XML Docs
/// <summary>
/// The number of elements contained in the list.
/// </summary>
#endregion
public int Count
{
get { return mInternalList.Count; }
}
#region XML Docs
/// <summary>
/// Gets and sets the name of this instance.
/// </summary>
#endregion
public string Name
{
get { return mName; }
set { mName = value; }
}
#endregion
#region Methods
#region Constructor
#region XML Docs
/// <summary>
/// Creates a new AttachableList.
/// </summary>
#endregion
public AttachableList()
{
mInternalList = new List<T>();
mInternalListAsIList = mInternalList;
}
#region XML Docs
/// <summary>
/// Creates a new AttachableList with the argument capacity.
/// </summary>
/// <param name="capacity">The initial capacity of the new AttachableList.</param>
#endregion
public AttachableList(int capacity)
{
mInternalList = new List<T>(capacity);
mInternalListAsIList = mInternalList;
}
#endregion
#region Public Static Methods
#region XML Docs
/// <summary>
/// Returns the top parents in the argument AttachableList
/// </summary>
/// <typeparam name="OutType">The type of object in the returned list.</typeparam>
/// <typeparam name="InType">Tye type of object in the argument list</typeparam>
/// <param name="poa">The list to search through.</param>
/// <returns>List of T's that are the top parents of the objects in the argument AttachableList.</returns>
#endregion
public static AttachableList<OutType> GetTopParents<OutType,InType>(AttachableList<InType> poa)
where OutType : PositionedObject
where InType : OutType, IAttachable
{
AttachableList<OutType> oldestParentsOneWay = new AttachableList<OutType>();
foreach (InType po in poa)
{
oldestParentsOneWay.AddUniqueOneWay(po.TopParent as OutType);
}
return oldestParentsOneWay;
}
#endregion
#region Public Methods
#region Add methods
#region XML Docs
/// <summary>
/// Adds the argument to the AttachableList and creates a two-way relationship.
/// </summary>
/// <param name="attachable">The IAttachable to add.</param>
#endregion
public void Add(T attachable)
{
#if DEBUG
if (mInternalList.Contains(attachable))
{
throw new InvalidOperationException("Can't add the following object twice: " + attachable.Name);
}
#endif
if (attachable == null)
return;
// January 4, 2012
// Victor Chelaru
// I think we can remove this for performance reasons...but I don't want
// to until I have a big game I can test this on.
// Update September 9, 2012
// Removing now and will be testing on Baron etc
//if (attachable.ListsBelongingTo.Contains(this) == false)
attachable.ListsBelongingTo.Add(this);
int countBefore = mInternalList.Count;
mInternalList.Add(attachable);
if (this.CollectionChanged != null)
{
// We put the index for Silverlight - but I don't want to do indexof for performance reasons so 0 it is
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, attachable, countBefore));
}
}
public void AddRange(IEnumerable<T> collection)
{
foreach (T t in collection)
Add(t);
}
#region XML Docs
/// <summary>
/// Adds all IAttachables contained in the argument AttachableList to this AttachableList and creates two
/// way relationships.
/// </summary>
/// <param name="listToAdd"></param>
#endregion
public void AddRange(AttachableList<T> listToAdd)
{
for (int i = 0; i < listToAdd.Count; i++)
{
Add(listToAdd[i]);
}
}
#region XML Docs
/// <summary>
/// Adds the argument attachable to this without creating a two-way relationship.
/// </summary>
/// <param name="attachable">The IAttachable to add to this.</param>
#endregion
public void AddOneWay(T attachable)
{
if (attachable == null) return;
mInternalList.Add(attachable);
if (this.CollectionChanged != null)
{
// We put the index for Silverlight - but I don't want to do indexof for performance reasons so 0 it is
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, attachable, 0));
}
}
#region XML Docs
/// <summary>
/// Adds all IAttachables contained in the argument AttachableList to this
/// without creating two-way relationships.
/// </summary>
/// <param name="listToAdd">The list of IAttachables to add.</param>
#endregion
public void AddRangeOneWay(AttachableList<T> listToAdd)
{
for (int i = 0; i < listToAdd.Count; i++)
{
mInternalList.Add(listToAdd[i]);
if (this.CollectionChanged != null)
{
// We put the index for Silverlight - but I don't want to do indexof for performance reasons so 0 it is
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, listToAdd[i], i));
}
}
}
#region XML Docs
/// <summary>
/// Adds a new IAttachable if it is not already in the list.
/// </summary>
/// <param name="attachable">The IAttachable to add.</param>
/// <returns>Index where the IAttachable was added. -1 is returned if the list already contains the argument attachable</returns>
#endregion
public void AddUnique(T attachable)
{
if (this.Contains(attachable))
return;
else
Add(attachable);
}
#region XML Docs
/// <summary>
/// Adds the argument IAttachable to this and creates a two-way relationship if
/// this does not already contain the IAttachable.
/// </summary>
/// <param name="attachable">The IAttachable to add.</param>
#endregion
public void AddUniqueOneWay(T attachable)
{
if (this.Contains(attachable))
return;
else
AddOneWay(attachable);
}
#endregion
/*
I don't know if this method is needed or not - it may provide some speed improvements, but I'm
* going to put it off for some more sure-fire speed improvemens.
public void ChangeIndexOfObject(int oldIndex, int newIndex)
{
if (oldIndex > newIndex)
{
// Moving the object down in the list (so it comes earlier)
T oldObject = this[oldIndex];
for (int i = oldIndex; i > newIndex; i--)
{
this[i] = this[i - 1];
}
this[newIndex] = oldObject;
}
else if (newIndex > oldIndex)
{
// Moving the object up in the list (so it comes later)
T oldObject = this[oldIndex];
for (int i = oldIndex; i < newIndex; i++)
{
}
}
}
*/
#region XML Docs
/// <summary>
/// Removes all IAttachables contained in this and eliminates all
/// two-way relationships.
/// </summary>
#endregion
public void Clear()
{
List<T> removed = null;
if (this.CollectionChanged != null)
{
removed = new List<T>();
removed.AddRange(mInternalList);
}
for (int i = 0; i < mInternalList.Count; i++)
{
if (mInternalList[i].ListsBelongingTo.Contains(this))
mInternalList[i].ListsBelongingTo.Remove(this);
}
mInternalList.Clear();
if (this.CollectionChanged != null)
{
// We put the index for Silverlight - but I don't want to do indexof for performance reasons so 0 it is
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed, 0));
}
}
#region XML Docs
/// <summary>
/// Returns whether this contains the argument IAttachable.
/// </summary>
/// <remarks>
/// If the argument is part of this instance and the two share a
/// two-way relationship then this method is able to use this two-way
/// relationship to speed up the method call.
/// </remarks>
/// <param name="attachable">The argument IAttachable to search for.</param>
/// <returns>Whether the argument attachable is contained in this list.</returns>
#endregion
public bool Contains(T attachable)
{
return (attachable != null &&
(attachable.ListsBelongingTo.Contains(this) || mInternalList.Contains(attachable)));
}
#region XML Docs
/// <summary>
/// Returns the IAttachable with name matching the argument.
/// </summary>
/// <remarks>This method performs a case-sensitive search.</remarks>
/// <param name="nameToSearchFor">The name to match when searching.</param>
/// <returns>The IAttachable with matching name or null if none are found.</returns>
#endregion
public T FindByName(string nameToSearchFor)
{
for (int i = 0; i < Count; i++)
if ((this[i]).Name == nameToSearchFor)
return this[i];
return default(T);
}
#region XML Docs
/// <summary>
/// Returns the first IAttachable with a name containing the argument string.
/// </summary>
/// <remarks>This method returns any IAttachable that has a name that contains the argument.
/// For example, an object with the name "MySprite" would return if the argument was "Sprite".</remarks>
/// <param name="stringToSearchFor">The string to check IAttachables for.</param>
/// <returns>The IAttachable with a name containing the argument string or null if none are found.</returns>
#endregion
public T FindWithNameContaining(string stringToSearchFor)
{
for (int i = 0; i < this.Count; i++)
{
T t = this[i];
if (t.Name.Contains(stringToSearchFor))
return t;
}
return default(T);
}
#region XML Docs
/// <summary>
/// Returns the first IAttachable with a name containing the argument string, case insensitive.
/// </summary>
/// <remarks>This method returns any IAttachable that has a name that contains the argument.
/// For example, an object with the name "MySprite" would return if the argument was "Sprite".</remarks>
/// <param name="stringToSearchFor">The string to check IAttachables for.</param>
/// <returns>The IAttachable with a name containing the argument string or null if none are found.</returns>
#endregion
public T FindWithNameContainingCaseInsensitive(string stringToSearchFor)
{
string name;
for (int i = 0; i < this.Count; i++)
{
T t = this[i];
name = t.Name.ToLower();
if (name.Contains(stringToSearchFor.ToLower()))
return t;
}
return default(T);
}
public AttachableList<T> FindAllWithNameContaining(string stringToSearchFor)
{
AttachableList<T> listToReturn = new AttachableList<T>();
for (int i = 0; i < this.Count; i++)
{
T t = this[i];
if (t.Name.Contains(stringToSearchFor))
{
listToReturn.Add(t);
}
}
return listToReturn;
}
#region XML Docs
/// <summary>
/// Inserts the argument IAttachable at the argument index and creates a
/// two-way relationship.
/// </summary>
/// <param name="index">The index to insert at.</param>
/// <param name="attachable">The IAttachable to insert.</param>
#endregion
public void Insert(int index, T attachable)
{
if (attachable == null)
return;
if (attachable.ListsBelongingTo.Contains(this) == false)
attachable.ListsBelongingTo.Add(this);
mInternalList.Insert(index, attachable);
if (this.CollectionChanged != null)
{
// We put the index for Silverlight - but I don't want to do indexof for performance reasons so 0 it is
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, attachable, 0));
}
}
#region XML Docs
/// <summary>
/// Inserts the argument IAttachable at the argument index but does not create
/// a two-way relationship.
/// </summary>
/// <param name="index">The index to insert at.</param>
/// <param name="attachable">The IAttachable to insert.</param>
#endregion
public void InsertOneWay(int index, T attachable)
{
mInternalList.Insert(index, attachable);
if (this.CollectionChanged != null)
{
// We put the index for Silverlight - but I don't want to do indexof for performance reasons so 0 it is
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, attachable, 0));
}
}
#region XML Docs
/// <summary>
/// Breaks all two-way relationships between this and all contained
/// IAttachables.
/// </summary>
/// <remarks>
/// This will still contain the same number of IAttachables before and
/// after the call.
/// </remarks>
#endregion
public void MakeOneWay()
{
for (int i = 0; i < this.Count; i++)
{
IAttachable ia = this[i];
if (ia.ListsBelongingTo.Contains(this))
ia.ListsBelongingTo.Remove(this);
}
}
#region XML Docs
/// <summary>
/// Makes the relationship between all contained IAttachables and this a two way relationship.
/// </summary>
/// <remarks>
/// If an IAttachable is added (through the Add method), the relationship is already a
/// two-way relationship. IAttachables which already have two-way relationships will not be affected
/// by this call. IAttachables that have been added through the AddOneWay call or added
/// through a call that returns a one-way array will be modified so that they hold a reference to
/// this instance in their ListsBelongingTo field. One-way relationships are often created in
/// FRB methods which return AttachableLists.
/// </remarks>
#endregion
public void MakeTwoWay()
{
for (int i = 0; i < this.Count; i++)
{
IAttachable ia = this[i];
if (ia.ListsBelongingTo.Contains(this) == false)
ia.ListsBelongingTo.Add(this);
}
}
#region XML Docs
/// <summary>
/// Moves the position of a block of IAttachables beginning at the argument
/// sourceIndex of numberToMove count to the argument destinationIndex.
/// </summary>
/// <param name="sourceIndex">The index of the first IAttachable in the block.</param>
/// <param name="numberToMove">The number of elements in the block.</param>
/// <param name="destinationIndex">The index to insert the block at.</param>
#endregion
public void MoveBlock(int sourceIndex, int numberToMove, int destinationIndex)
{
if (destinationIndex < sourceIndex)
{
for (int i = 0; i < numberToMove; i++)
{
mInternalList.Insert(destinationIndex + i, this[sourceIndex + i]);
mInternalList.RemoveAt(sourceIndex + i + 1);
}
}
else
{
for (int i = 0; i < numberToMove; i++)
{
mInternalList.Insert(destinationIndex, this[sourceIndex]);
mInternalList.RemoveAt(sourceIndex);
}
}
}
#region XML Docs
/// <summary>
/// Removes the argument IAttachable from this and clears the two-way relationship.
/// </summary>
/// <param name="attachable">The IAttachable to remove from this.</param>
#endregion
public void Remove(T attachable)
{
if (attachable.ListsBelongingTo.Contains(this))
{
attachable.ListsBelongingTo.Remove(this);
}
// Vic says: This makes things safer, but can also hurt performance. Should we leave this in?
// Update on March 7, 2011 - this kills performance for particles on the phone. We gotta take it
// out
//if (mInternalList.Contains(attachable))
mInternalList.Remove(attachable);
if (this.CollectionChanged != null)
{
// We put the index for Silverlight - but I don't want to do indexof for performance reasons so 0 it is
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, attachable, 0));
}
}
#region XML Docs
/// <summary>
/// Removes all IAttachables contained in the argument attachableList from this and clears the two-way relationships between
/// this and all IAttachables removed.
/// </summary>
/// <param name="attachableList">The list of IAttachables to remove.</param>
#endregion
public void Remove(AttachableList<T> attachableList)
{
for (int i = 0; i < attachableList.Count; i++)
{
Remove(attachableList[i]);
}
}
#region XML Docs
/// <summary>
/// Removes the IAttachable at the argument index and clears two-way relationships.
/// </summary>
/// <param name="index">The index of the object to remove.</param>
#endregion
public void RemoveAt(int index)
{
T removed = mInternalList[index];
if (mInternalList[index].ListsBelongingTo.Contains(this))
mInternalList[index].ListsBelongingTo.Remove(this);
mInternalList.RemoveAt(index);
if (this.CollectionChanged != null)
{
// We put the index for Silverlight - but I don't want to do indexof for performance reasons so 0 it is
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed, 0));
}
}
/// <summary>
/// Removes the IAttachable at the argument index from the list, but the IAttachable will continue to reference
/// this List in its ListsBelongingTo.
/// </summary>
/// <param name="index"></param>
public void RemoveAtOneWay(int index)
{
T removed = mInternalList[index];
mInternalList.RemoveAt(index);
if (this.CollectionChanged != null)
{
// We put the index for Silverlight - but I don't want to do indexof for performance reasons so 0 it is
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed, 0));
}
}
public void Sort(Comparison<T> comparison)
{
mInternalList.Sort(comparison);
}
public void Sort(IComparer<T> comparer)
{
// Calling Sort on the List is an unstable sort. This
// results in flickering. We want to implement our own sorting
// algorithm. We'll do the naive sort used elsewhere:
// mInternalList.Sort(comparer);
if (Count == 1 || Count == 0)
return;
int whereObjectBelongs;
for (int i = 1; i < Count; i++)
{
var itemAti = this[i];
if (comparer.Compare(itemAti, this[i-1]) < 0)
{
if (i == 1)
{
Insert(0, itemAti);
RemoveAtOneWay(i + 1);
continue;
}
for (whereObjectBelongs = i - 2; whereObjectBelongs > -1; whereObjectBelongs--)
{
if (comparer.Compare(itemAti, this[whereObjectBelongs]) >= 0)
{
Insert(whereObjectBelongs + 1, itemAti);
RemoveAtOneWay(i + 1);
break;
}
else if (whereObjectBelongs == 0 && comparer.Compare(itemAti, this[0]) < 0)
{
Insert(0, itemAti);
RemoveAtOneWay(i + 1);
break;
}
}
}
}
}
public void SortNameAscending()
{
if (Count == 1 || Count == 0)
return;
int whereObjectBelongs;
for (int i = 1; i < Count; i++)
{
if ((this[i]).Name.CompareTo(this[i - 1].Name) < 0)
{
if (i == 1)
{
Insert(0, this[i]);
RemoveAtOneWay(i + 1);
continue;
}
for (whereObjectBelongs = i - 2; whereObjectBelongs > -1; whereObjectBelongs--)
{
if ((this[i]).Name.CompareTo(this[whereObjectBelongs].Name) >= 0)
{
Insert(whereObjectBelongs + 1, this[i]);
RemoveAtOneWay(i + 1);
break;
}
else if (whereObjectBelongs == 0 && (this[i]).Name.CompareTo(this[0].Name) < 0)
{
Insert(0, this[i]);
RemoveAtOneWay(i + 1);
break;
}
}
}
}
}
#region XML Docs
/// <summary>
/// Returns a string with the name and the number of elements that this contains.
/// </summary>
/// <returns>The string with this instance's name and element count.</returns>
#endregion
public override string ToString()
{
return mName + ": " + this.Count;
}
#endregion
#region Protected Methods
#endregion
#endregion
#region IList<T> Members
public int IndexOf(T item)
{
return mInternalList.IndexOf(item);
}
public T this[int index]
{
get
{
return mInternalList[index];
}
set
{
mInternalList[index] = value;
}
}
#endregion
#region ICollection<T> Members
public void CopyTo(T[] array, int arrayIndex)
{
mInternalList.CopyTo(array, arrayIndex);
}
public bool IsReadOnly
{
get { return ((IList)mInternalList).IsReadOnly; }
}
bool ICollection<T>.Remove(T item)
{
// so inefficient
bool returnValue = this.Contains(item);
Remove((T)item);
return returnValue;
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < mInternalList.Count; i++)
{
yield return mInternalList[i];
}
//return mInternalList.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
for (int i = 0; i < mInternalList.Count; i++)
{
yield return mInternalList[i];
}
// return mInternalList.GetEnumerator();
}
#endregion
#region IList Members
//public int Add(object value)
//{
//}
int IList.Add(object value)
{
int returnValue = this.Count;
this.Add((T)value);
return returnValue;
}
bool IList.Contains(object value)
{
return ((IList)mInternalList).Contains(value);
}
int IList.IndexOf(object value)
{
return ((IList)mInternalList).IndexOf(value);
}
void IList.Insert(int index, object value)
{
this.Insert(index, (T)value);
}
bool IList.IsFixedSize
{
get { return ((IList)mInternalList).IsFixedSize; }
}
void IList.Remove(object value)
{
Remove((T)value);
}
object IList.this[int index]
{
get
{
return mInternalList[index];
}
set
{
((IList)mInternalList)[index] = value;
}
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
((ICollection)mInternalList).CopyTo(array, index);
}
bool ICollection.IsSynchronized
{
get { return ((ICollection)mInternalList).IsSynchronized; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)mInternalList).SyncRoot; }
}
#endregion
#region IAttachableRemovable Members
void IAttachableRemovable.RemoveGuaranteedContain(IAttachable attachable)
{
attachable.ListsBelongingTo.Remove(this);
mInternalListAsIList.Remove(attachable);
if (this.CollectionChanged != null)
{
// We put the index for Silverlight - but I don't want to do indexof for performance reasons so 0 it is
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, attachable, 0));
}
}
#endregion
#region INameable Members
string FlatRedBall.Utilities.INameable.Name
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
#region IList Members
void IList.Clear()
{
Clear();
}
bool IList.IsReadOnly
{
get { return IsReadOnly; }
}
void IList.RemoveAt(int index)
{
RemoveAt(index);
}
#endregion
#region ICollection Members
int ICollection.Count
{
get { return mInternalList.Count; }
}
#endregion
public event NotifyCollectionChangedEventHandler CollectionChanged;
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// PartitionerQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Linq.Parallel;
using System.Diagnostics;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
namespace System.Linq.Parallel
{
/// <summary>
/// A QueryOperator that represents the output of the query partitioner.AsParallel().
/// </summary>
internal class PartitionerQueryOperator<TElement> : QueryOperator<TElement>
{
private readonly Partitioner<TElement> _partitioner; // The partitioner to use as data source.
internal PartitionerQueryOperator(Partitioner<TElement> partitioner)
: base(false, QuerySettings.Empty)
{
_partitioner = partitioner;
}
internal bool Orderable
{
get { return _partitioner is OrderablePartitioner<TElement>; }
}
internal override QueryResults<TElement> Open(QuerySettings settings, bool preferStriping)
{
// Notice that the preferStriping argument is not used. Partitioner<T> does not support
// striped partitioning.
return new PartitionerQueryOperatorResults(_partitioner, settings);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TElement> AsSequentialQuery(CancellationToken token)
{
using (IEnumerator<TElement> enumerator = _partitioner.GetPartitions(1)[0])
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
}
//---------------------------------------------------------------------------------------
// The state of the order index of the results returned by this operator.
//
internal override OrdinalIndexState OrdinalIndexState
{
get { return GetOrdinalIndexState(_partitioner); }
}
/// <summary>
/// Determines the OrdinalIndexState for a partitioner
/// </summary>
internal static OrdinalIndexState GetOrdinalIndexState(Partitioner<TElement> partitioner)
{
OrderablePartitioner<TElement>? orderablePartitioner = partitioner as OrderablePartitioner<TElement>;
if (orderablePartitioner == null)
{
return OrdinalIndexState.Shuffled;
}
if (orderablePartitioner.KeysOrderedInEachPartition)
{
if (orderablePartitioner.KeysNormalized)
{
return OrdinalIndexState.Correct;
}
else
{
return OrdinalIndexState.Increasing;
}
}
else
{
return OrdinalIndexState.Shuffled;
}
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
/// <summary>
/// QueryResults for a PartitionerQueryOperator
/// </summary>
private class PartitionerQueryOperatorResults : QueryResults<TElement>
{
private readonly Partitioner<TElement> _partitioner; // The data source for the query
private QuerySettings _settings; // Settings collected from the query
internal PartitionerQueryOperatorResults(Partitioner<TElement> partitioner, QuerySettings settings)
{
_partitioner = partitioner;
_settings = settings;
}
internal override void GivePartitionedStream(IPartitionedStreamRecipient<TElement> recipient)
{
Debug.Assert(_settings.DegreeOfParallelism.HasValue);
int partitionCount = _settings.DegreeOfParallelism.Value;
OrderablePartitioner<TElement>? orderablePartitioner = _partitioner as OrderablePartitioner<TElement>;
// If the partitioner is not orderable, it will yield zeros as order keys. The order index state
// is irrelevant.
OrdinalIndexState indexState = (orderablePartitioner != null)
? GetOrdinalIndexState(orderablePartitioner)
: OrdinalIndexState.Shuffled;
PartitionedStream<TElement, int> partitions = new PartitionedStream<TElement, int>(
partitionCount,
Util.GetDefaultComparer<int>(),
indexState);
if (orderablePartitioner != null)
{
IList<IEnumerator<KeyValuePair<long, TElement>>> partitionerPartitions =
orderablePartitioner.GetOrderablePartitions(partitionCount);
if (partitionerPartitions == null)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_NullPartitionList);
}
if (partitionerPartitions.Count != partitionCount)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_WrongNumberOfPartitions);
}
for (int i = 0; i < partitionCount; i++)
{
IEnumerator<KeyValuePair<long, TElement>> partition = partitionerPartitions[i];
if (partition == null)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_NullPartition);
}
partitions[i] = new OrderablePartitionerEnumerator(partition);
}
}
else
{
IList<IEnumerator<TElement>> partitionerPartitions =
_partitioner.GetPartitions(partitionCount);
if (partitionerPartitions == null)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_NullPartitionList);
}
if (partitionerPartitions.Count != partitionCount)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_WrongNumberOfPartitions);
}
for (int i = 0; i < partitionCount; i++)
{
IEnumerator<TElement> partition = partitionerPartitions[i];
if (partition == null)
{
throw new InvalidOperationException(SR.PartitionerQueryOperator_NullPartition);
}
partitions[i] = new PartitionerEnumerator(partition);
}
}
recipient.Receive<int>(partitions);
}
}
/// <summary>
/// Enumerator that converts an enumerator over key-value pairs exposed by a partitioner
/// to a QueryOperatorEnumerator used by PLINQ internally.
/// </summary>
private class OrderablePartitionerEnumerator : QueryOperatorEnumerator<TElement, int>
{
private readonly IEnumerator<KeyValuePair<long, TElement>> _sourceEnumerator;
internal OrderablePartitionerEnumerator(IEnumerator<KeyValuePair<long, TElement>> sourceEnumerator)
{
_sourceEnumerator = sourceEnumerator;
}
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TElement currentElement, ref int currentKey)
{
if (!_sourceEnumerator.MoveNext()) return false;
KeyValuePair<long, TElement> current = _sourceEnumerator.Current;
currentElement = current.Value;
checked
{
currentKey = (int)current.Key;
}
return true;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_sourceEnumerator != null);
_sourceEnumerator.Dispose();
}
}
/// <summary>
/// Enumerator that converts an enumerator over key-value pairs exposed by a partitioner
/// to a QueryOperatorEnumerator used by PLINQ internally.
/// </summary>
private class PartitionerEnumerator : QueryOperatorEnumerator<TElement, int>
{
private readonly IEnumerator<TElement> _sourceEnumerator;
internal PartitionerEnumerator(IEnumerator<TElement> sourceEnumerator)
{
_sourceEnumerator = sourceEnumerator;
}
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TElement currentElement, ref int currentKey)
{
if (!_sourceEnumerator.MoveNext()) return false;
currentElement = _sourceEnumerator.Current;
currentKey = 0;
return true;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_sourceEnumerator != null);
_sourceEnumerator.Dispose();
}
}
}
}
| |
namespace Mdl2Tool
{
public class Mdl2
{
public static string Account => "&xEA8C;";
public static string AccountBox => "&xE187;";
public static string AccountCancel => "&xE1E0;";
public static string AccountDetailsOutline => "&xE136;";
public static string AccountFrameOutline => "&xE156;";
public static string AccountMultiple => "&xE125;";
public static string AccountOutline => "&xE13D;";
public static string AccountOutlineBox => "&xE8D4;";
public static string AccountPlus => "&xE1E2;";
public static string AccountStatus => "&xE181;";
public static string AccountSwitch => "&xE748;";
public static string Airplane => "&xEB4C;";
public static string AirplaneOutline => "&xE709;";
public static string Album => "&xE142;";
public static string Alert => "&xE814;";
public static string AlertOutline => "&xE7BA;";
public static string Archive => "&xE7B8;";
public static string Arrow => "&xE1D1;";
public static string ArrowBottomRight => "&xE741;";
public static string ArrowDown => "&xE1FD;";
public static string ArrowLeft => "&xE0A6;";
public static string ArrowRight => "&xE0AD;";
public static string ArrowTopLeft => "&xE742;";
public static string ArrowUp => "&xE110;";
public static string ArrowUpVariant => "&xE752;";
public static string Attach => "&xE16C;";
public static string Bag => "&xE14D;";
public static string Battery0 => "&xE850;";
public static string Battery1 => "&xE851;";
public static string Battery10 => "&xE83F;";
public static string Battery2 => "&xE852;";
public static string Battery3 => "&xE853;";
public static string Battery4 => "&xE854;";
public static string Battery5 => "&xE855;";
public static string Battery6 => "&xE856;";
public static string Battery7 => "&xE857;";
public static string Battery8 => "&xE858;";
public static string Battery9 => "&xE859;";
public static string BatteryCharge0 => "&xE85A;";
public static string BatteryCharge1 => "&xE85B;";
public static string BatteryCharge2 => "&xE85C;";
public static string BatteryCharge3 => "&xE85D;";
public static string BatteryCharge4 => "&xE85E;";
public static string BatteryCharge5 => "&xE85F;";
public static string BatteryCharge6 => "&xE860;";
public static string BatteryCharge7 => "&xE861;";
public static string BatteryCharge8 => "&xE862;";
public static string BatteryDisconnect => "&xE996;";
public static string BatteryLarge0 => "&xEBA0;";
public static string BatteryLarge1 => "&xEBA1;";
public static string BatteryLarge10 => "&xEBAA;";
public static string BatteryLarge2 => "&xEBA2;";
public static string BatteryLarge3 => "&xEBA3;";
public static string BatteryLarge4 => "&xEBA4;";
public static string BatteryLarge5 => "&xEBA5;";
public static string BatteryLarge6 => "&xEBA6;";
public static string BatteryLarge7 => "&xEBA7;";
public static string BatteryLarge8 => "&xEBA8;";
public static string BatteryLarge9 => "&xEBA9;";
public static string BatteryLargeCharge0 => "&xEBAB;";
public static string BatteryLargeCharge1 => "&xEBAC;";
public static string BatteryLargeCharge10 => "&xEBB5;";
public static string BatteryLargeCharge2 => "&xEBAD;";
public static string BatteryLargeCharge3 => "&xEBAE;";
public static string BatteryLargeCharge4 => "&xEBAF;";
public static string BatteryLargeCharge5 => "&xEBB0;";
public static string BatteryLargeCharge6 => "&xEBB1;";
public static string BatteryLargeCharge7 => "&xEBB2;";
public static string BatteryLargeCharge8 => "&xEBB3;";
public static string BatteryLargeCharge9 => "&xEBB4;";
public static string BatteryLargeSave0 => "&xEBB6;";
public static string BatteryLargeSave1 => "&xEBB7;";
public static string BatteryLargeSave10 => "&xEBC0;";
public static string BatteryLargeSave2 => "&xEBB8;";
public static string BatteryLargeSave3 => "&xEBB9;";
public static string BatteryLargeSave4 => "&xEBBA;";
public static string BatteryLargeSave5 => "&xEBBB;";
public static string BatteryLargeSave6 => "&xEBBC;";
public static string BatteryLargeSave7 => "&xEBBD;";
public static string BatteryLargeSave8 => "&xEBBE;";
public static string BatteryLargeSave9 => "&xEBBF;";
public static string BatterySave0 => "&xE863;";
public static string BatterySave1 => "&xE864;";
public static string BatterySave2 => "&xE865;";
public static string BatterySave3 => "&xE866;";
public static string BatterySave4 => "&xE867;";
public static string BatterySave5 => "&xE868;";
public static string BatterySave6 => "&xE869;";
public static string BatterySave7 => "&xE86A;";
public static string BatterySave8 => "&xE86B;";
public static string BellOffOutline => "&xE7ED;";
public static string BellOutline => "&xEA8F;";
public static string Bluetooth => "&xE702;";
public static string Boat => "&xEB48;";
public static string BoatOutline => "&xE7E3;";
public static string Book => "&xE82D;";
public static string BookPlus => "&xE82E;";
public static string BoxFourth => "&xE744;";
public static string BoxFull => "&xE747;";
public static string BoxHalfHorizontal => "&xE745;";
public static string BoxHalfVertical => "&xE746;";
public static string BoxSixteenth => "&xE743;";
public static string BoxSmall => "&xE004;";
public static string Bus => "&xEB47;";
public static string BusOutline => "&xE806;";
public static string Calculator => "&xE1D0;";
public static string Calendar => "&xE163;";
public static string CalendarDay => "&xE184;";
public static string CalendarRepeat => "&xE161;";
public static string CalendarReply => "&xE1DB;";
public static string CalendarWeeks => "&xE162;";
public static string Camera => "&xE114;";
public static string CameraClicker => "&xE12D;";
public static string CameraSwitch => "&xE124;";
public static string Cancel => "&xE25B;";
public static string Car => "&xE7EC;";
public static string CarLeftOutline => "&xE811;";
public static string CarRightOutline => "&xEA5E;";
public static string CarSide => "&xEA8B;";
public static string Cd => "&xE958;";
public static string Cellphone => "&xE1C9;";
public static string CellphoneTablet => "&xE8CC;";
public static string CellphoneWireless => "&xE957;";
public static string Check => "&xE001;";
public static string CheckboxBlank => "&xE002;";
public static string CheckboxBlankOutline => "&xE003;";
public static string CheckboxCheck => "&xE005;";
public static string CheckOutlineCheck => "&xE0A2;";
public static string ChevronBoldDown => "&xE96E;";
public static string ChevronBoldLeft => "&xE96F;";
public static string ChevronBoldRight => "&xE970;";
public static string ChevronBoldUp => "&xE96D;";
public static string ChevronDown => "&xE011;";
public static string ChevronLeft => "&xE00E;";
public static string ChevronLeftCircle => "&xE760;";
public static string ChevronRight => "&xE00F;";
public static string ChevronRightCircle => "&xE761;";
public static string ChevronUp => "&xE010;";
public static string Chip => "&xE964;";
public static string Clear => "&xE750;";
public static string ClearSmall => "&xE925;";
public static string Clipboard => "&xE77F;";
public static string Clock => "&xE121;";
public static string Close => "&xE106;";
public static string ClosedCaption => "&xE190;";
public static string Cloud => "&xE753;";
public static string Compare => "&xE11E;";
public static string Computer => "&xE211;";
public static string ComputerTheme => "&xE771;";
public static string Cone => "&xE98F;";
public static string Console => "&xE756;";
public static string Contact => "&xE12A;";
public static string ContactSend => "&xE1D7;";
public static string Controller => "&xE7FC;";
public static string Crop => "&xE123;";
public static string Cursor => "&xE1E3;";
public static string CursorDefault => "&xE8B0;";
public static string Delete => "&xE107;";
public static string Dialer => "&xE75F;";
public static string Diamond => "&xE18A;";
public static string Direction => "&xE816;";
public static string Disk => "&xE105;";
public static string DiskAll => "&xEA35;";
public static string DiskDownload => "&xE159;";
public static string DiskEdit => "&xE28F;";
public static string Divide => "&xE94A;";
public static string Doppler => "&xE95A;";
public static string DotsHorizontal => "&xE10C;";
public static string DotsVertical => "&xE796;";
public static string Download => "&xE118;";
public static string EaseOfAccess => "&xE07F;";
public static string Edit => "&xE104;";
public static string Education => "&xE7BE;";
public static string Email => "&xE119;";
public static string EmailAddress => "&xE168;";
public static string EmailForward => "&xE120;";
public static string EmailForwardRtl => "&xE1A8;";
public static string EmailOpened => "&xE166;";
public static string EmailReply => "&xE172;";
public static string EmailReplyall => "&xE165;";
public static string EmailReplyallRtl => "&xE1F2;";
public static string EmailReplyRtl => "&xE1AF;";
public static string Emoji => "&xE170;";
public static string EmojiGrin => "&xE11D;";
public static string Equal => "&xE94E;";
public static string Eraser => "&xE75C;";
public static string EraserColor1 => "&xE82B;";
public static string EraserColor2 => "&xE82C;";
public static string Exclamation => "&xE171;";
public static string File => "&xE132;";
public static string FileHiddenOutline => "&xE295;";
public static string FileMultiple => "&xE16F;";
public static string FileOutline => "&xE160;";
public static string FileOutlineUp => "&xE8E5;";
public static string FilePrinterOutline => "&xE956;";
public static string Filter => "&xE16E;";
public static string Fingerprint => "&xE928;";
public static string Firewall => "&xE83D;";
public static string Flag => "&xEB4F;";
public static string FlagOutline => "&xEB50;";
public static string Flash => "&xE945;";
public static string Flashlight => "&xE754;";
public static string Folder => "&xE188;";
public static string FolderMove => "&xE19C;";
public static string FolderOutline => "&xE8B7;";
public static string FolderPlus => "&xE1DA;";
public static string FolderRefresh => "&xE1DF;";
public static string FolderRefreshCancel => "&xE1DD;";
public static string FolderUp => "&xE197;";
public static string FormatBlockLeftDecrease => "&xE290;";
public static string FormatBlockLeftIndent => "&xE291;";
public static string FormatBlockRightDecrease => "&xE297;";
public static string FormatBlockRightIncrease => "&xE298;";
public static string FormatBold => "&xE19B;";
public static string FormatFontSize => "&xE1C8;";
public static string FormatFontSizeDecrease => "&xE1C6;";
public static string FormatFontSizeIncrease => "&xE1C7;";
public static string FormatTextCenter => "&xE1A1;";
public static string FormatTextLeft => "&xE1A2;";
public static string FormatTextRight => "&xE1A0;";
public static string FormatUnderline => "&xE19A;";
public static string Gps => "&xE1D2;";
public static string Grid => "&xE80A;";
public static string GridPerspective => "&xE809;";
public static string Headphones => "&xE7F6;";
public static string Headset => "&xE95B;";
public static string Heart => "&xE00B;";
public static string HeartBroken => "&xE007;";
public static string HeartOutline => "&xE006;";
public static string HeartPulse => "&xE95E;";
public static string Help => "&xE11B;";
public static string Home => "&xEA8A;";
public static string HomeOutline => "&xE10F;";
public static string HomeTree => "&xE1C3;";
public static string Image => "&xEB9F;";
public static string Indent => "&xE7FD;";
public static string Info => "&xE946;";
public static string InputMarker => "&xE193;";
public static string InputMarkerColor1 => "&xE891;";
public static string InputMarkerColor2 => "&xE82A;";
public static string InputPen => "&xE76D;";
public static string InputPenColor1 => "&xE88F;";
public static string InputPenColor2 => "&xE829;";
public static string Key => "&xE192;";
public static string Keyboard => "&xE087;";
public static string KeyboardDown => "&xE75B;";
public static string KeyboardEnter => "&xE751;";
public static string KeyboardLeft => "&xE763;";
public static string KeyboardMouse => "&xE961;";
public static string KeyboardRight => "&xE764;";
public static string KeyboardSplit => "&xE08F;";
public static string KeyboardUp => "&xE75A;";
public static string Landmark => "&xE825;";
public static string Laptop => "&xE770;";
public static string LaptopMonitor => "&xE7F8;";
public static string LaptopMonitorExtend => "&xE7F7;";
public static string LaptopPrinter => "&xE772;";
public static string LaptopTablet => "&xE212;";
public static string Layers => "&xE81E;";
public static string Led => "&xE781;";
public static string Library => "&xE1D3;";
public static string Lightbulb => "&xEA80;";
public static string LineHorizontal => "&xE0B8;";
public static string Link => "&xE167;";
public static string List => "&xE292;";
public static string ListBlock => "&xE15C;";
public static string ListBlockRtl => "&xEA65;";
public static string ListCheckRtl => "&xEA98;";
public static string ListCollapse => "&xE16A;";
public static string ListExpand => "&xE169;";
public static string ListRtl => "&xE175;";
public static string ListSelect => "&xE179;";
public static string ListSelectRtl => "&xE1EC;";
public static string ListSelectUp => "&xE17D;";
public static string ListSelectUpRtl => "&xE1ED;";
public static string Lock => "&xE1F6;";
public static string Lowercase => "&xE84A;";
public static string Magnify => "&xE1A3;";
public static string MagnifyMinus => "&xE1A4;";
public static string MagnifyPlus => "&xE12E;";
public static string MapDownload => "&xE826;";
public static string MapLocation => "&xE1C4;";
public static string MapMarkerPause => "&xEB4A;";
public static string MapMarkerPauseOutline => "&xE81A;";
public static string MapMarkerPlay => "&xEB49;";
public static string MapMarkerPlayOutline => "&xE819;";
public static string MapPin => "&xE139;";
public static string Media => "&xEA69;";
public static string MediaFastforward => "&xEB9D;";
public static string MediaNext => "&xE101;";
public static string MediaPause => "&xE103;";
public static string MediaPlay => "&xE102;";
public static string MediaPlayer => "&xE955;";
public static string MediaPrevious => "&xE100;";
public static string MediaRepeat => "&xE1CA;";
public static string MediaRewind => "&xEB9E;";
public static string MediaServer => "&xE953;";
public static string MediaWireless => "&xE952;";
public static string Megaphone => "&xE789;";
public static string Menu => "&xE700;";
public static string Message => "&xE15F;";
public static string MessageForwardRtl => "&xE89B;";
public static string MessageMultiple => "&xE8F2;";
public static string MessageProcessing => "&xE25C;";
public static string MessageQuote => "&xE134;";
public static string MessageVideo => "&xE13B;";
public static string Microphone => "&xE1D6;";
public static string Minus => "&xE108;";
public static string Monitor => "&xE7F4;";
public static string MonitorDuplicate => "&xE7F9;";
public static string MonitorExtend => "&xE7FA;";
public static string MonitorSound => "&xE7F3;";
public static string MonitorTape => "&xE954;";
public static string Moon => "&xE708;";
public static string Mouse => "&xE962;";
public static string Multiply => "&xE947;";
public static string Music => "&xE189;";
public static string Network => "&xE17B;";
public static string NetworkClose => "&xE17A;";
public static string Nfc => "&xE9A1;";
public static string Note => "&xE70B;";
public static string OpenInApp => "&xE17C;";
public static string Outline => "&xE12F;";
public static string OutlineRtl => "&xEA41;";
public static string Palette => "&xE2B1;";
public static string PanelBottom => "&xE147;";
public static string PanelLeft => "&xE145;";
public static string PanelRight => "&xE146;";
public static string Pen => "&xE929;";
public static string Percent => "&xE94C;";
public static string Phone => "&xE13A;";
public static string PhoneBook => "&xE1D4;";
public static string PhoneForward => "&xE7F2;";
public static string PhoneForwardRtl => "&xEA97;";
public static string PhoneHangup => "&xE137;";
public static string Pin => "&xE840;";
public static string PinColor => "&xE842;";
public static string PinLeft => "&xE141;";
public static string PinLeftColor => "&xE841;";
public static string Plus => "&xE109;";
public static string PlusMinus => "&xE94D;";
public static string Printer => "&xE2F6;";
public static string Printer3d => "&xE2F7;";
public static string Processor => "&xE950;";
public static string Projector => "&xE95D;";
public static string Puzzle => "&xEA86;";
public static string Redo => "&xE10D;";
public static string Refresh => "&xE117;";
public static string Region => "&xE775;";
public static string Remote => "&xE951;";
public static string Rename => "&xE13E;";
public static string Repeat => "&xE1CD;";
public static string RepeatOnce => "&xE1CC;";
public static string RotateClockwise => "&xE7AD;";
public static string RotateLeft => "&xE14F;";
public static string RotationLock => "&xE755;";
public static string Router => "&xE965;";
public static string RouterWireless => "&xE969;";
public static string Scanner => "&xE294;";
public static string Scissors => "&xE8C6;";
public static string Sd => "&xE7F1;";
public static string Search => "&xE094;";
public static string Security => "&xE727;";
public static string SecurityAlert => "&xE1DE;";
public static string SelectionCut => "&xE924;";
public static string SelectionRedo => "&xE1F4;";
public static string SelectionUndo => "&xE1C5;";
public static string SelectTable => "&xE14E;";
public static string Send => "&xE122;";
public static string Server => "&xE83B;";
public static string ServerNetwork => "&xE968;";
public static string Setting => "&xE115;";
public static string Share => "&xE72D;";
public static string Shuffle => "&xE14B;";
public static string SidebarLeft_expand => "&xE1C0;";
public static string SidebarLeftCollapse => "&xE1BF;";
public static string SidebarRightCollapse => "&xE126;";
public static string SidebarRightExpand => "&xE127;";
public static string Signal1 => "&xE86C;";
public static string Signal2 => "&xE86D;";
public static string Signal3 => "&xE86E;";
public static string Signal4 => "&xE86F;";
public static string Signal5 => "&xE870;";
public static string SignalCancel => "&xE871;";
public static string SlashForward => "&xE199;";
public static string Sound => "&xE15D;";
public static string Sound0 => "&xE992;";
public static string Sound1 => "&xE993;";
public static string Sound2 => "&xE994;";
public static string Sound3 => "&xE995;";
public static string SoundCancel => "&xE198;";
public static string Space => "&xE75D;";
public static string Speaker => "&xE7F5;";
public static string SquareRoot => "&xE94B;";
public static string Star => "&xE1CF;";
public static string StarCancel => "&xE195;";
public static string StarHalfLeft => "&xE7C6;";
public static string StarHalfRight => "&xE7C7;";
public static string StarOutline => "&xE1CE;";
public static string Sun => "&xE706;";
public static string Tablet => "&xE70A;";
public static string Tag => "&xE1CB;";
public static string Tape => "&xE96A;";
public static string ThoughtBubble => "&xEA91;";
public static string Thumbs => "&xE19D;";
public static string ThumbsDown => "&xE19E;";
public static string ThumbsUp => "&xE19F;";
public static string Timer => "&xE916;";
public static string Toolbox => "&xEB4E;";
public static string ToolboxOutline => "&xE821;";
public static string Tooltip => "&xE7E7;";
public static string TooltipOutline => "&xE91C;";
public static string Touch => "&xE815;";
public static string TouchSlider => "&xE927;";
public static string Tram => "&xEB4D;";
public static string TramOutline => "&xE7C0;";
public static string Translate => "&xE164;";
public static string Undo => "&xE10E;";
public static string Unlock => "&xE1F7;";
public static string Upload => "&xE11C;";
public static string Uppercase => "&xE84B;";
public static string Usb => "&xE88E;";
public static string Video => "&xE25D;";
public static string VideoOutline => "&xE116;";
public static string Voicemail => "&xE1D5;";
public static string Walk => "&xE726;";
public static string WalkOutline => "&xE805;";
public static string Webcam => "&xE960;";
public static string Wifi1 => "&xE872;";
public static string Wifi2 => "&xE873;";
public static string Wifi3 => "&xE874;";
public static string WifiOutline0 => "&xE1E5;";
public static string WifiOutline1 => "&xE1E6;";
public static string WifiOutline2 => "&xE1E7;";
public static string WifiOutline3 => "&xE1E8;";
public static string WifiOutline4 => "&xE1E9;";
public static string WindowCollapse => "&xE1D8;";
public static string WindowExpand => "&xE1D9;";
public static string Wireless => "&xE704;";
public static string World => "&xE128;";
public static string WorldWire => "&xE12B;";
public static string Wrench => "&xE15E;";
public static string Xbox => "&xE990;";
}
}
| |
//#if (!__solua__ && !__Windows__)
// #define __liblua__
//#endif
namespace SharpLua
{
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Collections;
using System.Text;
using System.Security;
using SharpLua;
/*
* Lua types for the API, returned by lua_type function
*/
public enum LuaTypes
{
LUA_TNONE = -1,
LUA_TNIL = 0,
LUA_TBOOLEAN = 1,
LUA_TLIGHTUSERDATA = 2,
LUA_TNUMBER = 3,
LUA_TSTRING = 4,
LUA_TTABLE = 5,
LUA_TFUNCTION = 6,
LUA_TUSERDATA = 7,
LUA_TTHREAD = 8,
}
// steffenj: BEGIN lua garbage collector options
/*
* Lua Garbage Collector options (param "what")
*/
public enum LuaGCOptions
{
LUA_GCSTOP = 0,
LUA_GCRESTART = 1,
LUA_GCCOLLECT = 2,
LUA_GCCOUNT = 3,
LUA_GCCOUNTB = 4,
LUA_GCSTEP = 5,
LUA_GCSETPAUSE = 6,
LUA_GCSETSTEPMUL = 7,
}
/*
sealed class LuaGCOptions
{
public static int LUA_GCSTOP = 0;
public static int LUA_GCRESTART = 1;
public static int LUA_GCCOLLECT = 2;
public static int LUA_GCCOUNT = 3;
public static int LUA_GCCOUNTB = 4;
public static int LUA_GCSTEP = 5;
public static int LUA_GCSETPAUSE = 6;
public static int LUA_GCSETSTEPMUL = 7;
};
*/
// steffenj: END lua garbage collector options
/*
* Special stack indexes
*/
public class LuaIndexes
{
public static int LUA_REGISTRYINDEX = -10000;
public static int LUA_ENVIRONINDEX = -10001; // steffenj: added environindex
public static int LUA_GLOBALSINDEX = -10002; // steffenj: globalsindex previously was -10001
}
/*
* Structure used by the chunk reader
*/
[StructLayout(LayoutKind.Sequential)]
public struct ReaderInfo
{
public String chunkData;
public bool finished;
}
/*
* Delegate for functions passed to Lua as function pointers
*/
public delegate int LuaCSFunction(SharpLua.Lua.LuaState luaState);
/*
* Delegate for chunk readers used with lua_load
*/
public delegate string LuaChunkReader(SharpLua.Lua.LuaState luaState, ref ReaderInfo data, ref uint size);
/// <summary>
/// Used to handle Lua panics
/// </summary>
/// <param name="luaState"></param>
/// <returns></returns>
public delegate int LuaFunctionCallback(SharpLua.Lua.LuaState luaState);
/*
* P/Invoke wrapper of the Lua API
*
* Author: Fabio Mascarenhas
* Version: 1.0
*
* // steffenj: noteable changes in the LuaDLL API:
* - luaopen_* functions are gone
* (however Lua class constructor already calls luaL_openlibs now, so just remove these calls)
* - deprecated functions: lua_open, lua_strlen, lua_dostring
* (they still work but may be removed with next Lua version)
*
* list of functions of the Lua 5.1.1 C API that are not in LuaDLL
* i thought this may come in handy for the next Lua version upgrade and for anyone to see
* what the differences are in the APIs (C API vs LuaDLL API)
lua_concat (use System.String concatenation or similar)
lua_cpcall (no point in calling C functions)
lua_dump (would write to unmanaged memory via lua_Writer)
lua_getallocf (no C functions/pointers)
lua_isthread (no threads)
lua_newstate (use luaL_newstate)
lua_newthread (no threads)
lua_pushcclosure (no C functions/pointers)
lua_pushcfunction (no C functions/pointers)
lua_pushfstring (use lua_pushstring)
lua_pushthread (no threads)
lua_pushvfstring (use lua_pushstring)
lua_register (all libs already opened, use require in scripts for external libs)
lua_resume (no threads)
lua_setallocf (no C functions/pointers)
lua_status (no threads)
lua_tointeger (use System.Convert)
lua_tolstring (use lua_tostring)
lua_topointer (no C functions/pointers)
lua_tothread (no threads)
lua_xmove (no threads)
lua_yield (no threads)
luaL_add* (use System.String concatenation or similar)
luaL_argcheck (function argument checking unnecessary)
luaL_argerror (function argument checking unnecessary)
luaL_buffinit (use System.String concatenation or similar)
luaL_checkany (function argument checking unnecessary)
luaL_checkint (function argument checking unnecessary)
luaL_checkinteger (function argument checking unnecessary)
luaL_checklong (function argument checking unnecessary)
luaL_checklstring (function argument checking unnecessary)
luaL_checknumber (function argument checking unnecessary)
luaL_checkoption (function argument checking unnecessary)
luaL_checkstring (function argument checking unnecessary)
luaL_checktype (function argument checking unnecessary)
luaL_prepbuffer (use System.String concatenation or similar)
luaL_pushresult (use System.String concatenation or similar)
luaL_register (all libs already opened, use require in scripts for external libs)
luaL_typerror (function argument checking unnecessary)
(complete lua_Debug interface omitted)
lua_gethook***
lua_getinfo
lua_getlocal
lua_getstack
lua_getupvalue
lua_sethook
lua_setlocal
lua_setupvalue
*/
/*public*/
class LuaDLL
{
// for debugging
// const string BASEPATH = @"C:\development\software\dotnet\tools\PulseRecognizer\PulseRecognizer\bin\Debug\";
// const string BASEPATH = @"C:\development\software\ThirdParty\lua\Built\";
/*const string BASEPATH = "";
#if __Windows__
const string DLLX = ".dll";
#else
const string DLLX = ".so";
#endif
#if __lib__
const string PREFIX = "liblua";
#else
const string PREFIX = "lua";
#endif
#if __novs__
const string DLL = PREFIX;
#elif __dot__
const string DLL = PREFIX+"5.1";
#else
const string DLL = PREFIX+"51";
#endif
const string LUADLL = BASEPATH + DLL + DLLX;
const string LUALIBDLL = LUADLL;
#if __embed__
const string STUBDLL = LUADLL;
#else
const string STUBDLL = BASEPATH + "luanet" + DLLX;
#endif
*/
// steffenj: BEGIN additional Lua API functions new in Lua 5.1
//[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static int lua_gc(SharpLua.Lua.LuaState luaState, LuaGCOptions what, int data)
{
return SharpLua.Lua.lua_gc(luaState, (int)what, data);
}
//[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static string lua_typename(SharpLua.Lua.LuaState luaState, LuaTypes type)
{
return SharpLua.Lua.lua_typename(luaState, (int)type).ToString();
}
public static string luaL_typename(SharpLua.Lua.LuaState luaState, int stackPos)
{
return lua_typename(luaState, lua_type(luaState, stackPos));
}
//[DllImport(LUALIBDLL, CallingConvention = CallingConvention.Cdecl)]
public static void luaL_error(SharpLua.Lua.LuaState luaState, string message)
{
SharpLua.Lua.luaL_error(luaState, message);
}
public static void lua_error(SharpLua.Lua.LuaState luaState)
{
SharpLua.Lua.lua_error(luaState);
}
//[DllImport(LUALIBDLL, CallingConvention = CallingConvention.Cdecl)]
//Not wrapped
//public static string luaL_gsub(SharpLua.Lua.lua_State luaState, string str, string pattern, string replacement);
#if false
// the functions below are still untested
//[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static void lua_getfenv(SharpLua.Lua.lua_State luaState, int stackPos);
public static int lua_isfunction(SharpLua.Lua.lua_State luaState, int stackPos);
public static int lua_islightuserdata(SharpLua.Lua.lua_State luaState, int stackPos);
public static int lua_istable(SharpLua.Lua.lua_State luaState, int stackPos);
public static int lua_isuserdata(SharpLua.Lua.lua_State luaState, int stackPos);
public static int lua_lessthan(SharpLua.Lua.lua_State luaState, int stackPos1, int stackPos2);
public static int lua_rawequal(SharpLua.Lua.lua_State luaState, int stackPos1, int stackPos2);
public static int lua_setfenv(SharpLua.Lua.lua_State luaState, int stackPos);
public static void lua_setfield(SharpLua.Lua.lua_State luaState, int stackPos, string name);
public static int luaL_callmeta(SharpLua.Lua.lua_State luaState, int stackPos, string name);
// steffenj: END additional Lua API functions new in Lua 5.1
#endif
// steffenj: BEGIN Lua 5.1.1 API change (lua_open replaced by luaL_newstate)
//[DllImport(LUALIBDLL, CallingConvention = CallingConvention.Cdecl)]
public static SharpLua.Lua.LuaState luaL_newstate()
{
return SharpLua.Lua.luaL_newstate();
}
/// <summary>DEPRECATED - use luaL_newstate() instead!</summary>
public static SharpLua.Lua.LuaState lua_open()
{
return LuaDLL.luaL_newstate();
}
// steffenj: END Lua 5.1.1 API change (lua_open replaced by luaL_newstate)
//[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static void lua_close(SharpLua.Lua.LuaState luaState)
{
SharpLua.Lua.lua_close(luaState);
}
// steffenj: BEGIN Lua 5.1.1 API change (new function luaL_openlibs)
//[DllImport(LUALIBDLL, CallingConvention = CallingConvention.Cdecl)]
public static void luaL_openlibs(SharpLua.Lua.LuaState luaState)
{
SharpLua.Lua.luaL_openlibs(luaState);
}
/*
//[DllImport(LUALIBDLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaopen_base(IntPtr luaState);
//[DllImport(LUALIBDLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void luaopen_io(IntPtr luaState);
//[DllImport(LUALIBDLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void luaopen_table(IntPtr luaState);
//[DllImport(LUALIBDLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void luaopen_string(IntPtr luaState);
//[DllImport(LUALIBDLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void luaopen_math(IntPtr luaState);
//[DllImport(LUALIBDLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void luaopen_debug(IntPtr luaState);
//[DllImport(LUALIBDLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void luaopen_loadlib(IntPtr luaState);
*/
// steffenj: END Lua 5.1.1 API change (new function luaL_openlibs)
// steffenj: BEGIN Lua 5.1.1 API change (lua_strlen is now lua_objlen)
//[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static int lua_objlen(SharpLua.Lua.LuaState luaState, int stackPos)
{
return (int)SharpLua.Lua.lua_objlen(luaState, stackPos);
}
/// <summary>DEPRECATED - use lua_objlen(IntPtr luaState, int stackPos) instead!</summary>
public static int lua_strlen(SharpLua.Lua.LuaState luaState, int stackPos)
{
return lua_objlen(luaState, stackPos);
}
// steffenj: END Lua 5.1.1 API change (lua_strlen is now lua_objlen)
// steffenj: BEGIN Lua 5.1.1 API change (lua_dostring is now a macro luaL_dostring)
//[DllImport(LUALIBDLL, CallingConvention = CallingConvention.Cdecl)]
public static int luaL_loadstring(SharpLua.Lua.LuaState luaState, string chunk)
{
return SharpLua.Lua.luaL_loadstring(luaState, chunk);
}
public static int luaL_dostring(SharpLua.Lua.LuaState luaState, string chunk)
{
int result = LuaDLL.luaL_loadstring(luaState, chunk);
if (result != 0)
return result;
return LuaDLL.lua_pcall(luaState, 0, -1, 0);
}
/// <summary>DEPRECATED - use luaL_dostring(IntPtr luaState, string chunk) instead!</summary>
public static int lua_dostring(SharpLua.Lua.LuaState luaState, string chunk)
{
return LuaDLL.luaL_dostring(luaState, chunk);
}
// steffenj: END Lua 5.1.1 API change (lua_dostring is now a macro luaL_dostring)
// steffenj: BEGIN Lua 5.1.1 API change (lua_newtable is gone, lua_createtable is new)
//[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static void lua_createtable(SharpLua.Lua.LuaState luaState, int narr, int nrec)
{
SharpLua.Lua.lua_createtable(luaState, narr, nrec);
}
public static void lua_newtable(SharpLua.Lua.LuaState luaState)
{
LuaDLL.lua_createtable(luaState, 0, 0);
}
// steffenj: END Lua 5.1.1 API change (lua_newtable is gone, lua_createtable is new)
// steffenj: BEGIN Lua 5.1.1 API change (lua_dofile now in LuaLib as luaL_dofile macro)
//[DllImport(LUALIBDLL, CallingConvention = CallingConvention.Cdecl)]
public static int luaL_dofile(SharpLua.Lua.LuaState luaState, string fileName)
{
int result = LuaDLL.luaL_loadfile(luaState, fileName);
if (result != 0)
return result;
return LuaDLL.lua_pcall(luaState, 0, -1, 0);
}
// steffenj: END Lua 5.1.1 API change (lua_dofile now in LuaLib as luaL_dofile)
public static void lua_getglobal(SharpLua.Lua.LuaState luaState, string name)
{
LuaDLL.lua_pushstring(luaState, name);
LuaDLL.lua_gettable(luaState, LuaIndexes.LUA_GLOBALSINDEX);
}
public static void lua_setglobal(SharpLua.Lua.LuaState luaState, string name)
{
LuaDLL.lua_pushstring(luaState, name);
LuaDLL.lua_insert(luaState, -2);
LuaDLL.lua_settable(luaState, LuaIndexes.LUA_GLOBALSINDEX);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_settop(SharpLua.Lua.LuaState luaState, int newTop)
{
SharpLua.Lua.lua_settop(luaState, newTop);
}
// steffenj: BEGIN added lua_pop "macro"
public static void lua_pop(SharpLua.Lua.LuaState luaState, int amount)
{
LuaDLL.lua_settop(luaState, -(amount) - 1);
}
// steffenj: END added lua_pop "macro"
//[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static void lua_insert(SharpLua.Lua.LuaState luaState, int newTop)
{
SharpLua.Lua.lua_insert(luaState, newTop);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_remove(SharpLua.Lua.LuaState luaState, int index)
{
SharpLua.Lua.lua_remove(luaState, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_gettable(SharpLua.Lua.LuaState luaState, int index)
{
SharpLua.Lua.lua_gettable(luaState, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_rawget(SharpLua.Lua.LuaState luaState, int index)
{
SharpLua.Lua.lua_rawget(luaState, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_settable(SharpLua.Lua.LuaState luaState, int index)
{
SharpLua.Lua.lua_settable(luaState, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_rawset(SharpLua.Lua.LuaState luaState, int index)
{
SharpLua.Lua.lua_rawset(luaState, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_setmetatable(SharpLua.Lua.LuaState luaState, int objIndex)
{
SharpLua.Lua.lua_setmetatable(luaState, objIndex);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static int lua_getmetatable(SharpLua.Lua.LuaState luaState, int objIndex)
{
return SharpLua.Lua.lua_getmetatable(luaState, objIndex);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static int lua_equal(SharpLua.Lua.LuaState luaState, int index1, int index2)
{
return SharpLua.Lua.lua_equal(luaState, index1, index2);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_pushvalue(SharpLua.Lua.LuaState luaState, int index)
{
SharpLua.Lua.lua_pushvalue(luaState, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_replace(SharpLua.Lua.LuaState luaState, int index)
{
SharpLua.Lua.lua_replace(luaState, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static int lua_gettop(SharpLua.Lua.LuaState luaState)
{
return SharpLua.Lua.lua_gettop(luaState);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static LuaTypes lua_type(SharpLua.Lua.LuaState luaState, int index)
{
return (LuaTypes)SharpLua.Lua.lua_type(luaState, index);
}
public static bool lua_isnil(SharpLua.Lua.LuaState luaState, int index)
{
return (LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TNIL);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static bool lua_isnumber(SharpLua.Lua.LuaState luaState, int index)
{
return (LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TNUMBER);
}
public static bool lua_isboolean(SharpLua.Lua.LuaState luaState, int index)
{
return LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TBOOLEAN;
}
//[DllImport(LUALIBDLL,CallingConvention=CallingConvention.Cdecl)]
public static int luaL_ref(SharpLua.Lua.LuaState luaState, int registryIndex)
{
return SharpLua.Lua.luaL_ref(luaState, registryIndex);
}
public static int lua_ref(SharpLua.Lua.LuaState luaState, int lockRef)
{
if (lockRef != 0)
{
return LuaDLL.luaL_ref(luaState, LuaIndexes.LUA_REGISTRYINDEX);
}
else return 0;
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_rawgeti(SharpLua.Lua.LuaState luaState, int tableIndex, int index)
{
SharpLua.Lua.lua_rawgeti(luaState, tableIndex, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_rawseti(SharpLua.Lua.LuaState luaState, int tableIndex, int index)
{
SharpLua.Lua.lua_rawseti(luaState, tableIndex, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static object lua_newuserdata(SharpLua.Lua.LuaState luaState, int size)
{
return SharpLua.Lua.lua_newuserdata(luaState, (uint)size);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static object lua_touserdata(SharpLua.Lua.LuaState luaState, int index)
{
return SharpLua.Lua.lua_touserdata(luaState, index);
}
public static void lua_getref(SharpLua.Lua.LuaState luaState, int reference)
{
LuaDLL.lua_rawgeti(luaState, LuaIndexes.LUA_REGISTRYINDEX, reference);
}
//[DllImport(LUALIBDLL,CallingConvention=CallingConvention.Cdecl)]
public static void luaL_unref(SharpLua.Lua.LuaState luaState, int registryIndex, int reference)
{
SharpLua.Lua.luaL_unref(luaState, registryIndex, reference);
}
public static void lua_unref(SharpLua.Lua.LuaState luaState, int reference)
{
LuaDLL.luaL_unref(luaState, LuaIndexes.LUA_REGISTRYINDEX, reference);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static bool lua_isstring(SharpLua.Lua.LuaState luaState, int index)
{
return SharpLua.Lua.lua_isstring(luaState, index) != 0;
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static bool lua_iscfunction(SharpLua.Lua.LuaState luaState, int index)
{
return SharpLua.Lua.lua_iscfunction(luaState, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_pushnil(SharpLua.Lua.LuaState luaState)
{
SharpLua.Lua.lua_pushnil(luaState);
}
//[DllImport(STUBDLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_pushstdcallcfunction(SharpLua.Lua.LuaState luaState, SharpLua.Lua.lua_CFunction function)
{
SharpLua.Lua.lua_pushcfunction(luaState, function);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_call(SharpLua.Lua.LuaState luaState, int nArgs, int nResults)
{
SharpLua.Lua.lua_call(luaState, nArgs, nResults);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static int lua_pcall(SharpLua.Lua.LuaState luaState, int nArgs, int nResults, int errfunc)
{
return SharpLua.Lua.lua_pcall(luaState, nArgs, nResults, errfunc);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
//not wrapped
//public static extern int lua_rawcall(SharpLua.Lua.lua_State luaState, int nArgs, int nResults)
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static SharpLua.Lua.lua_CFunction lua_tocfunction(SharpLua.Lua.LuaState luaState, int index)
{
return SharpLua.Lua.lua_tocfunction(luaState, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static double lua_tonumber(SharpLua.Lua.LuaState luaState, int index)
{
return SharpLua.Lua.lua_tonumber(luaState, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static bool lua_toboolean(SharpLua.Lua.LuaState luaState, int index)
{
return SharpLua.Lua.lua_toboolean(luaState, index) != 0;
}
//[DllImport(LUADLL,CallingConvention = CallingConvention.Cdecl)]
//unwrapped
//public static IntPtr lua_tolstring(SharpLua.Lua.lua_State luaState, int index, out int strLen)
public static string lua_tostring(SharpLua.Lua.LuaState luaState, int index)
{
#if true
// FIXME use the same format string as lua i.e. LUA_NUMBER_FMT
LuaTypes t = lua_type(luaState, index);
if (t == LuaTypes.LUA_TNUMBER)
return string.Format("{0}", lua_tonumber(luaState, index));
else if (t == LuaTypes.LUA_TSTRING)
{
uint strlen;
return SharpLua.Lua.lua_tolstring(luaState, index, out strlen).ToString();
}
else if (t == LuaTypes.LUA_TNIL)
return null; // treat lua nulls to as C# nulls
else
return "0"; // Because luaV_tostring does this
#else
size_t strlen;
// Note! This method will _change_ the representation of the object on the stack to a string.
// We do not want this behavior so we do the conversion ourselves
const char *str = Lua.lua_tolstring(luaState, index, &strlen);
if (str)
return Marshal::PtrToStringAnsi(IntPtr((char *) str), strlen);
else
return nullptr; // treat lua nulls to as C# nulls
#endif
}
//[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static Lua.lua_CFunction lua_atpanic(SharpLua.Lua.LuaState luaState, SharpLua.Lua.lua_CFunction panicf)
{
return SharpLua.Lua.lua_atpanic(luaState, panicf);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_pushnumber(SharpLua.Lua.LuaState luaState, double number)
{
SharpLua.Lua.lua_pushnumber(luaState, number);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_pushboolean(SharpLua.Lua.LuaState luaState, bool value)
{
SharpLua.Lua.lua_pushboolean(luaState, value ? 1 : 0);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
// Not yet wrapped
//public static void lua_pushlstring(SharpLua.Lua.lua_State luaState, string str, int size);
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_pushstring(SharpLua.Lua.LuaState luaState, string str)
{
SharpLua.Lua.lua_pushstring(luaState, str);
}
//[DllImport(LUALIBDLL,CallingConvention=CallingConvention.Cdecl)]
public static int luaL_newmetatable(SharpLua.Lua.LuaState luaState, string meta)
{
return SharpLua.Lua.luaL_newmetatable(luaState, meta);
}
// steffenj: BEGIN Lua 5.1.1 API change (luaL_getmetatable is now a macro using lua_getfield)
//[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static void lua_getfield(SharpLua.Lua.LuaState luaState, int stackPos, string meta)
{
SharpLua.Lua.lua_getfield(luaState, stackPos, meta);
}
public static void luaL_getmetatable(SharpLua.Lua.LuaState luaState, string meta)
{
LuaDLL.lua_getfield(luaState, LuaIndexes.LUA_REGISTRYINDEX, meta);
}
// steffenj: END Lua 5.1.1 API change (luaL_getmetatable is now a macro using lua_getfield)
//[DllImport(LUALIBDLL, CallingConvention = CallingConvention.Cdecl)]
public static Object luaL_checkudata(SharpLua.Lua.LuaState luaState, int stackPos, string meta)
{
return SharpLua.Lua.luaL_checkudata(luaState, stackPos, meta);
}
//[DllImport(LUALIBDLL,CallingConvention=CallingConvention.Cdecl)]
public static bool luaL_getmetafield(SharpLua.Lua.LuaState luaState, int stackPos, string field)
{
return SharpLua.Lua.luaL_getmetafield(luaState, stackPos, field) != 0;
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
//not yet wrapped
//public static extern int lua_load(SharpLua.Lua.lua_State luaState, LuaChunkReader chunkReader, ref ReaderInfo data, string chunkName);
//[DllImport(LUALIBDLL,CallingConvention=CallingConvention.Cdecl)]
public static int luaL_loadbuffer(SharpLua.Lua.LuaState luaState, string buff, int size, string name)
{
return SharpLua.Lua.luaL_loadbuffer(luaState, buff, (uint)size, name);
}
public static int luaL_loadbuffer(SharpLua.Lua.LuaState luaState, char[] buff, int size, string name)
{
return SharpLua.Lua.luaL_loadbuffer(luaState, buff, (uint)size, name);
}
//[DllImport(LUALIBDLL,CallingConvention=CallingConvention.Cdecl)]
public static int luaL_loadfile(SharpLua.Lua.LuaState luaState, string filename)
{
return SharpLua.Lua.luaL_loadfile(luaState, filename);
}
//[DllImport(STUBDLL,CallingConvention=CallingConvention.Cdecl)]
public static bool luaL_checkmetatable(SharpLua.Lua.LuaState luaState, int index)
{
bool retVal = false;
if (lua_getmetatable(luaState, index) != 0)
{
lua_pushlightuserdata(luaState, luanet_gettag());
lua_rawget(luaState, -2);
retVal = !lua_isnil(luaState, -1);
lua_settop(luaState, -3);
}
return retVal;
}
//[DllImport(STUBDLL,CallingConvention=CallingConvention.Cdecl)]
public static void luanet_newudata(SharpLua.Lua.LuaState luaState, int val)
{
byte[] userdata = lua_newuserdata(luaState, sizeof(int)) as byte[];
intToFourBytes(val, userdata);
}
//[DllImport(STUBDLL,CallingConvention=CallingConvention.Cdecl)]
public static int luanet_tonetobject(SharpLua.Lua.LuaState luaState, int index)
{
byte[] udata;
if (lua_type(luaState, index) == LuaTypes.LUA_TUSERDATA)
{
if (luaL_checkmetatable(luaState, index))
{
udata = lua_touserdata(luaState, index) as byte[];
if (udata != null)
{
return fourBytesToInt(udata);
}
}
udata = checkudata_raw(luaState, index, "luaNet_class") as byte[];
if (udata != null) return fourBytesToInt(udata);
udata = checkudata_raw(luaState, index, "luaNet_searchbase") as byte[];
if (udata != null) return fourBytesToInt(udata);
udata = checkudata_raw(luaState, index, "luaNet_function") as byte[];
if (udata != null) return fourBytesToInt(udata);
}
return -1;
}
//[DllImport(STUBDLL,CallingConvention=CallingConvention.Cdecl)]
public static int luanet_rawnetobj(SharpLua.Lua.LuaState luaState, int obj)
{
byte[] bytes = lua_touserdata(luaState, obj) as byte[];
return fourBytesToInt(bytes);
}
//[DllImport(STUBDLL,CallingConvention=CallingConvention.Cdecl)]
public static int luanet_checkudata(SharpLua.Lua.LuaState luaState, int ud, string tname)
{
object udata = checkudata_raw(luaState, ud, tname);
if (udata != null) return fourBytesToInt(udata as byte[]);
return -1;
}
//[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static bool lua_checkstack(SharpLua.Lua.LuaState luaState, int extra)
{
return SharpLua.Lua.lua_checkstack(luaState, extra) != 0;
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static int lua_next(SharpLua.Lua.LuaState luaState, int index)
{
return SharpLua.Lua.lua_next(luaState, index);
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void lua_pushlightuserdata(SharpLua.Lua.LuaState luaState, Object udata)
{
SharpLua.Lua.lua_pushlightuserdata(luaState, udata);
}
//[DllImport(STUBDLL,CallingConvention=CallingConvention.Cdecl)]
public static Object luanet_gettag()
{
return "_TAG_"; //0;
}
//[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static void luaL_where(SharpLua.Lua.LuaState luaState, int level)
{
SharpLua.Lua.luaL_where(luaState, level);
}
private static int fourBytesToInt(byte[] bytes)
{
return bytes[0] + (bytes[1] << 8) + (bytes[2] << 16) + (bytes[3] << 24);
}
private static void intToFourBytes(int val, byte[] bytes)
{
// gfoot: is this really a good idea?
bytes[0] = (byte)val;
bytes[1] = (byte)(val >> 8);
bytes[2] = (byte)(val >> 16);
bytes[3] = (byte)(val >> 24);
}
private static object checkudata_raw(SharpLua.Lua.LuaState L, int ud, string tname)
{
object p = SharpLua.Lua.lua_touserdata(L, ud);
if (p != null)
{ /* value is a userdata? */
if (SharpLua.Lua.lua_getmetatable(L, ud) != 0)
{
bool isEqual;
/* does it have a metatable? */
SharpLua.Lua.lua_getfield(L, (int)LuaIndexes.LUA_REGISTRYINDEX, tname); /* get correct metatable */
isEqual = SharpLua.Lua.lua_rawequal(L, -1, -2) != 0;
// NASTY - we need our own version of the lua_pop macro
// lua_pop(L, 2); /* remove both metatables */
SharpLua.Lua.lua_settop(L, -(2) - 1);
if (isEqual) /* does it have the correct mt? */
return p;
}
}
return null;
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudioTools.Navigation;
using Microsoft.VisualStudioTools.Project;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudioTools {
public abstract class CommonPackage : AsyncPackage, IOleComponent {
private uint _componentID;
private LibraryManager _libraryManager;
private IOleComponentManager _compMgr;
private UIThreadBase _uiThread;
private static readonly object _commandsLock = new object();
private static readonly Dictionary<Command, MenuCommand> _commands = new Dictionary<Command, MenuCommand>();
#region Language-specific abstracts
public abstract Type GetLibraryManagerType();
internal abstract LibraryManager CreateLibraryManager();
public abstract bool IsRecognizedFile(string filename);
// TODO:
// public abstract bool TryGetStartupFileAndDirectory(out string filename, out string dir);
#endregion
internal CommonPackage() {
#if DEBUG
AppDomain.CurrentDomain.UnhandledException += (sender, e) => {
if (e.IsTerminating) {
var ex = e.ExceptionObject as Exception;
if (ex is SEHException) {
return;
}
if (ex != null) {
Debug.Fail(
string.Format("An unhandled exception is about to terminate the process:\n\n{0}", ex.Message),
ex.ToString()
);
} else {
Debug.Fail(string.Format(
"An unhandled exception is about to terminate the process:\n\n{0}",
e.ExceptionObject
));
}
}
};
#endif
}
internal static Dictionary<Command, MenuCommand> Commands => _commands;
internal static object CommandsLock => _commandsLock;
protected override void Dispose(bool disposing) {
_uiThread?.MustBeCalledFromUIThreadOrThrow();
try {
if (_componentID != 0)
{
_compMgr.FRevokeComponent(_componentID);
_componentID = 0;
}
if (_libraryManager != null)
{
_libraryManager.Dispose();
_libraryManager = null;
}
} finally {
base.Dispose(disposing);
}
}
private object CreateLibraryManager(IServiceContainer container, Type serviceType) {
if (GetLibraryManagerType() != serviceType) {
return null;
}
return _libraryManager = CreateLibraryManager();
}
internal void RegisterCommands(Guid cmdSet, params Command[] commands) {
_uiThread.MustBeCalledFromUIThreadOrThrow();
if (GetService(typeof(IMenuCommandService)) is OleMenuCommandService mcs) {
lock (_commandsLock) {
foreach (var command in commands) {
var beforeQueryStatus = command.BeforeQueryStatus;
CommandID toolwndCommandID = new CommandID(cmdSet, command.CommandId);
OleMenuCommand menuToolWin = new OleMenuCommand(command.DoCommand, toolwndCommandID);
if (beforeQueryStatus != null) {
menuToolWin.BeforeQueryStatus += beforeQueryStatus;
}
mcs.AddCommand(menuToolWin);
_commands[command] = menuToolWin;
}
}
}
}
internal void RegisterCommands(params MenuCommand[] commands) {
_uiThread.MustBeCalledFromUIThreadOrThrow();
if (GetService(typeof(IMenuCommandService)) is OleMenuCommandService mcs) {
foreach (var command in commands) {
mcs.AddCommand(command);
}
}
}
/// <summary>
/// Gets the current IWpfTextView that is the active document.
/// </summary>
/// <returns></returns>
public static IWpfTextView GetActiveTextView(System.IServiceProvider serviceProvider) {
var monitorSelection = (IVsMonitorSelection)serviceProvider.GetService(typeof(SVsShellMonitorSelection));
if (monitorSelection == null) {
return null;
}
if (ErrorHandler.Failed(monitorSelection.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out var curDocument))) {
// TODO: Report error
return null;
}
if (!(curDocument is IVsWindowFrame frame)) {
// TODO: Report error
return null;
}
if (ErrorHandler.Failed(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out var docView))) {
// TODO: Report error
return null;
}
#if DEV11_OR_LATER
if (docView is IVsDifferenceCodeWindow diffWindow && diffWindow.DifferenceViewer != null) {
switch (diffWindow.DifferenceViewer.ActiveViewType) {
case VisualStudio.Text.Differencing.DifferenceViewType.InlineView:
return diffWindow.DifferenceViewer.InlineView;
case VisualStudio.Text.Differencing.DifferenceViewType.LeftView:
return diffWindow.DifferenceViewer.LeftView;
case VisualStudio.Text.Differencing.DifferenceViewType.RightView:
return diffWindow.DifferenceViewer.RightView;
default:
return null;
}
}
#endif
if (docView is IVsCodeWindow window) {
if (ErrorHandler.Failed(window.GetPrimaryView(out IVsTextView textView))) {
// TODO: Report error
return null;
}
var model = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
var adapterFactory = model.GetService<IVsEditorAdaptersFactoryService>();
var wpfTextView = adapterFactory.GetWpfTextView(textView);
return wpfTextView;
}
return null;
}
internal static CommonProjectNode GetStartupProject(System.IServiceProvider serviceProvider) {
var buildMgr = (IVsSolutionBuildManager)serviceProvider.GetService(typeof(IVsSolutionBuildManager));
if (buildMgr != null && ErrorHandler.Succeeded(buildMgr.get_StartupProject(out var hierarchy)) && hierarchy != null) {
return hierarchy.GetProject()?.GetCommonProject();
}
return null;
}
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) {
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
_uiThread = (UIThreadBase)GetService(typeof(UIThreadBase));
if (_uiThread == null) {
_uiThread = new UIThread(JoinableTaskFactory);
AddService<UIThreadBase>(_uiThread, true);
}
var libraryManagerType = GetLibraryManagerType();
if (libraryManagerType != null) {
AddService(libraryManagerType, CreateLibraryManager, true);
}
var crinfo = new OLECRINFO {
cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO)),
grfcrf = (uint)_OLECRF.olecrfNeedIdleTime,
grfcadvf = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff,
uIdleTimeInterval = 0
};
_compMgr = (IOleComponentManager)GetService(typeof(SOleComponentManager));
ErrorHandler.ThrowOnFailure(_compMgr.FRegisterComponent(this, new[] { crinfo }, out _componentID));
await base.InitializeAsync(cancellationToken, progress);
}
protected override object GetService(Type serviceType)
=> serviceType == typeof(UIThreadBase) ? _uiThread : base.GetService(serviceType);
protected void AddService<T>(object service, bool promote)
=> ((IServiceContainer)this).AddService(typeof(T), service, promote);
protected void AddService<T>(ServiceCreatorCallback callback, bool promote)
=> ((IServiceContainer)this).AddService(typeof(T), callback, promote);
protected void AddService(Type serviceType, ServiceCreatorCallback callback, bool promote)
=> ((IServiceContainer)this).AddService(serviceType, callback, promote);
internal static void OpenWebBrowser(System.IServiceProvider serviceProvider, string url) {
// TODO: In a future VS 2017 release, SVsWebBrowsingService will have the ability
// to open in an external browser, and we may want to switch to using that, as it
// may be safer/better than Process.Start.
serviceProvider.GetUIThread().Invoke(() => {
try {
var uri = new Uri(url);
Process.Start(new ProcessStartInfo(uri.AbsoluteUri));
} catch (Exception ex) when (!ex.IsCriticalException()) {
Utilities.ShowMessageBox(
serviceProvider,
SR.GetString(SR.WebBrowseNavigateError, url, ex.Message),
null,
OLEMSGICON.OLEMSGICON_CRITICAL,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
);
}
});
}
internal static void OpenVsWebBrowser(System.IServiceProvider serviceProvider, string url) {
serviceProvider.GetUIThread().Invoke(() => {
var web = serviceProvider.GetService(typeof(SVsWebBrowsingService)) as IVsWebBrowsingService;
if (web == null) {
OpenWebBrowser(serviceProvider, url);
return;
}
try {
IVsWindowFrame frame;
ErrorHandler.ThrowOnFailure(web.Navigate(url, (uint)__VSWBNAVIGATEFLAGS.VSNWB_ForceNew, out frame));
frame.Show();
} catch (Exception ex) when (!ex.IsCriticalException()) {
Utilities.ShowMessageBox(
serviceProvider,
SR.GetString(SR.WebBrowseNavigateError, url, ex.Message),
null,
OLEMSGICON.OLEMSGICON_CRITICAL,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
);
}
});
}
#region IOleComponent Members
public int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked) => 1;
public int FDoIdle(uint grfidlef) {
var componentManager = _compMgr;
if (componentManager == null) {
return 0;
}
_libraryManager?.OnIdle(componentManager);
OnIdle?.Invoke(this, new ComponentManagerEventArgs(componentManager));
return 0;
}
internal event EventHandler<ComponentManagerEventArgs> OnIdle;
public int FPreTranslateMessage(MSG[] pMsg) => 0;
public int FQueryTerminate(int fPromptUser) => 1;
public int FReserved1(uint dwReserved, uint message, IntPtr wParam, IntPtr lParam) => 1;
public IntPtr HwndGetWindow(uint dwWhich, uint dwReserved) => IntPtr.Zero;
public void OnActivationChange(IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved) { }
public void OnAppActivate(int fActive, uint dwOtherThreadID) { }
public void OnEnterState(uint uStateID, int fEnter) { }
public void OnLoseActivation() { }
public void Terminate() { }
#endregion
}
internal sealed class ComponentManagerEventArgs : EventArgs {
public ComponentManagerEventArgs(IOleComponentManager compMgr) {
ComponentManager = compMgr;
}
public IOleComponentManager ComponentManager { get; }
}
}
| |
using System;
using Microsoft.Xna.Framework;
namespace Operation_Cronos.Display {
public enum CameraDirection {
None,
Up,
Down,
Left,
Right,
UpLeft,
UpRight,
DownLeft,
DownRight
}
public enum CameraStatus
{
Stopped,
Dragged,
MouseScrolled,
KeyboardScrolled
}
public class Camera : Microsoft.Xna.Framework.GameComponent {
public event EventHandler OnMove = delegate { };
#region Fields
/// <summary>
/// The moving speed of the camera.
/// </summary>
public static float Speed = 8f;
private Matrix worldProjection;
private Vector2 position;
private Vector2 direction;
private CameraDirection cameraDirection;
private Rectangle screenSize;
private bool frozen;
private CameraStatus status;
private Point draggingMousePos;
#endregion
#region Constructor
public Camera(Game game)
: base(game) {
Game.Components.Add(this);
position = new Vector2(20, 0);
direction = Vector2.Zero;
frozen = false;
}
#endregion
#region Properties
public Point MouseDraggingPosition
{
get { return draggingMousePos; }
set { draggingMousePos = value; }
}
public CameraStatus CameraStatus
{
get { return status; }
set { status = value; }
}
/// <summary>
/// The world positions of the camera.
/// </summary>
public Vector2 Position {
get {
return position;
}
set {
position = new Vector2((float)Math.Round(value.X), (float)Math.Round(value.Y));
worldProjection = Matrix.CreateTranslation(-Position.X, -Position.Y, 0f);
}
}
/// <summary>
/// Wraps up the process of setting the camera moving direction.
/// </summary>
public CameraDirection Direction {
get {
return cameraDirection;
}
set {
cameraDirection = value;
switch (cameraDirection) {
case CameraDirection.None:
direction = Vector2.Zero;
break;
case CameraDirection.Left:
direction = Vector2.Normalize(new Vector2(-1, 0));
break;
case CameraDirection.Right:
direction = Vector2.Normalize(new Vector2(1, 0));
break;
case CameraDirection.Up:
direction = Vector2.Normalize(new Vector2(0, -1));
break;
case CameraDirection.Down:
direction = Vector2.Normalize(new Vector2(0, 1));
break;
case CameraDirection.UpRight:
direction = Vector2.Normalize(new Vector2(1, -1));
break;
case CameraDirection.UpLeft:
direction = Vector2.Normalize(new Vector2(-1, -1));
break;
case CameraDirection.DownRight:
direction = Vector2.Normalize(new Vector2(1, 1));
break;
case CameraDirection.DownLeft:
direction = Vector2.Normalize(new Vector2(-1, 1));
break;
}
}
}
/// <summary>
/// The view of the camera.
/// </summary>
public Matrix WorldProjection {
get {
return worldProjection;
}
set {
}
}
public Rectangle Screen {
get { return new Rectangle((int)Position.X, (int)Position.Y, screenSize.Width, screenSize.Height); }
set { screenSize = value; }
}
#endregion
#region Overrides
public override void Initialize() {
base.Initialize();
Screen = new Rectangle(0, 0, Game.GraphicsDevice.Viewport.Width, Game.GraphicsDevice.Viewport.Height);
}
public override void Update(GameTime gameTime)
{
HandleCameraMovement();
base.Update(gameTime);
}
#endregion
#region Methods
/// <summary>
/// Makes all the transformations regarding camera movemement.
/// </summary>
private void HandleCameraMovement()
{
if (frozen == false)
{
if ((cameraDirection == CameraDirection.Left ||
cameraDirection == CameraDirection.UpLeft ||
cameraDirection == CameraDirection.DownLeft) && position.X <= Speed)
{
Position = new Vector2(0, position.Y);
Direction = CameraDirection.None;
OnMove(this, new EventArgs());
}
if ((cameraDirection == CameraDirection.Up ||
cameraDirection == CameraDirection.UpLeft ||
cameraDirection == CameraDirection.UpRight) && position.Y <= Speed)
{
Position = new Vector2(position.X, 0);
Direction = CameraDirection.None;
OnMove(this, new EventArgs());
}
if ((cameraDirection == CameraDirection.Down ||
cameraDirection == CameraDirection.DownLeft ||
cameraDirection == CameraDirection.DownRight) && position.Y >= ((GameMap)Game.Services.GetService(typeof(GameMap))).Height - Speed - Screen.Height)
{
Position = new Vector2(position.X, ((GameMap)Game.Services.GetService(typeof(GameMap))).Height - Screen.Height);
Direction = CameraDirection.None;
OnMove(this, new EventArgs());
}
if ((cameraDirection == CameraDirection.Right ||
cameraDirection == CameraDirection.DownRight ||
cameraDirection == CameraDirection.UpRight) && position.X >= ((GameMap)Game.Services.GetService(typeof(GameMap))).Width - Speed - Screen.Width)
{
Position = new Vector2(((GameMap)Game.Services.GetService(typeof(GameMap))).Width - Screen.Width, position.Y);
Direction = CameraDirection.None;
OnMove(this, new EventArgs());
}
Position += Camera.Speed * direction;
if (direction != Vector2.Zero)
{
OnMove(this, new EventArgs());
}
if (CameraStatus == CameraStatus.Dragged)
{
OnMove(this, new EventArgs());
}
}
}
/*
public CameraDirection AddDirection(CameraDirection first, CameraDirection second)
{
switch (first)
{
case CameraDirection.None:
return second;
case CameraDirection.Up:
switch (second)
{
case CameraDirection.None:
return CameraDirection.Up;
case CameraDirection.Left:
return CameraDirection.UpLeft;
case CameraDirection.Right:
return CameraDirection.UpRight;
case CameraDirection.Up:
return CameraDirection.Up;
case CameraDirection.Down:
return CameraDirection.Down;
}
case CameraDirection.Down:
switch (second)
{
case CameraDirection.None:
return CameraDirection.Down;
case CameraDirection.Left:
return CameraDirection.DownLeft;
case CameraDirection.Right:
return CameraDirection.DownRight;
case CameraDirection.Up:
return CameraDirection.Up;
case CameraDirection.Down:
return CameraDirection.Down;
}
case CameraDirection.Left:
switch (second)
{
case CameraDirection.None:
return CameraDirection.Left;
case CameraDirection.Left:
return CameraDirection.Left;
case CameraDirection.Right:
return CameraDirection.Right;
case CameraDirection.Up:
return CameraDirection.UpLeft;
case CameraDirection.Down:
return CameraDirection.DownLeft;
}
case CameraDirection.Right:
switch (second)
{
case CameraDirection.None:
return CameraDirection.Right;
case CameraDirection.Left:
return CameraDirection.Left;
case CameraDirection.Right:
return CameraDirection.Right;
case CameraDirection.Up:
return CameraDirection.UpRight;
case CameraDirection.Down:
return CameraDirection.DownRight;
}
default:
return CameraDirection.None;
}
}
public CameraDirection SubstractDirection(CameraDirection first, CameraDirection second)
{
switch (first)
{
case CameraDirection.None:
return second;
case CameraDirection.Up:
switch (second)
{
case CameraDirection.None:
return CameraDirection.Up;
case CameraDirection.Left:
return CameraDirection.UpLeft;
case CameraDirection.Right:
return CameraDirection.UpRight;
case CameraDirection.Up:
return CameraDirection.Up;
case CameraDirection.Down:
return CameraDirection.Down;
}
case CameraDirection.Down:
switch (second)
{
case CameraDirection.None:
return CameraDirection.Down;
case CameraDirection.Left:
return CameraDirection.DownLeft;
case CameraDirection.Right:
return CameraDirection.DownRight;
case CameraDirection.Up:
return CameraDirection.Up;
case CameraDirection.Down:
return CameraDirection.Down;
}
case CameraDirection.Left:
switch (second)
{
case CameraDirection.None:
return CameraDirection.Left;
case CameraDirection.Left:
return CameraDirection.Left;
case CameraDirection.Right:
return CameraDirection.Right;
case CameraDirection.Up:
return CameraDirection.UpLeft;
case CameraDirection.Down:
return CameraDirection.DownLeft;
}
case CameraDirection.Right:
switch (second)
{
case CameraDirection.None:
return CameraDirection.Right;
case CameraDirection.Left:
return CameraDirection.Left;
case CameraDirection.Right:
return CameraDirection.Right;
case CameraDirection.Up:
return CameraDirection.UpRight;
case CameraDirection.Down:
return CameraDirection.DownRight;
}
default:
return CameraDirection.None;
}
}
*/
public Boolean ContainsObject(Rectangle bounds) {
return Screen.Intersects(bounds);
}
public Boolean ContainsPoint(Point position) {
return Screen.Contains(position);
}
public void ChangeResolution(int width, int height) {
GraphicsDeviceManager graphics = (GraphicsDeviceManager)Game.Services.GetService(typeof(GraphicsDeviceManager));
graphics.PreferredBackBufferWidth = width;
graphics.PreferredBackBufferHeight = height;
Screen = new Rectangle(0, 0, width, height);
graphics.ApplyChanges();
}
public Boolean Fullscreen {
get {
GraphicsDeviceManager graphics = (GraphicsDeviceManager)Game.Services.GetService(typeof(GraphicsDeviceManager));
return graphics.IsFullScreen;
}
set {
GraphicsDeviceManager graphics = (GraphicsDeviceManager)Game.Services.GetService(typeof(GraphicsDeviceManager));
graphics.IsFullScreen = value;
graphics.ApplyChanges();
}
}
public void Freeze() {
frozen = true;
}
public void Unfreeze() {
frozen = false;
}
#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;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudioTools.Project.Automation
{
/// <summary>
/// This can navigate a collection object only (partial implementation of ProjectItems interface)
/// </summary>
[ComVisible(true)]
public class OANavigableProjectItems : EnvDTE.ProjectItems
{
#region fields
private OAProject project;
private HierarchyNode nodeWithItems;
#endregion
#region properties
/// <summary>
/// Defines a relationship to the associated project.
/// </summary>
internal OAProject Project => this.project;
/// <summary>
/// Defines the node that contains the items
/// </summary>
internal HierarchyNode NodeWithItems => this.nodeWithItems;
#endregion
#region ctor
/// <summary>
/// Constructor.
/// </summary>
/// <param name="project">The associated project.</param>
/// <param name="nodeWithItems">The node that defines the items.</param>
internal OANavigableProjectItems(OAProject project, HierarchyNode nodeWithItems)
{
this.project = project;
this.nodeWithItems = nodeWithItems;
}
#endregion
#region EnvDTE.ProjectItems
/// <summary>
/// Gets a value indicating the number of objects in the collection.
/// </summary>
public virtual int Count
{
get
{
var count = 0;
this.project.ProjectNode.Site.GetUIThread().Invoke(() =>
{
for (var child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling)
{
if (!child.IsNonMemberItem && child.GetAutomationObject() is EnvDTE.ProjectItem)
{
count += 1;
}
}
});
return count;
}
}
/// <summary>
/// Gets the immediate parent object of a ProjectItems collection.
/// </summary>
public virtual object Parent => this.nodeWithItems.GetAutomationObject();
/// <summary>
/// Gets an enumeration indicating the type of object.
/// </summary>
public virtual string Kind =>
// TODO: Add OAProjectItems.Kind getter implementation
null;
/// <summary>
/// Gets the top-level extensibility object.
/// </summary>
public virtual EnvDTE.DTE DTE => (EnvDTE.DTE)this.project.DTE;
/// <summary>
/// Gets the project hosting the project item or items.
/// </summary>
public virtual EnvDTE.Project ContainingProject => this.project;
/// <summary>
/// Adds one or more ProjectItem objects from a directory to the ProjectItems collection.
/// </summary>
/// <param name="directory">The directory from which to add the project item.</param>
/// <returns>A ProjectItem object.</returns>
public virtual EnvDTE.ProjectItem AddFromDirectory(string directory)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates a new project item from an existing item template file and adds it to the project.
/// </summary>
/// <param name="fileName">The full path and file name of the template project file.</param>
/// <param name="name">The file name to use for the new project item.</param>
/// <returns>A ProjectItem object. </returns>
public virtual EnvDTE.ProjectItem AddFromTemplate(string fileName, string name)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates a new folder in Solution Explorer.
/// </summary>
/// <param name="name">The name of the folder node in Solution Explorer.</param>
/// <param name="kind">The type of folder to add. The available values are based on vsProjectItemsKindConstants and vsProjectItemKindConstants</param>
/// <returns>A ProjectItem object.</returns>
public virtual EnvDTE.ProjectItem AddFolder(string name, string kind)
{
throw new NotImplementedException();
}
/// <summary>
/// Copies a source file and adds it to the project.
/// </summary>
/// <param name="filePath">The path and file name of the project item to be added.</param>
/// <returns>A ProjectItem object. </returns>
public virtual EnvDTE.ProjectItem AddFromFileCopy(string filePath)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a project item from a file that is installed in a project directory structure.
/// </summary>
/// <param name="fileName">The file name of the item to add as a project item. </param>
/// <returns>A ProjectItem object. </returns>
public virtual EnvDTE.ProjectItem AddFromFile(string fileName)
{
throw new NotImplementedException();
}
/// <summary>
/// Get Project Item from index
/// </summary>
/// <param name="index">Either index by number (1-based) or by name can be used to get the item</param>
/// <returns>Project Item. ArgumentException if invalid index is specified</returns>
public virtual EnvDTE.ProjectItem Item(object index)
{
// Changed from MPFProj: throws ArgumentException instead of returning null (http://mpfproj10.codeplex.com/workitem/9158)
if (index is int)
{
var realIndex = (int)index - 1;
if (realIndex >= 0)
{
for (var child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling)
{
if (child.IsNonMemberItem)
{
continue;
}
var item = child.GetAutomationObject() as EnvDTE.ProjectItem;
if (item != null)
{
if (realIndex == 0)
{
return item;
}
realIndex -= 1;
}
}
}
}
else if (index is string)
{
var name = (string)index;
for (var child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling)
{
if (child.IsNonMemberItem)
{
continue;
}
var item = child.GetAutomationObject() as EnvDTE.ProjectItem;
if (item != null && StringComparer.OrdinalIgnoreCase.Equals(item.Name, name))
{
return item;
}
}
}
throw new ArgumentException("Failed to find item: " + index);
}
/// <summary>
/// Returns an enumeration for items in a collection.
/// </summary>
/// <returns>An IEnumerator for this object.</returns>
public virtual IEnumerator GetEnumerator()
{
for (var child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling)
{
if (child.IsNonMemberItem)
{
continue;
}
var item = child.GetAutomationObject() as EnvDTE.ProjectItem;
if (item != null)
{
yield return item;
}
}
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
namespace Microsoft.AzureStack.Management
{
public static partial class ManagedLocationOperationsExtensions
{
/// <summary>
/// Create / Update the location.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedLocationOperations.
/// </param>
/// <param name='parameters'>
/// Required. Location properties
/// </param>
/// <returns>
/// The location update result.
/// </returns>
public static ManagedLocationCreateOrUpdateResult CreateOrUpdate(this IManagedLocationOperations operations, ManagedLocationCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedLocationOperations)s).CreateOrUpdateAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create / Update the location.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedLocationOperations.
/// </param>
/// <param name='parameters'>
/// Required. Location properties
/// </param>
/// <returns>
/// The location update result.
/// </returns>
public static Task<ManagedLocationCreateOrUpdateResult> CreateOrUpdateAsync(this IManagedLocationOperations operations, ManagedLocationCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Delete a location.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedLocationOperations.
/// </param>
/// <param name='locationName'>
/// Required. Name of location to delete.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IManagedLocationOperations operations, string locationName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedLocationOperations)s).DeleteAsync(locationName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a location.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedLocationOperations.
/// </param>
/// <param name='locationName'>
/// Required. Name of location to delete.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IManagedLocationOperations operations, string locationName)
{
return operations.DeleteAsync(locationName, CancellationToken.None);
}
/// <summary>
/// Get the location.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedLocationOperations.
/// </param>
/// <param name='locationName'>
/// Required. The location name.
/// </param>
/// <returns>
/// Location get result.
/// </returns>
public static ManagedLocationGetResult Get(this IManagedLocationOperations operations, string locationName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedLocationOperations)s).GetAsync(locationName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the location.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedLocationOperations.
/// </param>
/// <param name='locationName'>
/// Required. The location name.
/// </param>
/// <returns>
/// Location get result.
/// </returns>
public static Task<ManagedLocationGetResult> GetAsync(this IManagedLocationOperations operations, string locationName)
{
return operations.GetAsync(locationName, CancellationToken.None);
}
/// <summary>
/// Get locations under subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedLocationOperations.
/// </param>
/// <returns>
/// The location list result.
/// </returns>
public static ManagedLocationListResult List(this IManagedLocationOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedLocationOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get locations under subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedLocationOperations.
/// </param>
/// <returns>
/// The location list result.
/// </returns>
public static Task<ManagedLocationListResult> ListAsync(this IManagedLocationOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
/// <summary>
/// Gets locations with the next link.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedLocationOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The url to get the next set of results.
/// </param>
/// <returns>
/// The location list result.
/// </returns>
public static ManagedLocationListResult ListNext(this IManagedLocationOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedLocationOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets locations with the next link.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedLocationOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The url to get the next set of results.
/// </param>
/// <returns>
/// The location list result.
/// </returns>
public static Task<ManagedLocationListResult> ListNextAsync(this IManagedLocationOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
// 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 System;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Avalonia.Data;
using Avalonia.Reactive;
namespace Avalonia
{
/// <summary>
/// Provides extension methods for <see cref="AvaloniaObject"/> and related classes.
/// </summary>
public static class AvaloniaObjectExtensions
{
/// <summary>
/// Converts an <see cref="IObservable{T}"/> to an <see cref="IBinding"/>.
/// </summary>
/// <typeparam name="T">The type produced by the observable.</typeparam>
/// <param name="source">The observable</param>
/// <returns>An <see cref="IBinding"/>.</returns>
public static IBinding ToBinding<T>(this IObservable<T> source)
{
return new BindingAdaptor(source.Select(x => (object)x));
}
/// <summary>
/// Gets an observable for a <see cref="AvaloniaProperty"/>.
/// </summary>
/// <param name="o">The object.</param>
/// <param name="property">The property.</param>
/// <returns>
/// An observable which fires immediately with the current value of the property on the
/// object and subsequently each time the property value changes.
/// </returns>
public static IObservable<object> GetObservable(this IAvaloniaObject o, AvaloniaProperty property)
{
Contract.Requires<ArgumentNullException>(o != null);
Contract.Requires<ArgumentNullException>(property != null);
return new AvaloniaObservable<object>(
observer =>
{
EventHandler<AvaloniaPropertyChangedEventArgs> handler = (s, e) =>
{
if (e.Property == property)
{
observer.OnNext(e.NewValue);
}
};
observer.OnNext(o.GetValue(property));
o.PropertyChanged += handler;
return Disposable.Create(() =>
{
o.PropertyChanged -= handler;
});
},
GetDescription(o, property));
}
/// <summary>
/// Gets an observable for a <see cref="AvaloniaProperty"/>.
/// </summary>
/// <param name="o">The object.</param>
/// <typeparam name="T">The property type.</typeparam>
/// <param name="property">The property.</param>
/// <returns>
/// An observable which fires immediately with the current value of the property on the
/// object and subsequently each time the property value changes.
/// </returns>
public static IObservable<T> GetObservable<T>(this IAvaloniaObject o, AvaloniaProperty<T> property)
{
Contract.Requires<ArgumentNullException>(o != null);
Contract.Requires<ArgumentNullException>(property != null);
return o.GetObservable((AvaloniaProperty)property).Cast<T>();
}
/// <summary>
/// Gets an observable for a <see cref="AvaloniaProperty"/>.
/// </summary>
/// <param name="o">The object.</param>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="property">The property.</param>
/// <returns>
/// An observable which when subscribed pushes the old and new values of the property each
/// time it is changed. Note that the observable returned from this method does not fire
/// with the current value of the property immediately.
/// </returns>
public static IObservable<Tuple<T, T>> GetObservableWithHistory<T>(
this IAvaloniaObject o,
AvaloniaProperty<T> property)
{
Contract.Requires<ArgumentNullException>(o != null);
Contract.Requires<ArgumentNullException>(property != null);
return new AvaloniaObservable<Tuple<T, T>>(
observer =>
{
EventHandler<AvaloniaPropertyChangedEventArgs> handler = (s, e) =>
{
if (e.Property == property)
{
observer.OnNext(Tuple.Create((T)e.OldValue, (T)e.NewValue));
}
};
o.PropertyChanged += handler;
return Disposable.Create(() =>
{
o.PropertyChanged -= handler;
});
},
GetDescription(o, property));
}
/// <summary>
/// Gets a subject for a <see cref="AvaloniaProperty"/>.
/// </summary>
/// <param name="o">The object.</param>
/// <param name="property">The property.</param>
/// <param name="priority">
/// The priority with which binding values are written to the object.
/// </param>
/// <returns>
/// An <see cref="ISubject{Object}"/> which can be used for two-way binding to/from the
/// property.
/// </returns>
public static ISubject<object> GetSubject(
this IAvaloniaObject o,
AvaloniaProperty property,
BindingPriority priority = BindingPriority.LocalValue)
{
// TODO: Subject.Create<T> is not yet in stable Rx : once it is, remove the
// AnonymousSubject classes and use Subject.Create<T>.
var output = new Subject<object>();
var result = new AnonymousSubject<object>(
Observer.Create<object>(
x => output.OnNext(x),
e => output.OnError(e),
() => output.OnCompleted()),
o.GetObservable(property));
o.Bind(property, output, priority);
return result;
}
/// <summary>
/// Gets a subject for a <see cref="AvaloniaProperty"/>.
/// </summary>
/// <typeparam name="T">The property type.</typeparam>
/// <param name="o">The object.</param>
/// <param name="property">The property.</param>
/// <param name="priority">
/// The priority with which binding values are written to the object.
/// </param>
/// <returns>
/// An <see cref="ISubject{T}"/> which can be used for two-way binding to/from the
/// property.
/// </returns>
public static ISubject<T> GetSubject<T>(
this IAvaloniaObject o,
AvaloniaProperty<T> property,
BindingPriority priority = BindingPriority.LocalValue)
{
// TODO: Subject.Create<T> is not yet in stable Rx : once it is, remove the
// AnonymousSubject classes from this file and use Subject.Create<T>.
var output = new Subject<T>();
var result = new AnonymousSubject<T>(
Observer.Create<T>(
x => output.OnNext(x),
e => output.OnError(e),
() => output.OnCompleted()),
o.GetObservable(property));
o.Bind(property, output, priority);
return result;
}
/// <summary>
/// Gets a weak observable for a <see cref="AvaloniaProperty"/>.
/// </summary>
/// <param name="o">The object.</param>
/// <param name="property">The property.</param>
/// <returns>An observable.</returns>
public static IObservable<object> GetWeakObservable(this IAvaloniaObject o, AvaloniaProperty property)
{
Contract.Requires<ArgumentNullException>(o != null);
Contract.Requires<ArgumentNullException>(property != null);
return new WeakPropertyChangedObservable(
new WeakReference<IAvaloniaObject>(o),
property,
GetDescription(o, property));
}
/// <summary>
/// Binds a property on an <see cref="IAvaloniaObject"/> to an <see cref="IBinding"/>.
/// </summary>
/// <param name="target">The object.</param>
/// <param name="property">The property to bind.</param>
/// <param name="binding">The binding.</param>
/// <param name="anchor">
/// An optional anchor from which to locate required context. When binding to objects that
/// are not in the logical tree, certain types of binding need an anchor into the tree in
/// order to locate named controls or resources. The <paramref name="anchor"/> parameter
/// can be used to provice this context.
/// </param>
/// <returns>An <see cref="IDisposable"/> which can be used to cancel the binding.</returns>
public static IDisposable Bind(
this IAvaloniaObject target,
AvaloniaProperty property,
IBinding binding,
object anchor = null)
{
Contract.Requires<ArgumentNullException>(target != null);
Contract.Requires<ArgumentNullException>(property != null);
Contract.Requires<ArgumentNullException>(binding != null);
var metadata = property.GetMetadata(target.GetType()) as IDirectPropertyMetadata;
var result = binding.Initiate(
target,
property,
anchor,
metadata?.EnableDataValidation ?? false);
if (result != null)
{
return BindingOperations.Apply(target, property, result, anchor);
}
else
{
return Disposable.Empty;
}
}
/// <summary>
/// Subscribes to a property changed notifications for changes that originate from a
/// <typeparamref name="TTarget"/>.
/// </summary>
/// <typeparam name="TTarget">The type of the property change sender.</typeparam>
/// <param name="observable">The property changed observable.</param>
/// <param name="action">
/// The method to call. The parameters are the sender and the event args.
/// </param>
/// <returns>A disposable that can be used to terminate the subscription.</returns>
public static IDisposable AddClassHandler<TTarget>(
this IObservable<AvaloniaPropertyChangedEventArgs> observable,
Action<TTarget, AvaloniaPropertyChangedEventArgs> action)
where TTarget : AvaloniaObject
{
return observable.Subscribe(e =>
{
if (e.Sender is TTarget)
{
action((TTarget)e.Sender, e);
}
});
}
/// <summary>
/// Subscribes to a property changed notifications for changes that originate from a
/// <typeparamref name="TTarget"/>.
/// </summary>
/// <typeparam name="TTarget">The type of the property change sender.</typeparam>
/// <param name="observable">The property changed observable.</param>
/// <param name="handler">Given a TTarget, returns the handler.</param>
/// <returns>A disposable that can be used to terminate the subscription.</returns>
public static IDisposable AddClassHandler<TTarget>(
this IObservable<AvaloniaPropertyChangedEventArgs> observable,
Func<TTarget, Action<AvaloniaPropertyChangedEventArgs>> handler)
where TTarget : class
{
return observable.Subscribe(e => SubscribeAdapter(e, handler));
}
/// <summary>
/// Gets a description of a property that van be used in observables.
/// </summary>
/// <param name="o">The object.</param>
/// <param name="property">The property</param>
/// <returns>The description.</returns>
private static string GetDescription(IAvaloniaObject o, AvaloniaProperty property)
{
return $"{o.GetType().Name}.{property.Name}";
}
/// <summary>
/// Observer method for <see cref="AddClassHandler{TTarget}(IObservable{AvaloniaPropertyChangedEventArgs},
/// Func{TTarget, Action{AvaloniaPropertyChangedEventArgs}})"/>.
/// </summary>
/// <typeparam name="TTarget">The sender type to accept.</typeparam>
/// <param name="e">The event args.</param>
/// <param name="handler">Given a TTarget, returns the handler.</param>
private static void SubscribeAdapter<TTarget>(
AvaloniaPropertyChangedEventArgs e,
Func<TTarget, Action<AvaloniaPropertyChangedEventArgs>> handler)
where TTarget : class
{
var target = e.Sender as TTarget;
if (target != null)
{
handler(target)(e);
}
}
private class BindingAdaptor : IBinding
{
private IObservable<object> _source;
public BindingAdaptor(IObservable<object> source)
{
this._source = source;
}
public InstancedBinding Initiate(
IAvaloniaObject target,
AvaloniaProperty targetProperty,
object anchor = null,
bool enableDataValidation = false)
{
return new InstancedBinding(_source);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Sockets;
using System.Text;
namespace System.Net
{
/// <summary>
/// <para>
/// Implements basic sending and receiving of network commands.
/// Handles generic parsing of server responses and provides
/// a pipeline sequencing mechanism for sending the commands to the server.
/// </para>
/// </summary>
internal class CommandStream : NetworkStreamWrapper
{
private static readonly AsyncCallback s_writeCallbackDelegate = new AsyncCallback(WriteCallback);
private static readonly AsyncCallback s_readCallbackDelegate = new AsyncCallback(ReadCallback);
private bool _recoverableFailure;
//
// Active variables used for the command state machine
//
protected WebRequest _request;
protected bool _isAsync;
private bool _aborted;
protected PipelineEntry[] _commands;
protected int _index;
private bool _doRead;
private bool _doSend;
private ResponseDescription _currentResponseDescription;
protected string _abortReason;
private const int WaitingForPipeline = 1;
private const int CompletedPipeline = 2;
internal CommandStream(TcpClient client)
: base(client)
{
_decoder = _encoding.GetDecoder();
}
internal virtual void Abort(Exception e)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "closing control Stream");
lock (this)
{
if (_aborted)
return;
_aborted = true;
}
try
{
base.Close(0);
}
finally
{
if (e != null)
{
InvokeRequestCallback(e);
}
else
{
InvokeRequestCallback(null);
}
}
}
protected override void Dispose(bool disposing)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
InvokeRequestCallback(null);
// Do not call base.Dispose(bool), which would close the web request.
// This stream effectively should be a wrapper around a web
// request that does not own the web request.
}
protected void InvokeRequestCallback(object obj)
{
WebRequest webRequest = _request;
if (webRequest != null)
{
FtpWebRequest ftpWebRequest = (FtpWebRequest)webRequest;
ftpWebRequest.RequestCallback(obj);
}
}
internal bool RecoverableFailure
{
get
{
return _recoverableFailure;
}
}
protected void MarkAsRecoverableFailure()
{
if (_index <= 1)
{
_recoverableFailure = true;
}
}
internal Stream SubmitRequest(WebRequest request, bool isAsync, bool readInitalResponseOnConnect)
{
ClearState();
PipelineEntry[] commands = BuildCommandsList(request);
InitCommandPipeline(request, commands, isAsync);
if (readInitalResponseOnConnect)
{
_doSend = false;
_index = -1;
}
return ContinueCommandPipeline();
}
protected virtual void ClearState()
{
InitCommandPipeline(null, null, false);
}
protected virtual PipelineEntry[] BuildCommandsList(WebRequest request)
{
return null;
}
protected Exception GenerateException(string message, WebExceptionStatus status, Exception innerException)
{
return new WebException(
message,
innerException,
status,
null /* no response */ );
}
protected Exception GenerateException(FtpStatusCode code, string statusDescription, Exception innerException)
{
return new WebException(SR.Format(SR.net_ftp_servererror, NetRes.GetWebStatusCodeString(code, statusDescription)),
innerException, WebExceptionStatus.ProtocolError, null);
}
protected void InitCommandPipeline(WebRequest request, PipelineEntry[] commands, bool isAsync)
{
_commands = commands;
_index = 0;
_request = request;
_aborted = false;
_doRead = true;
_doSend = true;
_currentResponseDescription = null;
_isAsync = isAsync;
_recoverableFailure = false;
_abortReason = string.Empty;
}
internal void CheckContinuePipeline()
{
if (_isAsync)
return;
try
{
ContinueCommandPipeline();
}
catch (Exception e)
{
Abort(e);
}
}
/// Pipelined command resoluton.
/// How this works:
/// A list of commands that need to be sent to the FTP server are spliced together into a array,
/// each command such STOR, PORT, etc, is sent to the server, then the response is parsed into a string,
/// with the response, the delegate is called, which returns an instruction (either continue, stop, or read additional
/// responses from server).
protected Stream ContinueCommandPipeline()
{
// In async case, The BeginWrite can actually result in a
// series of synchronous completions that eventually close
// the connection. So we need to save the members that
// we need to access, since they may not be valid after
// BeginWrite returns
bool isAsync = _isAsync;
while (_index < _commands.Length)
{
if (_doSend)
{
if (_index < 0)
throw new InternalException();
byte[] sendBuffer = Encoding.GetBytes(_commands[_index].Command);
if (NetEventSource.Log.IsEnabled())
{
string sendCommand = _commands[_index].Command.Substring(0, _commands[_index].Command.Length - 2);
if (_commands[_index].HasFlag(PipelineEntryFlags.DontLogParameter))
{
int index = sendCommand.IndexOf(' ');
if (index != -1)
sendCommand = sendCommand.Substring(0, index) + " ********";
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Sending command {sendCommand}");
}
try
{
if (isAsync)
{
BeginWrite(sendBuffer, 0, sendBuffer.Length, s_writeCallbackDelegate, this);
}
else
{
Write(sendBuffer, 0, sendBuffer.Length);
}
}
catch (IOException)
{
MarkAsRecoverableFailure();
throw;
}
catch
{
throw;
}
if (isAsync)
{
return null;
}
}
Stream stream = null;
bool isReturn = PostSendCommandProcessing(ref stream);
if (isReturn)
{
return stream;
}
}
lock (this)
{
Close();
}
return null;
}
private bool PostSendCommandProcessing(ref Stream stream)
{
if (_doRead)
{
// In async case, the next call can actually result in a
// series of synchronous completions that eventually close
// the connection. So we need to save the members that
// we need to access, since they may not be valid after the
// next call returns
bool isAsync = _isAsync;
int index = _index;
PipelineEntry[] commands = _commands;
try
{
ResponseDescription response = ReceiveCommandResponse();
if (isAsync)
{
return true;
}
_currentResponseDescription = response;
}
catch
{
// If we get an exception on the QUIT command (which is
// always the last command), ignore the final exception
// and continue with the pipeline regardlss of sync/async
if (index < 0 || index >= commands.Length ||
commands[index].Command != "QUIT\r\n")
throw;
}
}
return PostReadCommandProcessing(ref stream);
}
private bool PostReadCommandProcessing(ref Stream stream)
{
if (_index >= _commands.Length)
return false;
// Set up front to prevent a race condition on result == PipelineInstruction.Pause
_doSend = false;
_doRead = false;
PipelineInstruction result;
PipelineEntry entry;
if (_index == -1)
entry = null;
else
entry = _commands[_index];
// Final QUIT command may get exceptions since the connection
// may be already closed by the server. So there is no response
// to process, just advance the pipeline to continue.
if (_currentResponseDescription == null && entry.Command == "QUIT\r\n")
result = PipelineInstruction.Advance;
else
result = PipelineCallback(entry, _currentResponseDescription, false, ref stream);
if (result == PipelineInstruction.Abort)
{
Exception exception;
if (_abortReason != string.Empty)
exception = new WebException(_abortReason);
else
exception = GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null);
Abort(exception);
throw exception;
}
else if (result == PipelineInstruction.Advance)
{
_currentResponseDescription = null;
_doSend = true;
_doRead = true;
_index++;
}
else if (result == PipelineInstruction.Pause)
{
// PipelineCallback did an async operation and will have to re-enter again.
// Hold on for now.
return true;
}
else if (result == PipelineInstruction.GiveStream)
{
// We will have another response coming, don't send
_currentResponseDescription = null;
_doRead = true;
if (_isAsync)
{
// If they block in the requestcallback we should still continue the pipeline
ContinueCommandPipeline();
InvokeRequestCallback(stream);
}
return true;
}
else if (result == PipelineInstruction.Reread)
{
// Another response is expected after this one
_currentResponseDescription = null;
_doRead = true;
}
return false;
}
internal enum PipelineInstruction
{
Abort, // aborts the pipeline
Advance, // advances to the next pipelined command
Pause, // Let async callback to continue the pipeline
Reread, // rereads from the command socket
GiveStream, // returns with open data stream, let stream close to continue
}
[Flags]
internal enum PipelineEntryFlags
{
UserCommand = 0x1,
GiveDataStream = 0x2,
CreateDataConnection = 0x4,
DontLogParameter = 0x8
}
internal class PipelineEntry
{
internal PipelineEntry(string command)
{
Command = command;
}
internal PipelineEntry(string command, PipelineEntryFlags flags)
{
Command = command;
Flags = flags;
}
internal bool HasFlag(PipelineEntryFlags flags)
{
return (Flags & flags) != 0;
}
internal string Command;
internal PipelineEntryFlags Flags;
}
protected virtual PipelineInstruction PipelineCallback(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream)
{
return PipelineInstruction.Abort;
}
//
// I/O callback methods
//
private static void ReadCallback(IAsyncResult asyncResult)
{
ReceiveState state = (ReceiveState)asyncResult.AsyncState;
try
{
Stream stream = (Stream)state.Connection;
int bytesRead = 0;
try
{
bytesRead = stream.EndRead(asyncResult);
if (bytesRead == 0)
state.Connection.CloseSocket();
}
catch (IOException)
{
state.Connection.MarkAsRecoverableFailure();
throw;
}
catch
{
throw;
}
state.Connection.ReceiveCommandResponseCallback(state, bytesRead);
}
catch (Exception e)
{
state.Connection.Abort(e);
}
}
private static void WriteCallback(IAsyncResult asyncResult)
{
CommandStream connection = (CommandStream)asyncResult.AsyncState;
try
{
try
{
connection.EndWrite(asyncResult);
}
catch (IOException)
{
connection.MarkAsRecoverableFailure();
throw;
}
catch
{
throw;
}
Stream stream = null;
if (connection.PostSendCommandProcessing(ref stream))
return;
connection.ContinueCommandPipeline();
}
catch (Exception e)
{
connection.Abort(e);
}
}
//
// Read parsing methods and privates
//
private string _buffer = string.Empty;
private Encoding _encoding = Encoding.UTF8;
private Decoder _decoder;
protected Encoding Encoding
{
get
{
return _encoding;
}
set
{
_encoding = value;
_decoder = _encoding.GetDecoder();
}
}
/// <summary>
/// This function is implemented in a derived class to determine whether a response is valid, and when it is complete.
/// </summary>
protected virtual bool CheckValid(ResponseDescription response, ref int validThrough, ref int completeLength)
{
return false;
}
/// <summary>
/// Kicks off an asynchronous or sync request to receive a response from the server.
/// Uses the Encoding <code>encoding</code> to transform the bytes received into a string to be
/// returned in the GeneralResponseDescription's StatusDescription field.
/// </summary>
private ResponseDescription ReceiveCommandResponse()
{
// These are the things that will be needed to maintain state.
ReceiveState state = new ReceiveState(this);
try
{
// If a string of nonzero length was decoded from the buffered bytes after the last complete response, then we
// will use this string as our first string to append to the response StatusBuffer, and we will
// forego a Connection.Receive here.
if (_buffer.Length > 0)
{
ReceiveCommandResponseCallback(state, -1);
}
else
{
int bytesRead;
try
{
if (_isAsync)
{
BeginRead(state.Buffer, 0, state.Buffer.Length, s_readCallbackDelegate, state);
return null;
}
else
{
bytesRead = Read(state.Buffer, 0, state.Buffer.Length);
if (bytesRead == 0)
CloseSocket();
ReceiveCommandResponseCallback(state, bytesRead);
}
}
catch (IOException)
{
MarkAsRecoverableFailure();
throw;
}
catch
{
throw;
}
}
}
catch (Exception e)
{
if (e is WebException)
throw;
throw GenerateException(SR.net_ftp_receivefailure, WebExceptionStatus.ReceiveFailure, e);
}
return state.Resp;
}
/// <summary>
/// ReceiveCommandResponseCallback is the main "while loop" of the ReceiveCommandResponse function family.
/// In general, what is does is perform an EndReceive() to complete the previous retrieval of bytes from the
/// server (unless it is using a buffered response) It then processes what is received by using the
/// implementing class's CheckValid() function, as described above. If the response is complete, it returns the single complete
/// response in the GeneralResponseDescription created in BeginReceiveComamndResponse, and buffers the rest as described above.
///
/// If the response is not complete, it issues another Connection.BeginReceive, with callback ReceiveCommandResponse2,
/// so the action will continue at the next invocation of ReceiveCommandResponse2.
/// </summary>
private void ReceiveCommandResponseCallback(ReceiveState state, int bytesRead)
{
// completeLength will be set to a nonnegative number by CheckValid if the response is complete:
// it will set completeLength to the length of a complete response.
int completeLength = -1;
while (true)
{
int validThrough = state.ValidThrough; // passed to checkvalid
// If we have a Buffered response (ie data was received with the last response that was past the end of that response)
// deal with it as if we had just received it now instead of actually doing another receive
if (_buffer.Length > 0)
{
// Append the string we got from the buffer, and flush it out.
state.Resp.StatusBuffer.Append(_buffer);
_buffer = string.Empty;
// invoke checkvalid.
if (!CheckValid(state.Resp, ref validThrough, ref completeLength))
{
throw GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null);
}
}
else // we did a Connection.BeginReceive. Note that in this case, all bytes received are in the receive buffer (because bytes from
// the buffer were transferred there if necessary
{
// this indicates the connection was closed.
if (bytesRead <= 0)
{
throw GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null);
}
// decode the bytes in the receive buffer into a string, append it to the statusbuffer, and invoke checkvalid.
// Decoder automatically takes care of caching partial codepoints at the end of a buffer.
char[] chars = new char[_decoder.GetCharCount(state.Buffer, 0, bytesRead)];
int numChars = _decoder.GetChars(state.Buffer, 0, bytesRead, chars, 0, false);
string szResponse = new string(chars, 0, numChars);
state.Resp.StatusBuffer.Append(szResponse);
if (!CheckValid(state.Resp, ref validThrough, ref completeLength))
{
throw GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null);
}
// If the response is complete, then determine how many characters are left over...these bytes need to be set into Buffer.
if (completeLength >= 0)
{
int unusedChars = state.Resp.StatusBuffer.Length - completeLength;
if (unusedChars > 0)
{
_buffer = szResponse.Substring(szResponse.Length - unusedChars, unusedChars);
}
}
}
// Now, in general, if the response is not complete, update the "valid through" length for the efficiency of checkValid,
// and perform the next receive.
// Note that there may NOT be bytes in the beginning of the receive buffer (even if there were partial characters left over after the
// last encoding), because they get tracked in the Decoder.
if (completeLength < 0)
{
state.ValidThrough = validThrough;
try
{
if (_isAsync)
{
BeginRead(state.Buffer, 0, state.Buffer.Length, s_readCallbackDelegate, state);
return;
}
else
{
bytesRead = Read(state.Buffer, 0, state.Buffer.Length);
if (bytesRead == 0)
CloseSocket();
continue;
}
}
catch (IOException)
{
MarkAsRecoverableFailure();
throw;
}
catch
{
throw;
}
}
// The response is completed
break;
}
// Otherwise, we have a complete response.
string responseString = state.Resp.StatusBuffer.ToString();
state.Resp.StatusDescription = responseString.Substring(0, completeLength);
// Set the StatusDescription to the complete part of the response. Note that the Buffer has already been taken care of above.
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Received response: {responseString.Substring(0, completeLength - 2)}");
if (_isAsync)
{
// Tell who is listening what was received.
if (state.Resp != null)
{
_currentResponseDescription = state.Resp;
}
Stream stream = null;
if (PostReadCommandProcessing(ref stream))
return;
ContinueCommandPipeline();
}
}
} // class CommandStream
/// <summary>
/// Contains the parsed status line from the server
/// </summary>
internal class ResponseDescription
{
internal const int NoStatus = -1;
internal bool Multiline = false;
internal int Status = NoStatus;
internal string StatusDescription;
internal StringBuilder StatusBuffer = new StringBuilder();
internal string StatusCodeString;
internal bool PositiveIntermediate { get { return (Status >= 100 && Status <= 199); } }
internal bool PositiveCompletion { get { return (Status >= 200 && Status <= 299); } }
internal bool TransientFailure { get { return (Status >= 400 && Status <= 499); } }
internal bool PermanentFailure { get { return (Status >= 500 && Status <= 599); } }
internal bool InvalidStatusCode { get { return (Status < 100 || Status > 599); } }
}
/// <summary>
/// State information that is used during ReceiveCommandResponse()'s async operations
/// </summary>
internal class ReceiveState
{
private const int bufferSize = 1024;
internal ResponseDescription Resp;
internal int ValidThrough;
internal byte[] Buffer;
internal CommandStream Connection;
internal ReceiveState(CommandStream connection)
{
Connection = connection;
Resp = new ResponseDescription();
Buffer = new byte[bufferSize]; //1024
ValidThrough = 0;
}
}
} // namespace System.Net
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace DotSpatial.Data
{
/// <summary>
/// HfaEntry
/// </summary>
public class HfaEntry
{
#region Fields
private char[] _name;
private char[] _typeName;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HfaEntry"/> class.
/// </summary>
/// <param name="hfaIn">The HfaInfo.</param>
/// <param name="nPos">The position.</param>
/// <param name="parent">The parent.</param>
/// <param name="prev">The previous HfaEntry.</param>
public HfaEntry(HfaInfo hfaIn, long nPos, HfaEntry parent, HfaEntry prev)
{
// Initialize fields
_name = new char[64];
_typeName = new char[32];
Hfa = hfaIn;
FilePos = nPos;
Parent = parent;
Prev = prev;
Hfa.Fp.Seek(nPos, SeekOrigin.Begin);
Children = new List<HfaEntry>();
// Read entry information from the file
int[] anEntryNums = new int[6];
byte[] entryBytes = new byte[24];
Hfa.Fp.Read(entryBytes, 0, 24);
Buffer.BlockCopy(entryBytes, 0, anEntryNums, 0, 24);
NextPos = anEntryNums[0];
ChildPos = anEntryNums[3];
DataPos = anEntryNums[4];
DataSize = anEntryNums[5];
// Read the name
byte[] nameBytes = new byte[64];
Hfa.Fp.Read(nameBytes, 0, 64);
_name = Encoding.Default.GetChars(nameBytes);
// Read the type
byte[] typeBytes = new byte[32];
Hfa.Fp.Read(typeBytes, 0, 32);
_typeName = Encoding.Default.GetChars(typeBytes);
}
/// <summary>
/// Initializes a new instance of the <see cref="HfaEntry"/> class with the intention that it would
/// be written to disk later.
/// </summary>
/// <param name="hfaIn">The HfaInfo.</param>
/// <param name="name">The name.</param>
/// <param name="typename">The type name.</param>
/// <param name="parent">The parent.</param>
public HfaEntry(HfaInfo hfaIn, string name, string typename, HfaEntry parent)
{
// Initialize
Hfa = hfaIn;
Parent = parent;
Name = name;
TypeName = typename;
Children = new List<HfaEntry>();
// Update the previous or parent node to refer to this one
if (parent == null)
{
// do nothing
}
else if (parent.Child == null)
{
parent.Child = this;
parent.IsDirty = true;
}
else
{
HfaEntry prev = parent.Children[parent.Children.Count - 1];
prev.Next = this;
prev.IsDirty = true;
}
IsDirty = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="HfaEntry"/> class.
/// </summary>
public HfaEntry()
{
_name = new char[64];
_typeName = new char[32];
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the first child belonging to this entry.
/// </summary>
public HfaEntry Child
{
get
{
return Children?[0];
}
set
{
if (Children == null) Children = new List<HfaEntry>();
Children[0] = value;
}
}
/// <summary>
/// Gets or sets the long position of the child.
/// </summary>
public long ChildPos { get; set; }
/// <summary>
/// Gets or sets the collection of all the children.
/// </summary>
public List<HfaEntry> Children { get; set; }
/// <summary>
/// Gets or sets the data for this entry.
/// </summary>
public byte[] Data { get; set; }
/// <summary>
/// Gets or sets the GUInt32 Data Position of this entry.
/// </summary>
public long DataPos { get; set; }
/// <summary>
/// Gets or sets the GUInt32 Data Size of this entry.
/// </summary>
public long DataSize { get; set; }
/// <summary>
/// Gets or sets the long integer file position.
/// </summary>
public long FilePos { get; set; }
/// <summary>
/// Gets or sets the HFA Info.
/// </summary>
public HfaInfo Hfa { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this is changed.
/// </summary>
public bool IsDirty { get; set; }
/// <summary>
/// Gets or sets the 64 character name of the entry.
/// </summary>
public string Name
{
get
{
return new string(_name);
}
set
{
_name = value.ToCharArray(0, 64);
IsDirty = true;
}
}
/// <summary>
/// Gets or sets the HfaEntry that is the next entry.
/// </summary>
public HfaEntry Next { get; set; }
/// <summary>
/// Gets or sets the long integer position of the next entry in the file.
/// </summary>
public long NextPos { get; set; }
/// <summary>
/// Gets or sets the hfa parent.
/// </summary>
public HfaEntry Parent { get; set; }
/// <summary>
/// Gets or sets the previous entry.
/// </summary>
public HfaEntry Prev { get; set; }
/// <summary>
/// Gets or sets the type for this entry.
/// </summary>
public HfaType Type { get; set; }
/// <summary>
/// gets or sets the 32 character typestring.
/// </summary>
public string TypeName
{
get
{
return new string(_typeName);
}
set
{
_typeName = value.ToCharArray(0, 32);
IsDirty = true;
}
}
#endregion
#region Methods
/// <summary>
/// Gets or sets the HfaEntry that is the child.
/// </summary>
/// <returns>The first child or null.</returns>
public HfaEntry GetFirstChild()
{
return Children?.First();
}
/// <summary>
/// This parses a complete "path" separated by periods in order
/// to search for a specific child node.
/// </summary>
/// <param name="name">Name of the child.</param>
/// <returns>The child with the given name or null.</returns>
public HfaEntry GetNamedChild(string name)
{
string firstName = GetFirstChildName(name);
string subTree = GetSubtreeName(name);
foreach (HfaEntry child in Children)
{
if (child.Name != firstName) continue;
return subTree != null ? child.GetNamedChild(subTree) : child;
}
return null;
}
/// <summary>
/// Loads the data bytes for this element from the file.
/// </summary>
public void LoadData()
{
if (Data != null || DataSize == 0) return;
Hfa.Fp.Seek(DataPos, SeekOrigin.Begin);
Hfa.Fp.Read(Data, 0, (int)DataSize);
Type = Hfa.Dictionary[TypeName];
}
/// <summary>
/// Parses a name which may have an unwanted : or multiple sub-tree
/// names separated with periods.
/// </summary>
/// <param name="name">Name that gets parsed.</param>
/// <returns>The first part of the name.</returns>
private static string GetFirstChildName(string name)
{
int pos = name.Length;
if (name.Contains(":")) pos = name.IndexOf(':');
if (name.Contains("."))
{
int tempPos = name.IndexOf('.');
if (tempPos < pos) pos = tempPos;
}
return name.Substring(0, pos);
}
/// <summary>
/// If this is null, then there is no further subtree
/// </summary>
/// <param name="name">The name that gets parsed.</param>
/// <returns>The subtree name.</returns>
private static string GetSubtreeName(string name)
{
if (name.Contains("."))
{
int start = name.IndexOf('.') + 1;
return name.Substring(start, name.Length - start);
}
return null;
}
#endregion
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media.Core;
using Windows.Media.Playback;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
namespace VideoPlayback
{
/// <summary>
/// Demonstrates playing video lists using MediaPlaybackList.
/// </summary>
public sealed partial class Scenario7 : Page
{
private MainPage rootPage;
private Dictionary<string, BitmapImage> artCache = new Dictionary<string, BitmapImage>();
private MediaPlaybackList playbackList = new MediaPlaybackList();
public Scenario7()
{
this.InitializeComponent();
// Always use the cached page
this.NavigationCacheMode = NavigationCacheMode.Required;
// Create a static playback list
InitializePlaybackList();
// Subscribe to MediaElement events
mediaElement.CurrentStateChanged += MediaElement_CurrentStateChanged;
// Subscribe to list UI changes
playlistView.ItemClick += PlaylistView_ItemClick;
}
void InitializePlaybackList()
{
// Initialize the playlist data/view model.
// In a production app your data would be sourced from a data store or service.
// Add content
var media1 = new MediaModel();
media1.Title = "Fitness";
media1.MediaUri = new Uri("ms-appx:///Assets/Media/multivideo-with-captions.mkv");
media1.ArtUri = new Uri("ms-appx:///Assets/Media/multivideo.jpg");
playlistView.Media.Add(media1);
var media2 = new MediaModel();
media2.Title = "Elephant's Dream";
media2.MediaUri = new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-H264_SD-AAC_eng-AAC_spa-AAC_eng_commentary-SRT_eng-SRT_por-SRT_swe.mkv");
media2.ArtUri = new Uri("ms-appx:///Assets/Media/ElephantsDream.jpg");
playlistView.Media.Add(media2);
var media3 = new MediaModel();
media3.Title = "Sintel";
media3.MediaUri = new Uri("ms-appx:///Assets/Media/sintel_trailer-480p.mp4");
media3.ArtUri = new Uri("ms-appx:///Assets/Media/sintel.jpg");
playlistView.Media.Add(media3);
// Pre-cache all album art to facilitate smooth gapless transitions.
// A production app would have a more sophisticated object cache.
foreach (var media in playlistView.Media)
{
var bitmap = new BitmapImage();
bitmap.UriSource = media.ArtUri;
artCache[media.ArtUri.ToString()] = bitmap;
}
// Initialize the playback list for this content
foreach(var media in playlistView.Media)
{
var mediaSource = MediaSource.CreateFromUri(media.MediaUri);
mediaSource.CustomProperties["uri"] = media.MediaUri;
var playbackItem = new MediaPlaybackItem(mediaSource);
playbackList.Items.Add(playbackItem);
}
// Subscribe for changes
playbackList.CurrentItemChanged += PlaybackList_CurrentItemChanged;
// Loop
playbackList.AutoRepeatEnabled = true;
}
private void PlaybackList_CurrentItemChanged(MediaPlaybackList sender, CurrentMediaPlaybackItemChangedEventArgs args)
{
var ignoreAwaitWarning = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var currentItem = sender.CurrentItem;
playlistView.SelectedIndex = playbackList.Items.ToList().FindIndex(i => i == currentItem);
});
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
// Set list for playback
mediaElement.SetPlaybackSource(playbackList);
}
/// <summary>
/// MediaPlayer state changed event handlers.
/// Note that we can subscribe to events even if Media Player is playing media in background
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private async void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
{
var currentState = mediaElement.CurrentState; // cache outside of completion or you might get a different value
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// Update state label
txtCurrentState.Text = currentState.ToString();
// Update controls
UpdateTransportControls(currentState);
});
}
private void PlaylistView_ItemClick(object sender, ItemClickEventArgs e)
{
var item = e.ClickedItem as MediaModel;
Debug.WriteLine("Clicked item: " + item.MediaUri.ToString());
// Start the background task if it wasn't running
playbackList.MoveTo((uint)playbackList.Items.ToList().FindIndex(i => (Uri)i.Source.CustomProperties["uri"] == item.MediaUri));
if (MediaElementState.Paused == mediaElement.CurrentState ||
MediaElementState.Stopped == mediaElement.CurrentState)
{
mediaElement.Play();
}
}
/// <summary>
/// Sends message to the background task to skip to the previous track.
/// </summary>
private void prevButton_Click(object sender, RoutedEventArgs e)
{
playbackList.MovePrevious();
}
/// <summary>
/// If the task is already running, it will just play/pause MediaPlayer Instance
/// Otherwise, initializes MediaPlayer Handlers and starts playback
/// track or to pause if we're already playing.
/// </summary>
private void playButton_Click(object sender, RoutedEventArgs e)
{
if (MediaElementState.Playing == mediaElement.CurrentState)
{
mediaElement.Pause();
}
else if (MediaElementState.Paused == mediaElement.CurrentState ||
MediaElementState.Stopped == mediaElement.CurrentState)
{
mediaElement.Play();
}
}
/// <summary>
/// Tells the background audio agent to skip to the next track.
/// </summary>
/// <param name="sender">The button</param>
/// <param name="e">Click event args</param>
private void nextButton_Click(object sender, RoutedEventArgs e)
{
playbackList.MoveNext();
}
private void speedButton_Click(object sender, RoutedEventArgs e)
{
// Create menu and add commands
var popupMenu = new PopupMenu();
popupMenu.Commands.Add(new UICommand("4.0x", command => mediaElement.PlaybackRate = 4.0));
popupMenu.Commands.Add(new UICommand("2.0x", command => mediaElement.PlaybackRate = 2.0));
popupMenu.Commands.Add(new UICommand("1.5x", command => mediaElement.PlaybackRate = 1.5));
popupMenu.Commands.Add(new UICommand("1.0x", command => mediaElement.PlaybackRate = 1.0));
popupMenu.Commands.Add(new UICommand("0.5x", command => mediaElement.PlaybackRate = 0.5));
// Get button transform and then offset it by half the button
// width to center. This will show the popup just above the button.
var button = (Button)sender;
var transform = button.TransformToVisual(null);
var point = transform.TransformPoint(new Point(button.Width / 2, 0));
// Show popup
var ignoreAsyncResult = popupMenu.ShowAsync(point);
}
private void UpdateTransportControls(MediaElementState state)
{
nextButton.IsEnabled = true;
prevButton.IsEnabled = true;
if (state == MediaElementState.Playing)
{
playButton.Content = "| |"; // Change to pause button
}
else
{
playButton.Content = ">"; // Change to play button
}
}
}
}
| |
using UnityEngine;
/// <summary>
/// Functionality common to both NGUI and 2D sprites brought out into a single common parent.
/// Mostly contains everything related to drawing the sprite.
/// </summary>
public abstract class UIBasicSprite : UIWidget
{
public enum Type
{
Simple,
Sliced,
Tiled,
Filled,
Advanced,
Mirrored,
}
public enum FillDirection
{
Horizontal,
Vertical,
Radial90,
Radial180,
Radial360,
}
public enum AdvancedType
{
Invisible,
Sliced,
Tiled,
}
public enum Flip
{
Nothing,
Horizontally,
Vertically,
Both,
}
[HideInInspector][SerializeField] protected Type mType = Type.Simple;
[HideInInspector][SerializeField] protected FillDirection mFillDirection = FillDirection.Radial360;
[Range(0f, 1f)]
[HideInInspector][SerializeField] protected float mFillAmount = 1.0f;
[HideInInspector][SerializeField] protected bool mInvert = false;
[HideInInspector][SerializeField] protected Flip mFlip = Flip.Nothing;
// Cached to avoid allocations
[System.NonSerialized] Rect mInnerUV = new Rect();
[System.NonSerialized] Rect mOuterUV = new Rect();
/// <summary>
/// When the sprite type is advanced, this determines whether the center is tiled or sliced.
/// </summary>
public AdvancedType centerType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the left edge is tiled or sliced.
/// </summary>
public AdvancedType leftType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the right edge is tiled or sliced.
/// </summary>
public AdvancedType rightType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the bottom edge is tiled or sliced.
/// </summary>
public AdvancedType bottomType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the top edge is tiled or sliced.
/// </summary>
public AdvancedType topType = AdvancedType.Sliced;
/// <summary>
/// How the sprite is drawn. It's virtual for legacy reasons (UISlicedSprite, UITiledSprite, UIFilledSprite).
/// </summary>
public virtual Type type
{
get
{
return mType;
}
set
{
if (mType != value)
{
mType = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Sprite flip setting.
/// </summary>
public Flip flip
{
get
{
return mFlip;
}
set
{
if (mFlip != value)
{
mFlip = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Direction of the cut procedure.
/// </summary>
public FillDirection fillDirection
{
get
{
return mFillDirection;
}
set
{
if (mFillDirection != value)
{
mFillDirection = value;
mChanged = true;
}
}
}
/// <summary>
/// Amount of the sprite shown. 0-1 range with 0 being nothing shown, and 1 being the full sprite.
/// </summary>
public float fillAmount
{
get
{
return mFillAmount;
}
set
{
float val = Mathf.Clamp01(value);
if (mFillAmount != val)
{
mFillAmount = val;
mChanged = true;
}
}
}
/// <summary>
/// Minimum allowed width for this widget.
/// </summary>
override public int minWidth
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.x + b.z);
return Mathf.Max(base.minWidth, ((min & 1) == 1) ? min + 1 : min);
}
return base.minWidth;
}
}
/// <summary>
/// Minimum allowed height for this widget.
/// </summary>
override public int minHeight
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.y + b.w);
return Mathf.Max(base.minHeight, ((min & 1) == 1) ? min + 1 : min);
}
return base.minHeight;
}
}
/// <summary>
/// Whether the sprite should be filled in the opposite direction.
/// </summary>
public bool invert
{
get
{
return mInvert;
}
set
{
if (mInvert != value)
{
mInvert = value;
mChanged = true;
}
}
}
/// <summary>
/// Whether the widget has a border for 9-slicing.
/// </summary>
public bool hasBorder
{
get
{
Vector4 br = border;
return (br.x != 0f || br.y != 0f || br.z != 0f || br.w != 0f);
}
}
/// <summary>
/// Whether the sprite's material is using a pre-multiplied alpha shader.
/// </summary>
public virtual bool premultipliedAlpha { get { return false; } }
/// <summary>
/// Size of the pixel. Overwritten in the NGUI sprite to pull a value from the atlas.
/// </summary>
public virtual float pixelSize { get { return 1f; } }
#if UNITY_EDITOR
/// <summary>
/// Keep sane values.
/// </summary>
protected override void OnValidate ()
{
base.OnValidate();
mFillAmount = Mathf.Clamp01(mFillAmount);
}
#endif
#region Fill Functions
// Static variables to reduce garbage collection
static protected Vector2[] mTempPos = new Vector2[4];
static protected Vector2[] mTempUVs = new Vector2[4];
/// <summary>
/// Convenience function that returns the drawn UVs after flipping gets considered.
/// X = left, Y = bottom, Z = right, W = top.
/// </summary>
Vector4 drawingUVs
{
get
{
switch (mFlip)
{
case Flip.Horizontally: return new Vector4(mOuterUV.xMax, mOuterUV.yMin, mOuterUV.xMin, mOuterUV.yMax);
case Flip.Vertically: return new Vector4(mOuterUV.xMin, mOuterUV.yMax, mOuterUV.xMax, mOuterUV.yMin);
case Flip.Both: return new Vector4(mOuterUV.xMax, mOuterUV.yMax, mOuterUV.xMin, mOuterUV.yMin);
default: return new Vector4(mOuterUV.xMin, mOuterUV.yMin, mOuterUV.xMax, mOuterUV.yMax);
}
}
}
/// <summary>
/// Final widget's color passed to the draw buffer.
/// </summary>
Color32 drawingColor
{
get
{
Color colF = color;
colF.a = finalAlpha;
if (premultipliedAlpha) colF = NGUITools.ApplyPMA(colF);
if (QualitySettings.activeColorSpace == ColorSpace.Linear)
{
colF.r = Mathf.Pow(colF.r, 2.2f);
colF.g = Mathf.Pow(colF.g, 2.2f);
colF.b = Mathf.Pow(colF.b, 2.2f);
}
return colF;
}
}
/// <summary>
/// Fill the draw buffers.
/// </summary>
protected void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols, Rect outer, Rect inner)
{
mOuterUV = outer;
mInnerUV = inner;
switch (type)
{
case Type.Simple:
SimpleFill(verts, uvs, cols);
break;
case Type.Sliced:
SlicedFill(verts, uvs, cols);
break;
case Type.Filled:
FilledFill(verts, uvs, cols);
break;
case Type.Tiled:
TiledFill(verts, uvs, cols);
break;
case Type.Advanced:
AdvancedFill(verts, uvs, cols);
break;
case Type.Mirrored:
MirroredFill(verts, uvs, cols);
break;
}
}
/// <summary>
/// Regular sprite fill function is quite simple.
/// </summary>
void SimpleFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
verts.Add(new Vector3(v.x, v.y));
verts.Add(new Vector3(v.x, v.w));
verts.Add(new Vector3(v.z, v.w));
verts.Add(new Vector3(v.z, v.y));
uvs.Add(new Vector2(u.x, u.y));
uvs.Add(new Vector2(u.x, u.w));
uvs.Add(new Vector2(u.z, u.w));
uvs.Add(new Vector2(u.z, u.y));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
/// <summary>
/// Sliced sprite fill function is more complicated as it generates 9 quads instead of 1.
/// </summary>
void SlicedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y].y));
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y].y));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
}
}
/// <summary>
/// Tiled sprite fill function.
/// </summary>
void TiledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector2 size = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
size *= pixelSize;
if (tex == null || size.x < 2f || size.y < 2f) return;
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector4 u;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
u.x = mInnerUV.xMax;
u.z = mInnerUV.xMin;
}
else
{
u.x = mInnerUV.xMin;
u.z = mInnerUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
u.y = mInnerUV.yMax;
u.w = mInnerUV.yMin;
}
else
{
u.y = mInnerUV.yMin;
u.w = mInnerUV.yMax;
}
float x0 = v.x;
float y0 = v.y;
float u0 = u.x;
float v0 = u.y;
while (y0 < v.w)
{
x0 = v.x;
float y1 = y0 + size.y;
float v1 = u.w;
if (y1 > v.w)
{
v1 = Mathf.Lerp(u.y, u.w, (v.w - y0) / size.y);
y1 = v.w;
}
while (x0 < v.z)
{
float x1 = x0 + size.x;
float u1 = u.z;
if (x1 > v.z)
{
u1 = Mathf.Lerp(u.x, u.z, (v.z - x0) / size.x);
x1 = v.z;
}
verts.Add(new Vector3(x0, y0));
verts.Add(new Vector3(x0, y1));
verts.Add(new Vector3(x1, y1));
verts.Add(new Vector3(x1, y0));
uvs.Add(new Vector2(u0, v0));
uvs.Add(new Vector2(u0, v1));
uvs.Add(new Vector2(u1, v1));
uvs.Add(new Vector2(u1, v0));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
x0 += size.x;
}
y0 += size.y;
}
}
/// <summary>
/// Filled sprite fill function.
/// </summary>
void FilledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
if (mFillAmount < 0.001f) return;
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
// Horizontal and vertical filled sprites are simple -- just end the sprite prematurely
if (mFillDirection == FillDirection.Horizontal || mFillDirection == FillDirection.Vertical)
{
if (mFillDirection == FillDirection.Horizontal)
{
float fill = (u.z - u.x) * mFillAmount;
if (mInvert)
{
v.x = v.z - (v.z - v.x) * mFillAmount;
u.x = u.z - fill;
}
else
{
v.z = v.x + (v.z - v.x) * mFillAmount;
u.z = u.x + fill;
}
}
else if (mFillDirection == FillDirection.Vertical)
{
float fill = (u.w - u.y) * mFillAmount;
if (mInvert)
{
v.y = v.w - (v.w - v.y) * mFillAmount;
u.y = u.w - fill;
}
else
{
v.w = v.y + (v.w - v.y) * mFillAmount;
u.w = u.y + fill;
}
}
}
mTempPos[0] = new Vector2(v.x, v.y);
mTempPos[1] = new Vector2(v.x, v.w);
mTempPos[2] = new Vector2(v.z, v.w);
mTempPos[3] = new Vector2(v.z, v.y);
mTempUVs[0] = new Vector2(u.x, u.y);
mTempUVs[1] = new Vector2(u.x, u.w);
mTempUVs[2] = new Vector2(u.z, u.w);
mTempUVs[3] = new Vector2(u.z, u.y);
if (mFillAmount < 1f)
{
if (mFillDirection == FillDirection.Radial90)
{
if (RadialCut(mTempPos, mTempUVs, mFillAmount, mInvert, 0))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
return;
}
if (mFillDirection == FillDirection.Radial180)
{
for (int side = 0; side < 2; ++side)
{
float fx0, fx1, fy0, fy1;
fy0 = 0f;
fy1 = 1f;
if (side == 0) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = !mInvert ? fillAmount * 2f - side : mFillAmount * 2f - (1 - side);
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), !mInvert, NGUIMath.RepeatIndex(side + 3, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
if (mFillDirection == FillDirection.Radial360)
{
for (int corner = 0; corner < 4; ++corner)
{
float fx0, fx1, fy0, fy1;
if (corner < 2) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
if (corner == 0 || corner == 3) { fy0 = 0f; fy1 = 0.5f; }
else { fy0 = 0.5f; fy1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = mInvert ?
mFillAmount * 4f - NGUIMath.RepeatIndex(corner + 2, 4) :
mFillAmount * 4f - (3 - NGUIMath.RepeatIndex(corner + 2, 4));
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), mInvert, NGUIMath.RepeatIndex(corner + 2, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
}
// Fill the buffer with the quad for the sprite
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
/// <summary>
/// Advanced sprite fill function. Contributed by Nicki Hansen.
/// </summary>
void AdvancedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector2 tileSize = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
tileSize *= pixelSize;
if (tileSize.x < 1f) tileSize.x = 1f;
if (tileSize.y < 1f) tileSize.y = 1f;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
if (x == 1 && y == 1) // Center
{
if (centerType == AdvancedType.Tiled)
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float tileStartX = startPositionX;
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
tileStartY += tileSize.y;
}
}
else if (centerType == AdvancedType.Sliced)
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (x == 1) // Top or bottom
{
if ((y == 0 && bottomType == AdvancedType.Tiled) || (y == 2 && topType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float textureEndY = mTempUVs[y2].y;
float tileStartX = startPositionX;
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
startPositionY, endPositionY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
}
else if ((y == 0 && bottomType == AdvancedType.Sliced) || (y == 2 && topType == AdvancedType.Sliced))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (y == 1) // Left or right
{
if ((x == 0 && leftType == AdvancedType.Tiled) || (x == 2 && rightType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureEndX = mTempUVs[x2].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
Fill(verts, uvs, cols,
startPositionX, endPositionX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartY += tileSize.y;
}
}
else if ((x == 0 && leftType == AdvancedType.Sliced) || (x == 2 && rightType == AdvancedType.Sliced))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else // Corner
{
if ((y == 0 && bottomType == AdvancedType.Sliced) || (y == 2 && topType == AdvancedType.Sliced) ||
(x == 0 && leftType == AdvancedType.Sliced) || (x == 2 && rightType == AdvancedType.Sliced))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
}
}
}
void MirroredFill(BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector2 size = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
size *= pixelSize;
if (tex == null || size.x < 2f || size.y < 2f) return;
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector4 u = new Vector4(mInnerUV.xMin, mInnerUV.yMin, mInnerUV.xMax, mInnerUV.yMax);
float x0 = v.x;
float y0 = v.y;
float u0 = u.x;
float v0 = u.y;
bool yb = true;
while (y0 < v.w)
{
x0 = v.x;
float y1 = y0 + size.y;
float v1 = u.w;
if (y1 > v.w)
{
v1 = Mathf.Lerp(u.y, u.w, (v.w - y0) / size.y);
y1 = v.w;
}
bool b = true;
while (x0 < v.z)
{
float x1 = x0 + size.x;
float u1 = u.z;
if (x1 > v.z)
{
u1 = Mathf.Lerp(u.x, u.z, (v.z - x0) / size.x);
x1 = v.z;
}
float offset = 0.3f;
verts.Add(new Vector3(x0 - offset, y0 - offset));
verts.Add(new Vector3(x0 - offset, y1 + offset));
verts.Add(new Vector3(x1 + offset, y1 + offset));
verts.Add(new Vector3(x1 + offset, y0 - offset));
float yoffset = size.y != 1 ? 0.001f : 0.0f;
float xoffset = size.x != 1 ? 0.001f : 0.0f;
if (yb)
{
if (b)
{
uvs.Add(new Vector2(u0 - xoffset, v0));
uvs.Add(new Vector2(u0 - xoffset, v1 + yoffset));
uvs.Add(new Vector2(u1, v1 + yoffset));
uvs.Add(new Vector2(u1, v0));
}
else
{
uvs.Add(new Vector2(u1, v0));
uvs.Add(new Vector2(u1, v1 + yoffset));
uvs.Add(new Vector2(u0 - xoffset, v1 + yoffset));
uvs.Add(new Vector2(u0 - xoffset, v0));
}
}
else
{
if (b)
{
uvs.Add(new Vector2(u0 - xoffset, v1 + yoffset));
uvs.Add(new Vector2(u0 - xoffset, v0));
uvs.Add(new Vector2(u1, v0));
uvs.Add(new Vector2(u1, v1 + yoffset));
}
else
{
uvs.Add(new Vector2(u1, v1 + yoffset));
uvs.Add(new Vector2(u1, v0));
uvs.Add(new Vector2(u0 - xoffset, v0));
uvs.Add(new Vector2(u0 - xoffset, v1 + yoffset));
}
}
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
x0 += size.x;
b = !b;
}
yb = !yb;
y0 += size.y;
}
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static bool RadialCut (Vector2[] xy, Vector2[] uv, float fill, bool invert, int corner)
{
// Nothing to fill
if (fill < 0.001f) return false;
// Even corners invert the fill direction
if ((corner & 1) == 1) invert = !invert;
// Nothing to adjust
if (!invert && fill > 0.999f) return true;
// Convert 0-1 value into 0 to 90 degrees angle in radians
float angle = Mathf.Clamp01(fill);
if (invert) angle = 1f - angle;
angle *= 90f * Mathf.Deg2Rad;
// Calculate the effective X and Y factors
float cos = Mathf.Cos(angle);
float sin = Mathf.Sin(angle);
RadialCut(xy, cos, sin, invert, corner);
RadialCut(uv, cos, sin, invert, corner);
return true;
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static void RadialCut (Vector2[] xy, float cos, float sin, bool invert, int corner)
{
int i0 = corner;
int i1 = NGUIMath.RepeatIndex(corner + 1, 4);
int i2 = NGUIMath.RepeatIndex(corner + 2, 4);
int i3 = NGUIMath.RepeatIndex(corner + 3, 4);
if ((corner & 1) == 1)
{
if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i2].x = xy[i1].x;
}
}
else if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i2].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i3].y = xy[i2].y;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (!invert) xy[i3].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
else xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
}
else
{
if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i2].y = xy[i1].y;
}
}
else if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i2].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i3].x = xy[i2].x;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (invert) xy[i3].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
else xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
}
}
/// <summary>
/// Helper function that adds the specified values to the buffers.
/// </summary>
static void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols,
float v0x, float v1x, float v0y, float v1y, float u0x, float u1x, float u0y, float u1y, Color col)
{
verts.Add(new Vector3(v0x, v0y));
verts.Add(new Vector3(v0x, v1y));
verts.Add(new Vector3(v1x, v1y));
verts.Add(new Vector3(v1x, v0y));
uvs.Add(new Vector2(u0x, u0y));
uvs.Add(new Vector2(u0x, u1y));
uvs.Add(new Vector2(u1x, u1y));
uvs.Add(new Vector2(u1x, u0y));
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
}
#endregion // Fill functions
}
| |
//
// KeyInfoX509Data.cs - KeyInfoX509Data implementation for XML Signature
//
// Authors:
// Sebastien Pouliot <[email protected]>
// Atsushi Enomoto ([email protected])
// Tim Coleman ([email protected])
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) Tim Coleman, 2004
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Collections;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
namespace System.Security.Cryptography.Xml {
public class KeyInfoX509Data : KeyInfoClause {
private byte[] x509crl;
private ArrayList IssuerSerialList;
private ArrayList SubjectKeyIdList;
private ArrayList SubjectNameList;
private ArrayList X509CertificateList;
public KeyInfoX509Data ()
{
}
public KeyInfoX509Data (byte[] rgbCert)
{
#if NET_2_0
if (rgbCert == null)
throw new ArgumentException ("rgbCert");
#endif
AddCertificate (new X509Certificate (rgbCert));
}
public KeyInfoX509Data (X509Certificate cert)
{
AddCertificate (cert);
}
#if NET_2_0
public KeyInfoX509Data (X509Certificate cert, X509IncludeOption includeOption)
{
if (cert == null)
throw new ArgumentNullException ("cert");
switch (includeOption) {
case X509IncludeOption.None:
case X509IncludeOption.EndCertOnly:
AddCertificate (cert);
break;
case X509IncludeOption.ExcludeRoot:
AddCertificatesChainFrom (cert, false);
break;
case X509IncludeOption.WholeChain:
AddCertificatesChainFrom (cert, true);
break;
}
}
// this gets complicated because we must:
// 1. build the chain using a X509Certificate2 class;
// 2. test for root using the Mono.Security.X509.X509Certificate class;
// 3. add the certificates as X509Certificate instances;
private void AddCertificatesChainFrom (X509Certificate cert, bool root)
{
X509Chain chain = new X509Chain ();
chain.Build (new X509Certificate2 (cert));
foreach (X509ChainElement ce in chain.ChainElements) {
byte[] rawdata = ce.Certificate.RawData;
if (!root) {
// exclude root
Mono.Security.X509.X509Certificate mx = new Mono.Security.X509.X509Certificate (rawdata);
if (mx.IsSelfSigned)
rawdata = null;
}
if (rawdata != null)
AddCertificate (new X509Certificate (rawdata));
}
}
#endif
public ArrayList Certificates {
get { return X509CertificateList; }
}
public byte[] CRL {
get { return x509crl; }
set { x509crl = value; }
}
public ArrayList IssuerSerials {
get { return IssuerSerialList; }
}
public ArrayList SubjectKeyIds {
get { return SubjectKeyIdList; }
}
public ArrayList SubjectNames {
get { return SubjectNameList; }
}
public void AddCertificate (X509Certificate certificate)
{
#if NET_2_0
if (certificate == null)
throw new ArgumentNullException ("certificate");
#endif
if (X509CertificateList == null)
X509CertificateList = new ArrayList ();
X509CertificateList.Add (certificate);
}
public void AddIssuerSerial (string issuerName, string serialNumber)
{
#if NET_2_0
if (issuerName == null)
throw new ArgumentException ("issuerName");
#endif
if (IssuerSerialList == null)
IssuerSerialList = new ArrayList ();
X509IssuerSerial xis = new X509IssuerSerial (issuerName, serialNumber);
IssuerSerialList.Add (xis);
}
public void AddSubjectKeyId (byte[] subjectKeyId)
{
if (SubjectKeyIdList == null)
SubjectKeyIdList = new ArrayList ();
SubjectKeyIdList.Add (subjectKeyId);
}
#if NET_2_0
[ComVisible (false)]
public void AddSubjectKeyId (string subjectKeyId)
{
if (SubjectKeyIdList == null)
SubjectKeyIdList = new ArrayList ();
byte[] id = null;
if (subjectKeyId != null)
id = Convert.FromBase64String (subjectKeyId);
SubjectKeyIdList.Add (id);
}
#endif
public void AddSubjectName (string subjectName)
{
if (SubjectNameList == null)
SubjectNameList = new ArrayList ();
SubjectNameList.Add (subjectName);
}
public override XmlElement GetXml ()
{
#if !NET_2_0
// sanity check
int count = 0;
if (IssuerSerialList != null)
count += IssuerSerialList.Count;
if (SubjectKeyIdList != null)
count += SubjectKeyIdList.Count;
if (SubjectNameList != null)
count += SubjectNameList.Count;
if (X509CertificateList != null)
count += X509CertificateList.Count;
if ((x509crl == null) && (count == 0))
throw new CryptographicException ("value");
#endif
XmlDocument document = new XmlDocument ();
XmlElement xel = document.CreateElement (XmlSignature.ElementNames.X509Data, XmlSignature.NamespaceURI);
// FIXME: hack to match MS implementation
xel.SetAttribute ("xmlns", XmlSignature.NamespaceURI);
// <X509IssuerSerial>
if ((IssuerSerialList != null) && (IssuerSerialList.Count > 0)) {
foreach (X509IssuerSerial iser in IssuerSerialList) {
XmlElement isl = document.CreateElement (XmlSignature.ElementNames.X509IssuerSerial, XmlSignature.NamespaceURI);
XmlElement xin = document.CreateElement (XmlSignature.ElementNames.X509IssuerName, XmlSignature.NamespaceURI);
xin.InnerText = iser.IssuerName;
isl.AppendChild (xin);
XmlElement xsn = document.CreateElement (XmlSignature.ElementNames.X509SerialNumber, XmlSignature.NamespaceURI);
xsn.InnerText = iser.SerialNumber;
isl.AppendChild (xsn);
xel.AppendChild (isl);
}
}
// <X509SKI>
if ((SubjectKeyIdList != null) && (SubjectKeyIdList.Count > 0)) {
foreach (byte[] skid in SubjectKeyIdList) {
XmlElement ski = document.CreateElement (XmlSignature.ElementNames.X509SKI, XmlSignature.NamespaceURI);
ski.InnerText = Convert.ToBase64String (skid);
xel.AppendChild (ski);
}
}
// <X509SubjectName>
if ((SubjectNameList != null) && (SubjectNameList.Count > 0)) {
foreach (string subject in SubjectNameList) {
XmlElement sn = document.CreateElement (XmlSignature.ElementNames.X509SubjectName, XmlSignature.NamespaceURI);
sn.InnerText = subject;
xel.AppendChild (sn);
}
}
// <X509Certificate>
if ((X509CertificateList != null) && (X509CertificateList.Count > 0)) {
foreach (X509Certificate x509 in X509CertificateList) {
XmlElement cert = document.CreateElement (XmlSignature.ElementNames.X509Certificate, XmlSignature.NamespaceURI);
cert.InnerText = Convert.ToBase64String (x509.GetRawCertData ());
xel.AppendChild (cert);
}
}
// only one <X509CRL>
if (x509crl != null) {
XmlElement crl = document.CreateElement (XmlSignature.ElementNames.X509CRL, XmlSignature.NamespaceURI);
crl.InnerText = Convert.ToBase64String (x509crl);
xel.AppendChild (crl);
}
return xel;
}
public override void LoadXml (XmlElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
if (IssuerSerialList != null)
IssuerSerialList.Clear ();
if (SubjectKeyIdList != null)
SubjectKeyIdList.Clear ();
if (SubjectNameList != null)
SubjectNameList.Clear ();
if (X509CertificateList != null)
X509CertificateList.Clear ();
x509crl = null;
if ((element.LocalName != XmlSignature.ElementNames.X509Data) || (element.NamespaceURI != XmlSignature.NamespaceURI))
throw new CryptographicException ("element");
XmlElement [] xnl = null;
// <X509IssuerSerial>
xnl = XmlSignature.GetChildElements (element, XmlSignature.ElementNames.X509IssuerSerial);
if (xnl != null) {
for (int i=0; i < xnl.Length; i++) {
XmlElement xel = (XmlElement) xnl[i];
XmlElement issuer = XmlSignature.GetChildElement (xel, XmlSignature.ElementNames.X509IssuerName, XmlSignature.NamespaceURI);
XmlElement serial = XmlSignature.GetChildElement (xel, XmlSignature.ElementNames.X509SerialNumber, XmlSignature.NamespaceURI);
AddIssuerSerial (issuer.InnerText, serial.InnerText);
}
}
// <X509SKI>
xnl = XmlSignature.GetChildElements (element, XmlSignature.ElementNames.X509SKI);
if (xnl != null) {
for (int i=0; i < xnl.Length; i++) {
byte[] skid = Convert.FromBase64String (xnl[i].InnerXml);
AddSubjectKeyId (skid);
}
}
// <X509SubjectName>
xnl = XmlSignature.GetChildElements (element, XmlSignature.ElementNames.X509SubjectName);
if (xnl != null) {
for (int i=0; i < xnl.Length; i++) {
AddSubjectName (xnl[i].InnerXml);
}
}
// <X509Certificate>
xnl = XmlSignature.GetChildElements (element, XmlSignature.ElementNames.X509Certificate);
if (xnl != null) {
for (int i=0; i < xnl.Length; i++) {
byte[] cert = Convert.FromBase64String (xnl[i].InnerXml);
AddCertificate (new X509Certificate (cert));
}
}
// only one <X509CRL>
XmlElement x509el = XmlSignature.GetChildElement (element, XmlSignature.ElementNames.X509CRL, XmlSignature.NamespaceURI);
if (x509el != null) {
x509crl = Convert.FromBase64String (x509el.InnerXml);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;
using CslaGenerator.Controls;
using CslaGenerator.Data;
using CslaGenerator.Metadata;
using CslaGenerator.Util;
using CslaGenerator.Util.PropertyBags;
using DBSchemaInfo.Base;
using WeifenLuo.WinFormsUI.Docking;
namespace CslaGenerator
{
public class GeneratorController : IDisposable
{
#region Main (application entry point)
/// <summary>
/// The main entry point for the application.
/// </summary>
/// <param name="args">
/// Command line arguments. First arg can be a filename to load.
/// </param>
[STAThread]
static void Main(string[] args)
{
var controller = new GeneratorController();
controller.MainForm.Closing += controller.GeneratorFormClosing;
controller.CommandLineArgs = args;
// process the command line args here so we have a UI, also, we can not process in Init without
// modifying more code to take args[]
controller.ProcessCommandLineArgs();
Application.Run();
}
#endregion
#region Private Fields
private string[] _commandlineArgs;
private CslaGeneratorUnit _currentUnit;
private CslaObjectInfo _currentCslaObject;
private AssociativeEntity _currentAssociativeEntitiy;
private string _currentFilePath = string.Empty;
private MainForm _mainForm;
private static ICatalog _catalog;
private static GeneratorController _current;
private readonly PropertyContext _propertyContext = new PropertyContext();
internal bool IsDBConnected = false;
internal bool IsLoading = false;
internal bool HasErrors = false;
internal bool HasWarnings = false;
internal Stopwatch LoadingTimer = new Stopwatch();
internal int Tables;
internal int Views;
internal int Sprocs;
#endregion
#region Constructors/Dispose
internal GeneratorController()
{
Init();
_current = this;
GetConfig();
}
private void Init()
{
_mainForm = new MainForm(this);
_mainForm.ProjectPanel.SelectedItemsChanged += CslaObjectList_SelectedItemsChanged;
_mainForm.ProjectPanel.LastItemRemoved += delegate { _currentCslaObject = null; };
_mainForm.ObjectRelationsBuilderPanel.SelectedItemsChanged += AssociativeEntitiesList_SelectedItemsChanged;
_mainForm.Show();
_mainForm.formSizePosition.RestoreFormSizePosition();
}
public void Dispose()
{
}
/// <summary>
/// Processes command line args passed to CSLA Gen. Called after the generator is created.
/// </summary>
private void ProcessCommandLineArgs()
{
if (CommandLineArgs.Length > 0)
{
string filename = CommandLineArgs[0];
if (File.Exists(filename))
{
// request that the UI load the project, since it keeps track
// of *additional* state (isNew) that this class is unaware of.
_mainForm.OpenProjectFile(filename);
}
}
}
#endregion
#region internal Properties
internal CslaGeneratorUnit CurrentUnit
{
get { return _currentUnit; }
private set
{
_mainForm.ObjectRelationsBuilderPanel.Show(_mainForm.DockPanel);
if (_currentUnit != null)
{
if (_mainForm.ProjectPropertiesPanel != null && !_mainForm.ProjectPropertiesPanel.IsDisposed)
{
if (_mainForm.ProjectPropertiesPanel.Visible)
_mainForm.ProjectPropertiesPanel.Close();
_mainForm.ProjectPropertiesPanel.Dispose();
}
}
_currentUnit = value;
if (_mainForm.ProjectPropertiesPanel != null)
{
_mainForm.ProjectPropertiesPanel.Close();
_mainForm.ProjectPropertiesPanel.Dispose();
}
_mainForm.ProjectPropertiesPanel = new ProjectProperties();
_mainForm.ProjectPropertiesPanel.LoadInfo();
_mainForm.ActivateShowProjectProperties();
}
}
internal CslaGeneratorUnitLayout CurrentUnitLayout { get; set; }
internal string TemplatesDirectory { get; set; }
internal string ProjectsDirectory { get; set; }
internal string ObjectsDirectory { get; set; }
internal string RulesDirectory { get; set; }
internal List<string> MruItems { get; set; }
internal string[] CommandLineArgs
{
get { return _commandlineArgs; }
set { _commandlineArgs = value; }
}
internal ProjectProperties CurrentProjectProperties
{
get { return _mainForm.ProjectPropertiesPanel; }
}
internal MainForm MainForm
{
get { return _mainForm; }
set { _mainForm = value; }
}
internal string CurrentFilePath
{
get { return _currentFilePath; }
set { _currentFilePath = value; }
}
internal static ICatalog Catalog
{
get { return _catalog; }
set { _catalog = value; }
}
internal static GeneratorController Current
{
get { return _current; }
}
#endregion
#region internal Methods
internal void Connect()
{
var frmConn = new ConnectionForm();
var result = frmConn.ShowDialog();
if (result == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
BuildSchemaTree(ConnectionFactory.ConnectionString);
Cursor.Current = Cursors.Default;
IsDBConnected = true;
}
}
internal void Load(string filePath)
{
IsLoading = true;
LoadingTimer.Restart();
FileStream fs = null;
try
{
Cursor.Current = Cursors.WaitCursor;
var deserialized = false;
while (!deserialized)
{
try
{
fs = File.Open(filePath, FileMode.Open);
var xml = new XmlSerializer(typeof (CslaGeneratorUnit));
CurrentUnit = (CslaGeneratorUnit) xml.Deserialize(fs);
deserialized = true;
}
catch (InvalidOperationException exception)
{
if (exception.InnerException == null)
throw;
fs.Close();
string[] fileLines = File.ReadAllLines(filePath);
var fileVersion = FileVersion.ExtractFileVersion(fileLines);
if (fileVersion == FileVersion.CurrentFileVersion)
throw;
fileLines = FileVersion.HandleFileVersion(fileVersion, fileLines);
File.WriteAllLines(filePath, fileLines);
}
}
_currentUnit.ResetParent();
_currentCslaObject = null;
_currentAssociativeEntitiy = null;
_currentFilePath = GetFilePath(filePath);
ConnectionFactory.ConnectionString = _currentUnit.ConnectionString;
// check if this is a valid connection, else let the user enter new connection info
SqlConnection cn = null;
try
{
cn = ConnectionFactory.NewConnection;
cn.Open();
BuildSchemaTree(_currentUnit.ConnectionString);
IsDBConnected = true;
}
catch //(SqlException e)
{
// call connect function which will allow user to enter new info
Connect();
}
finally
{
if (cn != null && cn.State == ConnectionState.Open)
{
cn.Close();
}
}
BindControls();
_currentUnit.CslaObjects.ListChanged += CslaObjects_ListChanged;
foreach (var info in _currentUnit.CslaObjects)
{
info.InheritedType.Parent = info;
}
if (_currentUnit.CslaObjects.Count > 0)
{
if (_mainForm.ProjectPanel.ListObjects.Items.Count > 0)
{
_currentCslaObject = (CslaObjectInfo)_mainForm.ProjectPanel.ListObjects.Items[0];
}
else
{
_currentCslaObject = null;
}
if (_mainForm.DbSchemaPanel != null)
_mainForm.DbSchemaPanel.CslaObjectInfo = _currentCslaObject;
}
else
{
_currentCslaObject = null;
if (_mainForm.DbSchemaPanel != null)
_mainForm.DbSchemaPanel.CslaObjectInfo = null;
}
_mainForm.ProjectPanel.ApplyFiltersPresenter();
_currentUnit.AssociativeEntities.ListChanged += AssociativeEntities_ListChanged;
/*if (_currentUnit.AssociativeEntities.Count > 0)
{
_currentAssociativeEntitiy = _currentUnit.AssociativeEntities[0];
}
else
{
_currentAssociativeEntitiy = null;
_frmGenerator.ObjectRelationsBuilder.PropertyGrid1.SelectedObject = null;
_frmGenerator.ObjectRelationsBuilder.PropertyGrid2.SelectedObject = null;
_frmGenerator.ObjectRelationsBuilder.PropertyGrid3.SelectedObject = null;
}*/
}
catch (Exception e)
{
var message = filePath + Environment.NewLine + e.Message;
if (e.InnerException != null)
message += Environment.NewLine + e.InnerException.Message;
MessageBox.Show(_mainForm, message, "Loading File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor.Current = Cursors.Default;
fs.Close();
}
LoadProjectLayout(filePath);
IsLoading = false;
LoadingTimer.Stop();
/*if (File.Exists(MainForm.DockSettingsFile))
{
MainForm.DockPanel.SuspendLayout(true);
MainForm.CloseDockContents();
MainForm.DockPanel.LoadFromXml(MainForm.DockSettingsFile, MainForm.DeserializeDockContent);
MainForm.DockPanel.ResumeLayout(true, true);
ShowStartPage();
PanelsSetUp();
}*/
}
internal void LoadProjectLayout(string filePath)
{
filePath = ExtractPathWithoutExtension(filePath) + ".Layout";
if (File.Exists(filePath))
{
var fs = File.Open(filePath, FileMode.Open);
var xml = new XmlSerializer(typeof(CslaGeneratorUnitLayout));
CurrentUnitLayout = (CslaGeneratorUnitLayout)xml.Deserialize(fs);
fs.Close();
MainForm.SetProjectState();
}
}
private void CslaObjects_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemChanged)
{
if (e.PropertyDescriptor.Name == "ObjectType" && _mainForm.ProjectPanel.FilterTypeIsActive)
ReloadPropertyGrid();
}
}
private void AssociativeEntities_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemChanged)
{
if (e.PropertyDescriptor.Name == "ObjectName" || e.PropertyDescriptor.Name == "RelationType")
ReloadBuilderPropertyGrid();
}
}
internal void NewCslaUnit()
{
CurrentUnit = new CslaGeneratorUnit();
CurrentUnitLayout = new CslaGeneratorUnitLayout();
_currentFilePath = Path.GetTempPath() + @"\" + Guid.NewGuid().ToString();
_currentCslaObject = null;
_currentUnit.ConnectionString = ConnectionFactory.ConnectionString;
BindControls();
EnableButtons();
_mainForm.ObjectInfoGrid.SelectedObject = null;
}
internal void Save(string filePath)
{
if (!_mainForm.ApplyProjectProperties())
return;
FileStream fs = null;
var tempFile = Path.GetTempPath() + Guid.NewGuid().ToString() + ".cslagenerator";
var success = false;
try
{
Cursor.Current = Cursors.WaitCursor;
fs = File.Open(tempFile, FileMode.Create);
var s = new XmlSerializer(typeof(CslaGeneratorUnit));
s.Serialize(fs, _currentUnit);
success = true;
}
catch (Exception e)
{
MessageBox.Show(_mainForm, @"An error occurred while trying to save: " + Environment.NewLine + e.Message, "Save Error");
}
finally
{
Cursor.Current = Cursors.Default;
fs.Close();
}
if (success)
{
File.Delete(filePath);
File.Move(tempFile, filePath);
_currentFilePath = GetFilePath(filePath);
}
SaveProjectLayout(filePath);
}
internal void SaveProjectLayout(string filePath)
{
_mainForm.GetProjectState();
filePath = ExtractPathWithoutExtension(filePath) + ".Layout";
FileStream fs = null;
var tempFile = Path.GetTempPath() + Guid.NewGuid().ToString() + ".cslagenerator";
var success = false;
try
{
Cursor.Current = Cursors.WaitCursor;
fs = File.Open(tempFile, FileMode.Create);
var s = new XmlSerializer(typeof(CslaGeneratorUnitLayout));
s.Serialize(fs, CurrentUnitLayout);
success = true;
}
catch (Exception e)
{
MessageBox.Show(_mainForm, @"An error occurred while trying to save: " + Environment.NewLine + e.Message, "Save Error");
}
finally
{
Cursor.Current = Cursors.Default;
fs.Close();
}
if (success)
{
File.Delete(filePath);
File.Move(tempFile, filePath);
File.SetAttributes(filePath, FileAttributes.Hidden);
}
}
internal static string ExtractFilename(string filePath)
{
var slash = filePath.LastIndexOf('\\');
if (slash > 0)
return filePath.Substring(slash + 1);
return filePath;
}
internal static string ExtractPathWithoutExtension(string filePath)
{
var dot = filePath.LastIndexOf('.');
if (dot > 0)
return filePath.Substring(0, dot);
return filePath;
}
#endregion
#region private Methods
private string GetFilePath(string fileName)
{
var fi = new FileInfo(fileName);
return fi.Directory.FullName;
}
private void BindControls()
{
if (_currentUnit != null)
{
_mainForm.ProjectNameTextBox.Enabled = true;
_mainForm.ProjectNameTextBox.DataBindings.Clear();
_mainForm.ProjectNameTextBox.DataBindings.Add("Text", _currentUnit, "ProjectName");
_mainForm.TargetDirectoryButton.Enabled = true;
_mainForm.TargetDirectoryTextBox.Enabled = true;
_mainForm.TargetDirectoryTextBox.DataBindings.Clear();
_mainForm.TargetDirectoryTextBox.DataBindings.Add("Text", _currentUnit, "TargetDirectory");
BindCslaList();
BindRelationsList();
}
}
private void BindCslaList()
{
if (_currentUnit != null)
{
_mainForm.ProjectPanel.Objects = _currentUnit.CslaObjects;
_mainForm.ProjectPanel.ApplyFilters(true);
_mainForm.ProjectPanel.ListObjects.ClearSelected();
if (_mainForm.ProjectPanel.ListObjects.Items.Count > 0)
_mainForm.ProjectPanel.ListObjects.SelectedIndex = 0;
// make sure the previous stored selection is cleared
_mainForm.ProjectPanel.ClearSelectedItems();
}
}
private void BindRelationsList()
{
if (_currentUnit != null)
{
_mainForm.ObjectRelationsBuilderPanel.AssociativeEntities = _currentUnit.AssociativeEntities;
_mainForm.ObjectRelationsBuilderPanel.FillViews(true);
_mainForm.ObjectRelationsBuilderPanel.GetCurrentListBox().ClearSelected();
if (_mainForm.ObjectRelationsBuilderPanel.GetCurrentListBox().Items.Count > 0)
_mainForm.ObjectRelationsBuilderPanel.GetCurrentListBox().SelectedIndex = 0;
// make sure the previous stored selection is cleared
_mainForm.ObjectRelationsBuilderPanel.ClearSelectedItems();
}
}
private void BuildSchemaTree(string connectionString)
{
try
{
if (_mainForm.DbSchemaPanel != null && _mainForm.DbSchemaPanel.Visible)
_mainForm.DbSchemaPanel.Hide();
if (_mainForm.DbSchemaPanel != null)
{
_mainForm.DbSchemaPanel.Close();
_mainForm.DbSchemaPanel.Dispose();
}
_mainForm.DbSchemaPanel = new DbSchemaPanel(_currentUnit, _currentCslaObject, connectionString);
_mainForm.DbSchemaPanel.BuildSchemaTree();
_mainForm.ActivateShowSchema();
_mainForm.DbSchemaPanel.SetDbColumnsPctHeight(73);
_mainForm.DbSchemaPanel.SetDbTreeViewPctHeight(73);
}
catch (Exception e)
{
throw (e);
}
}
private void EnableButtons()
{
//TODO: This needs to be applied to menu
//frmGenerator.AddPropertiesButtton.Enabled = true;
//frmGenerator.AddObjectButton.Enabled = true;
//frmGenerator.DeleteObjectButton.Enabled = true;
//frmGenerator.SaveButton.Enabled = true;
//frmGenerator.DuplicateButton.Enabled = true;
//frmGenerator.ConnectButton.Enabled = true;
//frmGenerator.SelectDirectoryButton.Enabled = true;
}
private string GetFileNameWithoutExtension(string fileName)
{
int index = fileName.LastIndexOf(".");
if (index >= 0)
{
return fileName.Substring(0, index);
}
return fileName;
}
private string GetFileExtension(string fileName)
{
int index = fileName.LastIndexOf(".");
if (index >= 0)
{
return fileName.Substring(index + 1);
}
return ".cs";
}
private string GetTemplateName(CslaObjectInfo info)
{
switch (info.ObjectType)
{
case CslaObjectType.EditableRoot:
return ConfigurationManager.AppSettings["EditableRootTemplate"];
case CslaObjectType.EditableChild:
return ConfigurationManager.AppSettings["EditableChildTemplate"];
case CslaObjectType.EditableRootCollection:
return ConfigurationManager.AppSettings["EditableRootCollectionTemplate"];
case CslaObjectType.EditableChildCollection:
return ConfigurationManager.AppSettings["EditableChildCollectionTemplate"];
case CslaObjectType.EditableSwitchable:
return ConfigurationManager.AppSettings["EditableSwitchableTemplate"];
case CslaObjectType.DynamicEditableRoot:
return ConfigurationManager.AppSettings["DynamicEditableRootTemplate"];
case CslaObjectType.DynamicEditableRootCollection:
return ConfigurationManager.AppSettings["DynamicEditableRootCollectionTemplate"];
case CslaObjectType.ReadOnlyObject:
return ConfigurationManager.AppSettings["ReadOnlyObjectTemplate"];
case CslaObjectType.ReadOnlyCollection:
return ConfigurationManager.AppSettings["ReadOnlyCollectionTemplate"];
default:
return String.Empty;
}
}
#endregion
#region Event Handlers
private void GeneratorFormClosing(object sender, CancelEventArgs e)
{
Application.Exit();
}
private void CslaObjectList_SelectedItemsChanged(object sender, EventArgs e)
{
// fired on "ObjectName" changed for the following scenario:
// Suppose we have a filter on the name,
// and we change the object name in such way that
// the object isn't visible any longer,
// and it must not be shown on the PropertyGrid
// THEN we need to reload the PropertyGrid
ReloadPropertyGrid();
}
private void AssociativeEntitiesList_SelectedItemsChanged(object sender, EventArgs e)
{
ReloadBuilderPropertyGrid();
}
// changed visibility so ActiveObjects settings can be hidden dynamicaly
internal void ReloadPropertyGrid()
{
if (_mainForm.DbSchemaPanel != null)
_mainForm.DbSchemaPanel.CslaObjectInfo = null;
var selectedItems = new List<CslaObjectInfo>();
foreach (CslaObjectInfo obj in _mainForm.ProjectPanel.ListObjects.SelectedItems)
{
selectedItems.Add(obj);
if (!IsLoading && _mainForm.DbSchemaPanel != null)
{
_currentCslaObject = obj;
_mainForm.DbSchemaPanel.CslaObjectInfo = obj;
}
}
if (_mainForm.DbSchemaPanel != null && selectedItems.Count != 1)
{
_currentCslaObject = null;
_mainForm.DbSchemaPanel.CslaObjectInfo = null;
}
if (selectedItems.Count == 0)
_mainForm.ObjectInfoGrid.SelectedObject = null;
else
_mainForm.ObjectInfoGrid.SelectedObject = new PropertyBag(selectedItems.ToArray(), _propertyContext);
}
void ReloadBuilderPropertyGrid()
{
var selectedItems = new List<AssociativeEntity>();
var listBoxSelectedItems = _mainForm.ObjectRelationsBuilderPanel.GetCurrentListBox().SelectedItems;
foreach (AssociativeEntity obj in listBoxSelectedItems)
{
selectedItems.Add(obj);
if (!IsLoading)
{
_currentAssociativeEntitiy = obj;
}
}
if (selectedItems.Count == 0)
{
_currentAssociativeEntitiy = null;
}
else
{
if (_currentAssociativeEntitiy == null)
_currentAssociativeEntitiy = selectedItems[0];
}
_mainForm.ObjectRelationsBuilderPanel.SetAllPropertyGridSelectedObject(_currentAssociativeEntitiy);
}
#endregion
private void GetConfig()
{
GetConfigTemplatesFolder();
GetConfigProjectsFolder();
GetConfigObjectsFolder();
GetConfigRulesFolder();
GetConfigMruItems();
}
private void GetConfigTemplatesFolder()
{
var tDir = ConfigTools.Get("TemplatesDirectory");
if (string.IsNullOrEmpty(tDir))
{
tDir = ConfigTools.OriginalGet("TemplatesDirectory");
while (tDir.LastIndexOf(@"\\") == tDir.Length - 2)
{
tDir = tDir.Substring(0, tDir.Length - 1);
}
}
if (string.IsNullOrEmpty(tDir))
{
TemplatesDirectory = Environment.SpecialFolder.Desktop.ToString();
}
else
{
TemplatesDirectory = tDir;
}
}
private void GetConfigProjectsFolder()
{
var tDir = ConfigTools.Get("ProjectsDirectory");
if (string.IsNullOrEmpty(tDir))
{
tDir = ConfigTools.OriginalGet("ProjectsDirectory");
while (tDir.LastIndexOf(@"\\") == tDir.Length - 2)
{
tDir = tDir.Substring(0, tDir.Length - 1);
}
}
if (string.IsNullOrEmpty(tDir))
{
ProjectsDirectory = Environment.SpecialFolder.Desktop.ToString();
}
else
{
ProjectsDirectory = tDir;
}
}
internal void GetConfigObjectsFolder()
{
var tDir = ConfigTools.Get("ObjectsDirectory");
if (string.IsNullOrEmpty(tDir))
{
tDir = ConfigTools.OriginalGet("ObjectsDirectory");
while (tDir.LastIndexOf(@"\\") == tDir.Length - 2)
{
tDir = tDir.Substring(0, tDir.Length - 1);
}
}
if (string.IsNullOrEmpty(tDir))
{
ObjectsDirectory = Environment.SpecialFolder.Desktop.ToString();
}
else
{
ObjectsDirectory = tDir;
}
}
internal void GetConfigRulesFolder()
{
var tDir = ConfigTools.Get("RulesDirectory");
if (string.IsNullOrEmpty(tDir))
{
tDir = ConfigTools.OriginalGet("RulesDirectory");
while (tDir.LastIndexOf(@"\\") == tDir.Length - 2)
{
tDir = tDir.Substring(0, tDir.Length - 1);
}
}
if (string.IsNullOrEmpty(tDir))
{
RulesDirectory = Environment.SpecialFolder.Desktop.ToString();
}
else
{
RulesDirectory = tDir;
}
}
internal void GetConfigMruItems()
{
var tDir = ConfigTools.Get("RulesDirectory");
if (string.IsNullOrEmpty(tDir))
{
tDir = ConfigTools.OriginalGet("RulesDirectory");
while (tDir.LastIndexOf(@"\\") == tDir.Length - 2)
{
tDir = tDir.Substring(0, tDir.Length - 1);
}
}
if (string.IsNullOrEmpty(tDir))
{
RulesDirectory = Environment.SpecialFolder.Desktop.ToString();
}
else
{
RulesDirectory = tDir;
}
}
internal void ReSortMruItems()
{
string[] original = MruItems.ToArray();
MruItems.Clear();
foreach (var item in original)
{
if(!MruItems.Contains(item))
MruItems.Add(item);
}
ConfigTools.ChangeMru(MruItems);
}
#region Nested CslaObjectInfoComparer
private class CslaObjectInfoComparer : IComparer<CslaObjectInfo>
{
#region IComparer<CslaObjectInfo> Members
public int Compare(CslaObjectInfo x, CslaObjectInfo y)
{
return x.ObjectName.CompareTo(y.ObjectName);
}
#endregion
}
#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.Globalization;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.PropertyNamesShouldNotMatchGetMethodsAnalyzer,
Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpPropertyNamesShouldNotMatchGetMethodsFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.PropertyNamesShouldNotMatchGetMethodsAnalyzer,
Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicPropertyNamesShouldNotMatchGetMethodsFixer>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class PropertyNamesShouldNotMatchGetMethodsTests
{
private const string CSharpTestTemplate = @"
using System;
public class Test
{{
{0} DateTime Date {{ get; }}
{1} string GetDate()
{{
return DateTime.Today.ToString();
}}
}}";
private const string CSharpNotExternallyVisibleTestTemplate = @"
using System;
internal class OuterClass
{{
public class Test
{{
{0} DateTime Date {{ get; }}
{1} string GetDate()
{{
return DateTime.Today.ToString();
}}
}}
}}";
private const string BasicTestTemplate = @"
Imports System
Public Class Test
{0} ReadOnly Property [Date]() As DateTime
Get
Return DateTime.Today
End Get
End Property
{1} Function GetDate() As String
Return Me.Date.ToString()
End Function
End Class";
private const string BasicNotExternallyVisibleTestTemplate = @"
Imports System
Friend Class OuterClass
Public Class Test
{0} ReadOnly Property [Date]() As DateTime
Get
Return DateTime.Today
End Get
End Property
{1} Function GetDate() As String
Return Me.Date.ToString()
End Function
End Class
End Class
";
[Fact]
public async Task CSharp_CA1721_PropertyNameDoesNotMatchGetMethodName_Exposed_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class Test
{
public DateTime Date { get; }
public string GetTime()
{
return DateTime.Today.ToString();
}
}");
}
[Theory]
[InlineData("public", "public")]
[InlineData("public", "protected")]
[InlineData("public", "protected internal")]
[InlineData("protected", "public")]
[InlineData("protected", "protected")]
[InlineData("protected", "protected internal")]
[InlineData("protected internal", "public")]
[InlineData("protected internal", "protected")]
[InlineData("protected internal", "protected internal")]
public async Task CSharp_CA1721_PropertyNamesMatchGetMethodNames_Exposed_Diagnostics(string propertyAccessibility, string methodAccessibility)
{
await VerifyCS.VerifyAnalyzerAsync(
string.Format(CultureInfo.InvariantCulture, CSharpTestTemplate, propertyAccessibility, methodAccessibility),
GetCA1721CSharpResultAt(
line: 6,
column: $" {propertyAccessibility} DateTime ".Length + 1,
identifierName: "Date",
otherIdentifierName: "GetDate"));
await VerifyCS.VerifyAnalyzerAsync(
string.Format(CultureInfo.InvariantCulture, CSharpNotExternallyVisibleTestTemplate, propertyAccessibility, methodAccessibility));
}
[Theory]
[InlineData("private", "private")]
[InlineData("private", "internal")]
[InlineData("internal", "private")]
[InlineData("internal", "internal")]
[InlineData("", "")]
public async Task CSharp_CA1721_PropertyNamesMatchGetMethodNames_Unexposed_NoDiagnostics(string propertyAccessibility, string methodAccessibility)
{
await VerifyCS.VerifyAnalyzerAsync(string.Format(CultureInfo.InvariantCulture, CSharpTestTemplate, propertyAccessibility, methodAccessibility));
}
[Theory, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
[InlineData("public", "private")]
[InlineData("protected", "private")]
[InlineData("protected internal", "private")]
[InlineData("public", "internal")]
[InlineData("protected", "internal")]
[InlineData("protected internal", "internal")]
[InlineData("public", "")]
[InlineData("protected", "")]
[InlineData("protected internal", "")]
[InlineData("private", "public")]
[InlineData("private", "protected")]
[InlineData("private", "protected internal")]
[InlineData("internal", "public")]
[InlineData("internal", "protected")]
[InlineData("internal", "protected internal")]
[InlineData("", "public")]
[InlineData("", "protected")]
[InlineData("", "protected internal")]
public async Task CSharp_CA1721_PropertyNamesMatchGetMethodNames_MixedExposure_NoDiagnostics(string propertyAccessibility, string methodAccessibility)
{
await VerifyCS.VerifyAnalyzerAsync(string.Format(CultureInfo.InvariantCulture, CSharpTestTemplate, propertyAccessibility, methodAccessibility));
}
[Fact]
public async Task CSharp_CA1721_PropertyNameMatchesBaseClassGetMethodName_Exposed_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class SomeClass
{
public string GetDate()
{
return DateTime.Today.ToString();
}
}
public class SometOtherClass : SomeClass
{
public DateTime Date
{
get { return DateTime.Today; }
}
}",
GetCA1721CSharpResultAt(line: 14, column: 21, identifierName: "Date", otherIdentifierName: "GetDate"));
}
[Fact]
public async Task CSharp_CA1721_GetMethodNameMatchesBaseClassPropertyName_Exposed_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class SomeClass
{
public DateTime Date
{
get { return DateTime.Today; }
}
}
public class SometOtherClass : SomeClass
{
public string GetDate()
{
return DateTime.Today.ToString();
}
}",
GetCA1721CSharpResultAt(line: 14, column: 19, identifierName: "Date", otherIdentifierName: "GetDate"));
}
[Fact]
public async Task Basic_CA1721_PropertyNameDoesNotMatchGetMethodName_Exposed_NoDiagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class Test
Public ReadOnly Property [Date]() As DateTime
Get
Return DateTime.Today
End Get
End Property
Public Function GetTime() As String
Return Me.Date.ToString()
End Function
End Class");
}
[Theory, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
[InlineData("Public", "Public")]
[InlineData("Public", "Protected")]
[InlineData("Public", "Protected Friend")]
[InlineData("Protected", "Public")]
[InlineData("Protected", "Protected")]
[InlineData("Protected", "Protected Friend")]
[InlineData("Protected Friend", "Public")]
[InlineData("Protected Friend", "Protected")]
[InlineData("Protected Friend", "Protected Friend")]
public async Task Basic_CA1721_PropertyNamesMatchGetMethodNames_Exposed_Diagnostics(string propertyAccessibility, string methodAccessibility)
{
await VerifyVB.VerifyAnalyzerAsync(
string.Format(CultureInfo.InvariantCulture, BasicTestTemplate, propertyAccessibility, methodAccessibility),
GetCA1721BasicResultAt(
line: 5,
column: $" {propertyAccessibility} ReadOnly Property ".Length + 1,
identifierName: "Date",
otherIdentifierName: "GetDate"));
await VerifyVB.VerifyAnalyzerAsync(
string.Format(CultureInfo.InvariantCulture, BasicNotExternallyVisibleTestTemplate, propertyAccessibility, methodAccessibility));
}
[Theory]
[InlineData("Private", "Private")]
[InlineData("Private", "Friend")]
[InlineData("Friend", "Private")]
[InlineData("Friend", "Friend")]
public async Task Basic_CA1721_PropertyNamesMatchGetMethodNames_Unexposed_NoDiagnostics(string propertyAccessibility, string methodAccessibility)
{
await VerifyVB.VerifyAnalyzerAsync(string.Format(CultureInfo.InvariantCulture, BasicTestTemplate, propertyAccessibility, methodAccessibility));
}
[Theory]
[InlineData("Public", "Private")]
[InlineData("Protected", "Private")]
[InlineData("Protected Friend", "Private")]
[InlineData("Public", "Friend")]
[InlineData("Protected", "Friend")]
[InlineData("Protected Friend", "Friend")]
[InlineData("Private", "Public")]
[InlineData("Private", "Protected")]
[InlineData("Private", "Protected Friend")]
[InlineData("Friend", "Public")]
[InlineData("Friend", "Protected")]
[InlineData("Friend", "Protected Friend")]
public async Task Basic_CA1721_PropertyNamesMatchGetMethodNames_MixedExposure_NoDiagnostics(string propertyAccessibility, string methodAccessibility)
{
await VerifyVB.VerifyAnalyzerAsync(string.Format(CultureInfo.InvariantCulture, BasicTestTemplate, propertyAccessibility, methodAccessibility));
}
[Fact]
public async Task Basic_CA1721_PropertyNameMatchesBaseClassGetMethodName_Exposed_Diagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class SomeClass
Public Function GetDate() As String
Return DateTime.Today.ToString()
End Function
End Class
Public Class SometOtherClass
Inherits SomeClass
Public ReadOnly Property [Date]() As DateTime
Get
Return DateTime.Today
End Get
End Property
End Class",
GetCA1721BasicResultAt(line: 12, column: 30, identifierName: "Date", otherIdentifierName: "GetDate"));
}
[Fact]
public async Task Basic_CA1721_GetMethodNameMatchesBaseClassPropertyName_Exposed_Diagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class SomeClass
Public ReadOnly Property [Date]() As DateTime
Get
Return DateTime.Today
End Get
End Property
End Class
Public Class SometOtherClass
Inherits SomeClass
Public Function GetDate() As String
Return DateTime.Today.ToString()
End Function
End Class",
GetCA1721BasicResultAt(line: 13, column: 21, identifierName: "Date", otherIdentifierName: "GetDate"));
}
[Fact, WorkItem(1374, "https://github.com/dotnet/roslyn-analyzers/issues/1374")]
public async Task CA1721_TypePropertyNoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
class T { }
class C
{
public T Type { get; }
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Class T
End Class
Class C
Public Property Type As T
End Class");
}
[Fact, WorkItem(2085, "https://github.com/dotnet/roslyn-analyzers/issues/2085")]
public async Task CA1721_StaticAndInstanceMismatchNoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class C1
{
public int Value { get; }
public static int GetValue(int i) => i;
}
public class C2
{
public static int Value { get; }
public int GetValue(int i) => i;
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class C1
Public ReadOnly Property Value As Integer
Public Shared Function GetValue(i As Integer) As Integer
Return i
End Function
End Class
Public Class C2
Public Shared ReadOnly Property Value As Integer
Public Function GetValue(i As Integer) As Integer
Return i
End Function
End Class");
}
[Fact, WorkItem(2914, "https://github.com/dotnet/roslyn-analyzers/issues/2914")]
public async Task CA1721_OverrideNoDiagnosticButVirtualDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class BaseClass
{
public virtual int Value { get; }
public virtual int GetValue(int i) => i;
}
public class C1 : BaseClass
{
public override int Value => 42;
}
public class C2 : BaseClass
{
public override int GetValue(int i) => i * 2;
}
public class C3 : BaseClass
{
public override int Value => 42;
public override int GetValue(int i) => i * 2;
}
",
GetCA1721CSharpResultAt(line: 4, column: 24, identifierName: "Value", otherIdentifierName: "GetValue"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class BaseClass
Public Overridable ReadOnly Property Value As Integer
Public Overridable Function GetValue(ByVal i As Integer) As Integer
Return i
End Function
End Class
Public Class C1
Inherits BaseClass
Public Overrides ReadOnly Property Value As Integer
Get
Return 42
End Get
End Property
End Class
Public Class C2
Inherits BaseClass
Public Overrides Function GetValue(ByVal i As Integer) As Integer
Return i * 2
End Function
End Class
Public Class C3
Inherits BaseClass
Public Overrides ReadOnly Property Value As Integer
Get
Return 42
End Get
End Property
Public Overrides Function GetValue(ByVal i As Integer) As Integer
Return i * 2
End Function
End Class
",
GetCA1721BasicResultAt(line: 3, column: 42, identifierName: "Value", otherIdentifierName: "GetValue"));
}
[Fact, WorkItem(2914, "https://github.com/dotnet/roslyn-analyzers/issues/2914")]
public async Task CA1721_OverrideWithLocalMemberDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class BaseClass1
{
public virtual int Value { get; }
}
public class C1 : BaseClass1
{
public override int Value => 42;
public int GetValue(int i) => i;
}
public class BaseClass2
{
public virtual int GetValue(int i) => i;
}
public class C2 : BaseClass2
{
public int Value => 42;
public override int GetValue(int i) => i * 2;
}
",
GetCA1721CSharpResultAt(line: 10, column: 16, identifierName: "Value", otherIdentifierName: "GetValue"),
GetCA1721CSharpResultAt(line: 20, column: 16, identifierName: "Value", otherIdentifierName: "GetValue"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class BaseClass1
Public Overridable ReadOnly Property Value As Integer
End Class
Public Class C1
Inherits BaseClass1
Public Overrides ReadOnly Property Value As Integer
Get
Return 42
End Get
End Property
Public Function GetValue(ByVal i As Integer) As Integer
Return i
End Function
End Class
Public Class BaseClass2
Public Overridable Function GetValue(ByVal i As Integer) As Integer
Return i
End Function
End Class
Public Class C2
Inherits BaseClass2
Public ReadOnly Property Value As Integer
Get
Return 42
End Get
End Property
Public Overrides Function GetValue(ByVal i As Integer) As Integer
Return i * 2
End Function
End Class
",
GetCA1721BasicResultAt(line: 15, column: 21, identifierName: "Value", otherIdentifierName: "GetValue"),
GetCA1721BasicResultAt(line: 29, column: 30, identifierName: "Value", otherIdentifierName: "GetValue"));
}
[Fact, WorkItem(2914, "https://github.com/dotnet/roslyn-analyzers/issues/2914")]
public async Task CA1721_OverrideMultiLevelDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class MyBaseClass
{
public virtual int GetValue(int i) => i;
public virtual int Something { get; }
}
public class MyClass : MyBaseClass
{
public virtual int Value { get; }
public virtual int GetSomething(int i) => i;
}
public class MySubClass : MyClass
{
public override int GetValue(int i) => 2;
public override int Value => 2;
public override int GetSomething(int i) => 2;
public override int Something => 2;
}
",
GetCA1721CSharpResultAt(line: 10, column: 24, identifierName: "Value", otherIdentifierName: "GetValue"),
GetCA1721CSharpResultAt(line: 11, column: 24, identifierName: "Something", otherIdentifierName: "GetSomething"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class MyBaseClass
Public Overridable Function GetValue(ByVal i As Integer) As Integer
Return i
End Function
Public Overridable ReadOnly Property Something As Integer
End Class
Public Class [MyClass]
Inherits MyBaseClass
Public Overridable ReadOnly Property Value As Integer
Public Overridable Function GetSomething(ByVal i As Integer) As Integer
Return i
End Function
End Class
Public Class MySubClass
Inherits [MyClass]
Public Overrides Function GetValue(ByVal i As Integer) As Integer
Return 2
End Function
Public Overrides ReadOnly Property Value As Integer
Get
Return 2
End Get
End Property
Public Overrides Function GetSomething(ByVal i As Integer) As Integer
Return 2
End Function
Public Overrides ReadOnly Property Something As Integer
Get
Return 2
End Get
End Property
End Class
",
GetCA1721BasicResultAt(line: 13, column: 42, identifierName: "Value", otherIdentifierName: "GetValue"),
GetCA1721BasicResultAt(line: 15, column: 33, identifierName: "Something", otherIdentifierName: "GetSomething"));
}
[Fact, WorkItem(2956, "https://github.com/dotnet/roslyn-analyzers/issues/2956")]
public async Task CA1721_Obsolete_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C1
{
[Obsolete(""Use the method."")]
public int PropertyValue => 1;
public int GetPropertyValue()
{
return 1;
}
}
public class C2
{
public int PropertyValue => 1;
[Obsolete(""Use the property."")]
public int GetPropertyValue()
{
return 1;
}
}
public class C3
{
[Obsolete(""Deprecated"")]
public int PropertyValue => 1;
[Obsolete(""Deprecated"")]
public int GetPropertyValue()
{
return 1;
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class C1
<Obsolete(""Use the method."")>
Public ReadOnly Property PropertyValue As Integer
Get
Return 1
End Get
End Property
Public Function GetPropertyValue() As Integer
Return 1
End Function
End Class
Public Class C2
Public ReadOnly Property PropertyValue As Integer
Get
Return 1
End Get
End Property
<Obsolete(""Use the property."")>
Public Function GetPropertyValue() As Integer
Return 1
End Function
End Class
Public Class C3
<Obsolete(""Deprecated"")>
Public ReadOnly Property PropertyValue As Integer
Get
Return 1
End Get
End Property
<Obsolete(""Deprecated"")>
Public Function GetPropertyValue() As Integer
Return 1
End Function
End Class");
}
[Fact, WorkItem(2956, "https://github.com/dotnet/roslyn-analyzers/issues/2956")]
public async Task CA1721_OnlyOneOverloadObsolete_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
public int PropertyValue => 1;
[Obsolete(""Use the property."")]
public int GetPropertyValue()
{
return 1;
}
public int GetPropertyValue(int i)
{
return i;
}
}",
GetCA1721CSharpResultAt(6, 16, "PropertyValue", "GetPropertyValue"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class C
Public ReadOnly Property PropertyValue As Integer
Get
Return 1
End Get
End Property
<Obsolete(""Use the property."")>
Public Function GetPropertyValue() As Integer
Return 1
End Function
Public Function GetPropertyValue(i As Integer) As Integer
Return i
End Function
End Class",
GetCA1721BasicResultAt(5, 30, "PropertyValue", "GetPropertyValue"));
}
[Fact, WorkItem(2956, "https://github.com/dotnet/roslyn-analyzers/issues/2956")]
public async Task CA1721_AllOverloadsObsolete_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
public int PropertyValue => 1;
[Obsolete(""Use the property."")]
public int GetPropertyValue()
{
return 1;
}
[Obsolete(""Use the property."")]
public int GetPropertyValue(int i)
{
return i;
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class C
Public ReadOnly Property PropertyValue As Integer
Get
Return 1
End Get
End Property
<Obsolete(""Use the property."")>
Public Function GetPropertyValue() As Integer
Return 1
End Function
<Obsolete(""Use the property."")>
Public Function GetPropertyValue(i As Integer) As Integer
Return i
End Function
End Class");
}
#region Helpers
private static DiagnosticResult GetCA1721CSharpResultAt(int line, int column, string identifierName, string otherIdentifierName)
=> VerifyCS.Diagnostic()
.WithLocation(line, column)
.WithArguments(identifierName, otherIdentifierName);
private static DiagnosticResult GetCA1721BasicResultAt(int line, int column, string identifierName, string otherIdentifierName)
=> VerifyVB.Diagnostic()
.WithLocation(line, column)
.WithArguments(identifierName, otherIdentifierName);
#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.Internal.Resources
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ManagementLocksOperations operations.
/// </summary>
public partial interface IManagementLocksOperations
{
/// <summary>
/// Creates or updates a management lock at the resource group level.
/// </summary>
/// When you apply a lock at a parent scope, all child resources
/// inherit the same lock. To create management locks, you must have
/// access to Microsoft.Authorization/* or
/// Microsoft.Authorization/locks/* actions. Of the built-in roles,
/// only Owner and User Access Administrator are granted those
/// actions.
/// <param name='resourceGroupName'>
/// The name of the resource group to lock.
/// </param>
/// <param name='lockName'>
/// The lock name. The lock name can be a maximum of 260 characters.
/// It cannot contain <, > %, &, :, \\\\, ?, /, or any
/// control characters.
/// </param>
/// <param name='parameters'>
/// The management lock parameters.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ManagementLockObject>> CreateOrUpdateAtResourceGroupLevelWithHttpMessagesAsync(string resourceGroupName, string lockName, ManagementLockObject parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a management lock at the resource group level.
/// </summary>
/// To delete management locks, you must have access to
/// Microsoft.Authorization/* or Microsoft.Authorization/locks/*
/// actions. Of the built-in roles, only Owner and User Access
/// Administrator are granted those actions.
/// <param name='resourceGroupName'>
/// The name of the resource group containing the lock.
/// </param>
/// <param name='lockName'>
/// The name of lock to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteAtResourceGroupLevelWithHttpMessagesAsync(string resourceGroupName, string lockName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a management lock at the resource group level.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the locked resource group.
/// </param>
/// <param name='lockName'>
/// The name of the lock to get.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ManagementLockObject>> GetAtResourceGroupLevelWithHttpMessagesAsync(string resourceGroupName, string lockName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update a management lock by scope.
/// </summary>
/// <param name='scope'>
/// The scope for the lock. When providing a scope for the assignment,
/// use '/subscriptions/{subscriptionId}' for subscriptions,
/// '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}'
/// for resource groups, and
/// '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}'
/// for resources.
/// </param>
/// <param name='lockName'>
/// The name of lock.
/// </param>
/// <param name='parameters'>
/// Create or update management lock parameters.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ManagementLockObject>> CreateOrUpdateByScopeWithHttpMessagesAsync(string scope, string lockName, ManagementLockObject parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete a management lock by scope.
/// </summary>
/// <param name='scope'>
/// The scope for the lock.
/// </param>
/// <param name='lockName'>
/// The name of lock.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteByScopeWithHttpMessagesAsync(string scope, string lockName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a management lock by scope.
/// </summary>
/// <param name='scope'>
/// The scope for the lock.
/// </param>
/// <param name='lockName'>
/// The name of lock.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ManagementLockObject>> GetByScopeWithHttpMessagesAsync(string scope, string lockName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a management lock at the resource level or any
/// level below the resource.
/// </summary>
/// When you apply a lock at a parent scope, all child resources
/// inherit the same lock. To create management locks, you must have
/// access to Microsoft.Authorization/* or
/// Microsoft.Authorization/locks/* actions. Of the built-in roles,
/// only Owner and User Access Administrator are granted those
/// actions.
/// <param name='resourceGroupName'>
/// The name of the resource group containing the resource to lock.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The resource provider namespace of the resource to lock.
/// </param>
/// <param name='parentResourcePath'>
/// The parent resource identity.
/// </param>
/// <param name='resourceType'>
/// The resource type of the resource to lock.
/// </param>
/// <param name='resourceName'>
/// The name of the resource to lock.
/// </param>
/// <param name='lockName'>
/// The name of lock. The lock name can be a maximum of 260
/// characters. It cannot contain <, > %, &, :, \\\\, ?, /,
/// or any control characters.
/// </param>
/// <param name='parameters'>
/// Parameters for creating or updating a management lock.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ManagementLockObject>> CreateOrUpdateAtResourceLevelWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string lockName, ManagementLockObject parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the management lock of a resource or any level below the
/// resource.
/// </summary>
/// To delete management locks, you must have access to
/// Microsoft.Authorization/* or Microsoft.Authorization/locks/*
/// actions. Of the built-in roles, only Owner and User Access
/// Administrator are granted those actions.
/// <param name='resourceGroupName'>
/// The name of the resource group containing the resource with the
/// lock to delete.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The resource provider namespace of the resource with the lock to
/// delete.
/// </param>
/// <param name='parentResourcePath'>
/// The parent resource identity.
/// </param>
/// <param name='resourceType'>
/// The resource type of the resource with the lock to delete.
/// </param>
/// <param name='resourceName'>
/// The name of the resource with the lock to delete.
/// </param>
/// <param name='lockName'>
/// The name of the lock to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteAtResourceLevelWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string lockName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the management lock of a resource or any level below resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider.
/// </param>
/// <param name='parentResourcePath'>
/// An extra path parameter needed in some services, like SQL
/// Databases.
/// </param>
/// <param name='resourceType'>
/// The type of the resource.
/// </param>
/// <param name='resourceName'>
/// The name of the resource.
/// </param>
/// <param name='lockName'>
/// The name of lock.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ManagementLockObject>> GetAtResourceLevelWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string lockName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a management lock at the subscription level.
/// </summary>
/// When you apply a lock at a parent scope, all child resources
/// inherit the same lock. To create management locks, you must have
/// access to Microsoft.Authorization/* or
/// Microsoft.Authorization/locks/* actions. Of the built-in roles,
/// only Owner and User Access Administrator are granted those
/// actions.
/// <param name='lockName'>
/// The name of lock. The lock name can be a maximum of 260
/// characters. It cannot contain <, > %, &, :, \\\\, ?, /,
/// or any control characters.
/// </param>
/// <param name='parameters'>
/// The management lock parameters.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ManagementLockObject>> CreateOrUpdateAtSubscriptionLevelWithHttpMessagesAsync(string lockName, ManagementLockObject parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the management lock at the subscription level.
/// </summary>
/// To delete management locks, you must have access to
/// Microsoft.Authorization/* or Microsoft.Authorization/locks/*
/// actions. Of the built-in roles, only Owner and User Access
/// Administrator are granted those actions.
/// <param name='lockName'>
/// The name of lock to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteAtSubscriptionLevelWithHttpMessagesAsync(string lockName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a management lock at the subscription level.
/// </summary>
/// <param name='lockName'>
/// The name of the lock to get.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ManagementLockObject>> GetAtSubscriptionLevelWithHttpMessagesAsync(string lockName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the management locks for a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the locks to get.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListAtResourceGroupLevelWithHttpMessagesAsync(string resourceGroupName, ODataQuery<ManagementLockObject> odataQuery = default(ODataQuery<ManagementLockObject>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the management locks for a resource or any level below
/// resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the locked resource. The
/// name is case insensitive.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider.
/// </param>
/// <param name='parentResourcePath'>
/// The parent resource identity.
/// </param>
/// <param name='resourceType'>
/// The resource type of the locked resource.
/// </param>
/// <param name='resourceName'>
/// The name of the locked resource.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListAtResourceLevelWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, ODataQuery<ManagementLockObject> odataQuery = default(ODataQuery<ManagementLockObject>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the management locks for a subscription.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListAtSubscriptionLevelWithHttpMessagesAsync(ODataQuery<ManagementLockObject> odataQuery = default(ODataQuery<ManagementLockObject>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the management locks for a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListAtResourceGroupLevelNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the management locks for a resource or any level below
/// resource.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListAtResourceLevelNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the management locks for a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListAtSubscriptionLevelNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Globalization;
using System.Net.Mail;
namespace System.Net.Mime
{
/// <summary>
/// Summary description for MimePart.
/// </summary>
internal class MimePart: MimeBasePart,IDisposable
{
Stream stream = null;
bool streamSet = false;
bool streamUsedOnce = false;
AsyncCallback readCallback;
AsyncCallback writeCallback;
const int maxBufferSize = 0x4400; //seems optimal for send based on perf analysis
internal MimePart()
{
}
public void Dispose(){
if (stream != null) {
stream.Close();
}
}
internal Stream Stream {
get {
return stream;
}
}
internal ContentDisposition ContentDisposition{
get{
return contentDisposition;
}
set{
contentDisposition = value;
if(value == null){
((HeaderCollection)Headers).InternalRemove(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition));
}
else{
contentDisposition.PersistIfNeeded((HeaderCollection)Headers,true);
}
}
}
internal TransferEncoding TransferEncoding {
get {
string value = Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)];
if (value.Equals("base64", StringComparison.OrdinalIgnoreCase))
return TransferEncoding.Base64;
else if (value.Equals("quoted-printable", StringComparison.OrdinalIgnoreCase))
return TransferEncoding.QuotedPrintable;
else if (value.Equals("7bit", StringComparison.OrdinalIgnoreCase))
return TransferEncoding.SevenBit;
else if (value.Equals("8bit", StringComparison.OrdinalIgnoreCase))
return TransferEncoding.EightBit;
else
return TransferEncoding.Unknown;
}
set {
//QFE 4554
if (value == TransferEncoding.Base64) {
Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)] = "base64";
}
else if (value == TransferEncoding.QuotedPrintable) {
Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)] = "quoted-printable";
}
else if (value == TransferEncoding.SevenBit) {
Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)] = "7bit";
}
else if (value == TransferEncoding.EightBit) {
Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)] = "8bit";
}
else {
throw new NotSupportedException(SR.GetString(SR.MimeTransferEncodingNotSupported, value));
}
}
}
internal void SetContent(Stream stream){
if (stream == null) {
throw new ArgumentNullException("stream");
}
if (streamSet) {
this.stream.Close();
this.stream = null;
streamSet = false;
}
this.stream = stream;
streamSet = true;
streamUsedOnce = false;
TransferEncoding = TransferEncoding.Base64;
}
internal void SetContent(Stream stream, string name, string mimeType) {
if (stream == null) {
throw new ArgumentNullException("stream");
}
if (mimeType != null && mimeType != string.Empty) {
contentType = new ContentType(mimeType);
}
if (name != null && name != string.Empty) {
ContentType.Name = name;
}
SetContent(stream);
}
internal void SetContent(Stream stream, ContentType contentType) {
if (stream == null) {
throw new ArgumentNullException("stream");
}
this.contentType = contentType;
SetContent(stream);
}
internal void Complete(IAsyncResult result, Exception e){
//if we already completed and we got called again,
//it mean's that there was an exception in the callback and we
//should just rethrow it.
MimePartContext context = (MimePartContext)result.AsyncState;
if (context.completed) {
throw e;
}
try{
if(context.outputStream != null){
context.outputStream.Close();
}
}
catch(Exception ex){
if (e == null) {
e = ex;
}
}
context.completed = true;
context.result.InvokeCallback(e);
}
internal void ReadCallback(IAsyncResult result)
{
if (result.CompletedSynchronously ) {
return;
}
((MimePartContext)result.AsyncState).completedSynchronously = false;
try {
ReadCallbackHandler(result);
}
catch(Exception e){
Complete(result,e);
}
}
internal void ReadCallbackHandler(IAsyncResult result){
MimePartContext context = (MimePartContext)result.AsyncState;
context.bytesLeft = Stream.EndRead(result);
if (context.bytesLeft > 0) {
IAsyncResult writeResult = context.outputStream.BeginWrite(context.buffer, 0, context.bytesLeft, writeCallback, context);
if (writeResult.CompletedSynchronously) {
WriteCallbackHandler(writeResult);
}
}
else {
Complete(result,null);
}
}
internal void WriteCallback(IAsyncResult result)
{
if (result.CompletedSynchronously ) {
return;
}
((MimePartContext)result.AsyncState).completedSynchronously = false;
try {
WriteCallbackHandler(result);
}
catch (Exception e) {
Complete(result,e);
}
}
internal void WriteCallbackHandler(IAsyncResult result){
MimePartContext context = (MimePartContext)result.AsyncState;
context.outputStream.EndWrite(result);
IAsyncResult readResult = Stream.BeginRead(context.buffer, 0, context.buffer.Length, readCallback, context);
if (readResult.CompletedSynchronously) {
ReadCallbackHandler(readResult);
}
}
internal Stream GetEncodedStream(Stream stream){
Stream outputStream = stream;
if (TransferEncoding == TransferEncoding.Base64) {
outputStream = new Base64Stream(outputStream, new Base64WriteStateInfo());
}
else if (TransferEncoding == TransferEncoding.QuotedPrintable) {
outputStream = new QuotedPrintableStream(outputStream,true);
}
else if (TransferEncoding == TransferEncoding.SevenBit || TransferEncoding == TransferEncoding.EightBit) {
outputStream = new EightBitStream(outputStream);
}
return outputStream;
}
internal void ContentStreamCallbackHandler(IAsyncResult result){
MimePartContext context = (MimePartContext)result.AsyncState;
Stream outputStream = context.writer.EndGetContentStream(result);
context.outputStream = GetEncodedStream(outputStream);
readCallback = new AsyncCallback(ReadCallback);
writeCallback = new AsyncCallback(WriteCallback);
IAsyncResult readResult = Stream.BeginRead(context.buffer, 0, context.buffer.Length,readCallback, context);
if (readResult.CompletedSynchronously) {
ReadCallbackHandler(readResult);
}
}
internal void ContentStreamCallback(IAsyncResult result)
{
if (result.CompletedSynchronously ) {
return;
}
((MimePartContext)result.AsyncState).completedSynchronously = false;
try{
ContentStreamCallbackHandler(result);
}
catch (Exception e) {
Complete(result,e);
}
}
internal class MimePartContext
{
internal MimePartContext(BaseWriter writer, LazyAsyncResult result)
{
this.writer = writer;
this.result = result;
buffer = new byte[maxBufferSize];
}
internal Stream outputStream;
internal LazyAsyncResult result;
internal int bytesLeft;
internal BaseWriter writer;
internal byte[] buffer;
internal bool completed;
internal bool completedSynchronously = true;
}
internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback, bool allowUnicode,
object state)
{
PrepareHeaders(allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
MimePartAsyncResult result = new MimePartAsyncResult(this, state, callback);
MimePartContext context = new MimePartContext(writer, result);
ResetStream();
streamUsedOnce = true;
IAsyncResult contentResult = writer.BeginGetContentStream(new AsyncCallback(ContentStreamCallback),context);
if (contentResult.CompletedSynchronously) {
ContentStreamCallbackHandler(contentResult);
}
return result;
}
internal override void Send(BaseWriter writer, bool allowUnicode) {
if (Stream != null) {
byte[] buffer = new byte[maxBufferSize];
PrepareHeaders(allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
Stream outputStream = writer.GetContentStream();
outputStream = GetEncodedStream(outputStream);
int read;
ResetStream();
streamUsedOnce = true;
while ((read = Stream.Read(buffer, 0, maxBufferSize)) > 0) {
outputStream.Write(buffer, 0, read);
}
outputStream.Close();
}
}
//Ensures that if we've used the stream once, we will either reset it to the origin, or throw.
internal void ResetStream(){
if (streamUsedOnce) {
if (Stream.CanSeek) {
Stream.Seek(0,SeekOrigin.Begin);
streamUsedOnce = false;
}
else{
throw new InvalidOperationException(SR.GetString(SR.MimePartCantResetStream));
}
}
}
}
}
| |
/* 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:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using XenAdmin;
using XenAPI;
using System.Collections;
using XenAdmin.Properties;
using XenAdmin.Actions;
using XenAdmin.Core;
namespace XenAdmin.SettingsPanels
{
public partial class BootOptionsEditPage : UserControl, IEditPage
{
#region Private fields
private VM vm;
private bool bootFromCD;
#endregion
public BootOptionsEditPage()
{
InitializeComponent();
Text = Messages.GENERAL_HEADING_BOOT_OPTIONS;
}
#region IEditPage implementation
public bool ValidToSave { get { return true; } }
/// <summary>
/// Show local validation balloon tooltips
/// </summary>
public void ShowLocalValidationMessages()
{ }
/// <summary>
/// Unregister listeners, dispose balloon tooltips, etc.
/// </summary>
public void Cleanup()
{ }
public bool HasChanged
{
get
{
bool autoBootChanged = Helpers.BostonOrGreater(vm.Connection) ? false : m_checkBoxAutoBoot.Checked != vm.AutoPowerOn;
return autoBootChanged || (vm.IsHVM && GetOrder() != vm.BootOrder) || (m_textBoxOsParams.Text != vm.PV_args) || (VMPVBootableDVD() != bootFromCD);
}
}
public AsyncAction SaveSettings()
{
vm.BootOrder = GetOrder();
if (!Helpers.BostonOrGreater(vm.Connection))
vm.AutoPowerOn = m_checkBoxAutoBoot.Checked;
vm.PV_args = m_textBoxOsParams.Text;
return new DelegatedAsyncAction(vm.Connection, "Change VBDs bootable", "Change VBDs bootable", null,
delegate(Session session)
{
if (bootFromCD)
{
foreach (var vbd in vm.Connection.ResolveAll(vm.VBDs))
VBD.set_bootable(session, vbd.opaque_ref, vbd.IsCDROM);
}
else
{
// The lowest numbered disk is the system disk and we should set it to bootable: see CA-47457
List<VBD> vbds = vm.Connection.ResolveAll(vm.VBDs);
vbds.Sort((vbd1, vbd2) =>
{
if (vbd1.userdevice == "xvda")
return -1;
if (vbd2.userdevice == "xvda")
return 1;
return StringUtility.NaturalCompare(vbd1.userdevice,
vbd2.userdevice);
});
bool foundSystemDisk = false;
foreach (var vbd in vbds)
{
bool bootable = (!foundSystemDisk && vbd.type == vbd_type.Disk);
if (bootable)
foundSystemDisk = true;
VBD.set_bootable(session, vbd.opaque_ref, bootable);
}
}
},
true, // supress history
"VBD.set_bootable"
);
}
public void SetXenObjects(IXenObject orig, IXenObject clone)
{
vm = clone as VM;
if (vm == null)
return;
Repopulate();
}
#endregion
#region VerticalTabs.VerticalTab implementation
public String SubText
{
get
{
if (vm == null)
return "";
if (vm.IsHVM)
{
List<String> driveLetters = new List<String>();
foreach (object o in m_checkedListBox.Items)
{
BootDevice device = o as BootDevice;
if (device != null)
driveLetters.Add(device.ToString());
}
string order = String.Join(", ", driveLetters.ToArray());
if (!Helpers.BostonOrGreater(vm.Connection) && m_checkBoxAutoBoot.Checked)
return String.Format(Messages.BOOTORDER_AUTOSTART, order);
else
return String.Format(Messages.BOOTORDER, order);
}
if (!Helpers.BostonOrGreater(vm.Connection) && m_checkBoxAutoBoot.Checked)
return Messages.AUTOSTART;
else
return Messages.NONE_DEFINED;
}
}
public Image Image
{
get
{
return Resources._001_PowerOn_h32bit_16;
}
}
#endregion
private void BootDeviceAndOrderEnabled(bool enabledState)
{
m_checkedListBox.Enabled = enabledState;
m_comboBoxBootDevice.Enabled = enabledState;
}
private void Repopulate()
{
if (Helpers.BostonOrGreater(vm.Connection))
m_checkBoxAutoBoot.Visible = false;
else
{
m_checkBoxAutoBoot.Visible = true;
m_checkBoxAutoBoot.Checked = vm.AutoPowerOn;
}
BootDeviceAndOrderEnabled(vm.IsHVM);
if (vm.IsHVM)
{
m_tlpHvm.Visible = true;
m_autoHeightLabelHvm.Visible = true;
m_tlpNonHvm.Visible = false;
m_autoHeightLabelNonHvm.Visible = false;
m_checkedListBox.Items.Clear();
string order = vm.BootOrder.ToUpper();
foreach (char c in order)
m_checkedListBox.Items.Add(new BootDevice(c),true);
// then add any 'missing' entries
foreach (char c in BootDevice.BootOptions)
{
if (!order.Contains(c.ToString()))
m_checkedListBox.Items.Add(new BootDevice(c), false);
}
ToggleUpDownButtonsEnabledState();
}
else
{
m_tlpHvm.Visible = false;
m_autoHeightLabelHvm.Visible = false;
m_tlpNonHvm.Visible = true;
m_autoHeightLabelNonHvm.Visible = true;
m_comboBoxBootDevice.Items.Clear();
m_comboBoxBootDevice.Items.Add(Messages.BOOT_HARD_DISK);
if (vm.HasCD)
{
m_comboBoxBootDevice.Items.Add(Messages.DVD_DRIVE);
m_comboBoxBootDevice.SelectedItem = VMPVBootableDVD() ? Messages.DVD_DRIVE : Messages.BOOT_HARD_DISK;
}
else
m_comboBoxBootDevice.SelectedItem = Messages.BOOT_HARD_DISK;
m_textBoxOsParams.Text = vm.PV_args;
}
}
private bool VMPVBootableDVD()
{
foreach (var vbd in vm.Connection.ResolveAll(vm.VBDs))
{
if (vbd.IsCDROM && vbd.bootable)
return true;
}
return false;
}
private string GetOrder()
{
string bootOrder = "";
foreach (object o in m_checkedListBox.CheckedItems)
{
BootDevice device = o as BootDevice;
if (device != null)
bootOrder += device.GetChar().ToString();
}
return bootOrder;
}
private void ToggleUpDownButtonsEnabledState()
{
m_buttonUp.Enabled = 0 < m_checkedListBox.SelectedIndex && m_checkedListBox.SelectedIndex <= m_checkedListBox.Items.Count - 1;
m_buttonDown.Enabled = 0 <= m_checkedListBox.SelectedIndex && m_checkedListBox.SelectedIndex < m_checkedListBox.Items.Count - 1;
}
/// <param name="up">
/// True moves the item up, false moves it down
/// </param>
private void MoveItem(bool up)
{
int oldIndex = m_checkedListBox.SelectedIndex;
//check selection valid
if (oldIndex < 0 || oldIndex > m_checkedListBox.Items.Count - 1)
return;
//check operation valid
if (up && oldIndex == 0)
return;
if (!up && oldIndex == m_checkedListBox.Items.Count - 1)
return;
int newIndex = up ? oldIndex - 1 : oldIndex + 1;
object item = m_checkedListBox.SelectedItem;
bool isChecked = m_checkedListBox.GetItemChecked(oldIndex);
m_checkedListBox.Items.Remove(item);
m_checkedListBox.Items.Insert(newIndex, item);
m_checkedListBox.SetItemChecked(newIndex, isChecked);
m_checkedListBox.SelectedIndex = newIndex;
ToggleUpDownButtonsEnabledState();
}
#region Control Event Handlers
private void m_checkedListBox_SelectedIndexChanged(object sender, EventArgs e)
{
ToggleUpDownButtonsEnabledState();
}
private void m_buttonUp_Click(object sender, EventArgs e)
{
MoveItem(true);
}
private void m_buttonDown_Click(object sender, EventArgs e)
{
MoveItem(false);
}
private void m_comboBoxBootDevice_SelectedIndexChanged(object sender, EventArgs e)
{
bootFromCD = (string)m_comboBoxBootDevice.SelectedItem == Messages.DVD_DRIVE;
}
#endregion
}
}
| |
/* ====================================================================
Licensed To the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file To You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed To in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.Formula
{
using System;
using NPOI.SS.Formula;
using NPOI.SS.Formula.PTG;
/**
* This class performs 'operand class' transformation. Non-base Tokens are classified into three
* operand classes:
* <ul>
* <li>reference</li>
* <li>value</li>
* <li>array</li>
* </ul>
* <p/>
*
* The operand class chosen for each Token depends on the formula type and the Token's place
* in the formula. If POI Gets the operand class wrong, Excel <em>may</em> interpret the formula
* incorrectly. This condition is typically manifested as a formula cell that displays as '#VALUE!',
* but resolves correctly when the user presses F2, enter.<p/>
*
* The logic implemented here was partially inspired by the description in
* "OpenOffice.org's Documentation of the Microsoft Excel File Format". The model presented there
* seems To be inconsistent with observed Excel behaviour (These differences have not been fully
* investigated). The implementation in this class Has been heavily modified in order To satisfy
* concrete examples of how Excel performs the same logic (see TestRVA).<p/>
*
* Hopefully, as Additional important test cases are identified and Added To the test suite,
* patterns might become more obvious in this code and allow for simplification.
*
* @author Josh Micich
*/
class OperandClassTransformer
{
private FormulaType _formulaType;
public OperandClassTransformer(FormulaType formulaType)
{
_formulaType = formulaType;
}
/**
* Traverses the supplied formula parse tree, calling <c>Ptg.SetClass()</c> for each non-base
* Token To Set its operand class.
*/
public void TransformFormula(ParseNode rootNode)
{
byte rootNodeOperandClass;
switch (_formulaType)
{
case FormulaType.CELL:
rootNodeOperandClass = Ptg.CLASS_VALUE;
break;
case FormulaType.ARRAY:
rootNodeOperandClass = Ptg.CLASS_ARRAY;
break;
case FormulaType.NAMEDRANGE:
case FormulaType.DATAVALIDATION_LIST:
rootNodeOperandClass = Ptg.CLASS_REF;
break;
default:
throw new Exception("Incomplete code - formula type ("
+ _formulaType + ") not supported yet");
}
TransformNode(rootNode, rootNodeOperandClass, false);
}
/**
* @param callerForceArrayFlag <c>true</c> if one of the current node's parents is a
* function Ptg which Has been Changed from default 'V' To 'A' type (due To requirements on
* the function return value).
*/
private void TransformNode(ParseNode node, byte desiredOperandClass,
bool callerForceArrayFlag)
{
Ptg token = node.GetToken();
ParseNode[] children = node.GetChildren();
bool IsSimpleValueFunc = IsSimpleValueFunction(token);
if (IsSimpleValueFunc)
{
bool localForceArray = desiredOperandClass == Ptg.CLASS_ARRAY;
for (int i = 0; i < children.Length; i++)
{
TransformNode(children[i], desiredOperandClass, localForceArray);
}
SetSimpleValueFuncClass((AbstractFunctionPtg)token, desiredOperandClass, callerForceArrayFlag);
return;
}
if (IsSingleArgSum(token)) {
// Need to process the argument of SUM with transformFunctionNode below
// so make a dummy FuncVarPtg for that call.
token = FuncVarPtg.SUM;
// Note - the tAttrSum token (node.getToken()) is a base
// token so does not need to have its operand class set
}
if (token is ValueOperatorPtg || token is ControlPtg
|| token is MemFuncPtg
|| token is MemAreaPtg
|| token is UnionPtg)
{
// Value Operator Ptgs and Control are base Tokens, so Token will be unchanged
// but any child nodes are processed according To desiredOperandClass and callerForceArrayFlag
// As per OOO documentation Sec 3.2.4 "Token Class Transformation", "Step 1"
// All direct operands of value operators that are initially 'R' type will
// be converted To 'V' type.
byte localDesiredOperandClass = desiredOperandClass == Ptg.CLASS_REF ? Ptg.CLASS_VALUE : desiredOperandClass;
for (int i = 0; i < children.Length; i++)
{
TransformNode(children[i], localDesiredOperandClass, callerForceArrayFlag);
}
return;
}
if (token is AbstractFunctionPtg)
{
TransformFunctionNode((AbstractFunctionPtg)token, children, desiredOperandClass, callerForceArrayFlag);
return;
}
if (children.Length > 0)
{
//if (token == RangePtg.instance)
if(token is OperationPtg)
{
// TODO is any Token transformation required under the various ref operators?
return;
}
throw new InvalidOperationException("Node should not have any children");
}
if (token.IsBaseToken)
{
// nothing To do
return;
}
token.PtgClass = (TransformClass(token.PtgClass, desiredOperandClass, callerForceArrayFlag));
}
private static bool IsSingleArgSum(Ptg token)
{
if (token is AttrPtg)
{
AttrPtg attrPtg = (AttrPtg)token;
return attrPtg.IsSum;
}
return false;
}
private static bool IsSimpleValueFunction(Ptg token)
{
if (token is AbstractFunctionPtg)
{
AbstractFunctionPtg aptg = (AbstractFunctionPtg)token;
if (aptg.DefaultOperandClass != Ptg.CLASS_VALUE)
{
return false;
}
int numberOfOperands = aptg.NumberOfOperands;
for (int i = numberOfOperands - 1; i >= 0; i--)
{
if (aptg.GetParameterClass(i) != Ptg.CLASS_VALUE)
{
return false;
}
}
return true;
}
return false;
}
private byte TransformClass(byte currentOperandClass, byte desiredOperandClass,
bool callerForceArrayFlag)
{
switch (desiredOperandClass)
{
case Ptg.CLASS_VALUE:
if (!callerForceArrayFlag)
{
return Ptg.CLASS_VALUE;
}
return Ptg.CLASS_ARRAY;
//break;
// else fall through
case Ptg.CLASS_ARRAY:
return Ptg.CLASS_ARRAY;
case Ptg.CLASS_REF:
if (!callerForceArrayFlag)
{
return currentOperandClass;
}
return Ptg.CLASS_REF;
}
throw new InvalidOperationException("Unexpected operand class (" + desiredOperandClass + ")");
}
private void TransformFunctionNode(AbstractFunctionPtg afp, ParseNode[] children,
byte desiredOperandClass, bool callerForceArrayFlag)
{
bool localForceArrayFlag;
byte defaultReturnOperandClass = afp.DefaultOperandClass;
if (callerForceArrayFlag)
{
switch (defaultReturnOperandClass)
{
case Ptg.CLASS_REF:
if (desiredOperandClass == Ptg.CLASS_REF)
{
afp.PtgClass = (Ptg.CLASS_REF);
}
else
{
afp.PtgClass = (Ptg.CLASS_ARRAY);
}
localForceArrayFlag = false;
break;
case Ptg.CLASS_ARRAY:
afp.PtgClass = (Ptg.CLASS_ARRAY);
localForceArrayFlag = false;
break;
case Ptg.CLASS_VALUE:
afp.PtgClass = (Ptg.CLASS_ARRAY);
localForceArrayFlag = true;
break;
default:
throw new InvalidOperationException("Unexpected operand class ("
+ defaultReturnOperandClass + ")");
}
}
else
{
if (defaultReturnOperandClass == desiredOperandClass)
{
localForceArrayFlag = false;
// an alternative would have been To for non-base Ptgs To Set their operand class
// from their default, but this would require the call in many subclasses because
// the default OC is not known until the end of the constructor
afp.PtgClass = (defaultReturnOperandClass);
}
else
{
switch (desiredOperandClass)
{
case Ptg.CLASS_VALUE:
// always OK To Set functions To return 'value'
afp.PtgClass = (Ptg.CLASS_VALUE);
localForceArrayFlag = false;
break;
case Ptg.CLASS_ARRAY:
switch (defaultReturnOperandClass)
{
case Ptg.CLASS_REF:
afp.PtgClass = (Ptg.CLASS_REF);
// afp.SetClass(Ptg.CLASS_ARRAY);
break;
case Ptg.CLASS_VALUE:
afp.PtgClass = (Ptg.CLASS_ARRAY);
break;
default:
throw new InvalidOperationException("Unexpected operand class ("
+ defaultReturnOperandClass + ")");
}
localForceArrayFlag = (defaultReturnOperandClass == Ptg.CLASS_VALUE);
break;
case Ptg.CLASS_REF:
switch (defaultReturnOperandClass)
{
case Ptg.CLASS_ARRAY:
afp.PtgClass=(Ptg.CLASS_ARRAY);
break;
case Ptg.CLASS_VALUE:
afp.PtgClass=(Ptg.CLASS_VALUE);
break;
default:
throw new InvalidOperationException("Unexpected operand class ("
+ defaultReturnOperandClass + ")");
}
localForceArrayFlag = false;
break;
default:
throw new InvalidOperationException("Unexpected operand class ("
+ desiredOperandClass + ")");
}
}
}
for (int i = 0; i < children.Length; i++)
{
ParseNode child = children[i];
byte paramOperandClass = afp.GetParameterClass(i);
TransformNode(child, paramOperandClass, localForceArrayFlag);
}
}
private void SetSimpleValueFuncClass(AbstractFunctionPtg afp,
byte desiredOperandClass, bool callerForceArrayFlag)
{
if (callerForceArrayFlag || desiredOperandClass == Ptg.CLASS_ARRAY)
{
afp.PtgClass = (Ptg.CLASS_ARRAY);
}
else
{
afp.PtgClass = (Ptg.CLASS_VALUE);
}
}
}
}
| |
using System;
using System.ComponentModel;
using SharpKit.JavaScript;
using SharpKit.DotNet.JavaScript;
using SharpKit.DotNet.Html.storage;
using SharpKit.DotNet.Html.webdatabase;
namespace SharpKit.DotNet.Html
{
[JsType(JsMode.Global, Export = false)]
public class HtmlContext : JsContext
{
#region Window
public static Console console { get; private set; }
public static Window window { get; private set; }
public static Window self { get; private set; }
public static JsString name { get; set; }
public static Location location { get; set; }
public static History history { get; private set; }
//public static UndoManager undoManager { get; private set; }
public static Selection selection { get; private set; }
public static object locationbar { get; set; }
public static object menubar { get; set; }
public static object personalbar { get; set; }
public static object scrollbars { get; set; }
public static object statusbar { get; set; }
public static object toolbar { get; set; }
public static object frames { get; set; }
public static object length { get; set; }
public static Window top { get; private set; }
public static object opener { get; set; }
public static Window parent { get; private set; }
public static Element frameElement { get; private set; }
public static Navigator navigator { get; private set; }
//public static ApplicationCache applicationCache { get; private set; }
public static HtmlDocument document { get; private set; }
public static StyleMedia styleMedia { get; private set; }
public static Screen screen { get; private set; }
public static int innerWidth { get; private set; }
public static int innerHeight { get; private set; }
public static int pageXOffset { get; private set; }
public static int pageYOffset { get; private set; }
public static void ScrollBy(int x, int y) { }
public static int screenX { get; private set; }
public static int screenY { get; private set; }
public static int outerWidth { get; private set; }
public static int outerHeight { get; private set; }
// WindowSessionStorage
public static Storage sessionStorage { get; private set; }
// WindowLocalStorage
public static Storage localStorage { get; private set; }
[JsMethod(Name = "close")]
public static void Close() { }
[JsMethod(Name = "stop")]
public static void Stop() { }
[JsMethod(Name = "focus")]
public static void Focus() { }
[JsMethod(Name = "blur")]
public static void Blur() { }
[JsMethod(Name = "open")]
public static Window Open() { return null; }
[JsMethod(Name = "open")]
public static Window Open(JsString url) { return null; }
[JsMethod(Name = "open")]
public static Window Open(JsString url, JsString target) { return null; }
[JsMethod(Name = "open")]
public static Window Open(JsString url, JsString target, JsString features) { return null; }
[JsMethod(Name = "open")]
public static Window Open(JsString url, JsString target, JsString features, JsString replace) { return null; }
[JsMethod(Name = "getElement")]
public static Window GetElement(int index) { return null; }
[JsMethod(Name = "getElement")]
public static object GetElement(JsString name) { return null; }
[JsMethod(Name = "setElement")]
public static void SetElement(JsString name, object value) { }
[JsMethod(Name = "alert")]
public static void Alert(JsString message) { }
[JsMethod(Name = "alert")]
public static void Alert(object obj) { }
[JsMethod(Name = "confirm")]
public static bool Confirm(JsString message) { return false; }
[JsMethod(Name = "confirm")]
public static bool Confirm(object obj) { return false; }
[JsMethod(Name = "prompt")]
public static JsString Prompt(JsString message) { return null; }
[JsMethod(Name = "prompt")]
public static JsString Prompt(object obj) { return null; }
[JsMethod(Name = "prompt")]
public static JsString Prompt(JsString message, JsString _default) { return null; }
[JsMethod(Name = "prompt")]
public static JsString Prompt(object obj, object _default) { return null; }
[JsMethod(Name = "print")]
public static void Print() { }
[JsMethod(Name = "showModalDialog")]
public static object ShowModalDialog(JsString url) { return null; }
[JsMethod(Name = "showModalDialog")]
public static object ShowModalDialog(JsString url, object argument) { return null; }
[JsMethod(Name = "postMessage")]
public static void PostMessage(object message, JsString targetOrigin) { }
[JsMethod(Name = "postMessage")]
public static void PostMessage(object message, JsString targetOrigin, MessagePort[] ports) { }
// Window-1
[JsMethod(Name = "getComputedStyle")]
public static CssStyleDeclaration GetComputedStyle(Element elt) { return null; }
[JsMethod(Name = "getComputedStyle")]
public static CssStyleDeclaration GetComputedStyle(Element elt, JsString pseudoElt) { return null; }
// Window-2
[JsMethod(Name = "scroll")]
public static void Scroll(int x, int y) { }
[JsMethod(Name = "scrollTo")]
public static void ScrollTo(int x, int y) { }
[JsMethod(Name = "scrollBy")]
// WindowTimers
[JsMethod(Name = "setTimeout")]
public static int SetTimeout(JsAction handler) { return 0; }
[JsMethod(Name = "setTimeout")]
public static int SetTimeout(JsAction handler, object timeout, params object[] args) { return 0; }
[JsMethod(Name = "setTimeout")]
public static int SetTimeout(JsString handler) { return 0; }
[JsMethod(Name = "setTimeout")]
public static int SetTimeout(JsString handler, object timeout, params object[] args) { return 0; }
[JsMethod(Name = "clearTimeout")]
public static void ClearTimeout(int handle) { }
[JsMethod(Name = "setInterval")]
public static int SetInterval(JsAction handler) { return 0; }
[JsMethod(Name = "setInterval")]
public static int SetInterval(JsAction handler, object timeout, params object[] args) { return 0; }
[JsMethod(Name = "clearInterval")]
public static void ClearInterval(int handle) { }
[Obsolete("requestAnimationFrame is not a WHATWG-sanctioned function and may be deprecated without notice.", false)]
[JsMethod(Name = "requestAnimationFrame")]
public static void RequestAnimationFrame(JsAction handler) { }
[Obsolete("webkitRequestAnimationFrame is not a WHATWG-sanctioned function and may be deprecated without notice.", false)]
[JsMethod(Name = "webkitRequestAnimationFrame")]
public static void WebkitRequestAnimationFrame(JsAction handler) { }
[Obsolete("mozRequestAnimationFrame is not a WHATWG-sanctioned function and may be deprecated without notice.", false)]
[JsMethod(Name = "mozRequestAnimationFrame")]
public static void MozRequestAnimationFrame(JsAction handler) { }
[Obsolete("oRequestAnimationFrame is not a WHATWG-sanctioned function and may be deprecated without notice.", false)]
[JsMethod(Name = "oRequestAnimationFrame")]
public static void ORequestAnimationFrame(JsAction handler) { }
[Obsolete("msRequestAnimationFrame is not a WHATWG-sanctioned function and may be deprecated without notice.", false)]
[JsMethod(Name = "msRequestAnimationFrame")]
public static void MsRequestAnimationFrame(JsAction handler) { }
// WindowDatabase
[JsMethod(Name = "openDatabase")]
public static Database OpenDatabase(JsString name, JsString version, JsString displayName, int estimatedSize) { return null; }
[JsMethod(Name = "openDatabase")]
public static Database OpenDatabase(JsString name, JsString version, JsString displayName, int estimatedSize, DatabaseCallback creationCallback) { return null; }
#endregion
///<summary>
///Encodes String objects so they can be read on all computers.
///</summary>
///<param name="s">String object or literal to be encoded.</param>
///<returns>A JsString value (in Unicode format) that contains the contents of charstring. All spaces, punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding, where xx is equivalent to the hexadecimal number representing the character. For example, a space is returned as "%20."</returns>
[JsMethod(Name = "escape")]
public static JsString Escape(JsString s) { return null; }
///<summary>
///Returns the unencoded version of an encoded component of a Uniform Resource Identifier (URI).
///</summary>
///<param name="encodedURIString">A value representing an encoded URI component.</param>
///<returns>The required encodedURIString argument is a value representing an encoded
///URI component.A URIComponent is part of a complete URI. If the encodedURIString is
///not valid, a URIError occurs.</returns>
[JsMethod(Name = "decodeURIComponent")]
public static JsString DecodeURIComponent(JsString encodedURIString) { return null; }
///<summary>
///Encodes a text JsString as a valid component of a Uniform Resource Identifier (URI).
///</summary>
///<param name="encodedURIString">A value representing an encoded URI component.</param>
///<returns>A an encoded URI. If you pass the result to decodeURIComponent,
///the original JsString is returned. Because the encodeURIComponent method encodes all
///characters, be careful if the JsString represents a path such
///as /folder1/folder2/default.html. The slash characters will be encoded and will
///not be valid if sent as a request to a web server. Use the encodeURI method if the
///JsString contains more than a single URI component.</returns>
[JsMethod(Name = "encodeURIComponent")]
public static JsString EncodeURIComponent(JsString encodedURIString) { return null; }
///<summary>
///Encodes a text JsString as a valid Uniform Resource Identifier (URI)
///</summary>
///<param name="URIString">A value representing an encoded URI.</param>
///<returns>n encoded URI. If you pass the result to decodeURI, the original JsString is returned. The encodeURI method does not encode the following characters: ":", "/", ";", and "?". Use encodeURIComponent to encode these characters.</returns>
[JsMethod(Name = "encodeURI")]
public static JsString EncodeURI(JsString URIString) { return null; }
///<summary>
///Returns the unencoded version of an encoded Uniform Resource Identifier (URI).
///</summary>
///<param name="URIString"></param>
///<returns></returns>
[JsMethod(Name = "decodeURI")]
public static JsString DecodeURI(JsString URIString) { return null; }
///<summary>
///Decodes String objects encoded with the escape method.
///</summary>
///<param name="charString">String object or literal to be decoded.</param>
///<returns>A JsString value that contains the contents of charstring. All characters encoded with the %xx hexadecimal form are replaced by their ASCII character set equivalents.</returns>
[JsMethod(Name = "unescape")]
public static JsString Unescape(JsString charString) { return null; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Xunit;
namespace System.Numerics.Tests
{
public class cast_fromTest
{
public delegate void ExceptionGenerator();
private const int NumberOfRandomIterations = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunByteExplicitCastFromBigIntegerTests()
{
Byte value = 0;
BigInteger bigInteger;
// Byte Explicit Cast from BigInteger: Random value < Byte.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(Byte.MinValue, s_random);
value = bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifyByteExplicitCastFromBigInteger(value, bigInteger));
// Byte Explicit Cast from BigInteger: Byte.MinValue - 1
bigInteger = new BigInteger(Byte.MinValue);
bigInteger -= BigInteger.One;
value = bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifyByteExplicitCastFromBigInteger(value, bigInteger));
// Byte Explicit Cast from BigInteger: Byte.MinValue
VerifyByteExplicitCastFromBigInteger(Byte.MinValue);
// Byte Explicit Cast from BigInteger: 0
VerifyByteExplicitCastFromBigInteger(0);
// Byte Explicit Cast from BigInteger: 1
VerifyByteExplicitCastFromBigInteger(1);
// Byte Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyByteExplicitCastFromBigInteger((Byte)s_random.Next(1, Byte.MaxValue));
}
// Byte Explicit Cast from BigInteger: Byte.MaxValue + 1
bigInteger = new BigInteger(Byte.MaxValue);
bigInteger += BigInteger.One;
value = bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifyByteExplicitCastFromBigInteger(value, bigInteger));
// Byte Explicit Cast from BigInteger: Random value > Byte.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(Byte.MaxValue, s_random);
value = bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifyByteExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunSByteExplicitCastFromBigIntegerTests()
{
SByte value = 0;
BigInteger bigInteger;
// SByte Explicit Cast from BigInteger: Random value < SByte.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(SByte.MinValue, s_random);
value = (SByte)bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifySByteExplicitCastFromBigInteger(value, bigInteger));
// SByte Explicit Cast from BigInteger: SByte.MinValue - 1
bigInteger = new BigInteger(SByte.MinValue);
bigInteger -= BigInteger.One;
value = (SByte)bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifySByteExplicitCastFromBigInteger(value, bigInteger));
// SByte Explicit Cast from BigInteger: SByte.MinValue
VerifySByteExplicitCastFromBigInteger(SByte.MinValue);
// SByte Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySByteExplicitCastFromBigInteger((SByte)s_random.Next(SByte.MinValue, 0));
}
// SByte Explicit Cast from BigInteger: -1
VerifySByteExplicitCastFromBigInteger(-1);
// SByte Explicit Cast from BigInteger: 0
VerifySByteExplicitCastFromBigInteger(0);
// SByte Explicit Cast from BigInteger: 1
VerifySByteExplicitCastFromBigInteger(1);
// SByte Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySByteExplicitCastFromBigInteger((SByte)s_random.Next(1, SByte.MaxValue));
}
// SByte Explicit Cast from BigInteger: SByte.MaxValue
VerifySByteExplicitCastFromBigInteger(SByte.MaxValue);
// SByte Explicit Cast from BigInteger: SByte.MaxValue + 1
bigInteger = new BigInteger(SByte.MaxValue);
bigInteger += BigInteger.One;
value = (SByte)bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifySByteExplicitCastFromBigInteger(value, bigInteger));
// SByte Explicit Cast from BigInteger: Random value > SByte.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan((UInt64)SByte.MaxValue, s_random);
value = (SByte)bigInteger.ToByteArray()[0];
Assert.Throws<OverflowException>(() => VerifySByteExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunUInt16ExplicitCastFromBigIntegerTests()
{
ushort value;
BigInteger bigInteger;
// UInt16 Explicit Cast from BigInteger: Random value < UInt16.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(UInt16.MinValue, s_random);
value = BitConverter.ToUInt16(ByteArrayMakeMinSize(bigInteger.ToByteArray(), 2), 0);
Assert.Throws<OverflowException>(() => VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger));
// UInt16 Explicit Cast from BigInteger: UInt16.MinValue - 1
bigInteger = new BigInteger(UInt16.MinValue);
bigInteger -= BigInteger.One;
value = BitConverter.ToUInt16(new byte[] { 0xff, 0xff }, 0);
Assert.Throws<OverflowException>(() => VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger));
// UInt16 Explicit Cast from BigInteger: UInt16.MinValue
VerifyUInt16ExplicitCastFromBigInteger(UInt16.MinValue);
// UInt16 Explicit Cast from BigInteger: 0
VerifyUInt16ExplicitCastFromBigInteger(0);
// UInt16 Explicit Cast from BigInteger: 1
VerifyUInt16ExplicitCastFromBigInteger(1);
// UInt16 Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyUInt16ExplicitCastFromBigInteger((UInt16)s_random.Next(1, UInt16.MaxValue));
}
// UInt16 Explicit Cast from BigInteger: UInt16.MaxValue
VerifyUInt16ExplicitCastFromBigInteger(UInt16.MaxValue);
// UInt16 Explicit Cast from BigInteger: UInt16.MaxValue + 1
bigInteger = new BigInteger(UInt16.MaxValue);
bigInteger += BigInteger.One;
value = BitConverter.ToUInt16(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger));
// UInt16 Explicit Cast from BigInteger: Random value > UInt16.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(UInt16.MaxValue, s_random);
value = BitConverter.ToUInt16(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunInt16ExplicitCastFromBigIntegerTests()
{
short value;
BigInteger bigInteger;
// Int16 Explicit Cast from BigInteger: Random value < Int16.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(Int16.MinValue, s_random);
value = BitConverter.ToInt16(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt16ExplicitCastFromBigInteger(value, bigInteger));
// Int16 Explicit Cast from BigInteger: Int16.MinValue - 1
bigInteger = new BigInteger(Int16.MinValue);
bigInteger -= BigInteger.One;
value = BitConverter.ToInt16(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt16ExplicitCastFromBigInteger(value, bigInteger));
// Int16 Explicit Cast from BigInteger: Int16.MinValue
VerifyInt16ExplicitCastFromBigInteger(Int16.MinValue);
// Int16 Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt16ExplicitCastFromBigInteger((Int16)s_random.Next(Int16.MinValue, 0));
}
// Int16 Explicit Cast from BigInteger: -1
VerifyInt16ExplicitCastFromBigInteger(-1);
// Int16 Explicit Cast from BigInteger: 0
VerifyInt16ExplicitCastFromBigInteger(0);
// Int16 Explicit Cast from BigInteger: 1
VerifyInt16ExplicitCastFromBigInteger(1);
// Int16 Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt16ExplicitCastFromBigInteger((Int16)s_random.Next(1, Int16.MaxValue));
}
// Int16 Explicit Cast from BigInteger: Int16.MaxValue
VerifyInt16ExplicitCastFromBigInteger(Int16.MaxValue);
// Int16 Explicit Cast from BigInteger: Int16.MaxValue + 1
bigInteger = new BigInteger(Int16.MaxValue);
bigInteger += BigInteger.One;
value = BitConverter.ToInt16(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt16ExplicitCastFromBigInteger(value, bigInteger));
// Int16 Explicit Cast from BigInteger: Random value > Int16.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan((UInt64)Int16.MaxValue, s_random);
value = BitConverter.ToInt16(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt16ExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunUInt32ExplicitCastFromBigIntegerTests()
{
uint value;
BigInteger bigInteger;
// UInt32 Explicit Cast from BigInteger: Random value < UInt32.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(UInt32.MinValue, s_random);
value = BitConverter.ToUInt32(ByteArrayMakeMinSize(bigInteger.ToByteArray(), 4), 0);
Assert.Throws<OverflowException>(() => VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger));
// UInt32 Explicit Cast from BigInteger: UInt32.MinValue - 1
bigInteger = new BigInteger(UInt32.MinValue);
bigInteger -= BigInteger.One;
value = BitConverter.ToUInt32(new byte[] { 0xff, 0xff, 0xff, 0xff }, 0);
Assert.Throws<OverflowException>(() => VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger));
// UInt32 Explicit Cast from BigInteger: UInt32.MinValue
VerifyUInt32ExplicitCastFromBigInteger(UInt32.MinValue);
// UInt32 Explicit Cast from BigInteger: 0
VerifyUInt32ExplicitCastFromBigInteger(0);
// UInt32 Explicit Cast from BigInteger: 1
VerifyUInt32ExplicitCastFromBigInteger(1);
// UInt32 Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyUInt32ExplicitCastFromBigInteger((UInt32)(UInt32.MaxValue * s_random.NextDouble()));
}
// UInt32 Explicit Cast from BigInteger: UInt32.MaxValue
VerifyUInt32ExplicitCastFromBigInteger(UInt32.MaxValue);
// UInt32 Explicit Cast from BigInteger: UInt32.MaxValue + 1
bigInteger = new BigInteger(UInt32.MaxValue);
bigInteger += BigInteger.One;
value = BitConverter.ToUInt32(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger));
// UInt32 Explicit Cast from BigInteger: Random value > UInt32.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(UInt32.MaxValue, s_random);
value = BitConverter.ToUInt32(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunInt32ExplicitCastFromBigIntegerTests()
{
int value;
BigInteger bigInteger;
// Int32 Explicit Cast from BigInteger: Random value < Int32.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(Int32.MinValue, s_random);
value = BitConverter.ToInt32(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt32ExplicitCastFromBigInteger(value, bigInteger));
// Int32 Explicit Cast from BigInteger: Int32.MinValue - 1
bigInteger = new BigInteger(Int32.MinValue);
bigInteger -= BigInteger.One;
value = BitConverter.ToInt32(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt32ExplicitCastFromBigInteger(value, bigInteger));
// Int32 Explicit Cast from BigInteger: Int32.MinValue
VerifyInt32ExplicitCastFromBigInteger(Int32.MinValue);
// Int32 Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt32ExplicitCastFromBigInteger((Int32)s_random.Next(Int32.MinValue, 0));
}
// Int32 Explicit Cast from BigInteger: -1
VerifyInt32ExplicitCastFromBigInteger(-1);
// Int32 Explicit Cast from BigInteger: 0
VerifyInt32ExplicitCastFromBigInteger(0);
// Int32 Explicit Cast from BigInteger: 1
VerifyInt32ExplicitCastFromBigInteger(1);
// Int32 Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt32ExplicitCastFromBigInteger((Int32)s_random.Next(1, Int32.MaxValue));
}
// Int32 Explicit Cast from BigInteger: Int32.MaxValue
VerifyInt32ExplicitCastFromBigInteger(Int32.MaxValue);
// Int32 Explicit Cast from BigInteger: Int32.MaxValue + 1
bigInteger = new BigInteger(Int32.MaxValue);
bigInteger += BigInteger.One;
value = BitConverter.ToInt32(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt32ExplicitCastFromBigInteger(value, bigInteger));
// Int32 Explicit Cast from BigInteger: Random value > Int32.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(Int32.MaxValue, s_random);
value = BitConverter.ToInt32(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt32ExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunUInt64ExplicitCastFromBigIntegerTests()
{
ulong value;
BigInteger bigInteger;
// UInt64 Explicit Cast from BigInteger: Random value < UInt64.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(0, s_random);
value = BitConverter.ToUInt64(ByteArrayMakeMinSize(bigInteger.ToByteArray(), 8), 0);
Assert.Throws<OverflowException>(() => VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger));
// UInt64 Explicit Cast from BigInteger: UInt64.MinValue - 1
bigInteger = new BigInteger(UInt64.MinValue);
bigInteger -= BigInteger.One;
value = BitConverter.ToUInt64(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, 0);
Assert.Throws<OverflowException>(() => VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger));
// UInt64 Explicit Cast from BigInteger: UInt64.MinValue
VerifyUInt64ExplicitCastFromBigInteger(UInt64.MinValue);
// UInt64 Explicit Cast from BigInteger: 0
VerifyUInt64ExplicitCastFromBigInteger(0);
// UInt64 Explicit Cast from BigInteger: 1
VerifyUInt64ExplicitCastFromBigInteger(1);
// UInt64 Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyUInt64ExplicitCastFromBigInteger((UInt64)(UInt64.MaxValue * s_random.NextDouble()));
}
// UInt64 Explicit Cast from BigInteger: UInt64.MaxValue
VerifyUInt64ExplicitCastFromBigInteger(UInt64.MaxValue);
// UInt64 Explicit Cast from BigInteger: UInt64.MaxValue + 1
bigInteger = new BigInteger(UInt64.MaxValue);
bigInteger += BigInteger.One;
value = BitConverter.ToUInt64(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger));
// UInt64 Explicit Cast from BigInteger: Random value > UInt64.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(UInt64.MaxValue, s_random);
value = BitConverter.ToUInt64(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunInt64ExplicitCastFromBigIntegerTests()
{
long value;
BigInteger bigInteger;
// Int64 Explicit Cast from BigInteger: Random value < Int64.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(Int64.MinValue, s_random);
value = BitConverter.ToInt64(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt64ExplicitCastFromBigInteger(value, bigInteger));
// Int64 Explicit Cast from BigInteger: Int64.MinValue - 1
bigInteger = new BigInteger(Int64.MinValue);
bigInteger -= BigInteger.One;
value = BitConverter.ToInt64(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt64ExplicitCastFromBigInteger(value, bigInteger));
// Int64 Explicit Cast from BigInteger: Int64.MinValue
VerifyInt64ExplicitCastFromBigInteger(Int64.MinValue);
// Int64 Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt64ExplicitCastFromBigInteger(((Int64)(Int64.MaxValue * s_random.NextDouble())) - Int64.MaxValue);
}
// Int64 Explicit Cast from BigInteger: -1
VerifyInt64ExplicitCastFromBigInteger(-1);
// Int64 Explicit Cast from BigInteger: 0
VerifyInt64ExplicitCastFromBigInteger(0);
// Int64 Explicit Cast from BigInteger: 1
VerifyInt64ExplicitCastFromBigInteger(1);
// Int64 Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyInt64ExplicitCastFromBigInteger((Int64)(Int64.MaxValue * s_random.NextDouble()));
}
// Int64 Explicit Cast from BigInteger: Int64.MaxValue
VerifyInt64ExplicitCastFromBigInteger(Int64.MaxValue);
// Int64 Explicit Cast from BigInteger: Int64.MaxValue + 1
bigInteger = new BigInteger(Int64.MaxValue);
bigInteger += BigInteger.One;
value = BitConverter.ToInt64(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt64ExplicitCastFromBigInteger(value, bigInteger));
// Int64 Explicit Cast from BigInteger: Random value > Int64.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(Int64.MaxValue, s_random);
value = BitConverter.ToInt64(bigInteger.ToByteArray(), 0);
Assert.Throws<OverflowException>(() => VerifyInt64ExplicitCastFromBigInteger(value, bigInteger));
}
[Fact]
public static void RunSingleExplicitCastFromBigIntegerTests()
{
BigInteger bigInteger;
// Single Explicit Cast from BigInteger: Random value < Single.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(Single.MinValue * 2.0, s_random);
VerifySingleExplicitCastFromBigInteger(Single.NegativeInfinity, bigInteger);
// Single Explicit Cast from BigInteger: Single.MinValue - 1
bigInteger = new BigInteger(Single.MinValue);
bigInteger -= BigInteger.One;
VerifySingleExplicitCastFromBigInteger(Single.MinValue, bigInteger);
// Single Explicit Cast from BigInteger: Single.MinValue
VerifySingleExplicitCastFromBigInteger(Single.MinValue);
// Single Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySingleExplicitCastFromBigInteger(((Single)(Single.MaxValue * s_random.NextDouble())) - Single.MaxValue);
}
// Single Explicit Cast from BigInteger: Random Negative Non-integral > -100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySingleExplicitCastFromBigInteger(((Single)(100 * s_random.NextDouble())) - 100);
}
// Single Explicit Cast from BigInteger: -1
VerifySingleExplicitCastFromBigInteger(-1);
// Single Explicit Cast from BigInteger: 0
VerifySingleExplicitCastFromBigInteger(0);
// Single Explicit Cast from BigInteger: 1
VerifySingleExplicitCastFromBigInteger(1);
// Single Explicit Cast from BigInteger: Random Positive Non-integral < 100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySingleExplicitCastFromBigInteger((Single)(100 * s_random.NextDouble()));
}
// Single Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifySingleExplicitCastFromBigInteger((Single)(Single.MaxValue * s_random.NextDouble()));
}
// Single Explicit Cast from BigInteger: Single.MaxValue + 1
bigInteger = new BigInteger(Single.MaxValue);
bigInteger += BigInteger.One;
VerifySingleExplicitCastFromBigInteger(Single.MaxValue, bigInteger);
// Single Explicit Cast from BigInteger: Random value > Single.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan((double)Single.MaxValue * 2, s_random);
VerifySingleExplicitCastFromBigInteger(Single.PositiveInfinity, bigInteger);
// Single Explicit Cast from BigInteger: value < Single.MaxValue but can not be accurately represented in a Single
bigInteger = new BigInteger(16777217);
VerifySingleExplicitCastFromBigInteger(16777216f, bigInteger);
// Single Explicit Cast from BigInteger: Single.MinValue < value but can not be accurately represented in a Single
bigInteger = new BigInteger(-16777217);
VerifySingleExplicitCastFromBigInteger(-16777216f, bigInteger);
}
[Fact]
public static void RunDoubleExplicitCastFromBigIntegerTests()
{
BigInteger bigInteger;
// Double Explicit Cast from BigInteger: Random value < Double.MinValue
bigInteger = GenerateRandomBigIntegerLessThan(Double.MinValue, s_random);
bigInteger *= 2;
VerifyDoubleExplicitCastFromBigInteger(Double.NegativeInfinity, bigInteger);
// Double Explicit Cast from BigInteger: Double.MinValue - 1
bigInteger = new BigInteger(Double.MinValue);
bigInteger -= BigInteger.One;
VerifyDoubleExplicitCastFromBigInteger(Double.MinValue, bigInteger);
// Double Explicit Cast from BigInteger: Double.MinValue
VerifyDoubleExplicitCastFromBigInteger(Double.MinValue);
// Double Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDoubleExplicitCastFromBigInteger(((Double)(Double.MaxValue * s_random.NextDouble())) - Double.MaxValue);
}
// Double Explicit Cast from BigInteger: Random Negative Non-integral > -100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDoubleExplicitCastFromBigInteger(((Double)(100 * s_random.NextDouble())) - 100);
}
// Double Explicit Cast from BigInteger: -1
VerifyDoubleExplicitCastFromBigInteger(-1);
// Double Explicit Cast from BigInteger: 0
VerifyDoubleExplicitCastFromBigInteger(0);
// Double Explicit Cast from BigInteger: 1
VerifyDoubleExplicitCastFromBigInteger(1);
// Double Explicit Cast from BigInteger: Random Positive Non-integral < 100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDoubleExplicitCastFromBigInteger((Double)(100 * s_random.NextDouble()));
}
// Double Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDoubleExplicitCastFromBigInteger((Double)(Double.MaxValue * s_random.NextDouble()));
}
// Double Explicit Cast from BigInteger: Double.MaxValue
VerifyDoubleExplicitCastFromBigInteger(Double.MaxValue);
// Double Explicit Cast from BigInteger: Double.MaxValue + 1
bigInteger = new BigInteger(Double.MaxValue);
bigInteger += BigInteger.One;
VerifyDoubleExplicitCastFromBigInteger(Double.MaxValue, bigInteger);
// Double Explicit Cast from BigInteger: Double.MinValue - 1
bigInteger = new BigInteger(Double.MinValue);
bigInteger -= BigInteger.One;
VerifyDoubleExplicitCastFromBigInteger(Double.MinValue, bigInteger);
// Double Explicit Cast from BigInteger: Random value > Double.MaxValue
bigInteger = GenerateRandomBigIntegerGreaterThan(Double.MaxValue, s_random);
bigInteger *= 2;
VerifyDoubleExplicitCastFromBigInteger(Double.PositiveInfinity, bigInteger);
// Double Explicit Cast from BigInteger: Random value < -Double.MaxValue
VerifyDoubleExplicitCastFromBigInteger(Double.NegativeInfinity, -bigInteger);
// Double Explicit Cast from BigInteger: very large values (more than Int32.MaxValue bits) should be infinity
DoubleExplicitCastFromLargeBigIntegerTests(128, 1);
// Double Explicit Cast from BigInteger: value < Double.MaxValue but can not be accurately represented in a Double
bigInteger = new BigInteger(9007199254740993);
VerifyDoubleExplicitCastFromBigInteger(9007199254740992, bigInteger);
// Double Explicit Cast from BigInteger: Double.MinValue < value but can not be accurately represented in a Double
bigInteger = new BigInteger(-9007199254740993);
VerifyDoubleExplicitCastFromBigInteger(-9007199254740992, bigInteger);
}
[Fact]
[OuterLoop]
public static void RunDoubleExplicitCastFromLargeBigIntegerTests()
{
DoubleExplicitCastFromLargeBigIntegerTests(0, 5, 64, 4);
}
[Fact]
public static void RunDecimalExplicitCastFromBigIntegerTests()
{
int[] bits = new int[3];
uint temp2;
bool carry;
byte[] temp;
Decimal value;
BigInteger bigInteger;
// Decimal Explicit Cast from BigInteger: Random value < Decimal.MinValue
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
bigInteger = GenerateRandomBigIntegerLessThan(Decimal.MinValue, s_random);
temp = bigInteger.ToByteArray();
carry = true;
for (int j = 0; j < 3; j++)
{
temp2 = BitConverter.ToUInt32(temp, 4 * j);
temp2 = ~temp2;
if (carry)
{
carry = false;
temp2 += 1;
if (temp2 == 0)
{
carry = true;
}
}
bits[j] = (int)temp2;
}
value = new Decimal(bits[0], bits[1], bits[2], true, 0);
Assert.Throws<OverflowException>(() => VerifyDecimalExplicitCastFromBigInteger(value, bigInteger));
}
// Decimal Explicit Cast from BigInteger: Decimal.MinValue - 1
bigInteger = new BigInteger(Decimal.MinValue);
bigInteger -= BigInteger.One;
temp = bigInteger.ToByteArray();
carry = true;
for (int j = 0; j < 3; j++)
{
temp2 = BitConverter.ToUInt32(temp, 4 * j);
temp2 = ~temp2;
if (carry)
{
carry = false;
temp2 += 1;
if (temp2 == 0)
{
carry = true;
}
}
bits[j] = (int)temp2;
}
value = new Decimal(bits[0], bits[1], bits[2], true, 0);
Assert.Throws<OverflowException>(() => VerifyDecimalExplicitCastFromBigInteger(value, bigInteger));
// Decimal Explicit Cast from BigInteger: Decimal.MinValue
VerifyDecimalExplicitCastFromBigInteger(Decimal.MinValue);
// Decimal Explicit Cast from BigInteger: Random Negative
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDecimalExplicitCastFromBigInteger(((Decimal)((Double)Decimal.MaxValue * s_random.NextDouble())) - Decimal.MaxValue);
}
// Decimal Explicit Cast from BigInteger: Random Negative Non-Integral > -100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
value = (Decimal)(100 * s_random.NextDouble() - 100);
VerifyDecimalExplicitCastFromBigInteger(Decimal.Truncate(value), new BigInteger(value));
}
// Decimal Explicit Cast from BigInteger: -1
VerifyDecimalExplicitCastFromBigInteger(-1);
// Decimal Explicit Cast from BigInteger: 0
VerifyDecimalExplicitCastFromBigInteger(0);
// Decimal Explicit Cast from BigInteger: 1
VerifyDecimalExplicitCastFromBigInteger(1);
// Decimal Explicit Cast from BigInteger: Random Positive Non-Integral < 100
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
value = (Decimal)(100 * s_random.NextDouble());
VerifyDecimalExplicitCastFromBigInteger(Decimal.Truncate(value), new BigInteger(value));
}
// Decimal Explicit Cast from BigInteger: Random Positive
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
VerifyDecimalExplicitCastFromBigInteger((Decimal)((Double)Decimal.MaxValue * s_random.NextDouble()));
}
// Decimal Explicit Cast from BigInteger: Decimal.MaxValue
VerifyDecimalExplicitCastFromBigInteger(Decimal.MaxValue);
// Decimal Explicit Cast from BigInteger: Decimal.MaxValue + 1
bigInteger = new BigInteger(Decimal.MaxValue);
bigInteger += BigInteger.One;
temp = bigInteger.ToByteArray();
for (int j = 0; j < 3; j++)
{
bits[j] = BitConverter.ToInt32(temp, 4 * j);
}
value = new Decimal(bits[0], bits[1], bits[2], false, 0);
Assert.Throws<OverflowException>(() => VerifyDecimalExplicitCastFromBigInteger(value, bigInteger));
// Decimal Explicit Cast from BigInteger: Random value > Decimal.MaxValue
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
bigInteger = GenerateRandomBigIntegerGreaterThan(Decimal.MaxValue, s_random);
temp = bigInteger.ToByteArray();
for (int j = 0; j < 3; j++)
{
bits[j] = BitConverter.ToInt32(temp, 4 * j);
}
value = new Decimal(bits[0], bits[1], bits[2], false, 0);
Assert.Throws<OverflowException>(() => VerifyDecimalExplicitCastFromBigInteger(value, bigInteger));
}
}
/// <summary>
/// Test cast to Double on Very Large BigInteger more than (1 << Int.MaxValue)
/// Tested BigInteger are: +/-pow(2, startShift + smallLoopShift * [1..smallLoopLimit] + Int32.MaxValue * [1..bigLoopLimit])
/// Expected double is positive and negative infinity
/// Note:
/// ToString() can not operate such large values
/// </summary>
private static void DoubleExplicitCastFromLargeBigIntegerTests(int startShift, int bigShiftLoopLimit, int smallShift = 0, int smallShiftLoopLimit = 1)
{
BigInteger init = BigInteger.One << startShift;
for (int i = 0; i < smallShiftLoopLimit; i++)
{
BigInteger temp = init << ((i + 1) * smallShift);
for (int j = 0; j < bigShiftLoopLimit; j++)
{
temp = temp << Int32.MaxValue;
VerifyDoubleExplicitCastFromBigInteger(Double.PositiveInfinity, temp);
VerifyDoubleExplicitCastFromBigInteger(Double.NegativeInfinity, -temp);
}
}
}
private static BigInteger GenerateRandomNegativeBigInteger(Random random)
{
BigInteger bigInteger;
int arraySize = random.Next(1, 8) * 4;
byte[] byteArray = new byte[arraySize];
for (int i = 0; i < arraySize; ++i)
{
byteArray[i] = (byte)random.Next(0, 256);
}
byteArray[arraySize - 1] |= 0x80;
bigInteger = new BigInteger(byteArray);
return bigInteger;
}
private static BigInteger GenerateRandomPositiveBigInteger(Random random)
{
BigInteger bigInteger;
int arraySize = random.Next(1, 8) * 4;
byte[] byteArray = new byte[arraySize];
for (int i = 0; i < arraySize; ++i)
{
byteArray[i] = (byte)random.Next(0, 256);
}
byteArray[arraySize - 1] &= 0x7f;
bigInteger = new BigInteger(byteArray);
return bigInteger;
}
private static BigInteger GenerateRandomBigIntegerLessThan(Int64 value, Random random)
{
return (GenerateRandomNegativeBigInteger(random) + value) - 1;
}
private static BigInteger GenerateRandomBigIntegerLessThan(Double value, Random random)
{
return (GenerateRandomNegativeBigInteger(random) + (BigInteger)value) - 1;
}
private static BigInteger GenerateRandomBigIntegerLessThan(Decimal value, Random random)
{
return (GenerateRandomNegativeBigInteger(random) + (BigInteger)value) - 1;
}
private static BigInteger GenerateRandomBigIntegerGreaterThan(UInt64 value, Random random)
{
return (GenerateRandomPositiveBigInteger(random) + value) + 1;
}
private static BigInteger GenerateRandomBigIntegerGreaterThan(Double value, Random random)
{
return (GenerateRandomPositiveBigInteger(random) + (BigInteger)value) + 1;
}
private static BigInteger GenerateRandomBigIntegerGreaterThan(Decimal value, Random random)
{
return (GenerateRandomPositiveBigInteger(random) + (BigInteger)value) + 1;
}
private static void VerifyByteExplicitCastFromBigInteger(Byte value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyByteExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyByteExplicitCastFromBigInteger(Byte value, BigInteger bigInteger)
{
Assert.Equal(value, (Byte)bigInteger);
}
private static void VerifySByteExplicitCastFromBigInteger(SByte value)
{
BigInteger bigInteger = new BigInteger(value);
VerifySByteExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifySByteExplicitCastFromBigInteger(SByte value, BigInteger bigInteger)
{
Assert.Equal(value, (SByte)bigInteger);
}
private static void VerifyUInt16ExplicitCastFromBigInteger(UInt16 value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyUInt16ExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyUInt16ExplicitCastFromBigInteger(UInt16 value, BigInteger bigInteger)
{
Assert.Equal(value, (UInt16)bigInteger);
}
private static void VerifyInt16ExplicitCastFromBigInteger(Int16 value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyInt16ExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyInt16ExplicitCastFromBigInteger(Int16 value, BigInteger bigInteger)
{
Assert.Equal(value, (Int16)bigInteger);
}
private static void VerifyUInt32ExplicitCastFromBigInteger(UInt32 value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyUInt32ExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyUInt32ExplicitCastFromBigInteger(UInt32 value, BigInteger bigInteger)
{
Assert.Equal(value, (UInt32)bigInteger);
}
private static void VerifyInt32ExplicitCastFromBigInteger(Int32 value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyInt32ExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyInt32ExplicitCastFromBigInteger(Int32 value, BigInteger bigInteger)
{
Assert.Equal(value, (Int32)bigInteger);
}
private static void VerifyUInt64ExplicitCastFromBigInteger(UInt64 value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyUInt64ExplicitCastFromBigInteger(UInt64 value, BigInteger bigInteger)
{
Assert.Equal(value, (UInt64)bigInteger);
}
private static void VerifyInt64ExplicitCastFromBigInteger(Int64 value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyInt64ExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyInt64ExplicitCastFromBigInteger(Int64 value, BigInteger bigInteger)
{
Assert.Equal(value, (Int64)bigInteger);
}
private static void VerifySingleExplicitCastFromBigInteger(Single value)
{
BigInteger bigInteger = new BigInteger(value);
VerifySingleExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifySingleExplicitCastFromBigInteger(Single value, BigInteger bigInteger)
{
Assert.Equal((Single)Math.Truncate(value), (Single)bigInteger);
}
private static void VerifyDoubleExplicitCastFromBigInteger(Double value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyDoubleExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyDoubleExplicitCastFromBigInteger(Double value, BigInteger bigInteger)
{
Assert.Equal(Math.Truncate(value), (Double)bigInteger);
}
private static void VerifyDecimalExplicitCastFromBigInteger(Decimal value)
{
BigInteger bigInteger = new BigInteger(value);
VerifyDecimalExplicitCastFromBigInteger(value, bigInteger);
}
private static void VerifyDecimalExplicitCastFromBigInteger(Decimal value, BigInteger bigInteger)
{
Assert.Equal(value, (Decimal)bigInteger);
}
public static byte[] ByteArrayMakeMinSize(Byte[] input, int minSize)
{
if (input.Length >= minSize)
{
return input;
}
Byte[] output = new byte[minSize];
Byte filler = 0;
if ((input[input.Length - 1] & 0x80) != 0)
{
filler = 0xff;
}
for (int i = 0; i < output.Length; i++)
{
output[i] = (i < input.Length) ? input[i] : filler;
}
return output;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class ConditionalTests
{
[Fact]
public void VisitIfThenDoesNotCloneTree()
{
var ifTrue = ((Expression<Action>)(() => Nop())).Body;
var e = Expression.IfThen(Expression.Constant(true), ifTrue);
var r = new Visitor().Visit(e);
Assert.Same(e, r);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void Conditional(bool useInterpreter)
{
Expression<Func<int, int, int>> f = (x, y) => x > 5 ? x : y;
var d = f.Compile(useInterpreter);
Assert.Equal(7, d(7, 4));
Assert.Equal(6, d(3, 6));
}
[Fact]
public void NullTest()
{
Assert.Throws<ArgumentNullException>("test", () => Expression.IfThen(null, Expression.Empty()));
Assert.Throws<ArgumentNullException>("test", () => Expression.IfThenElse(null, Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentNullException>("test", () => Expression.Condition(null, Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentNullException>("test", () => Expression.Condition(null, Expression.Empty(), Expression.Empty(), typeof(void)));
}
[Fact]
public void UnreadableTest()
{
Expression test = Expression.Property(null, typeof(Unreadable<bool>), nameof(Unreadable<bool>.WriteOnly));
Assert.Throws<ArgumentException>("test", () => Expression.IfThen(test, Expression.Empty()));
Assert.Throws<ArgumentException>("test", () => Expression.IfThenElse(test, Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentException>("test", () => Expression.Condition(test, Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentException>("test", () => Expression.Condition(test, Expression.Empty(), Expression.Empty(), typeof(void)));
}
[Fact]
public void NullIfTrue()
{
Assert.Throws<ArgumentNullException>("ifTrue", () => Expression.IfThen(Expression.Constant(true), null));
Assert.Throws<ArgumentNullException>("ifTrue", () => Expression.IfThenElse(Expression.Constant(true), null, Expression.Empty()));
Assert.Throws<ArgumentNullException>("ifTrue", () => Expression.Condition(Expression.Constant(true), null, Expression.Empty()));
Assert.Throws<ArgumentNullException>("ifTrue", () => Expression.Condition(Expression.Constant(true), null, Expression.Empty(), typeof(void)));
}
[Fact]
public void UnreadableIfTrue()
{
Expression ifTrue = Expression.Property(null, typeof(Unreadable<int>), nameof(Unreadable<int>.WriteOnly));
Assert.Throws<ArgumentException>("ifTrue", () => Expression.IfThen(Expression.Constant(true), ifTrue));
Assert.Throws<ArgumentException>("ifTrue", () => Expression.IfThenElse(Expression.Constant(true), ifTrue, Expression.Empty()));
Assert.Throws<ArgumentException>("ifTrue", () => Expression.Condition(Expression.Constant(true), ifTrue, Expression.Constant(0)));
Assert.Throws<ArgumentException>("ifTrue", () => Expression.Condition(Expression.Constant(true), ifTrue, Expression.Empty(), typeof(void)));
}
[Fact]
public void NullIfFalse()
{
Assert.Throws<ArgumentNullException>("ifFalse", () => Expression.IfThenElse(Expression.Constant(true), Expression.Empty(), null));
Assert.Throws<ArgumentNullException>("ifFalse", () => Expression.Condition(Expression.Constant(true), Expression.Empty(), null));
Assert.Throws<ArgumentNullException>("ifFalse", () => Expression.Condition(Expression.Constant(true), Expression.Empty(), null, typeof(void)));
}
[Fact]
public void UnreadbleIfFalse()
{
Expression ifFalse = Expression.Property(null, typeof(Unreadable<int>), nameof(Unreadable<int>.WriteOnly));
Assert.Throws<ArgumentException>("ifFalse", () => Expression.IfThenElse(Expression.Constant(true), Expression.Empty(), ifFalse));
Assert.Throws<ArgumentException>("ifFalse", () => Expression.Condition(Expression.Constant(true), Expression.Constant(0), ifFalse));
Assert.Throws<ArgumentException>("ifFalse", () => Expression.Condition(Expression.Constant(true), Expression.Empty(), ifFalse, typeof(void)));
}
[Fact]
public void NullType()
{
Assert.Throws<ArgumentNullException>("type", () => Expression.Condition(Expression.Constant(true), Expression.Empty(), Expression.Empty(), null));
}
[Fact]
public void NonBooleanTest()
{
Assert.Throws<ArgumentException>(() => Expression.IfThen(Expression.Constant(0), Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.IfThenElse(Expression.Constant(0), Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(0), Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(0), Expression.Empty(), Expression.Empty(), typeof(void)));
Assert.Throws<ArgumentException>(() => Expression.IfThen(Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.IfThenElse(Expression.Empty(), Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Empty(), Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Empty(), Expression.Empty(), Expression.Empty(), typeof(void)));
Assert.Throws<ArgumentException>(() => Expression.IfThen(Expression.Constant(true, typeof(bool?)), Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.IfThenElse(Expression.Constant(true, typeof(bool?)), Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(true, typeof(bool?)), Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(true, typeof(bool?)), Expression.Empty(), Expression.Empty(), typeof(void)));
ConstantExpression truthyConstant = Expression.Constant(new Truthiness(true));
Assert.Throws<ArgumentException>(() => Expression.IfThen(Expression.Constant(truthyConstant), Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.IfThenElse(Expression.Constant(truthyConstant), Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(truthyConstant), Expression.Empty(), Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(truthyConstant), Expression.Empty(), Expression.Empty(), typeof(void)));
}
[Fact]
public void IncompatibleImplicitTypes()
{
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant(0L)));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(true), Expression.Constant(0L), Expression.Constant(0)));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(true), Expression.Constant("hello"), Expression.Constant(new object())));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(true), Expression.Constant(new object()), Expression.Constant("hello")));
}
[Fact]
public void IncompatibleExplicitTypes()
{
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant(0L), typeof(int)));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(true), Expression.Constant(0L), Expression.Constant(0), typeof(int)));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant(0L), typeof(long)));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(true), Expression.Constant(0L), Expression.Constant(0), typeof(long)));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant("hello"), typeof(object)));
Assert.Throws<ArgumentException>(() => Expression.Condition(Expression.Constant(true), Expression.Constant("hello"), Expression.Constant(0), typeof(object)));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void AnyTypesAllowedWithExplicitVoid(bool useInterpreter)
{
Action act = Expression.Lambda<Action>(
Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant(0L), typeof(void))
).Compile(useInterpreter);
act();
act = Expression.Lambda<Action>(
Expression.Condition(Expression.Constant(true), Expression.Constant(0L), Expression.Constant(0), typeof(void))
).Compile(useInterpreter);
act();
}
[Theory, PerCompilationType(nameof(ConditionalValues))]
public void ConditionalSelectsCorrectExpression(bool test, object ifTrue, object ifFalse, object expected, bool useInterpreter)
{
Func<object> func = Expression.Lambda<Func<object>>(
Expression.Convert(
Expression.Condition(
Expression.Constant(test),
Expression.Constant(ifTrue),
Expression.Constant(ifFalse)
),
typeof(object)
)
).Compile(useInterpreter);
Assert.Equal(expected, func());
}
[Theory, PerCompilationType(nameof(ConditionalValuesWithTypes))]
public void ConditionalSelectsCorrectExpressionWithType(bool test, object ifTrue, object ifFalse, object expected, Type type, bool useInterpreter)
{
Func<object> func = Expression.Lambda<Func<object>>(
Expression.Condition(
Expression.Constant(test),
Expression.Constant(ifTrue),
Expression.Constant(ifFalse),
type
)
).Compile(useInterpreter);
Assert.Same(expected, func());
}
[Fact]
public void ByRefType()
{
Assert.Throws<ArgumentException>(() => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(string).MakeByRefType()));
}
[Fact]
public void PointerType()
{
Assert.Throws<ArgumentException>(() => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(string).MakePointerType()));
}
[Fact]
public void GenericType()
{
Assert.Throws<ArgumentException>(() => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(List<>)));
}
[Fact]
public void TypeContainsGenericParameters()
{
Assert.Throws<ArgumentException>(() => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(List<>.Enumerator)));
Assert.Throws<ArgumentException>(() => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(List<>).MakeGenericType(typeof(List<>))));
}
private static IEnumerable<object[]> ConditionalValues()
{
yield return new object[] { true, "yes", "no", "yes" };
yield return new object[] { false, "yes", "no", "no" };
yield return new object[] { true, 42, 12, 42 };
yield return new object[] { false, 42L, 12L, 12L };
}
private static IEnumerable<object[]> ConditionalValuesWithTypes()
{
ConstantExpression ce = Expression.Constant(98);
BinaryExpression be = Expression.And(Expression.Constant(2), Expression.Constant(3));
yield return new object[] { true, ce, be, ce, typeof(Expression) };
yield return new object[] { false, ce, be, be, typeof(Expression) };
}
private class Truthiness
{
private bool Value { get; }
public Truthiness(bool value)
{
Value = value;
}
public static implicit operator bool(Truthiness truth) => truth.Value;
public static bool operator true(Truthiness truth) => truth.Value;
public static bool operator false(Truthiness truth) => !truth.Value;
public static Truthiness operator !(Truthiness truth) => new Truthiness(!truth.Value);
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
private static void Nop()
{
}
private class Visitor : ExpressionVisitor
{
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
// James Driscoll, mailto:[email protected]
//
// 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
[assembly: Elmah.Scc("$Id: ConnectionStringHelper.cs 641 2009-06-01 17:38:40Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Configuration;
using System.Data.Common;
using System.IO;
using System.Runtime.CompilerServices;
using IDictionary = System.Collections.IDictionary;
#endregion
/// <summary>
/// Helper class for resolving connection strings.
/// </summary>
static class ConnectionStringHelper
{
/// <summary>
/// Gets the connection string from the given configuration
/// dictionary.
/// </summary>
public static string GetConnectionString(IDictionary config)
{
Debug.Assert(config != null);
//
// First look for a connection string name that can be
// subsequently indexed into the <connectionStrings> section of
// the configuration to get the actual connection string.
//
string connectionStringName = config.Find("connectionStringName", string.Empty);
if (connectionStringName.Length > 0)
{
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[connectionStringName];
if (settings == null)
return string.Empty;
return settings.ConnectionString ?? string.Empty;
}
//
// Connection string name not found so see if a connection
// string was given directly.
//
var connectionString = config.Find("connectionString", string.Empty);
if (connectionString.Length > 0)
return connectionString;
//
// As a last resort, check for another setting called
// connectionStringAppKey. The specifies the key in
// <appSettings> that contains the actual connection string to
// be used.
//
var connectionStringAppKey = config.Find("connectionStringAppKey", string.Empty);
return connectionStringAppKey.Length > 0
? ConfigurationManager.AppSettings[connectionStringAppKey]
: string.Empty;
}
/// <summary>
/// Gets the provider name from the named connection string (if supplied)
/// from the given configuration dictionary.
/// </summary>
public static string GetConnectionStringProviderName(IDictionary config)
{
Debug.Assert(config != null);
//
// First look for a connection string name that can be
// subsequently indexed into the <connectionStrings> section of
// the configuration to get the actual connection string.
//
var connectionStringName = config.Find("connectionStringName", string.Empty);
if (connectionStringName.Length == 0)
return string.Empty;
var settings = ConfigurationManager.ConnectionStrings[connectionStringName];
if (settings == null)
return string.Empty;
return settings.ProviderName ?? string.Empty;
}
/// <summary>
/// Extracts the Data Source file path from a connection string
/// ~/ gets resolved as does |DataDirectory|
/// </summary>
public static string GetDataSourceFilePath(string connectionString)
{
Debug.AssertStringNotEmpty(connectionString);
DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
return GetDataSourceFilePath(builder, connectionString);
}
/// <summary>
/// Gets the connection string from the given configuration,
/// resolving ~/ and DataDirectory if necessary.
/// </summary>
public static string GetConnectionString(IDictionary config, bool resolveDataSource)
{
string connectionString = GetConnectionString(config);
return resolveDataSource ? GetResolvedConnectionString(connectionString) : connectionString;
}
/// <summary>
/// Converts the supplied connection string so that the Data Source
/// specification contains the full path and not ~/ or DataDirectory.
/// </summary>
public static string GetResolvedConnectionString(string connectionString)
{
Debug.AssertStringNotEmpty(connectionString);
DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
builder["Data Source"] = GetDataSourceFilePath(builder, connectionString);
return builder.ToString();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static string MapPath(string path)
{
return System.Web.Hosting.HostingEnvironment.MapPath(path);
}
private static string GetDataSourceFilePath(DbConnectionStringBuilder builder, string connectionString)
{
builder.ConnectionString = connectionString;
if (!builder.ContainsKey("Data Source"))
throw new ArgumentException("A 'Data Source' parameter was expected in the supplied connection string, but it was not found.");
string dataSource = builder["Data Source"].ToString();
return ResolveDataSourceFilePath(dataSource);
}
private static readonly char[] _dirSeparators = new char[] { Path.DirectorySeparatorChar };
private static string ResolveDataSourceFilePath(string path)
{
const string dataDirectoryMacroString = "|DataDirectory|";
//
// Check to see if it starts with a ~/ and if so map it and return it.
//
if (path.StartsWith("~/"))
return MapPath(path);
//
// Else see if it uses the DataDirectory macro/substitution
// string, and if so perform the appropriate substitution.
//
if (!path.StartsWith(dataDirectoryMacroString, StringComparison.OrdinalIgnoreCase))
return path;
//
// Look-up the data directory from the current AppDomain.
// See "Working with local databases" for more:
// http://blogs.msdn.com/smartclientdata/archive/2005/08/26/456886.aspx
//
string baseDirectory = AppDomain.CurrentDomain.GetData("DataDirectory") as string;
//
// If not, try the current AppDomain's base directory.
//
if (string.IsNullOrEmpty(baseDirectory))
baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
//
// Piece the file path back together, taking leading and
// trailing backslashes into account to avoid duplication.
//
return (baseDirectory ?? string.Empty).TrimEnd(_dirSeparators)
+ Path.DirectorySeparatorChar
+ path.Substring(dataDirectoryMacroString.Length).TrimStart(_dirSeparators);
}
}
}
| |
//
// Encog(tm) Core v3.2 - .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 Encog.ML.Data.Market;
using Encog.Util.CSV;
using System.IO;
using Encog.ML.Data.Market.Loader;
namespace ErrorTesterConsoleApplication
{
public class MultiCsvLoader : IMarketLoader
{
#region IMarketLoader Members
string Precision { get; set; }
private string LoadedFile { get; set; }
/// <summary>
/// Set CSVFormat, default CSVFormat.DecimalPoint
/// </summary>
public CSVFormat LoadedFormat { get; set; }
/// <summary>
/// Use to indicate that Date and Time exist in different columns, default true
/// </summary>
bool DateTimeDualColumn { get; set; }
/// <summary>
/// Use to set format for Date or DateTime column, default MM/dd/yyyy
/// </summary>
string DateFormat { get; set; }
/// <summary>
/// Use to set format for Time column, default HHmm
/// </summary>
string TimeFormat { get; set; }
/// <summary>
/// Links a TickerSymbol to a CSV file
/// </summary>
private IDictionary<TickerSymbol, string> fileList = new Dictionary<TickerSymbol, string>();
/// <summary>
/// Construct a multi CSV file loader
/// </summary>
public MultiCsvLoader()
{
LoadedFormat = CSVFormat.DecimalPoint;
DateTimeDualColumn = true;
DateFormat = "MM/dd/yyyy";
TimeFormat = "HHmm";
}
/// <summary>
/// Construct a multi CSV file loader with option to set loaded format and indicate if CSV date is in two columns
/// </summary>
/// <param name="format">Set the CSV format</param>
/// <param name="dualDateTimeColumn"> Indicate true for DateTime information in two separate columns</param>
public MultiCsvLoader(CSVFormat format, bool dualDateTimeColumn)
{
LoadedFormat = format;
DateTimeDualColumn = dualDateTimeColumn;
}
/// <summary>
/// Reads and parses CSV data from file
/// </summary>
/// <param name="ticker">Ticker associated with CSV file</param>
/// <param name="neededTypes">Columns to parse (headers)</param>
/// <param name="from">DateTime from</param>
/// <param name="to">DateTime to</param>
/// <param name="File">Filepath to CSV</param>
/// <returns>Marketdata</returns>
public ICollection<LoadedMarketData> ReadAndCallLoader(TickerSymbol ticker, IList<MarketDataType> neededTypes, DateTime from, DateTime to, string File)
{
try
{
LoadedFile = File;
Console.WriteLine("Loading instrument: " + ticker.Symbol + " from: " + File);
//We got a file, lets load it.
ICollection<LoadedMarketData> result = new List<LoadedMarketData>();
ReadCSV csv = new ReadCSV(File, true, LoadedFormat);
if (DateTimeDualColumn)
{
csv.DateFormat = DateFormat;
csv.TimeFormat = TimeFormat;
}
else
{
csv.DateFormat = DateFormat;
}
//"Date","Time","Open","High","Low","Close","Volume"
while (csv.Next())
{
string datetime = "";
if (DateTimeDualColumn)
{
datetime = csv.GetDate("Date").ToShortDateString() + " " +
csv.GetTime("Time").ToShortTimeString();
}
else
{
datetime = csv.GetDate("Date").ToShortDateString();
}
DateTime date = DateTime.Parse(datetime);
if (date > from && date < to)
{
// CSV columns
double open = csv.GetDouble("Open");
double high = csv.GetDouble("High");
double low = csv.GetDouble("Low");
double close = csv.GetDouble("Close");
double volume = csv.GetDouble("Volume");
LoadedMarketData data = new LoadedMarketData(date, ticker);
foreach (MarketDataType marketDataType in neededTypes)
{
switch (marketDataType.ToString())
{
case "Open":
data.SetData(MarketDataType.Open, open);
break;
case "High":
data.SetData(MarketDataType.High, high);
break;
case "Low":
data.SetData(MarketDataType.Low, low);
break;
case "Close":
data.SetData(MarketDataType.Close, close);
break;
case "Volume":
data.SetData(MarketDataType.Volume, volume);
break;
case "RangeHighLow":
data.SetData(MarketDataType.RangeHighLow, Math.Round(Math.Abs(high - low), 6));
break;
case "RangeOpenClose":
data.SetData(MarketDataType.RangeOpenClose, Math.Round(Math.Abs(close - open), 6));
break;
case "RangeOpenCloseNonAbsolute":
data.SetData(MarketDataType.RangeOpenCloseNonAbsolute, Math.Round(close - open, 6));
break;
case "Weighted":
data.SetData(MarketDataType.Weighted, Math.Round((high + low + 2 * close) / 4, 6));
break;
}
}
result.Add(data);
}
}
csv.Close();
return result;
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong reading the csv: " + ex.Message);
}
return null;
}
/// <summary>
/// Set correct CSVFormat, e.g. "Decimal Point"
/// </summary>
/// <param name="csvformat">Enter format, e.g. "Decimal Point"</param>
/// <returns></returns>
public CSVFormat fromStringCSVFormattoCSVFormat(string csvformat)
{
switch (csvformat)
{
case "Decimal Point":
LoadedFormat = CSVFormat.DecimalPoint;
break;
case "Decimal Comma":
LoadedFormat = CSVFormat.DecimalComma;
break;
case "English Format":
LoadedFormat = CSVFormat.English;
break;
case "EG Format":
LoadedFormat = CSVFormat.EgFormat;
break;
default:
break;
}
return LoadedFormat;
}
#region IMarketLoader Members
/// <derived/>
public ICollection<LoadedMarketData> Load(TickerSymbol ticker, IList<MarketDataType> dataNeeded,
DateTime from, DateTime to)
{
try
{
string fileCSV = "";
foreach (TickerSymbol tickerSymbol in fileList.Keys)
{
if (tickerSymbol.Symbol.ToLower().Equals(ticker.Symbol.ToLower()))
{
if (fileList.TryGetValue(tickerSymbol, out fileCSV))
{
return File.Exists(fileCSV) ?
(ReadAndCallLoader(tickerSymbol, dataNeeded, from, to, fileCSV)) : null; //If file does not exist
}
return null; //Problem reading list
}
}
return null; //if ticker is not defined
}
catch (FileNotFoundException fnfe)
{
Console.WriteLine("Problem with loading data for instruments", fnfe);
return null;
}
}
//Should be removed/changed in interface
public string GetFile(string file)
{
return LoadedFile;
}
#endregion
/// <summary>
/// Add filepaths with matching ticker symbols
/// </summary>
/// <param name="ticker">Set Ticker, e.g. EURUSD</param>
/// <param name="fileName">Set filepath, e.g. .\\EURUSD.csv</param>
/// <returns>True returned if file exists, if file does not exist FileNotFoundException thrown,
/// if TickerSymbol exist false is returned</returns>
public bool SetFiles(string ticker, string fileName)
{
if (!File.Exists(fileName))
{
throw new FileNotFoundException("File submitted did not exist", fileName);
}
else if (!fileList.ContainsKey(new TickerSymbol(ticker)))
{
fileList.Add(new TickerSymbol(ticker), fileName);
return true;
}
return false; //Ticker exists
}
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using System;
using NPOI.OpenXml4Net.OPC;
using NPOI.OpenXmlFormats.Dml;
using NPOI.OpenXmlFormats.Dml.Spreadsheet;
namespace NPOI.XSSF.UserModel
{
/**
* This object specifies a group shape that represents many shapes grouped together. This shape is to be treated
* just as if it were a regular shape but instead of being described by a single geometry it is made up of all the
* shape geometries encompassed within it. Within a group shape each of the shapes that make up the group are
* specified just as they normally would.
*
* @author Yegor Kozlov
*/
public class XSSFShapeGroup : XSSFShape
{
private static CT_GroupShape prototype = null;
private CT_GroupShape ctGroup;
/**
* Construct a new XSSFSimpleShape object.
*
* @param Drawing the XSSFDrawing that owns this shape
* @param ctGroup the XML bean that stores this group content
*/
public XSSFShapeGroup(XSSFDrawing drawing, CT_GroupShape ctGroup)
{
this.drawing = drawing;
this.ctGroup = ctGroup;
}
/**
* Initialize default structure of a new shape group
*/
internal static CT_GroupShape Prototype()
{
CT_GroupShape shape = new CT_GroupShape();
CT_GroupShapeNonVisual nv = shape.AddNewNvGrpSpPr();
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_NonVisualDrawingProps nvpr = nv.AddNewCNvPr();
nvpr.id = (0);
nvpr.name = ("Group 0");
nv.AddNewCNvGrpSpPr();
CT_GroupShapeProperties sp = shape.AddNewGrpSpPr();
CT_GroupTransform2D t2d = sp.AddNewXfrm();
CT_PositiveSize2D p1 = t2d.AddNewExt();
p1.cx = (0);
p1.cy = (0);
CT_Point2D p2 = t2d.AddNewOff();
p2.x = (0);
p2.y = (0);
CT_PositiveSize2D p3 = t2d.AddNewChExt();
p3.cx = (0);
p3.cy = (0);
CT_Point2D p4 = t2d.AddNewChOff();
p4.x = (0);
p4.y = (0);
prototype = shape;
return prototype;
}
/**
* Constructs a textbox.
*
* @param anchor the child anchor describes how this shape is attached
* to the group.
* @return the newly Created textbox.
*/
public XSSFTextBox CreateTextbox(XSSFChildAnchor anchor)
{
CT_Shape ctShape = ctGroup.AddNewSp();
ctShape.Set(XSSFSimpleShape.Prototype());
XSSFTextBox shape = new XSSFTextBox(GetDrawing(), ctShape);
shape.parent = this;
shape.anchor = anchor;
shape.GetCTShape().spPr.xfrm = (anchor.GetCTTransform2D());
return shape;
}
/**
* Creates a simple shape. This includes such shapes as lines, rectangles,
* and ovals.
*
* @param anchor the child anchor describes how this shape is attached
* to the group.
* @return the newly Created shape.
*/
public XSSFSimpleShape CreateSimpleShape(XSSFChildAnchor anchor)
{
CT_Shape ctShape = ctGroup.AddNewSp();
ctShape.Set(XSSFSimpleShape.Prototype());
XSSFSimpleShape shape = new XSSFSimpleShape(GetDrawing(), ctShape);
shape.parent = (this);
shape.anchor = anchor;
shape.GetCTShape().spPr.xfrm = (anchor.GetCTTransform2D());
return shape;
}
/**
* Creates a simple shape. This includes such shapes as lines, rectangles,
* and ovals.
*
* @param anchor the child anchor describes how this shape is attached
* to the group.
* @return the newly Created shape.
*/
public XSSFConnector CreateConnector(XSSFChildAnchor anchor)
{
CT_Connector ctShape = ctGroup.AddNewCxnSp();
ctShape.Set(XSSFConnector.Prototype());
XSSFConnector shape = new XSSFConnector(GetDrawing(), ctShape);
shape.parent = this;
shape.anchor = anchor;
shape.GetCTConnector().spPr.xfrm = (anchor.GetCTTransform2D());
return shape;
}
/**
* Creates a picture.
*
* @param anchor the client anchor describes how this picture is attached to the sheet.
* @param pictureIndex the index of the picture in the workbook collection of pictures,
* {@link XSSFWorkbook#getAllPictures()} .
* @return the newly Created picture shape.
*/
public XSSFPicture CreatePicture(XSSFClientAnchor anchor, int pictureIndex)
{
PackageRelationship rel = GetDrawing().AddPictureReference(pictureIndex);
CT_Picture ctShape = ctGroup.AddNewPic();
ctShape.Set(XSSFPicture.Prototype());
XSSFPicture shape = new XSSFPicture(GetDrawing(), ctShape);
shape.parent = this;
shape.anchor = anchor;
shape.SetPictureReference(rel);
return shape;
}
public CT_GroupShape GetCTGroupShape()
{
return ctGroup;
}
/**
* Sets the coordinate space of this group. All children are constrained
* to these coordinates.
*/
public void SetCoordinates(int x1, int y1, int x2, int y2)
{
CT_GroupTransform2D t2d = ctGroup.grpSpPr.xfrm;
CT_Point2D off = t2d.off;
off.x = (x1);
off.y = (y1);
CT_PositiveSize2D ext = t2d.ext;
ext.cx = (x2);
ext.cy = (y2);
CT_Point2D chOff = t2d.chOff;
chOff.x = (x1);
chOff.y = (y1);
CT_PositiveSize2D chExt = t2d.chExt;
chExt.cx = (x2);
chExt.cy = (y2);
}
protected internal override NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_ShapeProperties GetShapeProperties()
{
throw new InvalidOperationException("Not supported for shape group");
}
}
}
| |
// 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.
/*
We are testing the following scenario:
interface I<T> {}
[in Class_ImplicitOverrideVirtualNewslot.cs]
class C<T> : I<T> { virtual newslot methods}
class D<T> : C<T> {virtual NEWSLOT methods}
--> When invoking I::method<T>() we should get the parent's implementation.
*/
using System;
public class CC1 : C1
{
public new virtual int method1()
{
return 10;
}
public new virtual int method2<T>()
{
return 20;
}
}
public class CC2<T> : C2<T>
{
public new virtual int method1()
{
return 30;
}
public new virtual int method2<U>()
{
return 40;
}
}
public class CC3Int : C3Int
{
public new virtual int method1()
{
return 50;
}
public new virtual int method2<U>()
{
return 60;
}
}
public class CC3String : C3String
{
public new virtual int method1()
{
return 50;
}
public new virtual int method2<U>()
{
return 60;
}
}
public class CC3Object: C3Object
{
public new virtual int method1()
{
return 50;
}
public new virtual int method2<U>()
{
return 60;
}
}
public class CC4<T> : C4<T>
{
public new virtual int method1()
{
return 70;
}
public new virtual int method2<U>()
{
return 80;
}
}
public class Test
{
public static int counter = 0;
public static bool pass = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
pass = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static void TestNonGenInterface_NonGenType()
{
I ic1 = new CC1();
// since CC1's method doesn't have newslot, in both cases we should get CC1's method
// TEST1: test generic virtual method
Eval( (ic1.method2<int>().ToString()).Equals("2") );
Eval( (ic1.method2<string>() .ToString()).Equals("2") );
Eval( (ic1.method2<object>().ToString()).Equals("2") );
Eval( (ic1.method2<A<int>>().ToString()).Equals("2") );
Eval( (ic1.method2<S<object>>().ToString()).Equals("2") );
}
public static void TestNonGenInterface_GenType()
{
I ic2Int = new CC2<int>();
I ic2Object = new CC2<object>();
I ic2String = new CC2<string>();
// TEST2: test non generic virtual method
Eval( (ic2Int.method1().ToString()).Equals("3") );
Eval( (ic2String.method1().ToString()).Equals("3") );
Eval( (ic2Object.method1().ToString()).Equals("3") );
// TEST3: test generic virtual method
Eval( (ic2Int.method2<int>().ToString()).Equals("4") );
Eval( (ic2Int.method2<object>().ToString()).Equals("4") );
Eval( (ic2Int.method2<string>().ToString()).Equals("4") );
Eval( (ic2Int.method2<A<int>>().ToString()).Equals("4") );
Eval( (ic2Int.method2<S<string>>().ToString()).Equals("4") );
Eval( (ic2String.method2<int>().ToString()).Equals("4") );
Eval( (ic2String.method2<object>().ToString()).Equals("4") );
Eval( (ic2String.method2<string>().ToString()).Equals("4") );
Eval( (ic2String.method2<A<int>>().ToString()).Equals("4") );
Eval( (ic2String.method2<S<string>>().ToString()).Equals("4") );
Eval( (ic2Object.method2<int>().ToString()).Equals("4") );
Eval( (ic2Object.method2<object>().ToString()).Equals("4") );
Eval( (ic2Object.method2<string>().ToString()).Equals("4") );
Eval( (ic2Object.method2<A<int>>().ToString()).Equals("4") );
Eval( (ic2Object.method2<S<string>>().ToString()).Equals("4") );
}
public static void TestGenInterface_NonGenType()
{
IGen<int> iIntc3 = new CC3Int();
IGen<object> iObjectc3 = new CC3Object();
IGen<string> iStringc3 = new CC3String();
// TEST4: test non generic virtual method
Eval( (iIntc3.method1().ToString()).Equals("5") );
Eval( (iObjectc3.method1().ToString()).Equals("5") );
Eval( (iStringc3.method1().ToString()).Equals("5") );
// TEST5: test generic virtual method
Eval( (iIntc3.method2<int>().ToString()).Equals("6") );
Eval( (iIntc3.method2<object>().ToString()).Equals("6") );
Eval( (iIntc3.method2<string>().ToString()).Equals("6") );
Eval( (iIntc3.method2<A<int>>().ToString()).Equals("6") );
Eval( (iIntc3.method2<S<string>>().ToString()).Equals("6") );
Eval( (iStringc3.method2<int>().ToString()).Equals("6") );
Eval( (iStringc3.method2<object>().ToString()).Equals("6") );
Eval( (iStringc3.method2<string>().ToString()).Equals("6") );
Eval( (iStringc3.method2<A<int>>().ToString()).Equals("6") );
Eval( (iStringc3.method2<S<string>>().ToString()).Equals("6") );
Eval( (iObjectc3.method2<int>().ToString()).Equals("6") );
Eval( (iObjectc3.method2<object>().ToString()).Equals("6") );
Eval( (iObjectc3.method2<string>().ToString()).Equals("6") );
Eval( (iObjectc3.method2<A<int>>().ToString()).Equals("6") );
Eval( (iObjectc3.method2<S<string>>().ToString()).Equals("6") );
}
public static void TestGenInterface_GenType()
{
IGen<int> iGenC4Int = new CC4<int>();
IGen<object> iGenC4Object = new CC4<object>();
IGen<string> iGenC4String = new CC4<string>();
// TEST6: test non generic virtual method
Eval( (iGenC4Int.method1().ToString()).Equals("7") );
Eval( (iGenC4Object.method1().ToString()).Equals("7") );
Eval( (iGenC4String.method1().ToString()).Equals("7") );
// TEST7: test generic virtual method
Eval( (iGenC4Int.method2<int>().ToString()).Equals("8") );
Eval( (iGenC4Int.method2<object>().ToString()).Equals("8") );
Eval( (iGenC4Int.method2<string>().ToString()).Equals("8") );
Eval( (iGenC4Int.method2<A<int>>().ToString()).Equals("8") );
Eval( (iGenC4Int.method2<S<string>>().ToString()).Equals("8") );
Eval( (iGenC4String.method2<int>().ToString()).Equals("8") );
Eval( (iGenC4String.method2<object>().ToString()).Equals("8") );
Eval( (iGenC4String.method2<string>().ToString()).Equals("8") );
Eval( (iGenC4String.method2<A<int>>().ToString()).Equals("8") );
Eval( (iGenC4String.method2<S<string>>().ToString()).Equals("8") );
Eval( (iGenC4Object.method2<int>().ToString()).Equals("8") );
Eval( (iGenC4Object.method2<object>().ToString()).Equals("8") );
Eval( (iGenC4Object.method2<string>().ToString()).Equals("8") );
Eval( (iGenC4Object.method2<A<int>>().ToString()).Equals("8") );
Eval( (iGenC4Object.method2<S<string>>().ToString()).Equals("8") );
}
public static int Main()
{
TestNonGenInterface_NonGenType();
TestNonGenInterface_GenType();
TestGenInterface_NonGenType();
TestGenInterface_GenType();
if (pass)
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL");
return 101;
}
}
}
| |
//
// System.Web.UI.WebControls.TableStyle.cs
//
// Authors:
// Gaurav Vaish ([email protected])
// Andreas Nahr ([email protected])
//
// (C) Gaurav Vaish (2002)
// (C) 2003 Andreas Nahr
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.ComponentModel;
using System.Globalization;
using System.Web;
using System.Web.UI;
namespace System.Web.UI.WebControls
{
public class TableStyle : Style
{
private static int IMAGE_URL = (0x01 << 16);
private static int CELL_PADD = (0x01 << 17);
private static int CELL_SPAC = (0x01 << 18);
private static int GRID_LINE = (0x01 << 19);
private static int HOR_ALIGN = (0x01 << 20);
public TableStyle(): base()
{
}
public TableStyle(StateBag bag): base(bag)
{
}
#if NET_2_0
[NotifyParentPropertyAttribute (true)]
[UrlPropertyAttribute]
#else
[Bindable (true)]
#endif
[DefaultValue (""), WebCategory ("Appearance")]
[WebSysDescription ("An Url specifying the background image for the table.")]
public virtual string BackImageUrl
{
get
{
if(IsSet(IMAGE_URL))
return (string)(ViewState["BackImageUrl"]);
return String.Empty;
}
set
{
if(value == null)
throw new ArgumentNullException("value");
ViewState["BackImageUrl"] = value;
Set(IMAGE_URL);
}
}
#if NET_2_0
[NotifyParentPropertyAttribute (true)]
#else
[Bindable (true)]
#endif
[DefaultValue (-1), WebCategory ("Appearance")]
[WebSysDescription ("The space left around the borders within a cell.")]
public virtual int CellPadding
{
get
{
if(IsSet(CELL_PADD))
return (int)(ViewState["CellPadding"]);
return -1;
}
set
{
if(value < -1)
throw new ArgumentOutOfRangeException("value", "CellPadding value has to be -1 for 'not set' or a value >= 0");
ViewState["CellPadding"] = value;
Set(CELL_PADD);
}
}
#if NET_2_0
[NotifyParentPropertyAttribute (true)]
#else
[Bindable (true)]
#endif
[DefaultValue (-1), WebCategory ("Appearance")]
[WebSysDescription ("The space left between cells.")]
public virtual int CellSpacing
{
get
{
if(IsSet(CELL_SPAC))
return (int)(ViewState["CellSpacing"]);
return -1;
}
set
{
if(value < -1)
throw new ArgumentOutOfRangeException("value"," CellSpacing value has to be -1 for 'not set' or a value >= 0");
ViewState["CellSpacing"] = value;
Set(CELL_SPAC);
}
}
#if NET_2_0
[NotifyParentPropertyAttribute (true)]
#else
[Bindable (true)]
#endif
[DefaultValue (typeof (GridLines), "None"), WebCategory ("Appearance")]
[WebSysDescription ("The type of grid that a table uses.")]
public virtual GridLines GridLines
{
get
{
if(IsSet(GRID_LINE))
return (GridLines)(ViewState["GridLines"]);
return GridLines.None;
}
set
{
if(!Enum.IsDefined(typeof(GridLines), value))
throw new ArgumentOutOfRangeException("value"," Gridlines value has to be a valid enumeration member");
ViewState["GridLines"] = value;
Set(GRID_LINE);
}
}
#if NET_2_0
[NotifyParentPropertyAttribute (true)]
#else
[Bindable (true)]
#endif
[DefaultValue (typeof (HorizontalAlign), "NotSet"), WebCategory ("Layout")]
[WebSysDescription ("The horizonal alignment of the table.")]
public virtual HorizontalAlign HorizontalAlign
{
get
{
if(IsSet(HOR_ALIGN))
return (HorizontalAlign)(ViewState["HorizontalAlign"]);
return HorizontalAlign.NotSet;
}
set
{
if(!Enum.IsDefined(typeof(HorizontalAlign), value))
throw new ArgumentOutOfRangeException("value"," Gridlines value has to be a valid enumeration member");
ViewState["HorizontalAlign"] = value;
Set(HOR_ALIGN);
}
}
public override void AddAttributesToRender(HtmlTextWriter writer, WebControl owner)
{
base.AddAttributesToRender(writer, owner);
if(BackImageUrl.Length > 0)
{
writer.AddStyleAttribute(HtmlTextWriterStyle.BackgroundImage, "url(" + owner.ResolveUrl(BackImageUrl) + ")");
}
if(CellSpacing >= 0)
{
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, CellSpacing.ToString(NumberFormatInfo.InvariantInfo));
if(CellSpacing == 0)
writer.AddStyleAttribute(HtmlTextWriterStyle.BorderCollapse, "collapse");
}
if(CellPadding >= 0)
{
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, CellPadding.ToString(NumberFormatInfo.InvariantInfo));
}
if(HorizontalAlign != HorizontalAlign.NotSet)
{
writer.AddAttribute(HtmlTextWriterAttribute.Align, Enum.Format(typeof(HorizontalAlign), HorizontalAlign, "G"));
}
string gd = null;
switch(GridLines)
{
case GridLines.None: break;
case GridLines.Horizontal: gd = "rows";
break;
case GridLines.Vertical: gd = "cols";
break;
case GridLines.Both: gd = "all";
break;
}
if (gd != null)
writer.AddAttribute(HtmlTextWriterAttribute.Rules, gd);
}
public override void CopyFrom(Style s)
{
if (s == null || s.IsEmpty)
return;
base.CopyFrom (s);
TableStyle from = s as TableStyle;
if (from == null)
return;
if (from.IsSet (HOR_ALIGN))
HorizontalAlign = from.HorizontalAlign;
if (from.IsSet (IMAGE_URL))
BackImageUrl = from.BackImageUrl;
if (from.IsSet (CELL_PADD))
CellPadding = from.CellPadding;
if (from.IsSet (CELL_SPAC))
CellSpacing = from.CellSpacing;
if (from.IsSet (GRID_LINE))
GridLines = from.GridLines;
}
public override void MergeWith(Style s)
{
if(s != null && !s.IsEmpty)
{
if (IsEmpty) {
CopyFrom (s);
return;
}
base.MergeWith(s);
if (!(s is TableStyle))
return;
TableStyle with = (TableStyle)s;
if(with.IsSet(HOR_ALIGN) && !IsSet(HOR_ALIGN))
{
HorizontalAlign = with.HorizontalAlign;
}
if(with.IsSet(IMAGE_URL) && !IsSet(IMAGE_URL))
{
BackImageUrl = with.BackImageUrl;
}
if(with.IsSet(CELL_PADD) && !IsSet(CELL_PADD))
{
CellPadding = with.CellPadding;
}
if(with.IsSet(CELL_SPAC) && !IsSet(CELL_SPAC))
{
CellSpacing = with.CellSpacing;
}
if(with.IsSet(GRID_LINE) && !IsSet(GRID_LINE))
{
GridLines = with.GridLines;
}
}
}
public override void Reset()
{
if(IsSet(IMAGE_URL))
ViewState.Remove("BackImageUrl");
if(IsSet(HOR_ALIGN))
ViewState.Remove("HorizontalAlign");
if(IsSet(CELL_PADD))
ViewState.Remove("CellPadding");
if(IsSet(CELL_SPAC))
ViewState.Remove("CellSpacing");
if(IsSet(GRID_LINE))
ViewState.Remove("GridLines");
base.Reset();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.ComponentModel
{
/// <summary>
/// <para>Specifies the category in which the property or event will be displayed in a
/// visual designer.</para>
/// </summary>
[AttributeUsage(AttributeTargets.All)]
public class CategoryAttribute : Attribute
{
private static volatile CategoryAttribute s_action;
private static volatile CategoryAttribute s_appearance;
private static volatile CategoryAttribute s_asynchronous;
private static volatile CategoryAttribute s_behavior;
private static volatile CategoryAttribute s_data;
private static volatile CategoryAttribute s_design;
private static volatile CategoryAttribute s_dragDrop;
private static volatile CategoryAttribute s_defAttr;
private static volatile CategoryAttribute s_focus;
private static volatile CategoryAttribute s_format;
private static volatile CategoryAttribute s_key;
private static volatile CategoryAttribute s_layout;
private static volatile CategoryAttribute s_mouse;
private static volatile CategoryAttribute s_windowStyle;
private bool _localized;
/// <summary>
/// <para>
/// Provides the actual category name.
/// </para>
/// </summary>
private string _categoryValue;
/// <summary>
/// <para>Gets the action category attribute.</para>
/// </summary>
public static CategoryAttribute Action
{
get
{
if (s_action == null)
{
s_action = new CategoryAttribute(nameof(Action));
}
return s_action;
}
}
/// <summary>
/// <para>Gets the appearance category attribute.</para>
/// </summary>
public static CategoryAttribute Appearance
{
get
{
if (s_appearance == null)
{
s_appearance = new CategoryAttribute(nameof(Appearance));
}
return s_appearance;
}
}
/// <summary>
/// <para>Gets the asynchronous category attribute.</para>
/// </summary>
public static CategoryAttribute Asynchronous
{
get
{
if (s_asynchronous == null)
{
s_asynchronous = new CategoryAttribute(nameof(Asynchronous));
}
return s_asynchronous;
}
}
/// <summary>
/// <para>Gets the behavior category attribute.</para>
/// </summary>
public static CategoryAttribute Behavior
{
get
{
if (s_behavior == null)
{
s_behavior = new CategoryAttribute(nameof(Behavior));
}
return s_behavior;
}
}
/// <summary>
/// <para>Gets the data category attribute.</para>
/// </summary>
public static CategoryAttribute Data
{
get
{
if (s_data == null)
{
s_data = new CategoryAttribute(nameof(Data));
}
return s_data;
}
}
/// <summary>
/// <para>Gets the default category attribute.</para>
/// </summary>
public static CategoryAttribute Default
{
get
{
if (s_defAttr == null)
{
s_defAttr = new CategoryAttribute();
}
return s_defAttr;
}
}
/// <summary>
/// <para>Gets the design category attribute.</para>
/// </summary>
public static CategoryAttribute Design
{
get
{
if (s_design == null)
{
s_design = new CategoryAttribute(nameof(Design));
}
return s_design;
}
}
/// <summary>
/// <para>Gets the drag and drop category attribute.</para>
/// </summary>
public static CategoryAttribute DragDrop
{
get
{
if (s_dragDrop == null)
{
s_dragDrop = new CategoryAttribute(nameof(DragDrop));
}
return s_dragDrop;
}
}
/// <summary>
/// <para>Gets the focus category attribute.</para>
/// </summary>
public static CategoryAttribute Focus
{
get
{
if (s_focus == null)
{
s_focus = new CategoryAttribute(nameof(Focus));
}
return s_focus;
}
}
/// <summary>
/// <para>Gets the format category attribute.</para>
/// </summary>
public static CategoryAttribute Format
{
get
{
if (s_format == null)
{
s_format = new CategoryAttribute(nameof(Format));
}
return s_format;
}
}
/// <summary>
/// <para>Gets the keyboard category attribute.</para>
/// </summary>
public static CategoryAttribute Key
{
get
{
if (s_key == null)
{
s_key = new CategoryAttribute(nameof(Key));
}
return s_key;
}
}
/// <summary>
/// <para>Gets the layout category attribute.</para>
/// </summary>
public static CategoryAttribute Layout
{
get
{
if (s_layout == null)
{
s_layout = new CategoryAttribute(nameof(Layout));
}
return s_layout;
}
}
/// <summary>
/// <para>Gets the mouse category attribute.</para>
/// </summary>
public static CategoryAttribute Mouse
{
get
{
if (s_mouse == null)
{
s_mouse = new CategoryAttribute(nameof(Mouse));
}
return s_mouse;
}
}
/// <summary>
/// <para> Gets the window style category
/// attribute.</para>
/// </summary>
public static CategoryAttribute WindowStyle
{
get
{
if (s_windowStyle == null)
{
s_windowStyle = new CategoryAttribute(nameof(WindowStyle));
}
return s_windowStyle;
}
}
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.CategoryAttribute'/>
/// class with the default category.</para>
/// </summary>
public CategoryAttribute() : this(nameof(Default))
{
}
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.CategoryAttribute'/> class with
/// the specified category name.</para>
/// </summary>
public CategoryAttribute(string category)
{
_categoryValue = category;
_localized = false;
}
/// <summary>
/// <para>Gets the name of the category for the property or event
/// that this attribute is bound to.</para>
/// </summary>
public string Category
{
get
{
if (!_localized)
{
_localized = true;
string localizedValue = GetLocalizedString(_categoryValue);
if (localizedValue != null)
{
_categoryValue = localizedValue;
}
}
return _categoryValue;
}
}
/// <summary>
/// </summary>
/// <summary>
/// </summary>
/// <internalonly/>
/// <internalonly/>
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
CategoryAttribute other = obj as CategoryAttribute;
return other != null && Category.Equals(other.Category);
}
/// <summary>
/// <para>[To be supplied.]</para>
/// </summary>
public override int GetHashCode()
{
return Category.GetHashCode();
}
/// <summary>
/// <para>Looks up the localized name of a given category.</para>
/// </summary>
protected virtual string GetLocalizedString(string value)
{
return SR.GetResourceString("PropertyCategory" + value, null);
}
public override bool IsDefaultAttribute()
{
return Category.Equals(CategoryAttribute.Default.Category);
}
}
}
| |
// 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.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Security;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace HttpStress
{
public class StressClient : IDisposable
{
private const string UNENCRYPTED_HTTP2_ENV_VAR = "DOTNET_SYSTEM_NET_HTTP_SOCKETSHTTPHANDLER_HTTP2UNENCRYPTEDSUPPORT";
private readonly (string name, Func<RequestContext, Task> operation)[] _clientOperations;
private readonly Uri _baseAddress;
private readonly Configuration _config;
private readonly StressResultAggregator _aggregator;
private readonly Stopwatch _stopwatch = new Stopwatch();
private readonly CancellationTokenSource _cts = new CancellationTokenSource();
private Task? _clientTask;
public long TotalErrorCount => _aggregator.TotalErrorCount;
public StressClient((string name, Func<RequestContext, Task> operation)[] clientOperations, Configuration configuration)
{
_clientOperations = clientOperations;
_config = configuration;
_baseAddress = new Uri(configuration.ServerUri);
_aggregator = new StressResultAggregator(clientOperations);
}
public void Start()
{
lock (_cts)
{
if (_cts.IsCancellationRequested)
{
throw new ObjectDisposedException(nameof(StressClient));
}
if (_clientTask != null)
{
throw new InvalidOperationException("Stress client already running");
}
_stopwatch.Start();
_clientTask = StartCore();
}
}
public void Stop()
{
_cts.Cancel();
_clientTask?.Wait();
_stopwatch.Stop();
_cts.Dispose();
}
public void PrintFinalReport()
{
lock(Console.Out)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("HttpStress Run Final Report");
Console.WriteLine();
_aggregator.PrintCurrentResults(_stopwatch.Elapsed);
_aggregator.PrintLatencies();
_aggregator.PrintFailureTypes();
}
}
public void Dispose() => Stop();
private async Task StartCore()
{
if (_baseAddress.Scheme == "http")
{
Environment.SetEnvironmentVariable(UNENCRYPTED_HTTP2_ENV_VAR, "1");
}
HttpMessageHandler CreateHttpHandler()
{
if (_config.UseWinHttpHandler)
{
return new System.Net.Http.WinHttpHandler()
{
ServerCertificateValidationCallback = delegate { return true; }
};
}
else
{
return new SocketsHttpHandler()
{
PooledConnectionLifetime = _config.ConnectionLifetime.GetValueOrDefault(Timeout.InfiniteTimeSpan),
SslOptions = new SslClientAuthenticationOptions
{
RemoteCertificateValidationCallback = delegate { return true; }
}
};
}
}
HttpClient CreateHttpClient() =>
new HttpClient(CreateHttpHandler())
{
BaseAddress = _baseAddress,
Timeout = _config.DefaultTimeout,
DefaultRequestVersion = _config.HttpVersion,
};
using HttpClient client = CreateHttpClient();
// Before starting the full-blown test, make sure can communicate with the server
// Needed for scenaria where we're deploying server & client in separate containers, simultaneously.
await SendTestRequestToServer(maxRetries: 10);
// Spin up a thread dedicated to outputting stats for each defined interval
new Thread(() =>
{
while (!_cts.IsCancellationRequested)
{
Thread.Sleep(_config.DisplayInterval);
lock (Console.Out) { _aggregator.PrintCurrentResults(_stopwatch.Elapsed); }
}
})
{ IsBackground = true }.Start();
// Start N workers, each of which sits in a loop making requests.
Task[] tasks = Enumerable.Range(0, _config.ConcurrentRequests).Select(RunWorker).ToArray();
await Task.WhenAll(tasks);
async Task RunWorker(int taskNum)
{
// create random instance specific to the current worker
var random = new Random(Combine(taskNum, _config.RandomSeed));
var stopwatch = new Stopwatch();
for (long i = taskNum; ; i++)
{
if (_cts.IsCancellationRequested)
break;
int opIndex = (int)(i % _clientOperations.Length);
(string operation, Func<RequestContext, Task> func) = _clientOperations[opIndex];
var requestContext = new RequestContext(_config, client, random, _cts.Token, taskNum);
stopwatch.Restart();
try
{
await func(requestContext);
_aggregator.RecordSuccess(opIndex, stopwatch.Elapsed);
}
catch (OperationCanceledException) when (requestContext.IsCancellationRequested || _cts.IsCancellationRequested)
{
_aggregator.RecordCancellation(opIndex, stopwatch.Elapsed);
}
catch (Exception e)
{
_aggregator.RecordFailure(e, opIndex, stopwatch.Elapsed, taskNum: taskNum, iteration: i);
}
}
// deterministic hashing copied from System.Runtime.Hashing
int Combine(int h1, int h2)
{
uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
return ((int)rol5 + h1) ^ h2;
}
}
async Task SendTestRequestToServer(int maxRetries)
{
using HttpClient client = CreateHttpClient();
for (int remainingRetries = maxRetries; ; remainingRetries--)
{
try
{
await client.GetAsync("/");
break;
}
catch (HttpRequestException) when (remainingRetries > 0)
{
Console.WriteLine($"Stress client could not connect to host {_baseAddress}, {remainingRetries} attempts remaining");
await Task.Delay(millisecondsDelay: 1000);
}
}
}
}
/// <summary>Aggregate view of a particular stress failure type</summary>
private sealed class StressFailureType
{
// Representative error text of stress failure
public string ErrorText { get; }
// Operation id => failure timestamps
public Dictionary<int, List<DateTime>> Failures { get; }
public StressFailureType(string errorText)
{
ErrorText = errorText;
Failures = new Dictionary<int, List<DateTime>>();
}
public int FailureCount => Failures.Values.Select(x => x.Count).Sum();
}
private sealed class StressResultAggregator
{
private readonly string[] _operationNames;
private long _totalRequests = 0;
private readonly long[] _successes, _cancellations, _failures;
private long _reuseAddressFailures = 0;
private long _lastTotal = -1;
private readonly ConcurrentDictionary<(Type exception, string message, string callSite)[], StressFailureType> _failureTypes;
private readonly ConcurrentBag<double> _latencies = new ConcurrentBag<double>();
public long TotalErrorCount => _failures.Sum();
public StressResultAggregator((string name, Func<RequestContext, Task>)[] operations)
{
_operationNames = operations.Select(x => x.name).ToArray();
_successes = new long[operations.Length];
_cancellations = new long[operations.Length];
_failures = new long[operations.Length];
_failureTypes = new ConcurrentDictionary<(Type, string, string)[], StressFailureType>(new StructuralEqualityComparer<(Type, string, string)[]>());
}
public void RecordSuccess(int operationIndex, TimeSpan elapsed)
{
Interlocked.Increment(ref _totalRequests);
Interlocked.Increment(ref _successes[operationIndex]);
_latencies.Add(elapsed.TotalMilliseconds);
}
public void RecordCancellation(int operationIndex, TimeSpan elapsed)
{
Interlocked.Increment(ref _totalRequests);
Interlocked.Increment(ref _cancellations[operationIndex]);
_latencies.Add(elapsed.TotalMilliseconds);
}
public void RecordFailure(Exception exn, int operationIndex, TimeSpan elapsed, int taskNum, long iteration)
{
DateTime timestamp = DateTime.Now;
Interlocked.Increment(ref _totalRequests);
Interlocked.Increment(ref _failures[operationIndex]);
_latencies.Add(elapsed.TotalMilliseconds);
RecordFailureType();
PrintToConsole();
// record exception according to failure type classification
void RecordFailureType()
{
(Type, string, string)[] key = ClassifyFailure(exn);
StressFailureType failureType = _failureTypes.GetOrAdd(key, _ => new StressFailureType(exn.ToString()));
lock (failureType)
{
if(!failureType.Failures.TryGetValue(operationIndex, out List<DateTime>? timestamps))
{
timestamps = new List<DateTime>();
failureType.Failures.Add(operationIndex, timestamps);
}
timestamps.Add(timestamp);
}
(Type exception, string message, string callSite)[] ClassifyFailure(Exception exn)
{
var acc = new List<(Type exception, string message, string callSite)>();
for (Exception? e = exn; e != null; )
{
acc.Add((e.GetType(), e.Message ?? "", new StackTrace(e, true).GetFrame(0)?.ToString() ?? ""));
e = e.InnerException;
}
return acc.ToArray();
}
}
void PrintToConsole()
{
if (exn is HttpRequestException hre && hre.InnerException is SocketException se && se.SocketErrorCode == SocketError.AddressAlreadyInUse)
{
Interlocked.Increment(ref _reuseAddressFailures);
}
else
{
lock (Console.Out)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"Error from iteration {iteration} ({_operationNames[operationIndex]}) in task {taskNum} with {_successes.Sum()} successes / {_failures.Sum()} fails:");
Console.ResetColor();
Console.WriteLine(exn);
Console.WriteLine();
}
}
}
}
public void PrintCurrentResults(TimeSpan runtime)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("[" + DateTime.Now + "]");
Console.ResetColor();
if (_lastTotal == _totalRequests)
{
Console.ForegroundColor = ConsoleColor.Red;
}
_lastTotal = _totalRequests;
Console.Write(" Total: " + _totalRequests.ToString("N0"));
Console.ResetColor();
Console.WriteLine($" Runtime: " + runtime.ToString(@"hh\:mm\:ss"));
if (_reuseAddressFailures > 0)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("~~ Reuse address failures: " + _reuseAddressFailures.ToString("N0") + "~~");
Console.ResetColor();
}
for (int i = 0; i < _operationNames.Length; i++)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write($"\t{_operationNames[i].PadRight(30)}");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("Success: ");
Console.Write(_successes[i].ToString("N0"));
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("\tCanceled: ");
Console.Write(_cancellations[i].ToString("N0"));
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.Write("\tFail: ");
Console.ResetColor();
Console.WriteLine(_failures[i].ToString("N0"));
}
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("\t TOTAL".PadRight(31));
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("Success: ");
Console.Write(_successes.Sum().ToString("N0"));
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("\tCanceled: ");
Console.Write(_cancellations.Sum().ToString("N0"));
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.Write("\tFail: ");
Console.ResetColor();
Console.WriteLine(_failures.Sum().ToString("N0"));
Console.WriteLine();
}
public void PrintLatencies()
{
var latencies = _latencies.ToArray();
Array.Sort(latencies);
Console.WriteLine($"Latency(ms) : n={latencies.Length}, p50={Pc(0.5)}, p75={Pc(0.75)}, p99={Pc(0.99)}, p999={Pc(0.999)}, max={Pc(1)}");
Console.WriteLine();
double Pc(double percentile)
{
int N = latencies.Length;
double n = (N - 1) * percentile + 1;
if (n == 1) return Rnd(latencies[0]);
else if (n == N) return Rnd(latencies[N - 1]);
else
{
int k = (int)n;
double d = n - k;
return Rnd(latencies[k - 1] + d * (latencies[k] - latencies[k - 1]));
}
double Rnd(double value) => Math.Round(value, 2);
}
}
public void PrintFailureTypes()
{
if (_failureTypes.Count == 0)
return;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"There were a total of {_failures.Sum()} failures classified into {_failureTypes.Count} different types:");
Console.WriteLine();
Console.ResetColor();
int i = 0;
foreach (StressFailureType failure in _failureTypes.Values.OrderByDescending(x => x.FailureCount))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"Failure Type {++i}/{_failureTypes.Count}:");
Console.ResetColor();
Console.WriteLine(failure.ErrorText);
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Yellow;
foreach (KeyValuePair<int, List<DateTime>> operation in failure.Failures)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write($"\t{_operationNames[operation.Key].PadRight(30)}");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Fail: ");
Console.ResetColor();
Console.Write(operation.Value.Count);
Console.WriteLine($"\tTimestamps: {string.Join(", ", operation.Value.Select(x => x.ToString("HH:mm:ss")))}");
}
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("\t TOTAL".PadRight(31));
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.Write($"Fail: ");
Console.ResetColor();
Console.WriteLine(failure.FailureCount);
Console.WriteLine();
}
}
}
private class StructuralEqualityComparer<T> : IEqualityComparer<T> where T : IStructuralEquatable
{
public bool Equals(T left, T right) => left.Equals(right, StructuralComparisons.StructuralEqualityComparer);
public int GetHashCode(T value) => value.GetHashCode(StructuralComparisons.StructuralEqualityComparer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using AldursLab.WurmAssistantWebService.Areas.HelpPage.ModelDescriptions;
using AldursLab.WurmAssistantWebService.Areas.HelpPage.Models;
using AldursLab.WurmAssistantWebService.Areas.HelpPage.SampleGeneration;
namespace AldursLab.WurmAssistantWebService.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
$PostFXManager::defaultPreset = "core/scripts/client/postFx/default.postfxpreset.cs";
function PostFXManager::settingsSetEnabled(%this, %bEnablePostFX)
{
$PostFXManager::PostFX::Enabled = %bEnablePostFX;
//if to enable the postFX, apply the ones that are enabled
if ( %bEnablePostFX )
{
//SSAO, HDR, LightRays, DOF
if ( $PostFXManager::PostFX::EnableSSAO )
SSAOPostFx.enable();
else
SSAOPostFx.disable();
if ( $PostFXManager::PostFX::EnableHDR )
HDRPostFX.enable();
else
HDRPostFX.disable();
if ( $PostFXManager::PostFX::EnableLightRays )
LightRayPostFX.enable();
else
LightRayPostFX.disable();
if ( $PostFXManager::PostFX::EnableDOF )
DOFPostEffect.enable();
else
DOFPostEffect.disable();
if ( $PostFXManager::PostFX::EnableVignette )
VignettePostEffect.enable();
else
VignettePostEffect.disable();
postVerbose("% - PostFX Manager - PostFX enabled");
}
else
{
//Disable all postFX
SSAOPostFx.disable();
HDRPostFX.disable();
LightRayPostFX.disable();
DOFPostEffect.disable();
VignettePostEffect.disable();
postVerbose("% - PostFX Manager - PostFX disabled");
}
VolFogGlowPostFx.disable();
}
function PostFXManager::settingsEffectSetEnabled(%this, %sName, %bEnable)
{
%postEffect = 0;
//Determine the postFX to enable, and apply the boolean
if(%sName $= "SSAO")
{
%postEffect = SSAOPostFx;
$PostFXManager::PostFX::EnableSSAO = %bEnable;
//$pref::PostFX::SSAO::Enabled = %bEnable;
}
else if(%sName $= "HDR")
{
%postEffect = HDRPostFX;
$PostFXManager::PostFX::EnableHDR = %bEnable;
//$pref::PostFX::HDR::Enabled = %bEnable;
}
else if(%sName $= "LightRays")
{
%postEffect = LightRayPostFX;
$PostFXManager::PostFX::EnableLightRays = %bEnable;
//$pref::PostFX::LightRays::Enabled = %bEnable;
}
else if(%sName $= "DOF")
{
%postEffect = DOFPostEffect;
$PostFXManager::PostFX::EnableDOF = %bEnable;
//$pref::PostFX::DOF::Enabled = %bEnable;
}
else if(%sName $= "Vignette")
{
%postEffect = VignettePostEffect;
$PostFXManager::PostFX::EnableVignette = %bEnable;
//$pref::PostFX::Vignette::Enabled = %bEnable;
}
// Apply the change
if ( %bEnable == true )
{
%postEffect.enable();
postVerbose("% - PostFX Manager - " @ %sName @ " enabled");
}
else
{
%postEffect.disable();
postVerbose("% - PostFX Manager - " @ %sName @ " disabled");
}
}
function PostFXManager::settingsRefreshSSAO(%this)
{
//Apply the enabled flag
ppOptionsEnableSSAO.setValue($PostFXManager::PostFX::EnableSSAO);
//Add the items we need to display
ppOptionsSSAOQuality.clear();
ppOptionsSSAOQuality.add("Low", 0);
ppOptionsSSAOQuality.add("Medium", 1);
ppOptionsSSAOQuality.add("High", 2);
//Set the selected, after adding the items!
ppOptionsSSAOQuality.setSelected($SSAOPostFx::quality);
//SSAO - Set the values of the sliders, General Tab
ppOptionsSSAOOverallStrength.setValue($SSAOPostFx::overallStrength);
ppOptionsSSAOBlurDepth.setValue($SSAOPostFx::blurDepthTol);
ppOptionsSSAOBlurNormal.setValue($SSAOPostFx::blurNormalTol);
//SSAO - Set the values for the near tab
ppOptionsSSAONearDepthMax.setValue($SSAOPostFx::sDepthMax);
ppOptionsSSAONearDepthMin.setValue($SSAOPostFx::sDepthMin);
ppOptionsSSAONearRadius.setValue($SSAOPostFx::sRadius);
ppOptionsSSAONearStrength.setValue($SSAOPostFx::sStrength);
ppOptionsSSAONearToleranceNormal.setValue($SSAOPostFx::sNormalTol);
ppOptionsSSAONearTolerancePower.setValue($SSAOPostFx::sNormalPow);
//SSAO - Set the values for the far tab
ppOptionsSSAOFarDepthMax.setValue($SSAOPostFx::lDepthMax);
ppOptionsSSAOFarDepthMin.setValue($SSAOPostFx::lDepthMin);
ppOptionsSSAOFarRadius.setValue($SSAOPostFx::lRadius);
ppOptionsSSAOFarStrength.setValue($SSAOPostFx::lStrength);
ppOptionsSSAOFarToleranceNormal.setValue($SSAOPostFx::lNormalTol);
ppOptionsSSAOFarTolerancePower.setValue($SSAOPostFx::lNormalPow);
}
function PostFXManager::settingsRefreshHDR(%this)
{
//Apply the enabled flag
ppOptionsEnableHDR.setValue($PostFXManager::PostFX::EnableHDR);
ppOptionsHDRBloom.setValue($HDRPostFX::enableBloom);
ppOptionsHDRBloomBlurBrightPassThreshold.setValue($HDRPostFX::brightPassThreshold);
ppOptionsHDRBloomBlurMean.setValue($HDRPostFX::gaussMean);
ppOptionsHDRBloomBlurMultiplier.setValue($HDRPostFX::gaussMultiplier);
ppOptionsHDRBloomBlurStdDev.setValue($HDRPostFX::gaussStdDev);
ppOptionsHDRBrightnessAdaptRate.setValue($HDRPostFX::adaptRate);
ppOptionsHDREffectsBlueShift.setValue($HDRPostFX::enableBlueShift);
ppOptionsHDREffectsBlueShiftColor.BaseColor = $HDRPostFX::blueShiftColor;
ppOptionsHDREffectsBlueShiftColor.PickColor = $HDRPostFX::blueShiftColor;
ppOptionsHDRKeyValue.setValue($HDRPostFX::keyValue);
ppOptionsHDRMinLuminance.setValue($HDRPostFX::minLuminace);
ppOptionsHDRToneMapping.setValue($HDRPostFX::enableToneMapping);
ppOptionsHDRToneMappingAmount.setValue($HDRPostFX::enableToneMapping);
ppOptionsHDRWhiteCutoff.setValue($HDRPostFX::whiteCutoff);
%this-->ColorCorrectionFileName.Text = $HDRPostFX::colorCorrectionRamp;
}
function PostFXManager::settingsRefreshLightrays(%this)
{
//Apply the enabled flag
ppOptionsEnableLightRays.setValue($PostFXManager::PostFX::EnableLightRays);
ppOptionsLightRaysBrightScalar.setValue($LightRayPostFX::brightScalar);
ppOptionsLightRaysSampleScalar.setValue($LightRayPostFX::numSamples);
ppOptionsLightRaysDensityScalar.setValue($LightRayPostFX::density);
ppOptionsLightRaysWeightScalar.setValue($LightRayPostFX::weight);
ppOptionsLightRaysDecayScalar.setValue($LightRayPostFX::decay);
}
function PostFXManager::settingsRefreshDOF(%this)
{
//Apply the enabled flag
ppOptionsEnableDOF.setValue($PostFXManager::PostFX::EnableDOF);
//ppOptionsDOFEnableDOF.setValue($PostFXManager::PostFX::EnableDOF);
ppOptionsDOFEnableAutoFocus.setValue($DOFPostFx::EnableAutoFocus);
ppOptionsDOFFarBlurMinSlider.setValue($DOFPostFx::BlurMin);
ppOptionsDOFFarBlurMaxSlider.setValue($DOFPostFx::BlurMax);
ppOptionsDOFFocusRangeMinSlider.setValue($DOFPostFx::FocusRangeMin);
ppOptionsDOFFocusRangeMaxSlider.setValue($DOFPostFx::FocusRangeMax);
ppOptionsDOFBlurCurveNearSlider.setValue($DOFPostFx::BlurCurveNear);
ppOptionsDOFBlurCurveFarSlider.setValue($DOFPostFx::BlurCurveFar);
}
function PostFXManager::settingsRefreshVignette(%this)
{
//Apply the enabled flag
ppOptionsEnableVignette.setValue($PostFXManager::PostFX::EnableVignette);
}
function PostFXManager::settingsRefreshAll(%this)
{
$PostFXManager::PostFX::Enabled = $pref::enablePostEffects;
$PostFXManager::PostFX::EnableSSAO = SSAOPostFx.isEnabled();
$PostFXManager::PostFX::EnableHDR = HDRPostFX.isEnabled();
$PostFXManager::PostFX::EnableLightRays = LightRayPostFX.isEnabled();
$PostFXManager::PostFX::EnableDOF = DOFPostEffect.isEnabled();
$PostFXManager::PostFX::EnableVignette = VignettePostEffect.isEnabled();
//For all the postFX here, apply the active settings in the system
//to the gui controls.
%this.settingsRefreshSSAO();
%this.settingsRefreshHDR();
%this.settingsRefreshLightrays();
%this.settingsRefreshDOF();
%this.settingsRefreshVignette();
ppOptionsEnable.setValue($PostFXManager::PostFX::Enabled);
postVerbose("% - PostFX Manager - GUI values updated.");
}
function PostFXManager::settingsApplyFromPreset(%this)
{
postVerbose("% - PostFX Manager - Applying from preset");
//SSAO Settings
$SSAOPostFx::blurDepthTol = $PostFXManager::Settings::SSAO::blurDepthTol;
$SSAOPostFx::blurNormalTol = $PostFXManager::Settings::SSAO::blurNormalTol;
$SSAOPostFx::lDepthMax = $PostFXManager::Settings::SSAO::lDepthMax;
$SSAOPostFx::lDepthMin = $PostFXManager::Settings::SSAO::lDepthMin;
$SSAOPostFx::lDepthPow = $PostFXManager::Settings::SSAO::lDepthPow;
$SSAOPostFx::lNormalPow = $PostFXManager::Settings::SSAO::lNormalPow;
$SSAOPostFx::lNormalTol = $PostFXManager::Settings::SSAO::lNormalTol;
$SSAOPostFx::lRadius = $PostFXManager::Settings::SSAO::lRadius;
$SSAOPostFx::lStrength = $PostFXManager::Settings::SSAO::lStrength;
$SSAOPostFx::overallStrength = $PostFXManager::Settings::SSAO::overallStrength;
$SSAOPostFx::quality = $PostFXManager::Settings::SSAO::quality;
$SSAOPostFx::sDepthMax = $PostFXManager::Settings::SSAO::sDepthMax;
$SSAOPostFx::sDepthMin = $PostFXManager::Settings::SSAO::sDepthMin;
$SSAOPostFx::sDepthPow = $PostFXManager::Settings::SSAO::sDepthPow;
$SSAOPostFx::sNormalPow = $PostFXManager::Settings::SSAO::sNormalPow;
$SSAOPostFx::sNormalTol = $PostFXManager::Settings::SSAO::sNormalTol;
$SSAOPostFx::sRadius = $PostFXManager::Settings::SSAO::sRadius;
$SSAOPostFx::sStrength = $PostFXManager::Settings::SSAO::sStrength;
//HDR settings
$HDRPostFX::adaptRate = $PostFXManager::Settings::HDR::adaptRate;
$HDRPostFX::blueShiftColor = $PostFXManager::Settings::HDR::blueShiftColor;
$HDRPostFX::brightPassThreshold = $PostFXManager::Settings::HDR::brightPassThreshold;
$HDRPostFX::enableBloom = $PostFXManager::Settings::HDR::enableBloom;
$HDRPostFX::enableBlueShift = $PostFXManager::Settings::HDR::enableBlueShift;
$HDRPostFX::enableToneMapping = $PostFXManager::Settings::HDR::enableToneMapping;
$HDRPostFX::gaussMean = $PostFXManager::Settings::HDR::gaussMean;
$HDRPostFX::gaussMultiplier = $PostFXManager::Settings::HDR::gaussMultiplier;
$HDRPostFX::gaussStdDev = $PostFXManager::Settings::HDR::gaussStdDev;
$HDRPostFX::keyValue = $PostFXManager::Settings::HDR::keyValue;
$HDRPostFX::minLuminace = $PostFXManager::Settings::HDR::minLuminace;
$HDRPostFX::whiteCutoff = $PostFXManager::Settings::HDR::whiteCutoff;
$HDRPostFX::colorCorrectionRamp = $PostFXManager::Settings::ColorCorrectionRamp;
//Light rays settings
$LightRayPostFX::brightScalar = $PostFXManager::Settings::LightRays::brightScalar;
$LightRayPostFX::numSamples = $PostFXManager::Settings::LightRays::numSamples;
$LightRayPostFX::density = $PostFXManager::Settings::LightRays::density;
$LightRayPostFX::weight = $PostFXManager::Settings::LightRays::weight;
$LightRayPostFX::decay = $PostFXManager::Settings::LightRays::decay;
//DOF settings
$DOFPostFx::EnableAutoFocus = $PostFXManager::Settings::DOF::EnableAutoFocus;
$DOFPostFx::BlurMin = $PostFXManager::Settings::DOF::BlurMin;
$DOFPostFx::BlurMax = $PostFXManager::Settings::DOF::BlurMax;
$DOFPostFx::FocusRangeMin = $PostFXManager::Settings::DOF::FocusRangeMin;
$DOFPostFx::FocusRangeMax = $PostFXManager::Settings::DOF::FocusRangeMax;
$DOFPostFx::BlurCurveNear = $PostFXManager::Settings::DOF::BlurCurveNear;
$DOFPostFx::BlurCurveFar = $PostFXManager::Settings::DOF::BlurCurveFar;
//Vignette settings
$VignettePostEffect::VMax = $PostFXManager::Settings::Vignette::VMax;
if ( $PostFXManager::forceEnableFromPresets )
{
$PostFXManager::PostFX::Enabled = $PostFXManager::Settings::EnablePostFX;
$PostFXManager::PostFX::EnableDOF = $PostFXManager::Settings::EnableDOF;
$PostFXManager::PostFX::EnableVignette = $PostFXManager::Settings::EnableVignette;
$PostFXManager::PostFX::EnableLightRays = $PostFXManager::Settings::EnableLightRays;
$PostFXManager::PostFX::EnableHDR = $PostFXManager::Settings::EnableHDR;
$PostFXManager::PostFX::EnableSSAO = $PostFXManager::Settings::EnabledSSAO;
%this.settingsSetEnabled( true );
}
//make sure we apply the correct settings to the DOF
ppOptionsUpdateDOFSettings();
// Update the actual GUI controls if its awake ( otherwise it will when opened ).
if ( PostFXManager.isAwake() )
%this.settingsRefreshAll();
}
function PostFXManager::settingsApplySSAO(%this)
{
$PostFXManager::Settings::SSAO::blurDepthTol = $SSAOPostFx::blurDepthTol;
$PostFXManager::Settings::SSAO::blurNormalTol = $SSAOPostFx::blurNormalTol;
$PostFXManager::Settings::SSAO::lDepthMax = $SSAOPostFx::lDepthMax;
$PostFXManager::Settings::SSAO::lDepthMin = $SSAOPostFx::lDepthMin;
$PostFXManager::Settings::SSAO::lDepthPow = $SSAOPostFx::lDepthPow;
$PostFXManager::Settings::SSAO::lNormalPow = $SSAOPostFx::lNormalPow;
$PostFXManager::Settings::SSAO::lNormalTol = $SSAOPostFx::lNormalTol;
$PostFXManager::Settings::SSAO::lRadius = $SSAOPostFx::lRadius;
$PostFXManager::Settings::SSAO::lStrength = $SSAOPostFx::lStrength;
$PostFXManager::Settings::SSAO::overallStrength = $SSAOPostFx::overallStrength;
$PostFXManager::Settings::SSAO::quality = $SSAOPostFx::quality;
$PostFXManager::Settings::SSAO::sDepthMax = $SSAOPostFx::sDepthMax;
$PostFXManager::Settings::SSAO::sDepthMin = $SSAOPostFx::sDepthMin;
$PostFXManager::Settings::SSAO::sDepthPow = $SSAOPostFx::sDepthPow;
$PostFXManager::Settings::SSAO::sNormalPow = $SSAOPostFx::sNormalPow;
$PostFXManager::Settings::SSAO::sNormalTol = $SSAOPostFx::sNormalTol;
$PostFXManager::Settings::SSAO::sRadius = $SSAOPostFx::sRadius;
$PostFXManager::Settings::SSAO::sStrength = $SSAOPostFx::sStrength;
postVerbose("% - PostFX Manager - Settings Saved - SSAO");
}
function PostFXManager::settingsApplyHDR(%this)
{
$PostFXManager::Settings::HDR::adaptRate = $HDRPostFX::adaptRate;
$PostFXManager::Settings::HDR::blueShiftColor = $HDRPostFX::blueShiftColor;
$PostFXManager::Settings::HDR::brightPassThreshold = $HDRPostFX::brightPassThreshold;
$PostFXManager::Settings::HDR::enableBloom = $HDRPostFX::enableBloom;
$PostFXManager::Settings::HDR::enableBlueShift = $HDRPostFX::enableBlueShift;
$PostFXManager::Settings::HDR::enableToneMapping = $HDRPostFX::enableToneMapping;
$PostFXManager::Settings::HDR::gaussMean = $HDRPostFX::gaussMean;
$PostFXManager::Settings::HDR::gaussMultiplier = $HDRPostFX::gaussMultiplier;
$PostFXManager::Settings::HDR::gaussStdDev = $HDRPostFX::gaussStdDev;
$PostFXManager::Settings::HDR::keyValue = $HDRPostFX::keyValue;
$PostFXManager::Settings::HDR::minLuminace = $HDRPostFX::minLuminace;
$PostFXManager::Settings::HDR::whiteCutoff = $HDRPostFX::whiteCutoff;
$PostFXManager::Settings::ColorCorrectionRamp = $HDRPostFX::colorCorrectionRamp;
postVerbose("% - PostFX Manager - Settings Saved - HDR");
}
function PostFXManager::settingsApplyLightRays(%this)
{
$PostFXManager::Settings::LightRays::brightScalar = $LightRayPostFX::brightScalar;
$PostFXManager::Settings::LightRays::numSamples = $LightRayPostFX::numSamples;
$PostFXManager::Settings::LightRays::density = $LightRayPostFX::density;
$PostFXManager::Settings::LightRays::weight = $LightRayPostFX::weight;
$PostFXManager::Settings::LightRays::decay = $LightRayPostFX::decay;
postVerbose("% - PostFX Manager - Settings Saved - Light Rays");
}
function PostFXManager::settingsApplyDOF(%this)
{
$PostFXManager::Settings::DOF::EnableAutoFocus = $DOFPostFx::EnableAutoFocus;
$PostFXManager::Settings::DOF::BlurMin = $DOFPostFx::BlurMin;
$PostFXManager::Settings::DOF::BlurMax = $DOFPostFx::BlurMax;
$PostFXManager::Settings::DOF::FocusRangeMin = $DOFPostFx::FocusRangeMin;
$PostFXManager::Settings::DOF::FocusRangeMax = $DOFPostFx::FocusRangeMax;
$PostFXManager::Settings::DOF::BlurCurveNear = $DOFPostFx::BlurCurveNear;
$PostFXManager::Settings::DOF::BlurCurveFar = $DOFPostFx::BlurCurveFar;
postVerbose("% - PostFX Manager - Settings Saved - DOF");
}
function PostFXManager::settingsApplyVignette(%this)
{
$PostFXManager::Settings::Vignette::VMax = $VignettePostEffect::VMax;
postVerbose("% - PostFX Manager - Settings Saved - Vignette");
}
function PostFXManager::settingsApplyAll(%this, %sFrom)
{
// Apply settings which control if effects are on/off altogether.
$PostFXManager::Settings::EnablePostFX = $PostFXManager::PostFX::Enabled;
$PostFXManager::Settings::EnableDOF = $PostFXManager::PostFX::EnableDOF;
$PostFXManager::Settings::EnableVignette = $PostFXManager::PostFX::EnableVignette;
$PostFXManager::Settings::EnableLightRays = $PostFXManager::PostFX::EnableLightRays;
$PostFXManager::Settings::EnableHDR = $PostFXManager::PostFX::EnableHDR;
$PostFXManager::Settings::EnabledSSAO = $PostFXManager::PostFX::EnableSSAO;
// Apply settings should save the values in the system to the
// the preset structure ($PostFXManager::Settings::*)
// SSAO Settings
%this.settingsApplySSAO();
// HDR settings
%this.settingsApplyHDR();
// Light rays settings
%this.settingsApplyLightRays();
// DOF
%this.settingsApplyDOF();
// Vignette
%this.settingsApplyVignette();
postVerbose("% - PostFX Manager - All Settings applied to $PostFXManager::Settings");
}
function PostFXManager::settingsApplyDefaultPreset(%this)
{
PostFXManager::loadPresetHandler($PostFXManager::defaultPreset);
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
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.Runtime.InteropServices;
using System.Text.RegularExpressions;
using UnityEngine;
using System.Collections.Generic;
#if UNITY_2017_2_OR_NEWER
using InputTracking = UnityEngine.XR.InputTracking;
using Node = UnityEngine.XR.XRNode;
using NodeState = UnityEngine.XR.XRNodeState;
using Settings = UnityEngine.XR.XRSettings;
#elif UNITY_2017_1_OR_NEWER
using InputTracking = UnityEngine.VR.InputTracking;
using Node = UnityEngine.VR.VRNode;
using NodeState = UnityEngine.VR.VRNodeState;
using Settings = UnityEngine.VR.VRSettings;
#else
using Node = UnityEngine.VR.VRNode;
using Settings = UnityEngine.VR.VRSettings;
#endif
/// <summary>
/// Manages an Oculus Rift head-mounted display (HMD).
/// </summary>
public class OVRDisplay
{
/// <summary>
/// Contains full fov information per eye
/// Under Symmetric Fov mode, UpFov == DownFov and LeftFov == RightFov.
/// </summary>
public struct EyeFov
{
public float UpFov;
public float DownFov;
public float LeftFov;
public float RightFov;
}
/// <summary>
/// Specifies the size and field-of-view for one eye texture.
/// </summary>
public struct EyeRenderDesc
{
/// <summary>
/// The horizontal and vertical size of the texture.
/// </summary>
public Vector2 resolution;
/// <summary>
/// The angle of the horizontal and vertical field of view in degrees.
/// For Symmetric FOV interface compatibility
/// Note this includes the fov angle from both sides
/// </summary>
public Vector2 fov;
/// <summary>
/// The full information of field of view in degrees.
/// When Asymmetric FOV isn't enabled, this returns the maximum fov angle
/// </summary>
public EyeFov fullFov;
}
/// <summary>
/// Contains latency measurements for a single frame of rendering.
/// </summary>
public struct LatencyData
{
/// <summary>
/// The time it took to render both eyes in seconds.
/// </summary>
public float render;
/// <summary>
/// The time it took to perform TimeWarp in seconds.
/// </summary>
public float timeWarp;
/// <summary>
/// The time between the end of TimeWarp and scan-out in seconds.
/// </summary>
public float postPresent;
public float renderError;
public float timeWarpError;
}
private bool needsConfigureTexture;
private EyeRenderDesc[] eyeDescs = new EyeRenderDesc[2];
private bool recenterRequested = false;
private int recenterRequestedFrameCount = int.MaxValue;
/// <summary>
/// Creates an instance of OVRDisplay. Called by OVRManager.
/// </summary>
public OVRDisplay()
{
UpdateTextures();
}
/// <summary>
/// Updates the internal state of the OVRDisplay. Called by OVRManager.
/// </summary>
public void Update()
{
UpdateTextures();
if (recenterRequested && Time.frameCount > recenterRequestedFrameCount)
{
if (RecenteredPose != null)
{
RecenteredPose();
}
recenterRequested = false;
recenterRequestedFrameCount = int.MaxValue;
}
}
/// <summary>
/// Occurs when the head pose is reset.
/// </summary>
public event System.Action RecenteredPose;
/// <summary>
/// Recenters the head pose.
/// </summary>
public void RecenterPose()
{
#if UNITY_2017_2_OR_NEWER
UnityEngine.XR.InputTracking.Recenter();
#else
UnityEngine.VR.InputTracking.Recenter();
#endif
// The current poses are cached for the current frame and won't be updated immediately
// after UnityEngine.VR.InputTracking.Recenter(). So we need to wait until next frame
// to trigger the RecenteredPose delegate. The application could expect the correct pose
// when the RecenteredPose delegate get called.
recenterRequested = true;
recenterRequestedFrameCount = Time.frameCount;
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
OVRMixedReality.RecenterPose();
#endif
}
/// <summary>
/// Gets the current linear acceleration of the head.
/// </summary>
public Vector3 acceleration
{
get {
if (!OVRManager.isHmdPresent)
return Vector3.zero;
return OVRNodeStateProperties.GetNodeStateProperty(Node.Head, NodeStatePropertyType.Acceleration, OVRPlugin.Node.Head, OVRPlugin.Step.Render);
}
}
/// <summary>
/// Gets the current angular acceleration of the head in radians per second per second about each axis.
/// </summary>
public Vector3 angularAcceleration
{
get
{
if (!OVRManager.isHmdPresent)
return Vector3.zero;
return OVRNodeStateProperties.GetNodeStateProperty(Node.Head, NodeStatePropertyType.AngularAcceleration, OVRPlugin.Node.Head, OVRPlugin.Step.Render);
}
}
/// <summary>
/// Gets the current linear velocity of the head in meters per second.
/// </summary>
public Vector3 velocity
{
get
{
if (!OVRManager.isHmdPresent)
return Vector3.zero;
return OVRNodeStateProperties.GetNodeStateProperty(Node.Head, NodeStatePropertyType.Velocity, OVRPlugin.Node.Head, OVRPlugin.Step.Render);
}
}
/// <summary>
/// Gets the current angular velocity of the head in radians per second about each axis.
/// </summary>
public Vector3 angularVelocity
{
get {
if (!OVRManager.isHmdPresent)
return Vector3.zero;
return OVRNodeStateProperties.GetNodeStateProperty(Node.Head, NodeStatePropertyType.AngularVelocity, OVRPlugin.Node.Head, OVRPlugin.Step.Render);
}
}
/// <summary>
/// Gets the resolution and field of view for the given eye.
/// </summary>
#if UNITY_2017_2_OR_NEWER
public EyeRenderDesc GetEyeRenderDesc(UnityEngine.XR.XRNode eye)
#else
public EyeRenderDesc GetEyeRenderDesc(UnityEngine.VR.VRNode eye)
#endif
{
return eyeDescs[(int)eye];
}
/// <summary>
/// Gets the current measured latency values.
/// </summary>
public LatencyData latency
{
get {
if (!OVRManager.isHmdPresent)
return new LatencyData();
string latency = OVRPlugin.latency;
var r = new Regex("Render: ([0-9]+[.][0-9]+)ms, TimeWarp: ([0-9]+[.][0-9]+)ms, PostPresent: ([0-9]+[.][0-9]+)ms", RegexOptions.None);
var ret = new LatencyData();
Match match = r.Match(latency);
if (match.Success)
{
ret.render = float.Parse(match.Groups[1].Value);
ret.timeWarp = float.Parse(match.Groups[2].Value);
ret.postPresent = float.Parse(match.Groups[3].Value);
}
return ret;
}
}
/// <summary>
/// Gets application's frame rate reported by oculus plugin
/// </summary>
public float appFramerate
{
get
{
if (!OVRManager.isHmdPresent)
return 0;
return OVRPlugin.GetAppFramerate();
}
}
/// <summary>
/// Gets the recommended MSAA level for optimal quality/performance the current device.
/// </summary>
public int recommendedMSAALevel
{
get
{
int result = OVRPlugin.recommendedMSAALevel;
if (result == 1)
result = 0;
return result;
}
}
/// <summary>
/// Gets the list of available display frequencies supported by this hardware.
/// </summary>
public float[] displayFrequenciesAvailable
{
get { return OVRPlugin.systemDisplayFrequenciesAvailable; }
}
/// <summary>
/// Gets and sets the current display frequency.
/// </summary>
public float displayFrequency
{
get
{
return OVRPlugin.systemDisplayFrequency;
}
set
{
OVRPlugin.systemDisplayFrequency = value;
}
}
private void UpdateTextures()
{
#if UNITY_2017_2_OR_NEWER
ConfigureEyeDesc(UnityEngine.XR.XRNode.LeftEye);
ConfigureEyeDesc(UnityEngine.XR.XRNode.RightEye);
#else
ConfigureEyeDesc(UnityEngine.VR.VRNode.LeftEye);
ConfigureEyeDesc(UnityEngine.VR.VRNode.RightEye);
#endif
}
#if UNITY_2017_2_OR_NEWER
private void ConfigureEyeDesc(UnityEngine.XR.XRNode eye)
#else
private void ConfigureEyeDesc(UnityEngine.VR.VRNode eye)
#endif
{
if (!OVRManager.isHmdPresent)
return;
int eyeTextureWidth = Settings.eyeTextureWidth;
int eyeTextureHeight = Settings.eyeTextureHeight;
eyeDescs[(int)eye] = new EyeRenderDesc();
eyeDescs[(int)eye].resolution = new Vector2(eyeTextureWidth, eyeTextureHeight);
OVRPlugin.Frustumf2 frust;
if (OVRPlugin.GetNodeFrustum2((OVRPlugin.Node)eye, out frust))
{
eyeDescs[(int)eye].fullFov.LeftFov = Mathf.Rad2Deg * Mathf.Atan(frust.Fov.LeftTan);
eyeDescs[(int)eye].fullFov.RightFov = Mathf.Rad2Deg * Mathf.Atan(frust.Fov.RightTan);
eyeDescs[(int)eye].fullFov.UpFov = Mathf.Rad2Deg * Mathf.Atan(frust.Fov.UpTan);
eyeDescs[(int)eye].fullFov.DownFov = Mathf.Rad2Deg * Mathf.Atan(frust.Fov.DownTan);
}
else
{
OVRPlugin.Frustumf frustOld = OVRPlugin.GetEyeFrustum((OVRPlugin.Eye)eye);
eyeDescs[(int)eye].fullFov.LeftFov = Mathf.Rad2Deg * frustOld.fovX * 0.5f;
eyeDescs[(int)eye].fullFov.RightFov = Mathf.Rad2Deg * frustOld.fovX * 0.5f;
eyeDescs[(int)eye].fullFov.UpFov = Mathf.Rad2Deg * frustOld.fovY * 0.5f;
eyeDescs[(int)eye].fullFov.DownFov = Mathf.Rad2Deg * frustOld.fovY * 0.5f;
}
// Symmetric Fov uses the maximum fov angle
float maxFovX = Mathf.Max(eyeDescs[(int)eye].fullFov.LeftFov, eyeDescs[(int)eye].fullFov.RightFov);
float maxFovY = Mathf.Max(eyeDescs[(int)eye].fullFov.UpFov, eyeDescs[(int)eye].fullFov.DownFov);
eyeDescs[(int)eye].fov.x = maxFovX * 2.0f;
eyeDescs[(int)eye].fov.y = maxFovY * 2.0f;
if (!OVRPlugin.AsymmetricFovEnabled)
{
eyeDescs[(int)eye].fullFov.LeftFov = maxFovX;
eyeDescs[(int)eye].fullFov.RightFov = maxFovX;
eyeDescs[(int)eye].fullFov.UpFov = maxFovY;
eyeDescs[(int)eye].fullFov.DownFov = maxFovY;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for ApplicationGatewaysOperations.
/// </summary>
public static partial class ApplicationGatewaysOperationsExtensions
{
/// <summary>
/// The delete applicationgateway operation deletes the specified
/// applicationgateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the applicationgateway.
/// </param>
public static void Delete(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName)
{
Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).DeleteAsync(resourceGroupName, applicationGatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete applicationgateway operation deletes the specified
/// applicationgateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the applicationgateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The delete applicationgateway operation deletes the specified
/// applicationgateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the applicationgateway.
/// </param>
public static void BeginDelete(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName)
{
Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).BeginDeleteAsync(resourceGroupName, applicationGatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete applicationgateway operation deletes the specified
/// applicationgateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the applicationgateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The Get applicationgateway operation retreives information about the
/// specified applicationgateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the applicationgateway.
/// </param>
public static ApplicationGateway Get(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName)
{
return Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).GetAsync(resourceGroupName, applicationGatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get applicationgateway operation retreives information about the
/// specified applicationgateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the applicationgateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ApplicationGateway> GetAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put ApplicationGateway operation creates/updates a ApplicationGateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the ApplicationGateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete ApplicationGateway operation
/// </param>
public static ApplicationGateway CreateOrUpdate(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters)
{
return Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).CreateOrUpdateAsync(resourceGroupName, applicationGatewayName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put ApplicationGateway operation creates/updates a ApplicationGateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the ApplicationGateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete ApplicationGateway operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ApplicationGateway> CreateOrUpdateAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put ApplicationGateway operation creates/updates a ApplicationGateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the ApplicationGateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete ApplicationGateway operation
/// </param>
public static ApplicationGateway BeginCreateOrUpdate(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters)
{
return Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, applicationGatewayName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put ApplicationGateway operation creates/updates a ApplicationGateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the ApplicationGateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete ApplicationGateway operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ApplicationGateway> BeginCreateOrUpdateAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List ApplicationGateway opertion retrieves all the applicationgateways
/// in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<ApplicationGateway> List(this IApplicationGatewaysOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List ApplicationGateway opertion retrieves all the applicationgateways
/// in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ApplicationGateway>> ListAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List applicationgateway opertion retrieves all the applicationgateways
/// in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<ApplicationGateway> ListAll(this IApplicationGatewaysOperations operations)
{
return Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List applicationgateway opertion retrieves all the applicationgateways
/// in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ApplicationGateway>> ListAllAsync(this IApplicationGatewaysOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Start ApplicationGateway operation starts application gatewayin the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
public static void Start(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName)
{
Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).StartAsync(resourceGroupName, applicationGatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Start ApplicationGateway operation starts application gatewayin the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task StartAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.StartWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The Start ApplicationGateway operation starts application gatewayin the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
public static void BeginStart(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName)
{
Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).BeginStartAsync(resourceGroupName, applicationGatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Start ApplicationGateway operation starts application gatewayin the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginStartAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginStartWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The STOP ApplicationGateway operation stops application gatewayin the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
public static void Stop(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName)
{
Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).StopAsync(resourceGroupName, applicationGatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The STOP ApplicationGateway operation stops application gatewayin the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task StopAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.StopWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The STOP ApplicationGateway operation stops application gatewayin the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
public static void BeginStop(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName)
{
Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).BeginStopAsync(resourceGroupName, applicationGatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The STOP ApplicationGateway operation stops application gatewayin the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginStopAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginStopWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The List ApplicationGateway opertion retrieves all the applicationgateways
/// in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ApplicationGateway> ListNext(this IApplicationGatewaysOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List ApplicationGateway opertion retrieves all the applicationgateways
/// in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ApplicationGateway>> ListNextAsync(this IApplicationGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List applicationgateway opertion retrieves all the applicationgateways
/// in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ApplicationGateway> ListAllNext(this IApplicationGatewaysOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IApplicationGatewaysOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List applicationgateway opertion retrieves all the applicationgateways
/// in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ApplicationGateway>> ListAllNextAsync(this IApplicationGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
namespace SpellChecker.Net.Search.Spell
{
using System;
using Lucene.Net.Search;
using Lucene.Net.Store;
using BooleanClause = Lucene.Net.Search.BooleanClause;
using BooleanQuery = Lucene.Net.Search.BooleanQuery;
using Directory = Lucene.Net.Store.Directory;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using Query = Lucene.Net.Search.Query;
using Term = Lucene.Net.Index.Term;
using TermQuery = Lucene.Net.Search.TermQuery;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
/// <summary> <p>
/// Spell Checker class (Main class) <br/>
/// (initially inspired by the David Spencer code).
/// </p>
///
/// <p>Example Usage:</p>
///
/// <pre>
/// SpellChecker spellchecker = new SpellChecker(spellIndexDirectory);
/// // To index a field of a user index:
/// spellchecker.indexDictionary(new LuceneDictionary(my_lucene_reader, a_field));
/// // To index a file containing words:
/// spellchecker.indexDictionary(new PlainTextDictionary(new File("myfile.txt")));
/// String[] suggestions = spellchecker.suggestSimilar("misspelt", 5);
/// </pre>
///
/// </summary>
/// <author> Nicolas Maisonneuve
/// </author>
/// <version> 1.0
/// </version>
public class SpellChecker : IDisposable
{
/// <summary> Field name for each word in the ngram index.</summary>
public const System.String F_WORD = "word";
private readonly Term F_WORD_TERM = new Term(F_WORD);
/// <summary> the spell index</summary>
internal Directory spellindex;
/// <summary> Boost value for start and end grams</summary>
private const float bStart = 2.0f;
private const float bEnd = 1.0f;
// don't use this searcher directly - see #swapSearcher()
private IndexSearcher searcher;
/// <summary>
/// this locks all modifications to the current searcher.
/// </summary>
private static readonly System.Object searcherLock = new System.Object();
/*
* this lock synchronizes all possible modifications to the
* current index directory. It should not be possible to try modifying
* the same index concurrently. Note: Do not acquire the searcher lock
* before acquiring this lock!
*/
private static readonly System.Object modifyCurrentIndexLock = new System.Object();
private volatile bool closed = false;
internal float minScore = 0.5f; //LUCENENET-359 Spellchecker accuracy gets overwritten
private StringDistance sd;
/// <summary>
/// Use the given directory as a spell checker index. The directory
/// is created if it doesn't exist yet.
/// </summary>
/// <param name="spellIndex">the spell index directory</param>
/// <param name="sd">the <see cref="StringDistance"/> measurement to use </param>
public SpellChecker(Directory spellIndex, StringDistance sd)
{
this.SetSpellIndex(spellIndex);
this.setStringDistance(sd);
}
/// <summary>
/// Use the given directory as a spell checker index with a
/// <see cref="LevenshteinDistance"/> as the default <see cref="StringDistance"/>. The
/// directory is created if it doesn't exist yet.
/// </summary>
/// <param name="spellIndex">the spell index directory</param>
public SpellChecker(Directory spellIndex)
: this(spellIndex, new LevenshteinDistance())
{ }
/// <summary>
/// Use a different index as the spell checker index or re-open
/// the existing index if <c>spellIndex</c> is the same value
/// as given in the constructor.
/// </summary>
/// <param name="spellIndexDir">spellIndexDir the spell directory to use </param>
/// <throws>AlreadyClosedException if the Spellchecker is already closed</throws>
/// <throws>IOException if spellchecker can not open the directory</throws>
virtual public void SetSpellIndex(Directory spellIndexDir)
{
// this could be the same directory as the current spellIndex
// modifications to the directory should be synchronized
lock (modifyCurrentIndexLock)
{
EnsureOpen();
if (!IndexReader.IndexExists(spellIndexDir))
{
var writer = new IndexWriter(spellIndexDir, null, true,
IndexWriter.MaxFieldLength.UNLIMITED);
writer.Close();
}
SwapSearcher(spellIndexDir);
}
}
/// <summary>
/// Sets the <see cref="StringDistance"/> implementation for this
/// <see cref="SpellChecker"/> instance.
/// </summary>
/// <param name="sd">the <see cref="StringDistance"/> implementation for this
/// <see cref="SpellChecker"/> instance.</param>
public void setStringDistance(StringDistance sd)
{
this.sd = sd;
}
/// <summary>
/// Returns the <see cref="StringDistance"/> instance used by this
/// <see cref="SpellChecker"/> instance.
/// </summary>
/// <returns>
/// Returns the <see cref="StringDistance"/> instance used by this
/// <see cref="SpellChecker"/> instance.
/// </returns>
public StringDistance GetStringDistance()
{
return sd;
}
/// <summary> Set the accuracy 0 < min < 1; default 0.5</summary>
virtual public void SetAccuracy(float minScore)
{
this.minScore = minScore;
}
/// <summary> Suggest similar words</summary>
/// <param name="word">String the word you want a spell check done on
/// </param>
/// <param name="num_sug">int the number of suggest words
/// </param>
/// <throws> IOException </throws>
/// <returns> String[]
/// </returns>
public virtual System.String[] SuggestSimilar(System.String word, int num_sug)
{
return this.SuggestSimilar(word, num_sug, null, null, false);
}
/// <summary> Suggest similar words (restricted or not to a field of a user index)</summary>
/// <param name="word">String the word you want a spell check done on
/// </param>
/// <param name="numSug">int the number of suggest words
/// </param>
/// <param name="ir">the indexReader of the user index (can be null see field param)
/// </param>
/// <param name="field">String the field of the user index: if field is not null, the suggested
/// words are restricted to the words present in this field.
/// </param>
/// <param name="morePopular">boolean return only the suggest words that are more frequent than the searched word
/// (only if restricted mode = (indexReader!=null and field!=null)
/// </param>
/// <throws> IOException </throws>
/// <returns> String[] the sorted list of the suggest words with this 2 criteria:
/// first criteria: the edit distance, second criteria (only if restricted mode): the popularity
/// of the suggest words in the field of the user index
/// </returns>
public virtual System.String[] SuggestSimilar(System.String word, int numSug, IndexReader ir, System.String field, bool morePopular)
{ // obtainSearcher calls ensureOpen
IndexSearcher indexSearcher = ObtainSearcher();
try
{
float min = this.minScore;
int lengthWord = word.Length;
int freq = (ir != null && field != null) ? ir.DocFreq(new Term(field, word)) : 0;
int goalFreq = (morePopular && ir != null && field != null) ? freq : 0;
// if the word exists in the real index and we don't care for word frequency, return the word itself
if (!morePopular && freq > 0)
{
return new String[] { word };
}
var query = new BooleanQuery();
String[] grams;
String key;
var alreadySeen = new HashSet<string>();
for (var ng = GetMin(lengthWord); ng <= GetMax(lengthWord); ng++)
{
key = "gram" + ng; // form key
grams = FormGrams(word, ng); // form word into ngrams (allow dups too)
if (grams.Length == 0)
{
continue; // hmm
}
if (bStart > 0)
{ // should we boost prefixes?
Add(query, "start" + ng, grams[0], bStart); // matches start of word
}
if (bEnd > 0)
{ // should we boost suffixes
Add(query, "end" + ng, grams[grams.Length - 1], bEnd); // matches end of word
}
for (int i = 0; i < grams.Length; i++)
{
Add(query, key, grams[i]);
}
}
int maxHits = 10 * numSug;
// System.out.println("Q: " + query);
ScoreDoc[] hits = indexSearcher.Search(query, null, maxHits).ScoreDocs;
// System.out.println("HITS: " + hits.length());
SuggestWordQueue sugQueue = new SuggestWordQueue(numSug);
// go thru more than 'maxr' matches in case the distance filter triggers
int stop = Math.Min(hits.Length, maxHits);
SuggestWord sugWord = new SuggestWord();
for (int i = 0; i < stop; i++)
{
sugWord.termString = indexSearcher.Doc(hits[i].Doc).Get(F_WORD); // get orig word
// don't suggest a word for itself, that would be silly
if (sugWord.termString.Equals(word))
{
continue;
}
// edit distance
sugWord.score = sd.GetDistance(word, sugWord.termString);
if (sugWord.score < min)
{
continue;
}
if (ir != null && field != null)
{ // use the user index
sugWord.freq = ir.DocFreq(new Term(field, sugWord.termString)); // freq in the index
// don't suggest a word that is not present in the field
if ((morePopular && goalFreq > sugWord.freq) || sugWord.freq < 1)
{
continue;
}
}
if (alreadySeen.Add(sugWord.termString) == false) // we already seen this word, no point returning it twice
continue;
sugQueue.InsertWithOverflow(sugWord);
if (sugQueue.Size() == numSug)
{
// if queue full, maintain the minScore score
min = ((SuggestWord)sugQueue.Top()).score;
}
sugWord = new SuggestWord();
}
// convert to array string
String[] list = new String[sugQueue.Size()];
for (int i = sugQueue.Size() - 1; i >= 0; i--)
{
list[i] = ((SuggestWord)sugQueue.Pop()).termString;
}
return list;
}
finally
{
ReleaseSearcher(indexSearcher);
}
}
/// <summary> Add a clause to a boolean query.</summary>
private static void Add(BooleanQuery q, System.String k, System.String v, float boost)
{
Query tq = new TermQuery(new Term(k, v));
tq.Boost = boost;
q.Add(new BooleanClause(tq, Occur.SHOULD));
}
/// <summary> Add a clause to a boolean query.</summary>
private static void Add(BooleanQuery q, System.String k, System.String v)
{
q.Add(new BooleanClause(new TermQuery(new Term(k, v)), Occur.SHOULD));
}
/// <summary> Form all ngrams for a given word.</summary>
/// <param name="text">the word to parse
/// </param>
/// <param name="ng">the ngram length e.g. 3
/// </param>
/// <returns> an array of all ngrams in the word and note that duplicates are not removed
/// </returns>
private static System.String[] FormGrams(System.String text, int ng)
{
int len = text.Length;
System.String[] res = new System.String[len - ng + 1];
for (int i = 0; i < len - ng + 1; i++)
{
res[i] = text.Substring(i, (i + ng) - (i));
}
return res;
}
/// <summary>
/// Removes all terms from the spell check index.
/// </summary>
public virtual void ClearIndex()
{
lock (modifyCurrentIndexLock)
{
EnsureOpen();
Directory dir = this.spellindex;
IndexWriter writer = new IndexWriter(dir, null, true, IndexWriter.MaxFieldLength.UNLIMITED);
writer.Close();
SwapSearcher(dir);
}
}
/// <summary> Check whether the word exists in the index.</summary>
/// <param name="word">String
/// </param>
/// <throws> IOException </throws>
/// <returns> true iff the word exists in the index
/// </returns>
public virtual bool Exist(System.String word)
{
// obtainSearcher calls ensureOpen
IndexSearcher indexSearcher = ObtainSearcher();
try
{
return indexSearcher.DocFreq(F_WORD_TERM.CreateTerm(word)) > 0;
}
finally
{
ReleaseSearcher(indexSearcher);
}
}
/// <summary> Index a Dictionary</summary>
/// <param name="dict">the dictionary to index</param>
/// <param name="mergeFactor">mergeFactor to use when indexing</param>
/// <param name="ramMB">the max amount or memory in MB to use</param>
/// <throws> IOException </throws>
/// <throws>AlreadyClosedException if the Spellchecker is already closed</throws>
public virtual void IndexDictionary(IDictionary dict, int mergeFactor, int ramMB)
{
lock (modifyCurrentIndexLock)
{
EnsureOpen();
Directory dir = this.spellindex;
IndexWriter writer = new IndexWriter(spellindex, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED);
writer.MergeFactor = mergeFactor;
writer.SetMaxBufferedDocs(ramMB);
System.Collections.IEnumerator iter = dict.GetWordsIterator();
while (iter.MoveNext())
{
System.String word = (System.String)iter.Current;
int len = word.Length;
if (len < 3)
{
continue; // too short we bail but "too long" is fine...
}
if (this.Exist(word))
{
// if the word already exist in the gramindex
continue;
}
// ok index the word
Document doc = CreateDocument(word, GetMin(len), GetMax(len));
writer.AddDocument(doc);
}
// close writer
writer.Optimize();
writer.Close();
// also re-open the spell index to see our own changes when the next suggestion
// is fetched:
SwapSearcher(dir);
}
}
/// <summary>
/// Indexes the data from the given <see cref="IDictionary"/>.
/// </summary>
/// <param name="dict">dict the dictionary to index</param>
public void IndexDictionary(IDictionary dict)
{
IndexDictionary(dict, 300, 10);
}
private int GetMin(int l)
{
if (l > 5)
{
return 3;
}
if (l == 5)
{
return 2;
}
return 1;
}
private int GetMax(int l)
{
if (l > 5)
{
return 4;
}
if (l == 5)
{
return 3;
}
return 2;
}
private static Document CreateDocument(System.String text, int ng1, int ng2)
{
Document doc = new Document();
doc.Add(new Field(F_WORD, text, Field.Store.YES, Field.Index.NOT_ANALYZED)); // orig term
AddGram(text, doc, ng1, ng2);
return doc;
}
private static void AddGram(System.String text, Document doc, int ng1, int ng2)
{
int len = text.Length;
for (int ng = ng1; ng <= ng2; ng++)
{
System.String key = "gram" + ng;
System.String end = null;
for (int i = 0; i < len - ng + 1; i++)
{
System.String gram = text.Substring(i, (i + ng) - (i));
doc.Add(new Field(key, gram, Field.Store.NO, Field.Index.NOT_ANALYZED));
if (i == 0)
{
doc.Add(new Field("start" + ng, gram, Field.Store.NO, Field.Index.NOT_ANALYZED));
}
end = gram;
}
if (end != null)
{
// may not be present if len==ng1
doc.Add(new Field("end" + ng, end, Field.Store.NO, Field.Index.NOT_ANALYZED));
}
}
}
private IndexSearcher ObtainSearcher()
{
lock (searcherLock)
{
EnsureOpen();
searcher.IndexReader.IncRef();
return searcher;
}
}
private void ReleaseSearcher(IndexSearcher aSearcher)
{
// don't check if open - always decRef
// don't decrement the private searcher - could have been swapped
aSearcher.IndexReader.DecRef();
}
private void EnsureOpen()
{
if (closed)
{
throw new AlreadyClosedException("Spellchecker has been closed");
}
}
public void Close()
{
lock (searcherLock)
{
EnsureOpen();
closed = true;
if (searcher != null)
{
searcher.Close();
}
searcher = null;
}
}
private void SwapSearcher(Directory dir)
{
/*
* opening a searcher is possibly very expensive.
* We rather close it again if the Spellchecker was closed during
* this operation than block access to the current searcher while opening.
*/
IndexSearcher indexSearcher = CreateSearcher(dir);
lock (searcherLock)
{
if (closed)
{
indexSearcher.Close();
throw new AlreadyClosedException("Spellchecker has been closed");
}
if (searcher != null)
{
searcher.Close();
}
// set the spellindex in the sync block - ensure consistency.
searcher = indexSearcher;
this.spellindex = dir;
}
}
/// <summary>
/// Creates a new read-only IndexSearcher (for testing purposes)
/// </summary>
/// <param name="dir">dir the directory used to open the searcher</param>
/// <returns>a new read-only IndexSearcher. (throws IOException f there is a low-level IO error)</returns>
public virtual IndexSearcher CreateSearcher(Directory dir)
{
return new IndexSearcher(dir, true);
}
/// <summary>
/// Returns <c>true</c> if and only if the <see cref="SpellChecker"/> is
/// closed, otherwise <c>false</c>.
/// </summary>
/// <returns><c>true</c> if and only if the <see cref="SpellChecker"/> is
/// closed, otherwise <c>false</c>.
///</returns>
bool IsClosed()
{
return closed;
}
~SpellChecker()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposeOfManagedResources)
{
if (disposeOfManagedResources)
{
if (!this.closed)
this.Close();
}
}
}
}
| |
// 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 CompareGreaterThanOrEqualUnorderedScalarBoolean()
{
var test = new BooleanComparisonOpTest__CompareGreaterThanOrEqualUnorderedScalarBoolean();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.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 (Sse.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 (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanComparisonOpTest__CompareGreaterThanOrEqualUnorderedScalarBoolean
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Single);
private const int Op2ElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private BooleanComparisonOpTest__DataTable<Single, Single> _dataTable;
static BooleanComparisonOpTest__CompareGreaterThanOrEqualUnorderedScalarBoolean()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
}
public BooleanComparisonOpTest__CompareGreaterThanOrEqualUnorderedScalarBoolean()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
_dataTable = new BooleanComparisonOpTest__DataTable<Single, Single>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse.CompareGreaterThanOrEqualUnorderedScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse.CompareGreaterThanOrEqualUnorderedScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse.CompareGreaterThanOrEqualUnorderedScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThanOrEqualUnorderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThanOrEqualUnorderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThanOrEqualUnorderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
var result = Sse.CompareGreaterThanOrEqualUnorderedScalar(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareGreaterThanOrEqualUnorderedScalar(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareGreaterThanOrEqualUnorderedScalar(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareGreaterThanOrEqualUnorderedScalar(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanComparisonOpTest__CompareGreaterThanOrEqualUnorderedScalarBoolean();
var result = Sse.CompareGreaterThanOrEqualUnorderedScalar(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse.CompareGreaterThanOrEqualUnorderedScalar(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Single[] left, Single[] right, bool result, [CallerMemberName] string method = "")
{
if ((left[0] >= right[0]) != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareGreaterThanOrEqualUnorderedScalar)}<Boolean>(Vector128<Single>, Vector128<Single>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// [email protected]
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
namespace MatterHackers.Agg
{
public class ArrayPOD<T> where T : struct
{
public ArrayPOD()
: this(64)
{
}
public ArrayPOD(int size)
{
m_array = new T[size];
m_size = size;
}
public void RemoveLast()
{
throw new NotImplementedException();
}
public ArrayPOD(ArrayPOD<T> v)
{
m_array = (T[])v.m_array.Clone();
m_size = v.m_size;
}
public void Resize(int size)
{
if (size != m_size)
{
m_array = new T[size];
}
}
public int Size()
{
return m_size;
}
public T this[int index]
{
get
{
return m_array[index];
}
set
{
m_array[index] = value;
}
}
public T[] Array
{
get
{
return m_array;
}
}
private T[] m_array;
private int m_size;
}
//--------------------------------------------------------------pod_vector
// A simple class template to store Plain Old Data, a vector
// of a fixed size. The data is contiguous in memory
//------------------------------------------------------------------------
public class VectorPOD<DataType> where DataType : struct
{
protected int currentSize;
private DataType[] internalArray = new DataType[0];
public int Count
{
get { return currentSize; }
}
public IEnumerable<DataType> DataIterator()
{
for (int index = 0; index < currentSize; index++)
{
// Yield each day of the week.
yield return internalArray[index];
}
}
public IEnumerator GetEnumerator()
{
for (int index = 0; index < currentSize; index++)
{
// Yield each day of the week.
yield return internalArray[index];
}
}
public int AllocatedSize
{
get
{
return internalArray.Length;
}
}
public VectorPOD()
{
}
public VectorPOD(int cap)
: this(cap, 0)
{
}
public VectorPOD(int capacity, int extraTail)
{
Allocate(capacity, extraTail);
}
public void RemoveAt(int indexToRemove)
{
Remove(indexToRemove);
}
public void Remove(int indexToRemove)
{
if (indexToRemove >= Length)
{
throw new Exception("requested remove past end of array");
}
for (int i = indexToRemove; i < Length - 1; i++)
{
internalArray[i] = internalArray[i + 1];
}
currentSize--;
}
public void RemoveLast()
{
if (currentSize != 0)
{
currentSize--;
}
}
// Copying
public VectorPOD(VectorPOD<DataType> vectorToCopy)
{
currentSize = vectorToCopy.currentSize;
internalArray = (DataType[])vectorToCopy.internalArray.Clone();
}
public void CopyFrom(VectorPOD<DataType> vetorToCopy)
{
Allocate(vetorToCopy.currentSize);
if (vetorToCopy.currentSize != 0)
{
vetorToCopy.internalArray.CopyTo(internalArray, 0);
}
}
// Set new capacity. All data is lost, size is set to zero.
public void Capacity(int newCapacity)
{
Capacity(newCapacity, 0);
}
public void Capacity(int newCapacity, int extraTail)
{
currentSize = 0;
if (newCapacity > AllocatedSize)
{
internalArray = null;
int sizeToAllocate = newCapacity + extraTail;
if (sizeToAllocate != 0)
{
internalArray = new DataType[sizeToAllocate];
}
}
}
public int Capacity()
{
return AllocatedSize;
}
// Allocate n elements. All data is lost,
// but elements can be accessed in range 0...size-1.
public void Allocate(int size)
{
Allocate(size, 0);
}
public void Allocate(int size, int extraTail)
{
Capacity(size, extraTail);
currentSize = size;
}
// Resize keeping the content.
public void Resize(int newSize)
{
if (newSize > currentSize)
{
if (newSize > AllocatedSize)
{
var newArray = new DataType[newSize];
if (internalArray != null)
{
for (int i = 0; i < internalArray.Length; i++)
{
newArray[i] = internalArray[i];
}
}
internalArray = newArray;
}
}
}
#pragma warning disable 649
private static DataType zeroed_object;
#pragma warning restore 649
public void zero()
{
int NumItems = internalArray.Length;
for (int i = 0; i < NumItems; i++)
{
internalArray[i] = zeroed_object;
}
}
public void Add(DataType v)
{
add(v);
}
public virtual void add(DataType v)
{
if (internalArray == null || internalArray.Length < (currentSize + 1))
{
if (currentSize < 100000)
{
Resize(currentSize + (currentSize / 2) + 16);
}
else
{
Resize(currentSize + currentSize / 4);
}
}
internalArray[currentSize++] = v;
}
public void push_back(DataType v)
{
internalArray[currentSize++] = v;
}
public void Insert(int index, DataType value)
{
insert_at(index, value);
}
public void insert_at(int pos, DataType val)
{
if (pos >= currentSize)
{
internalArray[currentSize] = val;
}
else
{
for (int i = 0; i < currentSize - pos; i++)
{
internalArray[i + pos + 1] = internalArray[i + pos];
}
internalArray[pos] = val;
}
++currentSize;
}
public void inc_size(int size)
{
currentSize += size;
}
public int size()
{
return currentSize;
}
public DataType this[int i]
{
get
{
return internalArray[i];
}
}
public DataType[] Array
{
get
{
return internalArray;
}
}
public DataType at(int i)
{
return internalArray[i];
}
public DataType value_at(int i)
{
return internalArray[i];
}
public DataType[] data()
{
return internalArray;
}
public void remove_all()
{
currentSize = 0;
}
public void clear()
{
currentSize = 0;
}
public void cut_at(int num)
{
if (num < currentSize) currentSize = num;
}
public int Length
{
get
{
return currentSize;
}
}
public void Clear()
{
currentSize = 0;
}
public void Remove(DataType itemToRemove)
{
for (int i = 0; i < Length; i++)
{
if ((object)internalArray[i] == (object)itemToRemove)
{
Remove(i);
}
}
}
}
//----------------------------------------------------------range_adaptor
public class VectorPOD_RangeAdaptor
{
private VectorPOD<int> m_array;
private int m_start;
private int m_size;
public VectorPOD_RangeAdaptor(VectorPOD<int> array, int start, int size)
{
m_array = (array);
m_start = (start);
m_size = (size);
}
public int size()
{
return m_size;
}
public int this[int i]
{
get
{
return m_array.Array[m_start + i];
}
set
{
m_array.Array[m_start + i] = value;
}
}
public int at(int i)
{
return m_array.Array[m_start + i];
}
public int value_at(int i)
{
return m_array.Array[m_start + i];
}
}
public class FirstInFirstOutQueue<T>
{
private T[] itemArray;
private int size;
private int head;
private int shiftFactor;
private int mask;
public int Count
{
get { return size; }
}
public FirstInFirstOutQueue(int shiftFactor)
{
this.shiftFactor = shiftFactor;
mask = (1 << shiftFactor) - 1;
itemArray = new T[1 << shiftFactor];
head = 0;
size = 0;
}
public T First
{
get { return itemArray[head & mask]; }
}
public void Enqueue(T itemToQueue)
{
if (size == itemArray.Length)
{
int headIndex = head & mask;
shiftFactor += 1;
mask = (1 << shiftFactor) - 1;
T[] newArray = new T[1 << shiftFactor];
// copy the from head to the end
Array.Copy(itemArray, headIndex, newArray, 0, size - headIndex);
// copy form 0 to the size
Array.Copy(itemArray, 0, newArray, size - headIndex, headIndex);
itemArray = newArray;
head = 0;
}
itemArray[(head + (size++)) & mask] = itemToQueue;
}
public T Dequeue()
{
int headIndex = head & mask;
T firstItem = itemArray[headIndex];
if (size > 0)
{
head++;
size--;
}
return firstItem;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using OpenMetaverse;
namespace OpenSim.Framework
{
public class EstateSettings
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public delegate void SaveDelegate(EstateSettings rs);
public event SaveDelegate OnSave;
// Only the client uses these
//
private uint m_EstateID = 0;
public uint EstateID
{
get { return m_EstateID; }
set { m_EstateID = value; }
}
private string m_EstateName = "My Estate";
public string EstateName
{
get { return m_EstateName; }
set { m_EstateName = value; }
}
private uint m_ParentEstateID = 1;
public uint ParentEstateID
{
get { return m_ParentEstateID; }
set { m_ParentEstateID = value; }
}
private float m_BillableFactor = 0.0f;
public float BillableFactor
{
get { return m_BillableFactor; }
set { m_BillableFactor = value; }
}
private int m_PricePerMeter = 1;
public int PricePerMeter
{
get { return m_PricePerMeter; }
set { m_PricePerMeter = value; }
}
private int m_RedirectGridX = 0;
public int RedirectGridX
{
get { return m_RedirectGridX; }
set { m_RedirectGridX = value; }
}
private int m_RedirectGridY = 0;
public int RedirectGridY
{
get { return m_RedirectGridY; }
set { m_RedirectGridY = value; }
}
// Used by the sim
//
private bool m_UseGlobalTime = true;
public bool UseGlobalTime
{
get { return m_UseGlobalTime; }
set { m_UseGlobalTime = value; }
}
private bool m_FixedSun = false;
public bool FixedSun
{
get { return m_FixedSun; }
set { m_FixedSun = value; }
}
private double m_SunPosition = 0.0;
public double SunPosition
{
get { return m_SunPosition; }
set { m_SunPosition = value; }
}
private bool m_AllowVoice = true;
public bool AllowVoice
{
get { return m_AllowVoice; }
set { m_AllowVoice = value; }
}
private bool m_AllowDirectTeleport = true;
public bool AllowDirectTeleport
{
get { return m_AllowDirectTeleport; }
set { m_AllowDirectTeleport = value; }
}
private bool m_DenyAnonymous = false;
public bool DenyAnonymous
{
get { return m_DenyAnonymous; }
set { m_DenyAnonymous = value; }
}
private bool m_DenyIdentified = false;
public bool DenyIdentified
{
get { return m_DenyIdentified; }
set { m_DenyIdentified = value; }
}
private bool m_DenyTransacted = false;
public bool DenyTransacted
{
get { return m_DenyTransacted; }
set { m_DenyTransacted = value; }
}
private bool m_AbuseEmailToEstateOwner = false;
public bool AbuseEmailToEstateOwner
{
get { return m_AbuseEmailToEstateOwner; }
set { m_AbuseEmailToEstateOwner = value; }
}
private bool m_BlockDwell = false;
public bool BlockDwell
{
get { return m_BlockDwell; }
set { m_BlockDwell = value; }
}
private bool m_EstateSkipScripts = false;
public bool EstateSkipScripts
{
get { return m_EstateSkipScripts; }
set { m_EstateSkipScripts = value; }
}
private bool m_ResetHomeOnTeleport = false;
public bool ResetHomeOnTeleport
{
get { return m_ResetHomeOnTeleport; }
set { m_ResetHomeOnTeleport = value; }
}
private bool m_TaxFree = false;
public bool TaxFree
{
get { return m_TaxFree; }
set { m_TaxFree = value; }
}
private bool m_PublicAccess = true;
public bool PublicAccess
{
get { return m_PublicAccess; }
set { m_PublicAccess = value; }
}
private string m_AbuseEmail = String.Empty;
public string AbuseEmail
{
get { return m_AbuseEmail; }
set { m_AbuseEmail= value; }
}
private UUID m_EstateOwner = UUID.Zero;
public UUID EstateOwner
{
get { return m_EstateOwner; }
set { m_EstateOwner = value; }
}
private bool m_DenyMinors = false;
public bool DenyMinors
{
get { return m_DenyMinors; }
set { m_DenyMinors = value; }
}
// All those lists...
//
private List<UUID> l_EstateManagers = new List<UUID>();
public UUID[] EstateManagers
{
get { return l_EstateManagers.ToArray(); }
set { l_EstateManagers = new List<UUID>(value); }
}
private List<EstateBan> l_EstateBans = new List<EstateBan>();
public EstateBan[] EstateBans
{
get { return l_EstateBans.ToArray(); }
set { l_EstateBans = new List<EstateBan>(value); }
}
private List<UUID> l_EstateAccess = new List<UUID>();
public UUID[] EstateAccess
{
get { return l_EstateAccess.ToArray(); }
set { l_EstateAccess = new List<UUID>(value); }
}
private List<UUID> l_EstateGroups = new List<UUID>();
public UUID[] EstateGroups
{
get { return l_EstateGroups.ToArray(); }
set { l_EstateGroups = new List<UUID>(value); }
}
public EstateSettings()
{
}
public void Save()
{
if (OnSave != null)
OnSave(this);
}
public void AddEstateUser(UUID avatarID)
{
if (avatarID == UUID.Zero)
return;
if (!l_EstateAccess.Contains(avatarID))
l_EstateAccess.Add(avatarID);
}
public void RemoveEstateUser(UUID avatarID)
{
if (l_EstateAccess.Contains(avatarID))
l_EstateAccess.Remove(avatarID);
}
public void AddEstateGroup(UUID avatarID)
{
if (avatarID == UUID.Zero)
return;
if (!l_EstateGroups.Contains(avatarID))
l_EstateGroups.Add(avatarID);
}
public void RemoveEstateGroup(UUID avatarID)
{
if (l_EstateGroups.Contains(avatarID))
l_EstateGroups.Remove(avatarID);
}
public void AddEstateManager(UUID avatarID)
{
if (avatarID == UUID.Zero)
return;
if (!l_EstateManagers.Contains(avatarID))
l_EstateManagers.Add(avatarID);
}
public void RemoveEstateManager(UUID avatarID)
{
if (l_EstateManagers.Contains(avatarID))
l_EstateManagers.Remove(avatarID);
}
public bool IsEstateManager(UUID avatarID)
{
if (IsEstateOwner(avatarID))
return true;
return l_EstateManagers.Contains(avatarID);
}
public bool IsEstateOwner(UUID avatarID)
{
if (avatarID == m_EstateOwner)
return true;
return false;
}
public bool IsBanned(UUID avatarID)
{
foreach (EstateBan ban in l_EstateBans)
if (ban.BannedUserID == avatarID)
return true;
return false;
}
public void AddBan(EstateBan ban)
{
if (ban == null)
return;
if (!IsBanned(ban.BannedUserID))
l_EstateBans.Add(ban);
}
public void ClearBans()
{
l_EstateBans.Clear();
}
public void RemoveBan(UUID avatarID)
{
foreach (EstateBan ban in new List<EstateBan>(l_EstateBans))
if (ban.BannedUserID == avatarID)
l_EstateBans.Remove(ban);
}
public bool HasAccess(UUID user)
{
if (IsEstateManager(user))
return true;
return l_EstateAccess.Contains(user);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.Updating.Resources
{
public sealed class AtomicUpdateToOneRelationshipTests : IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext;
private readonly OperationsFakers _fakers = new();
public AtomicUpdateToOneRelationshipTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<OperationsController>();
}
[Fact]
public async Task Can_clear_OneToOne_relationship_from_principal_side()
{
// Arrange
Lyric existingLyric = _fakers.Lyric.Generate();
existingLyric.Track = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<MusicTrack>();
dbContext.Lyrics.Add(existingLyric);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "lyrics",
id = existingLyric.StringId,
relationships = new
{
track = new
{
data = (object)null
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Lyric lyricInDatabase = await dbContext.Lyrics.Include(lyric => lyric.Track).FirstWithIdAsync(existingLyric.Id);
lyricInDatabase.Track.Should().BeNull();
List<MusicTrack> tracksInDatabase = await dbContext.MusicTracks.ToListAsync();
tracksInDatabase.Should().HaveCount(1);
});
}
[Fact]
public async Task Can_clear_OneToOne_relationship_from_dependent_side()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
existingTrack.Lyric = _fakers.Lyric.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Lyric>();
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
data = (object)null
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Lyric).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.Lyric.Should().BeNull();
List<Lyric> lyricsInDatabase = await dbContext.Lyrics.ToListAsync();
lyricsInDatabase.Should().HaveCount(1);
});
}
[Fact]
public async Task Can_clear_ManyToOne_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
existingTrack.OwnedBy = _fakers.RecordCompany.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<RecordCompany>();
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
ownedBy = new
{
data = (object)null
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.OwnedBy).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.OwnedBy.Should().BeNull();
List<RecordCompany> companiesInDatabase = await dbContext.RecordCompanies.ToListAsync();
companiesInDatabase.Should().HaveCount(1);
});
}
[Fact]
public async Task Can_create_OneToOne_relationship_from_principal_side()
{
// Arrange
Lyric existingLyric = _fakers.Lyric.Generate();
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.AddInRange(existingLyric, existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "lyrics",
id = existingLyric.StringId,
relationships = new
{
track = new
{
data = new
{
type = "musicTracks",
id = existingTrack.StringId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Lyric lyricInDatabase = await dbContext.Lyrics.Include(lyric => lyric.Track).FirstWithIdAsync(existingLyric.Id);
lyricInDatabase.Track.Id.Should().Be(existingTrack.Id);
});
}
[Fact]
public async Task Can_create_OneToOne_relationship_from_dependent_side()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
Lyric existingLyric = _fakers.Lyric.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.AddInRange(existingTrack, existingLyric);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
data = new
{
type = "lyrics",
id = existingLyric.StringId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Lyric).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.Lyric.Id.Should().Be(existingLyric.Id);
});
}
[Fact]
public async Task Can_create_ManyToOne_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
RecordCompany existingCompany = _fakers.RecordCompany.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.AddInRange(existingTrack, existingCompany);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
ownedBy = new
{
data = new
{
type = "recordCompanies",
id = existingCompany.StringId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.OwnedBy).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.OwnedBy.Id.Should().Be(existingCompany.Id);
});
}
[Fact]
public async Task Can_replace_OneToOne_relationship_from_principal_side()
{
// Arrange
Lyric existingLyric = _fakers.Lyric.Generate();
existingLyric.Track = _fakers.MusicTrack.Generate();
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<MusicTrack>();
dbContext.AddInRange(existingLyric, existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "lyrics",
id = existingLyric.StringId,
relationships = new
{
track = new
{
data = new
{
type = "musicTracks",
id = existingTrack.StringId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Lyric lyricInDatabase = await dbContext.Lyrics.Include(lyric => lyric.Track).FirstWithIdAsync(existingLyric.Id);
lyricInDatabase.Track.Id.Should().Be(existingTrack.Id);
List<MusicTrack> tracksInDatabase = await dbContext.MusicTracks.ToListAsync();
tracksInDatabase.Should().HaveCount(2);
});
}
[Fact]
public async Task Can_replace_OneToOne_relationship_from_dependent_side()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
existingTrack.Lyric = _fakers.Lyric.Generate();
Lyric existingLyric = _fakers.Lyric.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Lyric>();
dbContext.AddInRange(existingTrack, existingLyric);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
data = new
{
type = "lyrics",
id = existingLyric.StringId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Lyric).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.Lyric.Id.Should().Be(existingLyric.Id);
List<Lyric> lyricsInDatabase = await dbContext.Lyrics.ToListAsync();
lyricsInDatabase.Should().HaveCount(2);
});
}
[Fact]
public async Task Can_replace_ManyToOne_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
existingTrack.OwnedBy = _fakers.RecordCompany.Generate();
RecordCompany existingCompany = _fakers.RecordCompany.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<RecordCompany>();
dbContext.AddInRange(existingTrack, existingCompany);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
ownedBy = new
{
data = new
{
type = "recordCompanies",
id = existingCompany.StringId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.OwnedBy).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.OwnedBy.Id.Should().Be(existingCompany.Id);
List<RecordCompany> companiesInDatabase = await dbContext.RecordCompanies.ToListAsync();
companiesInDatabase.Should().HaveCount(2);
});
}
[Fact]
public async Task Cannot_create_for_array_in_relationship_data()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
data = new[]
{
new
{
type = "lyrics",
id = Unknown.StringId.For<Lyric, long>()
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected single data element for to-one relationship.");
error.Detail.Should().Be("Expected single data element for 'lyric' relationship.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_create_for_missing_type_in_relationship_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "lyrics",
id = Unknown.StringId.For<Lyric, long>(),
relationships = new
{
track = new
{
data = new
{
id = Unknown.StringId.For<MusicTrack, Guid>()
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body must include 'type' element.");
error.Detail.Should().Be("Expected 'type' element in 'track' relationship.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_create_for_unknown_type_in_relationship_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
relationships = new
{
lyric = new
{
data = new
{
type = Unknown.ResourceType,
id = Unknown.StringId.For<Lyric, long>()
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body includes unknown resource type.");
error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_create_for_missing_ID_in_relationship_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
relationships = new
{
lyric = new
{
data = new
{
type = "lyrics"
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body must include 'id' or 'lid' element.");
error.Detail.Should().Be("Expected 'id' or 'lid' element in 'lyric' relationship.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_create_for_ID_and_local_ID_in_relationship_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
relationships = new
{
lyric = new
{
data = new
{
type = "lyrics",
id = Unknown.StringId.For<Lyric, long>(),
lid = "local-1"
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Request body must include 'id' or 'lid' element.");
error.Detail.Should().Be("Expected 'id' or 'lid' element in 'lyric' relationship.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_create_for_unknown_ID_in_relationship_data()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
string lyricId = Unknown.StringId.For<Lyric, long>();
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
data = new
{
type = "lyrics",
id = lyricId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.NotFound);
error.Title.Should().Be("A related resource does not exist.");
error.Detail.Should().Be($"Related resource of type 'lyrics' with ID '{lyricId}' in relationship 'lyric' does not exist.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_create_for_relationship_mismatch()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
data = new
{
type = "playlists",
id = Unknown.StringId.For<Playlist, long>()
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Relationship contains incompatible resource type.");
error.Detail.Should().Be("Relationship 'lyric' contains incompatible resource type 'playlists'.");
error.Source.Pointer.Should().Be("/atomic:operations[0]");
}
}
}
| |
using System;
using NLog;
namespace SlimeSimulation.Algorithms.LinearEquations
{
public class LupDecompositionSolver : ILinearEquationSolver
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public static int ErrorColumnNumber { get; private set; }
// Ax = b
public double[] FindX(double[][] a, double[] b)
{
if (Logger.IsDebugEnabled)
{
CheckMatrix(a);
LogDensity(a);
}
if (Logger.IsTraceEnabled)
{
Logger.Trace("A: " + LogHelper.PrintArrWithSpaces(a) + ", B: " + LogHelper.PrintArrWithNewLines(b));
}
Logger.Info($"[FindX] Solving with matrix with a size: {a.Length}, b size: {b.Length}. This will take approx {(long)b.Length * b.Length * ((long)b.Length)} operations");
var pi = LupDecompose(a);
var matrix = new UpperLowerMatrix(a);
return LupSolve(matrix, pi, b);
}
private void CheckMatrix(double[][] doubles)
{
for (int row = 0; row < doubles.Length; row++)
{
bool zeros = true;
for (int col = 0; col < doubles[row].Length; col++)
{
if (doubles[row][col] != 0)
{
zeros = false;
}
}
if (zeros)
{
throw new SingularMatrixException("Given matrix had zero row. rowNum: " + row);
}
}
for (int col = 0; col < doubles.Length; col++)
{
bool zeros = true;
for (int row = 0; row < doubles[col].Length; row++)
{
if (doubles[row][col] != 0)
{
zeros = false;
}
}
if (zeros)
{
throw new SingularMatrixException("Given matrix had zero column. column: " + col);
}
}
}
private void LogDensity(double[][] a)
{
int count = 0;
int total = 0;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < a[i].Length; j++)
{
total++;
if (a[i][j] != 0)
{
count++;
}
}
}
Logger.Debug("[LogDensity] Found nonzero: {0}, total: {1}, density %: {2}%", count, total, (count / (double)total) * 100);
}
private int[] MakePi(int length)
{
var pi = new int[length];
for (int i = 0; i < length; i++)
{
pi[i] = i;
}
return pi;
}
internal double[] LupSolve(UpperLowerMatrix matrix, int[] pi, double[] b)
{
int n = b.Length;
double[] y = ForwardSubstituteForY(matrix, pi, b, n);
double[] x = BackSubstitutionForX(matrix, pi, y, n);
return x;
}
internal double[] BackSubstitutionForX(UpperLowerMatrix matrix, int[] pi, double[] y, int n)
{
double[] x = new double[n];
for (int i = n - 1; i >= 0; i--)
{
double sequenceSum = 0;
for (int j = i + 1; j < n; j++)
{
sequenceSum += matrix.Upper(i, j) * x[j];
}
x[i] = (y[i] - sequenceSum) / matrix.Upper(i, i);
Logger.Trace("[LupSolve] for i {0} sequenceSum: {1}, x[i]: {2}", i, sequenceSum, x[i]);
}
return x;
}
internal double[] ForwardSubstituteForY(UpperLowerMatrix matrix, int[] pi, double[] b, int n)
{
double[] y = new double[n];
for (int i = 0; i < n; i++)
{
double sequenceSum = 0;
for (int j = 0; j < i; j++)
{
sequenceSum += matrix.Lower(i, j) * y[j];
}
y[i] = b[pi[i]] - sequenceSum;
Logger.Trace("[ForwardSubstituteForY] for i {0} sequenceSum: {1}, y[i]: {2}", i, sequenceSum, y[i]);
}
return y;
}
internal int[] LupDecompose(double[][] a)
{
int n = a.Length;
int[] pi = MakePi(a.Length);
for (int k = 0; k < n; k++)
{
int kdash = GetRowWithBiggestValueForColumn(a, k, pi);
Exchange(ref pi[k], ref pi[kdash]);
ExchangeRows(a, k, kdash);
for (int i = k + 1; i < n; i++)
{
a[i][k] = a[i][k] / a[k][k];
for (int j = k + 1; j < n; j++)
{
a[i][j] = a[i][j] - a[i][k] * a[k][j];
}
}
}
return pi;
}
private void ExchangeRows(double[][] array, int rowOne, int rowTwo)
{
for (int i = 0; i < array.Length; i++)
{
Exchange(ref array[rowOne][i], ref array[rowTwo][i]);
}
}
private int GetRowWithBiggestValueForColumn(double[][] array, int columnNumber, int[] pi)
{
double p = 0;
int kdash = -1;
for (int i = columnNumber; i < array.Length; i++)
{
if (Math.Abs(array[i][columnNumber]) > p)
{
p = Math.Abs(array[i][columnNumber]);
kdash = i;
}
}
if (p == 0)
{
var arrayString = LogHelper.PrintArr(array);
ErrorColumnNumber = pi[columnNumber];
var logstr = "No values found in column " + columnNumber + ". Meaning array A was singular: " + arrayString;
Logger.Error(logstr);
throw new SingularMatrixException(logstr);
}
return kdash;
}
private void Exchange(ref double v1, ref double v2)
{
var tmp = v1;
v1 = v2;
v2 = tmp;
}
public void Exchange(ref int v1, ref int v2)
{
var tmp = v1;
v1 = v2;
v2 = tmp;
}
}
internal class UpperLowerMatrix
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly double[][] _original;
private readonly double[][] _upper;
public UpperLowerMatrix(double[][] a)
{
_original = a;
_upper = MakeUpper(a);
}
private double[][] MakeUpper(double[][] array)
{
double[][] upper = new double[array.Length][];
for (int i = 0; i < upper.Length; i++)
{
upper[i] = new double[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
upper[i][j] = CheckedUpper(i, j);
}
}
return upper;
}
private double CheckedUpper(int i, int j)
{
if (i > j)
{
return 0;
}
return _original[i][j];
}
internal double Lower(int i, int j)
{
CheckArg(i);
CheckArg(j);
if (i <= j)
{
Logger.Warn("Lower matrix requested element which would have been upper");
return 0;
}
return _original[i][j];
}
internal double Upper(int i, int j)
{
CheckArg(i);
CheckArg(j);
return _upper[i][j];
}
private void CheckArg(int i)
{
if (i < 0)
{
throw new ArgumentOutOfRangeException("Must be positive. Given: " + i);
}
if (i >= _original.Length)
{
throw new ArgumentOutOfRangeException("Must be 0 indexed index. Max: " + _original.Length + ", Given: " + i);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using log4net;
using MindTouch.Reflection;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Documentation.Util {
// TODO (arnec): Need to handle operators
// TODO (arnec): Need to fixup !: types from xmldoc
public class HtmlDocumentationBuilder : IDisposable {
//--- Static Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
//--- Fields ---
private readonly Dictionary<string, string> _assemblies = new Dictionary<string, string>();
private readonly Dictionary<string, XDoc> _documentationBySignature = new Dictionary<string, XDoc>();
private readonly Dictionary<string, IReflectedInfo> _memberLookup = new Dictionary<string, IReflectedInfo>();
private readonly HashSet<string> _namespaces = new HashSet<string>();
private readonly HashSet<string> _documentedNamespaces = new HashSet<string>();
private readonly ITypeInspector _typeInspector;
private int _currentDataId;
private XDoc _manifest;
private XDoc _fileMap;
private string _outputPath;
private IEnumerable<ReflectedTypeInfo> _types;
//--- Constructors ---
public HtmlDocumentationBuilder() {
_typeInspector = new IsolatedTypeInspector();
}
public HtmlDocumentationBuilder(ITypeInspector typeInspector) {
_typeInspector = typeInspector;
}
//--- Methods ---
public void BuildDocumenationPackage(string outputPath, params string[] namespaces) {
_types = GetTypes();
InitNamespaces(namespaces);
_outputPath = outputPath;
_currentDataId = 0;
var package = new XDoc("package").Elem("manifest").Elem("map");
_manifest = package["manifest"];
_fileMap = package["map"];
var root = NewHtmlDocument("", false).Start("div").Attr("class", "doctree").Value("{{wiki.tree()}}").End();
Save(root, "", "//", "root.xml", null);
foreach(var type in _types.OrderBy(x => x.LongDisplayName).Where(IsTypeInDocumentation)) {
EnsureNamespaceRootDocument(type.Namespace);
var sig = type.Signature;
var xmlDoc = GetDoc(sig);
var title = type.DisplayName;
if(type.IsStatic) {
title += " Static";
}
switch(type.Kind) {
case TypeKind.Enum:
title += " Enumeration";
break;
case TypeKind.Interface:
title += " Interface";
break;
case TypeKind.Struct:
title += " Struct";
break;
default:
title += " Class";
break;
}
var html = NewHtmlDocument(title, true);
html.StartSection("docheader")
.CSharpBlock(type.CodeSignature)
.NameValueLine("namespace", "Namespace", type.Namespace)
.NameValueLine("assembly", "Assembly", type.Assembly);
BuildInheritanceChain(html, type);
BuildInterfaceBlock(html, type);
html
.Div("summary", xmlDoc["summary"])
.EndSection() // header section
.Section(1, "remarks", "Remarks", xmlDoc["remarks"]);
if(type.Kind == TypeKind.Enum) {
BuildEnumFields(html, type.Fields);
} else {
BuildGenericParameterSection(1, html, xmlDoc, type.GenericParameters.Where(x => !x.IsInherited));
if(!type.IsDelegate) {
AddMemberTables(html, type);
BuildConstructorHtml(type.Constructors);
BuildFieldHtml(type.Fields);
BuildPropertyHtml(type.Properties.Where(x => !x.IsInherited));
BuildMethodHtml(type.Methods.Where(x => !x.IsInherited));
BuildEventHtml(type.Events.Where(x => !x.IsInherited));
}
}
AddExceptionSection(html, xmlDoc);
Save(html, title, type.UriPath, type.FilePath, type.Assembly);
}
var packagePath = Path.Combine(_outputPath, "package.xml");
Directory.CreateDirectory(Path.GetDirectoryName(packagePath));
using(var stream = File.Create(packagePath)) {
using(var writer = new StreamWriter(stream)) {
writer.Write(package.ToPrettyString());
}
}
}
private void BuildInterfaceBlock(XDoc html, ReflectedTypeInfo type) {
if(type.Interfaces.Any()) {
html.StartNameValueBlock("implements", "Implements")
.Start("ul");
foreach(var interfaceParameter in type.Interfaces) {
html.Start("li");
BuildParameterMarkup(html, interfaceParameter);
html.End();
}
html.End() // ul
.EndNameValue();
}
if(type.Kind == TypeKind.Interface) {
var implementers = (from t in _types where t.Interfaces.Where(x => x.Type == type).Any() select t).ToList();
if(implementers.Any()) {
html.StartNameValueBlock("implementors", "Implementors")
.Start("ul");
foreach(var implementor in implementers) {
html.Start("li");
if(IsTypeInDocumentation(implementor)) {
html.Link(implementor.UriPath, implementor.DisplayName);
} else {
html.Value(implementor.DisplayName);
}
html.End();
}
html.End() // ul
.EndNameValue();
}
}
}
private void EnsureNamespaceRootDocument(string ns) {
if(_documentedNamespaces.Add(ns)) {
var html = NewHtmlDocument(ns, false).Start("div").Attr("class", "doctree").Value("{{wiki.tree()}}").End();
Save(html, ns, "//" + ns, "ns." + ns + ".xml", null);
}
}
public void AddAssembly(string assemblyPath) {
string assembly = _typeInspector.InspectAssembly(assemblyPath);
_assemblies.Add(assembly, assemblyPath);
}
protected IEnumerable<ReflectedTypeInfo> GetTypes() {
_log.Debug("getting types");
var types = _typeInspector.Types;
_log.Debug("build type lookup");
foreach(ReflectedTypeInfo type in types) {
_memberLookup[type.Signature] = type;
foreach(var ctor in type.Constructors) {
_memberLookup[ctor.Signature] = ctor;
}
foreach(var field in type.Fields) {
if(!field.IsInherited) {
_memberLookup[field.Signature] = field;
}
}
foreach(var method in type.Methods) {
if(!method.IsInherited) {
_memberLookup[method.Signature] = method;
}
}
foreach(var property in type.Properties) {
if(!property.IsInherited) {
_memberLookup[property.Signature] = property;
}
}
}
_log.Debug("rewriting xml documentation links");
foreach(var assemblyPath in _assemblies.Values) {
string docPath = Path.Combine(Path.GetDirectoryName(assemblyPath), Path.GetFileNameWithoutExtension(assemblyPath) + ".xml");
if(File.Exists(docPath)) {
XDoc xmlDocumentation = XDocFactory.LoadFrom(docPath, MimeType.TEXT_XML);
foreach(XDoc see in xmlDocumentation[".//see"]) {
string cref = see["@cref"].AsText;
if(!string.IsNullOrEmpty(cref)) {
var info = GetTypeInfo(cref);
if(info == null) {
see.Replace(new XDoc("b").Value(cref));
} else if(IsTypeInDocumentation(info.Type)) {
see.Replace(new XDoc("a").Attr("href.path", info.UriPath).Value(info.LongDisplayName));
} else {
see.Replace(new XDoc("b").Value(info.LongDisplayName));
}
}
string langword = see["@langword"].AsText;
if(!string.IsNullOrEmpty(langword)) {
see.Replace(new XDoc("b").Value(langword));
continue;
}
}
foreach(XDoc member in xmlDocumentation["members/member"]) {
string signature = member["@name"].AsText;
_documentationBySignature[signature] = member;
}
}
}
_log.Debug("finished building type lookup");
return types.Where(IsTypeInDocumentation).ToList();
}
protected void InitNamespaces(string[] namespaces) {
_namespaces.Clear();
_documentedNamespaces.Clear();
foreach(string ns in namespaces) {
_namespaces.Add(ns);
}
}
protected bool IsTypeInDocumentation(ReflectedTypeInfo x) {
if(_assemblies.ContainsKey(x.Assembly)) {
if(!_namespaces.Any()) {
return true;
}
foreach(string ns in _namespaces) {
if(x.Namespace.StartsWith(ns)) {
return true;
}
}
}
return false;
}
protected XDoc GetDoc(string signature) {
XDoc doc;
if(!_documentationBySignature.TryGetValue(signature, out doc)) {
doc = XDoc.Empty;
}
return doc;
}
protected IReflectedInfo GetTypeInfo(string signature) {
IReflectedInfo info;
_memberLookup.TryGetValue(signature, out info);
return info;
}
protected IReflectedInfo GetMember(string signature) {
IReflectedInfo member;
if(!_memberLookup.TryGetValue(signature, out member)) {
return null;
}
return member;
}
public void Dispose() {
_typeInspector.Dispose();
}
private void AddExceptionSection(XDoc html, XDoc xmlDoc) {
var exceptions = xmlDoc["exception"];
if(exceptions.ListLength == 0) {
return;
}
html.StartSection(1, "exceptions", "Exceptions")
.Start("table")
.Start("tr").Elem("th", "Exception").Elem("th", "Condition");
foreach(var exception in exceptions) {
var cref = exception["@cref"].AsText;
var info = GetTypeInfo(cref);
if(info == null) {
continue;
}
html.Start("tr")
.Start("td");
if(IsTypeInDocumentation(info.Type)) {
html.Link(info.UriPath, info.DisplayName);
} else {
html.Value(info.DisplayName);
}
html.End() // td
.Start("td").AddNodes(exception).End()
.End(); // tr
}
html.End() // table
.EndSection();
}
private void BuildEnumFields(XDoc html, IEnumerable<ReflectedFieldInfo> fields) {
html.Heading(1, "Members")
.Start("table")
.Start("tr").Elem("th", "Name").Elem("th", "Description").End();
foreach(var field in fields.Where(x => x.Name != "value__")) {
var xmlDoc = GetDoc(field.Signature);
html.Start("tr")
.Elem("td", field.Name)
.Start("td").AddNodes(xmlDoc["summary"]).End()
.End();
}
html.End();
}
private void BuildGenericParameterSection(int level, XDoc html, XDoc xmlDoc, IEnumerable<ReflectedGenericParameterInfo> genericParameters) {
if(genericParameters.Any()) {
html.StartSection(level, "genericparameters", "Generic Parameters");
foreach(var parameter in genericParameters.OrderBy(x => x.ParameterPosition)) {
html.StartSection(level + 1, "genericparameter", "Parameter " + parameter.Name)
.Div("description", xmlDoc[string.Format("typeparam[@name='{0}']", parameter.Name)])
.StartNameValueBlock("constraints", "Constraints");
var constraints = new List<string>();
if(parameter.MustBeReferenceType) {
constraints.Add("class");
}
if(parameter.MustBeValueType) {
constraints.Add("struct");
}
if(parameter.MustHaveDefaultConstructor) {
constraints.Add("new()");
}
if(constraints.Any() || parameter.Types.Any()) {
html.Start("ul");
foreach(var constraint in constraints) {
html.Start("li").Elem("b", constraint).End();
}
foreach(var parameterType in parameter.Types) {
html.Start("li");
BuildParameterMarkup(html, parameterType);
html.End();
}
html.End(); // ul
} else {
html.Elem("i", "none");
}
html.EndNameValue()
.EndSection();
}
html.EndSection();
}
}
private void BuildParameterMarkup(XDoc html, ReflectedParameterTypeInfo parameterType) {
if(parameterType.IsGenericType) {
if(IsTypeInDocumentation(parameterType.Type)) {
html.Link(parameterType.Type.UriPath, parameterType.Type.Name);
} else {
html.Value(parameterType.Type.Name);
}
html.Value("<");
bool first = true;
foreach(var childParam in parameterType.Parameters) {
if(!first) {
html.Value(",");
}
first = false;
BuildParameterMarkup(html, childParam);
}
html.Value(">");
} else {
if(!parameterType.IsGenericParameter && IsTypeInDocumentation(parameterType.Type)) {
html.Link(parameterType.Type.UriPath, parameterType.DisplayName);
} else {
html.Value(parameterType.DisplayName);
}
}
}
private void BuildInheritanceChain(XDoc html, ReflectedTypeInfo type) {
html.StartNameValueBlock("inheritance", "Type Hierarchy");
var chain = GetParents(type.BaseType).ToList();
foreach(var link in chain) {
html.Start("ul")
.Start("li");
BuildParameterMarkup(html, link);
html.End(); // li
}
html.Start("ul")
.Start("li").Elem("b", type.DisplayName).End();
var subclasses = (from t in _types
where t.BaseType != null && !t.BaseType.IsGenericParameter && t.BaseType.Type == type
select t).ToList();
if(subclasses.Any()) {
html.Start("ul");
foreach(var subclass in subclasses) {
html.Start("li");
if(IsTypeInDocumentation(subclass)) {
html.Link(subclass.UriPath, subclass.DisplayName);
} else {
html.Value(subclass.DisplayName);
}
html.End(); // li
}
html.End(); // subclass ul
}
html.End(); // type ul
for(var i = 0; i < chain.Count; i++) {
html.End();
}
html.EndNameValue();
}
private IEnumerable<ReflectedParameterTypeInfo> GetParents(ReflectedParameterTypeInfo type) {
if(type == null) {
yield break;
}
foreach(var parent in GetParents(type.Type.BaseType)) {
yield return parent;
}
yield return type;
}
private void BuildParameterTable(XDoc html, XDoc xmlDoc, IEnumerable<ReflectedParameterInfo> parameters) {
html.StartSection(2, "parameters", "Parameters")
.Start("table")
.Start("tr").Elem("th", "Name").Elem("th", "Type").Elem("th", "Description").End();
foreach(var parameter in parameters.OrderBy(x => x.ParameterPosition)) {
html.Start("tr")
.Start("td").Elem("b", parameter.Name).End()
.Start("td");
if(parameter.IsOut) {
html.Value("out ");
} else if(parameter.IsRef) {
html.Value("ref ");
} else if(parameter.IsParams) {
html.Value("params ");
}
BuildParameterMarkup(html, parameter.Type);
html
.End() // td
.Start("td").AddNodes(xmlDoc[string.Format("param[@name='{0}']", parameter.Name)]).End()
.End(); // tr
}
html
.End() //table
.EndSection();
}
private void BuildMethodHtml(IEnumerable<ReflectedMethodInfo> methods) {
var q = from m in methods
where !m.IsInherited
group m by m.Name
into overloads
select overloads;
foreach(var memberOverloads in q) {
XDoc html = null;
string href = null;
string path = null;
string title = null;
string assembly = null;
foreach(var method in memberOverloads.OrderBy(x => x.DisplayName)) {
var xmlDoc = GetDoc(method.Signature);
if(html == null) {
href = method.UriPath;
if(string.IsNullOrEmpty(href)) {
continue;
}
path = method.FilePath;
title = method.Name + (method.IsExtensionMethod ? " Extension" : "") + " Method";
html = NewHtmlDocument(title, true);
assembly = method.Assembly;
}
html
.StartSection(1, "method", method.DisplayName)
.CSharpBlock(method.CodeSignature)
.Div("summary", xmlDoc["summary"])
.Section(2, "remarks", "Remarks", xmlDoc["remarks"]);
BuildGenericParameterSection(2, html, xmlDoc, method.GenericParameters.Where(x => x.MethodParameter));
BuildParameterTable(html, xmlDoc, method.Parameters);
html.StartSection(2, "returns", "Returns");
if(!method.ReturnType.IsGenericParameter && method.ReturnType.Type.Name == "Void") {
html.Value("void");
} else {
html.StartNameValueLine("type", "Type");
BuildParameterMarkup(html, method.ReturnType);
html.EndNameValue()
.Start("div")
.Attr("class", "summary")
.AddNodes(xmlDoc["returns"])
.End();
}
html.EndSection(); // return section
AddExceptionSection(html, xmlDoc);
html.EndSection();
}
if(html != null) {
Save(html, title, href, path, assembly);
}
}
}
private void BuildPropertyHtml(IEnumerable<ReflectedPropertyInfo> properties) {
var q = from p in properties
where !p.IsInherited
group p by p.Name
into overloads
select overloads;
foreach(var memberOverloadsEnumerable in q) {
XDoc html = null;
string href = null;
string path = null;
string title = null;
string assembly = null;
var memberOverloads = memberOverloadsEnumerable.ToList();
foreach(var member in memberOverloads.OrderBy(x => x.DisplayName)) {
var xmlDoc = GetDoc(member.Signature);
if(html == null) {
href = member.UriPath;
if(string.IsNullOrEmpty(href)) {
continue;
}
path = member.FilePath;
title = member.Name + " Property";
html = NewHtmlDocument(title, true);
assembly = member.Assembly;
}
html.StartSection(1, "property", member.DisplayName);
html.CSharpBlock(member.CodeSignature)
.Div("summary", xmlDoc["summary"])
.Section(2, "remarks", "Remarks", xmlDoc["remarks"]);
if(member.IsIndexer) {
BuildParameterTable(html, xmlDoc, member.IndexerParameters);
}
html.StartSection(2, "returns", "Value");
html.StartNameValueLine("type", "Type");
BuildParameterMarkup(html, member.ReturnType);
html.EndNameValue()
.Start("div")
.Attr("class", "summary")
.AddNodes(xmlDoc["returns"])
.End()
.EndSection(); // returns section
AddExceptionSection(html, xmlDoc);
html.EndSection();
}
if(html != null) {
Save(html, title, href, path, assembly);
}
}
}
private void BuildFieldHtml(IEnumerable<ReflectedFieldInfo> fields) {
foreach(var field in fields.Where(x => !x.IsInherited).OrderBy(x => x.DisplayName)) {
var xmlDoc = GetDoc(field.Signature);
var href = field.UriPath;
var path = field.FilePath;
if(string.IsNullOrEmpty(href)) {
return;
}
var title = field.DisplayName + " Field";
var html = NewHtmlDocument(title, true);
html.CSharpBlock(field.CodeSignature)
.Div("summary", xmlDoc["summary"])
.Section(1, "remarks", "Remarks", xmlDoc["remarks"]);
html.StartSection(1, "returns", "Type");
BuildParameterMarkup(html, field.ReturnType);
html.EndSection();
Save(html, title, href, path, field.Assembly);
}
}
private void BuildEventHtml(IEnumerable<ReflectedEventInfo> events) {
foreach(var ev in events.Where(x => !x.IsInherited).OrderBy(x => x.DisplayName)) {
var xmlDoc = GetDoc(ev.Signature);
var href = ev.UriPath;
var path = ev.FilePath;
if(string.IsNullOrEmpty(href)) {
return;
}
var title = ev.DisplayName + " Event";
var html = NewHtmlDocument(title, true);
html.CSharpBlock(ev.CodeSignature)
.Div("summary", xmlDoc["summary"])
.Section(1, "remarks", "Remarks", xmlDoc["remarks"]);
html.StartSection(1, "returns", "Handler");
BuildParameterMarkup(html, ev.ReturnType);
html.EndSection();
Save(html, title, href, path, ev.Assembly);
}
}
private void BuildConstructorHtml(IEnumerable<ReflectedConstructorInfo> ctors) {
XDoc html = null;
string href = null;
string path = null;
string title = null;
string assembly = null;
foreach(var ctor in ctors.OrderBy(x => x.DisplayName)) {
var xmlDoc = GetDoc(ctor.Signature);
if(html == null) {
href = ctor.UriPath;
if(string.IsNullOrEmpty(href)) {
continue;
}
path = ctor.FilePath;
title = ctor.Type.Name + " Constructors";
html = NewHtmlDocument(title, true);
assembly = ctor.Assembly;
}
html.StartSection(1, "ctor", ctor.DisplayName)
.CSharpBlock(ctor.CodeSignature)
.Div("summary", xmlDoc["summary"])
.Section(2, "remarks", "Remarks", xmlDoc["remarks"]);
BuildParameterTable(html, xmlDoc, ctor.Parameters);
AddExceptionSection(html, xmlDoc);
html.EndSection();
}
if(html != null) {
Save(html, title, href, path, assembly);
}
}
private void AddMemberTables(XDoc html, ReflectedTypeInfo type) {
if(!type.Constructors.Any() && !type.Fields.Any() && !type.Properties.Any() && !type.Methods.Any() && !type.Events.Any()) {
return;
}
html.StartSection(1, "members", "Members");
if(type.Constructors.Any()) {
html.StartSection(2, "ctors", "Constructors")
.Start("table")
.Start("tr").Elem("th", "Visibility").Elem("th", "Description").End();
foreach(var member in type.Constructors.OrderBy(x => x.DisplayName)) {
BuildConstructorRow(html, member);
}
html.End() // table
.EndSection();
}
if(type.Fields.Any()) {
html.StartSection(2, "fields", "Fields")
.Start("table")
.Start("tr").Elem("th", "Visibility").Elem("th", "Description").End();
foreach(var member in type.Fields.OrderBy(x => x.DisplayName)) {
BuildFieldRow(html, member);
}
html.End() // table
.EndSection();
}
if(type.Properties.Any()) {
html.StartSection(2, "properties", "Properties")
.Start("table")
.Start("tr").Elem("th", "Visibility").Elem("th", "Description").End();
foreach(var member in type.Properties.OrderBy(x => x.DisplayName)) {
BuildPropertyRow(html, member);
}
html.End() // table
.EndSection();
}
if(type.Methods.Any()) {
html.StartSection(2, "methods", "Methods")
.Start("table")
.Start("tr").Elem("th", "Visibility").Elem("th", "Description").End();
foreach(var member in type.Methods.OrderBy(x => x.DisplayName)) {
BuildMethodRow(html, member);
}
html.End() // table
.EndSection();
}
if(type.Events.Any()) {
html.StartSection(2, "events", "Events")
.Start("table")
.Start("tr").Elem("th", "Visibility").Elem("th", "Description").End();
foreach(var member in type.Events.OrderBy(x => x.DisplayName)) {
BuildEventRow(html, member);
}
html.End() // table
.EndSection();
}
html.EndSection(); //members
}
private void BuildEventRow(XDoc html, ReflectedEventInfo member) {
var xmlDoc = GetDoc(member.Signature);
html.Start("tr")
.Elem("td", member.MemberAccess)
.Start("td").StartSpan("member");
if(IsTypeInDocumentation(member.DeclaringType)) {
html.Link(member.UriPath, member.DisplayName);
} else {
html.Value(member.DisplayName);
}
html
.EndSpan()
.StartSpan("description");
if(member.IsOverride) {
html.Value("(Override)");
}
html.AddNodes(xmlDoc["summary"]);
if(member.IsInherited) {
html.Value(string.Format("(Inherited from {0})", member.DeclaringType.DisplayName));
}
html
.EndSpan()
.End() // td
.End(); // tr
}
private void BuildMethodRow(XDoc html, ReflectedMethodInfo member) {
var xmlDoc = GetDoc(member.Signature);
html.Start("tr")
.Elem("td", member.MemberAccess)
.Start("td").StartSpan("member");
if(IsTypeInDocumentation(member.DeclaringType)) {
html.Link(member.UriPath, member.DisplayName);
} else {
html.Value(member.DisplayName);
}
html
.EndSpan()
.StartSpan("description");
if(member.IsOverride && !member.IsInherited) {
html.Value("(Override)");
}
if(member.IsExtensionMethod) {
html.Value("(Extension)");
}
html.AddNodes(xmlDoc["summary"]);
if(member.IsInherited) {
html.Value(string.Format("(Inherited from {0})", member.DeclaringType.DisplayName));
}
html
.EndSpan()
.End() // td
.End(); // tr
}
private void BuildPropertyRow(XDoc html, ReflectedPropertyInfo member) {
var xmlDoc = GetDoc(member.Signature);
html.Start("tr")
.Elem("td", member.MemberAccess)
.Start("td").StartSpan("member");
if(IsTypeInDocumentation(member.DeclaringType)) {
html.Link(member.UriPath, member.DisplayName);
} else {
html.Value(member.DisplayName);
}
html
.EndSpan()
.StartSpan("description");
if(member.IsOverride && !member.IsInherited) {
html.Value("(Override)");
}
html.AddNodes(xmlDoc["summary"]);
if(member.IsInherited) {
html.Value(string.Format("(Inherited from {0})", member.DeclaringType.DisplayName));
}
html
.EndSpan()
.End() // td
.End(); // tr
}
private void BuildConstructorRow(XDoc html, ReflectedConstructorInfo member) {
var xmlDoc = GetDoc(member.Signature);
html.Start("tr")
.Elem("td", member.MemberAccess)
.Start("td")
.StartSpan("member").Link(member.UriPath, member.DisplayName).EndSpan()
.StartSpan("description").AddNodes(xmlDoc["summary"]).EndSpan()
.End()
.End();
}
private void BuildFieldRow(XDoc html, ReflectedFieldInfo member) {
var xmlDoc = GetDoc(member.Signature);
html.Start("tr")
.Elem("td", member.MemberAccess)
.Start("td").StartSpan("member");
if(IsTypeInDocumentation(member.DeclaringType)) {
html.Link(member.UriPath, member.DisplayName);
} else {
html.Value(member.DisplayName);
}
html
.EndSpan()
.StartSpan("description").AddNodes(xmlDoc["summary"]).EndSpan()
.End() // td
.End(); // tr
}
private XDoc NewHtmlDocument(string title, bool includeToc) {
var html = new XDoc("content")
.Attr("type", "application/x.deki-text")
.Attr("title", title)
.Attr("unsafe", false)
.Start("body")
.UsePrefix("eval", "http://mindtouch.com/2007/dekiscript")
.Start("div").Attr("class", "xdocs");
if(includeToc) {
html.Elem("div", "{{DocToc()}}");
}
return html;
}
private void Save(XDoc html, string title, string href, string path, string assembly) {
html.EndAll(); // xdocs div
var filepath = Path.Combine("relative", path);
_fileMap.Start("item").Attr("dataid", _currentDataId).Attr("path", filepath).End();
_manifest.Start("page")
.Attr("dataid", _currentDataId);
if(!string.IsNullOrEmpty(title)) {
_manifest.Elem("title", title);
}
_manifest
.Elem("path", href)
.Start("contents").Attr("type", "application/x.deki0805+xml").End()
.End();
filepath = Path.Combine(_outputPath, filepath);
Directory.CreateDirectory(Path.GetDirectoryName(filepath));
using(var stream = File.Create(filepath)) {
using(var writer = new StreamWriter(stream)) {
writer.Write(html.ToPrettyString());
writer.Close();
}
stream.Close();
}
_currentDataId++;
if(string.IsNullOrEmpty(assembly)) {
return;
}
// add assembly tag to file
var assemblyString = "assembly:" + assembly;
var tagDoc = new XDoc("tags")
.Attr("count", 1)
.Start("tag")
.Attr("value", assemblyString)
.Elem("type", "text")
.Elem("title", assemblyString)
.End();
filepath = Path.Combine("relative", Path.GetFileNameWithoutExtension(path) + ".tags");
_fileMap.Start("item").Attr("dataid", _currentDataId).Attr("path", filepath).End();
_manifest.Start("tags")
.Attr("dataid", _currentDataId)
.Elem("path", href)
.End();
filepath = Path.Combine(_outputPath, filepath);
using(var stream = File.Create(filepath)) {
using(var writer = new StreamWriter(stream)) {
writer.Write(tagDoc.ToPrettyString());
writer.Close();
}
stream.Close();
}
_currentDataId++;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: route_guide.proto
// Original file comments:
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace Routeguide {
/// <summary>
/// Interface exported by the server.
/// </summary>
public static class RouteGuide
{
static readonly string __ServiceName = "routeguide.RouteGuide";
static readonly Marshaller<global::Routeguide.Point> __Marshaller_Point = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.Point.Parser.ParseFrom);
static readonly Marshaller<global::Routeguide.Feature> __Marshaller_Feature = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.Feature.Parser.ParseFrom);
static readonly Marshaller<global::Routeguide.Rectangle> __Marshaller_Rectangle = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.Rectangle.Parser.ParseFrom);
static readonly Marshaller<global::Routeguide.RouteSummary> __Marshaller_RouteSummary = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.RouteSummary.Parser.ParseFrom);
static readonly Marshaller<global::Routeguide.RouteNote> __Marshaller_RouteNote = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.RouteNote.Parser.ParseFrom);
static readonly Method<global::Routeguide.Point, global::Routeguide.Feature> __Method_GetFeature = new Method<global::Routeguide.Point, global::Routeguide.Feature>(
MethodType.Unary,
__ServiceName,
"GetFeature",
__Marshaller_Point,
__Marshaller_Feature);
static readonly Method<global::Routeguide.Rectangle, global::Routeguide.Feature> __Method_ListFeatures = new Method<global::Routeguide.Rectangle, global::Routeguide.Feature>(
MethodType.ServerStreaming,
__ServiceName,
"ListFeatures",
__Marshaller_Rectangle,
__Marshaller_Feature);
static readonly Method<global::Routeguide.Point, global::Routeguide.RouteSummary> __Method_RecordRoute = new Method<global::Routeguide.Point, global::Routeguide.RouteSummary>(
MethodType.ClientStreaming,
__ServiceName,
"RecordRoute",
__Marshaller_Point,
__Marshaller_RouteSummary);
static readonly Method<global::Routeguide.RouteNote, global::Routeguide.RouteNote> __Method_RouteChat = new Method<global::Routeguide.RouteNote, global::Routeguide.RouteNote>(
MethodType.DuplexStreaming,
__ServiceName,
"RouteChat",
__Marshaller_RouteNote,
__Marshaller_RouteNote);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Routeguide.RouteGuideReflection.Descriptor.Services[0]; }
}
/// <summary>Client for RouteGuide</summary>
[System.Obsolete("Client side interfaced will be removed in the next release. Use client class directly.")]
public interface IRouteGuideClient
{
/// <summary>
/// A simple RPC.
///
/// Obtains the feature at a given position.
///
/// A feature with an empty name is returned if there's no feature at the given
/// position.
/// </summary>
global::Routeguide.Feature GetFeature(global::Routeguide.Point request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A simple RPC.
///
/// Obtains the feature at a given position.
///
/// A feature with an empty name is returned if there's no feature at the given
/// position.
/// </summary>
global::Routeguide.Feature GetFeature(global::Routeguide.Point request, CallOptions options);
/// <summary>
/// A simple RPC.
///
/// Obtains the feature at a given position.
///
/// A feature with an empty name is returned if there's no feature at the given
/// position.
/// </summary>
AsyncUnaryCall<global::Routeguide.Feature> GetFeatureAsync(global::Routeguide.Point request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A simple RPC.
///
/// Obtains the feature at a given position.
///
/// A feature with an empty name is returned if there's no feature at the given
/// position.
/// </summary>
AsyncUnaryCall<global::Routeguide.Feature> GetFeatureAsync(global::Routeguide.Point request, CallOptions options);
/// <summary>
/// A server-to-client streaming RPC.
///
/// Obtains the Features available within the given Rectangle. Results are
/// streamed rather than returned at once (e.g. in a response message with a
/// repeated field), as the rectangle may cover a large area and contain a
/// huge number of features.
/// </summary>
AsyncServerStreamingCall<global::Routeguide.Feature> ListFeatures(global::Routeguide.Rectangle request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A server-to-client streaming RPC.
///
/// Obtains the Features available within the given Rectangle. Results are
/// streamed rather than returned at once (e.g. in a response message with a
/// repeated field), as the rectangle may cover a large area and contain a
/// huge number of features.
/// </summary>
AsyncServerStreamingCall<global::Routeguide.Feature> ListFeatures(global::Routeguide.Rectangle request, CallOptions options);
/// <summary>
/// A client-to-server streaming RPC.
///
/// Accepts a stream of Points on a route being traversed, returning a
/// RouteSummary when traversal is completed.
/// </summary>
AsyncClientStreamingCall<global::Routeguide.Point, global::Routeguide.RouteSummary> RecordRoute(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A client-to-server streaming RPC.
///
/// Accepts a stream of Points on a route being traversed, returning a
/// RouteSummary when traversal is completed.
/// </summary>
AsyncClientStreamingCall<global::Routeguide.Point, global::Routeguide.RouteSummary> RecordRoute(CallOptions options);
/// <summary>
/// A Bidirectional streaming RPC.
///
/// Accepts a stream of RouteNotes sent while a route is being traversed,
/// while receiving other RouteNotes (e.g. from other users).
/// </summary>
AsyncDuplexStreamingCall<global::Routeguide.RouteNote, global::Routeguide.RouteNote> RouteChat(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A Bidirectional streaming RPC.
///
/// Accepts a stream of RouteNotes sent while a route is being traversed,
/// while receiving other RouteNotes (e.g. from other users).
/// </summary>
AsyncDuplexStreamingCall<global::Routeguide.RouteNote, global::Routeguide.RouteNote> RouteChat(CallOptions options);
}
/// <summary>Interface of server-side implementations of RouteGuide</summary>
[System.Obsolete("Service implementations should inherit from the generated abstract base class instead.")]
public interface IRouteGuide
{
/// <summary>
/// A simple RPC.
///
/// Obtains the feature at a given position.
///
/// A feature with an empty name is returned if there's no feature at the given
/// position.
/// </summary>
global::System.Threading.Tasks.Task<global::Routeguide.Feature> GetFeature(global::Routeguide.Point request, ServerCallContext context);
/// <summary>
/// A server-to-client streaming RPC.
///
/// Obtains the Features available within the given Rectangle. Results are
/// streamed rather than returned at once (e.g. in a response message with a
/// repeated field), as the rectangle may cover a large area and contain a
/// huge number of features.
/// </summary>
global::System.Threading.Tasks.Task ListFeatures(global::Routeguide.Rectangle request, IServerStreamWriter<global::Routeguide.Feature> responseStream, ServerCallContext context);
/// <summary>
/// A client-to-server streaming RPC.
///
/// Accepts a stream of Points on a route being traversed, returning a
/// RouteSummary when traversal is completed.
/// </summary>
global::System.Threading.Tasks.Task<global::Routeguide.RouteSummary> RecordRoute(IAsyncStreamReader<global::Routeguide.Point> requestStream, ServerCallContext context);
/// <summary>
/// A Bidirectional streaming RPC.
///
/// Accepts a stream of RouteNotes sent while a route is being traversed,
/// while receiving other RouteNotes (e.g. from other users).
/// </summary>
global::System.Threading.Tasks.Task RouteChat(IAsyncStreamReader<global::Routeguide.RouteNote> requestStream, IServerStreamWriter<global::Routeguide.RouteNote> responseStream, ServerCallContext context);
}
/// <summary>Base class for server-side implementations of RouteGuide</summary>
public abstract class RouteGuideBase
{
/// <summary>
/// A simple RPC.
///
/// Obtains the feature at a given position.
///
/// A feature with an empty name is returned if there's no feature at the given
/// position.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Routeguide.Feature> GetFeature(global::Routeguide.Point request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// A server-to-client streaming RPC.
///
/// Obtains the Features available within the given Rectangle. Results are
/// streamed rather than returned at once (e.g. in a response message with a
/// repeated field), as the rectangle may cover a large area and contain a
/// huge number of features.
/// </summary>
public virtual global::System.Threading.Tasks.Task ListFeatures(global::Routeguide.Rectangle request, IServerStreamWriter<global::Routeguide.Feature> responseStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// A client-to-server streaming RPC.
///
/// Accepts a stream of Points on a route being traversed, returning a
/// RouteSummary when traversal is completed.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Routeguide.RouteSummary> RecordRoute(IAsyncStreamReader<global::Routeguide.Point> requestStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// A Bidirectional streaming RPC.
///
/// Accepts a stream of RouteNotes sent while a route is being traversed,
/// while receiving other RouteNotes (e.g. from other users).
/// </summary>
public virtual global::System.Threading.Tasks.Task RouteChat(IAsyncStreamReader<global::Routeguide.RouteNote> requestStream, IServerStreamWriter<global::Routeguide.RouteNote> responseStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for RouteGuide</summary>
#pragma warning disable 0618
public class RouteGuideClient : ClientBase<RouteGuideClient>, IRouteGuideClient
#pragma warning restore 0618
{
public RouteGuideClient(Channel channel) : base(channel)
{
}
public RouteGuideClient(CallInvoker callInvoker) : base(callInvoker)
{
}
///<summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected RouteGuideClient() : base()
{
}
///<summary>Protected constructor to allow creation of configured clients.</summary>
protected RouteGuideClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// A simple RPC.
///
/// Obtains the feature at a given position.
///
/// A feature with an empty name is returned if there's no feature at the given
/// position.
/// </summary>
public virtual global::Routeguide.Feature GetFeature(global::Routeguide.Point request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetFeature(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A simple RPC.
///
/// Obtains the feature at a given position.
///
/// A feature with an empty name is returned if there's no feature at the given
/// position.
/// </summary>
public virtual global::Routeguide.Feature GetFeature(global::Routeguide.Point request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetFeature, null, options, request);
}
/// <summary>
/// A simple RPC.
///
/// Obtains the feature at a given position.
///
/// A feature with an empty name is returned if there's no feature at the given
/// position.
/// </summary>
public virtual AsyncUnaryCall<global::Routeguide.Feature> GetFeatureAsync(global::Routeguide.Point request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetFeatureAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A simple RPC.
///
/// Obtains the feature at a given position.
///
/// A feature with an empty name is returned if there's no feature at the given
/// position.
/// </summary>
public virtual AsyncUnaryCall<global::Routeguide.Feature> GetFeatureAsync(global::Routeguide.Point request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetFeature, null, options, request);
}
/// <summary>
/// A server-to-client streaming RPC.
///
/// Obtains the Features available within the given Rectangle. Results are
/// streamed rather than returned at once (e.g. in a response message with a
/// repeated field), as the rectangle may cover a large area and contain a
/// huge number of features.
/// </summary>
public virtual AsyncServerStreamingCall<global::Routeguide.Feature> ListFeatures(global::Routeguide.Rectangle request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListFeatures(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A server-to-client streaming RPC.
///
/// Obtains the Features available within the given Rectangle. Results are
/// streamed rather than returned at once (e.g. in a response message with a
/// repeated field), as the rectangle may cover a large area and contain a
/// huge number of features.
/// </summary>
public virtual AsyncServerStreamingCall<global::Routeguide.Feature> ListFeatures(global::Routeguide.Rectangle request, CallOptions options)
{
return CallInvoker.AsyncServerStreamingCall(__Method_ListFeatures, null, options, request);
}
/// <summary>
/// A client-to-server streaming RPC.
///
/// Accepts a stream of Points on a route being traversed, returning a
/// RouteSummary when traversal is completed.
/// </summary>
public virtual AsyncClientStreamingCall<global::Routeguide.Point, global::Routeguide.RouteSummary> RecordRoute(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RecordRoute(new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A client-to-server streaming RPC.
///
/// Accepts a stream of Points on a route being traversed, returning a
/// RouteSummary when traversal is completed.
/// </summary>
public virtual AsyncClientStreamingCall<global::Routeguide.Point, global::Routeguide.RouteSummary> RecordRoute(CallOptions options)
{
return CallInvoker.AsyncClientStreamingCall(__Method_RecordRoute, null, options);
}
/// <summary>
/// A Bidirectional streaming RPC.
///
/// Accepts a stream of RouteNotes sent while a route is being traversed,
/// while receiving other RouteNotes (e.g. from other users).
/// </summary>
public virtual AsyncDuplexStreamingCall<global::Routeguide.RouteNote, global::Routeguide.RouteNote> RouteChat(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RouteChat(new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A Bidirectional streaming RPC.
///
/// Accepts a stream of RouteNotes sent while a route is being traversed,
/// while receiving other RouteNotes (e.g. from other users).
/// </summary>
public virtual AsyncDuplexStreamingCall<global::Routeguide.RouteNote, global::Routeguide.RouteNote> RouteChat(CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_RouteChat, null, options);
}
protected override RouteGuideClient NewInstance(ClientBaseConfiguration configuration)
{
return new RouteGuideClient(configuration);
}
}
/// <summary>Creates a new client for RouteGuide</summary>
public static RouteGuideClient NewClient(Channel channel)
{
return new RouteGuideClient(channel);
}
/// <summary>Creates service definition that can be registered with a server</summary>
#pragma warning disable 0618
public static ServerServiceDefinition BindService(IRouteGuide serviceImpl)
#pragma warning restore 0618
{
return ServerServiceDefinition.CreateBuilder(__ServiceName)
.AddMethod(__Method_GetFeature, serviceImpl.GetFeature)
.AddMethod(__Method_ListFeatures, serviceImpl.ListFeatures)
.AddMethod(__Method_RecordRoute, serviceImpl.RecordRoute)
.AddMethod(__Method_RouteChat, serviceImpl.RouteChat).Build();
}
/// <summary>Creates service definition that can be registered with a server</summary>
#pragma warning disable 0618
public static ServerServiceDefinition BindService(RouteGuideBase serviceImpl)
#pragma warning restore 0618
{
return ServerServiceDefinition.CreateBuilder(__ServiceName)
.AddMethod(__Method_GetFeature, serviceImpl.GetFeature)
.AddMethod(__Method_ListFeatures, serviceImpl.ListFeatures)
.AddMethod(__Method_RecordRoute, serviceImpl.RecordRoute)
.AddMethod(__Method_RouteChat, serviceImpl.RouteChat).Build();
}
}
}
#endregion
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// James Driscoll, mailto:[email protected]
//
// 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
[assembly: Elmah.Scc("$Id: AccessErrorLog.cs 642 2009-06-01 17:41:53Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using IDictionary = System.Collections.IDictionary;
using System.Collections.Generic;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses Microsoft Access
/// as its backing store.
/// </summary>
/// <remarks>
/// The MDB file is automatically created at the path specified in the
/// connection string if it does not already exist.
/// </remarks>
public class AccessErrorLog : ErrorLog
{
private readonly string _connectionString;
private const int _maxAppNameLength = 60;
private const string _scriptResourceName = "mkmdb.vbs";
private static readonly object _mdbInitializationLock = new object();
/// <summary>
/// Initializes a new instance of the <see cref="AccessErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public AccessErrorLog(IDictionary config)
{
if (config == null)
throw new ArgumentNullException("config");
string connectionString = ConnectionStringHelper.GetConnectionString(config);
//
// If there is no connection string to use then throw an
// exception to abort construction.
//
if (connectionString.Length == 0)
throw new ApplicationException("Connection string is missing for the Access error log.");
_connectionString = connectionString;
InitializeDatabase();
//
// Set the application name as this implementation provides
// per-application isolation over a single store.
//
string appName = config.Find("applicationName", string.Empty);
if (appName.Length > _maxAppNameLength)
{
throw new ApplicationException(string.Format(
"Application name is too long. Maximum length allowed is {0} characters.",
_maxAppNameLength.ToString("N0")));
}
ApplicationName = appName;
}
/// <summary>
/// Initializes a new instance of the <see cref="AccessErrorLog"/> class
/// to use a specific connection string for connecting to the database.
/// </summary>
public AccessErrorLog(string connectionString)
{
if (connectionString == null)
throw new ArgumentNullException("connectionString");
if (connectionString.Length == 0)
throw new ArgumentException(null, "connectionString");
_connectionString = connectionString;
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "Microsoft Access Error Log"; }
}
/// <summary>
/// Gets the connection string used by the log to connect to the database.
/// </summary>
public virtual string ConnectionString
{
get { return _connectionString; }
}
/// <summary>
/// Logs an error to the database.
/// </summary>
/// <remarks>
/// Use the stored procedure called by this implementation to set a
/// policy on how long errors are kept in the log. The default
/// implementation stores all errors for an indefinite time.
/// </remarks>
public override string Log(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
string errorXml = ErrorXml.EncodeString(error);
using (OleDbConnection connection = new OleDbConnection(this.ConnectionString))
using (OleDbCommand command = connection.CreateCommand())
{
connection.Open();
command.CommandType = CommandType.Text;
command.CommandText = @"INSERT INTO ELMAH_Error
(Application, Host, Type, Source,
Message, UserName, StatusCode, TimeUtc, AllXml)
VALUES
(@Application, @Host, @Type, @Source,
@Message, @UserName, @StatusCode, @TimeUtc, @AllXml)";
command.CommandType = CommandType.Text;
OleDbParameterCollection parameters = command.Parameters;
parameters.Add("@Application", OleDbType.VarChar, _maxAppNameLength).Value = ApplicationName;
parameters.Add("@Host", OleDbType.VarChar, 30).Value = error.HostName;
parameters.Add("@Type", OleDbType.VarChar, 100).Value = error.Type;
parameters.Add("@Source", OleDbType.VarChar, 60).Value = error.Source;
parameters.Add("@Message", OleDbType.LongVarChar, error.Message.Length).Value = error.Message;
parameters.Add("@User", OleDbType.VarChar, 50).Value = error.User;
parameters.Add("@StatusCode", OleDbType.Integer).Value = error.StatusCode;
parameters.Add("@TimeUtc", OleDbType.Date).Value = error.Time.ToUniversalTime();
parameters.Add("@AllXml", OleDbType.LongVarChar, errorXml.Length).Value = errorXml;
command.ExecuteNonQuery();
using (OleDbCommand identityCommand = connection.CreateCommand())
{
identityCommand.CommandType = CommandType.Text;
identityCommand.CommandText = "SELECT @@IDENTITY";
return Convert.ToString(identityCommand.ExecuteScalar(), CultureInfo.InvariantCulture);
}
}
}
/// <summary>
/// Returns a page of errors from the databse in descending order
/// of logged time.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
using (OleDbConnection connection = new OleDbConnection(this.ConnectionString))
using (OleDbCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "SELECT COUNT(*) FROM ELMAH_Error";
connection.Open();
int totalCount = (int)command.ExecuteScalar();
if (errorEntryList != null && pageIndex * pageSize < totalCount)
{
int maxRecords = pageSize * (pageIndex + 1);
if (maxRecords > totalCount)
{
maxRecords = totalCount;
pageSize = totalCount - pageSize * (totalCount / pageSize);
}
StringBuilder sql = new StringBuilder(1000);
sql.Append("SELECT e.* FROM (");
sql.Append("SELECT TOP ");
sql.Append(pageSize.ToString());
sql.Append(" TimeUtc, ErrorId FROM (");
sql.Append("SELECT TOP ");
sql.Append(maxRecords.ToString());
sql.Append(" TimeUtc, ErrorId FROM ELMAH_Error ");
sql.Append("ORDER BY TimeUtc DESC, ErrorId DESC) ");
sql.Append("ORDER BY TimeUtc ASC, ErrorId ASC) AS i ");
sql.Append("INNER JOIN Elmah_Error AS e ON i.ErrorId = e.ErrorId ");
sql.Append("ORDER BY e.TimeUtc DESC, e.ErrorId DESC");
command.CommandText = sql.ToString();
using (OleDbDataReader reader = command.ExecuteReader())
{
Debug.Assert(reader != null);
while (reader.Read())
{
var id = Convert.ToString(reader["ErrorId"], CultureInfo.InvariantCulture);
var error = new Error
{
ApplicationName = reader["Application"].ToString(),
HostName = reader["Host"].ToString(),
Type = reader["Type"].ToString(),
Source = reader["Source"].ToString(),
Message = reader["Message"].ToString(),
User = reader["UserName"].ToString(),
StatusCode = Convert.ToInt32(reader["StatusCode"]),
Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime()
};
errorEntryList.Add(new ErrorLogEntry(this, id, error));
}
reader.Close();
}
}
return totalCount;
}
}
/// <summary>
/// Returns the specified error from the database, or null
/// if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
if (id == null)
throw new ArgumentNullException("id");
if (id.Length == 0)
throw new ArgumentException(null, "id");
int errorId;
try
{
errorId = int.Parse(id, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
throw new ArgumentException(e.Message, "id", e);
}
catch (OverflowException e)
{
throw new ArgumentException(e.Message, "id", e);
}
string errorXml;
using (OleDbConnection connection = new OleDbConnection(this.ConnectionString))
using (OleDbCommand command = connection.CreateCommand())
{
command.CommandText = @"SELECT AllXml
FROM ELMAH_Error
WHERE ErrorId = @ErrorId";
command.CommandType = CommandType.Text;
OleDbParameterCollection parameters = command.Parameters;
parameters.Add("@ErrorId", OleDbType.Integer).Value = errorId;
connection.Open();
errorXml = (string)command.ExecuteScalar();
}
if (errorXml == null)
return null;
Error error = ErrorXml.DecodeString(errorXml);
return new ErrorLogEntry(this, id, error);
}
private void InitializeDatabase()
{
string connectionString = ConnectionString;
Debug.AssertStringNotEmpty(connectionString);
string dbFilePath = ConnectionStringHelper.GetDataSourceFilePath(connectionString);
if (File.Exists(dbFilePath))
return;
//
// Make sure that we don't have multiple instances trying to create the database.
//
lock (_mdbInitializationLock)
{
//
// Just double-check that no other thread has created the database while
// we were waiting for the lock.
//
if (File.Exists(dbFilePath))
return;
//
// Create a temporary copy of the mkmdb.vbs script.
// We do this in the same directory as the resulting database for security permission purposes.
//
string scriptPath = Path.Combine(Path.GetDirectoryName(dbFilePath), _scriptResourceName);
using (FileStream scriptStream = new FileStream(scriptPath, FileMode.Create, FileAccess.Write, FileShare.None))
{
ManifestResourceHelper.WriteResourceToStream(scriptStream, _scriptResourceName);
}
//
// Run the script file to create the database using batch
// mode (//B), which suppresses script errors and prompts
// from displaying.
//
ProcessStartInfo psi = new ProcessStartInfo(
"cscript", scriptPath + " \"" + dbFilePath + "\" //B //NoLogo");
psi.UseShellExecute = false; // i.e. CreateProcess
psi.CreateNoWindow = true; // Stay lean, stay mean
try
{
using (Process process = Process.Start(psi))
{
//
// A few seconds should be plenty of time to create the database.
//
TimeSpan tolerance = TimeSpan.FromSeconds(2);
if (!process.WaitForExit((int) tolerance.TotalMilliseconds))
{
//
// but it wasn't, so clean up and throw an exception!
// Realistically, I don't expect to ever get here!
//
process.Kill();
throw new Exception(string.Format(
"The Microsoft Access database creation script took longer than the allocated time of {0} seconds to execute. "
+ "The script was terminated prematurely.",
tolerance.TotalSeconds));
}
if (process.ExitCode != 0)
{
throw new Exception(string.Format(
"The Microsoft Access database creation script failed with exit code {0}.",
process.ExitCode));
}
}
}
finally
{
//
// Clean up after ourselves!!
//
File.Delete(scriptPath);
}
}
}
}
}
| |
using System;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Threading.Tasks;
using Newtonsoft.Json;
using System.Reactive;
using System.Threading.Tasks;
using System.Reflection;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Splat;
namespace Akavache
{
public static class BlobCache
{
static string applicationName;
static BlobCache()
{
Locator.RegisterResolverCallbackChanged(() =>
{
if (Locator.CurrentMutable == null) return;
Locator.CurrentMutable.InitializeAkavache();
});
InMemory = new InMemoryBlobCache(Scheduler.Default);
}
/// <summary>
/// Your application's name. Set this at startup, this defines where
/// your data will be stored (usually at %AppData%\[ApplicationName])
/// </summary>
public static string ApplicationName
{
get
{
if (applicationName == null)
throw new Exception("Make sure to set BlobCache.ApplicationName on startup");
return applicationName;
}
set { applicationName = value; }
}
static IBlobCache localMachine;
static IBlobCache userAccount;
static ISecureBlobCache secure;
static bool shutdownRequested;
[ThreadStatic] static IBlobCache unitTestLocalMachine;
[ThreadStatic] static IBlobCache unitTestUserAccount;
[ThreadStatic] static ISecureBlobCache unitTestSecure;
/// <summary>
/// The local machine cache. Store data here that is unrelated to the
/// user account or shouldn't be uploaded to other machines (i.e.
/// image cache data)
/// </summary>
public static IBlobCache LocalMachine
{
get { return unitTestLocalMachine ?? localMachine ?? (shutdownRequested ? new ShutdownBlobCache() : null) ?? Locator.Current.GetService<IBlobCache>("LocalMachine"); }
set
{
if (ModeDetector.InUnitTestRunner())
{
unitTestLocalMachine = value;
localMachine = localMachine ?? value;
}
else
{
localMachine = value;
}
}
}
/// <summary>
/// The user account cache. Store data here that is associated with
/// the user; in large organizations, this data will be synced to all
/// machines via NT Roaming Profiles.
/// </summary>
public static IBlobCache UserAccount
{
get { return unitTestUserAccount ?? userAccount ?? (shutdownRequested ? new ShutdownBlobCache() : null) ?? Locator.Current.GetService<IBlobCache>("UserAccount"); }
set {
if (ModeDetector.InUnitTestRunner())
{
unitTestUserAccount = value;
userAccount = userAccount ?? value;
}
else
{
userAccount = value;
}
}
}
/// <summary>
/// An IBlobCache that is encrypted - store sensitive data in this
/// cache such as login information.
/// </summary>
public static ISecureBlobCache Secure
{
get { return unitTestSecure ?? secure ?? (shutdownRequested ? new ShutdownBlobCache() : null) ?? Locator.Current.GetService<ISecureBlobCache>(); }
set
{
if (ModeDetector.InUnitTestRunner())
{
unitTestSecure = value;
secure = secure ?? value;
}
else
{
secure = value;
}
}
}
/// <summary>
/// An IBlobCache that simply stores data in memory. Data stored in
/// this cache will be lost when the application restarts.
/// </summary>
public static ISecureBlobCache InMemory { get; set; }
/// <summary>
///
/// </summary>
public static void EnsureInitialized()
{
// NB: This method doesn't actually do anything, it just ensures
// that the static constructor runs
LogHost.Default.Debug("Initializing Akavache");
}
/// <summary>
/// This method shuts down all of the blob caches. Make sure call it
/// on app exit and await / Wait() on it!
/// </summary>
/// <returns>A Task representing when all caches have finished shutting
/// down.</returns>
public static Task Shutdown()
{
shutdownRequested = true;
var toDispose = new[] { LocalMachine, UserAccount, Secure, InMemory, };
var ret = toDispose.Select(x =>
{
x.Dispose();
return x.Shutdown;
}).Merge().ToList().Select(_ => Unit.Default);
return ret.ToTask();
}
#if PORTABLE
static IScheduler TaskpoolOverride;
public static IScheduler TaskpoolScheduler
{
get
{
var ret = TaskpoolOverride ?? Locator.Current.GetService<IScheduler>("Taskpool");
if (ret == null)
{
throw new Exception("Can't find a TaskPoolScheduler. You probably accidentally linked to the PCL Akavache in your app.");
}
return ret;
}
set { TaskpoolOverride = value; }
}
#else
static IScheduler TaskpoolOverride;
public static IScheduler TaskpoolScheduler
{
get { return TaskpoolOverride ?? Locator.Current.GetService<IScheduler>("Taskpool") ?? System.Reactive.Concurrency.TaskPoolScheduler.Default; }
set { TaskpoolOverride = value; }
}
#endif
private class ShutdownBlobCache : ISecureBlobCache
{
public void Dispose()
{
}
public IObservable<Unit> Insert(string key, byte[] data, DateTimeOffset? absoluteExpiration = null)
{
return null;
}
public IObservable<byte[]> Get(string key)
{
return null;
}
public IObservable<IEnumerable<string>> GetAllKeys()
{
return null;
}
public IObservable<DateTimeOffset?> GetCreatedAt(string key)
{
return null;
}
public IObservable<Unit> Flush()
{
return null;
}
public IObservable<Unit> Invalidate(string key)
{
return null;
}
public IObservable<Unit> InvalidateAll()
{
return null;
}
public IObservable<Unit> Vacuum()
{
return null;
}
IObservable<Unit> IBlobCache.Shutdown {
get { return Observable.Return(Unit.Default); }
}
public IScheduler Scheduler {
get { return System.Reactive.Concurrency.Scheduler.Immediate; }
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
public class UnitySmartbodyCharacter : ICharacter
{
#region Constants
public enum DebugFlags
{
Show_Bones = 1,
Show_Axes = 1 << 1,
Show_Eye_Beams = 1 << 2,
}
public delegate void ChannelCallback(UnitySmartbodyCharacter character, string channelName, float value);
#endregion
#region DataMembers
// used for GetBoneAndBaseBonePosition(). Instead of passing back a Vector3, which is a struct, and requires a copy, we wrapped the Vector3 with a class, so that it can be passed back by reference. This function is called so many times, it's worth this optimization
public class Vector3class
{
public Vector3 vector3;
}
public class Quaternionclass
{
public Quaternion quat;
public Quaternionclass() { }
public Quaternionclass(Quaternion _quat)
{
quat = _quat;
}
}
// this struct represents the data that is passed to the smartbody dll wrapper and gets filled out.
// Upon returning from smartbody, the data in this structure is assigned to this character's bones
public struct UnityCharacterData
{
public SmartbodyExternals.SmartbodyCharacterFrameData m_Character;
public IntPtr [] jnames;
public float [] jx;
public float [] jy;
public float [] jz;
public float [] jrw;
public float [] jrx;
public float [] jry;
public float [] jrz;
public float [] jprevx;
public float [] jprevy;
public float [] jprevz;
public float [] jprevrw;
public float [] jprevrx;
public float [] jprevry;
public float [] jprevrz;
public float [] jNextUpdateTime;
}
public UnityCharacterData m_CharacterData = new UnityCharacterData();
public const string SoundNodeName = "SoundNode";
protected int m_characterID;
protected string m_characterType;
protected string m_sbmCharacterName;
protected uint m_DebugFlags;
protected ChannelCallback m_ChannelCB;
const int NumBones = 120;
Transform[] m_Bones;// = new Transform[NumBones];
Vector3class[] m_BaseBonePositions;
Quaternionclass[] m_BaseBoneRotations;
Dictionary<string, int> m_BoneLookupTable = new Dictionary<string, int>(NumBones);
Dictionary<string, List<SkinnedMeshRenderer>> m_BlendShapes = new Dictionary<string, List<SkinnedMeshRenderer>>();
Dictionary<string, string> m_BlendShapeNameMap = new Dictionary<string, string>();
// these are fudge factors for legacy projects for adjusting scale.
// for example, if your incoming smartbody data is in cm, and your level is in feet, you'd call these functions with a parameter of ( 1 / 30.48 )
// These should be considered hacks because changes in scale will cause issues with smartbody
float m_characterPositionScaleModifier;
float m_bonePositionScaleModifier;
AudioSource m_AudioSource;
#endregion
#region Properties
public bool ShowBones
{
get { return VHMath.IsFlagOn(m_DebugFlags, (uint)DebugFlags.Show_Bones); }
}
public bool ShowEyeBeams
{
get { return VHMath.IsFlagOn(m_DebugFlags, (uint)DebugFlags.Show_Eye_Beams); }
}
public bool ShowAxes
{
get { return VHMath.IsFlagOn(m_DebugFlags, (uint)DebugFlags.Show_Axes); }
}
public int GetNumBones
{
get { return m_Bones.Length; }
}
public void ToggleDebugFlag(DebugFlags flag)
{
VHMath.ToggleFlag(ref m_DebugFlags, (uint)flag);
if (flag == DebugFlags.Show_Bones)
{
// stop showing geometry, show the bones
ShowGeometry(!VHMath.IsFlagOn(m_DebugFlags, (uint)DebugFlags.Show_Bones));
}
}
public float CharacterPositionScaleModifier
{
get { return m_characterPositionScaleModifier; }
set { m_characterPositionScaleModifier = value; }
}
public float BonePositionScaleModifier
{
get { return m_bonePositionScaleModifier; }
set { m_bonePositionScaleModifier = value; }
}
public int CharacterID
{
get { return m_characterID; }
set { m_characterID = value; }
}
public string CharacterType
{
get { return m_characterType; }
set { m_characterType = value; }
}
public override string CharacterName
{
get { return SBMCharacterName; }
}
public override AudioSource Voice {
get { return AudioSource; }
}
public string SBMCharacterName
{
get { return m_sbmCharacterName; }
set { m_sbmCharacterName = value; }
}
public AudioSource AudioSource
{
get { return m_AudioSource; }
}
public bool IsSpeaking
{
get { return m_AudioSource != null && m_AudioSource.isPlaying; }
}
public string SkeletonName
{
get { return GetComponent<SmartbodyCharacterInit>().skeletonName; }
}
public string BoneParentName
{
get { return GetComponent<SmartbodyCharacterInit>().unityBoneParent; }
}
#endregion
public void Awake()
{
}
public void Start()
{
//Debug.Log("UnitySmartbodyCharacter.Start()");
// SmartbodyManager is a dependency of this component. Make sure Start() has been called.
SmartbodyManager sbm = SmartbodyManager.Get();
sbm.Start();
m_CharacterData.m_Character = new SmartbodyExternals.SmartbodyCharacterFrameData();
m_CharacterData.m_Character.m_name = IntPtr.Zero;
SmartbodyCharacterInit init = GetComponent<SmartbodyCharacterInit>();
if (init != null)
{
DateTime startTime = DateTime.Now;
SmartbodyFaceDefinition face = GetComponent<SmartbodyFaceDefinition>(); // ok if it's null
SmartbodyJointMap jointMap = GetComponent<SmartbodyJointMap>(); // ok if it's null
GestureMapDefinition gestureMap = GetComponent<GestureMapDefinition>(); // ok if it's null
CreateCharacter(init, face, jointMap, gestureMap);
Debug.Log(string.Format("Finished initializing character {0} in {1} seconds", SBMCharacterName, (DateTime.Now - startTime).TotalSeconds.ToString("f3")));
}
else
{
Debug.LogWarning("UnitySmartbodyCharacter.Start() - " + name + " - No SmartbodyCharacterInit script attached. You need to attach a SmartbodyCharacterInit script to this gameobject so that it will initialize properly");
}
}
public void Update()
{
}
void OnDestroy()
{
//Debug.Log("UnitySmartbodyCharacter.OnDestroy()");
SmartbodyManager sbm = SmartbodyManager.Get();
if (sbm != null)
{
//sbm.PythonCommand(string.Format(@"scene.command('sbm char {0} remove')", SBMCharacterName)); // old-style command
sbm.PythonCommand(string.Format(@"scene.removeCharacter('{0}')", SBMCharacterName));
sbm.RemoveCharacter(this);
}
}
public void OnDrawGizmos()
{
if (ShowEyeBeams)
{
Transform t;
t = GetBone("eyeball_left");
if (t == null ) t = GetBone("JtEyeLf");
Debug.DrawRay(t.position, t.forward, Color.red);
t = GetBone("eyeball_right");
if (t == null ) t = GetBone("JtEyeRt");
Debug.DrawRay(t.position, t.forward, Color.red);
}
if (ShowAxes)
{
for (int i = 0; i < m_Bones.Length; i++)
{
VHUtils.DrawTransformLines(m_Bones[i].transform, 0.025f);
}
}
if (ShowBones)
{
for (int i = 0; i < m_Bones.Length; i++)
{
Gizmos.DrawSphere(m_Bones[i].transform.position, 0.0125f);
if (m_Bones[i].parent != null)
{
Debug.DrawLine(m_Bones[i].transform.position, m_Bones[i].parent.transform.position);
}
}
}
}
#region Functions
public static string FixJointName(string jointName)
{
string fixedName = jointName;
fixedName = fixedName.Replace(".", "");
fixedName = fixedName.Replace(" ", "");
return fixedName;
}
public void GetAllBlendShapes(out Dictionary<string, string> blendShapeNameMap, out Dictionary<string, List<SkinnedMeshRenderer>> blendShapes)
{
blendShapeNameMap = new Dictionary<string, string>();
blendShapes = new Dictionary<string, List<SkinnedMeshRenderer>>();
SkinnedMeshRenderer[] skinnedMeshes = GetComponentsInChildren<SkinnedMeshRenderer>();
for (int skinnedMeshIndex = 0; skinnedMeshIndex < skinnedMeshes.Length; skinnedMeshIndex++)
{
SkinnedMeshRenderer smr = skinnedMeshes[skinnedMeshIndex];
int blendShapeCount = smr.sharedMesh.blendShapeCount;
for (int blendShapeIndex = 0; blendShapeIndex < blendShapeCount; blendShapeIndex++)
{
string blendShapeName = smr.sharedMesh.GetBlendShapeName(blendShapeIndex);
blendShapeName = FixJointName(blendShapeName);
if (!blendShapeNameMap.ContainsKey(blendShapeName))
{
blendShapeNameMap.Add(blendShapeName, smr.sharedMesh.GetBlendShapeName(blendShapeIndex));
}
if (!blendShapes.ContainsKey(blendShapeName))
{
blendShapes.Add(blendShapeName, new List<SkinnedMeshRenderer>());
}
blendShapes[blendShapeName].Add(smr);
}
}
}
public void CreateSkeleton()
{
SmartbodyCharacterInit characterInit = GetComponent<SmartbodyCharacterInit>();
CreateSkeleton(characterInit);
}
public void CreateSkeleton(SmartbodyCharacterInit characterInit)
{
if (characterInit != null)
{
if (characterInit.loadSkeletonFromSk)
return;
SmartbodyManager sbm = SmartbodyManager.Get();
if (sbm.IsSkeletonLoaded(characterInit.skeletonName))
return;
Transform skeletonTransform = VHUtils.FindChild(gameObject, characterInit.unityBoneParent).transform;
bool loadAllChannels = characterInit.loadAllChannels;
List<string> blendShapesList = new List<string>(m_BlendShapes.Keys);
sbm.CreateSkeleton(characterInit.skeletonName, skeletonTransform, loadAllChannels, blendShapesList);
}
else
{
Debug.LogError("Failed to create skeleton because no SmartbodyCharacterInit was found");
}
}
public static void InstantiateMotionSets(SmartbodyMotionSet [] motionSets)
{
// put the referenced MotionSets in the scene if they point to prefabs
// the MotionSets need to be instantiated because they do work in Awake() and start coroutines.
SmartbodyMotionSet [] allObjectsInScene = FindObjectsOfType<SmartbodyMotionSet>();
for (int i = 0; i < motionSets.Length; i++)
{
SmartbodyMotionSet motionSet = motionSets[i];
if (motionSet && motionSet.gameObject.activeSelf)
{
bool found = false;
foreach (SmartbodyMotionSet obj in allObjectsInScene)
{
if (obj == motionSet)
{
// object matches
found = true;
break;
}
if (obj.gameObject.name == motionSet.gameObject.name)
{
// object name matches, so we found a gameobject in the scene that matches the prefab
// this assumes all motion sets have unique names
motionSets[i] = obj;
found = true;
break;
}
}
if (!found)
{
GameObject topLevel = GameObject.Find("__DynamicMotionSets");
if (topLevel == null)
topLevel = new GameObject("__DynamicMotionSets");
GameObject newObj = (GameObject)UnityEngine.Object.Instantiate(motionSet.gameObject);
newObj.name = newObj.name.Replace("(Clone)", "");
newObj.transform.parent = topLevel.transform;
motionSets[i] = newObj.GetComponent<SmartbodyMotionSet>();
}
}
}
}
public void CreateCharacter(SmartbodyCharacterInit character, SmartbodyFaceDefinition face, SmartbodyJointMap jointMap, GestureMapDefinition gestureMap)
{
/*
brad = scene.createCharacter("brad", "brad-attach")
brad.setSkeleton(scene.createSkeleton("common.sk"))
brad.setFaceDefinition(defaultFace)
brad.createStandardControllers()
brad.setVoice("audiofile")
brad.setVoiceCode("Sounds")
brad.setVoiceBackup("remote")
brad.setVoiceBackupCode("Festival_voice_rab_diphone")
brad.setUseVisemeCurves(True)
*/
{
GameObject boneParent = VHUtils.FindChild(gameObject, character.unityBoneParent);
m_Bones = boneParent.GetComponentsInChildren<Transform>();
m_BaseBonePositions = new Vector3class[m_Bones.Length];
m_BaseBoneRotations = new Quaternionclass[m_Bones.Length];
m_BoneLookupTable = new Dictionary<string, int>(NumBones);
//Debug.Log("num bones: " + m_Bones.Length + " m_Bones[0].name: " + m_Bones[0].name);
for (int i = 0; i < m_Bones.Length; i++)
{
m_BoneLookupTable.Add(m_Bones[i].gameObject.name, i);
m_BaseBonePositions[i] = new Vector3class();
m_BaseBonePositions[i].vector3 = m_Bones[i].localPosition;
m_BaseBoneRotations[i] = new Quaternionclass(m_Bones[i].localRotation);
}
}
// find all blend shapes
GetAllBlendShapes(out m_BlendShapeNameMap, out m_BlendShapes);
GameObject soundNode = VHUtils.FindChild(gameObject, SoundNodeName);
if (soundNode != null)
{
m_AudioSource = soundNode.GetComponent<AudioSource>();
}
else
{
Debug.LogWarning("No SoundNode found for " + name + ". You need to create a gameobject called '" +
SoundNodeName + "' ,attach it as a child to this character's prefab, and give it an audiosource component. " +
"Until you do this, sound cannot be played from this character");
}
SBMCharacterName = character.name;
SmartbodyManager sbm = SmartbodyManager.Get();
CreateSkeleton(); // only if loadSkeletonFromSk is false
InstantiateMotionSets(character.m_MotionSets);
DateTime startTime = DateTime.Now;
sbm.LoadAssetPaths(character.assetPaths);
Debug.Log(string.Format("Finished loading asset paths {0} seconds", (DateTime.Now - startTime).TotalSeconds.ToString("f3")));
if (jointMap != null)
{
sbm.AddJointMap(jointMap);
sbm.ApplySkeletonToJointMap(jointMap, character.skeletonName);
sbm.MapSkeletonAndAssetPaths(jointMap, character.skeletonName, character.assetPaths);
}
SmartbodyMotionSet [] allMotionSets = GameObject.FindObjectsOfType<SmartbodyMotionSet>();
foreach (SmartbodyMotionSet motionSet in allMotionSets)
{
if (motionSet && motionSet.gameObject.activeSelf)
{
motionSet.LoadMotions();
sbm.CreateRetargetPair(motionSet.SkeletonName, character.skeletonName);
}
}
foreach (var pair in character.assetPaths)
{
string skeletonName = pair.Key;
sbm.CreateRetargetPair(skeletonName, character.skeletonName);
}
sbm.PythonCommand(string.Format(@"scene.createCharacter('{0}', '{1}')", SBMCharacterName, CharacterName));
sbm.PythonCommand(string.Format(@"scene.getCharacter('{0}').setSkeleton(scene.createSkeleton('{1}'))", SBMCharacterName, character.skeletonName));
sbm.PythonCommand(string.Format(@"scene.getCharacter('{0}').setDoubleAttribute('bmlscheduledelay', 0)", SBMCharacterName));
if (face != null && face.enabled)
{
//Debug.Log("face.definitionName: " + face.definitionName);
sbm.AddFaceDefinition(face);
sbm.PythonCommand(string.Format(@"scene.getCharacter('{0}').setFaceDefinition(scene.getFaceDefinition('{1}'))", SBMCharacterName, face.definitionName));
}
sbm.PythonCommand(string.Format(@"scene.getCharacter('{0}').createStandardControllers()", SBMCharacterName));
if (!string.IsNullOrEmpty(character.voiceType) &&
!string.IsNullOrEmpty(character.voiceCode))
{
sbm.SetCharacterVoice(SBMCharacterName, character.voiceType, character.voiceCode, false);
//sbm.PythonCommand(string.Format(@"scene.getCharacter('{0}').setVoice('{1}')", SBMCharacterName, character.voiceType));
//sbm.PythonCommand(string.Format(@"scene.getCharacter('{0}').setVoiceCode('{1}')", SBMCharacterName, character.voiceCode));
}
if (!string.IsNullOrEmpty(character.voiceTypeBackup) &&
!string.IsNullOrEmpty(character.voiceCodeBackup))
{
sbm.SetCharacterVoice(SBMCharacterName, character.voiceTypeBackup, character.voiceCodeBackup, true);
//sbm.PythonCommand(string.Format(@"scene.getCharacter('{0}').setVoiceBackup('{1}')", SBMCharacterName, character.voiceTypeBackup));
//sbm.PythonCommand(string.Format(@"scene.getCharacter('{0}').setVoiceBackupCode('{1}')", SBMCharacterName, character.voiceCodeBackup));
}
if (character.usePhoneBigram)
{
sbm.PythonCommand(string.Format(@"scene.getCharacter('{0}').setStringAttribute('lipSyncSetName', 'default')", SBMCharacterName));
sbm.PythonCommand(string.Format(@"scene.getCharacter('{0}').setBoolAttribute('usePhoneBigram', True)", SBMCharacterName));
}
else
{
sbm.PythonCommand(string.Format(@"scene.getCharacter('{0}').setUseVisemeCurves(True)", SBMCharacterName));
}
if (gestureMap != null && gestureMap.enabled)
{
sbm.AddGestureMapDefinition(gestureMap);
sbm.PythonCommand(string.Format(@"scene.getCharacter('{0}').setStringAttribute('gestureMap', '{1}')", SBMCharacterName, gestureMap.gestureMapName));
//SmartbodyManager.Get().PythonCommand(string.Format(@"scene.getCharacter('{0}').setBoolAttribute('bmlRequest.autoGestureTransition', True)", character.SBMCharacterName));
}
if (!string.IsNullOrEmpty(character.startingPosture))
{
sbm.SBPosture(SBMCharacterName, character.startingPosture, UnityEngine.Random.Range(0, 4.0f));
}
// locomotion/steering currently only working under certain platforms (can't find pprAI lib)
if (Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.WindowsPlayer ||
Application.platform == RuntimePlatform.IPhonePlayer)
{
if (!string.IsNullOrEmpty(character.locomotionInitPythonFile))
{
if (!string.IsNullOrEmpty(character.locomotionInitPythonSkeletonName))
{
sbm.PythonCommand(string.Format(@"locomotionInitSkeleton = '{0}'", character.locomotionInitPythonSkeletonName));
}
sbm.SBRunPythonScript(character.locomotionInitPythonFile);
sbm.PythonCommand(string.Format(@"scene.getSteerManager().removeSteerAgent('{0}')", SBMCharacterName));
sbm.PythonCommand(string.Format(@"scene.getSteerManager().createSteerAgent('{0}')", SBMCharacterName));
if (!string.IsNullOrEmpty(character.locomotionSteerPrefix))
{
sbm.PythonCommand(string.Format(@"scene.getSteerManager().getSteerAgent('{0}').setSteerStateNamePrefix('{1}')", SBMCharacterName, character.locomotionSteerPrefix));
}
else
{
Debug.LogWarning("UnitySmartbodyCharacter.CreateCharacter() - locomotionInitPython file specified, but no locomotionSteerPrefix specified. This must be specified for locomotion to work");
}
sbm.PythonCommand(string.Format(@"scene.getSteerManager().getSteerAgent('{0}').setSteerType('{1}')", SBMCharacterName, "example"));
//# Toggle the steering manager
sbm.PythonCommand(string.Format(@"scene.getSteerManager().setEnable(False)"));
sbm.PythonCommand(string.Format(@"scene.getSteerManager().setEnable(True)"));
}
}
sbm.CreateCharacter(this);
sbm.SBTransform(SBMCharacterName, transform);
character.TriggerPostLoadEvent(this);
}
void ShowGeometry(bool show)
{
Renderer[] renderers = GetComponentsInChildren<Renderer>();
for (int i = 0; i < renderers.Length; i++)
{
renderers[i].enabled = show;
}
}
public bool IsVisible()
{
Renderer[] renderers = GetComponentsInChildren<Renderer>();
for (int i = 0; i < renderers.Length; i++)
{
if (renderers[i].isVisible)
{
return true;
}
}
return false;
}
public virtual void OnBoneTransformations(float positionScale)
{
Transform currentBoneTransform = null;
Quaternion tempQ = Quaternion.identity;
Vector3 tempVec = Vector3.zero;
UnitySmartbodyCharacter.Vector3class baseBonePosition = null;
string jointName = String.Empty;
float curTime = Time.time;
SmartbodyFaceDefinition face = GetComponent<SmartbodyFaceDefinition>();
for (int i = 0; i < m_CharacterData.m_Character.m_numJoints; i++)
{
bool posCacheHit = false;
bool rotCacheHit = false;
if (m_CharacterData.jNextUpdateTime[i] > curTime)
{
if (m_CharacterData.jx[i] == m_CharacterData.jprevx[i] &&
m_CharacterData.jy[i] == m_CharacterData.jprevy[i] &&
m_CharacterData.jz[i] == m_CharacterData.jprevz[i])
{
posCacheHit = true;
}
if (m_CharacterData.jrw[i] == m_CharacterData.jprevrw[i] &&
m_CharacterData.jrx[i] == m_CharacterData.jprevrx[i] &&
m_CharacterData.jry[i] == m_CharacterData.jprevry[i] &&
m_CharacterData.jrz[i] == m_CharacterData.jprevrz[i])
{
rotCacheHit = true;
}
}
if (posCacheHit && rotCacheHit)
continue;
// update when next to force an update no matter what the cache status
const float cacheRefreshTimeMin = 5.0f; // seconds between refreshes
const float cacheRefreshTimeMax = 6.0f;
float refreshTime = Mathf.Lerp(cacheRefreshTimeMin, cacheRefreshTimeMax, UnityEngine.Random.value); // return number between min/max
m_CharacterData.jNextUpdateTime[i] = curTime + refreshTime;
jointName = Marshal.PtrToStringAnsi(m_CharacterData.jnames[i]);
if (String.IsNullOrEmpty(jointName))
{
continue;
}
if (face != null && face.enabled && (face.visemes.FindIndex(s => s.Key == jointName) != -1 || jointName.IndexOf("au_") != -1))
{
SetChannel(jointName, m_CharacterData.jx[i] * positionScale);
}
bool ret = GetBoneAndBaseBonePosition(jointName, out currentBoneTransform, out baseBonePosition);
if (ret == false)
{
if (IsBlendShape(jointName))
{
HandleBlendShape(jointName, m_CharacterData.jx[i]);
}
continue;
}
if (!rotCacheHit)
{
// set rotation
tempQ.Set( m_CharacterData.jrx[i],
-m_CharacterData.jry[i],
-m_CharacterData.jrz[i],
m_CharacterData.jrw[i]);
currentBoneTransform.localRotation = tempQ;
}
if (!posCacheHit)
{
// set position
tempVec.Set(baseBonePosition.vector3.x + (-m_CharacterData.jx[i] * positionScale),
baseBonePosition.vector3.y + ( m_CharacterData.jy[i] * positionScale),
baseBonePosition.vector3.z + ( m_CharacterData.jz[i] * positionScale));
currentBoneTransform.localPosition = tempVec;
}
}
}
public virtual void SetChannel(string channelName, float value)
{
//Debug.Log("SetChannel() - " + channelName + " " + value);
if (m_ChannelCB != null)
{
m_ChannelCB(this, channelName, value);
}
else
{
//Debug.LogError("UnitySmartbodyCharacter::SetChannel was called but no callback is set. Call SetChannelCallback to set up a callback function.");
}
}
public void SetChannelCallback(ChannelCallback channelCB)
{
m_ChannelCB += channelCB;
}
public void ResetSkeleton()
{
for (int i = 0; i < m_Bones.Length; i++)
{
m_Bones[i].transform.localPosition = GetBaseBonePosition(m_Bones[i].name);
m_Bones[i].transform.localRotation = GetBaseBoneRotation(m_Bones[i].name);
}
}
public Transform GetBone(string boneName)
{
int index = -1;
if (m_BoneLookupTable.TryGetValue(boneName, out index))
{
return m_Bones[index];
}
else
{
Debug.LogError("there's no bone named: " + boneName);
}
return null;
}
public Transform GetBone(int index)
{
if (index < 0 || index >= m_Bones.Length)
{
return null;
}
return m_Bones[index];
}
public Vector3 GetBaseBonePosition(string boneName)
{
int index = -1;
if (m_BoneLookupTable.TryGetValue(boneName, out index))
{
return m_BaseBonePositions[index].vector3;
}
else
{
Debug.LogError("there's no bone named: " + boneName);
}
return Vector3.zero;
}
public Quaternion GetBaseBoneRotation(string boneName)
{
int index = -1;
if (m_BoneLookupTable.TryGetValue(boneName, out index))
{
return m_BaseBoneRotations[index].quat;
}
else
{
Debug.LogError("there's no bone named: " + boneName);
}
return Quaternion.identity;
}
public bool GetBoneAndBaseBonePosition(string boneName, out Transform bone, out Vector3class baseBonePosition)
{
// this is a combination of GetBone() and GetBaseBonePosition() to reduce dictionary lookups
int index;
if (m_BoneLookupTable.TryGetValue(boneName, out index))
{
bone = m_Bones[index];
baseBonePosition = m_BaseBonePositions[index];
return true;
}
else
{
//Debug.LogError("there's no bone named: " + boneName);
bone = null;
baseBonePosition = null;
}
return false;
}
bool IsBlendShape(string shapeName)
{
if (m_BlendShapes.ContainsKey(shapeName))
{
return true;
}
return false;
}
void HandleBlendShape(string shapeName, float weight)
{
if (m_BlendShapes.ContainsKey(shapeName))
{
foreach (SkinnedMeshRenderer smr in m_BlendShapes[shapeName])
{
int blendShapeIndex = smr.sharedMesh.GetBlendShapeIndex(m_BlendShapeNameMap[shapeName]);
if (blendShapeIndex != -1)
{
//Debug.Log("shapeName: " + shapeName + " weight: " + weight);
// unity uses blend shape scale 0-100 whereas maya uses 0-1, so we have to convert
smr.SetBlendShapeWeight(blendShapeIndex, Mathf.Clamp(weight, 0, 100));
SetChannel(shapeName, weight);
}
else
{
Debug.LogError(string.Format("No blend shape found with name shape name {0}", shapeName));
}
}
}
else
{
Debug.LogError(string.Format("No blend shape found with name shape name {0}", shapeName));
}
}
#region ICharacter Implementation
public override void PlayAudio(AudioSpeechFile audioId)
{
//SmartbodyManager.Get().PythonCommand();
}
public override void PlayXml(string xml)
{
throw new NotImplementedException();
}
public override void PlayXml(AudioSpeechFile xml)
{
throw new NotImplementedException();
}
public override void Transform(Transform trans)
{
throw new NotImplementedException();
}
public override void Transform(Vector3 pos, Quaternion rot)
{
throw new NotImplementedException();
}
public override void Transform(float y, float p)
{
throw new NotImplementedException();
}
public override void Transform(float x, float y, float z)
{
throw new NotImplementedException();
}
public override void Transform(float x, float y, float z, float h, float p, float r)
{
throw new NotImplementedException();
}
public override void Rotate(float h)
{
throw new NotImplementedException();
}
public override void PlayPosture(string posture, float startTime)
{
throw new NotImplementedException();
}
public override void PlayAnim(string animName)
{
throw new NotImplementedException();
}
public override void PlayAnim(string animName, float readyTime, float strokeStartTime, float emphasisTime, float strokeTime, float relaxTime)
{
throw new NotImplementedException();
}
public override void PlayViseme(string viseme, float weight)
{
throw new NotImplementedException();
}
public override void PlayViseme(string viseme, float weight, float totalTime, float blendTime)
{
throw new NotImplementedException();
}
public override void Nod(float amount, float repeats, float time)
{
throw new NotImplementedException();
}
public override void Shake(float amount, float repeats, float time)
{
throw new NotImplementedException();
}
public override void Gaze(string gazeAt)
{
throw new NotImplementedException();
}
public override void Gaze(string gazeAt, float headSpeed)
{
throw new NotImplementedException();
}
public override void Gaze(string gazeAt, float headSpeed, float eyeSpeed, CharacterDefines.GazeJointRange jointRange)
{
throw new NotImplementedException();
}
public override void Gaze(string gazeAt, string targetBone, CharacterDefines.GazeDirection gazeDirection, CharacterDefines.GazeJointRange jointRange, float angle, float headSpeed, float eyeSpeed, float fadeOut, string gazeHandleName, float duration)
{
throw new NotImplementedException();
}
public override void StopGaze()
{
throw new NotImplementedException();
}
public override void StopGaze(float fadoutTime)
{
throw new NotImplementedException();
}
public override void Saccade(CharacterDefines.SaccadeType type, bool finish, float duration)
{
throw new NotImplementedException();
}
public override void Saccade(CharacterDefines.SaccadeType type, bool finish, float duration, float angleLimit, float direction, float magnitude)
{
throw new NotImplementedException();
}
public override void StopSaccade()
{
throw new NotImplementedException();
}
#endregion
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Text;
using System.Collections;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
{
[Serializable]
public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible
{
#region Private Constants
private const char enumSeparatorChar = ',';
private const String enumSeparatorString = ", ";
#endregion
#region Private Static Methods
private static TypeValuesAndNames GetCachedValuesAndNames(RuntimeType enumType, bool getNames)
{
TypeValuesAndNames entry = enumType.GenericCache as TypeValuesAndNames;
if (entry == null || (getNames && entry.Names == null))
{
ulong[] values = null;
String[] names = null;
bool isFlags = enumType.IsDefined(typeof(System.FlagsAttribute), false);
GetEnumValuesAndNames(
enumType.GetTypeHandleInternal(),
JitHelpers.GetObjectHandleOnStack(ref values),
JitHelpers.GetObjectHandleOnStack(ref names),
getNames);
entry = new TypeValuesAndNames(isFlags, values, names);
enumType.GenericCache = entry;
}
return entry;
}
private unsafe String InternalFormattedHexString()
{
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
{
switch (InternalGetCorElementType())
{
case CorElementType.I1:
case CorElementType.U1:
return (*(byte*)pValue).ToString("X2", null);
case CorElementType.Boolean:
// direct cast from bool to byte is not allowed
return Convert.ToByte(*(bool*)pValue).ToString("X2", null);
case CorElementType.I2:
case CorElementType.U2:
case CorElementType.Char:
return (*(ushort*)pValue).ToString("X4", null);
case CorElementType.I4:
case CorElementType.U4:
return (*(uint*)pValue).ToString("X8", null);
case CorElementType.I8:
case CorElementType.U8:
return (*(ulong*)pValue).ToString("X16", null);
default:
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
}
private static String InternalFormattedHexString(object value)
{
TypeCode typeCode = Convert.GetTypeCode(value);
switch (typeCode)
{
case TypeCode.SByte:
return ((byte)(sbyte)value).ToString("X2", null);
case TypeCode.Byte:
return ((byte)value).ToString("X2", null);
case TypeCode.Boolean:
// direct cast from bool to byte is not allowed
return Convert.ToByte((bool)value).ToString("X2", null);
case TypeCode.Int16:
return ((UInt16)(Int16)value).ToString("X4", null);
case TypeCode.UInt16:
return ((UInt16)value).ToString("X4", null);
case TypeCode.Char:
return ((UInt16)(Char)value).ToString("X4", null);
case TypeCode.UInt32:
return ((UInt32)value).ToString("X8", null);
case TypeCode.Int32:
return ((UInt32)(Int32)value).ToString("X8", null);
case TypeCode.UInt64:
return ((UInt64)value).ToString("X16", null);
case TypeCode.Int64:
return ((UInt64)(Int64)value).ToString("X16", null);
// All unsigned types will be directly cast
default:
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
internal static String GetEnumName(RuntimeType eT, ulong ulValue)
{
Contract.Requires(eT != null);
ulong[] ulValues = Enum.InternalGetValues(eT);
int index = Array.BinarySearch(ulValues, ulValue);
if (index >= 0)
{
string[] names = Enum.InternalGetNames(eT);
return names[index];
}
return null; // return null so the caller knows to .ToString() the input
}
private static String InternalFormat(RuntimeType eT, ulong value)
{
Contract.Requires(eT != null);
// These values are sorted by value. Don't change this
TypeValuesAndNames entry = GetCachedValuesAndNames(eT, true);
if (!entry.IsFlag) // Not marked with Flags attribute
{
return Enum.GetEnumName(eT, value);
}
else // These are flags OR'ed together (We treat everything as unsigned types)
{
return InternalFlagsFormat(eT, entry, value);
}
}
private static String InternalFlagsFormat(RuntimeType eT, ulong result)
{
// These values are sorted by value. Don't change this
TypeValuesAndNames entry = GetCachedValuesAndNames(eT, true);
return InternalFlagsFormat(eT, entry, result);
}
private static String InternalFlagsFormat(RuntimeType eT, TypeValuesAndNames entry, ulong result)
{
Contract.Requires(eT != null);
String[] names = entry.Names;
ulong[] values = entry.Values;
Debug.Assert(names.Length == values.Length);
int index = values.Length - 1;
StringBuilder sb = StringBuilderCache.Acquire();
bool firstTime = true;
ulong saveResult = result;
// We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied
// to minimize the comparsions required. This code works the same for the best/worst case. In general the number of
// items in an enum are sufficiently small and not worth the optimization.
while (index >= 0)
{
if ((index == 0) && (values[index] == 0))
break;
if ((result & values[index]) == values[index])
{
result -= values[index];
if (!firstTime)
sb.Insert(0, enumSeparatorString);
sb.Insert(0, names[index]);
firstTime = false;
}
index--;
}
string returnString;
if (result != 0)
{
// We were unable to represent this number as a bitwise or of valid flags
returnString = null; // return null so the caller knows to .ToString() the input
}
else if (saveResult == 0)
{
// For the cases when we have zero
if (values.Length > 0 && values[0] == 0)
{
returnString = names[0]; // Zero was one of the enum values.
}
else
{
returnString = "0";
}
}
else
{
returnString = sb.ToString(); // Return the string representation
}
StringBuilderCache.Release(sb);
return returnString;
}
internal static ulong ToUInt64(Object value)
{
// Helper function to silently convert the value to UInt64 from the other base types for enum without throwing an exception.
// This is need since the Convert functions do overflow checks.
TypeCode typeCode = Convert.GetTypeCode(value);
ulong result;
switch (typeCode)
{
case TypeCode.SByte:
result = (ulong)(sbyte)value;
break;
case TypeCode.Byte:
result = (byte)value;
break;
case TypeCode.Boolean:
// direct cast from bool to byte is not allowed
result = Convert.ToByte((bool)value);
break;
case TypeCode.Int16:
result = (ulong)(Int16)value;
break;
case TypeCode.UInt16:
result = (UInt16)value;
break;
case TypeCode.Char:
result = (UInt16)(Char)value;
break;
case TypeCode.UInt32:
result = (UInt32)value;
break;
case TypeCode.Int32:
result = (ulong)(int)value;
break;
case TypeCode.UInt64:
result = (ulong)value;
break;
case TypeCode.Int64:
result = (ulong)(Int64)value;
break;
// All unsigned types will be directly cast
default:
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
return result;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int InternalCompareTo(Object o1, Object o2);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeType InternalGetUnderlyingType(RuntimeType enumType);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[System.Security.SuppressUnmanagedCodeSecurity]
private static extern void GetEnumValuesAndNames(RuntimeTypeHandle enumType, ObjectHandleOnStack values, ObjectHandleOnStack names, bool getNames);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object InternalBoxEnum(RuntimeType enumType, long value);
#endregion
#region Public Static Methods
private enum ParseFailureKind
{
None = 0,
Argument = 1,
ArgumentNull = 2,
ArgumentWithParameter = 3,
UnhandledException = 4
}
// This will store the result of the parsing.
private struct EnumResult
{
internal object parsedEnum;
internal bool canThrow;
internal ParseFailureKind m_failure;
internal string m_failureMessageID;
internal string m_failureParameter;
internal object m_failureMessageFormatArgument;
internal Exception m_innerException;
internal void SetFailure(Exception unhandledException)
{
m_failure = ParseFailureKind.UnhandledException;
m_innerException = unhandledException;
}
internal void SetFailure(ParseFailureKind failure, string failureParameter)
{
m_failure = failure;
m_failureParameter = failureParameter;
if (canThrow)
throw GetEnumParseException();
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument)
{
m_failure = failure;
m_failureMessageID = failureMessageID;
m_failureMessageFormatArgument = failureMessageFormatArgument;
if (canThrow)
throw GetEnumParseException();
}
internal Exception GetEnumParseException()
{
switch (m_failure)
{
case ParseFailureKind.Argument:
return new ArgumentException(SR.GetResourceString(m_failureMessageID));
case ParseFailureKind.ArgumentNull:
return new ArgumentNullException(m_failureParameter);
case ParseFailureKind.ArgumentWithParameter:
return new ArgumentException(SR.Format(SR.GetResourceString(m_failureMessageID), m_failureMessageFormatArgument));
case ParseFailureKind.UnhandledException:
return m_innerException;
default:
Debug.Assert(false, "Unknown EnumParseFailure: " + m_failure);
return new ArgumentException(SR.Arg_EnumValueNotFound);
}
}
}
public static bool TryParse(Type enumType, String value, out Object result)
{
return TryParse(enumType, value, false, out result);
}
public static bool TryParse(Type enumType, String value, bool ignoreCase, out Object result)
{
result = null;
EnumResult parseResult = new EnumResult();
bool retValue;
if (retValue = TryParseEnum(enumType, value, ignoreCase, ref parseResult))
result = parseResult.parsedEnum;
return retValue;
}
public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct
{
return TryParse(value, false, out result);
}
public static bool TryParse<TEnum>(String value, bool ignoreCase, out TEnum result) where TEnum : struct
{
result = default(TEnum);
EnumResult parseResult = new EnumResult();
bool retValue;
if (retValue = TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult))
result = (TEnum)parseResult.parsedEnum;
return retValue;
}
public static Object Parse(Type enumType, String value)
{
return Parse(enumType, value, false);
}
public static Object Parse(Type enumType, String value, bool ignoreCase)
{
EnumResult parseResult = new EnumResult() { canThrow = true };
if (TryParseEnum(enumType, value, ignoreCase, ref parseResult))
return parseResult.parsedEnum;
else
throw parseResult.GetEnumParseException();
}
public static TEnum Parse<TEnum>(String value) where TEnum : struct
{
return Parse<TEnum>(value, false);
}
public static TEnum Parse<TEnum>(String value, bool ignoreCase) where TEnum : struct
{
EnumResult parseResult = new EnumResult() { canThrow = true };
if (TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult))
return (TEnum)parseResult.parsedEnum;
else
throw parseResult.GetEnumParseException();
}
private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, ref EnumResult parseResult)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
if (value == null)
{
parseResult.SetFailure(ParseFailureKind.ArgumentNull, nameof(value));
return false;
}
int firstNonWhitespaceIndex = -1;
for (int i = 0; i < value.Length; i++)
{
if (!Char.IsWhiteSpace(value[i]))
{
firstNonWhitespaceIndex = i;
break;
}
}
if (firstNonWhitespaceIndex == -1)
{
parseResult.SetFailure(ParseFailureKind.Argument, "Arg_MustContainEnumInfo", null);
return false;
}
// We have 2 code paths here. One if they are values else if they are Strings.
// values will have the first character as as number or a sign.
ulong result = 0;
char firstNonWhitespaceChar = value[firstNonWhitespaceIndex];
if (Char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '-' || firstNonWhitespaceChar == '+')
{
Type underlyingType = GetUnderlyingType(enumType);
Object temp;
try
{
value = value.Trim();
temp = Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture);
parseResult.parsedEnum = ToObject(enumType, temp);
return true;
}
catch (FormatException)
{ // We need to Parse this as a String instead. There are cases
// when you tlbimp enums that can have values of the form "3D".
// Don't fix this code.
}
catch (Exception ex)
{
if (parseResult.canThrow)
throw;
else
{
parseResult.SetFailure(ex);
return false;
}
}
}
// Find the field. Let's assume that these are always static classes
// because the class is an enum.
TypeValuesAndNames entry = GetCachedValuesAndNames(rtType, true);
String[] enumNames = entry.Names;
ulong[] enumValues = entry.Values;
StringComparison comparison = ignoreCase ?
StringComparison.OrdinalIgnoreCase :
StringComparison.Ordinal;
int valueIndex = firstNonWhitespaceIndex;
while (valueIndex <= value.Length) // '=' is to handle invalid case of an ending comma
{
// Find the next separator, if there is one, otherwise the end of the string.
int endIndex = value.IndexOf(enumSeparatorChar, valueIndex);
if (endIndex == -1)
{
endIndex = value.Length;
}
// Shift the starting and ending indices to eliminate whitespace
int endIndexNoWhitespace = endIndex;
while (valueIndex < endIndex && Char.IsWhiteSpace(value[valueIndex])) valueIndex++;
while (endIndexNoWhitespace > valueIndex && Char.IsWhiteSpace(value[endIndexNoWhitespace - 1])) endIndexNoWhitespace--;
int valueSubstringLength = endIndexNoWhitespace - valueIndex;
// Try to match this substring against each enum name
bool success = false;
for (int i = 0; i < enumNames.Length; i++)
{
if (enumNames[i].Length == valueSubstringLength &&
string.Compare(enumNames[i], 0, value, valueIndex, valueSubstringLength, comparison) == 0)
{
result |= enumValues[i];
success = true;
break;
}
}
// If we couldn't find a match, throw an argument exception.
if (!success)
{
// Not found, throw an argument exception.
parseResult.SetFailure(ParseFailureKind.ArgumentWithParameter, "Arg_EnumValueNotFound", value);
return false;
}
// Move our pointer to the ending index to go again.
valueIndex = endIndex + 1;
}
try
{
parseResult.parsedEnum = ToObject(enumType, result);
return true;
}
catch (Exception ex)
{
if (parseResult.canThrow)
throw;
else
{
parseResult.SetFailure(ex);
return false;
}
}
}
public static Type GetUnderlyingType(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
Contract.Ensures(Contract.Result<Type>() != null);
Contract.EndContractBlock();
return enumType.GetEnumUnderlyingType();
}
public static Array GetValues(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
Contract.Ensures(Contract.Result<Array>() != null);
Contract.EndContractBlock();
return enumType.GetEnumValues();
}
internal static ulong[] InternalGetValues(RuntimeType enumType)
{
// Get all of the values
return GetCachedValuesAndNames(enumType, false).Values;
}
public static String GetName(Type enumType, Object value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
Contract.EndContractBlock();
return enumType.GetEnumName(value);
}
public static String[] GetNames(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return enumType.GetEnumNames();
}
internal static String[] InternalGetNames(RuntimeType enumType)
{
// Get all of the names
return GetCachedValuesAndNames(enumType, true).Names;
}
public static Object ToObject(Type enumType, Object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Delegate rest of error checking to the other functions
TypeCode typeCode = Convert.GetTypeCode(value);
switch (typeCode)
{
case TypeCode.Int32:
return ToObject(enumType, (int)value);
case TypeCode.SByte:
return ToObject(enumType, (sbyte)value);
case TypeCode.Int16:
return ToObject(enumType, (short)value);
case TypeCode.Int64:
return ToObject(enumType, (long)value);
case TypeCode.UInt32:
return ToObject(enumType, (uint)value);
case TypeCode.Byte:
return ToObject(enumType, (byte)value);
case TypeCode.UInt16:
return ToObject(enumType, (ushort)value);
case TypeCode.UInt64:
return ToObject(enumType, (ulong)value);
case TypeCode.Char:
return ToObject(enumType, (char)value);
case TypeCode.Boolean:
return ToObject(enumType, (bool)value);
default:
// All unsigned types will be directly cast
throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value));
}
}
[Pure]
public static bool IsDefined(Type enumType, Object value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
Contract.EndContractBlock();
return enumType.IsEnumDefined(value);
}
public static String Format(Type enumType, Object value, String format)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (format == null)
throw new ArgumentNullException(nameof(format));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
// Check if both of them are of the same type
Type valueType = value.GetType();
Type underlyingType = GetUnderlyingType(enumType);
// If the value is an Enum then we need to extract the underlying value from it
if (valueType.IsEnum)
{
if (!valueType.IsEquivalentTo(enumType))
throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, valueType.ToString(), enumType.ToString()));
if (format.Length != 1)
{
// all acceptable format string are of length 1
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
return ((Enum)value).ToString(format);
}
// The value must be of the same type as the Underlying type of the Enum
else if (valueType != underlyingType)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, valueType.ToString(), underlyingType.ToString()));
}
if (format.Length != 1)
{
// all acceptable format string are of length 1
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
char formatCh = format[0];
if (formatCh == 'G' || formatCh == 'g')
return GetEnumName(rtType, ToUInt64(value)) ?? value.ToString();
if (formatCh == 'D' || formatCh == 'd')
return value.ToString();
if (formatCh == 'X' || formatCh == 'x')
return InternalFormattedHexString(value);
if (formatCh == 'F' || formatCh == 'f')
return Enum.InternalFlagsFormat(rtType, ToUInt64(value)) ?? value.ToString();
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
#endregion
#region Definitions
private class TypeValuesAndNames
{
// Each entry contains a list of sorted pair of enum field names and values, sorted by values
public TypeValuesAndNames(bool isFlag, ulong[] values, String[] names)
{
this.IsFlag = isFlag;
this.Values = values;
this.Names = names;
}
public bool IsFlag;
public ulong[] Values;
public String[] Names;
}
#endregion
#region Private Methods
internal unsafe Object GetValue()
{
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
{
switch (InternalGetCorElementType())
{
case CorElementType.I1:
return *(sbyte*)pValue;
case CorElementType.U1:
return *(byte*)pValue;
case CorElementType.Boolean:
return *(bool*)pValue;
case CorElementType.I2:
return *(short*)pValue;
case CorElementType.U2:
return *(ushort*)pValue;
case CorElementType.Char:
return *(char*)pValue;
case CorElementType.I4:
return *(int*)pValue;
case CorElementType.U4:
return *(uint*)pValue;
case CorElementType.R4:
return *(float*)pValue;
case CorElementType.I8:
return *(long*)pValue;
case CorElementType.U8:
return *(ulong*)pValue;
case CorElementType.R8:
return *(double*)pValue;
case CorElementType.I:
return *(IntPtr*)pValue;
case CorElementType.U:
return *(UIntPtr*)pValue;
default:
Debug.Assert(false, "Invalid primitive type");
return null;
}
}
}
private unsafe ulong ToUInt64()
{
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
{
switch (InternalGetCorElementType())
{
case CorElementType.I1:
return (ulong)*(sbyte*)pValue;
case CorElementType.U1:
return *(byte*)pValue;
case CorElementType.Boolean:
return Convert.ToUInt64(*(bool*)pValue, CultureInfo.InvariantCulture);
case CorElementType.I2:
return (ulong)*(short*)pValue;
case CorElementType.U2:
case CorElementType.Char:
return *(ushort*)pValue;
case CorElementType.I4:
return (ulong)*(int*)pValue;
case CorElementType.U4:
case CorElementType.R4:
return *(uint*)pValue;
case CorElementType.I8:
return (ulong)*(long*)pValue;
case CorElementType.U8:
case CorElementType.R8:
return *(ulong*)pValue;
case CorElementType.I:
if (IntPtr.Size == 8)
{
return *(ulong*)pValue;
}
else
{
return (ulong)*(int*)pValue;
}
case CorElementType.U:
if (IntPtr.Size == 8)
{
return *(ulong*)pValue;
}
else
{
return *(uint*)pValue;
}
default:
Debug.Assert(false, "Invalid primitive type");
return 0;
}
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool InternalHasFlag(Enum flags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern CorElementType InternalGetCorElementType();
#endregion
#region Object Overrides
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern override bool Equals(Object obj);
public override unsafe int GetHashCode()
{
// CONTRACT with the runtime: GetHashCode of enum types is implemented as GetHashCode of the underlying type.
// The runtime can bypass calls to Enum::GetHashCode and call the underlying type's GetHashCode directly
// to avoid boxing the enum.
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
{
switch (InternalGetCorElementType())
{
case CorElementType.I1:
return (*(sbyte*)pValue).GetHashCode();
case CorElementType.U1:
return (*(byte*)pValue).GetHashCode();
case CorElementType.Boolean:
return (*(bool*)pValue).GetHashCode();
case CorElementType.I2:
return (*(short*)pValue).GetHashCode();
case CorElementType.U2:
return (*(ushort*)pValue).GetHashCode();
case CorElementType.Char:
return (*(char*)pValue).GetHashCode();
case CorElementType.I4:
return (*(int*)pValue).GetHashCode();
case CorElementType.U4:
return (*(uint*)pValue).GetHashCode();
case CorElementType.R4:
return (*(float*)pValue).GetHashCode();
case CorElementType.I8:
return (*(long*)pValue).GetHashCode();
case CorElementType.U8:
return (*(ulong*)pValue).GetHashCode();
case CorElementType.R8:
return (*(double*)pValue).GetHashCode();
case CorElementType.I:
return (*(IntPtr*)pValue).GetHashCode();
case CorElementType.U:
return (*(UIntPtr*)pValue).GetHashCode();
default:
Debug.Assert(false, "Invalid primitive type");
return 0;
}
}
}
public override String ToString()
{
// Returns the value in a human readable format. For PASCAL style enums who's value maps directly the name of the field is returned.
// For PASCAL style enums who's values do not map directly the decimal value of the field is returned.
// For BitFlags (indicated by the Flags custom attribute): If for each bit that is set in the value there is a corresponding constant
//(a pure power of 2), then the OR string (ie "Red | Yellow") is returned. Otherwise, if the value is zero or if you can't create a string that consists of
// pure powers of 2 OR-ed together, you return a hex value
// Try to see if its one of the enum values, then we return a String back else the value
return Enum.InternalFormat((RuntimeType)GetType(), ToUInt64()) ?? GetValue().ToString();
}
#endregion
#region IFormattable
[Obsolete("The provider argument is not used. Please use ToString(String).")]
public String ToString(String format, IFormatProvider provider)
{
return ToString(format);
}
#endregion
#region IComparable
public int CompareTo(Object target)
{
const int retIncompatibleMethodTables = 2; // indicates that the method tables did not match
const int retInvalidEnumType = 3; // indicates that the enum was of an unknown/unsupported underlying type
if (this == null)
throw new NullReferenceException();
Contract.EndContractBlock();
int ret = InternalCompareTo(this, target);
if (ret < retIncompatibleMethodTables)
{
// -1, 0 and 1 are the normal return codes
return ret;
}
else if (ret == retIncompatibleMethodTables)
{
Type thisType = this.GetType();
Type targetType = target.GetType();
throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, targetType.ToString(), thisType.ToString()));
}
else
{
// assert valid return code (3)
Debug.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid");
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
#endregion
#region Public Methods
public String ToString(String format)
{
char formatCh;
if (format == null || format.Length == 0)
formatCh = 'G';
else if (format.Length != 1)
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
else
formatCh = format[0];
if (formatCh == 'G' || formatCh == 'g')
return ToString();
if (formatCh == 'D' || formatCh == 'd')
return GetValue().ToString();
if (formatCh == 'X' || formatCh == 'x')
return InternalFormattedHexString();
if (formatCh == 'F' || formatCh == 'f')
return InternalFlagsFormat((RuntimeType)GetType(), ToUInt64()) ?? GetValue().ToString();
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
[Obsolete("The provider argument is not used. Please use ToString().")]
public String ToString(IFormatProvider provider)
{
return ToString();
}
public Boolean HasFlag(Enum flag)
{
if (flag == null)
throw new ArgumentNullException(nameof(flag));
Contract.EndContractBlock();
if (!this.GetType().IsEquivalentTo(flag.GetType()))
{
throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), this.GetType()));
}
return InternalHasFlag(flag);
}
#endregion
#region IConvertable
public TypeCode GetTypeCode()
{
switch (InternalGetCorElementType())
{
case CorElementType.I1:
return TypeCode.SByte;
case CorElementType.U1:
return TypeCode.Byte;
case CorElementType.Boolean:
return TypeCode.Boolean;
case CorElementType.I2:
return TypeCode.Int16;
case CorElementType.U2:
return TypeCode.UInt16;
case CorElementType.Char:
return TypeCode.Char;
case CorElementType.I4:
return TypeCode.Int32;
case CorElementType.U4:
return TypeCode.UInt32;
case CorElementType.I8:
return TypeCode.Int64;
case CorElementType.U8:
return TypeCode.UInt64;
default:
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Enum", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
#endregion
#region ToObject
[CLSCompliant(false)]
public static Object ToObject(Type enumType, sbyte value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
public static Object ToObject(Type enumType, short value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
public static Object ToObject(Type enumType, int value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
public static Object ToObject(Type enumType, byte value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
[CLSCompliant(false)]
public static Object ToObject(Type enumType, ushort value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
[CLSCompliant(false)]
public static Object ToObject(Type enumType, uint value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
public static Object ToObject(Type enumType, long value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
[CLSCompliant(false)]
public static Object ToObject(Type enumType, ulong value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, unchecked((long)value));
}
private static Object ToObject(Type enumType, char value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
private static Object ToObject(Type enumType, bool value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value ? 1 : 0);
}
#endregion
}
}
| |
using System;
using System.Threading.Tasks;
using EasyNetQ.Consumer;
using EasyNetQ.FluentConfiguration;
using EasyNetQ.Producer;
namespace EasyNetQ
{
/// <summary>
/// Provides a simple Publish/Subscribe and Request/Response API for a message bus.
/// </summary>
public interface IBus : IDisposable
{
/// <summary>
/// Publishes a message.
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="message">The message to publish</param>
void Publish<T>(T message) where T : class;
/// <summary>
/// Publishes a message with a topic
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="message">The message to publish</param>
/// <param name="topic">The topic string</param>
void Publish<T>(T message, string topic) where T : class;
/// <summary>
/// Publishes a message.
/// When used with publisher confirms the task completes when the publish is confirmed.
/// Task will throw an exception if the confirm is NACK'd or times out.
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="message">The message to publish</param>
/// <returns></returns>
Task PublishAsync<T>(T message) where T : class;
/// <summary>
/// Publishes a message with a topic.
/// When used with publisher confirms the task completes when the publish is confirmed.
/// Task will throw an exception if the confirm is NACK'd or times out.
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="message">The message to publish</param>
/// <param name="topic">The topic string</param>
/// <returns></returns>
Task PublishAsync<T>(T message, string topic) where T : class;
/// <summary>
/// Subscribes to a stream of messages that match a .NET type.
/// </summary>
/// <typeparam name="T">The type to subscribe to</typeparam>
/// <param name="subscriptionId">
/// A unique identifier for the subscription. Two subscriptions with the same subscriptionId
/// and type will get messages delivered in turn. This is useful if you want multiple subscribers
/// to load balance a subscription in a round-robin fashion.
/// </param>
/// <param name="onMessage">
/// The action to run when a message arrives. When onMessage completes the message
/// recipt is Ack'd. All onMessage delegates are processed on a single thread so you should
/// avoid long running blocking IO operations. Consider using SubscribeAsync
/// </param>
/// <returns>
/// An <see cref="ISubscriptionResult"/>
/// Call Dispose on it or on its <see cref="ISubscriptionResult.ConsumerCancellation"/> to cancel the subscription.
/// </returns>
ISubscriptionResult Subscribe<T>(string subscriptionId, Action<T> onMessage) where T : class;
/// <summary>
/// Subscribes to a stream of messages that match a .NET type.
/// </summary>
/// <typeparam name="T">The type to subscribe to</typeparam>
/// <param name="subscriptionId">
/// A unique identifier for the subscription. Two subscriptions with the same subscriptionId
/// and type will get messages delivered in turn. This is useful if you want multiple subscribers
/// to load balance a subscription in a round-robin fashion.
/// </param>
/// <param name="onMessage">
/// The action to run when a message arrives. When onMessage completes the message
/// recipt is Ack'd. All onMessage delegates are processed on a single thread so you should
/// avoid long running blocking IO operations. Consider using SubscribeAsync
/// </param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithTopic("uk.london")
/// </param>
/// <returns>
/// An <see cref="ISubscriptionResult"/>
/// Call Dispose on it or on its <see cref="ISubscriptionResult.ConsumerCancellation"/> to cancel the subscription.
/// </returns>
ISubscriptionResult Subscribe<T>(string subscriptionId, Action<T> onMessage, Action<ISubscriptionConfiguration> configure)
where T : class;
/// <summary>
/// Subscribes to a stream of messages that match a .NET type.
/// Allows the subscriber to complete asynchronously.
/// </summary>
/// <typeparam name="T">The type to subscribe to</typeparam>
/// <param name="subscriptionId">
/// A unique identifier for the subscription. Two subscriptions with the same subscriptionId
/// and type will get messages delivered in turn. This is useful if you want multiple subscribers
/// to load balance a subscription in a round-robin fashion.
/// </param>
/// <param name="onMessage">
/// The action to run when a message arrives. onMessage can immediately return a Task and
/// then continue processing asynchronously. When the Task completes the message will be
/// Ack'd.
/// </param>
/// <returns>
/// An <see cref="ISubscriptionResult"/>
/// Call Dispose on it or on its <see cref="ISubscriptionResult.ConsumerCancellation"/> to cancel the subscription.
/// </returns>
ISubscriptionResult SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage) where T : class;
/// <summary>
/// Subscribes to a stream of messages that match a .NET type.
/// </summary>
/// <typeparam name="T">The type to subscribe to</typeparam>
/// <param name="subscriptionId">
/// A unique identifier for the subscription. Two subscriptions with the same subscriptionId
/// and type will get messages delivered in turn. This is useful if you want multiple subscribers
/// to load balance a subscription in a round-robin fashion.
/// </param>
/// <param name="onMessage">
/// The action to run when a message arrives. onMessage can immediately return a Task and
/// then continue processing asynchronously. When the Task completes the message will be
/// Ack'd.
/// </param>
/// <param name="configure">
/// Fluent configuration e.g. x => x.WithTopic("uk.london").WithArgument("x-message-ttl", "60")
/// </param>
/// <returns>
/// An <see cref="ISubscriptionResult"/>
/// Call Dispose on it or on its <see cref="ISubscriptionResult.ConsumerCancellation"/> to cancel the subscription.
/// </returns>
ISubscriptionResult SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage, Action<ISubscriptionConfiguration> configure)
where T : class;
/// <summary>
/// Makes an RPC style request
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type.</typeparam>
/// <param name="request">The request message.</param>
/// <returns>The response</returns>
TResponse Request<TRequest, TResponse>(TRequest request)
where TRequest : class
where TResponse : class;
/// <summary>
/// Makes an RPC style request.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type.</typeparam>
/// <param name="request">The request message.</param>
/// <returns>A task that completes when the response returns</returns>
Task<TResponse> RequestAsync<TRequest, TResponse>(TRequest request)
where TRequest : class
where TResponse : class;
/// <summary>
/// Responds to an RPC request.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type.</typeparam>
/// <param name="responder">
/// A function to run when the request is received. It should return the response.
/// </param>
IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder)
where TRequest : class
where TResponse : class;
/// <summary>
/// Responds to an RPC request.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type.</typeparam>
/// <param name="responder">
/// A function to run when the request is received. It should return the response.
/// </param>
/// <param name="configure">
/// A function for responder configuration
/// </param>
IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder, Action<IResponderConfiguration> configure)
where TRequest : class
where TResponse : class;
/// <summary>
/// Responds to an RPC request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type</typeparam>
/// <param name="responder">
/// A function to run when the request is received.
/// </param>
IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder)
where TRequest : class
where TResponse : class;
/// <summary>
/// Responds to an RPC request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The request type.</typeparam>
/// <typeparam name="TResponse">The response type</typeparam>
/// <param name="responder">
/// A function to run when the request is received.
/// </param>
/// <param name="configure">
/// A function for responder configuration
/// </param>
IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder, Action<IResponderConfiguration> configure)
where TRequest : class
where TResponse : class;
/// <summary>
/// Send a message directly to a queue
/// </summary>
/// <typeparam name="T">The type of message to send</typeparam>
/// <param name="queue">The queue to send to</param>
/// <param name="message">The message</param>
void Send<T>(string queue, T message) where T : class;
/// <summary>
/// Send a message directly to a queue
/// </summary>
/// <typeparam name="T">The type of message to send</typeparam>
/// <param name="queue">The queue to send to</param>
/// <param name="message">The message</param>
Task SendAsync<T>(string queue, T message) where T : class;
/// <summary>
/// Receive messages from a queue.
/// Multiple calls to Receive for the same queue, but with different message types
/// will add multiple message handlers to the same consumer.
/// </summary>
/// <typeparam name="T">The type of message to receive</typeparam>
/// <param name="queue">The queue to receive from</param>
/// <param name="onMessage">The message handler</param>
IDisposable Receive<T>(string queue, Action<T> onMessage) where T : class;
/// <summary>
/// Receive messages from a queue.
/// Multiple calls to Receive for the same queue, but with different message types
/// will add multiple message handlers to the same consumer.
/// </summary>
/// <typeparam name="T">The type of message to receive</typeparam>
/// <param name="queue">The queue to receive from</param>
/// <param name="onMessage">The message handler</param>
/// <param name="configure">Action to configure consumer with</param>
IDisposable Receive<T>(string queue, Action<T> onMessage, Action<IConsumerConfiguration> configure) where T : class;
/// <summary>
/// Receive messages from a queue.
/// Multiple calls to Receive for the same queue, but with different message types
/// will add multiple message handlers to the same consumer.
/// </summary>
/// <typeparam name="T">The type of message to receive</typeparam>
/// <param name="queue">The queue to receive from</param>
/// <param name="onMessage">The asychronous message handler</param>
IDisposable Receive<T>(string queue, Func<T, Task> onMessage) where T : class;
/// <summary>
/// Receive messages from a queue.
/// Multiple calls to Receive for the same queue, but with different message types
/// will add multiple message handlers to the same consumer.
/// </summary>
/// <typeparam name="T">The type of message to receive</typeparam>
/// <param name="queue">The queue to receive from</param>
/// <param name="onMessage">The asychronous message handler</param>
/// <param name="configure">Action to configure consumer with</param>
IDisposable Receive<T>(string queue, Func<T, Task> onMessage, Action<IConsumerConfiguration> configure) where T : class;
/// <summary>
/// Receive a message from the specified queue. Dispatch them to the given handlers
/// </summary>
/// <param name="queue">The queue to take messages from</param>
/// <param name="addHandlers">A function to add handlers</param>
/// <returns>Consumer cancellation. Call Dispose to stop consuming</returns>
IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers);
/// <summary>
/// Receive a message from the specified queue. Dispatch them to the given handlers
/// </summary>
/// <param name="queue">The queue to take messages from</param>
/// <param name="addHandlers">A function to add handlers</param>
/// <param name="configure">Action to configure consumer with</param>
/// <returns>Consumer cancellation. Call Dispose to stop consuming</returns>
IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers, Action<IConsumerConfiguration> configure);
/// <summary>
/// True if the bus is connected, False if it is not.
/// </summary>
bool IsConnected { get; }
/// <summary>
/// Return the advanced EasyNetQ advanced API.
/// </summary>
IAdvancedBus Advanced { get; }
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using OpenSource.UPnP;
using OpenSource.UPnP.AV.CdsMetadata;
using OpenSource.UPnP.AV.MediaServer.CP;
using OpenSource.UPnP.AV.RENDERER.Device;
namespace UPnPRenderer
{
/// <summary>
/// Summary description for MainForm.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
public delegate void FormCreator(AVRenderer r, AVConnection c);
private UPnPDevice device;
private AVRenderer r;
private int MaxConnections = 0;
private Hashtable ConnectionTable = new Hashtable();
private System.Windows.Forms.TextBox InfoStringBox;
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem menuItem16;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.MenuItem startMenuItem;
private System.Windows.Forms.MenuItem exitMenuItem;
private System.Windows.Forms.MenuItem pfcNoneMenuItem;
private System.Windows.Forms.MenuItem pfc1MenuItem;
private System.Windows.Forms.MenuItem pfc2MenuItem;
private System.Windows.Forms.MenuItem pfc5MenuItem;
private System.Windows.Forms.MenuItem pfc10MenuItem;
private System.Windows.Forms.MenuItem pfc100MenuItem;
private System.Windows.Forms.MenuItem supportNextContentUriMenuItem;
private System.Windows.Forms.MenuItem pfcMenuItem;
private System.Windows.Forms.MenuItem supportRecordMenuItem;
private System.Windows.Forms.MenuItem supportRecordQualityMenuItem;
private System.Windows.Forms.MenuItem menuItem4;
private System.Windows.Forms.MenuItem helpMenuItem;
private System.Windows.Forms.MenuItem menuItem6;
private IContainer components;
public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
InfoStringBox.Text = "http-get:*:audio/mpegurl:*\r\nhttp-get:*:audio/mp3:*\r\nhttp-get:*:audio/mpeg:*\r\nhttp-get:*:audio/x-ms-wma:*\r\nhttp-get:*:audio/wma:*\r\nhttp-get:*:audio/mpeg3:*\r\nhttp-get:*:video/x-ms-wmv:*\r\nhttp-get:*:video/x-ms-asf:*\r\nhttp-get:*:video/x-ms-avi:*\r\nhttp-get:*:video/mpeg:*";
InfoStringBox.SelectionStart = 0;
InfoStringBox.SelectionLength = 0;
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.InfoStringBox = new System.Windows.Forms.TextBox();
this.mainMenu = new System.Windows.Forms.MainMenu(this.components);
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.startMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem16 = new System.Windows.Forms.MenuItem();
this.exitMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.pfcMenuItem = new System.Windows.Forms.MenuItem();
this.pfcNoneMenuItem = new System.Windows.Forms.MenuItem();
this.pfc1MenuItem = new System.Windows.Forms.MenuItem();
this.pfc2MenuItem = new System.Windows.Forms.MenuItem();
this.pfc5MenuItem = new System.Windows.Forms.MenuItem();
this.pfc10MenuItem = new System.Windows.Forms.MenuItem();
this.pfc100MenuItem = new System.Windows.Forms.MenuItem();
this.supportNextContentUriMenuItem = new System.Windows.Forms.MenuItem();
this.supportRecordMenuItem = new System.Windows.Forms.MenuItem();
this.supportRecordQualityMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.helpMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem6 = new System.Windows.Forms.MenuItem();
this.menuItem4 = new System.Windows.Forms.MenuItem();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// InfoStringBox
//
this.InfoStringBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.InfoStringBox.Location = new System.Drawing.Point(12, 28);
this.InfoStringBox.Multiline = true;
this.InfoStringBox.Name = "InfoStringBox";
this.InfoStringBox.Size = new System.Drawing.Size(274, 245);
this.InfoStringBox.TabIndex = 9;
//
// mainMenu
//
this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1,
this.menuItem3,
this.menuItem2});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.startMenuItem,
this.menuItem16,
this.exitMenuItem});
this.menuItem1.Text = "&File";
//
// startMenuItem
//
this.startMenuItem.Index = 0;
this.startMenuItem.Text = "Start AV Renderer";
this.startMenuItem.Click += new System.EventHandler(this.startMenuItem_Click);
//
// menuItem16
//
this.menuItem16.Index = 1;
this.menuItem16.Text = "-";
//
// exitMenuItem
//
this.exitMenuItem.Index = 2;
this.exitMenuItem.Text = "E&xit";
//
// menuItem3
//
this.menuItem3.Index = 1;
this.menuItem3.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.pfcMenuItem,
this.supportNextContentUriMenuItem,
this.supportRecordMenuItem,
this.supportRecordQualityMenuItem});
this.menuItem3.Text = "&Support";
//
// pfcMenuItem
//
this.pfcMenuItem.Index = 0;
this.pfcMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.pfcNoneMenuItem,
this.pfc1MenuItem,
this.pfc2MenuItem,
this.pfc5MenuItem,
this.pfc10MenuItem,
this.pfc100MenuItem});
this.pfcMenuItem.Text = "Prepare for Connection";
//
// pfcNoneMenuItem
//
this.pfcNoneMenuItem.Checked = true;
this.pfcNoneMenuItem.Index = 0;
this.pfcNoneMenuItem.Text = "Not Supported";
this.pfcNoneMenuItem.Click += new System.EventHandler(this.pfcNoneMenuItem_Click);
//
// pfc1MenuItem
//
this.pfc1MenuItem.Index = 1;
this.pfc1MenuItem.Text = "1 Instance";
this.pfc1MenuItem.Click += new System.EventHandler(this.pfcNoneMenuItem_Click);
//
// pfc2MenuItem
//
this.pfc2MenuItem.Index = 2;
this.pfc2MenuItem.Text = "2 Instances";
this.pfc2MenuItem.Click += new System.EventHandler(this.pfcNoneMenuItem_Click);
//
// pfc5MenuItem
//
this.pfc5MenuItem.Index = 3;
this.pfc5MenuItem.Text = "5 Instances";
this.pfc5MenuItem.Click += new System.EventHandler(this.pfcNoneMenuItem_Click);
//
// pfc10MenuItem
//
this.pfc10MenuItem.Index = 4;
this.pfc10MenuItem.Text = "10 Instances";
this.pfc10MenuItem.Click += new System.EventHandler(this.pfcNoneMenuItem_Click);
//
// pfc100MenuItem
//
this.pfc100MenuItem.Index = 5;
this.pfc100MenuItem.Text = "100 Instances";
this.pfc100MenuItem.Click += new System.EventHandler(this.pfcNoneMenuItem_Click);
//
// supportNextContentUriMenuItem
//
this.supportNextContentUriMenuItem.Index = 1;
this.supportNextContentUriMenuItem.Text = "Next Content URI";
this.supportNextContentUriMenuItem.Click += new System.EventHandler(this.supportNextContentUriMenuItem_Click);
//
// supportRecordMenuItem
//
this.supportRecordMenuItem.Index = 2;
this.supportRecordMenuItem.Text = "Record";
this.supportRecordMenuItem.Click += new System.EventHandler(this.supportRecordMenuItem_Click);
//
// supportRecordQualityMenuItem
//
this.supportRecordQualityMenuItem.Index = 3;
this.supportRecordQualityMenuItem.Text = "Record Quality Mode";
this.supportRecordQualityMenuItem.Click += new System.EventHandler(this.supportRecordQualityMenuItem_Click);
//
// menuItem2
//
this.menuItem2.Index = 2;
this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.helpMenuItem,
this.menuItem6,
this.menuItem4});
this.menuItem2.Text = "&Help";
//
// helpMenuItem
//
this.helpMenuItem.Index = 0;
this.helpMenuItem.Shortcut = System.Windows.Forms.Shortcut.F1;
this.helpMenuItem.Text = "&Help Topics";
this.helpMenuItem.Click += new System.EventHandler(this.helpMenuItem_Click);
//
// menuItem6
//
this.menuItem6.Index = 1;
this.menuItem6.Text = "-";
//
// menuItem4
//
this.menuItem4.Index = 2;
this.menuItem4.Text = "&Show Debug Information";
this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click);
//
// label1
//
this.label1.Location = new System.Drawing.Point(9, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(128, 16);
this.label1.TabIndex = 13;
this.label1.Text = "Supported Mime Types";
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(298, 285);
this.Controls.Add(this.label1);
this.Controls.Add(this.InfoStringBox);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Menu = this.mainMenu;
this.Name = "MainForm";
this.Text = "AV Media Renderer";
this.Load += new System.EventHandler(this.MainForm_Load);
this.HelpRequested += new System.Windows.Forms.HelpEventHandler(this.MainForm_HelpRequested);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void ClosedConnectionSink(AVRenderer sender, AVConnection c)
{
RendererForm f = (RendererForm)ConnectionTable[c];
ConnectionTable.Remove(c);
f.Close();
}
private void NewConnectionSink(AVRenderer sender, AVConnection c)
{
object[] args = new Object[2];
args[0] = sender;
args[1] = c;
Invoke(new FormCreator(FormSink),args);
}
private void FormSink(AVRenderer r, AVConnection c)
{
RendererForm f = new RendererForm(c);
ConnectionTable[c] = f;
f.Show();
}
private void button1_Click(object sender, System.EventArgs e)
{
}
private void DvSink(UPnPSmartControlPoint sender, UPnPDevice Dv)
{
}
private void DebugButton_Click(object sender, System.EventArgs e)
{
}
private void supportNextContentUriMenuItem_Click(object sender, System.EventArgs e)
{
supportNextContentUriMenuItem.Checked = !supportNextContentUriMenuItem.Checked;
}
private void pfcNoneMenuItem_Click(object sender, System.EventArgs e)
{
foreach (MenuItem i in pfcMenuItem.MenuItems) {i.Checked = false;}
((MenuItem)sender).Checked = true;
if (sender == pfcNoneMenuItem) MaxConnections = 0;
if (sender == pfc1MenuItem) MaxConnections = 1;
if (sender == pfc2MenuItem) MaxConnections = 2;
if (sender == pfc5MenuItem) MaxConnections = 5;
if (sender == pfc10MenuItem) MaxConnections = 10;
if (sender == pfc100MenuItem) MaxConnections = 100;
}
public void NullMethod()
{
}
private void startMenuItem_Click(object sender, System.EventArgs e)
{
startMenuItem.Enabled = false;
foreach (MenuItem i in pfcMenuItem.MenuItems) {i.Enabled = false;}
foreach (MenuItem i in menuItem3.MenuItems) {i.Enabled = false;}
InfoStringBox.Enabled = false;
device = UPnPDevice.CreateRootDevice(900,1,"");
device.UniqueDeviceName = Guid.NewGuid().ToString();
device.StandardDeviceType = "MediaRenderer";
device.FriendlyName = "Media Renderer (" + System.Net.Dns.GetHostName() + ")";
device.HasPresentation = false;
device.Manufacturer = "OpenSource";
device.ManufacturerURL = "http://opentools.homeip.net/";
device.PresentationURL = "/";
device.HasPresentation = true;
device.ModelName = "AV Renderer";
device.ModelDescription = "Media Renderer Device";
device.ModelURL = new Uri("http://opentools.homeip.net/");
UPnPService ts = new UPnPService(1, "EmptyService", "EmptyService", true, this);
ts.AddMethod("NullMethod");
//device.AddService(ts);
DText p = new DText();
p.ATTRMARK = "\r\n";
p[0] = this.InfoStringBox.Text;
int len = p.DCOUNT();
ProtocolInfoString[] istring = new ProtocolInfoString[len];
for(int i=1;i<=len;++i)
{
istring[i-1] = new ProtocolInfoString(p[i]);
}
r = new AVRenderer(MaxConnections, istring, new AVRenderer.ConnectionHandler(NewConnectionSink));
r.OnClosedConnection += new AVRenderer.ConnectionHandler(ClosedConnectionSink);
if (supportRecordMenuItem.Checked == false)
{
r.AVT.RemoveAction_Record();
}
if (supportRecordQualityMenuItem.Checked == false)
{
r.AVT.RemoveAction_SetRecordQualityMode();
}
if (supportNextContentUriMenuItem.Checked == false)
{
r.AVT.RemoveAction_SetNextAVTransportURI();
}
if (MaxConnections == 0)
{
r.Manager.RemoveAction_PrepareForConnection();
r.Manager.RemoveAction_ConnectionComplete();
}
r.AVT.GetUPnPService().GetStateVariableObject("CurrentPlayMode").AllowedStringValues = new String[3]{"NORMAL","REPEAT_ALL","INTRO"};
r.Control.GetUPnPService().GetStateVariableObject("A_ARG_TYPE_Channel").AllowedStringValues = new String[3]{"Master","LF","RF"};
r.Control.GetUPnPService().GetStateVariableObject("RedVideoBlackLevel").SetRange((ushort)0,(ushort)100,(ushort)1);
r.Control.GetUPnPService().GetStateVariableObject("GreenVideoBlackLevel").SetRange((ushort)0,(ushort)100,(ushort)1);
r.Control.GetUPnPService().GetStateVariableObject("BlueVideoBlackLevel").SetRange((ushort)0,(ushort)100,(ushort)1);
r.Control.GetUPnPService().GetStateVariableObject("RedVideoGain").SetRange((ushort)0,(ushort)100,(ushort)1);
r.Control.GetUPnPService().GetStateVariableObject("GreenVideoGain").SetRange((ushort)0,(ushort)100,(ushort)1);
r.Control.GetUPnPService().GetStateVariableObject("BlueVideoGain").SetRange((ushort)0,(ushort)100,(ushort)1);
r.Control.GetUPnPService().GetStateVariableObject("Brightness").SetRange((ushort)0,(ushort)100,(ushort)1);
r.Control.GetUPnPService().GetStateVariableObject("Contrast").SetRange((ushort)0,(ushort)100,(ushort)1);
r.Control.GetUPnPService().GetStateVariableObject("Sharpness").SetRange((ushort)0,(ushort)100,(ushort)1);
r.Control.GetUPnPService().GetStateVariableObject("Volume").SetRange((UInt16)0,(UInt16)100,(ushort)1);
device.AddService(r.Control);
device.AddService(r.AVT);
device.AddService(r.Manager);
//device.AddDevice(r);
device.StartDevice();
//r.Start();
}
private void supportRecordMenuItem_Click(object sender, System.EventArgs e)
{
supportRecordMenuItem.Checked = !supportRecordMenuItem.Checked;
}
private void supportRecordQualityMenuItem_Click(object sender, System.EventArgs e)
{
supportRecordQualityMenuItem.Checked = !supportRecordQualityMenuItem.Checked;
}
private void menuItem4_Click(object sender, System.EventArgs e)
{
OpenSource.Utilities.InstanceTracker.Display();
}
private void helpMenuItem_Click(object sender, System.EventArgs e)
{
Help.ShowHelp(this,"ToolsHelp.chm",HelpNavigator.KeywordIndex,"AV MediaRenderer");
}
private void MainForm_HelpRequested(object sender, System.Windows.Forms.HelpEventArgs hlpevent)
{
Help.ShowHelp(this,"ToolsHelp.chm",HelpNavigator.KeywordIndex,"AV MediaRenderer");
}
private void MainForm_Load(object sender, EventArgs e)
{
//startMenuItem_Click(this, null);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
/// <summary>
/// UInt16.Parse(String, NumberStyles, IFormatProvider)
/// </summary>
public class UInt16Parse
{
public static int Main()
{
UInt16Parse ui32ct2 = new UInt16Parse();
TestLibrary.TestFramework.BeginTestCase("for method: UInt16.Parse(String, NumberStyles, IFormatProvider)");
if (ui32ct2.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;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
string errorDesc;
UInt16 actualValue;
NumberStyles numberStyle;
CultureInfo culture;
IFormatProvider provider;
numberStyle = NumberStyles.Integer;
string strValue = UInt16.MaxValue.ToString();
strValue = " " + strValue + " ";
culture = CultureInfo.InvariantCulture;
provider = culture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest1: UInt16.MaxValue, number style is NumberStyles.Integer.");
try
{
actualValue = UInt16.Parse(strValue, numberStyle, provider);
if (actualValue != UInt16.MaxValue)
{
errorDesc = "The parse value of " + strValue + " with number styles " +
numberStyle + " and format " + culture.NumberFormat +
" is not the value " + UInt16.MaxValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("001", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc = "\nThe string representation is " + strValue + " with number styles " +
numberStyle + " and format " + culture.NumberFormat;
TestLibrary.TestFramework.LogError("002", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string errorDesc;
UInt16 actualValue;
NumberStyles numberStyle;
CultureInfo culture;
IFormatProvider provider;
string strValue = UInt16.MinValue.ToString();
numberStyle = NumberStyles.None;
culture = CultureInfo.InvariantCulture;
provider = culture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest2: UInt16.MinValue, number style is NumberStyles.None.");
try
{
actualValue = UInt16.Parse(strValue, numberStyle,provider);
if (actualValue != UInt16.MinValue)
{
errorDesc = "The parse value of " + strValue + " with number styles " +
numberStyle + " and format " + culture.NumberFormat +
" is not the value " + UInt16.MaxValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("003", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc = "\nThe string representation is " + strValue + " with number styles " +
numberStyle + " and format " + culture.NumberFormat;
TestLibrary.TestFramework.LogError("004", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string errorDesc;
UInt16 expectedValue;
UInt16 actualValue;
NumberStyles numberStyle;
CultureInfo culture;
IFormatProvider provider;
expectedValue = (UInt16)this.GetInt32(0, UInt16.MaxValue);
string strValue = expectedValue.ToString("x");
numberStyle = NumberStyles.HexNumber;
culture = CultureInfo.InvariantCulture;
provider = culture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest3: random hexadecimal UInt16 value between 0 and UInt16.MaxValue");
try
{
actualValue = UInt16.Parse(strValue, numberStyle,provider);
if (actualValue != expectedValue)
{
errorDesc = "The parse value of " + strValue + " with number styles " +
numberStyle + " and format " + culture.NumberFormat +
" is not the value " + UInt16.MaxValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc = "\nThe string representation is " + strValue + " with number styles " +
numberStyle + " and format " + culture.NumberFormat;
TestLibrary.TestFramework.LogError("006", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string errorDesc;
UInt16 expectedValue;
UInt16 actualValue;
NumberStyles numberStyle;
CultureInfo culture;
IFormatProvider provider;
string strValue;
expectedValue = (UInt16)this.GetInt32(0, UInt16.MaxValue);
strValue = expectedValue.ToString("c");
numberStyle = NumberStyles.Currency;
culture = CultureInfo.CurrentCulture;
provider = culture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest4: random currency UInt16 value between 0 and UInt16.MaxValue");
try
{
actualValue = UInt16.Parse(strValue, numberStyle,provider);
if (actualValue != expectedValue)
{
errorDesc = "The parse value of " + strValue + " with number styles " +
numberStyle + " and format " + culture.NumberFormat +
" is not the value " + UInt16.MaxValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc = "\nThe string representation is " + strValue + " with number styles " +
numberStyle + " and format " + culture.NumberFormat;
TestLibrary.TestFramework.LogError("008", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string errorDesc;
UInt16 expectedValue;
UInt16 actualValue;
NumberStyles numberStyle;
CultureInfo culture;
IFormatProvider provider;
expectedValue = (UInt16)this.GetInt32(0, UInt16.MaxValue);
string strValue = expectedValue.ToString("f");
numberStyle = NumberStyles.Any;
culture = CultureInfo.InvariantCulture;
provider = culture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest5: random UInt16 value between 0 and UInt16.MaxValue, number styles is NumberStyels.Any");
try
{
actualValue = UInt16.Parse(strValue, numberStyle);
if (actualValue != expectedValue)
{
errorDesc = "The parse value of " + strValue + " with number styles " +
numberStyle + " and format " + culture.NumberFormat +
" is not the value " + UInt16.MaxValue +
" as expected: actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("009", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc = "\nThe string representation is " + strValue + " with number styles " +
numberStyle + " and format " + culture.NumberFormat;
TestLibrary.TestFramework.LogError("010", errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//ArgumentNullException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: string representation is a null reference";
string errorDesc;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
UInt16.Parse(null, NumberStyles.Integer, null);
errorDesc = "ArgumentNullException is not thrown as expected.";
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentNullException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//FormatException
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: String representation is not in the correct format";
string errorDesc;
string strValue;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strValue = "Incorrect";
UInt16.Parse(strValue, NumberStyles.Integer, null);
errorDesc = "FormatException is not thrown as expected.";
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (FormatException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_ID = "N003";
const string c_TEST_DESC = "NegTest3: String representation does not match the correct number style";
string errorDesc;
string strValue;
strValue = this.GetInt32(0, UInt16.MaxValue).ToString("c");
NumberStyles numberStyle = NumberStyles.None;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
UInt16.Parse(strValue, numberStyle, null);
errorDesc = "FormatException is not thrown as expected.";
errorDesc += string.Format("\nString representation is {0}, number styles is {1}",
strValue,
numberStyle);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (FormatException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nString representation is {0}, number styles is {1}",
strValue,
numberStyle);
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//OverflowException
public bool NegTest4()
{
bool retVal = true;
const string c_TEST_ID = "N004";
const string c_TEST_DESC = "NegTest4: String representation is greater than UInt16.MaxValue";
string errorDesc;
string strValue;
int i;
i = this.GetInt32(UInt16.MaxValue + 1, int.MaxValue);
strValue = i.ToString();
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
UInt16.Parse(strValue, NumberStyles.None, null);
errorDesc = "OverflowException is not thrown as expected.";
errorDesc += string.Format("\nString representation is {0}, number styles is {1}",
strValue,
NumberStyles.None);
TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nString representation is {0}, number styles is {1}",
strValue,
NumberStyles.None);
TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
const string c_TEST_ID = "N005";
const string c_TEST_DESC = "NegTest5: String representation is less than UInt16.MaxValue";
string errorDesc;
string strValue;
int i;
i = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
strValue = i.ToString();
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
UInt16.Parse(strValue, NumberStyles.Integer, null);
errorDesc = "OverflowException is not thrown as expected.";
errorDesc += string.Format("\nString representation is {0}, number styles is {1}",
strValue,
NumberStyles.Integer);
TestLibrary.TestFramework.LogError("017" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nString representation is {0}, number styles is {1}",
strValue,
NumberStyles.Integer);
TestLibrary.TestFramework.LogError("018" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//ArgumentException
public bool NegTest6()
{
bool retVal = true;
const string c_TEST_ID = "N006";
const string c_TEST_DESC = "NegTest6: style is not a NumberStyles value.";
string errorDesc;
string strValue;
UInt16 i;
i = (UInt16)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1));
strValue = i.ToString();
NumberStyles numberStyle = (NumberStyles)(0x204 + TestLibrary.Generator.GetInt16(-55));
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
UInt16.Parse(strValue, numberStyle, null);
errorDesc = "ArgumentException is not thrown as expected.";
errorDesc += string.Format("\nString representation is {0}, number styles is {1}",
strValue,
numberStyle);
TestLibrary.TestFramework.LogError("019" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nString representation is {0}, number styles is {1}",
strValue,
numberStyle);
TestLibrary.TestFramework.LogError("020" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
const string c_TEST_ID = "N007";
const string c_TEST_DESC = "NegTest7: style is not a combination of AllowHexSpecifier and HexNumber values.";
string errorDesc;
string strValue;
UInt16 i;
i = (UInt16)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1));
strValue = i.ToString();
NumberStyles numberStyle = (NumberStyles)(NumberStyles.AllowHexSpecifier |
NumberStyles.AllowCurrencySymbol);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
UInt16.Parse(strValue, numberStyle, null);
errorDesc = "ArgumentException is not thrown as expected.";
errorDesc += string.Format("\nString representation is {0}, number styles is {1}",
strValue,
numberStyle);
TestLibrary.TestFramework.LogError("021" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nString representation is {0}, number styles is {1}",
strValue,
numberStyle);
TestLibrary.TestFramework.LogError("022" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region ForTestObject
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;
}
#endregion
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.CoreModules.World.Wind;
namespace OpenSim.Region.CoreModules
{
public class WindModule : IWindModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private uint m_frame = 0;
private uint m_frameLastUpdateClientArray = 0;
private int m_frameUpdateRate = 150;
//private Random m_rndnums = new Random(Environment.TickCount);
private Scene m_scene = null;
private bool m_ready = false;
private bool m_enabled = false;
private IWindModelPlugin m_activeWindPlugin = null;
private const string m_dWindPluginName = "SimpleRandomWind";
private Dictionary<string, IWindModelPlugin> m_availableWindPlugins = new Dictionary<string, IWindModelPlugin>();
// Simplified windSpeeds based on the fact that the client protocal tracks at a resolution of 16m
private Vector2[] windSpeeds = new Vector2[16 * 16];
#region IRegion Methods
public void Initialise(Scene scene, IConfigSource config)
{
IConfig windConfig = config.Configs["Wind"];
string desiredWindPlugin = m_dWindPluginName;
if (windConfig != null)
{
m_enabled = windConfig.GetBoolean("enabled", true);
m_frameUpdateRate = windConfig.GetInt("wind_update_rate", 150);
// Determine which wind model plugin is desired
if (windConfig.Contains("wind_plugin"))
{
desiredWindPlugin = windConfig.GetString("wind_plugin");
}
}
if (m_enabled)
{
m_log.InfoFormat("[WIND] Enabled with an update rate of {0} frames.", m_frameUpdateRate);
m_scene = scene;
m_frame = 0;
// Register all the Wind Model Plug-ins
foreach (IWindModelPlugin windPlugin in AddinManager.GetExtensionObjects("/OpenSim/WindModule", false))
{
m_log.InfoFormat("[WIND] Found Plugin: {0}", windPlugin.Name);
m_availableWindPlugins.Add(windPlugin.Name, windPlugin);
}
// Check for desired plugin
if (m_availableWindPlugins.ContainsKey(desiredWindPlugin))
{
m_activeWindPlugin = m_availableWindPlugins[desiredWindPlugin];
m_log.InfoFormat("[WIND] {0} plugin found, initializing.", desiredWindPlugin);
if (windConfig != null)
{
m_activeWindPlugin.Initialise();
m_activeWindPlugin.WindConfig(m_scene, windConfig);
}
}
// if the plug-in wasn't found, default to no wind.
if (m_activeWindPlugin == null)
{
m_log.ErrorFormat("[WIND] Could not find specified wind plug-in: {0}", desiredWindPlugin);
m_log.ErrorFormat("[WIND] Defaulting to no wind.");
}
// This one puts an entry in the main help screen
m_scene.AddCommand(this, String.Empty, "wind", "Usage: wind <plugin> <param> [value] - Get or Update Wind paramaters", null);
// This one enables the ability to type just the base command without any parameters
m_scene.AddCommand(this, "wind", "", "", HandleConsoleCommand);
// Get a list of the parameters for each plugin
foreach (IWindModelPlugin windPlugin in m_availableWindPlugins.Values)
{
m_scene.AddCommand(this, String.Format("wind base wind_plugin {0}", windPlugin.Name), String.Format("{0} - {1}", windPlugin.Name, windPlugin.Description), "", HandleConsoleBaseCommand);
m_scene.AddCommand(this, String.Format("wind base wind_update_rate"), "Change the wind update rate.", "", HandleConsoleBaseCommand);
foreach (KeyValuePair<string, string> kvp in windPlugin.WindParams())
{
m_scene.AddCommand(this, String.Format("wind {0} {1}", windPlugin.Name, kvp.Key), String.Format("{0} : {1} - {2}", windPlugin.Name, kvp.Key, kvp.Value), "", HandleConsoleParamCommand);
}
}
// Register event handlers for when Avatars enter the region, and frame ticks
m_scene.EventManager.OnFrame += WindUpdate;
m_scene.EventManager.OnMakeRootAgent += OnAgentEnteredRegion;
// Register the wind module
m_scene.RegisterModuleInterface<IWindModule>(this);
// Generate initial wind values
GenWindPos();
// Mark Module Ready for duty
m_ready = true;
}
}
public void PostInitialise()
{
}
public void Close()
{
if (m_enabled)
{
m_ready = false;
// REVIEW: If a region module is closed, is there a possibility that it'll re-open/initialize ??
m_activeWindPlugin = null;
foreach (IWindModelPlugin windPlugin in m_availableWindPlugins.Values)
{
windPlugin.Dispose();
}
m_availableWindPlugins.Clear();
// Remove our hooks
m_scene.EventManager.OnFrame -= WindUpdate;
m_scene.EventManager.OnMakeRootAgent -= OnAgentEnteredRegion;
}
}
public string Name
{
get { return "WindModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
#region Console Commands
private void ValidateConsole()
{
if (m_scene.ConsoleScene() == null)
{
// FIXME: If console region is root then this will be printed by every module. Currently, there is no
// way to prevent this, short of making the entire module shared (which is complete overkill).
// One possibility is to return a bool to signal whether the module has completely handled the command
m_log.InfoFormat("[WIND]: Please change to a specific region in order to set Sun parameters.");
return;
}
if (m_scene.ConsoleScene() != m_scene)
{
m_log.InfoFormat("[WIND]: Console Scene is not my scene.");
return;
}
}
/// <summary>
/// Base console command handler, only used if a person specifies the base command with now options
/// </summary>
private void HandleConsoleCommand(string module, string[] cmdparams)
{
ValidateConsole();
m_log.Info("[WIND] The wind command can be used to change the currently active wind model plugin and update the parameters for wind plugins.");
}
/// <summary>
/// Called to change the active wind model plugin
/// </summary>
private void HandleConsoleBaseCommand(string module, string[] cmdparams)
{
ValidateConsole();
if ((cmdparams.Length != 4)
|| !cmdparams[1].Equals("base"))
{
m_log.Info("[WIND] Invalid parameters to change parameters for Wind module base, usage: wind base <parameter> <value>");
return;
}
switch (cmdparams[2])
{
case "wind_update_rate":
int newRate = 1;
if (int.TryParse(cmdparams[3], out newRate))
{
m_frameUpdateRate = newRate;
}
else
{
m_log.InfoFormat("[WIND] Invalid value {0} specified for {1}", cmdparams[3], cmdparams[2]);
return;
}
break;
case "wind_plugin":
string desiredPlugin = cmdparams[3];
if (desiredPlugin.Equals(m_activeWindPlugin.Name))
{
m_log.InfoFormat("[WIND] Wind model plugin {0} is already active", cmdparams[3]);
return;
}
if (m_availableWindPlugins.ContainsKey(desiredPlugin))
{
m_activeWindPlugin = m_availableWindPlugins[cmdparams[3]];
m_log.InfoFormat("[WIND] {0} wind model plugin now active", m_activeWindPlugin.Name);
}
else
{
m_log.InfoFormat("[WIND] Could not find wind model plugin {0}", desiredPlugin);
}
break;
}
}
/// <summary>
/// Called to change plugin parameters.
/// </summary>
private void HandleConsoleParamCommand(string module, string[] cmdparams)
{
ValidateConsole();
// wind <plugin> <param> [value]
if ((cmdparams.Length != 4)
&& (cmdparams.Length != 3))
{
m_log.Info("[WIND] Usage: wind <plugin> <param> [value]");
return;
}
string plugin = cmdparams[1];
string param = cmdparams[2];
float value = 0f;
if (cmdparams.Length == 4)
{
if (!float.TryParse(cmdparams[3], out value))
{
m_log.InfoFormat("[WIND] Invalid value {0}", cmdparams[3]);
}
try
{
WindParamSet(plugin, param, value);
}
catch (Exception e)
{
m_log.InfoFormat("[WIND] {0}", e.Message);
}
}
else
{
try
{
value = WindParamGet(plugin, param);
m_log.InfoFormat("[WIND] {0} : {1}", param, value);
}
catch (Exception e)
{
m_log.InfoFormat("[WIND] {0}", e.Message);
}
}
}
#endregion
#region IWindModule Methods
/// <summary>
/// Retrieve the wind speed at the given region coordinate. This
/// implimentation ignores Z.
/// </summary>
/// <param name="x">0...255</param>
/// <param name="y">0...255</param>
public Vector3 WindSpeed(int x, int y, int z)
{
if (m_activeWindPlugin != null)
{
return m_activeWindPlugin.WindSpeed(x, y, z);
}
else
{
return new Vector3(0.0f, 0.0f, 0.0f);
}
}
public void WindParamSet(string plugin, string param, float value)
{
if (m_availableWindPlugins.ContainsKey(plugin))
{
IWindModelPlugin windPlugin = m_availableWindPlugins[plugin];
windPlugin.WindParamSet(param, value);
m_log.InfoFormat("[WIND] {0} set to {1}", param, value);
}
else
{
throw new Exception(String.Format("Could not find plugin {0}", plugin));
}
}
public float WindParamGet(string plugin, string param)
{
if (m_availableWindPlugins.ContainsKey(plugin))
{
IWindModelPlugin windPlugin = m_availableWindPlugins[plugin];
return windPlugin.WindParamGet(param);
}
else
{
throw new Exception(String.Format("Could not find plugin {0}", plugin));
}
}
public string WindActiveModelPluginName
{
get
{
if (m_activeWindPlugin != null)
{
return m_activeWindPlugin.Name;
}
else
{
return String.Empty;
}
}
}
#endregion
/// <summary>
/// Called on each frame update. Updates the wind model and clients as necessary.
/// </summary>
public void WindUpdate()
{
if (((m_frame++ % m_frameUpdateRate) != 0) || !m_ready)
{
return;
}
GenWindPos();
SendWindAllClients();
}
public void OnAgentEnteredRegion(ScenePresence avatar)
{
if (m_ready)
{
if (m_activeWindPlugin != null)
{
// Ask wind plugin to generate a LL wind array to be cached locally
// Try not to update this too often, as it may involve array copies
if (m_frame >= (m_frameLastUpdateClientArray + m_frameUpdateRate))
{
windSpeeds = m_activeWindPlugin.WindLLClientArray();
m_frameLastUpdateClientArray = m_frame;
}
}
avatar.ControllingClient.SendWindData(windSpeeds);
}
}
private void SendWindAllClients()
{
if (m_ready)
{
List<ScenePresence> avatars = m_scene.GetAvatars();
if (avatars.Count > 0)
{
// Ask wind plugin to generate a LL wind array to be cached locally
// Try not to update this too often, as it may involve array copies
if (m_frame >= (m_frameLastUpdateClientArray + m_frameUpdateRate))
{
windSpeeds = m_activeWindPlugin.WindLLClientArray();
m_frameLastUpdateClientArray = m_frame;
}
foreach (ScenePresence avatar in avatars)
{
if (!avatar.IsChildAgent)
avatar.ControllingClient.SendWindData(windSpeeds);
}
}
}
}
/// <summary>
/// Calculate the sun's orbital position and its velocity.
/// </summary>
private void GenWindPos()
{
if (m_activeWindPlugin != null)
{
// Tell Wind Plugin to update it's wind data
m_activeWindPlugin.WindUpdate(m_frame);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#region Compact Binary format
/*
.----------.--------------. .----------.---------.
struct (v1) | fields | BT_STOP_BASE |...| fields | BT_STOP |
'----------'--------------' '----------'---------'
.----------.----------.--------------. .----------.---------.
struct (v2) | length | fields | BT_STOP_BASE |...| fields | BT_STOP |
'----------'----------'--------------' '----------'---------'
length variable int encoded uint32 length of following fields, up to and
including BT_STOP but excluding length itself.
.----------.----------. .----------.
fields | field | field |...| field |
'----------'----------' '----------'
.----------.----------.
field | id+type | value |
'----------'----------'
.---.---.---.---.---.---.---.---. i - id bits
id+type 0 <= id <= 5 | i | i | i | t | t | t | t | t | t - type bits
'---'---'---'---'---'---'---'---' v - value bits
2 0 4 0
.---.---.---.---.---.---.---.---.---. .---.
5 < id <= 0xff | 1 | 1 | 0 | t | t | t | t | t | i |...| i |
'---'---'---'---'---'---'---'---'---' '---'
4 0 7 0
.---.---.---.---.---.---.---.---.---. .---.---. .---.
0xff < id <= 0xffff | 1 | 1 | 1 | t | t | t | t | t | i |...| i | i |...| i |
'---'---'---'---'---'---'---'---'---' '---'---' '---'
4 0 7 0 15 8
.---.---.---.---.---.---.---.---.
value bool | | | | | | | | v |
'---'---'---'---'---'---'---'---'
0
.---.---.---.---.---.---.---.---.
int8, uint8 | v | v | v | v | v | v | v | v |
'---'---'---'---'---'---'---'---'
7 0
.---.---. .---.---.---. .---.
uint16, uint32, | 1 | v |...| v | 0 | v |...| v | [...]
uint64 '---'---' '---'---'---' '---'
6 0 13 7
variable encoding, high bit of every byte
indicates if there is another byte
int16, int32, zig zag encoded to unsigned integer:
int64
0 -> 0
-1 -> 1
1 -> 2
-2 -> 3
...
and then encoded as unsigned integer
float, double little endian
.-------.------------.
string, wstring | count | characters |
'-------'------------'
count variable encoded uint32 count of 1-byte (for
string) or 2-byte (for wstring) Unicode code
units
characters 1-byte UTF-8 code units (for string) or 2-byte
UTF-16LE code units (for wstring)
.-------.-------.-------.
blob, list, set, | type | count | items |
vector, nullable '-------'-------'-------'
.---.---.---.---.---.---.---.---.
type (v1) | | | | t | t | t | t | t |
'---'---'---'---'---'---'---'---'
4 0
.---.---.---.---.---.---.---.---.
type (v2) | c | c | c | t | t | t | t | t |
'---'---'---'---'---'---'---'---'
2 0 4 0
if count of items is < 7, 'c' are bit of (count + 1),
otherwise 'c' bits are 0.
count variable encoded uint32 count of items
omitted in v2 if 'c' bits within type byte are not 0
items each item encoded according to its type
.----------.------------.-------.-----.-------.
map | key type | value type | count | key | value |
'----------'------------'-------'-----'-------'
.---.---.---.---.---.---.---.---.
key type, | | | | t | t | t | t | t |
value type '---'---'---'---'---'---'---'---'
4 0
count variable encoded uint32 count of {key,mapped} pairs
key, mapped each item encoded according to its type
*/
#endregion
namespace Bond.Protocols
{
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using Bond.IO;
/// <summary>
/// Writer for the Compact Binary tagged protocol
/// </summary>
/// <typeparam name="O">Implementation of IOutputStream interface</typeparam>
[Reader(typeof(CompactBinaryReader<>))]
[FirstPassWriter(typeof(CompactBinaryCounter))]
public struct CompactBinaryWriter<O> : ITwoPassProtocolWriter
where O : IOutputStream
{
const ushort Magic = (ushort)ProtocolType.COMPACT_PROTOCOL;
readonly O output;
readonly ushort version;
readonly CompactBinaryCounter? firstPassWriter;
readonly LinkedList<uint> lengths;
Stack<long> lengthCheck;
/// <summary>
/// Create an instance of CompactBinaryWriter
/// </summary>
/// <param name="output">Serialized payload output</param>
/// <param name="version">Protocol version</param>
public CompactBinaryWriter(O output, ushort version = 1)
{
this.output = output;
this.version = version;
if (version == 2)
{
lengths = new LinkedList<uint>();
firstPassWriter = new CompactBinaryCounter(lengths);
}
else
{
lengths = null;
firstPassWriter = null;
}
lengthCheck = null;
InitLengthCheck();
}
public IProtocolWriter GetFirstPassWriter()
{
if (version == 2)
{
// Only return first pass if not in middle of second pass
if (lengths.Count == 0)
{
return firstPassWriter.Value;
}
}
return null;
}
/// <summary>
/// Write protocol magic number and version
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteVersion()
{
output.WriteUInt16(Magic);
output.WriteUInt16(version);
}
#region Complex types
/// <summary>
/// Start writing a struct
/// </summary>
/// <param name="metadata">Schema metadata</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteStructBegin(Metadata metadata)
{
if (version == 2)
{
uint length = lengths.First.Value;
lengths.RemoveFirst();
output.WriteVarUInt32(length);
PushLengthCheck(output.Position + length);
}
}
/// <summary>
/// Start writing a base struct
/// </summary>
/// <param name="metadata">Base schema metadata</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBaseBegin(Metadata metadata)
{}
/// <summary>
/// End writing a struct
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteStructEnd()
{
output.WriteUInt8((Byte)BondDataType.BT_STOP);
PopLengthCheck(output.Position);
}
/// <summary>
/// End writing a base struct
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBaseEnd()
{
output.WriteUInt8((Byte)BondDataType.BT_STOP_BASE);
}
/// <summary>
/// Start writing a field
/// </summary>
/// <param name="type">Type of the field</param>
/// <param name="id">Identifier of the field</param>
/// <param name="metadata">Metadata of the field</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFieldBegin(BondDataType type, ushort id, Metadata metadata)
{
var fieldType = (uint)type;
if (id <= 5)
{
output.WriteUInt8((byte)(fieldType | ((uint)id << 5)));
}
else if (id <= 0xFF)
{
output.WriteUInt16((ushort)(fieldType | (uint)id << 8 | (0x06 << 5)));
}
else
{
output.WriteUInt8((byte)(fieldType | (0x07 << 5)));
output.WriteUInt16(id);
}
}
/// <summary>
/// Indicate that field was omitted because it was set to its default value
/// </summary>
/// <param name="dataType">Type of the field</param>
/// <param name="id">Identifier of the field</param>
/// <param name="metadata">Metadata of the field</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFieldOmitted(BondDataType dataType, ushort id, Metadata metadata)
{}
/// <summary>
/// End writing a field
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFieldEnd()
{}
/// <summary>
/// Start writing a list or set container
/// </summary>
/// <param name="count">Number of elements in the container</param>
/// <param name="elementType">Type of the elements</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteContainerBegin(int count, BondDataType elementType)
{
if (2 == version && count < 7)
{
output.WriteUInt8((byte)((uint)elementType | (((uint)count + 1) << 5)));
}
else
{
output.WriteUInt8((byte)elementType);
output.WriteVarUInt32((uint)count);
}
}
/// <summary>
/// Start writing a map container
/// </summary>
/// <param name="count">Number of elements in the container</param>
/// <param name="keyType">Type of the keys</param>
/// /// <param name="valueType">Type of the values</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteContainerBegin(int count, BondDataType keyType, BondDataType valueType)
{
output.WriteUInt8((byte)keyType);
output.WriteUInt8((byte)valueType);
output.WriteVarUInt32((uint)count);
}
/// <summary>
/// End writing a container
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteContainerEnd()
{}
/// <summary>
/// Write array of bytes verbatim
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBytes(ArraySegment<byte> data)
{
output.WriteBytes(data);
}
#endregion
#region Primitive types
/// <summary>
/// Write an UInt8
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt8(Byte value)
{
output.WriteUInt8(value);
}
/// <summary>
/// Write an UInt16
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt16(UInt16 value)
{
output.WriteVarUInt16(value);
}
/// <summary>
/// Write an UInt16
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt32(UInt32 value)
{
output.WriteVarUInt32(value);
}
/// <summary>
/// Write an UInt64
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt64(UInt64 value)
{
output.WriteVarUInt64(value);
}
/// <summary>
/// Write an Int8
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt8(SByte value)
{
output.WriteUInt8((Byte)value);
}
/// <summary>
/// Write an Int16
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt16(Int16 value)
{
output.WriteVarUInt16(IntegerHelper.EncodeZigzag16(value));
}
/// <summary>
/// Write an Int32
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt32(Int32 value)
{
output.WriteVarUInt32(IntegerHelper.EncodeZigzag32(value));
}
/// <summary>
/// Write an Int64
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt64(Int64 value)
{
output.WriteVarUInt64(IntegerHelper.EncodeZigzag64(value));
}
/// <summary>
/// Write a float
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFloat(float value)
{
output.WriteFloat(value);
}
/// <summary>
/// Write a double
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteDouble(double value)
{
output.WriteDouble(value);
}
/// <summary>
/// Write a bool
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBool(bool value)
{
output.WriteUInt8((byte)(value ? 1 : 0));
}
/// <summary>
/// Write a UTF-8 string
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteString(string value)
{
if (value.Length == 0)
{
WriteUInt32(0);
}
else
{
var size = Encoding.UTF8.GetByteCount(value);
WriteUInt32((UInt32)size);
output.WriteString(Encoding.UTF8, value, size);
}
}
/// <summary>
/// Write a UTF-16 string
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteWString(string value)
{
if (value.Length == 0)
{
WriteUInt32(0);
}
else
{
WriteUInt32((UInt32)value.Length);
output.WriteString(Encoding.Unicode, value, value.Length << 1);
}
}
#endregion
#region Length check
[Conditional("DEBUG")]
private void InitLengthCheck()
{
if (version == 2)
{
lengthCheck = new Stack<long>();
}
}
[Conditional("DEBUG")]
private void PushLengthCheck(long position)
{
lengthCheck.Push(position);
}
[Conditional("DEBUG")]
private void PopLengthCheck(long position)
{
if (version == 2)
{
if (position != lengthCheck.Pop())
{
Throw.EndOfStreamException();
}
}
}
#endregion
}
/// <summary>
/// Reader for the Compact Binary tagged protocol
/// </summary>
/// <typeparam name="I">Implementation of IInputStream interface</typeparam>
public struct CompactBinaryReader<I> : IClonableTaggedProtocolReader, ICloneable<CompactBinaryReader<I>>
where I : IInputStream, ICloneable<I>
{
readonly I input;
readonly ushort version;
/// <summary>
/// Create an instance of CompactBinaryReader
/// </summary>
/// <param name="input">Input payload</param>
/// <param name="version">Protocol version</param>
public CompactBinaryReader(I input, ushort version = 1)
{
this.input = input;
this.version = version;
}
/// <summary>
/// Clone the reader
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
CompactBinaryReader<I> ICloneable<CompactBinaryReader<I>>.Clone()
{
return new CompactBinaryReader<I>(input.Clone(), version);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
IClonableTaggedProtocolReader ICloneable<IClonableTaggedProtocolReader>.Clone()
{
return (this as ICloneable<CompactBinaryReader<I>>).Clone();
}
#region Complex types
/// <summary>
/// Start reading a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadStructBegin()
{
if (2 == version)
{
input.ReadVarUInt32();
}
}
/// <summary>
/// Start reading a base of a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadBaseBegin()
{ }
/// <summary>
/// End reading a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadStructEnd()
{ }
/// <summary>
/// End reading a base of a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadBaseEnd()
{ }
/// <summary>
/// Start reading a field
/// </summary>
/// <param name="type">An out parameter set to the field type
/// or BT_STOP/BT_STOP_BASE if there is no more fields in current struct/base</param>
/// <param name="id">Out parameter set to the field identifier</param>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadFieldBegin(out BondDataType type, out ushort id)
{
uint raw = input.ReadUInt8();
type = (BondDataType)(raw & 0x1f);
raw >>= 5;
if (raw < 6)
{
id = (ushort)raw;
}
else if (raw == 6)
{
id = input.ReadUInt8();
}
else
{
id = input.ReadUInt16();
}
}
/// <summary>
/// End reading a field
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadFieldEnd()
{ }
/// <summary>
/// Start reading a list or set container
/// </summary>
/// <param name="count">An out parameter set to number of items in the container</param>
/// <param name="elementType">An out parameter set to type of container elements</param>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadContainerBegin(out int count, out BondDataType elementType)
{
var raw = input.ReadUInt8();
elementType = (BondDataType)(raw & 0x1f);
if (2 == version && (raw & (0x07 << 5)) != 0)
count = (raw >> 5) - 1;
else
count = (int)input.ReadVarUInt32();
}
/// <summary>
/// Start reading a map container
/// </summary>
/// <param name="count">An out parameter set to number of items in the container</param>
/// <param name="keyType">An out parameter set to the type of map keys</param>
/// <param name="valueType">An out parameter set to the type of map values</param>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadContainerBegin(out int count, out BondDataType keyType, out BondDataType valueType)
{
keyType = (BondDataType)input.ReadUInt8();
valueType = (BondDataType)input.ReadUInt8();
count = (int)input.ReadVarUInt32();
}
/// <summary>
/// End reading a container
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadContainerEnd()
{ }
#endregion
#region Primitive types
/// <summary>
/// Read an UInt8
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public byte ReadUInt8()
{
return input.ReadUInt8();
}
/// <summary>
/// Read an UInt16
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ushort ReadUInt16()
{
return input.ReadVarUInt16();
}
/// <summary>
/// Read an UInt32
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public uint ReadUInt32()
{
return input.ReadVarUInt32();
}
/// <summary>
/// Read an UInt64
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public UInt64 ReadUInt64()
{
return input.ReadVarUInt64();
}
/// <summary>
/// Read an Int8
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public sbyte ReadInt8()
{
return (sbyte)input.ReadUInt8();
}
/// <summary>
/// Read an Int16
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public short ReadInt16()
{
return IntegerHelper.DecodeZigzag16(input.ReadVarUInt16());
}
/// <summary>
/// Read an Int32
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ReadInt32()
{
return IntegerHelper.DecodeZigzag32(input.ReadVarUInt32());
}
/// <summary>
/// Read an Int64
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Int64 ReadInt64()
{
return IntegerHelper.DecodeZigzag64(input.ReadVarUInt64());
}
/// <summary>
/// Read a bool
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ReadBool()
{
return input.ReadUInt8() != 0;
}
/// <summary>
/// Read a float
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float ReadFloat()
{
return input.ReadFloat();
}
/// <summary>
/// Read a double
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public double ReadDouble()
{
return input.ReadDouble();
}
/// <summary>
/// Read a UTF-8 string
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public String ReadString()
{
var length = (int)input.ReadVarUInt32();
return length == 0 ? string.Empty : input.ReadString(Encoding.UTF8, length);
}
/// <summary>
/// Read a UTF-16 string
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string ReadWString()
{
var length = (int)input.ReadVarUInt32();
return length == 0 ? string.Empty : input.ReadString(Encoding.Unicode, length << 1);
}
/// <summary>
/// Read an array of bytes verbatim
/// </summary>
/// <param name="count">Number of bytes to read</param>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ArraySegment<byte> ReadBytes(int count)
{
return input.ReadBytes(count);
}
#endregion
#region Skip
/// <summary>
/// Skip a value of specified type
/// </summary>
/// <param name="type">Type of the value to skip</param>
/// <exception cref="EndOfStreamException"/>
public void Skip(BondDataType type)
{
switch (type)
{
case (BondDataType.BT_BOOL):
case (BondDataType.BT_UINT8):
case (BondDataType.BT_INT8):
input.SkipBytes(sizeof(byte));
break;
case (BondDataType.BT_UINT16):
case (BondDataType.BT_INT16):
input.ReadVarUInt16();
break;
case (BondDataType.BT_UINT32):
case (BondDataType.BT_INT32):
input.ReadVarUInt32();
break;
case (BondDataType.BT_FLOAT):
input.SkipBytes(sizeof(float));
break;
case (BondDataType.BT_DOUBLE):
input.SkipBytes(sizeof(double));
break;
case (BondDataType.BT_UINT64):
case (BondDataType.BT_INT64):
input.ReadVarUInt64();
break;
case (BondDataType.BT_STRING):
input.SkipBytes((int)input.ReadVarUInt32());
break;
case (BondDataType.BT_WSTRING):
input.SkipBytes((int)(input.ReadVarUInt32() << 1));
break;
case BondDataType.BT_LIST:
case BondDataType.BT_SET:
SkipContainer();
break;
case BondDataType.BT_MAP:
SkipMap();
break;
case BondDataType.BT_STRUCT:
SkipStruct();
break;
default:
Throw.InvalidBondDataType(type);
break;
}
}
void SkipContainer()
{
BondDataType elementType;
int count;
ReadContainerBegin(out count, out elementType);
if (elementType == BondDataType.BT_UINT8 || elementType == BondDataType.BT_INT8)
{
input.SkipBytes(count);
}
else if (elementType == BondDataType.BT_FLOAT)
{
input.SkipBytes(count * sizeof(float));
}
else if (elementType == BondDataType.BT_DOUBLE)
{
input.SkipBytes(count * sizeof(double));
}
else
{
while (0 <= --count)
{
Skip(elementType);
}
}
}
void SkipMap()
{
BondDataType keyType;
BondDataType valueType;
int count;
ReadContainerBegin(out count, out keyType, out valueType);
while (0 <= --count)
{
Skip(keyType);
Skip(valueType);
}
}
void SkipStruct()
{
if (2 == version)
{
input.SkipBytes((int)input.ReadVarUInt32());
}
else
{
while (true)
{
BondDataType type;
ushort id;
ReadFieldBegin(out type, out id);
if (type == BondDataType.BT_STOP_BASE) continue;
if (type == BondDataType.BT_STOP) break;
Skip(type);
}
}
}
#endregion
}
}
| |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Tracing;
using Microsoft.Azure.Mobile.Server;
using Microsoft.Azure.Mobile.Server.Config;
using Microsoft.Azure.Mobile.Server.Notifications;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ZumoE2EServerApp.Controllers
{
[MobileAppController]
public class PushApiController : ApiController
{
private ITraceWriter traceWriter;
private PushClient pushClient;
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
this.traceWriter = this.Configuration.Services.GetTraceWriter();
this.pushClient = new PushClient(this.Configuration);
}
[Route("api/push")]
public async Task<HttpResponseMessage> Post()
{
var data = await this.Request.Content.ReadAsAsync<JObject>();
var method = (string)data["method"];
if (method == null)
{
return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
if (method == "send")
{
var serialize = new JsonSerializer();
var token = (string)data["token"];
if (data["payload"] == null || token == null)
{
return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
// Payload could be a string or a dictionary
var payloadString = data["payload"].ToString();
var type = (string)data["type"];
var tag = (string)data["tag"];
if (type == "template")
{
TemplatePushMessage message = new TemplatePushMessage();
var payload = JObject.Parse(payloadString);
var keys = payload.Properties();
foreach (JProperty key in keys)
{
this.traceWriter.Info("Key: " + key.Name);
message.Add(key.Name, (string)key.Value);
}
var result = await this.pushClient.SendAsync(message);
}
else if (type == "gcm")
{
GooglePushMessage message = new GooglePushMessage();
message.JsonPayload = payloadString;
if (tag != null)
{
await this.pushClient.SendAsync(message, tag);
}
else
{
await this.pushClient.SendAsync(message);
}
}
else if (type == "apns")
{
ApplePushMessage message = new ApplePushMessage();
this.traceWriter.Info(payloadString.ToString());
message.JsonPayload = payloadString.ToString();
if (tag != null)
{
await this.pushClient.SendAsync(message, tag);
}
else
{
await this.pushClient.SendAsync(message);
}
}
else if (type == "wns")
{
var wnsType = (string)data["wnsType"];
WindowsPushMessage message = new WindowsPushMessage();
message.XmlPayload = payloadString;
message.Headers.Add("X-WNS-Type", type + '/' + wnsType);
if (tag != null)
{
await this.pushClient.SendAsync(message, tag);
}
else
{
await this.pushClient.SendAsync(message);
}
}
}
else
{
return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
[Route("api/verifyRegisterInstallationResult")]
public async Task<bool> GetVerifyRegisterInstallationResult(string channelUri, string templates = null, string secondaryTiles = null)
{
var nhClient = this.GetNhClient();
HttpResponseMessage msg = new HttpResponseMessage();
msg.StatusCode = HttpStatusCode.InternalServerError;
IEnumerable<string> installationIds;
if (this.Request.Headers.TryGetValues("X-ZUMO-INSTALLATION-ID", out installationIds))
{
return await Retry(async () =>
{
var installationId = installationIds.FirstOrDefault();
Installation nhInstallation = await nhClient.GetInstallationAsync(installationId);
string nhTemplates = null;
string nhSecondaryTiles = null;
if (nhInstallation.Templates != null)
{
nhTemplates = JsonConvert.SerializeObject(nhInstallation.Templates);
nhTemplates = Regex.Replace(nhTemplates, @"\s+", String.Empty);
templates = Regex.Replace(templates, @"\s+", String.Empty);
}
if (nhInstallation.SecondaryTiles != null)
{
nhSecondaryTiles = JsonConvert.SerializeObject(nhInstallation.SecondaryTiles);
nhSecondaryTiles = Regex.Replace(nhSecondaryTiles, @"\s+", String.Empty);
secondaryTiles = Regex.Replace(secondaryTiles, @"\s+", String.Empty);
}
if (nhInstallation.PushChannel.ToLower() != channelUri.ToLower())
{
msg.Content = new StringContent(string.Format("ChannelUri did not match. Expected {0} Found {1}", channelUri, nhInstallation.PushChannel));
throw new HttpResponseException(msg);
}
if (templates != nhTemplates)
{
msg.Content = new StringContent(string.Format("Templates did not match. Expected {0} Found {1}", templates, nhTemplates));
throw new HttpResponseException(msg);
}
if (secondaryTiles != nhSecondaryTiles)
{
msg.Content = new StringContent(string.Format("SecondaryTiles did not match. Expected {0} Found {1}", secondaryTiles, nhSecondaryTiles));
throw new HttpResponseException(msg);
}
bool tagsVerified = await VerifyTags(channelUri, installationId, nhClient);
if (!tagsVerified)
{
msg.Content = new StringContent("Did not find installationId tag");
throw new HttpResponseException(msg);
}
return true;
});
}
msg.Content = new StringContent("Did not find X-ZUMO-INSTALLATION-ID header in the incoming request");
throw new HttpResponseException(msg);
}
[Route("api/verifyUnregisterInstallationResult")]
public async Task<bool> GetVerifyUnregisterInstallationResult()
{
IEnumerable<string> installationIds;
string responseErrorMessage = null;
if (this.Request.Headers.TryGetValues("X-ZUMO-INSTALLATION-ID", out installationIds))
{
return await Retry(async () =>
{
var installationId = installationIds.FirstOrDefault();
try
{
Installation nhInstallation = await this.GetNhClient().GetInstallationAsync(installationId);
}
catch (Exception)
{
return true;
}
responseErrorMessage = string.Format("Found deleted Installation with id {0}", installationId);
return false;
});
}
HttpResponseMessage msg = new HttpResponseMessage()
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent(responseErrorMessage)
};
throw new HttpResponseException(msg);
}
[Route("api/deleteRegistrationsForChannel")]
public async Task DeleteRegistrationsForChannel(string channelUri)
{
await Retry(async () =>
{
await this.GetNhClient().DeleteRegistrationsByChannelAsync(channelUri);
return true;
});
}
[Route("api/register")]
public void Register(string data)
{
var installation = JsonConvert.DeserializeObject<Installation>(data);
new PushClient(this.Configuration).HubClient.CreateOrUpdateInstallation(installation);
}
private NotificationHubClient GetNhClient()
{
var settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
string notificationHubName = settings.NotificationHubName;
string notificationHubConnection = settings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
return NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
}
private async Task<bool> VerifyTags(string channelUri, string installationId, NotificationHubClient nhClient)
{
IPrincipal user = this.User;
int expectedTagsCount = 1;
if (user.Identity != null && user.Identity.IsAuthenticated)
{
expectedTagsCount = 2;
}
string continuationToken = null;
do
{
CollectionQueryResult<RegistrationDescription> regsForChannel = await nhClient.GetRegistrationsByChannelAsync(channelUri, continuationToken, 100);
continuationToken = regsForChannel.ContinuationToken;
foreach (RegistrationDescription reg in regsForChannel)
{
RegistrationDescription registration = await nhClient.GetRegistrationAsync<RegistrationDescription>(reg.RegistrationId);
if (registration.Tags == null || registration.Tags.Count() != expectedTagsCount)
{
return false;
}
if (!registration.Tags.Contains("$InstallationId:{" + installationId + "}"))
{
return false;
}
ClaimsIdentity identity = user.Identity as ClaimsIdentity;
Claim userIdClaim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
string userId = (userIdClaim != null) ? userIdClaim.Value : string.Empty;
if (expectedTagsCount > 1 && !registration.Tags.Contains("_UserId:" + userId))
{
return false;
}
}
} while (continuationToken != null);
return true;
}
private async Task<bool> Retry(Func<Task<bool>> target)
{
var sleepTimes = new int[3] { 1000, 3000, 5000 };
for (var i = 0; i < sleepTimes.Length; i++)
{
System.Threading.Thread.Sleep(sleepTimes[i]);
try
{
// if the call succeeds, return the result
return await target();
}
catch (Exception)
{
// if an exception was thrown and we've already retried three times, rethrow
if (i == 2)
throw;
}
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 ShiftLeftLogical128BitLaneInt321()
{
var test = new ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt321();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt321
{
private struct TestStruct
{
public Vector256<Int32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt321 testClass)
{
var result = Avx2.ShiftLeftLogical128BitLane(_fld, 1);
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<Vector256<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector256<Int32> _clsVar;
private Vector256<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt321()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt321()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftLeftLogical128BitLane(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftLeftLogical128BitLane(
Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftLeftLogical128BitLane(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftLeftLogical128BitLane(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt321();
var result = Avx2.ShiftLeftLogical128BitLane(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftLeftLogical128BitLane(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftLeftLogical128BitLane(test._fld, 1);
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));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != 2048)
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 2048)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical128BitLane)}<Int32>(Vector256<Int32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
namespace System.Xml
{
// Represents an element.
public class XmlElement : XmlLinkedNode
{
XmlName name;
XmlAttributeCollection attributes;
XmlLinkedNode lastChild; // == this for empty elements otherwise it is the last child
internal XmlElement(XmlName name, bool empty, XmlDocument doc) : base(doc)
{
Debug.Assert(name != null);
this.parentNode = null;
if (!doc.IsLoading)
{
XmlDocument.CheckName(name.Prefix);
XmlDocument.CheckName(name.LocalName);
}
if (name.LocalName.Length == 0)
throw new ArgumentException(SR.Xdom_Empty_LocalName);
this.name = name;
if (empty)
{
this.lastChild = this;
}
}
protected internal XmlElement(string prefix, string localName, string namespaceURI, XmlDocument doc)
: this(doc.AddXmlName(prefix, localName, namespaceURI), true, doc)
{
}
internal XmlName XmlName
{
get { return name; }
set { name = value; }
}
// Creates a duplicate of this node.
public override XmlNode CloneNode(bool deep)
{
Debug.Assert(OwnerDocument != null);
XmlDocument doc = OwnerDocument;
bool OrigLoadingStatus = doc.IsLoading;
doc.IsLoading = true;
XmlElement element = doc.CreateElement(Prefix, LocalName, NamespaceURI);
doc.IsLoading = OrigLoadingStatus;
if (element.IsEmpty != this.IsEmpty)
element.IsEmpty = this.IsEmpty;
if (HasAttributes)
{
foreach (XmlAttribute attr in Attributes)
{
XmlAttribute newAttr = (XmlAttribute)(attr.CloneNode(true));
if (attr is XmlUnspecifiedAttribute && attr.Specified == false)
((XmlUnspecifiedAttribute)newAttr).SetSpecified(false);
element.Attributes.InternalAppendAttribute(newAttr);
}
}
if (deep)
element.CopyChildren(doc, this, deep);
return element;
}
// Gets the name of the node.
public override string Name
{
get { return name.Name; }
}
// Gets the name of the current node without the namespace prefix.
public override string LocalName
{
get { return name.LocalName; }
}
// Gets the namespace URI of this node.
public override string NamespaceURI
{
get { return name.NamespaceURI; }
}
// Gets or sets the namespace prefix of this node.
public override string Prefix
{
get { return name.Prefix; }
set { name = name.OwnerDocument.AddXmlName(value, LocalName, NamespaceURI); }
}
// Gets the type of the current node.
public override XmlNodeType NodeType
{
get { return XmlNodeType.Element; }
}
public override XmlNode ParentNode
{
get
{
return this.parentNode;
}
}
// Gets the XmlDocument that contains this node.
public override XmlDocument OwnerDocument
{
get
{
return name.OwnerDocument;
}
}
internal override bool IsContainer
{
get { return true; }
}
//the function is provided only at Load time to speed up Load process
internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc)
{
XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this);
if (args != null)
doc.BeforeEvent(args);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (lastChild == null
|| lastChild == this)
{ // if LastNode == null
newNode.next = newNode;
lastChild = newNode; // LastNode = newNode;
newNode.SetParentForLoad(this);
}
else
{
XmlLinkedNode refNode = lastChild; // refNode = LastNode;
newNode.next = refNode.next;
refNode.next = newNode;
lastChild = newNode; // LastNode = newNode;
if (refNode.IsText
&& newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
else
{
newNode.SetParentForLoad(this);
}
}
if (args != null)
doc.AfterEvent(args);
return newNode;
}
// Gets or sets whether the element does not have any children.
public bool IsEmpty
{
get
{
return lastChild == this;
}
set
{
if (value)
{
if (lastChild != this)
{
RemoveAllChildren();
lastChild = this;
}
}
else
{
if (lastChild == this)
{
lastChild = null;
}
}
}
}
internal override XmlLinkedNode LastNode
{
get
{
return lastChild == this ? null : lastChild;
}
set
{
lastChild = value;
}
}
internal override bool IsValidChildType(XmlNodeType type)
{
switch (type)
{
case XmlNodeType.Element:
case XmlNodeType.Text:
case XmlNodeType.EntityReference:
case XmlNodeType.Comment:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.CDATA:
return true;
default:
return false;
}
}
// Gets a XmlAttributeCollection containing the list of attributes for this node.
public override XmlAttributeCollection Attributes
{
get
{
if (attributes == null)
{
lock (OwnerDocument.objLock)
{
if (attributes == null)
{
attributes = new XmlAttributeCollection(this);
}
}
}
return attributes;
}
}
// Gets a value indicating whether the current node
// has any attributes.
public virtual bool HasAttributes
{
get
{
if (this.attributes == null)
return false;
else
return this.attributes.Count > 0;
}
}
// Returns the value for the attribute with the specified name.
public virtual string GetAttribute(string name)
{
XmlAttribute attr = GetAttributeNode(name);
if (attr != null)
return attr.Value;
return String.Empty;
}
// Sets the value of the attribute
// with the specified name.
public virtual void SetAttribute(string name, string value)
{
XmlAttribute attr = GetAttributeNode(name);
if (attr == null)
{
attr = OwnerDocument.CreateAttribute(name);
attr.Value = value;
Attributes.InternalAppendAttribute(attr);
}
else
{
attr.Value = value;
}
}
// Removes an attribute by name.
public virtual void RemoveAttribute(string name)
{
if (HasAttributes)
Attributes.RemoveNamedItem(name);
}
// Returns the XmlAttribute with the specified name.
public virtual XmlAttribute GetAttributeNode(string name)
{
if (HasAttributes)
return Attributes[name];
return null;
}
// Adds the specified XmlAttribute.
public virtual XmlAttribute SetAttributeNode(XmlAttribute newAttr)
{
if (newAttr.OwnerElement != null)
throw new InvalidOperationException(SR.Xdom_Attr_InUse);
return (XmlAttribute)Attributes.SetNamedItem(newAttr);
}
// Removes the specified XmlAttribute.
public virtual XmlAttribute RemoveAttributeNode(XmlAttribute oldAttr)
{
if (HasAttributes)
return (XmlAttribute)Attributes.Remove(oldAttr);
return null;
}
// Returns a XmlNodeList containing
// a list of all descendant elements that match the specified name.
public virtual XmlNodeList GetElementsByTagName(string name)
{
return new XmlElementList(this, name);
}
//
// DOM Level 2
//
// Returns the value for the attribute with the specified LocalName and NamespaceURI.
public virtual string GetAttribute(string localName, string namespaceURI)
{
XmlAttribute attr = GetAttributeNode(localName, namespaceURI);
if (attr != null)
return attr.Value;
return String.Empty;
}
// Sets the value of the attribute with the specified name
// and namespace.
public virtual string SetAttribute(string localName, string namespaceURI, string value)
{
XmlAttribute attr = GetAttributeNode(localName, namespaceURI);
if (attr == null)
{
attr = OwnerDocument.CreateAttribute(string.Empty, localName, namespaceURI);
attr.Value = value;
Attributes.InternalAppendAttribute(attr);
}
else
{
attr.Value = value;
}
return value;
}
// Removes an attribute specified by LocalName and NamespaceURI.
public virtual void RemoveAttribute(string localName, string namespaceURI)
{
RemoveAttributeNode(localName, namespaceURI);
}
// Returns the XmlAttribute with the specified LocalName and NamespaceURI.
public virtual XmlAttribute GetAttributeNode(string localName, string namespaceURI)
{
if (HasAttributes)
return Attributes[localName, namespaceURI];
return null;
}
// Adds the specified XmlAttribute.
public virtual XmlAttribute SetAttributeNode(string localName, string namespaceURI)
{
XmlAttribute attr = GetAttributeNode(localName, namespaceURI);
if (attr == null)
{
attr = OwnerDocument.CreateAttribute(string.Empty, localName, namespaceURI);
Attributes.InternalAppendAttribute(attr);
}
return attr;
}
// Removes the XmlAttribute specified by LocalName and NamespaceURI.
public virtual XmlAttribute RemoveAttributeNode(string localName, string namespaceURI)
{
if (HasAttributes)
{
XmlAttribute attr = GetAttributeNode(localName, namespaceURI);
Attributes.Remove(attr);
return attr;
}
return null;
}
// Returns a XmlNodeList containing
// a list of all descendant elements that match the specified name.
public virtual XmlNodeList GetElementsByTagName(string localName, string namespaceURI)
{
return new XmlElementList(this, localName, namespaceURI);
}
// Determines whether the current node has the specified attribute.
public virtual bool HasAttribute(string name)
{
return GetAttributeNode(name) != null;
}
// Determines whether the current node has the specified
// attribute from the specified namespace.
public virtual bool HasAttribute(string localName, string namespaceURI)
{
return GetAttributeNode(localName, namespaceURI) != null;
}
// Saves the current node to the specified XmlWriter.
public override void WriteTo(XmlWriter w)
{
if (GetType() == typeof(XmlElement))
{
// Use the non-recursive version (for XmlElement only)
WriteElementTo(w, this);
}
else
{
// Use the (potentially) recursive version
WriteStartElement(w);
if (IsEmpty)
{
w.WriteEndElement();
}
else
{
WriteContentTo(w);
w.WriteFullEndElement();
}
}
}
// This method is copied from System.Xml.Linq.ElementWriter.WriteElement but adapted to DOM
private static void WriteElementTo(XmlWriter writer, XmlElement e)
{
XmlNode root = e;
XmlNode n = e;
while (true)
{
e = n as XmlElement;
// Only use the inlined write logic for XmlElement, not for derived classes
if (e != null && e.GetType() == typeof(XmlElement))
{
// Write the element
e.WriteStartElement(writer);
// Write the element's content
if (e.IsEmpty)
{
// No content; use a short end element <a />
writer.WriteEndElement();
}
else if (e.lastChild == null)
{
// No actual content; use a full end element <a></a>
writer.WriteFullEndElement();
}
else
{
// There are child node(s); move to first child
n = e.FirstChild;
Debug.Assert(n != null);
continue;
}
}
else
{
// Use virtual dispatch (might recurse)
n.WriteTo(writer);
}
// Go back to the parent after writing the last child
while (n != root && n == n.ParentNode.LastChild)
{
n = n.ParentNode;
Debug.Assert(n != null);
writer.WriteFullEndElement();
}
if (n == root)
break;
n = n.NextSibling;
Debug.Assert(n != null);
}
}
// Writes the start of the element (and its attributes) to the specified writer
private void WriteStartElement(XmlWriter w)
{
w.WriteStartElement(Prefix, LocalName, NamespaceURI);
if (HasAttributes)
{
XmlAttributeCollection attrs = Attributes;
for (int i = 0; i < attrs.Count; i += 1)
{
XmlAttribute attr = attrs[i];
attr.WriteTo(w);
}
}
}
// Saves all the children of the node to the specified XmlWriter.
public override void WriteContentTo(XmlWriter w)
{
for (XmlNode node = FirstChild; node != null; node = node.NextSibling)
{
node.WriteTo(w);
}
}
// Removes the attribute node with the specified index from the attribute collection.
public virtual XmlNode RemoveAttributeAt(int i)
{
if (HasAttributes)
return attributes.RemoveAt(i);
return null;
}
// Removes all attributes from the element.
public virtual void RemoveAllAttributes()
{
if (HasAttributes)
{
attributes.RemoveAll();
}
}
// Removes all the children and/or attributes
// of the current node.
public override void RemoveAll()
{
//remove all the children
base.RemoveAll();
//remove all the attributes
RemoveAllAttributes();
}
internal void RemoveAllChildren()
{
base.RemoveAll();
}
// Gets or sets the markup representing just
// the children of this node.
public override string InnerXml
{
get
{
return base.InnerXml;
}
set
{
RemoveAllChildren();
XmlLoader loader = new XmlLoader();
loader.LoadInnerXmlElement(this, value);
}
}
// Gets or sets the concatenated values of the
// node and all its children.
public override string InnerText
{
get
{
return base.InnerText;
}
set
{
XmlLinkedNode linkedNode = LastNode;
if (linkedNode != null && //there is one child
linkedNode.NodeType == XmlNodeType.Text && //which is text node
linkedNode.next == linkedNode) // and it is the only child
{
//this branch is for perf reason, event fired when TextNode.Value is changed.
linkedNode.Value = value;
}
else
{
RemoveAllChildren();
AppendChild(OwnerDocument.CreateTextNode(value));
}
}
}
public override XmlNode NextSibling
{
get
{
if (this.parentNode != null
&& this.parentNode.LastNode != this)
return next;
return null;
}
}
internal override void SetParent(XmlNode node)
{
this.parentNode = node;
}
internal override string GetXPAttribute(string localName, string ns)
{
if (ns == OwnerDocument.strReservedXmlns)
return null;
XmlAttribute attr = GetAttributeNode(localName, ns);
if (attr != null)
return attr.Value;
return string.Empty;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
public static partial class Console
{
public static System.ConsoleColor BackgroundColor { get { return default(System.ConsoleColor); } set { } }
public static void Beep() { }
public static void Clear() { }
public static bool CursorVisible { get { return default(bool); } set { } }
public static int CursorTop { get { return default(int); } set { } }
public static int CursorLeft { get { return default(int); } set { } }
public static System.IO.TextWriter Error { get { return default(System.IO.TextWriter); } }
public static System.ConsoleColor ForegroundColor { get { return default(System.ConsoleColor); } set { } }
public static bool IsInputRedirected { get { return false; } }
public static bool IsOutputRedirected { get { return false; } }
public static bool IsErrorRedirected { get { return false; } }
public static System.IO.TextReader In { get { return default(System.IO.TextReader); } }
public static bool KeyAvailable { get { return default(bool); } }
public static System.IO.TextWriter Out { get { return default(System.IO.TextWriter); } }
public static event System.ConsoleCancelEventHandler CancelKeyPress { add { } remove { } }
public static System.IO.Stream OpenStandardError() { return default(System.IO.Stream); }
public static System.IO.Stream OpenStandardInput() { return default(System.IO.Stream); }
public static System.IO.Stream OpenStandardOutput() { return default(System.IO.Stream); }
public static int Read() { return default(int); }
public static ConsoleKeyInfo ReadKey() { return default(ConsoleKeyInfo); }
public static ConsoleKeyInfo ReadKey(bool intercept) { return default(ConsoleKeyInfo); }
public static string ReadLine() { return default(string); }
public static void ResetColor() { }
public static void SetCursorPosition(int left, int top) { }
public static void SetError(System.IO.TextWriter newError) { }
public static void SetIn(System.IO.TextReader newIn) { }
public static void SetOut(System.IO.TextWriter newOut) { }
public static string Title { get { return default(string); } set { } }
public static int WindowWidth { get { return default(int); } set { } }
public static int WindowHeight { get { return default(int); } set { } }
public static int WindowLeft { get { return default(int); } set { } }
public static int WindowTop { get { return default(int); } set { } }
public static void Write(bool value) { }
public static void Write(char value) { }
public static void Write(char[] buffer) { }
public static void Write(char[] buffer, int index, int count) { }
public static void Write(decimal value) { }
public static void Write(double value) { }
public static void Write(int value) { }
public static void Write(long value) { }
public static void Write(object value) { }
public static void Write(float value) { }
public static void Write(string value) { }
public static void Write(string format, object arg0) { }
public static void Write(string format, object arg0, object arg1) { }
public static void Write(string format, object arg0, object arg1, object arg2) { }
public static void Write(string format, params object[] arg) { }
[System.CLSCompliantAttribute(false)]
public static void Write(uint value) { }
[System.CLSCompliantAttribute(false)]
public static void Write(ulong value) { }
public static void WriteLine() { }
public static void WriteLine(bool value) { }
public static void WriteLine(char value) { }
public static void WriteLine(char[] buffer) { }
public static void WriteLine(char[] buffer, int index, int count) { }
public static void WriteLine(decimal value) { }
public static void WriteLine(double value) { }
public static void WriteLine(int value) { }
public static void WriteLine(long value) { }
public static void WriteLine(object value) { }
public static void WriteLine(float value) { }
public static void WriteLine(string value) { }
public static void WriteLine(string format, object arg0) { }
public static void WriteLine(string format, object arg0, object arg1) { }
public static void WriteLine(string format, object arg0, object arg1, object arg2) { }
public static void WriteLine(string format, params object[] arg) { }
[System.CLSCompliantAttribute(false)]
public static void WriteLine(uint value) { }
[System.CLSCompliantAttribute(false)]
public static void WriteLine(ulong value) { }
}
public sealed partial class ConsoleCancelEventArgs : System.EventArgs
{
internal ConsoleCancelEventArgs() { }
public bool Cancel { get { return default(bool); } set { } }
public System.ConsoleSpecialKey SpecialKey { get { return default(System.ConsoleSpecialKey); } }
}
public delegate void ConsoleCancelEventHandler(object sender, System.ConsoleCancelEventArgs e);
public enum ConsoleColor
{
Black = 0,
Blue = 9,
Cyan = 11,
DarkBlue = 1,
DarkCyan = 3,
DarkGray = 8,
DarkGreen = 2,
DarkMagenta = 5,
DarkRed = 4,
DarkYellow = 6,
Gray = 7,
Green = 10,
Magenta = 13,
Red = 12,
White = 15,
Yellow = 14,
}
public partial struct ConsoleKeyInfo
{
public ConsoleKeyInfo(char keyChar, ConsoleKey key, bool shift, bool alt, bool control) { }
public char KeyChar { get { return default(char); } }
public ConsoleKey Key { get { return default(ConsoleKey); } }
public ConsoleModifiers Modifiers { get { return default(ConsoleModifiers); ; } }
}
public enum ConsoleKey
{
Backspace = 0x8,
Tab = 0x9,
Clear = 0xC,
Enter = 0xD,
Pause = 0x13,
Escape = 0x1B,
Spacebar = 0x20,
PageUp = 0x21,
PageDown = 0x22,
End = 0x23,
Home = 0x24,
LeftArrow = 0x25,
UpArrow = 0x26,
RightArrow = 0x27,
DownArrow = 0x28,
Select = 0x29,
Print = 0x2A,
Execute = 0x2B,
PrintScreen = 0x2C,
Insert = 0x2D,
Delete = 0x2E,
Help = 0x2F,
D0 = 0x30, // 0 through 9
D1 = 0x31,
D2 = 0x32,
D3 = 0x33,
D4 = 0x34,
D5 = 0x35,
D6 = 0x36,
D7 = 0x37,
D8 = 0x38,
D9 = 0x39,
A = 0x41,
B = 0x42,
C = 0x43,
D = 0x44,
E = 0x45,
F = 0x46,
G = 0x47,
H = 0x48,
I = 0x49,
J = 0x4A,
K = 0x4B,
L = 0x4C,
M = 0x4D,
N = 0x4E,
O = 0x4F,
P = 0x50,
Q = 0x51,
R = 0x52,
S = 0x53,
T = 0x54,
U = 0x55,
V = 0x56,
W = 0x57,
X = 0x58,
Y = 0x59,
Z = 0x5A,
Sleep = 0x5F,
NumPad0 = 0x60,
NumPad1 = 0x61,
NumPad2 = 0x62,
NumPad3 = 0x63,
NumPad4 = 0x64,
NumPad5 = 0x65,
NumPad6 = 0x66,
NumPad7 = 0x67,
NumPad8 = 0x68,
NumPad9 = 0x69,
Multiply = 0x6A,
Add = 0x6B,
Separator = 0x6C,
Subtract = 0x6D,
Decimal = 0x6E,
Divide = 0x6F,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7A,
F12 = 0x7B,
F13 = 0x7C,
F14 = 0x7D,
F15 = 0x7E,
F16 = 0x7F,
F17 = 0x80,
F18 = 0x81,
F19 = 0x82,
F20 = 0x83,
F21 = 0x84,
F22 = 0x85,
F23 = 0x86,
F24 = 0x87,
Oem1 = 0xBA,
OemPlus = 0xBB,
OemComma = 0xBC,
OemMinus = 0xBD,
OemPeriod = 0xBE,
Oem2 = 0xBF,
Oem3 = 0xC0,
Oem4 = 0xDB,
Oem5 = 0xDC,
Oem6 = 0xDD,
Oem7 = 0xDE,
Oem8 = 0xDF,
OemClear = 0xFE,
}
[Flags]
public enum ConsoleModifiers
{
Alt = 1,
Shift = 2,
Control = 4
}
public enum ConsoleSpecialKey
{
ControlBreak = 1,
ControlC = 0,
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Management.Automation;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Response object for html content without DOM parsing
/// </summary>
public partial class BasicHtmlWebResponseObject : WebResponseObject
{
#region Properties
/// <summary>
/// gets or protected sets the Content property
/// </summary>
public new string Content { get; private set; }
private WebCmdletElementCollection _inputFields;
/// <summary>
/// gets the Fields property
/// </summary>
public WebCmdletElementCollection InputFields
{
get
{
if (_inputFields == null)
{
EnsureHtmlParser();
List<PSObject> parsedFields = new List<PSObject>();
MatchCollection fieldMatch = s_inputFieldRegex.Matches(Content);
foreach (Match field in fieldMatch)
{
parsedFields.Add(CreateHtmlObject(field.Value, "INPUT"));
}
_inputFields = new WebCmdletElementCollection(parsedFields);
}
return _inputFields;
}
}
private WebCmdletElementCollection _links;
/// <summary>
/// gets the Links property
/// </summary>
public WebCmdletElementCollection Links
{
get
{
if (_links == null)
{
EnsureHtmlParser();
List<PSObject> parsedLinks = new List<PSObject>();
MatchCollection linkMatch = s_linkRegex.Matches(Content);
foreach (Match link in linkMatch)
{
parsedLinks.Add(CreateHtmlObject(link.Value, "A"));
}
_links = new WebCmdletElementCollection(parsedLinks);
}
return _links;
}
}
private WebCmdletElementCollection _images;
/// <summary>
/// gets the Images property
/// </summary>
public WebCmdletElementCollection Images
{
get
{
if (_images == null)
{
EnsureHtmlParser();
List<PSObject> parsedImages = new List<PSObject>();
MatchCollection imageMatch = s_imageRegex.Matches(Content);
foreach (Match image in imageMatch)
{
parsedImages.Add(CreateHtmlObject(image.Value, "IMG"));
}
_images = new WebCmdletElementCollection(parsedImages);
}
return _images;
}
}
#endregion Properties
#region Private Fields
private static Regex s_tagRegex;
private static Regex s_attribsRegex;
private static Regex s_attribNameValueRegex;
private static Regex s_inputFieldRegex;
private static Regex s_linkRegex;
private static Regex s_imageRegex;
#endregion Private Fields
#region Methods
private void EnsureHtmlParser()
{
if (s_tagRegex == null)
{
s_tagRegex = new Regex(@"<\w+((\s+[^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>",
RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
if (s_attribsRegex == null)
{
s_attribsRegex = new Regex(@"(?<=\s+)([^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)",
RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
if (s_attribNameValueRegex == null)
{
s_attribNameValueRegex = new Regex(@"([^""'>/=\s\p{Cc}]+)(?:\s*=\s*(?:""(.*?)""|'(.*?)'|([^'"">\s]+)))?",
RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
if (s_inputFieldRegex == null)
{
s_inputFieldRegex = new Regex(@"<input\s+[^>]*(/>|>.*?</input>)",
RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
if (s_linkRegex == null)
{
s_linkRegex = new Regex(@"<a\s+[^>]*(/>|>.*?</a>)",
RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
if (s_imageRegex == null)
{
s_imageRegex = new Regex(@"<img\s+[^>]*>",
RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
}
private PSObject CreateHtmlObject(string html, string tagName)
{
PSObject elementObject = new PSObject();
elementObject.Properties.Add(new PSNoteProperty("outerHTML", html));
elementObject.Properties.Add(new PSNoteProperty("tagName", tagName));
ParseAttributes(html, elementObject);
return elementObject;
}
private void ParseAttributes(string outerHtml, PSObject elementObject)
{
// We might get an empty input for a directive from the HTML file
if (!string.IsNullOrEmpty(outerHtml))
{
// Extract just the opening tag of the HTML element (omitting the closing tag and any contents,
// including contained HTML elements)
var match = s_tagRegex.Match(outerHtml);
// Extract all the attribute specifications within the HTML element opening tag
var attribMatches = s_attribsRegex.Matches(match.Value);
foreach (Match attribMatch in attribMatches)
{
// Extract the name and value for this attribute (allowing for variations like single/double/no
// quotes, and no value at all)
var nvMatches = s_attribNameValueRegex.Match(attribMatch.Value);
Debug.Assert(nvMatches.Groups.Count == 5);
// Name is always captured by group #1
string name = nvMatches.Groups[1].Value;
// The value (if any) is captured by group #2, #3, or #4, depending on quoting or lack thereof
string value = null;
if (nvMatches.Groups[2].Success)
{
value = nvMatches.Groups[2].Value;
}
else if (nvMatches.Groups[3].Success)
{
value = nvMatches.Groups[3].Value;
}
else if (nvMatches.Groups[4].Success)
{
value = nvMatches.Groups[4].Value;
}
elementObject.Properties.Add(new PSNoteProperty(name, value));
}
}
}
/// <summary>
/// Reads the response content from the web response.
/// </summary>
private void InitializeContent()
{
string contentType = ContentHelper.GetContentType(BaseResponse);
if (ContentHelper.IsText(contentType))
{
// fill the Content buffer
string characterSet = WebResponseHelper.GetCharacterSet(BaseResponse);
this.Content = StreamHelper.DecodeStream(RawContentStream, characterSet);
}
else
{
this.Content = string.Empty;
}
}
#endregion Methods
}
}
| |
namespace Ocelot.AcceptanceTests
{
using Microsoft.AspNetCore.Http;
using Ocelot.Configuration.File;
using System;
using System.Collections.Generic;
using System.Net;
using TestStack.BDDfy;
using Xunit;
public class RoutingWithQueryStringTests : IDisposable
{
private readonly Steps _steps;
private readonly ServiceHandler _serviceHandler;
public RoutingWithQueryStringTests()
{
_serviceHandler = new ServiceHandler();
_steps = new Steps();
}
[Fact]
public void should_return_response_200_with_query_string_template()
{
var subscriptionId = Guid.NewGuid().ToString();
var unitId = Guid.NewGuid().ToString();
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 61879,
}
},
UpstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:61879", $"/api/subscriptions/{subscriptionId}/updates", $"?unitId={unitId}", 200, "Hello from Laura"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/units/{subscriptionId}/{unitId}/updates"))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura"))
.BDDfy();
}
[Fact]
public void should_return_response_200_with_odata_query_string()
{
var subscriptionId = Guid.NewGuid().ToString();
var unitId = Guid.NewGuid().ToString();
var port = 57359;
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/{everything}",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = port,
}
},
UpstreamPathTemplate = "/{everything}",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/odata/customers", "?$filter=Name%20eq%20'Sam'", 200, "Hello from Laura"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway($"/odata/customers?$filter=Name eq 'Sam' "))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura"))
.BDDfy();
}
[Fact]
public void should_return_response_200_with_query_string_upstream_template()
{
var subscriptionId = Guid.NewGuid().ToString();
var unitId = Guid.NewGuid().ToString();
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 64879,
}
},
UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:64879", $"/api/units/{subscriptionId}/{unitId}/updates", "", 200, "Hello from Laura"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/subscriptions/{subscriptionId}/updates?unitId={unitId}"))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura"))
.BDDfy();
}
[Fact]
public void should_return_response_404_with_query_string_upstream_template_no_query_string()
{
var subscriptionId = Guid.NewGuid().ToString();
var unitId = Guid.NewGuid().ToString();
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 64879,
}
},
UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:64879", $"/api/units/{subscriptionId}/{unitId}/updates", "", 200, "Hello from Laura"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/subscriptions/{subscriptionId}/updates"))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.NotFound))
.BDDfy();
}
[Fact]
public void should_return_response_404_with_query_string_upstream_template_different_query_string()
{
var subscriptionId = Guid.NewGuid().ToString();
var unitId = Guid.NewGuid().ToString();
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 64879,
}
},
UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:64879", $"/api/units/{subscriptionId}/{unitId}/updates", "", 200, "Hello from Laura"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/subscriptions/{subscriptionId}/updates?test=1"))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.NotFound))
.BDDfy();
}
[Fact]
public void should_return_response_200_with_query_string_upstream_template_multiple_params()
{
var subscriptionId = Guid.NewGuid().ToString();
var unitId = Guid.NewGuid().ToString();
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 64879,
}
},
UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
};
this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:64879", $"/api/units/{subscriptionId}/{unitId}/updates", "?productId=1", 200, "Hello from Laura"))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning())
.When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/subscriptions/{subscriptionId}/updates?unitId={unitId}&productId=1"))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura"))
.BDDfy();
}
private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, string queryString, int statusCode, string responseBody)
{
_serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, async context =>
{
if ((context.Request.PathBase.Value != basePath) || context.Request.QueryString.Value != queryString)
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync("downstream path didnt match base path");
}
else
{
context.Response.StatusCode = statusCode;
await context.Response.WriteAsync(responseBody);
}
});
}
public void Dispose()
{
_serviceHandler?.Dispose();
_steps.Dispose();
}
}
}
| |
/* Copyright (c) 2006 Google 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.
*/
#define USE_TRACING
using System;
using System.Xml;
using System.IO;
using System.Collections;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Extensions.Exif;
using Google.GData.Extensions.Location;
using Google.GData.Extensions.AppControl;
using System.Globalization;
namespace Google.GData.YouTube {
/// <summary>
/// this is a helper class just for parsing the category document
/// </summary>
internal class YouTubeCategoryCollection : AtomBase
{
public YouTubeCategoryCollection()
{
this.ProtocolMajor = VersionDefaults.VersionTwo;
}
/// <summary>
/// this is the subclassing method for AtomBase derived
/// classes to overload what childelements should be created
/// needed to create CustomLink type objects, like WebContentLink etc
/// </summary>
/// <param name="reader">The XmlReader that tells us what we are working with</param>
/// <param name="parser">the parser is primarily used for nametable comparisons</param>
/// <returns>AtomBase</returns>
public override AtomBase CreateAtomSubElement(XmlReader reader, AtomFeedParser parser)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (parser == null)
{
throw new ArgumentNullException("parser");
}
Object localname = reader.LocalName;
if (localname.Equals(parser.Nametable.Category))
{
return new YouTubeCategory();
}
return base.CreateAtomSubElement(reader, parser);
}
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public override string XmlName
{
get { return null; }
}
/////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////
/// <summary>
/// Entry API customization class for defining entries in a YouTubeFeed feed.
/// </summary>
//////////////////////////////////////////////////////////////////////
public class YouTubeEntry : YouTubeBaseEntry
{
/// <summary>
/// Constructs a new YouTubeEntry instance
/// </summary>
public YouTubeEntry()
: base()
{
this.ProtocolMajor = VersionDefaults.VersionTwo;
Tracing.TraceMsg("Created YouTubeEntry");
addYouTubeEntryExtensions();
}
/// <summary>
/// helper method to add extensions to the evententry
/// </summary>
private void addYouTubeEntryExtensions()
{
MediaGroup mg = new MediaGroup();
this.AddExtension(mg);
GeoRssExtensions.AddExtension(this);
AppControl app = new AppControl();
app.ProtocolMajor = this.ProtocolMajor;
app.ProtocolMinor = this.ProtocolMinor;
AppControl acf = FindExtensionFactory(app.XmlName, app.XmlNameSpace) as AppControl;
if (acf == null)
{
// create a default appControl element
acf = new AppControl();
this.AddExtension(acf);
}
// add the youtube state element
acf.ExtensionFactories.Add(new State());
// things from the gd namespce
this.AddExtension(new Comments());
this.AddExtension(new Rating());
// add youtube namespace elements
this.AddExtension(new Statistics());
this.AddExtension(new Location());
this.AddExtension(new Recorded());
this.AddExtension(new Uploaded());
}
/// <summary>
/// getter/setter for the GeoRssWhere extension element
/// </summary>
public GeoRssWhere Location
{
get
{
return FindExtension(GeoNametable.GeoRssWhereElement,
GeoNametable.NSGeoRss) as GeoRssWhere;
}
set
{
ReplaceExtension(GeoNametable.GeoRssWhereElement,
GeoNametable.NSGeoRss,
value);
}
}
/// <summary>
/// returns the media:rss group container element
/// </summary>
public MediaGroup Media
{
get
{
return FindExtension(Google.GData.Extensions.MediaRss.MediaRssNameTable.MediaRssGroup,
Google.GData.Extensions.MediaRss.MediaRssNameTable.NSMediaRss) as MediaGroup;
}
set
{
ReplaceExtension(Google.GData.Extensions.MediaRss.MediaRssNameTable.MediaRssGroup,
Google.GData.Extensions.MediaRss.MediaRssNameTable.NSMediaRss,
value);
}
}
/// <summary>
/// returns the yt:statistics element
/// </summary>
/// <returns></returns>
public Statistics Statistics
{
get
{
return FindExtension(YouTubeNameTable.Statistics,
YouTubeNameTable.NSYouTube) as Statistics;
}
set
{
ReplaceExtension(YouTubeNameTable.Statistics,
YouTubeNameTable.NSYouTube,
value);
}
}
/// <summary>
/// Updates this YouTubeEntry.
/// </summary>
/// <returns>the updated YouTubeEntry or null</returns>
public new YouTubeEntry Update()
{
return base.Update() as YouTubeEntry;
}
/// <summary>
/// property accessor for the Comments
/// </summary>
public Comments Comments
{
get
{
return FindExtension(GDataParserNameTable.XmlCommentsElement,
GDataParserNameTable.gNamespace) as Comments;
}
set
{
ReplaceExtension(GDataParserNameTable.XmlCommentsElement,
GDataParserNameTable.gNamespace, value);
}
}
/// <summary>
/// returns the gd:rating element
/// </summary>
/// <returns></returns>
public Rating Rating
{
get
{
return FindExtension(GDataParserNameTable.XmlRatingElement,
GDataParserNameTable.gNamespace) as Rating;
}
set
{
ReplaceExtension(GDataParserNameTable.XmlRatingElement,
GDataParserNameTable.gNamespace,
value);
}
}
/// <summary>
/// returns the ratings link relationship as an atomUri
/// </summary>
public AtomUri RatingsLink
{
get
{
AtomLink link = this.Links.FindService(YouTubeNameTable.RatingsRelationship, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : link.HRef;
}
set
{
AtomLink link = this.Links.FindService(YouTubeNameTable.RatingsRelationship, AtomLink.ATOM_TYPE);
if (link == null)
{
link = new AtomLink(AtomLink.ATOM_TYPE, YouTubeNameTable.RatingsRelationship);
this.Links.Add(link);
}
link.HRef = value;
}
}
/////////////////////////////////////////////////////////////////////////////
/// <summary>
/// returns the yt:duration element
/// </summary>
/// <returns></returns>
public Duration Duration
{
get
{
if (this.Media != null)
{
return Media.Duration;
}
return null;
}
set
{
if (this.Media == null)
{
this.Media = new MediaGroup();
}
if (this.Media.Duration == null)
{
this.Media.Duration = new Duration();
}
this.Media.Duration = value;
}
}
/// <summary>
/// Returns the yt:state tag inside of app:control
/// </summary>
public State State
{
get
{
if (this.AppControl != null)
{
return this.AppControl.FindExtension(YouTubeNameTable.State,
YouTubeNameTable.NSYouTube) as State;
}
return null;
}
set
{
this.Dirty = true;
if (this.AppControl == null)
{
this.AppControl = new AppControl();
}
this.AppControl.ReplaceExtension(YouTubeNameTable.State,
YouTubeNameTable.NSYouTube, value);
}
}
/// <summary>
/// property accessor for the VideoID, if applicable
/// </summary>
public string VideoId
{
get
{
if (this.Media != null && this.Media.VideoId != null)
{
return this.Media.VideoId.Value;
}
return null;
}
set
{
if (this.Media == null)
{
this.Media = new MediaGroup();
}
if (this.Media.VideoId == null)
{
this.Media.VideoId = new VideoId();
}
this.Media.VideoId.Value = value;
}
}
/// <summary>
/// property accessor for the Uploaded element, if applicable
/// returns the date the video was uplaoded
/// </summary>
public string Uploaded
{
get
{
return GetExtensionValue(YouTubeNameTable.Uploaded, YouTubeNameTable.NSYouTube);
}
set
{
SetExtensionValue(YouTubeNameTable.Uploaded, YouTubeNameTable.NSYouTube, value);
}
}
/// <summary>
/// property accessor for the media:credit element, if applicable
/// The media:credit element identifies who uploaded the video
/// returns the date the video was uplaoded
/// </summary>
public MediaCredit Uploader
{
get
{
MediaGroup media = this.Media;
if (media != null)
{
return media.Credit;
}
return null;
}
set
{
if (this.Media == null)
{
this.Media = new MediaGroup();
}
this.Media.Credit = value;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor for the related videos feed URI</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public AtomUri RelatedVideosUri
{
get
{
AtomLink link = this.Links.FindService(YouTubeNameTable.RelatedVideo, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : link.HRef;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor for the video responses feed URI</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public AtomUri VideoResponsesUri
{
get
{
AtomLink link = this.Links.FindService(YouTubeNameTable.ResponseVideo, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : link.HRef;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor for the video responses feed URI</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public AtomUri ComplaintUri
{
get
{
AtomLink link = this.Links.FindService(YouTubeNameTable.Complaint, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : link.HRef;
}
}
/// <summary>
/// boolean property shortcut to set the mediagroup/yt:private element. Setting this to true
/// adds the element, if not already there (otherwise nothing happens)
/// setting this to false, removes it
/// it returns if the mediagroup:yt:private element exists, or not
/// </summary>
/// <returns></returns>
public bool Private
{
get
{
Private p = null;
if (this.Media != null)
{
p = Media.FindExtension(YouTubeNameTable.Private,
YouTubeNameTable.NSYouTube) as Private;
}
return p != null;
}
set
{
Private p = null;
if (this.Media != null)
{
p = Media.FindExtension(YouTubeNameTable.Private,
YouTubeNameTable.NSYouTube) as Private;
}
if (value == true)
{
if (p == null)
{
if (this.Media == null)
{
this.Media = new MediaGroup();
}
this.Media.ExtensionElements.Add(new Private());
}
}
else
{
// if we set it to false, we just going to remove the extension
if (p != null)
{
this.Media.DeleteExtensions(p.XmlName, p.XmlNameSpace);
}
}
}
}
}
}
| |
using Microsoft.VisualStudio.Services.Agent.Listener;
using Microsoft.VisualStudio.Services.Agent.Listener.Configuration;
using Microsoft.VisualStudio.Services.Agent.Util;
using Moq;
using System;
using System.Runtime.CompilerServices;
using Xunit;
namespace Microsoft.VisualStudio.Services.Agent.Tests
{
public sealed class CommandSettingsL0
{
private readonly Mock<IPromptManager> _promptManager = new Mock<IPromptManager>();
private readonly Mock<ISecretMasker> _secretMasker = new Mock<ISecretMasker>();
// It is sufficient to test one arg only. All individual args are tested by the PromptsFor___ methods.
// The PromptsFor___ methods suffice to cover the interesting differences between each of the args.
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsArg()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--agent", "some agent" });
// Act.
string actual = command.GetAgentName();
// Assert.
Assert.Equal("some agent", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsArgFromEnvVar()
{
using (TestHostContext hc = CreateTestContext())
{
try
{
// Arrange.
Environment.SetEnvironmentVariable("VSTS_AGENT_INPUT_AGENT", "some agent");
var command = new CommandSettings(hc, args: new string[0]);
// Act.
string actual = command.GetAgentName();
// Assert.
Assert.Equal("some agent", actual);
Assert.Equal(string.Empty, Environment.GetEnvironmentVariable("VSTS_AGENT_INPUT_AGENT") ?? string.Empty); // Should remove.
_secretMasker.Verify(x => x.AddValue(It.IsAny<string>()), Times.Never);
}
finally
{
Environment.SetEnvironmentVariable("VSTS_AGENT_INPUT_AGENT", null);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsArgSecretFromEnvVar()
{
using (TestHostContext hc = CreateTestContext())
{
try
{
// Arrange.
Environment.SetEnvironmentVariable("VSTS_AGENT_INPUT_TOKEN", "some secret token value");
var command = new CommandSettings(hc, args: new string[0]);
// Act.
string actual = command.GetToken();
// Assert.
Assert.Equal("some secret token value", actual);
Assert.Equal(string.Empty, Environment.GetEnvironmentVariable("VSTS_AGENT_INPUT_TOKEN") ?? string.Empty); // Should remove.
_secretMasker.Verify(x => x.AddValue("some secret token value"));
}
finally
{
Environment.SetEnvironmentVariable("VSTS_AGENT_INPUT_TOKEN", null);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsCommandConfigure()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "configure" });
// Act.
bool actual = command.Configure;
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsCommandRun()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "run" });
// Act.
bool actual = command.Run;
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsCommandUnconfigure()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "remove" });
// Act.
bool actual = command.Unconfigure;
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsFlagAcceptTeeEula()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--acceptteeeula" });
// Act.
bool actual = command.GetAcceptTeeEula();
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsFlagCommit()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--commit" });
// Act.
bool actual = command.Commit;
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsFlagHelp()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--help" });
// Act.
bool actual = command.Help;
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsFlagReplace()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--replace" });
// Act.
bool actual = command.GetReplace();
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsFlagRunAsService()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--runasservice" });
// Act.
bool actual = command.GetRunAsService();
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsFlagUnattended()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--unattended" });
// Act.
bool actual = command.Unattended;
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsFlagUnattendedFromEnvVar()
{
using (TestHostContext hc = CreateTestContext())
{
try
{
// Arrange.
Environment.SetEnvironmentVariable("VSTS_AGENT_INPUT_UNATTENDED", "true");
var command = new CommandSettings(hc, args: new string[0]);
// Act.
bool actual = command.Unattended;
// Assert.
Assert.Equal(true, actual);
Assert.Equal(string.Empty, Environment.GetEnvironmentVariable("VSTS_AGENT_INPUT_UNATTENDED") ?? string.Empty); // Should remove.
_secretMasker.Verify(x => x.AddValue(It.IsAny<string>()), Times.Never);
}
finally
{
Environment.SetEnvironmentVariable("VSTS_AGENT_INPUT_UNATTENDED", null);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsFlagVersion()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--version" });
// Act.
bool actual = command.Version;
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PassesUnattendedToReadBool()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--unattended" });
_promptManager
.Setup(x => x.ReadBool(
Constants.Agent.CommandLine.Flags.AcceptTeeEula, // argName
StringUtil.Loc("AcceptTeeEula"), // description
false, // defaultValue
true)) // unattended
.Returns(true);
// Act.
bool actual = command.GetAcceptTeeEula();
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PassesUnattendedToReadValue()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--unattended" });
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.Agent, // argName
StringUtil.Loc("AgentName"), // description
false, // secret
Environment.MachineName, // defaultValue
Validators.NonEmptyValidator, // validator
true)) // unattended
.Returns("some agent");
// Act.
string actual = command.GetAgentName();
// Assert.
Assert.Equal("some agent", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForAcceptTeeEula()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadBool(
Constants.Agent.CommandLine.Flags.AcceptTeeEula, // argName
StringUtil.Loc("AcceptTeeEula"), // description
false, // defaultValue
false)) // unattended
.Returns(true);
// Act.
bool actual = command.GetAcceptTeeEula();
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForAgent()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.Agent, // argName
StringUtil.Loc("AgentName"), // description
false, // secret
Environment.MachineName, // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("some agent");
// Act.
string actual = command.GetAgentName();
// Assert.
Assert.Equal("some agent", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForAuth()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.Auth, // argName
StringUtil.Loc("AuthenticationType"), // description
false, // secret
"some default auth", // defaultValue
Validators.AuthSchemeValidator, // validator
false)) // unattended
.Returns("some auth");
// Act.
string actual = command.GetAuth("some default auth");
// Assert.
Assert.Equal("some auth", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForPassword()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.Password, // argName
StringUtil.Loc("Password"), // description
true, // secret
string.Empty, // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("some password");
// Act.
string actual = command.GetPassword();
// Assert.
Assert.Equal("some password", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForPool()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.Pool, // argName
StringUtil.Loc("AgentMachinePoolNameLabel"), // description
false, // secret
"default", // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("some pool");
// Act.
string actual = command.GetPool();
// Assert.
Assert.Equal("some pool", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForReplace()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadBool(
Constants.Agent.CommandLine.Flags.Replace, // argName
StringUtil.Loc("Replace"), // description
false, // defaultValue
false)) // unattended
.Returns(true);
// Act.
bool actual = command.GetReplace();
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForRunAsService()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadBool(
Constants.Agent.CommandLine.Flags.RunAsService, // argName
StringUtil.Loc("RunAgentAsServiceDescription"), // description
false, // defaultValue
false)) // unattended
.Returns(true);
// Act.
bool actual = command.GetRunAsService();
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForToken()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.Token, // argName
StringUtil.Loc("PersonalAccessToken"), // description
true, // secret
string.Empty, // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("some token");
// Act.
string actual = command.GetToken();
// Assert.
Assert.Equal("some token", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForUrl()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.Url, // argName
StringUtil.Loc("ServerUrl"), // description
false, // secret
string.Empty, // defaultValue
Validators.ServerUrlValidator, // validator
false)) // unattended
.Returns("some url");
// Act.
string actual = command.GetUrl();
// Assert.
Assert.Equal("some url", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForUserName()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.UserName, // argName
StringUtil.Loc("UserName"), // description
false, // secret
string.Empty, // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("some user name");
// Act.
string actual = command.GetUserName();
// Assert.
Assert.Equal("some user name", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForWindowsLogonAccount()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.WindowsLogonAccount, // argName
StringUtil.Loc("WindowsLogonAccountNameDescription"), // description
false, // secret
"some default account", // defaultValue
Validators.NTAccountValidator, // validator
false)) // unattended
.Returns("some windows logon account");
// Act.
string actual = command.GetWindowsLogonAccount("some default account", StringUtil.Loc("WindowsLogonAccountNameDescription"));
// Assert.
Assert.Equal("some windows logon account", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForWindowsLogonPassword()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
string accountName = "somewindowsaccount";
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.WindowsLogonPassword, // argName
StringUtil.Loc("WindowsLogonPasswordDescription", accountName), // description
true, // secret
string.Empty, // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("some windows logon password");
// Act.
string actual = command.GetWindowsLogonPassword(accountName);
// Assert.
Assert.Equal("some windows logon password", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForWork()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.Work, // argName
StringUtil.Loc("WorkFolderDescription"), // description
false, // secret
"_work", // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("some work");
// Act.
string actual = command.GetWork();
// Assert.
Assert.Equal("some work", actual);
}
}
// It is sufficient to test one arg only. All individual args are tested by the PromptsFor___ methods.
// The PromptsFor___ methods suffice to cover the interesting differences between each of the args.
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsWhenEmpty()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--url", "" });
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.Url, // argName
StringUtil.Loc("ServerUrl"), // description
false, // secret
string.Empty, // defaultValue
Validators.ServerUrlValidator, // validator
false)) // unattended
.Returns("some url");
// Act.
string actual = command.GetUrl();
// Assert.
Assert.Equal("some url", actual);
}
}
// It is sufficient to test one arg only. All individual args are tested by the PromptsFor___ methods.
// The PromptsFor___ methods suffice to cover the interesting differences between each of the args.
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsWhenInvalid()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--url", "notValid" });
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.Url, // argName
StringUtil.Loc("ServerUrl"), // description
false, // secret
string.Empty, // defaultValue
Validators.ServerUrlValidator, // validator
false)) // unattended
.Returns("some url");
// Act.
string actual = command.GetUrl();
// Assert.
Assert.Equal("some url", actual);
}
}
/*
* Deployment Agent Tests
*/
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsFlagDeploymentAgentWithBackCompat()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--machinegroup" });
// Act.
bool actual = command.DeploymentGroup;
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsFlagDeploymentAgent()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--deploymentgroup" });
// Act.
bool actual = command.DeploymentGroup;
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsFlagAddDeploymentGroupTagsBackCompat()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--addmachinegrouptags" });
// Act.
bool actual = command.GetDeploymentGroupTagsRequired();
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void GetsFlagAddDeploymentGroupTags()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--adddeploymentgrouptags" });
// Act.
bool actual = command.GetDeploymentGroupTagsRequired();
// Assert.
Assert.True(actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForProjectName()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.ProjectName, // argName
StringUtil.Loc("ProjectName"), // description
false, // secret
string.Empty, // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("TestProject");
// Act.
string actual = command.GetProjectName(string.Empty);
// Assert.
Assert.Equal("TestProject", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForCollectionName()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.CollectionName, // argName
StringUtil.Loc("CollectionName"), // description
false, // secret
"DefaultCollection", // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("TestCollection");
// Act.
string actual = command.GetCollectionName();
// Assert.
Assert.Equal("TestCollection", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForDeploymentGroupName()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.DeploymentGroupName, // argName
StringUtil.Loc("DeploymentGroupName"), // description
false, // secret
string.Empty, // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("Test Deployment Group");
// Act.
string actual = command.GetDeploymentGroupName();
// Assert.
Assert.Equal("Test Deployment Group", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void DeploymentGroupNameBackCompat()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(
hc,
new[]
{
"--machinegroupname", "Test-MachineGroupName",
"--deploymentgroupname", "Test-DeploymentGroupName"
});
_promptManager.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.DeploymentGroupName, // argName
StringUtil.Loc("DeploymentGroupName"), // description
false, // secret
string.Empty, // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("This Method should not get called!");
// Act.
string actual = command.GetDeploymentGroupName();
// Validate if --machinegroupname parameter is working
Assert.Equal("Test-MachineGroupName", actual);
// Validate Read Value should not get invoked.
_promptManager.Verify(x =>
x.ReadValue(It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<Func<string, bool>>(), It.IsAny<bool>()), Times.Never);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void PromptsForDeploymentGroupTags()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[0]);
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.DeploymentGroupTags, // argName
StringUtil.Loc("DeploymentGroupTags"), // description
false, // secret
string.Empty, // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("Test-Tag1,Test-Tg2");
// Act.
string actual = command.GetDeploymentGroupTags();
// Assert.
Assert.Equal("Test-Tag1,Test-Tg2", actual);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void DeploymentGroupTagsBackCompat()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(
hc,
new[]
{
"--machinegrouptags", "Test-MachineGrouptag1,Test-MachineGrouptag2",
"--deploymentgrouptags", "Test-DeploymentGrouptag1,Test-DeploymentGrouptag2"
});
_promptManager.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.DeploymentGroupTags, // argName
StringUtil.Loc("DeploymentGroupTags"), // description
false, // secret
string.Empty, // defaultValue
Validators.NonEmptyValidator, // validator
false)) // unattended
.Returns("This Method should not get called!");
// Act.
string actual = command.GetDeploymentGroupTags();
// Validate if --machinegrouptags parameter is working fine
Assert.Equal("Test-MachineGrouptag1,Test-MachineGrouptag2", actual);
// Validate Read Value should not get invoked.
_promptManager.Verify(x =>
x.ReadValue(It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<bool>(),It.IsAny<string>(), It.IsAny<Func<string,bool>>(),It.IsAny<bool>()), Times.Never);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void ValidateCommands()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "badcommand" });
// Assert.
Assert.True(command.Validate().Contains("badcommand"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void ValidateFlags()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--badflag" });
// Assert.
Assert.True(command.Validate().Contains("badflag"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void ValidateArgs()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc, args: new string[] { "--badargname", "bad arg value" });
// Assert.
Assert.True(command.Validate().Contains("badargname"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", nameof(CommandSettings))]
public void ValidateGoodCommandline()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var command = new CommandSettings(hc,
args: new string[] {
"configure",
"--unattended",
"--agent",
"test agent" });
// Assert.
Assert.True(command.Validate().Count == 0);
}
}
private TestHostContext CreateTestContext([CallerMemberName] string testName = "")
{
TestHostContext hc = new TestHostContext(this, testName);
hc.SetSingleton<IPromptManager>(_promptManager.Object);
hc.SetSingleton<ISecretMasker>(_secretMasker.Object);
return hc;
}
}
}
| |
//---------------------------------------------------------------------------
//
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Limited Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/limitedpermissivelicense.mspx
// All other rights reserved.
//
// This file is part of the 3D Tools for Windows Presentation Foundation
// project. For more information, see:
//
// http://CodePlex.com/Wiki/View.aspx?ProjectName=3DTools
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Shapes;
using System.Windows.Input;
using System.Windows.Markup; // IAddChild, ContentPropertyAttribute
namespace _3DTools
{
/// <summary>
/// This class enables a Viewport3D to be enhanced by allowing UIElements to be placed
/// behind and in front of the Viewport3D. These can then be used for various enhancements.
/// For examples see the Trackball, or InteractiveViewport3D.
/// </summary>
[ContentProperty("Content")]
public abstract class Viewport3DDecorator : FrameworkElement, IAddChild
{
/// <summary>
/// Creates the Viewport3DDecorator
/// </summary>
public Viewport3DDecorator()
{
// create the two lists of children
_preViewportChildren = new UIElementCollection(this, this);
_postViewportChildren = new UIElementCollection(this, this);
// no content yet
_content = null;
}
/// <summary>
/// The content/child of the Viewport3DDecorator. A Viewport3DDecorator only has one
/// child and this child must be either another Viewport3DDecorator or a Viewport3D.
/// </summary>
public UIElement Content
{
get
{
return _content;
}
set
{
// check to make sure it is a Viewport3D or a Viewport3DDecorator
if (!(value is Viewport3D || value is Viewport3DDecorator))
{
throw new ArgumentException("Not a valid child type", "value");
}
// check to make sure we're attempting to set something new
if (_content != value)
{
UIElement oldContent = _content;
UIElement newContent = value;
// remove the previous child
RemoveVisualChild(oldContent);
RemoveLogicalChild(oldContent);
// set the private variable
_content = value;
// link in the new child
AddLogicalChild(newContent);
AddVisualChild(newContent);
// let anyone know that derives from us that there was a change
OnViewport3DDecoratorContentChange(oldContent, newContent);
// data bind to what is below us so that we have the same width/height
// as the Viewport3D being enhanced
// create the bindings now for use later
BindToContentsWidthHeight(newContent);
// Invalidate measure to indicate a layout update may be necessary
InvalidateMeasure();
}
}
}
/// <summary>
/// Data binds the (Max/Min)Width and (Max/Min)Height properties to the same
/// ones as the content. This will make it so we end up being sized to be
/// exactly the same ActualWidth and ActualHeight as waht is below us.
/// </summary>
/// <param name="newContent">What to bind to</param>
private void BindToContentsWidthHeight(UIElement newContent)
{
// bind to width height
Binding _widthBinding = new Binding("Width");
_widthBinding.Mode = BindingMode.OneWay;
Binding _heightBinding = new Binding("Height");
_heightBinding.Mode = BindingMode.OneWay;
_widthBinding.Source = newContent;
_heightBinding.Source = newContent;
BindingOperations.SetBinding(this, WidthProperty, _widthBinding);
BindingOperations.SetBinding(this, HeightProperty, _heightBinding);
// bind to max width and max height
Binding _maxWidthBinding = new Binding("MaxWidth");
_maxWidthBinding.Mode = BindingMode.OneWay;
Binding _maxHeightBinding = new Binding("MaxHeight");
_maxHeightBinding.Mode = BindingMode.OneWay;
_maxWidthBinding.Source = newContent;
_maxHeightBinding.Source = newContent;
BindingOperations.SetBinding(this, MaxWidthProperty, _maxWidthBinding);
BindingOperations.SetBinding(this, MaxHeightProperty, _maxHeightBinding);
// bind to min width and min height
Binding _minWidthBinding = new Binding("MinWidth");
_minWidthBinding.Mode = BindingMode.OneWay;
Binding _minHeightBinding = new Binding("MinHeight");
_minHeightBinding.Mode = BindingMode.OneWay;
_minWidthBinding.Source = newContent;
_minHeightBinding.Source = newContent;
BindingOperations.SetBinding(this, MinWidthProperty, _minWidthBinding);
BindingOperations.SetBinding(this, MinHeightProperty, _minHeightBinding);
}
/// <summary>
/// Extenders of Viewport3DDecorator can override this function to be notified
/// when the Content property changes
/// </summary>
/// <param name="oldContent">The old value of the Content property</param>
/// <param name="newContent">The new value of the Content property</param>
protected virtual void OnViewport3DDecoratorContentChange(UIElement oldContent, UIElement newContent)
{
}
/// <summary>
/// Property to get the Viewport3D that is being enhanced.
/// </summary>
public Viewport3D Viewport3D
{
get
{
Viewport3D viewport3D = null;
Viewport3DDecorator currEnhancer = this;
// we follow the enhancers down until we get the
// Viewport3D they are enhancing
while (true)
{
UIElement currContent = currEnhancer.Content;
if (currContent == null)
{
break;
}
else if (currContent is Viewport3D)
{
viewport3D = (Viewport3D)currContent;
break;
}
else
{
currEnhancer = (Viewport3DDecorator)currContent;
}
}
return viewport3D;
}
}
/// <summary>
/// The UIElements that occur before the Viewport3D
/// </summary>
protected UIElementCollection PreViewportChildren
{
get
{
return _preViewportChildren;
}
}
/// <summary>
/// The UIElements that occur after the Viewport3D
/// </summary>
protected UIElementCollection PostViewportChildren
{
get
{
return _postViewportChildren;
}
}
/// <summary>
/// Returns the number of Visual children this element has.
/// </summary>
protected override int VisualChildrenCount
{
get
{
int contentCount = (Content == null ? 0 : 1);
return PreViewportChildren.Count +
PostViewportChildren.Count +
contentCount;
}
}
/// <summary>
/// Returns the child at the specified index.
/// </summary>
protected override Visual GetVisualChild(int index)
{
int orginalIndex = index;
// see if index is in the pre viewport children
if (index < PreViewportChildren.Count)
{
return PreViewportChildren[index];
}
index -= PreViewportChildren.Count;
// see if it's the content
if (Content != null && index == 0)
{
return Content;
}
index -= (Content == null ? 0 : 1);
// see if it's the post viewport children
if (index < PostViewportChildren.Count)
{
return PostViewportChildren[index];
}
// if we didn't return then the index is out of range - throw an error
throw new ArgumentOutOfRangeException("index", orginalIndex, "Out of range visual requested");
}
/// <summary>
/// Returns an enumertor to this element's logical children.
/// </summary>
protected override IEnumerator LogicalChildren
{
get
{
Visual[] logicalChildren = new Visual[VisualChildrenCount];
for (int i = 0; i < VisualChildrenCount; i++)
{
logicalChildren[i] = GetVisualChild(i);
}
// return an enumerator to the ArrayList
return logicalChildren.GetEnumerator();
}
}
/// <summary>
/// Updates the DesiredSize of the Viewport3DDecorator
/// </summary>
/// <param name="constraint">The "upper limit" that the return value should not exceed</param>
/// <returns>The desired size of the Viewport3DDecorator</returns>
protected override Size MeasureOverride(Size constraint)
{
Size finalSize = new Size();
MeasurePreViewportChildren(constraint);
// measure our Viewport3D(Enhancer)
if (Content != null)
{
Content.Measure(constraint);
finalSize = Content.DesiredSize;
}
MeasurePostViewportChildren(constraint);
return finalSize;
}
/// <summary>
/// Measures the size of all the PreViewportChildren. If special measuring behavior is needed, this
/// method should be overridden.
/// </summary>
/// <param name="constraint">The "upper limit" on the size of an element</param>
protected virtual void MeasurePreViewportChildren(Size constraint)
{
// measure the pre viewport children
MeasureUIElementCollection(PreViewportChildren, constraint);
}
/// <summary>
/// Measures the size of all the PostViewportChildren. If special measuring behavior is needed, this
/// method should be overridden.
/// </summary>
/// <param name="constraint">The "upper limit" on the size of an element</param>
protected virtual void MeasurePostViewportChildren(Size constraint)
{
// measure the post viewport children
MeasureUIElementCollection(PostViewportChildren, constraint);
}
/// <summary>
/// Measures all of the UIElements in a UIElementCollection
/// </summary>
/// <param name="collection">The collection to measure</param>
/// <param name="constraint">The "upper limit" on the size of an element</param>
private void MeasureUIElementCollection(UIElementCollection collection, Size constraint)
{
// measure the pre viewport visual visuals
foreach (UIElement uiElem in collection)
{
uiElem.Measure(constraint);
}
}
/// <summary>
/// Arranges the Pre and Post Viewport children, and arranges itself
/// </summary>
/// <param name="arrangeSize">The final size to use to arrange itself and its children</param>
protected override Size ArrangeOverride(Size arrangeSize)
{
ArrangePreViewportChildren(arrangeSize);
// arrange our Viewport3D(Enhancer)
if (Content != null)
{
Content.Arrange(new Rect(arrangeSize));
}
ArrangePostViewportChildren(arrangeSize);
return arrangeSize;
}
/// <summary>
/// Arranges all the PreViewportChildren. If special measuring behavior is needed, this
/// method should be overridden.
/// </summary>
/// <param name="arrangeSize">The final size to use to arrange each child</param>
protected virtual void ArrangePreViewportChildren(Size arrangeSize)
{
ArrangeUIElementCollection(PreViewportChildren, arrangeSize);
}
/// <summary>
/// Arranges all the PostViewportChildren. If special measuring behavior is needed, this
/// method should be overridden.
/// </summary>
/// <param name="arrangeSize">The final size to use to arrange each child</param>
protected virtual void ArrangePostViewportChildren(Size arrangeSize)
{
ArrangeUIElementCollection(PostViewportChildren, arrangeSize);
}
/// <summary>
/// Arranges all the UIElements in the passed in UIElementCollection
/// </summary>
/// <param name="collection">The collection that should be arranged</param>
/// <param name="constraint">The final size that element should use to arrange itself and its children</param>
private void ArrangeUIElementCollection(UIElementCollection collection, Size constraint)
{
// measure the pre viewport visual visuals
foreach (UIElement uiElem in collection)
{
uiElem.Arrange(new Rect(constraint));
}
}
//------------------------------------------------------
//
// IAddChild implementation
//
//------------------------------------------------------
void IAddChild.AddChild(Object value)
{
// check against null
if (value == null)
{
throw new ArgumentNullException("value");
}
// we only can have one child
if (this.Content != null)
{
throw new ArgumentException("Viewport3DDecorator can only have one child");
}
// now we can actually set the content
Content = (UIElement)value;
}
void IAddChild.AddText(string text)
{
// The only text we accept is whitespace, which we ignore.
for (int i = 0; i < text.Length; i++)
{
if (!Char.IsWhiteSpace(text[i]))
{
throw new ArgumentException("Non whitespace in add text", text);
}
}
}
//---------------------------------------------------------
//
// Private data
//
//---------------------------------------------------------
private UIElementCollection _preViewportChildren;
private UIElementCollection _postViewportChildren;
private UIElement _content;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Orleans.CodeGeneration;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
namespace Orleans.Runtime
{
internal class Message : IOutgoingMessage
{
public static int LargeMessageSizeThreshold { get; set; }
public const int LENGTH_HEADER_SIZE = 8;
public const int LENGTH_META_HEADER = 4;
#region metadata
[NonSerialized]
private string _targetHistory;
[NonSerialized]
private DateTime? _queuedTime;
[NonSerialized]
private int? _retryCount;
[NonSerialized]
private int? _maxRetries;
public string TargetHistory
{
get { return _targetHistory; }
set { _targetHistory = value; }
}
public DateTime? QueuedTime
{
get { return _queuedTime; }
set { _queuedTime = value; }
}
public int? RetryCount
{
get { return _retryCount; }
set { _retryCount = value; }
}
public int? MaxRetries
{
get { return _maxRetries; }
set { _maxRetries = value; }
}
#endregion
/// <summary>
/// NOTE: The contents of bodyBytes should never be modified
/// </summary>
private List<ArraySegment<byte>> bodyBytes;
private List<ArraySegment<byte>> headerBytes;
private object bodyObject;
// Cache values of TargetAddess and SendingAddress as they are used very frequently
private ActivationAddress targetAddress;
private ActivationAddress sendingAddress;
private static readonly Logger logger;
static Message()
{
logger = LogManager.GetLogger("Message", LoggerType.Runtime);
}
public enum Categories
{
Ping,
System,
Application,
}
public enum Directions
{
Request,
Response,
OneWay
}
public enum ResponseTypes
{
Success,
Error,
Rejection
}
public enum RejectionTypes
{
Transient,
Overloaded,
DuplicateRequest,
Unrecoverable,
GatewayTooBusy,
}
internal HeadersContainer Headers { get; set; } = new HeadersContainer();
public Categories Category
{
get { return Headers.Category; }
set { Headers.Category = value; }
}
public Directions Direction
{
get { return Headers.Direction ?? default(Directions); }
set { Headers.Direction = value; }
}
public bool HasDirection => Headers.Direction.HasValue;
public bool IsReadOnly
{
get { return Headers.IsReadOnly; }
set { Headers.IsReadOnly = value; }
}
public bool IsAlwaysInterleave
{
get { return Headers.IsAlwaysInterleave; }
set { Headers.IsAlwaysInterleave = value; }
}
public bool IsUnordered
{
get { return Headers.IsUnordered; }
set { Headers.IsUnordered = value; }
}
public bool IsReturnedFromRemoteCluster
{
get { return Headers.IsReturnedFromRemoteCluster; }
set { Headers.IsReturnedFromRemoteCluster = value; }
}
public CorrelationId Id
{
get { return Headers.Id; }
set { Headers.Id = value; }
}
public int ResendCount
{
get { return Headers.ResendCount; }
set { Headers.ResendCount = value; }
}
public int ForwardCount
{
get { return Headers.ForwardCount; }
set { Headers.ForwardCount = value; }
}
public SiloAddress TargetSilo
{
get { return Headers.TargetSilo; }
set
{
Headers.TargetSilo = value;
targetAddress = null;
}
}
public GrainId TargetGrain
{
get { return Headers.TargetGrain; }
set
{
Headers.TargetGrain = value;
targetAddress = null;
}
}
public ActivationId TargetActivation
{
get { return Headers.TargetActivation; }
set
{
Headers.TargetActivation = value;
targetAddress = null;
}
}
public ActivationAddress TargetAddress
{
get { return targetAddress ?? (targetAddress = ActivationAddress.GetAddress(TargetSilo, TargetGrain, TargetActivation)); }
set
{
TargetGrain = value.Grain;
TargetActivation = value.Activation;
TargetSilo = value.Silo;
targetAddress = value;
}
}
public GuidId TargetObserverId
{
get { return Headers.TargetObserverId; }
set
{
Headers.TargetObserverId = value;
targetAddress = null;
}
}
public SiloAddress SendingSilo
{
get { return Headers.SendingSilo; }
set
{
Headers.SendingSilo = value;
sendingAddress = null;
}
}
public GrainId SendingGrain
{
get { return Headers.SendingGrain; }
set
{
Headers.SendingGrain = value;
sendingAddress = null;
}
}
public ActivationId SendingActivation
{
get { return Headers.SendingActivation; }
set
{
Headers.SendingActivation = value;
sendingAddress = null;
}
}
public ActivationAddress SendingAddress
{
get { return sendingAddress ?? (sendingAddress = ActivationAddress.GetAddress(SendingSilo, SendingGrain, SendingActivation)); }
set
{
SendingGrain = value.Grain;
SendingActivation = value.Activation;
SendingSilo = value.Silo;
sendingAddress = value;
}
}
public bool IsNewPlacement
{
get { return Headers.IsNewPlacement; }
set
{
Headers.IsNewPlacement = value;
}
}
public ResponseTypes Result
{
get { return Headers.Result; }
set { Headers.Result = value; }
}
public DateTime? Expiration
{
get { return Headers.Expiration; }
set { Headers.Expiration = value; }
}
public bool IsExpired => Expiration.HasValue && DateTime.UtcNow > Expiration.Value;
public bool IsExpirableMessage(IMessagingConfiguration config)
{
if (!config.DropExpiredMessages) return false;
GrainId id = TargetGrain;
if (id == null) return false;
// don't set expiration for one way, system target and system grain messages.
return Direction != Directions.OneWay && !id.IsSystemTarget && !Constants.IsSystemGrain(id);
}
public string DebugContext
{
get { return GetNotNullString(Headers.DebugContext); }
set { Headers.DebugContext = value; }
}
public List<ActivationAddress> CacheInvalidationHeader
{
get { return Headers.CacheInvalidationHeader; }
set { Headers.CacheInvalidationHeader = value; }
}
internal void AddToCacheInvalidationHeader(ActivationAddress address)
{
var list = new List<ActivationAddress>();
if (CacheInvalidationHeader != null)
{
list.AddRange(CacheInvalidationHeader);
}
list.Add(address);
CacheInvalidationHeader = list;
}
// Resends are used by the sender, usualy due to en error to send or due to a transient rejection.
public bool MayResend(IMessagingConfiguration config)
{
return ResendCount < config.MaxResendCount;
}
// Forwardings are used by the receiver, usualy when it cannot process the message and forwars it to another silo to perform the processing
// (got here due to outdated cache, silo is shutting down/overloaded, ...).
public bool MayForward(GlobalConfiguration config)
{
return ForwardCount < config.MaxForwardCount;
}
/// <summary>
/// Set by sender's placement logic when NewPlacementRequested is true
/// so that receiver knows desired grain type
/// </summary>
public string NewGrainType
{
get { return GetNotNullString(Headers.NewGrainType); }
set { Headers.NewGrainType = value; }
}
/// <summary>
/// Set by caller's grain reference
/// </summary>
public string GenericGrainType
{
get { return GetNotNullString(Headers.GenericGrainType); }
set { Headers.GenericGrainType = value; }
}
public RejectionTypes RejectionType
{
get { return Headers.RejectionType; }
set { Headers.RejectionType = value; }
}
public string RejectionInfo
{
get { return GetNotNullString(Headers.RejectionInfo); }
set { Headers.RejectionInfo = value; }
}
public Dictionary<string, object> RequestContextData
{
get { return Headers.RequestContextData; }
set { Headers.RequestContextData = value; }
}
public object BodyObject
{
get
{
if (bodyObject != null)
{
return bodyObject;
}
try
{
bodyObject = DeserializeBody(bodyBytes);
}
finally
{
if (bodyBytes != null)
{
BufferPool.GlobalPool.Release(bodyBytes);
bodyBytes = null;
}
}
return bodyObject;
}
set
{
bodyObject = value;
if (bodyBytes == null) return;
BufferPool.GlobalPool.Release(bodyBytes);
bodyBytes = null;
}
}
private static object DeserializeBody(List<ArraySegment<byte>> bytes)
{
if (bytes == null)
{
return null;
}
try
{
var stream = new BinaryTokenStreamReader(bytes);
return SerializationManager.Deserialize(stream);
}
catch (Exception ex)
{
logger.Error(ErrorCode.Messaging_UnableToDeserializeBody, "Exception deserializing message body", ex);
throw;
}
}
public Message()
{
bodyObject = null;
bodyBytes = null;
headerBytes = null;
}
private Message(Categories type, Directions subtype)
: this()
{
Category = type;
Direction = subtype;
}
internal static Message CreateMessage(InvokeMethodRequest request, InvokeMethodOptions options)
{
var message = new Message(
Categories.Application,
(options & InvokeMethodOptions.OneWay) != 0 ? Directions.OneWay : Directions.Request)
{
Id = CorrelationId.GetNext(),
IsReadOnly = (options & InvokeMethodOptions.ReadOnly) != 0,
IsUnordered = (options & InvokeMethodOptions.Unordered) != 0,
BodyObject = request
};
if ((options & InvokeMethodOptions.AlwaysInterleave) != 0)
message.IsAlwaysInterleave = true;
var contextData = RequestContext.Export();
if (contextData != null)
{
message.RequestContextData = contextData;
}
return message;
}
// Initializes body and header but does not take ownership of byte.
// Caller must clean up bytes
public Message(List<ArraySegment<byte>> header)
{
var context = new DeserializationContext
{
StreamReader = new BinaryTokenStreamReader(header)
};
Headers = SerializationManager.DeserializeMessageHeaders(context);
}
/// <summary>
/// Clears the current body and sets the serialized body contents to the provided value.
/// </summary>
/// <param name="body">The serialized body contents.</param>
public void SetBodyBytes(List<ArraySegment<byte>> body)
{
// Dispose of the current body.
this.BodyObject = null;
this.bodyBytes = body;
}
/// <summary>
/// Deserializes the provided value into this instance's <see cref="BodyObject"/>.
/// </summary>
/// <param name="body">The serialized body contents.</param>
public void DeserializeBodyObject(List<ArraySegment<byte>> body)
{
this.BodyObject = DeserializeBody(body);
}
public Message CreateResponseMessage()
{
var response = new Message(this.Category, Directions.Response)
{
Id = this.Id,
IsReadOnly = this.IsReadOnly,
IsAlwaysInterleave = this.IsAlwaysInterleave,
TargetSilo = this.SendingSilo
};
if (SendingGrain != null)
{
response.TargetGrain = SendingGrain;
if (SendingActivation != null)
{
response.TargetActivation = SendingActivation;
}
}
response.SendingSilo = this.TargetSilo;
if (TargetGrain != null)
{
response.SendingGrain = TargetGrain;
if (TargetActivation != null)
{
response.SendingActivation = TargetActivation;
}
else if (this.TargetGrain.IsSystemTarget)
{
response.SendingActivation = ActivationId.GetSystemActivation(TargetGrain, TargetSilo);
}
}
if (DebugContext != null)
{
response.DebugContext = DebugContext;
}
response.CacheInvalidationHeader = CacheInvalidationHeader;
response.Expiration = Expiration;
var contextData = RequestContext.Export();
if (contextData != null)
{
response.RequestContextData = contextData;
}
return response;
}
public Message CreateRejectionResponse(RejectionTypes type, string info, OrleansException ex = null)
{
var response = CreateResponseMessage();
response.Result = ResponseTypes.Rejection;
response.RejectionType = type;
response.RejectionInfo = info;
response.BodyObject = ex;
if (logger.IsVerbose) logger.Verbose("Creating {0} rejection with info '{1}' for {2} at:" + Environment.NewLine + "{3}", type, info, this, Utils.GetStackTrace());
return response;
}
public Message CreatePromptExceptionResponse(Exception exception)
{
return new Message(Category, Directions.Response)
{
Result = ResponseTypes.Error,
BodyObject = Response.ExceptionResponse(exception)
};
}
public void ClearTargetAddress()
{
targetAddress = null;
}
private static string GetNotNullString(string s)
{
return s ?? string.Empty;
}
/// <summary>
/// Tell whether two messages are duplicates of one another
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool IsDuplicate(Message other)
{
return Equals(SendingSilo, other.SendingSilo) && Equals(Id, other.Id);
}
#region Serialization
public List<ArraySegment<byte>> Serialize(out int headerLength)
{
int dummy;
return Serialize_Impl(out headerLength, out dummy);
}
private List<ArraySegment<byte>> Serialize_Impl(out int headerLengthOut, out int bodyLengthOut)
{
var context = new SerializationContext
{
StreamWriter = new BinaryTokenStreamWriter()
};
SerializationManager.SerializeMessageHeaders(Headers, context);
if (bodyBytes == null)
{
var bodyStream = new BinaryTokenStreamWriter();
SerializationManager.Serialize(bodyObject, bodyStream);
// We don't bother to turn this into a byte array and save it in bodyBytes because Serialize only gets called on a message
// being sent off-box. In this case, the likelihood of needed to re-serialize is very low, and the cost of capturing the
// serialized bytes from the steam -- where they're a list of ArraySegment objects -- into an array of bytes is actually
// pretty high (an array allocation plus a bunch of copying).
bodyBytes = bodyStream.ToBytes();
}
if (headerBytes != null)
{
BufferPool.GlobalPool.Release(headerBytes);
}
headerBytes = context.StreamWriter.ToBytes();
int headerLength = context.StreamWriter.CurrentOffset;
int bodyLength = BufferLength(bodyBytes);
var bytes = new List<ArraySegment<byte>>();
bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(headerLength)));
bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(bodyLength)));
bytes.AddRange(headerBytes);
bytes.AddRange(bodyBytes);
if (headerLength + bodyLength > LargeMessageSizeThreshold)
{
logger.Info(ErrorCode.Messaging_LargeMsg_Outgoing, "Preparing to send large message Size={0} HeaderLength={1} BodyLength={2} #ArraySegments={3}. Msg={4}",
headerLength + bodyLength + LENGTH_HEADER_SIZE, headerLength, bodyLength, bytes.Count, this.ToString());
if (logger.IsVerbose3) logger.Verbose3("Sending large message {0}", this.ToLongString());
}
headerLengthOut = headerLength;
bodyLengthOut = bodyLength;
return bytes;
}
public void ReleaseBodyAndHeaderBuffers()
{
ReleaseHeadersOnly();
ReleaseBodyOnly();
}
public void ReleaseHeadersOnly()
{
if (headerBytes == null) return;
BufferPool.GlobalPool.Release(headerBytes);
headerBytes = null;
}
public void ReleaseBodyOnly()
{
if (bodyBytes == null) return;
BufferPool.GlobalPool.Release(bodyBytes);
bodyBytes = null;
}
#endregion
// For testing and logging/tracing
public string ToLongString()
{
var sb = new StringBuilder();
string debugContex = DebugContext;
if (!string.IsNullOrEmpty(debugContex))
{
// if DebugContex is present, print it first.
sb.Append(debugContex).Append(".");
}
AppendIfExists(HeadersContainer.Headers.CACHE_INVALIDATION_HEADER, sb, (m) => m.CacheInvalidationHeader);
AppendIfExists(HeadersContainer.Headers.CATEGORY, sb, (m) => m.Category);
AppendIfExists(HeadersContainer.Headers.DIRECTION, sb, (m) => m.Direction);
AppendIfExists(HeadersContainer.Headers.EXPIRATION, sb, (m) => m.Expiration);
AppendIfExists(HeadersContainer.Headers.FORWARD_COUNT, sb, (m) => m.ForwardCount);
AppendIfExists(HeadersContainer.Headers.GENERIC_GRAIN_TYPE, sb, (m) => m.GenericGrainType);
AppendIfExists(HeadersContainer.Headers.CORRELATION_ID, sb, (m) => m.Id);
AppendIfExists(HeadersContainer.Headers.ALWAYS_INTERLEAVE, sb, (m) => m.IsAlwaysInterleave);
AppendIfExists(HeadersContainer.Headers.IS_NEW_PLACEMENT, sb, (m) => m.IsNewPlacement);
AppendIfExists(HeadersContainer.Headers.READ_ONLY, sb, (m) => m.IsReadOnly);
AppendIfExists(HeadersContainer.Headers.IS_UNORDERED, sb, (m) => m.IsUnordered);
AppendIfExists(HeadersContainer.Headers.IS_RETURNED_FROM_REMOTE_CLUSTER, sb, (m) => m.IsReturnedFromRemoteCluster);
AppendIfExists(HeadersContainer.Headers.NEW_GRAIN_TYPE, sb, (m) => m.NewGrainType);
AppendIfExists(HeadersContainer.Headers.REJECTION_INFO, sb, (m) => m.RejectionInfo);
AppendIfExists(HeadersContainer.Headers.REJECTION_TYPE, sb, (m) => m.RejectionType);
AppendIfExists(HeadersContainer.Headers.REQUEST_CONTEXT, sb, (m) => m.RequestContextData);
AppendIfExists(HeadersContainer.Headers.RESEND_COUNT, sb, (m) => m.ResendCount);
AppendIfExists(HeadersContainer.Headers.RESULT, sb, (m) => m.Result);
AppendIfExists(HeadersContainer.Headers.SENDING_ACTIVATION, sb, (m) => m.SendingActivation);
AppendIfExists(HeadersContainer.Headers.SENDING_GRAIN, sb, (m) => m.SendingGrain);
AppendIfExists(HeadersContainer.Headers.SENDING_SILO, sb, (m) => m.SendingSilo);
AppendIfExists(HeadersContainer.Headers.TARGET_ACTIVATION, sb, (m) => m.TargetActivation);
AppendIfExists(HeadersContainer.Headers.TARGET_GRAIN, sb, (m) => m.TargetGrain);
AppendIfExists(HeadersContainer.Headers.TARGET_OBSERVER, sb, (m) => m.TargetObserverId);
AppendIfExists(HeadersContainer.Headers.TARGET_SILO, sb, (m) => m.TargetSilo);
return sb.ToString();
}
private void AppendIfExists(HeadersContainer.Headers header, StringBuilder sb, Func<Message, object> valueProvider)
{
// used only under log3 level
if ((Headers.GetHeadersMask() & header) != HeadersContainer.Headers.NONE)
{
sb.AppendFormat("{0}={1};", header, valueProvider(this));
sb.AppendLine();
}
}
public override string ToString()
{
string response = String.Empty;
if (Direction == Directions.Response)
{
switch (Result)
{
case ResponseTypes.Error:
response = "Error ";
break;
case ResponseTypes.Rejection:
response = string.Format("{0} Rejection (info: {1}) ", RejectionType, RejectionInfo);
break;
default:
break;
}
}
return String.Format("{0}{1}{2}{3}{4} {5}->{6} #{7}{8}{9}: {10}",
IsReadOnly ? "ReadOnly " : "", //0
IsAlwaysInterleave ? "IsAlwaysInterleave " : "", //1
IsNewPlacement ? "NewPlacement " : "", // 2
response, //3
Direction, //4
String.Format("{0}{1}{2}", SendingSilo, SendingGrain, SendingActivation), //5
String.Format("{0}{1}{2}{3}", TargetSilo, TargetGrain, TargetActivation, TargetObserverId), //6
Id, //7
ResendCount > 0 ? "[ResendCount=" + ResendCount + "]" : "", //8
ForwardCount > 0 ? "[ForwardCount=" + ForwardCount + "]" : "", //9
DebugContext); //10
}
internal void SetTargetPlacement(PlacementResult value)
{
TargetActivation = value.Activation;
TargetSilo = value.Silo;
if (value.IsNewPlacement)
IsNewPlacement = true;
if (!String.IsNullOrEmpty(value.GrainType))
NewGrainType = value.GrainType;
}
public string GetTargetHistory()
{
var history = new StringBuilder();
history.Append("<");
if (TargetSilo != null)
{
history.Append(TargetSilo).Append(":");
}
if (TargetGrain != null)
{
history.Append(TargetGrain).Append(":");
}
if (TargetActivation != null)
{
history.Append(TargetActivation);
}
history.Append(">");
if (!string.IsNullOrEmpty(TargetHistory))
{
history.Append(" ").Append(TargetHistory);
}
return history.ToString();
}
public bool IsSameDestination(IOutgoingMessage other)
{
var msg = (Message)other;
return msg != null && Object.Equals(TargetSilo, msg.TargetSilo);
}
// For statistical measuring of time spent in queues.
private ITimeInterval timeInterval;
public void Start()
{
timeInterval = TimeIntervalFactory.CreateTimeInterval(true);
timeInterval.Start();
}
public void Stop()
{
timeInterval.Stop();
}
public void Restart()
{
timeInterval.Restart();
}
public TimeSpan Elapsed
{
get { return timeInterval.Elapsed; }
}
internal void DropExpiredMessage(MessagingStatisticsGroup.Phase phase)
{
MessagingStatisticsGroup.OnMessageExpired(phase);
if (logger.IsVerbose2) logger.Verbose2("Dropping an expired message: {0}", this);
ReleaseBodyAndHeaderBuffers();
}
private static int BufferLength(List<ArraySegment<byte>> buffer)
{
var result = 0;
for (var i = 0; i < buffer.Count; i++)
{
result += buffer[i].Count;
}
return result;
}
[Serializable]
public class HeadersContainer
{
[Flags]
public enum Headers
{
NONE = 0,
ALWAYS_INTERLEAVE = 1 << 0,
CACHE_INVALIDATION_HEADER = 1 << 1,
CATEGORY = 1 << 2,
CORRELATION_ID = 1 << 3,
DEBUG_CONTEXT = 1 << 4,
DIRECTION = 1 << 5,
EXPIRATION = 1 << 6,
FORWARD_COUNT = 1 << 7,
NEW_GRAIN_TYPE = 1 << 8,
GENERIC_GRAIN_TYPE = 1 << 9,
RESULT = 1 << 10,
REJECTION_INFO = 1 << 11,
REJECTION_TYPE = 1 << 12,
READ_ONLY = 1 << 13,
RESEND_COUNT = 1 << 14,
SENDING_ACTIVATION = 1 << 15,
SENDING_GRAIN = 1 <<16,
SENDING_SILO = 1 << 17,
IS_NEW_PLACEMENT = 1 << 18,
TARGET_ACTIVATION = 1 << 19,
TARGET_GRAIN = 1 << 20,
TARGET_SILO = 1 << 21,
TARGET_OBSERVER = 1 << 22,
IS_UNORDERED = 1 << 23,
REQUEST_CONTEXT = 1 << 24,
IS_RETURNED_FROM_REMOTE_CLUSTER = 1 << 25,
// Do not add over int.MaxValue of these.
}
private Categories _category;
private Directions? _direction;
private bool _isReadOnly;
private bool _isAlwaysInterleave;
private bool _isUnordered;
private bool _isReturnedFromRemoteCluster;
private CorrelationId _id;
private int _resendCount;
private int _forwardCount;
private SiloAddress _targetSilo;
private GrainId _targetGrain;
private ActivationId _targetActivation;
private GuidId _targetObserverId;
private SiloAddress _sendingSilo;
private GrainId _sendingGrain;
private ActivationId _sendingActivation;
private bool _isNewPlacement;
private ResponseTypes _result;
private DateTime? _expiration;
private string _debugContext;
private List<ActivationAddress> _cacheInvalidationHeader;
private string _newGrainType;
private string _genericGrainType;
private RejectionTypes _rejectionType;
private string _rejectionInfo;
private Dictionary<string, object> _requestContextData;
public Categories Category
{
get { return _category; }
set
{
_category = value;
}
}
public Directions? Direction
{
get { return _direction; }
set
{
_direction = value;
}
}
public bool IsReadOnly
{
get { return _isReadOnly; }
set
{
_isReadOnly = value;
}
}
public bool IsAlwaysInterleave
{
get { return _isAlwaysInterleave; }
set
{
_isAlwaysInterleave = value;
}
}
public bool IsUnordered
{
get { return _isUnordered; }
set
{
_isUnordered = value;
}
}
public bool IsReturnedFromRemoteCluster
{
get { return _isReturnedFromRemoteCluster; }
set
{
_isReturnedFromRemoteCluster = value;
}
}
public CorrelationId Id
{
get { return _id; }
set
{
_id = value;
}
}
public int ResendCount
{
get { return _resendCount; }
set
{
_resendCount = value;
}
}
public int ForwardCount
{
get { return _forwardCount; }
set
{
_forwardCount = value;
}
}
public SiloAddress TargetSilo
{
get { return _targetSilo; }
set
{
_targetSilo = value;
}
}
public GrainId TargetGrain
{
get { return _targetGrain; }
set
{
_targetGrain = value;
}
}
public ActivationId TargetActivation
{
get { return _targetActivation; }
set
{
_targetActivation = value;
}
}
public GuidId TargetObserverId
{
get { return _targetObserverId; }
set
{
_targetObserverId = value;
}
}
public SiloAddress SendingSilo
{
get { return _sendingSilo; }
set
{
_sendingSilo = value;
}
}
public GrainId SendingGrain
{
get { return _sendingGrain; }
set
{
_sendingGrain = value;
}
}
public ActivationId SendingActivation
{
get { return _sendingActivation; }
set
{
_sendingActivation = value;
}
}
public bool IsNewPlacement
{
get { return _isNewPlacement; }
set
{
_isNewPlacement = value;
}
}
public ResponseTypes Result
{
get { return _result; }
set
{
_result = value;
}
}
public DateTime? Expiration
{
get { return _expiration; }
set
{
_expiration = value;
}
}
public string DebugContext
{
get { return _debugContext; }
set
{
_debugContext = value;
}
}
public List<ActivationAddress> CacheInvalidationHeader
{
get { return _cacheInvalidationHeader; }
set
{
_cacheInvalidationHeader = value;
}
}
/// <summary>
/// Set by sender's placement logic when NewPlacementRequested is true
/// so that receiver knows desired grain type
/// </summary>
public string NewGrainType
{
get { return _newGrainType; }
set
{
_newGrainType = value;
}
}
/// <summary>
/// Set by caller's grain reference
/// </summary>
public string GenericGrainType
{
get { return _genericGrainType; }
set
{
_genericGrainType = value;
}
}
public RejectionTypes RejectionType
{
get { return _rejectionType; }
set
{
_rejectionType = value;
}
}
public string RejectionInfo
{
get { return _rejectionInfo; }
set
{
_rejectionInfo = value;
}
}
public Dictionary<string, object> RequestContextData
{
get { return _requestContextData; }
set
{
_requestContextData = value;
}
}
internal Headers GetHeadersMask()
{
Headers headers = Headers.NONE;
if(Category != default(Categories))
headers = headers | Headers.CATEGORY;
headers = _direction == null ? headers & ~Headers.DIRECTION : headers | Headers.DIRECTION;
if (IsReadOnly)
headers = headers | Headers.READ_ONLY;
if (IsAlwaysInterleave)
headers = headers | Headers.ALWAYS_INTERLEAVE;
if(IsUnordered)
headers = headers | Headers.IS_UNORDERED;
headers = _id == null ? headers & ~Headers.CORRELATION_ID : headers | Headers.CORRELATION_ID;
if (_resendCount != default(int))
headers = headers | Headers.RESEND_COUNT;
if(_forwardCount != default (int))
headers = headers | Headers.FORWARD_COUNT;
headers = _targetSilo == null ? headers & ~Headers.TARGET_SILO : headers | Headers.TARGET_SILO;
headers = _targetGrain == null ? headers & ~Headers.TARGET_GRAIN : headers | Headers.TARGET_GRAIN;
headers = _targetActivation == null ? headers & ~Headers.TARGET_ACTIVATION : headers | Headers.TARGET_ACTIVATION;
headers = _targetObserverId == null ? headers & ~Headers.TARGET_OBSERVER : headers | Headers.TARGET_OBSERVER;
headers = _sendingSilo == null ? headers & ~Headers.SENDING_SILO : headers | Headers.SENDING_SILO;
headers = _sendingGrain == null ? headers & ~Headers.SENDING_GRAIN : headers | Headers.SENDING_GRAIN;
headers = _sendingActivation == null ? headers & ~Headers.SENDING_ACTIVATION : headers | Headers.SENDING_ACTIVATION;
headers = _isNewPlacement == default(bool) ? headers & ~Headers.IS_NEW_PLACEMENT : headers | Headers.IS_NEW_PLACEMENT;
headers = _result == default(ResponseTypes)? headers & ~Headers.RESULT : headers | Headers.RESULT;
headers = _expiration == null ? headers & ~Headers.EXPIRATION : headers | Headers.EXPIRATION;
headers = string.IsNullOrEmpty(_debugContext) ? headers & ~Headers.DEBUG_CONTEXT : headers | Headers.DEBUG_CONTEXT;
headers = _cacheInvalidationHeader == null || _cacheInvalidationHeader.Count == 0 ? headers & ~Headers.CACHE_INVALIDATION_HEADER : headers | Headers.CACHE_INVALIDATION_HEADER;
headers = string.IsNullOrEmpty(_newGrainType) ? headers & ~Headers.NEW_GRAIN_TYPE : headers | Headers.NEW_GRAIN_TYPE;
headers = string.IsNullOrEmpty(GenericGrainType) ? headers & ~Headers.GENERIC_GRAIN_TYPE : headers | Headers.GENERIC_GRAIN_TYPE;
headers = _rejectionType == default(RejectionTypes) ? headers & ~Headers.REJECTION_TYPE : headers | Headers.REJECTION_TYPE;
headers = string.IsNullOrEmpty(_rejectionInfo) ? headers & ~Headers.REJECTION_INFO : headers | Headers.REJECTION_INFO;
headers = _requestContextData == null || _requestContextData.Count == 0 ? headers & ~Headers.REQUEST_CONTEXT : headers | Headers.REQUEST_CONTEXT;
return headers;
}
static HeadersContainer()
{
Register();
}
[CopierMethod]
public static object DeepCopier(object original, ICopyContext context)
{
return original;
}
[SerializerMethod]
public static void Serializer(object untypedInput, ISerializationContext context, Type expected)
{
HeadersContainer input = (HeadersContainer)untypedInput;
var headers = input.GetHeadersMask();
var writer = context.StreamWriter;
writer.Write((int)headers);
if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE)
{
var count = input.CacheInvalidationHeader.Count;
writer.Write(input.CacheInvalidationHeader.Count);
for (int i = 0; i < count; i++)
{
WriteObj(context, typeof(ActivationAddress), input.CacheInvalidationHeader[i]);
}
}
if ((headers & Headers.CATEGORY) != Headers.NONE)
{
writer.Write((byte)input.Category);
}
if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE)
writer.Write(input.DebugContext);
if ((headers & Headers.DIRECTION) != Headers.NONE)
writer.Write((byte)input.Direction.Value);
if ((headers & Headers.EXPIRATION) != Headers.NONE)
writer.Write(input.Expiration.Value);
if ((headers & Headers.FORWARD_COUNT) != Headers.NONE)
writer.Write(input.ForwardCount);
if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE)
writer.Write(input.GenericGrainType);
if ((headers & Headers.CORRELATION_ID) != Headers.NONE)
writer.Write(input.Id);
if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE)
writer.Write(input.IsAlwaysInterleave);
if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE)
writer.Write(input.IsNewPlacement);
if ((headers & Headers.READ_ONLY) != Headers.NONE)
writer.Write(input.IsReadOnly);
if ((headers & Headers.IS_UNORDERED) != Headers.NONE)
writer.Write(input.IsUnordered);
if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE)
writer.Write(input.NewGrainType);
if ((headers & Headers.REJECTION_INFO) != Headers.NONE)
writer.Write(input.RejectionInfo);
if ((headers & Headers.REJECTION_TYPE) != Headers.NONE)
writer.Write((byte)input.RejectionType);
if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE)
{
var requestData = input.RequestContextData;
var count = requestData.Count;
writer.Write(count);
foreach (var d in requestData)
{
writer.Write(d.Key);
SerializationManager.SerializeInner(d.Value, context, typeof(object));
}
}
if ((headers & Headers.RESEND_COUNT) != Headers.NONE)
writer.Write(input.ResendCount);
if ((headers & Headers.RESULT) != Headers.NONE)
writer.Write((byte)input.Result);
if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE)
{
writer.Write(input.SendingActivation);
}
if ((headers & Headers.SENDING_GRAIN) != Headers.NONE)
{
writer.Write(input.SendingGrain);
}
if ((headers & Headers.SENDING_SILO) != Headers.NONE)
{
writer.Write(input.SendingSilo);
}
if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE)
{
writer.Write(input.TargetActivation);
}
if ((headers & Headers.TARGET_GRAIN) != Headers.NONE)
{
writer.Write(input.TargetGrain);
}
if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE)
{
WriteObj(context, typeof(GuidId), input.TargetObserverId);
}
if ((headers & Headers.TARGET_SILO) != Headers.NONE)
{
writer.Write(input.TargetSilo);
}
}
[DeserializerMethod]
public static object Deserializer(Type expected, IDeserializationContext context)
{
var result = new HeadersContainer();
var reader = context.StreamReader;
context.RecordObject(result);
var headers = (Headers)reader.ReadInt();
if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE)
{
var n = reader.ReadInt();
if (n > 0)
{
var list = result.CacheInvalidationHeader = new List<ActivationAddress>(n);
for (int i = 0; i < n; i++)
{
list.Add((ActivationAddress)ReadObj(typeof(ActivationAddress), context));
}
}
}
if ((headers & Headers.CATEGORY) != Headers.NONE)
result.Category = (Categories)reader.ReadByte();
if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE)
result.DebugContext = reader.ReadString();
if ((headers & Headers.DIRECTION) != Headers.NONE)
result.Direction = (Message.Directions)reader.ReadByte();
if ((headers & Headers.EXPIRATION) != Headers.NONE)
result.Expiration = reader.ReadDateTime();
if ((headers & Headers.FORWARD_COUNT) != Headers.NONE)
result.ForwardCount = reader.ReadInt();
if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE)
result.GenericGrainType = reader.ReadString();
if ((headers & Headers.CORRELATION_ID) != Headers.NONE)
result.Id = (Orleans.Runtime.CorrelationId)ReadObj(typeof(Orleans.Runtime.CorrelationId), context);
if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE)
result.IsAlwaysInterleave = ReadBool(reader);
if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE)
result.IsNewPlacement = ReadBool(reader);
if ((headers & Headers.READ_ONLY) != Headers.NONE)
result.IsReadOnly = ReadBool(reader);
if ((headers & Headers.IS_UNORDERED) != Headers.NONE)
result.IsUnordered = ReadBool(reader);
if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE)
result.NewGrainType = reader.ReadString();
if ((headers & Headers.REJECTION_INFO) != Headers.NONE)
result.RejectionInfo = reader.ReadString();
if ((headers & Headers.REJECTION_TYPE) != Headers.NONE)
result.RejectionType = (RejectionTypes)reader.ReadByte();
if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE)
{
var c = reader.ReadInt();
var requestData = new Dictionary<string, object>(c);
for (int i = 0; i < c; i++)
{
requestData[reader.ReadString()] = SerializationManager.DeserializeInner(null, context);
}
result.RequestContextData = requestData;
}
if ((headers & Headers.RESEND_COUNT) != Headers.NONE)
result.ResendCount = reader.ReadInt();
if ((headers & Headers.RESULT) != Headers.NONE)
result.Result = (Orleans.Runtime.Message.ResponseTypes)reader.ReadByte();
if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE)
result.SendingActivation = reader.ReadActivationId();
if ((headers & Headers.SENDING_GRAIN) != Headers.NONE)
result.SendingGrain = reader.ReadGrainId();
if ((headers & Headers.SENDING_SILO) != Headers.NONE)
result.SendingSilo = reader.ReadSiloAddress();
if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE)
result.TargetActivation = reader.ReadActivationId();
if ((headers & Headers.TARGET_GRAIN) != Headers.NONE)
result.TargetGrain = reader.ReadGrainId();
if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE)
result.TargetObserverId = (Orleans.Runtime.GuidId)ReadObj(typeof(Orleans.Runtime.GuidId), context);
if ((headers & Headers.TARGET_SILO) != Headers.NONE)
result.TargetSilo = reader.ReadSiloAddress();
return (HeadersContainer)result;
}
private static bool ReadBool(BinaryTokenStreamReader stream)
{
return stream.ReadByte() == (byte) SerializationTokenType.True;
}
private static void WriteObj(ISerializationContext context, Type type, object input)
{
var ser = SerializationManager.GetSerializer(type);
ser.Invoke(input, context, type);
}
private static object ReadObj(Type t, IDeserializationContext context)
{
var des = SerializationManager.GetDeserializer(t);
return des.Invoke(t, context);
}
public static void Register()
{
SerializationManager.Register(typeof(HeadersContainer), DeepCopier, Serializer, Deserializer);
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft 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.
// ----------------------------------------------------------------------------------
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
{
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
using Microsoft.WindowsAzure.Commands.Common;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Linq;
using System.Management.Automation;
using System.Threading.Tasks;
/// <summary>
/// A cmdlet that creates a new azure resource.
/// </summary>
[Cmdlet(VerbsCommon.Set, "AzureRmResource", SupportsShouldProcess = true, DefaultParameterSetName = ResourceManipulationCmdletBase.ResourceIdParameterSet), OutputType(typeof(PSObject))]
public sealed class SetAzureResourceCmdlet : ResourceManipulationCmdletBase
{
/// <summary>
/// Gets or sets the kind.
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource kind.")]
[ValidateNotNullOrEmpty]
public string Kind { get; set; }
/// <summary>
/// Gets or sets the property object.
/// </summary>
[Alias("PropertyObject")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents resource properties.")]
[ValidateNotNullOrEmpty]
public PSObject Properties { get; set; }
/// <summary>
/// Gets or sets the plan object.
/// </summary>
[Alias("PlanObject")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents resource plan properties.")]
[ValidateNotNullOrEmpty]
public Hashtable Plan { get; set; }
/// <summary>
/// Gets or sets the Sku object.
/// </summary>
[Alias("SkuObject")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents sku properties.")]
[ValidateNotNullOrEmpty]
public Hashtable Sku { get; set; }
/// <summary>
/// Gets or sets the tags.
/// </summary>
[Alias("Tags")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents resource tags.")]
public Hashtable Tag { get; set; }
/// <summary>
/// Gets or sets a value that indicates if an HTTP PATCH request needs to be made instead of PUT.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "When set indicates if an HTTP PATCH should be used to update the object instead of PUT.")]
public SwitchParameter UsePatchSemantics { get; set; }
/// <summary>
/// Executes the cmdlet.
/// </summary>
protected override void OnProcessRecord()
{
base.OnProcessRecord();
if (!string.IsNullOrEmpty(this.ODataQuery))
{
this.WriteWarning("The ODataQuery parameter is being deprecated in Set-AzureRmResource cmdlet and will be removed in a future release.");
}
var resourceId = this.GetResourceId();
this.ConfirmAction(
this.Force,
"Are you sure you want to update the following resource: " + resourceId,
"Updating the resource...",
resourceId,
() =>
{
var apiVersion = this.DetermineApiVersion(resourceId: resourceId).Result;
var resourceBody = this.GetResourceBody();
var operationResult = this.ShouldUsePatchSemantics()
? this.GetResourcesClient()
.PatchResource(
resourceId: resourceId,
apiVersion: apiVersion,
resource: resourceBody,
cancellationToken: this.CancellationToken.Value,
odataQuery: this.ODataQuery)
.Result
: this.GetResourcesClient()
.PutResource(
resourceId: resourceId,
apiVersion: apiVersion,
resource: resourceBody,
cancellationToken: this.CancellationToken.Value,
odataQuery: this.ODataQuery)
.Result;
var managementUri = this.GetResourcesClient()
.GetResourceManagementRequestUri(
resourceId: resourceId,
apiVersion: apiVersion,
odataQuery: this.ODataQuery);
var activity = string.Format("{0} {1}", this.ShouldUsePatchSemantics() ? "PATCH" : "PUT", managementUri.PathAndQuery);
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true)
.WaitOnOperation(operationResult: operationResult);
this.TryConvertToResourceAndWriteObject(result);
});
}
/// <summary>
/// Gets the resource body.
/// </summary>
private JToken GetResourceBody()
{
if (this.ShouldUsePatchSemantics())
{
var resourceBody = this.GetPatchResourceBody();
return resourceBody == null ? null : resourceBody.ToJToken();
}
else
{
var getResult = this.GetResource().Result;
if (getResult.CanConvertTo<Resource<JToken>>())
{
var resource = getResult.ToResource();
return new Resource<JToken>()
{
Kind = this.Kind ?? resource.Kind,
Plan = this.Plan.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourcePlan>() ?? resource.Plan,
Sku = this.Sku.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourceSku>() ?? resource.Sku,
Tags = TagsHelper.GetTagsDictionary(this.Tag) ?? resource.Tags,
Location = resource.Location,
Properties = this.Properties == null ? resource.Properties : this.Properties.ToResourcePropertiesBody(),
}.ToJToken();
}
else
{
return this.Properties.ToJToken();
}
}
}
/// <summary>
/// Gets the resource body for PATCH calls
/// </summary>
private Resource<JToken> GetPatchResourceBody()
{
Resource<JToken> resourceBody = null;
if (this.Properties != null)
{
resourceBody = new Resource<JToken>()
{
Properties = this.Properties.ToResourcePropertiesBody()
};
}
if (this.Plan != null)
{
if (resourceBody != null)
{
resourceBody.Plan = this.Plan.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourcePlan>();
}
else
{
resourceBody = new Resource<JToken>()
{
Plan = this.Plan.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourcePlan>()
};
}
}
if (this.Kind != null)
{
if (resourceBody != null)
{
resourceBody.Kind = this.Kind;
}
else
{
resourceBody = new Resource<JToken>()
{
Kind = this.Kind
};
}
}
if (this.Sku != null)
{
if (resourceBody != null)
{
resourceBody.Sku = this.Sku.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourceSku>();
}
else
{
resourceBody = new Resource<JToken>()
{
Sku = this.Sku.ToDictionary(addValueLayer: false).ToJson().FromJson<ResourceSku>()
};
}
}
if (this.Tag != null)
{
if (resourceBody != null)
{
resourceBody.Tags = TagsHelper.GetTagsDictionary(this.Tag);
}
else
{
resourceBody = new Resource<JToken>()
{
Tags = TagsHelper.GetTagsDictionary(this.Tag)
};
}
}
return resourceBody;
}
/// <summary>
/// Determines if the cmdlet should use <c>PATCH</c> semantics.
/// </summary>
private bool ShouldUsePatchSemantics()
{
return this.UsePatchSemantics || ((this.Tag != null || this.Sku != null) && this.Plan == null && this.Properties == null && this.Kind == null);
}
/// <summary>
/// Gets a resource.
/// </summary>
private async Task<JObject> GetResource()
{
var resourceId = this.GetResourceId();
var apiVersion = await this
.DetermineApiVersion(resourceId: resourceId)
.ConfigureAwait(continueOnCapturedContext: false);
return await this
.GetResourcesClient()
.GetResource<JObject>(
resourceId: resourceId,
apiVersion: apiVersion,
cancellationToken: this.CancellationToken.Value)
.ConfigureAwait(continueOnCapturedContext: false);
}
}
}
| |
#region BSD License
/*
Copyright (c) 2004-2005 Matthew Holmes ([email protected]), Dan Moorehead ([email protected])
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Nodes
{
/// <summary>
/// A set of values that the Project's type can be
/// </summary>
public enum ProjectType
{
/// <summary>
/// The project is a console executable
/// </summary>
Exe,
/// <summary>
/// The project is a windows executable
/// </summary>
WinExe,
/// <summary>
/// The project is a library
/// </summary>
Library,
/// <summary>
/// The project is a website
/// </summary>
Web,
}
/// <summary>
///
/// </summary>
public enum ClrRuntime
{
/// <summary>
///
/// </summary>
Microsoft,
/// <summary>
///
/// </summary>
Mono
}
/// <summary>
/// The version of the .NET framework to use (Required for VS2008)
/// <remarks>We don't need .NET 1.1 in here, it'll default when using vs2003.</remarks>
/// </summary>
public enum FrameworkVersion
{
/// <summary>
/// .NET 2.0
/// </summary>
v2_0,
/// <summary>
/// .NET 3.0
/// </summary>
v3_0,
/// <summary>
/// .NET 3.5
/// </summary>
v3_5,
/// <summary>
/// .NET 4.0
/// </summary>
v4_0,
/// <summary>
/// .NET 4.5
/// </summary>
v4_5,
/// <summary>
/// .NET 4.6
/// </summary>
v4_6,
/// <summary>
/// .NET 4.6.1
/// </summary>
v4_6_1,
}
/// <summary>
/// The Node object representing /Prebuild/Solution/Project elements
/// </summary>
[DataNode("Project")]
public class ProjectNode : DataNode, IComparable
{
#region Fields
private string m_Name = "unknown";
private string m_Path = "";
private string m_FullPath = "";
private string m_AssemblyName;
private string m_AppIcon = "";
private string m_ConfigFile = "";
private string m_DesignerFolder = "";
private string m_Language = "C#";
private ProjectType m_Type = ProjectType.Exe;
private ClrRuntime m_Runtime = ClrRuntime.Microsoft;
private FrameworkVersion m_Framework = FrameworkVersion.v2_0;
private string m_StartupObject = "";
private string m_RootNamespace;
private string m_FilterGroups = "";
private string m_Version = "";
private Guid m_Guid;
private string m_DebugStartParameters;
private readonly Dictionary<string, ConfigurationNode> m_Configurations = new Dictionary<string, ConfigurationNode>();
private readonly List<ReferencePathNode> m_ReferencePaths = new List<ReferencePathNode>();
private readonly List<ReferenceNode> m_References = new List<ReferenceNode>();
private readonly List<AuthorNode> m_Authors = new List<AuthorNode>();
private FilesNode m_Files;
#endregion
#region Properties
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
return m_Name;
}
}
/// <summary>
/// The version of the .NET Framework to compile under
/// </summary>
public FrameworkVersion FrameworkVersion
{
get
{
return m_Framework;
}
}
/// <summary>
/// Gets the path.
/// </summary>
/// <value>The path.</value>
public string Path
{
get
{
return m_Path;
}
}
/// <summary>
/// Gets the filter groups.
/// </summary>
/// <value>The filter groups.</value>
public string FilterGroups
{
get
{
return m_FilterGroups;
}
}
/// <summary>
/// Gets the project's version
/// </summary>
/// <value>The project's version.</value>
public string Version
{
get
{
return m_Version;
}
}
/// <summary>
/// Gets the full path.
/// </summary>
/// <value>The full path.</value>
public string FullPath
{
get
{
return m_FullPath;
}
}
/// <summary>
/// Gets the name of the assembly.
/// </summary>
/// <value>The name of the assembly.</value>
public string AssemblyName
{
get
{
return m_AssemblyName;
}
}
/// <summary>
/// Gets the app icon.
/// </summary>
/// <value>The app icon.</value>
public string AppIcon
{
get
{
return m_AppIcon;
}
}
/// <summary>
/// Gets the app icon.
/// </summary>
/// <value>The app icon.</value>
public string ConfigFile
{
get
{
return m_ConfigFile;
}
}
/// <summary>
///
/// </summary>
public string DesignerFolder
{
get
{
return m_DesignerFolder;
}
}
/// <summary>
/// Gets the language.
/// </summary>
/// <value>The language.</value>
public string Language
{
get
{
return m_Language;
}
}
/// <summary>
/// Gets the type.
/// </summary>
/// <value>The type.</value>
public ProjectType Type
{
get
{
return m_Type;
}
}
/// <summary>
/// Gets the runtime.
/// </summary>
/// <value>The runtime.</value>
public ClrRuntime Runtime
{
get
{
return m_Runtime;
}
}
private bool m_GenerateAssemblyInfoFile;
/// <summary>
///
/// </summary>
public bool GenerateAssemblyInfoFile
{
get
{
return m_GenerateAssemblyInfoFile;
}
set
{
m_GenerateAssemblyInfoFile = value;
}
}
/// <summary>
/// Gets the startup object.
/// </summary>
/// <value>The startup object.</value>
public string StartupObject
{
get
{
return m_StartupObject;
}
}
/// <summary>
/// Gets the root namespace.
/// </summary>
/// <value>The root namespace.</value>
public string RootNamespace
{
get
{
return m_RootNamespace;
}
}
/// <summary>
/// Gets the configurations.
/// </summary>
/// <value>The configurations.</value>
public List<ConfigurationNode> Configurations
{
get
{
List<ConfigurationNode> tmp = new List<ConfigurationNode>(ConfigurationsTable.Values);
tmp.Sort();
return tmp;
}
}
/// <summary>
/// Gets the configurations table.
/// </summary>
/// <value>The configurations table.</value>
public Dictionary<string, ConfigurationNode> ConfigurationsTable
{
get
{
return m_Configurations;
}
}
/// <summary>
/// Gets the reference paths.
/// </summary>
/// <value>The reference paths.</value>
public List<ReferencePathNode> ReferencePaths
{
get
{
List<ReferencePathNode> tmp = new List<ReferencePathNode>(m_ReferencePaths);
tmp.Sort();
return tmp;
}
}
/// <summary>
/// Gets the references.
/// </summary>
/// <value>The references.</value>
public List<ReferenceNode> References
{
get
{
List<ReferenceNode> tmp = new List<ReferenceNode>(m_References);
tmp.Sort();
return tmp;
}
}
/// <summary>
/// Gets the Authors list.
/// </summary>
/// <value>The list of the project's authors.</value>
public List<AuthorNode> Authors
{
get
{
return m_Authors;
}
}
/// <summary>
/// Gets the files.
/// </summary>
/// <value>The files.</value>
public FilesNode Files
{
get
{
return m_Files;
}
}
/// <summary>
/// Gets or sets the parent.
/// </summary>
/// <value>The parent.</value>
public override IDataNode Parent
{
get
{
return base.Parent;
}
set
{
base.Parent = value;
if(base.Parent is SolutionNode && m_Configurations.Count < 1)
{
SolutionNode parent = (SolutionNode)base.Parent;
foreach(ConfigurationNode conf in parent.Configurations)
{
m_Configurations[conf.NameAndPlatform] = (ConfigurationNode) conf.Clone();
}
}
}
}
/// <summary>
/// Gets the GUID.
/// </summary>
/// <value>The GUID.</value>
public Guid Guid
{
get
{
return m_Guid;
}
}
public string DebugStartParameters
{
get
{
return m_DebugStartParameters;
}
}
#endregion
#region Private Methods
private void HandleConfiguration(ConfigurationNode conf)
{
if(String.Compare(conf.Name, "all", true) == 0) //apply changes to all, this may not always be applied first,
//so it *may* override changes to the same properties for configurations defines at the project level
{
foreach(ConfigurationNode confNode in m_Configurations.Values)
{
conf.CopyTo(confNode);//update the config templates defines at the project level with the overrides
}
}
if(m_Configurations.ContainsKey(conf.NameAndPlatform))
{
ConfigurationNode parentConf = m_Configurations[conf.NameAndPlatform];
conf.CopyTo(parentConf);//update the config templates defines at the project level with the overrides
}
else
{
m_Configurations[conf.NameAndPlatform] = conf;
}
}
#endregion
#region Public Methods
/// <summary>
/// Parses the specified node.
/// </summary>
/// <param name="node">The node.</param>
public override void Parse(XmlNode node)
{
m_Name = Helper.AttributeValue(node, "name", m_Name);
m_Path = Helper.AttributeValue(node, "path", m_Path);
m_FilterGroups = Helper.AttributeValue(node, "filterGroups", m_FilterGroups);
m_Version = Helper.AttributeValue(node, "version", m_Version);
m_AppIcon = Helper.AttributeValue(node, "icon", m_AppIcon);
m_ConfigFile = Helper.AttributeValue(node, "configFile", m_ConfigFile);
m_DesignerFolder = Helper.AttributeValue(node, "designerFolder", m_DesignerFolder);
m_AssemblyName = Helper.AttributeValue(node, "assemblyName", m_AssemblyName);
m_Language = Helper.AttributeValue(node, "language", m_Language);
m_Type = (ProjectType)Helper.EnumAttributeValue(node, "type", typeof(ProjectType), m_Type);
m_Runtime = (ClrRuntime)Helper.EnumAttributeValue(node, "runtime", typeof(ClrRuntime), m_Runtime);
m_Framework = (FrameworkVersion)Helper.EnumAttributeValue(node, "frameworkVersion", typeof(FrameworkVersion), m_Framework);
m_StartupObject = Helper.AttributeValue(node, "startupObject", m_StartupObject);
m_RootNamespace = Helper.AttributeValue(node, "rootNamespace", m_RootNamespace);
int hash = m_Name.GetHashCode();
Guid guidByHash = new Guid(hash, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
string guid = Helper.AttributeValue(node, "guid", guidByHash.ToString());
m_Guid = new Guid(guid);
m_GenerateAssemblyInfoFile = Helper.ParseBoolean(node, "generateAssemblyInfoFile", false);
m_DebugStartParameters = Helper.AttributeValue(node, "debugStartParameters", string.Empty);
if(string.IsNullOrEmpty(m_AssemblyName))
{
m_AssemblyName = m_Name;
}
if(string.IsNullOrEmpty(m_RootNamespace))
{
m_RootNamespace = m_Name;
}
m_FullPath = m_Path;
try
{
m_FullPath = Helper.ResolvePath(m_FullPath);
}
catch
{
throw new WarningException("Could not resolve Solution path: {0}", m_Path);
}
Kernel.Instance.CurrentWorkingDirectory.Push();
try
{
Helper.SetCurrentDir(m_FullPath);
if( node == null )
{
throw new ArgumentNullException("node");
}
foreach(XmlNode child in node.ChildNodes)
{
IDataNode dataNode = Kernel.Instance.ParseNode(child, this);
if(dataNode is ConfigurationNode)
{
HandleConfiguration((ConfigurationNode)dataNode);
}
else if(dataNode is ReferencePathNode)
{
m_ReferencePaths.Add((ReferencePathNode)dataNode);
}
else if(dataNode is ReferenceNode)
{
m_References.Add((ReferenceNode)dataNode);
}
else if(dataNode is AuthorNode)
{
m_Authors.Add((AuthorNode)dataNode);
}
else if(dataNode is FilesNode)
{
m_Files = (FilesNode)dataNode;
}
}
}
finally
{
Kernel.Instance.CurrentWorkingDirectory.Pop();
}
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
ProjectNode that = (ProjectNode)obj;
return m_Name.CompareTo(that.m_Name);
}
#endregion
}
}
| |
namespace KabMan.Forms
{
partial class ChangePasswordForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ChangePasswordForm));
DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule1 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule();
DevExpress.XtraEditors.DXErrorProvider.CompareAgainstControlValidationRule compareAgainstControlValidationRule1 = new DevExpress.XtraEditors.DXErrorProvider.CompareAgainstControlValidationRule();
this.Password1Box = new DevExpress.XtraEditors.TextEdit();
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.cancelButton = new DevExpress.XtraEditors.SimpleButton();
this.saveButton = new DevExpress.XtraEditors.SimpleButton();
this.Password2Box = new DevExpress.XtraEditors.TextEdit();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem();
this.PasswordValidator = new DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider(this.components);
((System.ComponentModel.ISupportInitialize)(this.Password1Box.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.Password2Box.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PasswordValidator)).BeginInit();
this.SuspendLayout();
//
// Password1Box
//
resources.ApplyResources(this.Password1Box, "Password1Box");
this.Password1Box.Name = "Password1Box";
this.Password1Box.StyleController = this.layoutControl1;
conditionValidationRule1.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank;
resources.ApplyResources(conditionValidationRule1, "conditionValidationRule1");
conditionValidationRule1.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
this.PasswordValidator.SetValidationRule(this.Password1Box, conditionValidationRule1);
//
// layoutControl1
//
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.cancelButton);
this.layoutControl1.Controls.Add(this.saveButton);
this.layoutControl1.Controls.Add(this.Password2Box);
this.layoutControl1.Controls.Add(this.Password1Box);
resources.ApplyResources(this.layoutControl1, "layoutControl1");
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
//
// cancelButton
//
this.cancelButton.Appearance.BackColor = System.Drawing.SystemColors.ButtonFace;
this.cancelButton.Appearance.BackColor2 = System.Drawing.SystemColors.ButtonHighlight;
this.cancelButton.Appearance.BorderColor = System.Drawing.Color.DimGray;
this.cancelButton.Appearance.Options.UseBackColor = true;
this.cancelButton.Appearance.Options.UseBorderColor = true;
resources.ApplyResources(this.cancelButton, "cancelButton");
this.cancelButton.Name = "cancelButton";
this.cancelButton.StyleController = this.layoutControl1;
this.cancelButton.Click += new System.EventHandler(this.CancelButton_Click);
//
// saveButton
//
this.saveButton.Appearance.BackColor = System.Drawing.SystemColors.ButtonFace;
this.saveButton.Appearance.BackColor2 = System.Drawing.SystemColors.ButtonHighlight;
this.saveButton.Appearance.BorderColor = System.Drawing.Color.DimGray;
this.saveButton.Appearance.Options.UseBackColor = true;
this.saveButton.Appearance.Options.UseBorderColor = true;
this.saveButton.Appearance.Options.UseForeColor = true;
resources.ApplyResources(this.saveButton, "saveButton");
this.saveButton.Name = "saveButton";
this.saveButton.StyleController = this.layoutControl1;
this.saveButton.Click += new System.EventHandler(this.SaveButton_Click);
//
// Password2Box
//
resources.ApplyResources(this.Password2Box, "Password2Box");
this.Password2Box.Name = "Password2Box";
this.Password2Box.StyleController = this.layoutControl1;
compareAgainstControlValidationRule1.CaseSensitive = true;
compareAgainstControlValidationRule1.CompareControlOperator = DevExpress.XtraEditors.DXErrorProvider.CompareControlOperator.Equals;
compareAgainstControlValidationRule1.Control = this.Password1Box;
resources.ApplyResources(compareAgainstControlValidationRule1, "compareAgainstControlValidationRule1");
compareAgainstControlValidationRule1.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
this.PasswordValidator.SetValidationRule(this.Password2Box, compareAgainstControlValidationRule1);
//
// layoutControlGroup1
//
resources.ApplyResources(this.layoutControlGroup1, "layoutControlGroup1");
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1,
this.layoutControlItem2,
this.emptySpaceItem1,
this.layoutControlItem3,
this.layoutControlItem4});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "layoutControlGroup1";
this.layoutControlGroup1.Size = new System.Drawing.Size(261, 97);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.Password1Box;
resources.ApplyResources(this.layoutControlItem1, "layoutControlItem1");
this.layoutControlItem1.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(259, 31);
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(84, 20);
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.Password2Box;
resources.ApplyResources(this.layoutControlItem2, "layoutControlItem2");
this.layoutControlItem2.Location = new System.Drawing.Point(0, 31);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(259, 31);
this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem2.TextSize = new System.Drawing.Size(84, 20);
//
// emptySpaceItem1
//
resources.ApplyResources(this.emptySpaceItem1, "emptySpaceItem1");
this.emptySpaceItem1.Location = new System.Drawing.Point(0, 62);
this.emptySpaceItem1.Name = "emptySpaceItem1";
this.emptySpaceItem1.Size = new System.Drawing.Size(105, 33);
this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
//
// layoutControlItem3
//
this.layoutControlItem3.Control = this.saveButton;
resources.ApplyResources(this.layoutControlItem3, "layoutControlItem3");
this.layoutControlItem3.Location = new System.Drawing.Point(105, 62);
this.layoutControlItem3.Name = "layoutControlItem3";
this.layoutControlItem3.Size = new System.Drawing.Size(77, 33);
this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem3.TextToControlDistance = 0;
this.layoutControlItem3.TextVisible = false;
//
// layoutControlItem4
//
this.layoutControlItem4.Control = this.cancelButton;
resources.ApplyResources(this.layoutControlItem4, "layoutControlItem4");
this.layoutControlItem4.Location = new System.Drawing.Point(182, 62);
this.layoutControlItem4.Name = "layoutControlItem4";
this.layoutControlItem4.Size = new System.Drawing.Size(77, 33);
this.layoutControlItem4.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem4.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem4.TextToControlDistance = 0;
this.layoutControlItem4.TextVisible = false;
//
// ChangePasswordForm
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.layoutControl1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ChangePasswordForm";
this.ShowInTaskbar = false;
this.Load += new System.EventHandler(this.ChangePasswordForm_Load);
((System.ComponentModel.ISupportInitialize)(this.Password1Box.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.Password2Box.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PasswordValidator)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraEditors.SimpleButton cancelButton;
private DevExpress.XtraEditors.SimpleButton saveButton;
private DevExpress.XtraEditors.TextEdit Password2Box;
private DevExpress.XtraEditors.TextEdit Password1Box;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4;
private DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider PasswordValidator;
}
}
| |
/*
* NPlot - A charting library for .NET
*
* LinearAxis.cs
* Copyright (C) 2003-2006 Matt Howlett and others.
* 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.
* 3. Neither the name of NPlot nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
namespace NPlot
{
/// <summary>
/// Provides functionality for drawing axes with a linear numeric scale.
/// </summary>
public class LinearAxis : Axis, ICloneable
{
/// <summary>
/// Deep copy of LinearAxis.
/// </summary>
/// <returns>A copy of the LinearAxis Class</returns>
public override object Clone()
{
LinearAxis a = new LinearAxis();
// ensure that this isn't being called on a derived type. If it is, then oh no!
if (this.GetType() != a.GetType())
{
throw new NPlotException("Clone not defined in derived type. Help!");
}
this.DoClone(this, a);
return a;
}
/// <summary>
/// Helper method for Clone.
/// </summary>
protected void DoClone(LinearAxis b, LinearAxis a)
{
Axis.DoClone(b, a);
a.numberSmallTicks_ = b.numberSmallTicks_;
a.largeTickValue_ = b.largeTickValue_;
a.largeTickStep_ = b.largeTickStep_;
a.offset_ = b.offset_;
a.scale_ = b.scale_;
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="a">The Axis to clone</param>
public LinearAxis(Axis a)
: base(a)
{
Init();
}
/// <summary>
/// Default constructor.
/// </summary>
public LinearAxis()
: base()
{
Init();
}
/// <summary>
/// Construct a linear axis with the provided world min and max values.
/// </summary>
/// <param name="worldMin">the world minimum value of the axis.</param>
/// <param name="worldMax">the world maximum value of the axis.</param>
public LinearAxis(double worldMin, double worldMax)
: base(worldMin, worldMax)
{
Init();
}
private void Init()
{
this.NumberFormat = "{0:g5}";
}
/// <summary>
/// Draws the large and small ticks [and tick labels] for this axis.
/// </summary>
/// <param name="g">The graphics surface on which to draw.</param>
/// <param name="physicalMin">The physical position corresponding to the world minimum of the axis.</param>
/// <param name="physicalMax">The physical position corresponding to the world maximum of the axis.</param>
/// <param name="boundingBox">out: smallest box that completely surrounds all ticks and associated labels for this axis.</param>
/// <param name="labelOffset">out: offset from the axis to draw the axis label.</param>
protected override void DrawTicks(
Graphics g,
Point physicalMin,
Point physicalMax,
out object labelOffset,
out object boundingBox)
{
Point tLabelOffset;
Rectangle tBoundingBox;
_ = this.getDefaultLabelOffset(physicalMin, physicalMax);
boundingBox = null;
this.WorldTickPositions(physicalMin, physicalMax, out List<double> largeTickPositions, out List<double> smallTickPositions);
labelOffset = new Point(0, 0);
boundingBox = null;
if (largeTickPositions.Count > 0)
{
for (int i = 0; i < largeTickPositions.Count; ++i)
{
double labelNumber = (double)largeTickPositions[i];
// TODO: Find out why zero is sometimes significantly not zero [seen as high as 10^-16].
if (Math.Abs(labelNumber) < 0.000000000000001)
{
labelNumber = 0.0;
}
StringBuilder label = new StringBuilder();
label.AppendFormat(this.NumberFormat, labelNumber);
this.DrawTick(g, (double)largeTickPositions[i] / this.scale_ - this.offset_,
this.LargeTickSize, label.ToString(),
new Point(0, 0), physicalMin, physicalMax,
out tLabelOffset, out tBoundingBox);
UpdateOffsetAndBounds(ref labelOffset, ref boundingBox,
tLabelOffset, tBoundingBox);
}
}
for (int i = 0; i < smallTickPositions.Count; ++i)
{
this.DrawTick(g, (double)smallTickPositions[i] / this.scale_ - this.offset_,
this.SmallTickSize, "",
new Point(0, 0), physicalMin, physicalMax,
out _, out _);
// assume bounding box and label offset unchanged by small tick bounds.
}
}
/// <summary>
/// Determines the positions, in world coordinates, of the small ticks
/// if they have not already been generated.
///
/// </summary>
/// <param name="physicalMin">The physical position corresponding to the world minimum of the axis.</param>
/// <param name="physicalMax">The physical position corresponding to the world maximum of the axis.</param>
/// <param name="largeTickPositions">The positions of the large ticks.</param>
/// <param name="smallTickPositions">If null, small tick positions are returned via this parameter. Otherwise this function does nothing.</param>
internal override void WorldTickPositions_SecondPass(
Point physicalMin,
Point physicalMax,
List<double> largeTickPositions,
ref List<double> smallTickPositions)
{
// return if already generated.
if (smallTickPositions != null)
return;
int physicalAxisLength = Utils.Distance(physicalMin, physicalMax);
double adjustedMax = this.AdjustedWorldValue(WorldMax);
double adjustedMin = this.AdjustedWorldValue(WorldMin);
smallTickPositions = new List<double>();
// TODO: Can optimize this now.
double bigTickSpacing = this.DetermineLargeTickStep(physicalAxisLength, out _);
int nSmall = this.DetermineNumberSmallTicks(bigTickSpacing);
double smallTickSpacing = bigTickSpacing / nSmall;
// if there is at least one big tick
if (largeTickPositions.Count > 0)
{
double pos1 = (double)largeTickPositions[0] - smallTickSpacing;
while (pos1 > adjustedMin)
{
smallTickPositions.Add(pos1);
pos1 -= smallTickSpacing;
}
}
for (int i = 0; i < largeTickPositions.Count; ++i)
{
for (int j = 1; j < nSmall; ++j)
{
double pos = (double)largeTickPositions[i] + j * smallTickSpacing;
if (pos <= adjustedMax)
{
smallTickPositions.Add(pos);
}
}
}
}
/// <summary>
/// Adjusts a real world value to one that has been modified to
/// reflect the Axis Scale and Offset properties.
/// </summary>
/// <param name="world">world value to adjust</param>
/// <returns>adjusted world value</returns>
public double AdjustedWorldValue(double world)
{
return world * this.scale_ + this.offset_;
}
/// <summary>
/// Determines the positions, in world coordinates, of the large ticks.
/// When the physical extent of the axis is small, some of the positions
/// that were generated in this pass may be converted to small tick
/// positions and returned as well.
///
/// If the LargeTickStep isn't set then this is calculated automatically and
/// depends on the physical extent of the axis.
/// </summary>
/// <param name="physicalMin">The physical position corresponding to the world minimum of the axis.</param>
/// <param name="physicalMax">The physical position corresponding to the world maximum of the axis.</param>
/// <param name="largeTickPositions">ArrayList containing the positions of the large ticks.</param>
/// <param name="smallTickPositions">ArrayList containing the positions of the small ticks if calculated, null otherwise.</param>
internal override void WorldTickPositions_FirstPass(
Point physicalMin,
Point physicalMax,
out List<double> largeTickPositions,
out List<double> smallTickPositions
)
{
// (1) error check
if (double.IsNaN(WorldMin) || double.IsNaN(WorldMax))
{
throw new NPlotException("world extent of axis not set.");
}
double adjustedMax = this.AdjustedWorldValue(WorldMax);
double adjustedMin = this.AdjustedWorldValue(WorldMin);
// (2) determine distance between large ticks.
double tickDist = this.DetermineLargeTickStep(
Utils.Distance(physicalMin, physicalMax),
out bool shouldCullMiddle);
// (3) determine starting position.
double first = 0.0f;
if (!double.IsNaN(largeTickValue_))
{
// this works for both case when largTickValue_ lt or gt adjustedMin.
first = largeTickValue_ + Math.Ceiling((adjustedMin - largeTickValue_) / tickDist) * tickDist;
}
else
{
if (adjustedMin > 0.0)
{
double nToFirst = Math.Floor(adjustedMin / tickDist) + 1.0f;
first = nToFirst * tickDist;
}
else
{
double nToFirst = Math.Floor(-adjustedMin / tickDist) - 1.0f;
first = -nToFirst * tickDist;
}
// could miss one, if first is just below zero.
if (first - tickDist >= adjustedMin)
{
first -= tickDist;
}
}
// (4) now make list of large tick positions.
largeTickPositions = new List<double>();
if (tickDist < 0.0) // some sanity checking. TODO: remove this.
throw new NPlotException("Tick dist is negative");
double position = first;
int safetyCount = 0;
while (
position <= adjustedMax &&
++safetyCount < 5000)
{
largeTickPositions.Add(position);
position += tickDist;
}
// (5) if the physical extent is too small, and the middle
// ticks should be turned into small ticks, then do this now.
smallTickPositions = null;
if (shouldCullMiddle)
{
smallTickPositions = new List<double>();
if (largeTickPositions.Count > 2)
{
for (int i = 1; i < largeTickPositions.Count - 1; ++i)
{
smallTickPositions.Add(largeTickPositions[i]);
}
}
List<double> culledPositions = new List<double>();
culledPositions.Add(largeTickPositions[0]);
culledPositions.Add(largeTickPositions[largeTickPositions.Count - 1]);
largeTickPositions = culledPositions;
}
}
/// <summary>
/// Calculates the world spacing between large ticks, based on the physical
/// axis length (parameter), world axis length, Mantissa values and
/// MinPhysicalLargeTickStep. A value such that at least two
/// </summary>
/// <param name="physicalLength">physical length of the axis</param>
/// <param name="shouldCullMiddle">Returns true if we were forced to make spacing of
/// large ticks too small in order to ensure that there are at least two of
/// them. The draw ticks method should not draw more than two large ticks if this
/// returns true.</param>
/// <returns>Large tick spacing</returns>
/// <remarks>TODO: This can be optimised a bit.</remarks>
private double DetermineLargeTickStep(float physicalLength, out bool shouldCullMiddle)
{
shouldCullMiddle = false;
if (double.IsNaN(WorldMin) || double.IsNaN(WorldMax))
{
throw new NPlotException("world extent of axis not set.");
}
// if the large tick has been explicitly set, then return this.
if (!double.IsNaN(largeTickStep_))
{
if (largeTickStep_ <= 0.0f)
{
throw new NPlotException(
"can't have negative or zero tick step - reverse WorldMin WorldMax instead."
);
}
return largeTickStep_;
}
// otherwise we need to calculate the large tick step ourselves.
// adjust world max and min for offset and scale properties of axis.
double adjustedMax = this.AdjustedWorldValue(WorldMax);
double adjustedMin = this.AdjustedWorldValue(WorldMin);
double range = adjustedMax - adjustedMin;
// if axis has zero world length, then return arbitrary number.
if (Utils.DoubleEqual(adjustedMax, adjustedMin))
{
return 1.0f;
}
double approxTickStep;
if (TicksIndependentOfPhysicalExtent)
{
approxTickStep = range / 6.0f;
}
else
{
approxTickStep = MinPhysicalLargeTickStep / physicalLength * range;
}
double exponent = Math.Floor(Math.Log10(approxTickStep));
double mantissa = Math.Pow(10.0, Math.Log10(approxTickStep) - exponent);
// determine next whole mantissa below the approx one.
int mantissaIndex = Mantissas.Length - 1;
for (int i = 1; i < Mantissas.Length; ++i)
{
if (mantissa < Mantissas[i])
{
mantissaIndex = i - 1;
break;
}
}
// then choose next largest spacing.
mantissaIndex += 1;
if (mantissaIndex == Mantissas.Length)
{
mantissaIndex = 0;
exponent += 1.0;
}
if (!TicksIndependentOfPhysicalExtent)
{
// now make sure that the returned value is such that at least two
// large tick marks will be displayed.
double tickStep = Math.Pow(10.0, exponent) * Mantissas[mantissaIndex];
float physicalStep = (float)(tickStep / range * physicalLength);
while (physicalStep > physicalLength / 2)
{
shouldCullMiddle = true;
mantissaIndex -= 1;
if (mantissaIndex == -1)
{
mantissaIndex = Mantissas.Length - 1;
exponent -= 1.0;
}
tickStep = Math.Pow(10.0, exponent) * Mantissas[mantissaIndex];
physicalStep = (float)(tickStep / range * physicalLength);
}
}
// and we're done.
return Math.Pow(10.0, exponent) * Mantissas[mantissaIndex];
}
/// <summary>
/// Given the large tick step, determine the number of small ticks that should
/// be placed in between.
/// </summary>
/// <param name="bigTickDist">the large tick step.</param>
/// <returns>the number of small ticks to place between large ticks.</returns>
private int DetermineNumberSmallTicks(double bigTickDist)
{
if (this.numberSmallTicks_ != null)
{
return (int)this.numberSmallTicks_ + 1;
}
if (this.SmallTickCounts.Length != this.Mantissas.Length)
{
throw new NPlotException("Mantissa.Length != SmallTickCounts.Length");
}
if (bigTickDist > 0.0f)
{
double exponent = Math.Floor(Math.Log10(bigTickDist));
double mantissa = Math.Pow(10.0, Math.Log10(bigTickDist) - exponent);
for (int i = 0; i < Mantissas.Length; ++i)
{
if (Math.Abs(mantissa - Mantissas[i]) < 0.001)
{
return SmallTickCounts[i] + 1;
}
}
}
return 0;
}
/// <summary>
/// The distance between large ticks. If this is set to NaN [default],
/// this distance will be calculated automatically.
/// </summary>
public double LargeTickStep
{
set => largeTickStep_ = value;
get => largeTickStep_;
}
/// <summary>
/// If set !NaN, gives the distance between large ticks.
/// </summary>
private double largeTickStep_ = double.NaN;
/// <summary>
/// If set, a large tick will be placed at this position, and other large ticks will
/// be placed relative to this position.
/// </summary>
public double LargeTickValue
{
set => largeTickValue_ = value;
get => largeTickValue_;
}
private double largeTickValue_ = double.NaN;
/// <summary>
/// The number of small ticks between large ticks.
/// </summary>
public int NumberOfSmallTicks
{
set => numberSmallTicks_ = value;
get =>
// TODO: something better here.
(int)numberSmallTicks_;
}
private object numberSmallTicks_;
/// <summary>
/// Scale to apply to world values when labelling axis:
/// (labelWorld = world * scale + offset). This does not
/// affect the "real" world range of the axis.
/// </summary>
public double Scale
{
get => scale_;
set => scale_ = value;
}
/// <summary>
/// Offset to apply to world values when labelling the axis:
/// (labelWorld = axisWorld * scale + offset). This does not
/// affect the "real" world range of the axis.
/// </summary>
public double Offset
{
get => offset_;
set => offset_ = value;
}
/// <summary>
/// If LargeTickStep isn't specified, then a suitable value is
/// calculated automatically. To determine the tick spacing, the
/// world axis length is divided by ApproximateNumberLargeTicks
/// and the next lowest distance m*10^e for some m in the Mantissas
/// set and some integer e is used as the large tick spacing.
/// </summary>
public float ApproxNumberLargeTicks = 3.0f;
/// <summary>
/// If LargeTickStep isn't specified, then a suitable value is
/// calculated automatically. The value will be of the form
/// m*10^e for some m in this set.
/// </summary>
public double[] Mantissas = {1.0, 2.0, 5.0};
/// <summary>
/// If NumberOfSmallTicks isn't specified then ....
/// If specified LargeTickStep manually, then no small ticks unless
/// NumberOfSmallTicks specified.
/// </summary>
public int[] SmallTickCounts = {4, 1, 4};
private double offset_;
private double scale_ = 1.0;
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Management.Automation.Provider;
using Dbg = System.Management.Automation;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
#pragma warning disable 56500
namespace System.Management.Automation
{
/// <summary>
/// Holds the state of a Monad Shell session.
/// </summary>
internal sealed partial class SessionStateInternal
{
/// <summary>
/// The currently active drive. It determines the current working directory.
/// </summary>
private PSDriveInfo _currentDrive;
#region NewDrive
/// <summary>
/// Adds the specified drive to the current scope.
/// </summary>
/// <param name="drive">
/// The drive to be added to the current scope.
/// </param>
/// <param name="scopeID">
/// The ID for the scope to add the drive to. The scope ID can be any of the
/// "special" scope identifiers like "global", "local", or "private" or it
/// can be a numeric identifier that is a count of the number of parent
/// scopes up from the current scope to put the drive in.
/// If this parameter is null or empty the drive will be placed in the
/// current scope.
/// </param>
/// <returns>
/// The drive that was added, if any.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="drive"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the drive already exists,
/// or
/// If <paramref name="drive"/>.Name contains one or more invalid characters; ~ / \\ . :
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider is not a DriveCmdletProvider.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// The provider for the <paramref name="drive"/> could not be found.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception or returned null.
/// </exception>
internal PSDriveInfo NewDrive(PSDriveInfo drive, string scopeID)
{
if (drive == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(drive));
}
PSDriveInfo result = null;
// Construct a CmdletProviderContext and call the override
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
NewDrive(drive, scopeID, context);
context.ThrowFirstErrorOrDoNothing();
Collection<PSObject> successObjects = context.GetAccumulatedObjects();
if (successObjects != null &&
successObjects.Count > 0)
{
Dbg.Diagnostics.Assert(
successObjects.Count == 1,
"NewDrive should only add one PSDriveInfo object to the pipeline");
// set the return value to the first drive (should only be one).
if (!successObjects[0].ImmediateBaseObjectIsEmpty)
{
result = (PSDriveInfo)successObjects[0].BaseObject;
}
}
return result;
}
/// <summary>
/// Adds a drive to the PowerShell namespace.
/// </summary>
/// <param name="drive">
/// The new drive to be added.
/// </param>
/// <param name="scopeID">
/// The ID for the scope to add the drive to. The scope ID can be any of the
/// "special" scope identifiers like "global", "local", or "private" or it
/// can be a numeric identifier that is a count of the number of parent
/// scopes up from the current scope to put the drive in.
/// If this parameter is null or empty the drive will be placed in the
/// current scope.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="drive"/> or <paramref name="context"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the drive already exists
/// or
/// If <paramref name="drive"/>.Name contains one or more invalid characters; ~ / \\ . :
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider is not a DriveCmdletProvider.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// The provider for the <paramref name="drive"/> could not be found.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception or returned null.
/// </exception>
internal void NewDrive(PSDriveInfo drive, string scopeID, CmdletProviderContext context)
{
if (drive == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(drive));
}
if (context == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(context));
}
if (!IsValidDriveName(drive.Name))
{
ArgumentException e =
PSTraceSource.NewArgumentException(
"drive.Name",
SessionStateStrings.DriveNameIllegalCharacters);
throw e;
}
// Allow the provider a chance to approve the drive and set
// provider specific data
PSDriveInfo result = ValidateDriveWithProvider(drive, context, true);
// We assume that the provider wrote the error message as they
// are suppose to.
if (result == null)
{
return;
}
if (string.Equals(result.Name, drive.Name, StringComparison.OrdinalIgnoreCase))
{
// Set the drive in the current scope.
try
{
SessionStateScope scope = _currentScope;
if (!string.IsNullOrEmpty(scopeID))
{
scope = GetScopeByID(scopeID);
}
scope.NewDrive(result);
}
catch (ArgumentException argumentException)
{
// Wrap up the exception and write it to the error stream
context.WriteError(
new ErrorRecord(
argumentException,
"NewDriveError",
ErrorCategory.InvalidArgument,
result));
return;
}
catch (SessionStateException)
{
// This should be a pipeline terminating condition
throw;
}
if (ProvidersCurrentWorkingDrive[drive.Provider] == null)
{
// Set the new drive as the current
// drive for the provider since there isn't one set.
ProvidersCurrentWorkingDrive[drive.Provider] = drive;
}
// Upon success, write the drive to the pipeline
context.WriteObject(result);
}
else
{
ProviderInvocationException e =
NewProviderInvocationException(
"NewDriveProviderFailed",
SessionStateStrings.NewDriveProviderFailed,
drive.Provider,
drive.Root,
PSTraceSource.NewArgumentException("root"));
throw e;
}
}
private static bool IsValidDriveName(string name)
{
bool result = true;
do
{
if (string.IsNullOrEmpty(name))
{
result = false;
break;
}
if (name.IndexOfAny(s_charactersInvalidInDriveName) >= 0)
{
result = false;
break;
}
} while (false);
return result;
}
private static readonly char[] s_charactersInvalidInDriveName = new char[] { ':', '/', '\\', '.', '~' };
/// <summary>
/// Tries to resolve the drive root as an MSH path. If it successfully resolves
/// to a single path then the resolved provider internal path is returned. If it
/// does not resolve to a single MSH path the root is returned as it was passed.
/// </summary>
/// <param name="root">
/// The root path of the drive to be resolved.
/// </param>
/// <param name="provider">
/// The provider that should be used when resolving the path.
/// </param>
/// <returns>
/// The new root path of the drive.
/// </returns>
private string GetProviderRootFromSpecifiedRoot(string root, ProviderInfo provider)
{
Dbg.Diagnostics.Assert(
root != null,
"Caller should have verified the root");
Dbg.Diagnostics.Assert(
provider != null,
"Caller should have verified the provider");
string result = root;
SessionState sessionState = new SessionState(ExecutionContext.TopLevelSessionState);
Collection<string> resolvedPaths = null;
ProviderInfo resolvedProvider = null;
try
{
// First try to resolve the root as an MSH path
resolvedPaths =
sessionState.Path.GetResolvedProviderPathFromPSPath(root, out resolvedProvider);
// If a single path was resolved...
if (resolvedPaths != null &&
resolvedPaths.Count == 1)
{
// and the provider used to resolve the path,
// matches the one specified by the drive...
if (provider.NameEquals(resolvedProvider.FullName))
{
// and the item exists
ProviderIntrinsics providerIntrinsics =
new ProviderIntrinsics(this);
if (providerIntrinsics.Item.Exists(root))
{
// then use the resolved path as the root of the drive
result = resolvedPaths[0];
}
}
}
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
// If any of the following exceptions are thrown we assume that
// the path is a file system path not an MSH path and try
// to create the drive with that root.
catch (DriveNotFoundException)
{
}
catch (ProviderNotFoundException)
{
}
catch (ItemNotFoundException)
{
}
catch (NotSupportedException)
{
}
catch (InvalidOperationException)
{
}
catch (ProviderInvocationException)
{
}
catch (ArgumentException)
{
}
return result;
}
/// <summary>
/// Gets an object that defines the additional parameters for the NewDrive implementation
/// for a provider.
/// </summary>
/// <param name="providerId">
/// The provider ID for the drive that is being created.
/// </param>
/// <param name="context">
/// The context under which this method is being called.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerId"/> is not a DriveCmdletProvider.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If <paramref name="providerId"/> does not exist.
/// </exception>
internal object NewDriveDynamicParameters(string providerId, CmdletProviderContext context)
{
if (providerId == null)
{
// If the provider hasn't been specified yet, just return null.
// The provider can be specified as pipeline input.
return null;
}
DriveCmdletProvider provider = GetDriveProviderInstance(providerId);
object result = null;
try
{
result = provider.NewDriveDynamicParameters(context);
}
catch (Exception e) // Catch-all OK, 3rd party callout
{
throw
NewProviderInvocationException(
"NewDriveDynamicParametersProviderException",
SessionStateStrings.NewDriveDynamicParametersProviderException,
provider.ProviderInfo,
null,
e);
}
return result;
}
#endregion NewDrive
#region GetDrive
/// <summary>
/// Searches through the session state scopes to find a drive.
/// </summary>
/// <param name="name">
/// The name of a drive to find.
/// </param>
/// <returns>
/// The drive information if the drive is found.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If there is no drive with <paramref name="name"/>.
/// </exception>
internal PSDriveInfo GetDrive(string name)
{
return GetDrive(name, true);
}
private PSDriveInfo GetDrive(string name, bool automount)
{
if (name == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(name));
}
PSDriveInfo result = null;
// Start searching through the scopes for the drive until the drive
// is found or the global scope is reached.
SessionStateScopeEnumerator scopeEnumerator = new SessionStateScopeEnumerator(CurrentScope);
int scopeID = 0;
foreach (SessionStateScope processingScope in scopeEnumerator)
{
result = processingScope.GetDrive(name);
if (result != null)
{
if (result.IsAutoMounted)
{
// Validate or remove the auto-mounted drive
if (!ValidateOrRemoveAutoMountedDrive(result, processingScope))
{
result = null;
}
}
if (result != null)
{
s_tracer.WriteLine("Drive found in scope {0}", scopeID);
break;
}
}
// Increment the scope ID
++scopeID;
}
if (result == null && automount)
{
// Attempt to automount as a file system drive
// or as a BuiltIn drive (e.g. "Cert"/"Certificate"/"WSMan")
result = AutomountFileSystemDrive(name) ?? AutomountBuiltInDrive(name);
}
if (result == null)
{
DriveNotFoundException driveNotFound =
new DriveNotFoundException(
name,
"DriveNotFound",
SessionStateStrings.DriveNotFound);
throw driveNotFound;
}
return result;
}
/// <summary>
/// Searches through the session state scopes looking
/// for a drive of the specified name.
/// </summary>
/// <param name="name">
/// The name of the drive to return.
/// </param>
/// <param name="scopeID">
/// The scope ID of the scope to look in for the drive.
/// If this parameter is null or empty the drive will be
/// found by searching the scopes using the dynamic scoping
/// rules.
/// </param>
/// <returns>
/// The drive for the given name in the given scope or null if
/// the drive was not found.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If <paramref name="scopeID"/> is less than zero, or not
/// a number and not "script", "global", "local", or "private"
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
internal PSDriveInfo GetDrive(string name, string scopeID)
{
if (name == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(name));
}
PSDriveInfo result = null;
// The scope ID wasn't defined or wasn't recognizable
// so do a search through the scopes looking for the
// drive.
if (string.IsNullOrEmpty(scopeID))
{
SessionStateScopeEnumerator scopeEnumerator =
new SessionStateScopeEnumerator(CurrentScope);
foreach (SessionStateScope scope in scopeEnumerator)
{
result = scope.GetDrive(name);
if (result != null)
{
if (result.IsAutoMounted)
{
// Validate or remove the auto-mounted drive
if (!ValidateOrRemoveAutoMountedDrive(result, scope))
{
result = null;
}
}
if (result != null)
{
break;
}
}
}
if (result == null)
{
result = AutomountFileSystemDrive(name);
}
}
else
{
SessionStateScope scope = GetScopeByID(scopeID);
result = scope.GetDrive(name);
if (result != null)
{
if (result.IsAutoMounted)
{
// Validate or remove the auto-mounted drive
if (!ValidateOrRemoveAutoMountedDrive(result, scope))
{
result = null;
}
}
}
else
{
if (scope == GlobalScope)
{
result = AutomountFileSystemDrive(name);
}
}
}
return result;
}
private PSDriveInfo AutomountFileSystemDrive(string name)
{
PSDriveInfo result = null;
// Check to see if it could be a "auto-mounted"
// file system drive. If so, add the new drive
// to the global scope and return it
if (name.Length == 1)
{
try
{
System.IO.DriveInfo driveInfo = new System.IO.DriveInfo(name);
result = AutomountFileSystemDrive(driveInfo);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception)
{
// Catch all exceptions and continue since the drive does not exist
// This action wasn't requested by the user and as such we don't
// want to expose the user to any error conditions other than
// DriveNotFoundException which will be thrown by the caller
}
}
return result;
}
private PSDriveInfo AutomountFileSystemDrive(System.IO.DriveInfo systemDriveInfo)
{
PSDriveInfo result = null;
if (!IsProviderLoaded(this.ExecutionContext.ProviderNames.FileSystem))
{
s_tracer.WriteLine("The {0} provider is not loaded", this.ExecutionContext.ProviderNames.FileSystem);
return null;
}
// Since the drive does exist, add it.
try
{
// Get the FS provider
DriveCmdletProvider driveProvider =
GetDriveProviderInstance(this.ExecutionContext.ProviderNames.FileSystem);
if (driveProvider != null)
{
// Create a new drive
string systemDriveName = systemDriveInfo.Name.Substring(0, 1);
string volumeLabel = string.Empty;
string displayRoot = null;
try
{
// When run in an AppContainer, we may not have access to the volume label.
volumeLabel = systemDriveInfo.VolumeLabel;
}
catch (UnauthorizedAccessException) { }
// Get the actual root path for Network type drives
if (systemDriveInfo.DriveType == DriveType.Network)
{
try
{
displayRoot = Microsoft.PowerShell.Commands.FileSystemProvider
.GetRootPathForNetworkDriveOrDosDevice(systemDriveInfo);
}
// We want to get root path of the network drive as extra information to display to the user.
// It's okay we failed to get the root path for some reason. We don't want to throw exception
// here as it would break the current behavior.
catch (Win32Exception) { }
catch (InvalidOperationException) { }
}
PSDriveInfo newPSDriveInfo =
new PSDriveInfo(
systemDriveName,
driveProvider.ProviderInfo,
systemDriveInfo.RootDirectory.FullName,
volumeLabel,
null,
displayRoot);
newPSDriveInfo.IsAutoMounted = true;
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
newPSDriveInfo.DriveBeingCreated = true;
// Validate the drive with the provider
result = ValidateDriveWithProvider(driveProvider, newPSDriveInfo, context, false);
newPSDriveInfo.DriveBeingCreated = false;
if (result != null && !context.HasErrors())
{
// Create the drive in the global scope.
GlobalScope.NewDrive(result);
}
}
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e)
{
// Since the user isn't expecting this behavior, we don't
// want to let errors find their way out. If there are any
// failures we just don't mount the drive.
MshLog.LogProviderHealthEvent(
this.ExecutionContext,
this.ExecutionContext.ProviderNames.FileSystem,
e,
Severity.Warning);
}
return result;
}
/// <summary>
/// Auto-mounts a built-in drive.
/// </summary>
/// <remarks>
/// Calls GetDrive(name, false) internally.
/// </remarks>
/// <param name="name">The name of the drive to load.</param>
/// <returns></returns>
internal PSDriveInfo AutomountBuiltInDrive(string name)
{
MountDefaultDrive(name, ExecutionContext);
PSDriveInfo result = GetDrive(name, false);
return result;
}
/// <summary>
/// Automatically mount the specified drive.
/// </summary>
/// <remarks>
/// Neither 'WSMan' nor 'Certificate' provider works in UNIX PS today.
/// So this method currently does nothing on UNIX.
/// </remarks>
internal static void MountDefaultDrive(string name, ExecutionContext context)
{
#if !UNIX
PSModuleAutoLoadingPreference moduleAutoLoadingPreference =
CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
if (moduleAutoLoadingPreference == PSModuleAutoLoadingPreference.None)
{
return;
}
string moduleName = null;
// Note: For the certificate provider, we actually support the provider name as an alternative to
// mount the default drive, since the provider names can be used for provider-qualified paths.
// The WSMAN drive is the same as the provider name.
if (
string.Equals("Cert", name, StringComparison.OrdinalIgnoreCase) ||
string.Equals("Certificate", name, StringComparison.OrdinalIgnoreCase)
)
{
moduleName = "Microsoft.PowerShell.Security";
}
else if (string.Equals("WSMan", name, StringComparison.OrdinalIgnoreCase))
{
moduleName = "Microsoft.WSMan.Management";
}
if (!string.IsNullOrEmpty(moduleName))
{
s_tracer.WriteLine("Auto-mounting built-in drive: {0}", name);
CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(Microsoft.PowerShell.Commands.ImportModuleCommand), null, null, context);
Exception exception = null;
s_tracer.WriteLine("Attempting to load module: {0}", moduleName);
CommandDiscovery.AutoloadSpecifiedModule(moduleName, context, commandInfo.Visibility, out exception);
if (exception != null)
{
// Call-out to user code, catch-all OK
}
}
#endif
}
/// <summary>
/// Determines if the specified automounted drive still exists. If not,
/// the drive is removed.
/// </summary>
/// <param name="drive">
/// The drive to validate or remove.
/// </param>
/// <param name="scope">
/// The scope the drive is in. This will be used to remove the drive
/// if necessary.
/// </param>
/// <returns>
/// True if the drive is still valid, false if the drive was removed.
/// </returns>
private bool ValidateOrRemoveAutoMountedDrive(PSDriveInfo drive, SessionStateScope scope)
{
bool result = true;
try
{
System.IO.DriveInfo systemDriveInfo = new System.IO.DriveInfo(drive.Name);
result = systemDriveInfo.DriveType != DriveType.NoRootDirectory;
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception)
{
// Assume any exception means the drive is no longer valid and needs
// to be removed.
result = false;
}
if (!result)
{
DriveCmdletProvider driveProvider = null;
try
{
driveProvider =
GetDriveProviderInstance(this.ExecutionContext.ProviderNames.FileSystem);
}
catch (NotSupportedException)
{
}
catch (ProviderNotFoundException)
{
}
if (driveProvider != null)
{
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
try
{
// Give the provider a chance to cleanup
driveProvider.RemoveDrive(drive, context);
}
// Ignore any exceptions the provider throws because we
// are doing this without an explicit request from the
// user. Since the provider can throw any exception
// we must catch all exceptions here.
catch (Exception)
{
}
scope.RemoveDrive(drive);
}
}
return result;
}
/// <summary>
/// If a VHD is mounted to a drive prior to the PowerShell session being launched,
/// then such a drive has to be validated for its existence before performing
/// any operations on that drive to make sure that the drive is not unmounted.
/// </summary>
/// <param name="drive"></param>
/// <returns>Absence of mounted drive for FileSystem provider or False for other provider types.</returns>
private bool IsAStaleVhdMountedDrive(PSDriveInfo drive)
{
bool result = false;
// check that drive's provider type is FileSystem
if ((drive.Provider != null) && (!drive.Provider.NameEquals(this.ExecutionContext.ProviderNames.FileSystem)))
{
return false;
}
// A VHD mounted drive gets detected with a DriveType of DriveType.Fixed
// when the VHD is mounted, however if the drive is unmounted, such a
// stale drive is no longer valid and gets detected with DriveType.NoRootDirectory.
// We would hit this situation in the following scenario:
// 1. Launch Powershell session 'A' and mount the VHD.
// 2. Launch different powershell session 'B'.
// 3. Unmount the VHD in session 'A'.
// The drive pointing to VHD in session 'B' gets detected as DriveType.NoRootDirectory
// after the VHD is removed in session 'A'.
if (drive != null && !string.IsNullOrEmpty(drive.Name) && drive.Name.Length == 1)
{
try
{
char driveChar = Convert.ToChar(drive.Name, CultureInfo.InvariantCulture);
if (char.ToUpperInvariant(driveChar) >= 'A' && char.ToUpperInvariant(driveChar) <= 'Z')
{
DriveInfo systemDriveInfo = new DriveInfo(drive.Name);
if (systemDriveInfo.DriveType == DriveType.NoRootDirectory)
{
if (!Directory.Exists(drive.Root))
{
result = true;
}
}
}
}
catch (ArgumentException)
{
// At this point, We dont care if the drive is not a valid drive that does not host the VHD.
}
}
return result;
}
/// <summary>
/// Gets all the drives for a specific provider.
/// </summary>
/// <param name="providerId">
/// The identifier for the provider to retrieve the drives for.
/// </param>
/// <returns>
/// An IEnumerable that contains the drives for the specified provider.
/// </returns>
internal Collection<PSDriveInfo> GetDrivesForProvider(string providerId)
{
if (string.IsNullOrEmpty(providerId))
{
return Drives(null);
}
// Ensure that the provider name resolves to a single provider
GetSingleProvider(providerId);
Collection<PSDriveInfo> drives = new Collection<PSDriveInfo>();
foreach (PSDriveInfo drive in Drives(null))
{
if (drive != null &&
drive.Provider.NameEquals(providerId))
{
drives.Add(drive);
}
}
return drives;
}
#endregion GetDrive
#region RemoveDrive
/// <summary>
/// Removes the drive with the specified name.
/// </summary>
/// <param name="driveName">
/// The name of the drive to remove.
/// </param>
/// <param name="force">
/// Determines whether drive should be forcefully removed even if there was errors.
/// </param>
/// <param name="scopeID">
/// The ID of the scope from which to remove the drive.
/// If the scope ID is null or empty, the scope hierarchy will be searched
/// starting at the current scope through all the parent scopes to the
/// global scope until a drive of the given name is found to remove.
/// </param>
internal void RemoveDrive(string driveName, bool force, string scopeID)
{
if (driveName == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(driveName));
}
PSDriveInfo drive = GetDrive(driveName, scopeID);
if (drive == null)
{
DriveNotFoundException e = new DriveNotFoundException(
driveName,
"DriveNotFound",
SessionStateStrings.DriveNotFound);
throw e;
}
RemoveDrive(drive, force, scopeID);
}
/// <summary>
/// Removes the drive with the specified name.
/// </summary>
/// <param name="driveName">
/// The name of the drive to remove.
/// </param>
/// <param name="force">
/// Determines whether drive should be forcefully removed even if there was errors.
/// </param>
/// <param name="scopeID">
/// The ID of the scope from which to remove the drive.
/// If the scope ID is null or empty, the scope hierarchy will be searched
/// starting at the current scope through all the parent scopes to the
/// global scope until a drive of the given name is found to remove.
/// </param>
/// <param name="context">
/// The context of the command.
/// </param>
internal void RemoveDrive(
string driveName,
bool force,
string scopeID,
CmdletProviderContext context)
{
if (driveName == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(driveName));
}
Dbg.Diagnostics.Assert(
context != null,
"The caller should verify the context");
PSDriveInfo drive = GetDrive(driveName, scopeID);
if (drive == null)
{
DriveNotFoundException e = new DriveNotFoundException(
driveName,
"DriveNotFound",
SessionStateStrings.DriveNotFound);
context.WriteError(new ErrorRecord(e.ErrorRecord, e));
}
else
{
RemoveDrive(drive, force, scopeID, context);
}
}
/// <summary>
/// Removes the specified drive.
/// </summary>
/// <param name="drive">
/// The drive to be removed.
/// </param>
/// <param name="force">
/// Determines whether drive should be forcefully removed even if there was errors.
/// </param>
/// <param name="scopeID">
/// The ID of the scope from which to remove the drive.
/// If the scope ID is null or empty, the scope hierarchy will be searched
/// starting at the current scope through all the parent scopes to the
/// global scope until a drive of the given name is found to remove.
/// </param>
internal void RemoveDrive(PSDriveInfo drive, bool force, string scopeID)
{
if (drive == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(drive));
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
RemoveDrive(drive, force, scopeID, context);
if (context.HasErrors() && !force)
{
context.ThrowFirstErrorOrDoNothing();
}
}
/// <summary>
/// Removes the specified drive.
/// </summary>
/// <param name="drive">
/// The drive to be removed.
/// </param>
/// <param name="force">
/// Determines whether drive should be forcefully removed even if there was errors.
/// </param>
/// <param name="scopeID">
/// The ID of the scope from which to remove the drive.
/// If the scope ID is null or empty, the scope hierarchy will be searched
/// starting at the current scope through all the parent scopes to the
/// global scope until a drive of the given name is found to remove.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
internal void RemoveDrive(
PSDriveInfo drive,
bool force,
string scopeID,
CmdletProviderContext context)
{
// Make sure that the CanRemoveDrive is called even if we are forcing
// the removal because we want the provider to have a chance to
// cleanup.
bool canRemove = false;
try
{
canRemove = CanRemoveDrive(drive, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (ProviderInvocationException)
{
if (!force)
{
throw;
}
}
// Now remove the drive if there was no error or we are forcing the removal
if (canRemove || force)
{
// The scope ID wasn't defined or wasn't recognizable
// so do a search through the scopes looking for the
// drive.
if (string.IsNullOrEmpty(scopeID))
{
SessionStateScopeEnumerator scopeEnumerator =
new SessionStateScopeEnumerator(CurrentScope);
foreach (SessionStateScope scope in scopeEnumerator)
{
try
{
PSDriveInfo result = scope.GetDrive(drive.Name);
if (result != null)
{
scope.RemoveDrive(drive);
// If the drive is the current drive for the provider, remove
// it from the current drive list.
if (ProvidersCurrentWorkingDrive[drive.Provider] == result)
{
ProvidersCurrentWorkingDrive[drive.Provider] = null;
}
break;
}
}
catch (ArgumentException)
{
}
}
}
else
{
SessionStateScope scope = GetScopeByID(scopeID);
scope.RemoveDrive(drive);
// If the drive is the current drive for the provider, remove
// it from the current drive list.
if (ProvidersCurrentWorkingDrive[drive.Provider] == drive)
{
ProvidersCurrentWorkingDrive[drive.Provider] = null;
}
}
}
else
{
PSInvalidOperationException e =
(PSInvalidOperationException)PSTraceSource.NewInvalidOperationException(
SessionStateStrings.DriveRemovalPreventedByProvider,
drive.Name,
drive.Provider);
context.WriteError(
new ErrorRecord(
e.ErrorRecord,
e));
}
}
/// <summary>
/// Determines if the drive can be removed by calling the provider
/// for the drive.
/// </summary>
/// <param name="drive">
/// The drive to test for removal.
/// </param>
/// <param name="context">
/// The context under which the command is running.
/// </param>
/// <returns>
/// True if the drive can be removed, false otherwise.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="drive"/> or <paramref name="context"/> is null.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception when RemoveDrive was called.
/// </exception>
private bool CanRemoveDrive(PSDriveInfo drive, CmdletProviderContext context)
{
if (context == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(context));
}
if (drive == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(drive));
}
s_tracer.WriteLine("Drive name = {0}", drive.Name);
// First set the drive data
context.Drive = drive;
// Now see if the provider will let us remove the drive
DriveCmdletProvider driveCmdletProvider =
GetDriveProviderInstance(drive.Provider);
bool driveRemovable = false;
PSDriveInfo result = null;
try
{
result = driveCmdletProvider.RemoveDrive(drive, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout
{
throw NewProviderInvocationException(
"RemoveDriveProviderException",
SessionStateStrings.RemoveDriveProviderException,
driveCmdletProvider.ProviderInfo,
null,
e);
}
if (result != null)
{
// Make sure the provider didn't try to pull a fast one on us
// and substitute a different drive.
if (string.Equals(result.Name, drive.Name, StringComparison.OrdinalIgnoreCase))
{
driveRemovable = true;
}
}
return driveRemovable;
}
#endregion RemoveDrive
#region Drives
/// <summary>
/// Gets an enumerable list of the drives that are mounted in
/// the specified scope.
/// </summary>
/// <param name="scope">
/// The scope to retrieve the drives from. If null or empty,
/// all drives from all scopes will be retrieved.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="scope"/> is less than zero, or not
/// a number and not "script", "global", "local", or "private"
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
internal Collection<PSDriveInfo> Drives(string scope)
{
Dictionary<string, PSDriveInfo> driveTable = new Dictionary<string, PSDriveInfo>();
SessionStateScope startingScope = _currentScope;
if (!string.IsNullOrEmpty(scope))
{
startingScope = GetScopeByID(scope);
}
SessionStateScopeEnumerator scopeEnumerator =
new SessionStateScopeEnumerator(startingScope);
DriveInfo[] alldrives = DriveInfo.GetDrives();
Collection<string> driveNames = new Collection<string>();
foreach (DriveInfo drive in alldrives)
{
driveNames.Add(drive.Name.Substring(0, 1));
}
foreach (SessionStateScope lookupScope in scopeEnumerator)
{
foreach (PSDriveInfo drive in lookupScope.Drives)
{
// It is the correct behavior for child scope
// drives to overwrite parent scope drives of
// the same name.
if (drive != null)
{
bool driveIsValid = true;
// If the drive is auto-mounted, ensure that it still exists, or remove the drive.
#if !UNIX
if (drive.IsAutoMounted || IsAStaleVhdMountedDrive(drive))
{
driveIsValid = ValidateOrRemoveAutoMountedDrive(drive, lookupScope);
}
#endif
if (drive.Name.Length == 1)
{
if (!(driveNames.Contains(drive.Name)))
driveTable.Remove(drive.Name);
}
if (driveIsValid && !driveTable.ContainsKey(drive.Name))
{
driveTable[drive.Name] = drive;
}
}
}
// If the scope was specified then don't loop
// through the other scopes
if (scope != null && scope.Length > 0)
{
break;
}
}
// Now lookup all the file system drives and automount any that are not
// present
try
{
foreach (System.IO.DriveInfo fsDriveInfo in alldrives)
{
if (fsDriveInfo != null)
{
string fsDriveName = fsDriveInfo.Name.Substring(0, 1);
if (!driveTable.ContainsKey(fsDriveName))
{
PSDriveInfo automountedDrive = AutomountFileSystemDrive(fsDriveInfo);
if (automountedDrive != null)
{
driveTable[automountedDrive.Name] = automountedDrive;
}
}
}
}
}
// We don't want to have automounting cause an exception. We
// rather it just fail silently as it wasn't a result of an
// explicit request by the user anyway.
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
Collection<PSDriveInfo> results = new Collection<PSDriveInfo>();
foreach (PSDriveInfo drive in driveTable.Values)
{
results.Add(drive);
}
return results;
}
#endregion Drives
/// <summary>
/// Gets or sets the current working drive.
/// </summary>
internal PSDriveInfo CurrentDrive
{
get
{
if (this != ExecutionContext.TopLevelSessionState)
return ExecutionContext.TopLevelSessionState.CurrentDrive;
else
return _currentDrive;
}
set
{
if (this != ExecutionContext.TopLevelSessionState)
ExecutionContext.TopLevelSessionState.CurrentDrive = value;
else
_currentDrive = value;
}
}
}
}
#pragma warning restore 56500
| |
// NewArrayListTest.cs
//
// Unit tests for System.Collections.ArrayList
//
// Copyright (c) 2003 Thong (Tum) Nguyen [[email protected]]
//
// Released under the MIT License:
//
// http://www.opensource.org/licenses/mit-license.html
//
// 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.
//
// Author's comment: Source code formatting has been changed by request to match
// Mono's formatting style. I personally use BSD-style formatting.
//
using System;
using System.Collections;
using NUnit.Framework;
namespace MonoTests.System.Collections
{
/// <summary>
/// Some test cases for the new ArrayList implementation.
/// </summary>
[TestFixture]
public class NewArrayListTest
: TestCase
{
private object[] c_TestData = new Object[] {0,1,2,3,4,5,6,7,8,9};
private void VerifyContains(IList list, IList values, string message)
{
if (values.Count != list.Count)
{
Assertion.Assert(message, false);
}
for (int i = 0; i < list.Count; i++)
{
if (list[i] == null && values[i] == null)
{
continue;
}
if ((list[i] == null || values[i] == null) || !list[i].Equals(values[i]))
{
Assertion.Assert(message, false);
}
}
}
private void PrivateTestSort(ArrayList arrayList)
{
Random random = new Random(1027);
// Sort arrays of lengths up to 200
for (int i = 1; i < 200; i++)
{
for (int j = 0; j < i; j++)
{
arrayList.Add(random.Next(0, 1000));
}
arrayList.Sort();
for (int j = 1; j < i; j++)
{
if ((int)arrayList[j] < (int)arrayList[j - 1])
{
Assertion.Fail("ArrayList.Sort()");
return;
}
}
arrayList.Clear();
}
}
[Test]
public void TestSortStandard()
{
PrivateTestSort(new ArrayList());
}
[Test]
public void TestSortSynchronized()
{
PrivateTestSort(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestSortAdapter()
{
PrivateTestSort(ArrayList.Adapter(new ArrayList()));
}
[Test]
public void TestSortGetRange()
{
PrivateTestSort(new ArrayList().GetRange(0, 0));
}
private void PrivateTestIndexOf(ArrayList arrayList)
{
int x;
arrayList.AddRange(c_TestData);
for (int i = 0; i < 10; i++)
{
x = arrayList.IndexOf(i);
Assertion.Assert("ArrayList.IndexOf(" + i + ")", x == i);
}
try
{
arrayList.IndexOf(0, 10, 1);
Assertion.Fail("ArrayList.IndexOf(0, 10, 1)");
}
catch (ArgumentOutOfRangeException)
{
}
try
{
arrayList.IndexOf(0, 0, -1);
Assertion.Fail("ArrayList.IndexOf(0, 10, 1)");
}
catch (ArgumentOutOfRangeException)
{
}
try
{
arrayList.IndexOf(0, -1, -1);
Assertion.Fail("ArrayList.IndexOf(0, 10, 1)");
}
catch (ArgumentOutOfRangeException)
{
}
try
{
arrayList.IndexOf(0, 9, 10);
Assertion.Fail("ArrayList.IndexOf(0, 10, 1)");
}
catch (ArgumentOutOfRangeException)
{
}
try
{
arrayList.IndexOf(0, 0, 10);
}
catch (ArgumentOutOfRangeException)
{
Assertion.Fail("ArrayList.IndexOf(0, 10, 1)");
}
try
{
arrayList.IndexOf(0, 0, 11);
Assertion.Fail("ArrayList.IndexOf(0, 10, 1)");
}
catch (ArgumentOutOfRangeException)
{
}
// LastIndexOf
for (int i = 0; i < 10; i++)
{
x = arrayList.LastIndexOf(i);
Assertion.Assert("ArrayList.LastIndexOf(" + i + ")", x == i);
}
try
{
arrayList.IndexOf(0, 10, 1);
Assertion.Fail("ArrayList.LastIndexOf(0, 10, 1)");
}
catch (ArgumentOutOfRangeException)
{
}
try
{
arrayList.IndexOf(0, 0, -1);
Assertion.Fail("ArrayList.LastIndexOf(0, 10, 1)");
}
catch (ArgumentOutOfRangeException)
{
}
try
{
arrayList.LastIndexOf(0, -1, -1);
Assertion.Fail("ArrayList.LastIndexOf(0, 10, 1)");
}
catch (ArgumentOutOfRangeException)
{
}
try
{
arrayList.LastIndexOf(0, 9, 10);
}
catch (ArgumentOutOfRangeException)
{
Assertion.Fail("ArrayList.LastIndexOf(0, 10, 1)");
}
try
{
arrayList.LastIndexOf(0, 0, 10);
Assertion.Fail("ArrayList.LastIndexOf(0, 10, 1)");
}
catch (ArgumentOutOfRangeException)
{
}
try
{
arrayList.LastIndexOf(0, 0, 11);
Assertion.Fail("ArrayList.LastIndexOf(0, 10, 1)");
}
catch (ArgumentOutOfRangeException)
{
}
}
private void PrivateTestAddRange(ArrayList arrayList)
{
arrayList.AddRange(c_TestData);
arrayList.AddRange(c_TestData);
VerifyContains(arrayList, new object[] {0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9}, "VerifyContains");
}
[Test]
public void TestAddRangeStandard()
{
PrivateTestAddRange(new ArrayList());
}
[Test]
public void TestAddRangeSynchronized()
{
PrivateTestAddRange(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestAddRangeAdapter()
{
PrivateTestAddRange(ArrayList.Adapter(new ArrayList()));
}
[Test]
public void TestAddRangeGetRange()
{
PrivateTestAddRange(new ArrayList().GetRange(0, 0));
}
[Test]
public void TestIndexOfStandard()
{
PrivateTestIndexOf(new ArrayList());
}
[Test]
public void TestIndexOfSynchronized()
{
PrivateTestIndexOf(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestIndexOfAdapter()
{
PrivateTestIndexOf(ArrayList.Adapter(new ArrayList()));
}
[Test]
public void TestIndexOfGetRange()
{
PrivateTestIndexOf(new ArrayList().GetRange(0, 0));
}
[Test]
public void TestReadOnly()
{
ArrayList arrayList, readOnlyList;
arrayList = new ArrayList();
readOnlyList = ArrayList.ReadOnly(arrayList);
arrayList.AddRange(c_TestData);
// Make sure the readOnlyList is a wrapper and not a clone.
arrayList.Add(10);
Assertion.Assert("readOnlyList.Count == 11", readOnlyList.Count == 11);
try
{
readOnlyList.Add(0);
Assertion.Fail("readOnlyList.Add(0)");
}
catch (NotSupportedException)
{
}
try
{
readOnlyList.AddRange(c_TestData);
Assertion.Fail("readOnlyList.AddRange(c_TestData)");
}
catch (NotSupportedException)
{
}
try
{
readOnlyList.BinarySearch(1);
}
catch (NotSupportedException)
{
Assertion.Fail("readOnlyList.BinarySearch(1)");
}
try
{
int x = readOnlyList.Capacity;
}
catch (NotSupportedException)
{
Assertion.Fail("readOnlyList.Capacity");
}
try
{
readOnlyList.Clear();
Assertion.Fail("readOnlyList.Clear()");
}
catch (NotSupportedException)
{
}
try
{
readOnlyList.Clone();
}
catch (NotSupportedException)
{
Assertion.Fail("readOnlyList.Clone()");
}
try
{
readOnlyList.Contains(1);
}
catch (NotSupportedException)
{
Assertion.Fail("readOnlyList.Contains");
}
try
{
readOnlyList.CopyTo(new object[readOnlyList.Count]);
}
catch (NotSupportedException)
{
Assertion.Fail("readOnlyList.CopyTo(new Array(readOnlyList.Count))");
}
try
{
foreach (object o in readOnlyList)
{
o.ToString();
}
}
catch (NotSupportedException)
{
Assertion.Fail("readOnlyList.GetEnumerator()");
}
try
{
readOnlyList.GetRange(0, 1);
}
catch (NotSupportedException)
{
Assertion.Fail("readOnlyList.GetRange(0, 1)");
}
try
{
readOnlyList.IndexOf(1);
}
catch (NotSupportedException)
{
Assertion.Fail("readOnlyList.readOnlyList.IndexOf(1)");
}
try
{
readOnlyList[0] = 0;
Assertion.Fail("readOnlyList[0] = 0");
}
catch (NotSupportedException)
{
}
try
{
readOnlyList.IndexOf(0);
}
catch (NotSupportedException)
{
Assertion.Fail("readOnlyList.IndexOf(0)");
}
try
{
readOnlyList.InsertRange(0, new object[] {1,2});
Assertion.Fail("readOnlyList.InsertRange(0, new object[] {1,2})");
}
catch (NotSupportedException)
{
}
try
{
readOnlyList.LastIndexOf(1111);
}
catch (NotSupportedException)
{
Assertion.Fail("readOnlyList.LastIndexOf(1)");
}
try
{
readOnlyList.Remove(1);
Assertion.Fail("readOnlyList.Remove(1)");
}
catch (NotSupportedException)
{
}
try
{
readOnlyList.RemoveAt(1);
Assertion.Fail("readOnlyList.RemoveAt(1)");
}
catch (NotSupportedException)
{
}
try
{
readOnlyList.RemoveRange(0, 1);
Assertion.Fail("readOnlyList.RemoveRange(0, 1)");
}
catch (NotSupportedException)
{
}
try
{
readOnlyList.Reverse();
Assertion.Fail("readOnlyList.Reverse()");
}
catch (NotSupportedException)
{
}
try
{
readOnlyList.SetRange(0, new Object[] {0, 1});
Assertion.Fail("readOnlyList.SetRange(0, new Object[] {0, 1})");
}
catch (NotSupportedException)
{
}
try
{
readOnlyList.Sort();
Assertion.Fail("readOnlyList.Sort()");
}
catch (NotSupportedException)
{
}
try
{
readOnlyList.ToArray();
}
catch (NotSupportedException)
{
Assertion.Fail("readOnlyList.ToArray()");
}
try
{
readOnlyList.TrimToSize();
Assertion.Fail("readOnlyList.TrimToSize()");
}
catch (NotSupportedException)
{
}
}
[Test]
public void TestFixedSize()
{
ArrayList arrayList, fixedSizeList;
arrayList = new ArrayList();
fixedSizeList = ArrayList.FixedSize(arrayList);
arrayList.AddRange(c_TestData);
// Make sure the fixedSizeList is a wrapper and not a clone.
arrayList.Add(10);
Assertion.Assert("fixedSizeList.Count == 11", fixedSizeList.Count == 11);
try
{
fixedSizeList.Add(0);
Assertion.Fail("fixedSizeList.Add(0)");
}
catch (NotSupportedException)
{
}
try
{
fixedSizeList.Remove(0);
Assertion.Fail("fixedSizeList.Remove(0)");
}
catch (NotSupportedException)
{
}
try
{
fixedSizeList.RemoveAt(0);
Assertion.Fail("fixedSizeList.RemoveAt(0)");
}
catch (NotSupportedException)
{
}
try
{
fixedSizeList.Clear();
Assertion.Fail("fixedSizeList.Clear()");
}
catch (NotSupportedException)
{
}
try
{
fixedSizeList[0] = 0;
}
catch (NotSupportedException)
{
Assertion.Fail("fixedSizeList[0] = 0");
}
try
{
fixedSizeList.Clear();
Assertion.Fail("fixedSizeList.Clear()");
}
catch (NotSupportedException)
{
}
try
{
fixedSizeList.Contains(1);
}
catch (NotSupportedException)
{
Assertion.Fail("fixedSizeList.Contains");
}
try
{
int x = fixedSizeList.Count;
}
catch (NotSupportedException)
{
Assertion.Fail("fixedSizeList.Count");
}
try
{
fixedSizeList.GetRange(0, 1);
}
catch (NotSupportedException)
{
Assertion.Fail("fixedSizeList.GetRange(0, 1)");
}
try
{
fixedSizeList.IndexOf(0);
}
catch (NotSupportedException)
{
Assertion.Fail("fixedSizeList.IndexOf(0)");
}
try
{
fixedSizeList.InsertRange(0, new object[] {1,2});
Assertion.Fail("fixedSizeList.InsertRange(0, new object[] {1,2})");
}
catch (NotSupportedException)
{
}
try
{
fixedSizeList.Reverse();
}
catch (NotSupportedException)
{
Assertion.Fail("fixedSizeList.Reverse()");
}
try
{
fixedSizeList.SetRange(0, new Object[] {0, 1});
}
catch (NotSupportedException)
{
Assertion.Fail("fixedSizeList.SetRange(0, new Object[] {0, 1})");
}
try
{
fixedSizeList.Sort();
}
catch (NotSupportedException)
{
Assertion.Fail("fixedSizeList.Sort()");
}
try
{
fixedSizeList.ToArray();
}
catch (NotSupportedException)
{
Assertion.Fail("fixedSizeList.ToArray()");
}
try
{
fixedSizeList.TrimToSize();
Assertion.Fail("fixedSizeList.TrimToSize()");
}
catch (NotSupportedException)
{
}
try
{
fixedSizeList.Clone();
}
catch (NotSupportedException)
{
Assertion.Fail("fixedSizeList.Clone()");
}
try
{
fixedSizeList.AddRange(c_TestData);
Assertion.Fail("fixedSizeList.AddRange(c_TestData)");
}
catch (NotSupportedException)
{
}
}
private void PrivateTestClone(ArrayList arrayList)
{
ArrayList arrayList2;
arrayList.AddRange(c_TestData);
arrayList2 = (ArrayList)arrayList.Clone();
VerifyContains(arrayList2, c_TestData, "arrayList.Clone()");
}
[Test]
public void TestCloneStandard()
{
PrivateTestClone(new ArrayList());
}
[Test]
public void TestCloneSynchronized()
{
PrivateTestClone(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestCloneAdapter()
{
PrivateTestClone(ArrayList.Adapter(new ArrayList()));
}
[Test]
public void TestCloneGetRange()
{
PrivateTestClone(new ArrayList().GetRange(0, 0));
}
private void PrivateTestCopyTo(ArrayList arrayList)
{
object[] array;
arrayList.AddRange(c_TestData);
array = new Object[arrayList.Count];
arrayList.CopyTo(array);
VerifyContains(array, new object[] {0,1,2,3,4,5,6,7,8,9}, "ArrayList.CopyTo(array)");
array = new Object[3];
arrayList.CopyTo(0, array, 0, 3);
VerifyContains(array, new object[] {0,1,2}, "ArrayList.CopyTo(0, array, 0, 3)");
array = new Object[4];
arrayList.CopyTo(0, array, 1, 3);
VerifyContains(array, new object[] {null,0, 1, 2}, "ArrayList.CopyTo(0, array, 1, 3)");
array = new object[10];
arrayList.CopyTo(3, array, 3, 5);
VerifyContains(array, new object[] {null, null, null, 3, 4, 5, 6, 7, null, null}, "VerifyContains(array, ...)");
}
[Test]
public void TestCopyToStandard()
{
PrivateTestCopyTo(new ArrayList());
}
[Test]
public void TestCopyToSynchronized()
{
PrivateTestCopyTo(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestCopyToAdapter()
{
PrivateTestCopyTo(ArrayList.Adapter(new ArrayList()));
}
[Test]
public void TestCopyToGetRange()
{
PrivateTestCopyTo(new ArrayList().GetRange(0, 0));
}
private void PrivateTestSetCapacity(ArrayList arrayList)
{
int x;
arrayList.AddRange(c_TestData);
x = arrayList.Capacity;
arrayList.Capacity = x * 2;
Assert("arrayList.Capacity == x * 2", arrayList.Capacity == x * 2);
VerifyContains(arrayList, c_TestData, "VerifyContains(arrayList, c_TestData)");
}
[Test]
public void TestSetCapacity()
{
PrivateTestSetCapacity(new ArrayList());
}
[Test]
public void TestSetCapacitySynchronized()
{
PrivateTestSetCapacity(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestCapacityExpands()
{
ArrayList arrayList = new ArrayList(10);
arrayList.AddRange(c_TestData);
Assertion.Assert("arrayList.Capacity == 10", arrayList.Capacity == 10);
arrayList.Add(10);
Assertion.Assert("arrayList.Capacity == 20", arrayList.Capacity == 20);
VerifyContains(arrayList, new object[] {0,1,2,3,4,5,6,7,8,9,10}, "VerifyContains");
}
private void PrivateTestBinarySearch(ArrayList arrayList)
{
// Try searching with different size lists...
for (int x = 0; x < 10; x++)
{
for (int i = 0; i < x; i++)
{
arrayList.Add(i);
}
for (int i = 0; i < x; i++)
{
int y;
y = arrayList.BinarySearch(i);
Assertion.Equals(y, i);
}
}
arrayList.Clear();
arrayList.Add(new object());
try
{
arrayList.BinarySearch(new object());
Assertion.Fail("1: Binary search on object that doesn't support IComparable.");
}
catch (ArgumentException)
{
}
catch (InvalidOperationException)
{
// LAMESPEC: ArrayList.BinarySearch() on MS.NET throws InvalidOperationException
}
try
{
arrayList.BinarySearch(1);
Assertion.Fail("2: Binary search on incompatible object.");
}
catch (ArgumentException)
{
}
catch (InvalidOperationException)
{
// LAMESPEC: ArrayList.BinarySearch() on MS.NET throws InvalidOperationException
}
arrayList.Clear();
for (int i = 0; i < 100; i++)
{
arrayList.Add(1);
}
Assertion.Assert("BinarySearch should start in middle.", arrayList.BinarySearch(1) == 49);
Assertion.Assert("arrayList.BinarySearch(0, 0, 0, Comparer.Default)", arrayList.BinarySearch(0, 0, 0, Comparer.Default) == -1);
}
[Test]
public void TestBinarySearchStandard()
{
PrivateTestBinarySearch(new ArrayList());
}
[Test]
public void TestBinarySearchSynchronized()
{
PrivateTestBinarySearch(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestBinarySearchAdapter()
{
PrivateTestBinarySearch(ArrayList.Adapter(new ArrayList()));
}
[Test]
public void TestBinarySearchGetRange()
{
PrivateTestBinarySearch(new ArrayList().GetRange(0, 0));
}
private void PrivateTestRemoveAt(ArrayList arrayList)
{
arrayList.Add(1);
arrayList.Add(2);
arrayList.Add(3);
arrayList.Add(4);
arrayList.Add(5);
arrayList.Remove(2);
VerifyContains(arrayList, new object[] {1, 3, 4, 5},
"Remove element failed.");
arrayList.RemoveAt(0);
VerifyContains(arrayList, new object[] {3, 4, 5},
"RemoveAt at start failed.");
arrayList.RemoveAt(2);
VerifyContains(arrayList, new object[] {3, 4},
"RemoveAt at end failed.");
}
[Test]
public void TestRemoveAtStandard()
{
PrivateTestRemoveAt(new ArrayList());
}
[Test]
public void TestRemoveAtSynchronized()
{
PrivateTestRemoveAt(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestRemoveAtAdapter()
{
PrivateTestRemoveAt(ArrayList.Adapter(new ArrayList()));
}
[Test]
public void TestRemoveAtGetRange()
{
PrivateTestRemoveAt(new ArrayList().GetRange(0, 0));
}
private void PrivateTestRemoveRange(ArrayList arrayList)
{
arrayList.AddRange(c_TestData);
arrayList.RemoveRange(0, 3);
VerifyContains(arrayList, new object[] { 3, 4, 5, 6, 7, 8, 9 },
"RemoveRange at start failed.");
arrayList.RemoveRange(4, 3);
VerifyContains(arrayList, new object[] { 3, 4, 5, 6 },
"RemoveRange at start failed.");
arrayList.RemoveRange(2, 1);
VerifyContains(arrayList, new object[] { 3, 4, 6 },
"RemoveRange in middle failed.");
}
[Test]
public void TestRemoveRangeStandard()
{
PrivateTestRemoveRange(new ArrayList());
}
[Test]
public void TestRemoveRangeSynchronized()
{
PrivateTestRemoveRange(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestRemoveRangeAdapter()
{
PrivateTestRemoveRange(ArrayList.Adapter(new ArrayList()));
}
[Test]
public void TestRemoveRangeGetRange()
{
PrivateTestRemoveRange(new ArrayList().GetRange(0, 0));
}
private void PrivateTestInsert(ArrayList arrayList)
{
arrayList.Add(1);
arrayList.Add(2);
arrayList.Add(3);
arrayList.Add(4);
arrayList.Insert(0, 1);
VerifyContains(arrayList, new object[] {1, 1, 2, 3, 4}, "Insert at beginning failed.");
arrayList.Insert(5, 5);
VerifyContains(arrayList, new object[] {1, 1, 2, 3, 4, 5}, "Insert at end failed.");
arrayList.Insert(3, 7);
VerifyContains(arrayList, new object[] {1, 1, 2, 7, 3, 4, 5}, "Insert in middle failed.");
}
[Test]
public void TestInsertStandard()
{
PrivateTestInsert(new ArrayList());
}
[Test]
public void TestInsertAdapter()
{
PrivateTestInsert(ArrayList.Adapter(new ArrayList()));
}
[Test]
public void TestInsertSynchronized()
{
PrivateTestInsert(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestInsertGetRange()
{
PrivateTestInsert(new ArrayList().GetRange(0, 0));
}
private void PrivateTestGetRange(ArrayList arrayList)
{
ArrayList rangeList;
arrayList.AddRange(c_TestData);
rangeList = arrayList.GetRange(3, 5);
Assertion.Assert("rangeList.Count == 5", rangeList.Count == 5);
this.VerifyContains(rangeList, new object[] {3,4,5,6,7}, "1: VerifyContains(rangeList)");
//FIXME: If items are removed from the Range, one may not iterate over it on .NET
/*
rangeList.Remove(7);
this.VerifyContains(a2, new object[] {3,4,5,6}, "2: VerifyContains(rangeList)");
rangeList.RemoveAt(0);
this.VerifyContains(a3, new object[] {4,5,6}, "3: VerifyContains(rangeList)");
rangeList.Add(7);
rangeList.Add(6);
rangeList.Add(3);
rangeList.Add(11);
Assertion.Assert("rangeList.LastIndexOf(6) == 4", rangeList.LastIndexOf(6) == 4);
rangeList.Sort();
this.VerifyContains(arrayList, new object[] {0, 1, 2, 3, 4, 5, 6, 6, 7, 11, 8, 9}, "4: VerifyContains(rangeList)");
*/
}
[Test]
public void TestGetRangeStandard()
{
PrivateTestGetRange(new ArrayList());
}
[Test]
public void TestGetRangeAdapter()
{
PrivateTestGetRange(ArrayList.Adapter(new ArrayList()));
}
[Test]
public void TestGetRangeSynchronized()
{
PrivateTestGetRange(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestGetRangeGetRange()
{
PrivateTestGetRange(new ArrayList().GetRange(0, 0));
}
private void PrivateTestEnumeratorWithRange(ArrayList arrayList)
{
IEnumerator enumerator;
arrayList.AddRange(c_TestData);
int x;
// Test with the range 1 - 3
enumerator = arrayList.GetEnumerator(1, 3);
x = 1;
while (enumerator.MoveNext())
{
Assertion.Assert("enumerator.Current == x", (int)enumerator.Current == x);
x++;
}
enumerator.Reset();
x = 1;
while (enumerator.MoveNext())
{
Assertion.Assert("enumerator.Current == x", (int)enumerator.Current == x);
x++;
}
// Test with a range covering the whole list.
enumerator = arrayList.GetEnumerator(0, arrayList.Count);
x = 0;
while (enumerator.MoveNext())
{
Assertion.Assert("enumerator.Current == x", (int)enumerator.Current == x);
x++;
}
enumerator.Reset();
x = 0;
while (enumerator.MoveNext())
{
Assertion.Assert("enumerator.Current == x", (int)enumerator.Current == x);
x++;
}
// Test with a range covering nothing.
enumerator = arrayList.GetEnumerator(arrayList.Count, 0);
Assertion.Assert("!enumerator.MoveNext()", !enumerator.MoveNext());
enumerator.Reset();
Assertion.Assert("!enumerator.MoveNext()", !enumerator.MoveNext());
}
[Test]
public void TestEnumeratorWithRangeStandard()
{
PrivateTestEnumeratorWithRange(new ArrayList());
}
[Test]
public void TestEnumeratorWithRangeSynchronized()
{
PrivateTestEnumeratorWithRange(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestEnumeratorWithRangeAdapter()
{
PrivateTestEnumeratorWithRange(ArrayList.Adapter(new ArrayList()));
}
[Test]
public void TestEnumeratorWithRangeGetRange()
{
PrivateTestEnumeratorWithRange(new ArrayList().GetRange(0, 0));
}
private void PrivateTestEnumerator(ArrayList arrayList)
{
int x = 0;
arrayList.AddRange(c_TestData);
x = 0;
foreach (object o in arrayList)
{
if (!o.Equals(x))
{
Assertion.Fail("Arraylist.GetEnumerator()");
break;
}
x++;
}
IEnumerator enumerator;
enumerator = arrayList.GetEnumerator();
enumerator.MoveNext();
Assert("enumerator.Current == 0", (int)enumerator.Current == 0);
// Invalidate the enumerator.
arrayList.Add(10);
try
{
// According to the spec this should still work even though the enumerator is invalid.
Assert("enumerator.Current == 0", (int)enumerator.Current == 0);
}
catch (InvalidOperationException)
{
Assert("enumerator.Current should not fail.", false);
}
try
{
// This should throw an InvalidOperationException.
enumerator.MoveNext();
Assert("enumerator.Current should fail.", false);
}
catch (InvalidOperationException)
{
}
}
[Test]
public void TestEnumeratorStandard()
{
PrivateTestEnumerator(new ArrayList());
}
[Test]
public void TestEnumeratorSynchronized()
{
PrivateTestEnumerator(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestEnumeratorAdapter()
{
PrivateTestEnumerator(ArrayList.Adapter(new ArrayList()));
}
[Test]
public void TestEnumeratorGetRange()
{
PrivateTestEnumerator(new ArrayList().GetRange(0, 0));
}
private void PrivateTestReverse(ArrayList arrayList)
{
ArrayList arrayList2;
for (int x = 1; x < 100; x ++)
{
arrayList2 = (ArrayList)arrayList.Clone();
for (int i = 0; i < x; i++)
{
arrayList2.Add(i);
}
arrayList2.Reverse();
bool ok = true;
// Check that reverse did reverse the adapter.
for (int i = 0; i < x; i++)
{
if ((int)arrayList2[i] != x - i - 1)
{
ok = false;
break;
}
}
Assertion.Assert
(
String.Format("Reverse on arrayList failed on list with {0} items.", x),
ok
);
}
}
[Test]
public void TestReverseStandard()
{
PrivateTestReverse(new ArrayList());
}
[Test]
public void TestReverseAdapter()
{
ArrayList arrayList = new ArrayList();
ArrayList adapter = ArrayList.Adapter(arrayList);
PrivateTestReverse(adapter);
VerifyContains(adapter, arrayList, "Changing adapter didn't change ArrayList.");
}
[Test]
public void TestReverseSynchronized()
{
PrivateTestReverse(ArrayList.Synchronized(new ArrayList()));
}
[Test]
public void TestReverseGetRange()
{
PrivateTestReverse(new ArrayList().GetRange(0,0));
}
[Test]
public void TestIterator ()
{
ArrayList a = new ArrayList ();
a.Add (1);
a.Add (2);
a.Add (3);
int total = 0;
foreach (int b in a)
total += b;
Assert ("Count should be 6", total == 6);
}
[Test]
public void TestIteratorObjects ()
{
ArrayList a = new ArrayList ();
a.Add (1);
a.Add (null);
a.Add (3);
int total = 0;
int count = 0;
bool found_null = false;
foreach (object b in a){
count++;
if (b == null){
if (found_null)
Assert ("Should only find one null", false);
found_null = true;
} else {
total += (int) b;
}
}
Assert ("Should fine one null", found_null);
Assert ("Total should be 4", total == 4);
Assert ("Count should be 3", count == 3);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
namespace System
{
public abstract partial class Type : MemberInfo, IReflect
{
protected Type() { }
public override MemberTypes MemberType => MemberTypes.TypeInfo;
public new Type GetType() => base.GetType();
public abstract string? Namespace { get; }
public abstract string? AssemblyQualifiedName { get; }
public abstract string? FullName { get; }
public abstract Assembly Assembly { get; }
public abstract new Module Module { get; }
public bool IsNested => DeclaringType != null;
public override Type? DeclaringType => null;
public virtual MethodBase? DeclaringMethod => null;
public override Type? ReflectedType => null;
public abstract Type UnderlyingSystemType { get; }
public virtual bool IsTypeDefinition { get { throw NotImplemented.ByDesign; } }
public bool IsArray => IsArrayImpl();
protected abstract bool IsArrayImpl();
public bool IsByRef => IsByRefImpl();
protected abstract bool IsByRefImpl();
public bool IsPointer => IsPointerImpl();
protected abstract bool IsPointerImpl();
public virtual bool IsConstructedGenericType { get { throw NotImplemented.ByDesign; } }
public virtual bool IsGenericParameter => false;
public virtual bool IsGenericTypeParameter => IsGenericParameter && DeclaringMethod is null;
public virtual bool IsGenericMethodParameter => IsGenericParameter && DeclaringMethod != null;
public virtual bool IsGenericType => false;
public virtual bool IsGenericTypeDefinition => false;
public virtual bool IsSZArray { get { throw NotImplemented.ByDesign; } }
public virtual bool IsVariableBoundArray => IsArray && !IsSZArray;
public virtual bool IsByRefLike => throw new NotSupportedException(SR.NotSupported_SubclassOverride);
public bool HasElementType => HasElementTypeImpl();
protected abstract bool HasElementTypeImpl();
public abstract Type? GetElementType();
public virtual int GetArrayRank() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public virtual Type GetGenericTypeDefinition() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public virtual Type[] GenericTypeArguments => (IsGenericType && !IsGenericTypeDefinition) ? GetGenericArguments() : Array.Empty<Type>();
public virtual Type[] GetGenericArguments() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public virtual int GenericParameterPosition { get { throw new InvalidOperationException(SR.Arg_NotGenericParameter); } }
public virtual GenericParameterAttributes GenericParameterAttributes { get { throw new NotSupportedException(); } }
public virtual Type[] GetGenericParameterConstraints()
{
if (!IsGenericParameter)
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
throw new InvalidOperationException();
}
public TypeAttributes Attributes => GetAttributeFlagsImpl();
protected abstract TypeAttributes GetAttributeFlagsImpl();
public bool IsAbstract => (GetAttributeFlagsImpl() & TypeAttributes.Abstract) != 0;
public bool IsImport => (GetAttributeFlagsImpl() & TypeAttributes.Import) != 0;
public bool IsSealed => (GetAttributeFlagsImpl() & TypeAttributes.Sealed) != 0;
public bool IsSpecialName => (GetAttributeFlagsImpl() & TypeAttributes.SpecialName) != 0;
public bool IsClass => (GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Class && !IsValueType;
public bool IsNestedAssembly => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedAssembly;
public bool IsNestedFamANDAssem => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamANDAssem;
public bool IsNestedFamily => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamily;
public bool IsNestedFamORAssem => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamORAssem;
public bool IsNestedPrivate => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate;
public bool IsNestedPublic => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic;
public bool IsNotPublic => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic;
public bool IsPublic => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.Public;
public bool IsAutoLayout => (GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.AutoLayout;
public bool IsExplicitLayout => (GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.ExplicitLayout;
public bool IsLayoutSequential => (GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.SequentialLayout;
public bool IsAnsiClass => (GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AnsiClass;
public bool IsAutoClass => (GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AutoClass;
public bool IsUnicodeClass => (GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.UnicodeClass;
public bool IsCOMObject => IsCOMObjectImpl();
protected abstract bool IsCOMObjectImpl();
public bool IsContextful => IsContextfulImpl();
protected virtual bool IsContextfulImpl() => false;
public virtual bool IsEnum => IsSubclassOf(typeof(Enum));
public bool IsMarshalByRef => IsMarshalByRefImpl();
protected virtual bool IsMarshalByRefImpl() => false;
public bool IsPrimitive => IsPrimitiveImpl();
protected abstract bool IsPrimitiveImpl();
public bool IsValueType => IsValueTypeImpl();
protected virtual bool IsValueTypeImpl() => IsSubclassOf(typeof(ValueType));
public virtual bool IsSignatureType => false;
public virtual bool IsSecurityCritical { get { throw NotImplemented.ByDesign; } }
public virtual bool IsSecuritySafeCritical { get { throw NotImplemented.ByDesign; } }
public virtual bool IsSecurityTransparent { get { throw NotImplemented.ByDesign; } }
public virtual StructLayoutAttribute? StructLayoutAttribute { get { throw new NotSupportedException(); } }
public ConstructorInfo? TypeInitializer => GetConstructorImpl(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, CallingConventions.Any, Type.EmptyTypes, null);
public ConstructorInfo? GetConstructor(Type[] types) => GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, types, null);
public ConstructorInfo? GetConstructor(BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) => GetConstructor(bindingAttr, binder, CallingConventions.Any, types, modifiers);
public ConstructorInfo? GetConstructor(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers)
{
if (types == null)
throw new ArgumentNullException(nameof(types));
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
throw new ArgumentNullException(nameof(types));
}
return GetConstructorImpl(bindingAttr, binder, callConvention, types, modifiers);
}
protected abstract ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers);
public ConstructorInfo[] GetConstructors() => GetConstructors(BindingFlags.Public | BindingFlags.Instance);
public abstract ConstructorInfo[] GetConstructors(BindingFlags bindingAttr);
public EventInfo? GetEvent(string name) => GetEvent(name, Type.DefaultLookup);
public abstract EventInfo? GetEvent(string name, BindingFlags bindingAttr);
public virtual EventInfo[] GetEvents() => GetEvents(Type.DefaultLookup);
public abstract EventInfo[] GetEvents(BindingFlags bindingAttr);
public FieldInfo? GetField(string name) => GetField(name, Type.DefaultLookup);
public abstract FieldInfo? GetField(string name, BindingFlags bindingAttr);
public FieldInfo[] GetFields() => GetFields(Type.DefaultLookup);
public abstract FieldInfo[] GetFields(BindingFlags bindingAttr);
public MemberInfo[] GetMember(string name) => GetMember(name, Type.DefaultLookup);
public virtual MemberInfo[] GetMember(string name, BindingFlags bindingAttr) => GetMember(name, MemberTypes.All, bindingAttr);
public virtual MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public MemberInfo[] GetMembers() => GetMembers(Type.DefaultLookup);
public abstract MemberInfo[] GetMembers(BindingFlags bindingAttr);
public MethodInfo? GetMethod(string name) => GetMethod(name, Type.DefaultLookup);
public MethodInfo? GetMethod(string name, BindingFlags bindingAttr)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return GetMethodImpl(name, bindingAttr, null, CallingConventions.Any, null, null);
}
public MethodInfo? GetMethod(string name, Type[] types) => GetMethod(name, types, null);
public MethodInfo? GetMethod(string name, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, Type.DefaultLookup, null, types, modifiers);
public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, bindingAttr, binder, CallingConventions.Any, types, modifiers);
public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (types == null)
throw new ArgumentNullException(nameof(types));
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
throw new ArgumentNullException(nameof(types));
}
return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
}
protected abstract MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers);
public MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types) => GetMethod(name, genericParameterCount, types, null);
public MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, genericParameterCount, Type.DefaultLookup, null, types, modifiers);
public MethodInfo? GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, genericParameterCount, bindingAttr, binder, CallingConventions.Any, types, modifiers);
public MethodInfo? GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (genericParameterCount < 0)
throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(genericParameterCount));
if (types == null)
throw new ArgumentNullException(nameof(types));
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
throw new ArgumentNullException(nameof(types));
}
return GetMethodImpl(name, genericParameterCount, bindingAttr, binder, callConvention, types, modifiers);
}
protected virtual MethodInfo? GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) => throw new NotSupportedException();
public MethodInfo[] GetMethods() => GetMethods(Type.DefaultLookup);
public abstract MethodInfo[] GetMethods(BindingFlags bindingAttr);
public Type? GetNestedType(string name) => GetNestedType(name, Type.DefaultLookup);
public abstract Type? GetNestedType(string name, BindingFlags bindingAttr);
public Type[] GetNestedTypes() => GetNestedTypes(Type.DefaultLookup);
public abstract Type[] GetNestedTypes(BindingFlags bindingAttr);
public PropertyInfo? GetProperty(string name) => GetProperty(name, Type.DefaultLookup);
public PropertyInfo? GetProperty(string name, BindingFlags bindingAttr)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return GetPropertyImpl(name, bindingAttr, null, null, null, null);
}
public PropertyInfo? GetProperty(string name, Type? returnType)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return GetPropertyImpl(name, Type.DefaultLookup, null, returnType, null, null);
}
public PropertyInfo? GetProperty(string name, Type[] types) => GetProperty(name, null, types);
public PropertyInfo? GetProperty(string name, Type? returnType, Type[] types) => GetProperty(name, returnType, types, null);
public PropertyInfo? GetProperty(string name, Type? returnType, Type[] types, ParameterModifier[]? modifiers) => GetProperty(name, Type.DefaultLookup, null, returnType, types, modifiers);
public PropertyInfo? GetProperty(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[] types, ParameterModifier[]? modifiers)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (types == null)
throw new ArgumentNullException(nameof(types));
return GetPropertyImpl(name, bindingAttr, binder, returnType, types, modifiers);
}
protected abstract PropertyInfo? GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers);
public PropertyInfo[] GetProperties() => GetProperties(Type.DefaultLookup);
public abstract PropertyInfo[] GetProperties(BindingFlags bindingAttr);
public virtual MemberInfo[] GetDefaultMembers() { throw NotImplemented.ByDesign; }
public virtual RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
public static RuntimeTypeHandle GetTypeHandle(object o)
{
if (o == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
Type type = o.GetType();
return type.TypeHandle;
}
public static Type[] GetTypeArray(object[] args)
{
if (args == null)
throw new ArgumentNullException(nameof(args));
Type[] cls = new Type[args.Length];
for (int i = 0; i < cls.Length; i++)
{
if (args[i] == null)
throw new ArgumentNullException();
cls[i] = args[i].GetType();
}
return cls;
}
public static TypeCode GetTypeCode(Type? type)
{
if (type == null)
return TypeCode.Empty;
return type.GetTypeCodeImpl();
}
protected virtual TypeCode GetTypeCodeImpl()
{
Type systemType = UnderlyingSystemType;
if (this != systemType && systemType != null)
return Type.GetTypeCode(systemType);
return TypeCode.Object;
}
public abstract Guid GUID { get; }
public static Type? GetTypeFromCLSID(Guid clsid) => GetTypeFromCLSID(clsid, null, throwOnError: false);
public static Type? GetTypeFromCLSID(Guid clsid, bool throwOnError) => GetTypeFromCLSID(clsid, null, throwOnError: throwOnError);
public static Type? GetTypeFromCLSID(Guid clsid, string? server) => GetTypeFromCLSID(clsid, server, throwOnError: false);
public static Type? GetTypeFromProgID(string progID) => GetTypeFromProgID(progID, null, throwOnError: false);
public static Type? GetTypeFromProgID(string progID, bool throwOnError) => GetTypeFromProgID(progID, null, throwOnError: throwOnError);
public static Type? GetTypeFromProgID(string progID, string? server) => GetTypeFromProgID(progID, server, throwOnError: false);
public abstract Type? BaseType { get; }
[DebuggerHidden]
[DebuggerStepThrough]
public object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args) => InvokeMember(name, invokeAttr, binder, target, args, null, null, null);
[DebuggerHidden]
[DebuggerStepThrough]
public object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, CultureInfo? culture) => InvokeMember(name, invokeAttr, binder, target, args, null, culture, null);
public abstract object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters);
public Type? GetInterface(string name) => GetInterface(name, ignoreCase: false);
public abstract Type? GetInterface(string name, bool ignoreCase);
public abstract Type[] GetInterfaces();
public virtual InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public virtual bool IsInstanceOfType(object? o) => o == null ? false : IsAssignableFrom(o.GetType());
public virtual bool IsEquivalentTo(Type? other) => this == other;
public virtual Type GetEnumUnderlyingType()
{
if (!IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
FieldInfo[] fields = GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (fields == null || fields.Length != 1)
throw new ArgumentException(SR.Argument_InvalidEnum, "enumType");
return fields[0].FieldType;
}
public virtual Array GetEnumValues()
{
if (!IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
// We don't support GetEnumValues in the default implementation because we cannot create an array of
// a non-runtime type. If there is strong need we can consider returning an object or int64 array.
throw NotImplemented.ByDesign;
}
public virtual Type MakeArrayType() { throw new NotSupportedException(); }
public virtual Type MakeArrayType(int rank) { throw new NotSupportedException(); }
public virtual Type MakeByRefType() { throw new NotSupportedException(); }
public virtual Type MakeGenericType(params Type[] typeArguments) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public virtual Type MakePointerType() { throw new NotSupportedException(); }
public static Type MakeGenericSignatureType(Type genericTypeDefinition, params Type[] typeArguments) => new SignatureConstructedGenericType(genericTypeDefinition, typeArguments);
public static Type MakeGenericMethodParameter(int position)
{
if (position < 0)
throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(position));
return new SignatureGenericMethodParameterType(position);
}
public override string ToString() => "Type: " + Name; // Why do we add the "Type: " prefix?
public override bool Equals(object? o) => o == null ? false : Equals(o as Type);
public override int GetHashCode()
{
Type systemType = UnderlyingSystemType;
if (!object.ReferenceEquals(systemType, this))
return systemType.GetHashCode();
return base.GetHashCode();
}
public virtual bool Equals(Type? o) => o == null ? false : object.ReferenceEquals(this.UnderlyingSystemType, o.UnderlyingSystemType);
public static Type? ReflectionOnlyGetType(string typeName, bool throwIfNotFound, bool ignoreCase) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); }
public static Binder DefaultBinder
{
get
{
if (s_defaultBinder == null)
{
DefaultBinder binder = new DefaultBinder();
Interlocked.CompareExchange<Binder?>(ref s_defaultBinder, binder, null);
}
return s_defaultBinder!;
}
}
private static volatile Binder? s_defaultBinder;
public static readonly char Delimiter = '.';
public static readonly Type[] EmptyTypes = Array.Empty<Type>();
public static readonly object Missing = System.Reflection.Missing.Value;
public static readonly MemberFilter FilterAttribute = FilterAttributeImpl!;
public static readonly MemberFilter FilterName = (m, c) => FilterNameImpl(m, c!, StringComparison.Ordinal);
public static readonly MemberFilter FilterNameIgnoreCase = (m, c) => FilterNameImpl(m, c!, StringComparison.OrdinalIgnoreCase);
private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
using System;
namespace HoloToolkit.Unity.InputModule
{
/// <summary>
/// Component that allows dragging an object with your hand on HoloLens.
/// Dragging is done by calculating the angular delta and z-delta between the current and previous hand positions,
/// and then repositioning the object based on that.
/// </summary>
public class HandDraggable : MonoBehaviour, IFocusable, IInputHandler, ISourceStateHandler
{
/// <summary>
/// Event triggered when dragging starts.
/// </summary>
public event Action StartedDragging;
/// <summary>
/// Event triggered when dragging stops.
/// </summary>
public event Action StoppedDragging;
[Tooltip("Transform that will be dragged. Defaults to the object of the component.")]
public Transform HostTransform;
[Tooltip("Scale by which hand movement in z is multiplied to move the dragged object.")]
public float DistanceScale = 2f;
public enum RotationModeEnum
{
Default,
LockObjectRotation,
OrientTowardUser,
OrientTowardUserAndKeepUpright
}
public RotationModeEnum RotationMode = RotationModeEnum.Default;
[Tooltip("Controls the speed at which the object will interpolate toward the desired position")]
[Range(0.01f, 1.0f)]
public float PositionLerpSpeed = 0.2f;
[Tooltip("Controls the speed at which the object will interpolate toward the desired rotation")]
[Range(0.01f, 1.0f)]
public float RotationLerpSpeed = 0.2f;
public bool IsDraggingEnabled = true;
private bool isDragging;
private bool isGazed;
private Vector3 objRefForward;
private Vector3 objRefUp;
private float objRefDistance;
private Quaternion gazeAngularOffset;
private float handRefDistance;
private Vector3 objRefGrabPoint;
private Vector3 draggingPosition;
private Quaternion draggingRotation;
private IInputSource currentInputSource;
private uint currentInputSourceId;
private void Start()
{
if (HostTransform == null)
{
HostTransform = transform;
}
}
private void OnDestroy()
{
if (isDragging)
{
StopDragging();
}
if (isGazed)
{
OnFocusExit();
}
}
private void Update()
{
if (IsDraggingEnabled && isDragging)
{
UpdateDragging();
}
}
/// <summary>
/// Starts dragging the object.
/// </summary>
public void StartDragging(Vector3 initialDraggingPosition)
{
if (!IsDraggingEnabled)
{
return;
}
if (isDragging)
{
return;
}
// TODO: robertes: Fix push/pop and single-handler model so that multiple HandDraggable components
// can be active at once.
// Add self as a modal input handler, to get all inputs during the manipulation
InputManager.Instance.PushModalInputHandler(gameObject);
isDragging = true;
Transform cameraTransform = CameraCache.Main.transform;
Vector3 handPosition;
currentInputSource.TryGetGripPosition(currentInputSourceId, out handPosition);
Vector3 pivotPosition = GetHandPivotPosition(cameraTransform);
handRefDistance = Vector3.Magnitude(handPosition - pivotPosition);
objRefDistance = Vector3.Magnitude(initialDraggingPosition - pivotPosition);
Vector3 objForward = HostTransform.forward;
Vector3 objUp = HostTransform.up;
// Store where the object was grabbed from
objRefGrabPoint = cameraTransform.transform.InverseTransformDirection(HostTransform.position - initialDraggingPosition);
Vector3 objDirection = Vector3.Normalize(initialDraggingPosition - pivotPosition);
Vector3 handDirection = Vector3.Normalize(handPosition - pivotPosition);
objForward = cameraTransform.InverseTransformDirection(objForward); // in camera space
objUp = cameraTransform.InverseTransformDirection(objUp); // in camera space
objDirection = cameraTransform.InverseTransformDirection(objDirection); // in camera space
handDirection = cameraTransform.InverseTransformDirection(handDirection); // in camera space
objRefForward = objForward;
objRefUp = objUp;
// Store the initial offset between the hand and the object, so that we can consider it when dragging
gazeAngularOffset = Quaternion.FromToRotation(handDirection, objDirection);
draggingPosition = initialDraggingPosition;
StartedDragging.RaiseEvent();
}
/// <summary>
/// Gets the pivot position for the hand, which is approximated to the base of the neck.
/// </summary>
/// <returns>Pivot position for the hand.</returns>
private Vector3 GetHandPivotPosition(Transform cameraTransform)
{
Vector3 pivot = cameraTransform.position + new Vector3(0, -0.2f, 0) - cameraTransform.forward * 0.2f; // a bit lower and behind
return pivot;
}
/// <summary>
/// Enables or disables dragging.
/// </summary>
/// <param name="isEnabled">Indicates whether dragging should be enabled or disabled.</param>
public void SetDragging(bool isEnabled)
{
if (IsDraggingEnabled == isEnabled)
{
return;
}
IsDraggingEnabled = isEnabled;
if (isDragging)
{
StopDragging();
}
}
/// <summary>
/// Update the position of the object being dragged.
/// </summary>
private void UpdateDragging()
{
Vector3 newHandPosition;
Transform cameraTransform = CameraCache.Main.transform;
currentInputSource.TryGetGripPosition(currentInputSourceId, out newHandPosition);
Vector3 pivotPosition = GetHandPivotPosition(cameraTransform);
Vector3 newHandDirection = Vector3.Normalize(newHandPosition - pivotPosition);
newHandDirection = cameraTransform.InverseTransformDirection(newHandDirection); // in camera space
Vector3 targetDirection = Vector3.Normalize(gazeAngularOffset * newHandDirection);
targetDirection = cameraTransform.TransformDirection(targetDirection); // back to world space
float currentHandDistance = Vector3.Magnitude(newHandPosition - pivotPosition);
float distanceRatio = currentHandDistance / handRefDistance;
float distanceOffset = distanceRatio > 0 ? (distanceRatio - 1f) * DistanceScale : 0;
float targetDistance = objRefDistance + distanceOffset;
draggingPosition = pivotPosition + (targetDirection * targetDistance);
if (RotationMode == RotationModeEnum.OrientTowardUser || RotationMode == RotationModeEnum.OrientTowardUserAndKeepUpright)
{
draggingRotation = Quaternion.LookRotation(HostTransform.position - pivotPosition);
}
else if (RotationMode == RotationModeEnum.LockObjectRotation)
{
draggingRotation = HostTransform.rotation;
}
else // RotationModeEnum.Default
{
Vector3 objForward = cameraTransform.TransformDirection(objRefForward); // in world space
Vector3 objUp = cameraTransform.TransformDirection(objRefUp); // in world space
draggingRotation = Quaternion.LookRotation(objForward, objUp);
}
// Apply Final Position
HostTransform.position = Vector3.Lerp(HostTransform.position, draggingPosition + cameraTransform.TransformDirection(objRefGrabPoint), PositionLerpSpeed);
// Apply Final Rotation
HostTransform.rotation = Quaternion.Lerp(HostTransform.rotation, draggingRotation, RotationLerpSpeed);
if (RotationMode == RotationModeEnum.OrientTowardUserAndKeepUpright)
{
Quaternion upRotation = Quaternion.FromToRotation(HostTransform.up, Vector3.up);
HostTransform.rotation = upRotation * HostTransform.rotation;
}
}
/// <summary>
/// Stops dragging the object.
/// </summary>
public void StopDragging()
{
if (!isDragging)
{
return;
}
// Remove self as a modal input handler
InputManager.Instance.PopModalInputHandler();
isDragging = false;
currentInputSource = null;
StoppedDragging.RaiseEvent();
}
public void OnFocusEnter()
{
if (!IsDraggingEnabled)
{
return;
}
if (isGazed)
{
return;
}
isGazed = true;
}
public void OnFocusExit()
{
if (!IsDraggingEnabled)
{
return;
}
if (!isGazed)
{
return;
}
isGazed = false;
}
public void OnInputUp(InputEventData eventData)
{
if (currentInputSource != null &&
eventData.SourceId == currentInputSourceId)
{
eventData.Use(); // Mark the event as used, so it doesn't fall through to other handlers.
StopDragging();
}
}
public void OnInputDown(InputEventData eventData)
{
if (isDragging)
{
// We're already handling drag input, so we can't start a new drag operation.
return;
}
if (!eventData.InputSource.SupportsInputInfo(eventData.SourceId, SupportedInputInfo.Position))
{
// The input source must provide positional data for this script to be usable
return;
}
eventData.Use(); // Mark the event as used, so it doesn't fall through to other handlers.
currentInputSource = eventData.InputSource;
currentInputSourceId = eventData.SourceId;
FocusDetails? details = FocusManager.Instance.TryGetFocusDetails(eventData);
Vector3 initialDraggingPosition = (details == null)
? HostTransform.position
: details.Value.Point;
StartDragging(initialDraggingPosition);
}
public void OnSourceDetected(SourceStateEventData eventData)
{
// Nothing to do
}
public void OnSourceLost(SourceStateEventData eventData)
{
if (currentInputSource != null && eventData.SourceId == currentInputSourceId)
{
StopDragging();
}
}
}
}
| |
using Signum.Utilities.DataStructures;
using Signum.Utilities.ExpressionTrees;
using Signum.Utilities.Reflection;
using Signum.Utilities.Synchronization;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.IO;
namespace Signum.Utilities;
public static class EnumerableUniqueExtensions
{
class UniqueExExpander : IMethodExpander
{
static MethodInfo miWhereE = ReflectionTools.GetMethodInfo(() => Enumerable.Where<int>(null!, a => false)).GetGenericMethodDefinition();
static MethodInfo miWhereQ = ReflectionTools.GetMethodInfo(() => Queryable.Where<int>(null!, a => false)).GetGenericMethodDefinition();
public Expression Expand(Expression? instance, Expression[] arguments, MethodInfo mi)
{
bool query = mi.GetParameters()[0].ParameterType.IsInstantiationOf(typeof(IQueryable<>));
var whereMi = (query ? miWhereQ : miWhereE).MakeGenericMethod(mi.GetGenericArguments());
var whereExpr = Expression.Call(whereMi, arguments[0], arguments[1]);
var uniqueMi = mi.DeclaringType!.GetMethods().SingleEx(m => m.Name == mi.Name && m.IsGenericMethod && m.GetParameters().Length == (mi.GetParameters().Length - 1));
return Expression.Call(uniqueMi.MakeGenericMethod(mi.GetGenericArguments()), whereExpr);
}
}
/// <summary>
/// Returns the single Element from a collections satisfying a predicate, or throws an Exception
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection">the collection to search</param>
/// <param name="predicate">the predicate</param>
/// <returns>the single Element from the collection satisfying the predicate.</returns>
[MethodExpander(typeof(UniqueExExpander))]
public static T SingleEx<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
T result = default!;
bool found = false;
foreach (T item in collection)
{
if (predicate(item))
{
if (found)
throw new InvalidOperationException("Sequence contains more than one {0}".FormatWith(typeof(T).TypeName()));
result = item;
found = true;
}
}
if (found)
return result;
throw new InvalidOperationException("Sequence contains no {0}".FormatWith(typeof(T).TypeName()));
}
[MethodExpander(typeof(UniqueExExpander))]
public static T SingleEx<T>(this IQueryable<T> query, Expression<Func<T, bool>> predicate)
{
return query.Where(predicate).SingleEx();
}
/// <summary>
/// Returns the single Object from the collection or throws an Exception
/// </summary>
/// <typeparam name="T">Type of the collection</typeparam>
/// <param name="collection">The collection to search</param>
/// <returns>The single Element from the collection</returns>
public static T SingleEx<T>(this IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext())
throw new InvalidOperationException("Sequence contains no {0}".FormatWith(typeof(T).TypeName()));
T current = enumerator.Current;
if (!enumerator.MoveNext())
return current;
}
throw new InvalidOperationException("Sequence contains more than one {0}".FormatWith(typeof(T).TypeName()));
}
/// <summary>
/// Returns the single Object from the collection or throws an Exception
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="elementName"></param>
/// <param name="forEndUser"></param>
/// <returns></returns>
public static T SingleEx<T>(this IEnumerable<T> collection, Func<string> elementName, bool forEndUser = false)
{
return collection.SingleEx(
() => forEndUser ? CollectionMessage.No0Found.NiceToString(elementName()) : "Sequence contains no {0}".FormatWith(elementName()),
() => forEndUser ? CollectionMessage.MoreThanOne0Found.NiceToString(elementName()) : "Sequence contains more than one {0}".FormatWith(elementName()),
forEndUser);
}
/// <summary>
/// Returns the single Object from the collection or throws an Exception
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="errorZero">The Message if there is no Element</param>
/// <param name="errorMoreThanOne">The Message if there is more than one Element</param>
/// <param name="forEndUser"></param>
/// <returns></returns>
public static T SingleEx<T>(this IEnumerable<T> collection, Func<string> errorZero, Func<string> errorMoreThanOne, bool forEndUser = false)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext())
throw NewException(forEndUser, errorZero());
T current = enumerator.Current;
if (!enumerator.MoveNext())
return current;
}
throw NewException(forEndUser, errorMoreThanOne());
}
static Exception NewException(bool forEndUser, string message)
{
if (forEndUser)
return new ApplicationException(message);
else
return new InvalidOperationException(message);
}
[MethodExpander(typeof(UniqueExExpander))]
public static T? SingleOrDefaultEx<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
T result = default!;
bool found = false;
foreach (T item in collection)
{
if (predicate(item))
{
if (found)
throw new InvalidOperationException("Sequence contains more than one {0}".FormatWith(typeof(T).TypeName()));
result = item;
found = true;
}
}
return result;
}
[MethodExpander(typeof(UniqueExExpander))]
public static T? SingleOrDefaultEx<T>(this IQueryable<T> query, Expression<Func<T, bool>> predicate)
{
return query.Where(predicate).SingleOrDefaultEx();
}
public static T? SingleOrDefaultEx<T>(this IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext())
return default!;
T current = enumerator.Current;
if (!enumerator.MoveNext())
return current;
}
throw new InvalidOperationException("Sequence contains more than one {0}".FormatWith(typeof(T).TypeName()));
}
public static T? SingleOrDefaultEx<T>(this IEnumerable<T> collection, Func<string> errorMoreThanOne, bool forEndUser = false)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext())
return default!;
T current = enumerator.Current;
if (!enumerator.MoveNext())
return current;
}
throw NewException(forEndUser, errorMoreThanOne());
}
[MethodExpander(typeof(UniqueExExpander))]
public static T FirstEx<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
foreach (T item in collection)
{
if (predicate(item))
return item;
}
throw new InvalidOperationException("Sequence contains no {0}".FormatWith(typeof(T).TypeName()));
}
[MethodExpander(typeof(UniqueExExpander))]
public static T FirstEx<T>(this IQueryable<T> query, Expression<Func<T, bool>> predicate)
{
return query.Where(predicate).FirstEx();
}
public static T FirstEx<T>(this IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext())
throw new InvalidOperationException("Sequence contains no {0}".FormatWith(typeof(T).TypeName()));
return enumerator.Current;
}
}
public static T FirstEx<T>(this IEnumerable<T> collection, Func<string> errorZero, bool forEndUser = false)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext())
throw NewException(forEndUser, errorZero());
return enumerator.Current;
}
}
[MethodExpander(typeof(UniqueExExpander))]
public static T? SingleOrManyEx<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
{
return collection.Where(predicate).FirstEx();
}
[MethodExpander(typeof(UniqueExExpander))]
public static T SingleOrManyEx<T>(this IQueryable<T> query, Expression<Func<T, bool>> predicate)
{
return query.Where(predicate).FirstEx();
}
public static T? SingleOrManyEx<T>(this IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext())
throw new InvalidOperationException("Sequence contains no {0}".FormatWith(typeof(T).TypeName()));
T current = enumerator.Current;
if (enumerator.MoveNext())
return default!;
return current;
}
}
public static T? SingleOrManyEx<T>(this IEnumerable<T> collection, Func<string> errorZero, bool forEndUser = false)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext())
throw NewException(forEndUser, errorZero());
T current = enumerator.Current;
if (enumerator.MoveNext())
return default!;
return current;
}
}
//returns default if 0 or many, returns if one
public static T? Only<T>(this IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext())
return default!;
T current = enumerator.Current;
if (enumerator.MoveNext())
return default!;
return current;
}
}
}
public static class EnumerableExtensions
{
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T>? collection)
{
if (collection == null)
return Enumerable.Empty<T>();
return collection;
}
[MethodExpander(typeof(IsEmptyExpander))]
public static bool IsEmpty<T>(this IEnumerable<T> collection)
{
foreach (var item in collection)
return false;
return true;
}
class IsEmptyExpander : IMethodExpander
{
static readonly MethodInfo miAny = ReflectionTools.GetMethodInfo((int[] a) => a.Any()).GetGenericMethodDefinition();
public Expression Expand(Expression? instance, Expression[] arguments, MethodInfo mi)
{
return Expression.Not(Expression.Call(miAny.MakeGenericMethod(mi.GetGenericArguments()), arguments));
}
}
public static bool IsNullOrEmpty<T>([NotNullWhen(false)]this IEnumerable<T>? collection)
{
return collection == null || collection.IsEmpty();
}
public static bool HasItems<T>([NotNullWhen(true)]this IEnumerable<T>? collection)
{
return collection != null && collection.Any();
}
public static IEnumerable<T> NotNull<T>(this IEnumerable<T?> collection) where T : class
{
foreach (var item in collection)
{
if (item != null)
yield return item;
}
}
public static IEnumerable<T> NotNull<T>(this IEnumerable<T?> collection) where T : struct
{
foreach (var item in collection)
{
if (item.HasValue)
yield return item.Value;
}
}
public static IEnumerable<T> And<T>(this IEnumerable<T> collection, T newItem)
{
foreach (var item in collection)
yield return item;
yield return newItem;
}
public static IEnumerable<T> PreAnd<T>(this IEnumerable<T> collection, T newItem)
{
yield return newItem;
foreach (var item in collection)
yield return item;
}
public static int IndexOf<T>(this IEnumerable<T> collection, T item)
{
int i = 0;
foreach (var val in collection)
{
if (EqualityComparer<T>.Default.Equals(item, val))
return i;
i++;
}
return -1;
}
public static int IndexOf<T>(this IEnumerable<T> collection, Func<T, bool> condition)
{
int i = 0;
foreach (var val in collection)
{
if (condition(val))
return i;
i++;
}
return -1;
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> collection, Random rng)
{
T[] elements = collection.ToArray();
for (int i = elements.Length - 1; i > 0; i--)
{
int rnd = rng.Next(i + 1);
yield return elements[rnd];
elements[rnd] = elements[i];
}
yield return elements[0];
}
public static string ToString<T>(this IEnumerable<T> source, string separator)
{
StringBuilder? sb = null;
foreach (var item in source)
{
if (sb == null)
sb = new StringBuilder();
else
sb.Append(separator);
sb.Append(item?.ToString());
}
if (sb == null)
return "";
return sb.ToString(); // Remove at the end is faster
}
public static string ToString<T>(this IEnumerable<T> source, Func<T, string?> toString, string separator)
{
StringBuilder? sb = null;
foreach (var item in source)
{
if (sb == null)
sb = new StringBuilder();
else
sb.Append(separator);
sb.Append(toString(item));
}
if (sb == null)
return "";
return sb.ToString(); // Remove at the end is faster
}
public static string ToString<T>(this IQueryable<T> source, Expression<Func<T, string?>> toString, string separator)
{
return source.Select(toString).ToString(separator);
}
public static string CommaAnd<T>(this IEnumerable<T> collection)
{
return CommaString(collection.Select(a => a!.ToString()).ToArray(), CollectionMessage.And.NiceToString());
}
public static string CommaAnd<T>(this IEnumerable<T> collection, Func<T, string?> toString)
{
return CommaString(collection.Select(toString).ToArray(), CollectionMessage.And.NiceToString());
}
public static string CommaOr<T>(this IEnumerable<T> collection)
{
return CommaString(collection.Select(a => a?.ToString()).ToArray(), CollectionMessage.Or.NiceToString());
}
public static string CommaOr<T>(this IEnumerable<T> collection, Func<T, string?> toString)
{
return CommaString(collection.Select(toString).ToArray(), CollectionMessage.Or.NiceToString());
}
public static string Comma<T>(this IEnumerable<T> collection, string lastSeparator)
{
return CommaString(collection.Select(a => a!.ToString()).ToArray(), lastSeparator);
}
public static string Comma<T>(this IEnumerable<T> collection, Func<T, string> toString, string lastSeparator)
{
return CommaString(collection.Select(toString).ToArray(), lastSeparator);
}
static string CommaString(this string?[] values, string lastSeparator)
{
if (values.Length == 0)
return "";
var sb = new StringBuilder();
sb.Append(values[0]);
for (int i = 1; i < values.Length - 1; i++)
{
sb.Append(", ");
sb.Append(values[i]);
}
if (values.Length > 1)
{
sb.Append(lastSeparator);
sb.Append(values[^1]);
}
return sb.ToString();
}
public static void ToConsole<T>(this IEnumerable<T> collection)
{
ToConsole(collection, a => a!.ToString()!);
}
public static void ToConsole<T>(this IEnumerable<T> collection, Func<T, string> toString)
{
foreach (var item in collection)
Console.WriteLine(toString(item));
}
public static void ToFile(this IEnumerable<string> collection, string fileName)
{
using (FileStream fs = File.Create(fileName))
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
foreach (var item in collection)
sw.WriteLine(item);
}
}
public static void ToFile<T>(this IEnumerable<T> collection, Func<T, string> toString, string fileName)
{
collection.Select(toString).ToFile(fileName);
}
public static DataTable ToDataTable<T>(this IEnumerable<T> collection, bool withDescriptions = false)
{
var table = new DataTable();
List<MemberEntry<T>> members = MemberEntryFactory.GenerateList<T>(MemberOptions.Default);
foreach (var m in members)
{
var name = withDescriptions ? m.MemberInfo.GetCustomAttribute<DescriptionAttribute>()?.Description ?? m.Name : m.Name;
var type = m.MemberInfo.ReturningType().UnNullify();
table.Columns.Add(name, type);
}
foreach (var e in collection)
table.Rows.Add(members.Select(m => m.Getter!(e)).ToArray());
return table;
}
public static DataTable Transpose(this DataTable table, string captionName = "")
{
var result = new DataTable();
result.Columns.Add(new DataColumn("Column", typeof(string)) { Caption = captionName});
var list = table.Columns.Cast<DataColumn>().Skip(1).Select(a => a.DataType).Distinct().ToList();
var bestCommon = BetsCommonType(list);
foreach (var row in table.Rows.Cast<DataRow>())
{
result.Columns.Add(new DataColumn(row[0]?.ToString(), bestCommon));
}
foreach (var col in table.Columns.Cast<DataColumn>().Skip(1))
{
var array = table.Rows.Cast<DataRow>().Select(dr => dr[col]).Cast<object>().ToArray();
result.Rows.Add(array.PreAnd(col.ColumnName).ToArray());
}
return result;
}
static Type BetsCommonType(List<Type> list)
{
if (list.Count == 1)
return list.Single();
return typeof(string);
}
#region String Tables
public static string[,] ToStringTable<T>(this IEnumerable<T> collection)
{
List<MemberEntry<T>> members = MemberEntryFactory.GenerateList<T>(MemberOptions.Default);
string[,] result = new string[members.Count, collection.Count() + 1];
for (int i = 0; i < members.Count; i++)
result[i, 0] = members[i].Name;
int j = 1;
foreach (var item in collection)
{
for (int i = 0; i < members.Count; i++)
result[i, j] = members[i].Getter!(item)?.ToString() ?? "";
j++;
}
return result;
}
public static string[,] ToStringTable(this DataTable table)
{
string[,] result = new string[table.Columns.Count, table.Rows.Count + 1];
for (int i = 0; i < table.Columns.Count; i++)
result[i, 0] = table.Columns[i].ColumnName;
int j = 1;
foreach (DataRow? row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
result[i, j] = row![i]?.ToString() ?? "";
j++;
}
return result;
}
public static string FormatTable(this string[,] table, bool longHeaders = true, string separator = " ")
{
int width = table.GetLength(0);
int height = table.GetLength(1);
int start = height == 1 ? 0 : (longHeaders ? 0 : 1);
int[] lengths = 0.To(width).Select(i => Math.Max(3, start.To(height).Max(j => table[i, j].Length))).ToArray();
return 0.To(height).Select(j => 0.To(width).ToString(i => table[i, j].PadChopRight(lengths[i]), separator)).ToString("\r\n");
}
public static void WriteFormattedStringTable<T>(this IEnumerable<T> collection, TextWriter textWriter, string? title, bool longHeaders)
{
textWriter.WriteLine();
if (title.HasText())
textWriter.WriteLine(title!);
textWriter.WriteLine(collection.ToStringTable().FormatTable(longHeaders));
textWriter.WriteLine();
}
public static void ToConsoleTable<T>(this IEnumerable<T> collection, string? title = null, bool longHeader = false)
{
collection.WriteFormattedStringTable(Console.Out, title, longHeader);
}
public static string ToFormattedTable<T>(this IEnumerable<T> collection, string? title = null, bool longHeader = false)
{
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
collection.WriteFormattedStringTable(sw, title, longHeader);
return sb.ToString();
}
#endregion
#region Min Max
public static MinMax<T> MinMaxBy<T, V>(this IEnumerable<T> collection, Func<T, V> valueSelector)
where V : IComparable<V>
{
T withMin = default!, withMax = default!;
bool hasMin = false, hasMax = false;
V min = default!, max = default!;
foreach (var item in collection)
{
V val = valueSelector(item);
if (!hasMax || val.CompareTo(max) > 0)
{
hasMax = true;
max = val;
withMax = item;
}
if (!hasMin || val.CompareTo(min) < 0)
{
hasMin = true;
min = val;
withMin = item;
}
}
return new MinMax<T>(withMin, withMax);
}
public static List<T> MinByList<T, V>(this IEnumerable<T> collection, Func<T, V> valueSelector)
where V : IComparable<V>
{
List<T> result = new List<T>();
V min = default!;
foreach (var item in collection)
{
V val = valueSelector(item);
int comp = 0;
if (result.Count == 0 || (comp = val.CompareTo(min)) <= 0)
{
if (comp < 0)
result.Clear();
result.Add(item);
min = val;
}
}
return result;
}
public static List<T> MaxByList<T, V>(this IEnumerable<T> collection, Func<T, V> valueSelector)
where V : IComparable<V>
{
List<T> result = new List<T>();
V max = default!;
foreach (var item in collection)
{
V val = valueSelector(item);
int comp = 0;
if (result.Count == 0 || (comp = val.CompareTo(max)) >= 0)
{
if (comp > 0)
result.Clear();
result.Add(item);
max = val;
}
}
return result;
}
public static Interval<T> ToInterval<T>(this IEnumerable<T> collection)
where T : struct, IComparable<T>, IEquatable<T>
{
bool has = false;
T min = default, max = default;
foreach (var item in collection)
{
if (!has)
{
has = true;
min = max = item;
}
else
{
if (item.CompareTo(max) > 0)
max = item;
if (item.CompareTo(min) < 0)
min = item;
}
}
return new Interval<T>(min, max);
}
public static Interval<V> ToInterval<T, V>(this IEnumerable<T> collection, Func<T, V> valueSelector)
where V : struct, IComparable<V>, IEquatable<V>
{
bool has = false;
V min = default, max = default;
foreach (var item in collection)
{
V val = valueSelector(item);
if (!has)
{
has = true;
min = max = val;
}
else
{
if (val.CompareTo(max) > 0)
max = val;
if (val.CompareTo(min) < 0)
min = val;
}
}
return new Interval<V>(min, max);
}
#endregion
#region Operation
public static IEnumerable<T> Concat<T>(params IEnumerable<T>[] collections)
{
foreach (var collection in collections)
{
foreach (var item in collection)
{
yield return item;
}
}
}
public static IEnumerable<S> BiSelectC<T, S>(this IEnumerable<T> collection, Func<T?, T?, S> func, BiSelectOptions options = BiSelectOptions.None)
where T : class
{
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext())
yield break;
T firstItem = enumerator.Current;
if (options == BiSelectOptions.Initial || options == BiSelectOptions.InitialAndFinal)
yield return func(null, firstItem);
T lastItem = firstItem;
while (enumerator.MoveNext())
{
T item = enumerator.Current;
yield return func(lastItem, item);
lastItem = item;
}
if (options == BiSelectOptions.Final || options == BiSelectOptions.InitialAndFinal)
yield return func(lastItem, null);
if (options == BiSelectOptions.Circular)
yield return func(lastItem, firstItem);
}
}
public static IEnumerable<S> BiSelectS<T, S>(this IEnumerable<T> collection, Func<T?, T?, S> func, BiSelectOptions options = BiSelectOptions.None)
where T : struct
{
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext())
yield break;
T firstItem = enumerator.Current;
if (options == BiSelectOptions.Initial || options == BiSelectOptions.InitialAndFinal)
yield return func(null, firstItem);
T lastItem = firstItem;
while (enumerator.MoveNext())
{
T item = enumerator.Current;
yield return func(lastItem, item);
lastItem = item;
}
if (options == BiSelectOptions.Final || options == BiSelectOptions.InitialAndFinal)
yield return func(lastItem, null);
if (options == BiSelectOptions.Circular)
yield return func(lastItem, firstItem);
}
}
//return one element more
public static IEnumerable<S> SelectAggregate<T, S>(this IEnumerable<T> collection, S seed, Func<S, T, S> aggregate)
{
yield return seed;
foreach (var item in collection)
{
seed = aggregate(seed, item);
yield return seed;
}
}
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
where T : notnull
{
IEnumerable<ImmutableStack<T>> emptyProduct = new[] { ImmutableStack<T>.Empty };
var result = sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Push(item));
return result.Select(a => a.Reverse());
}
public static IEnumerable<T> Distinct<T, S>(this IEnumerable<T> collection, Func<T, S> func)
{
return collection.Distinct(new LambdaComparer<T, S>(func));
}
public static IEnumerable<T> Distinct<T, S>(this IEnumerable<T> collection, Func<T, S> func, IEqualityComparer<S> comparer)
{
return collection.Distinct(new LambdaComparer<T, S>(func, comparer, null));
}
public static IEnumerable<T> Slice<T>(this IEnumerable<T> collection, int firstIncluded, int toNotIncluded)
{
return collection.Skip(firstIncluded).Take(toNotIncluded - firstIncluded);
}
public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> collection) where T : IComparable<T>
{
return collection.OrderBy(a => a);
}
public static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> collection) where T : IComparable<T>
{
return collection.OrderByDescending(a => a);
}
#endregion
#region Zip
public static IEnumerable<R> ZipOrDefault<A, B, R>(this IEnumerable<A> colA, IEnumerable<B> colB, Func<A, B, R> resultSelector)
{
bool okA = true, okB = true;
using (var enumA = colA.GetEnumerator())
using (var enumB = colB.GetEnumerator())
{
while (okA & (okA = enumA.MoveNext()) | okB & (okB = enumB.MoveNext()))
{
yield return resultSelector(
okA ? enumA.Current : default!,
okB ? enumB.Current : default!);
}
}
}
public static IEnumerable<(A first, B second)> ZipOrDefault<A, B>(this IEnumerable<A> colA, IEnumerable<B> colB)
{
bool okA = true, okB = true;
using (var enumA = colA.GetEnumerator())
using (var enumB = colB.GetEnumerator())
{
while ((okA &= enumA.MoveNext()) |
(okB &= enumB.MoveNext()))
{
var first = okA ? enumA.Current : default!;
var second = okB ? enumB.Current : default!;
yield return (first, second);
}
}
}
public static void ZipForeach<A, B>(this IEnumerable<A> colA, IEnumerable<B> colB, Action<A, B> actions)
{
using (var enumA = colA.GetEnumerator())
using (var enumB = colB.GetEnumerator())
{
while (enumA.MoveNext() && enumB.MoveNext())
{
actions(enumA.Current, enumB.Current);
}
}
}
public static IEnumerable<(A first, B second)> ZipStrict<A, B>(this IEnumerable<A> colA, IEnumerable<B> colB)
{
using (var enumA = colA.GetEnumerator())
using (var enumB = colB.GetEnumerator())
{
while (AssertoTwo(enumA.MoveNext(), enumB.MoveNext()))
{
yield return (first: enumA.Current, second: enumB.Current);
}
}
}
public static IEnumerable<R> ZipStrict<A, B, R>(this IEnumerable<A> colA, IEnumerable<B> colB, Func<A, B, R> mixer)
{
colA.Zip(colB, (a, b) => a);
using (var enumA = colA.GetEnumerator())
using (var enumB = colB.GetEnumerator())
{
while (AssertoTwo(enumA.MoveNext(), enumB.MoveNext()))
{
yield return mixer(enumA.Current, enumB.Current);
}
}
}
public static void ZipForeachStrict<A, B>(this IEnumerable<A> colA, IEnumerable<B> colB, Action<A, B> action)
{
using (var enumA = colA.GetEnumerator())
using (var enumB = colB.GetEnumerator())
{
while (AssertoTwo(enumA.MoveNext(), enumB.MoveNext()))
{
action(enumA.Current, enumB.Current);
}
}
}
static bool AssertoTwo(bool nextA, bool nextB)
{
if (nextA != nextB)
if (nextA)
throw new InvalidOperationException("Second collection is shorter");
else
throw new InvalidOperationException("First collection is shorter");
else
return nextA;
}
#endregion
#region Conversions
public static ReadOnlyCollection<T> ToReadOnly<T>(this IEnumerable<T>? collection)
{
return collection == null ? EmptyReadOnlyCollection<T>.Instance :
collection as ReadOnlyCollection<T> ??
(collection as List<T> ?? collection.ToList()).AsReadOnly();
}
static class EmptyReadOnlyCollection<T>
{
internal static ReadOnlyCollection<T> Instance;
static EmptyReadOnlyCollection()
{
EmptyReadOnlyCollection<T>.Instance = new ReadOnlyCollection<T>(Array.Empty<T>());
}
}
public static ReadOnlyDictionary<K, V> ToReadOnly<K, V>(this IDictionary<K, V> dictionary)
where K: notnull
{
return dictionary == null ? EmptyReadOnlyDictionary<K, V>.Instance :
dictionary as ReadOnlyDictionary<K, V> ??
new ReadOnlyDictionary<K, V>(dictionary);
}
static class EmptyReadOnlyDictionary<K, V>
where K :notnull
{
internal static ReadOnlyDictionary<K, V> Instance;
static EmptyReadOnlyDictionary()
{
EmptyReadOnlyDictionary<K, V>.Instance = new ReadOnlyDictionary<K, V>(new Dictionary<K, V>());
}
}
public static ObservableCollection<T>? ToObservableCollection<T>(this IEnumerable<T>? collection)
{
return collection == null ? null :
collection as ObservableCollection<T> ?? new ObservableCollection<T>(collection);
}
public static IEnumerable<T> AsThreadSafe<T>(this IEnumerable<T> source)
{
return new TreadSafeEnumerator<T>(source);
}
public static IEnumerable<T> ToProgressEnumerator<T>(this IEnumerable<T> source, out IProgressInfo pi)
{
pi = new ProgressEnumerator<T>(source, source.Count());
return (IEnumerable<T>)pi;
}
public static ImmutableStack<T> PushRange<T>(this ImmutableStack<T> stack, IEnumerable<T> elements)
{
foreach (var item in elements)
stack = stack.Push(item);
return stack;
}
public static void PushRange<T>(this Stack<T> stack, IEnumerable<T> elements)
{
foreach (var item in elements)
stack.Push(item);
}
public static ImmutableQueue<T> EnqueueRange<T>(this ImmutableQueue<T> queue, IEnumerable<T> elements)
{
foreach (var item in elements)
queue = queue.Enqueue(item);
return queue;
}
public static void EnqueueRange<T>(this Queue<T> queue, IEnumerable<T> elements)
{
foreach (var item in elements)
queue.Enqueue(item);
}
public static void AddRange<T>(this HashSet<T> hashset, IEnumerable<T> coleccion)
{
foreach (var item in coleccion)
{
hashset.Add(item);
}
}
public static bool TryContains<T>(this HashSet<T> hashset, T element)
{
if (hashset == null)
return false;
return hashset.Contains(element);
}
#endregion
public static IEnumerable<R> JoinStrict<K, C, S, R>(
IEnumerable<C> currentCollection,
IEnumerable<S> shouldCollection,
Func<C, K> currentKeySelector,
Func<S, K> shouldKeySelector,
Func<C, S, R> resultSelector, string action)
where K : notnull
{
var currentDictionary = currentCollection.ToDictionary(currentKeySelector);
var shouldDictionary = shouldCollection.ToDictionary(shouldKeySelector);
var extra = currentDictionary.Keys.Where(k => !shouldDictionary.ContainsKey(k)).ToList();
var missing = shouldDictionary.Keys.Where(k => !currentDictionary.ContainsKey(k)).ToList();
string? differences = GetDifferences(extra, missing);
if (differences != null)
{
throw new InvalidOperationException($@"Mismatches {action}:
{differences}");
}
return currentDictionary.Select(p => resultSelector(p.Value, shouldDictionary[p.Key]));
}
public static IEnumerable<R> JoinRelaxed<K, C, S, R>(
IEnumerable<C> currentCollection,
IEnumerable<S> shouldCollection,
Func<C, K> currentKeySelector,
Func<S, K> shouldKeySelector,
Func<C, S, R> resultSelector, string action)
where K : notnull
{
var currentDictionary = currentCollection.ToDictionary(currentKeySelector);
var shouldDictionary = shouldCollection.ToDictionary(shouldKeySelector);
var extra = currentDictionary.Keys.Where(k => !shouldDictionary.ContainsKey(k)).ToList();
var missing = shouldDictionary.Keys.Where(k => !currentDictionary.ContainsKey(k)).ToList();
string? differences = GetDifferences(extra, missing);
if (differences != null)
{
try
{
throw new InvalidOperationException($@"Mismatches {action}:
{differences}
Consider Synchronize.");
}
catch (Exception e) when (StartParameters.IgnoredDatabaseMismatches != null)
{
//This try { throw } catch is here to alert developers.
//In production, in some cases its OK to attempt starting an application with a slightly different schema (dynamic entities, green-blue deployments).
//In development, consider synchronize.
StartParameters.IgnoredDatabaseMismatches.Add(e);
}
}
var commonKeys = currentDictionary.Keys.Intersect(shouldDictionary.Keys);
return commonKeys.Select(k => resultSelector(currentDictionary[k], shouldDictionary[k]));
}
private static string? GetDifferences<K>(List<K> extra, List<K> missing)
{
if (extra.Count != 0)
{
if (missing.Count != 0)
return $" Extra: {extra.ToString(", ")}\r\n Missing: {missing.ToString(", ")}";
else
return $" Extra: {extra.ToString(", ")}";
}
else
{
if (missing.Count != 0)
return $" Missing: {missing.ToString(", ")}";
else
return null;
}
}
public static JoinStrictResult<C, S, R> JoinStrict<K, C, S, R>(
IEnumerable<C> currentCollection,
IEnumerable<S> shouldCollection,
Func<C, K> currentKeySelector,
Func<S, K> shouldKeySelector,
Func<C, S, R> resultSelector)
where K : notnull
{
var currentDictionary = currentCollection.ToDictionary(currentKeySelector);
var newDictionary = shouldCollection.ToDictionary(shouldKeySelector);
HashSet<K> commonKeys = new HashSet<K>(currentDictionary.Keys);
commonKeys.IntersectWith(newDictionary.Keys);
return new JoinStrictResult<C, S, R>
{
Extra = currentDictionary.Where(e => !newDictionary.ContainsKey(e.Key)).Select(e => e.Value).ToList(),
Missing = newDictionary.Where(e => !currentDictionary.ContainsKey(e.Key)).Select(e => e.Value).ToList(),
Result = commonKeys.Select(k => resultSelector(currentDictionary[k], newDictionary[k])).ToList()
};
}
public static IEnumerable<Iteration<T>> Iterate<T>(this IEnumerable<T> collection)
{
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
if (!enumerator.MoveNext())
{
yield break;
}
bool isFirst = true;
bool isLast = false;
int index = 0;
while (!isLast)
{
T current = enumerator.Current;
isLast = !enumerator.MoveNext();
yield return new Iteration<T>(current, isFirst, isLast, index++);
isFirst = false;
}
}
}
public static List<T> Duplicates<T, K>(this IEnumerable<T> source, Func<T, K> selector, IEqualityComparer<K>? comparer)
{
var hash = new HashSet<K>(comparer);
return source.Where(item => !hash.Add(selector(item))).ToList();
}
public static List<T> Duplicates<T, K>(this IEnumerable<T> source, Func<T, K> selector)
{
return source.Duplicates(selector, null);
}
public static List<T> Duplicates<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer)
{
var hash = new HashSet<T>(comparer);
return source.Where(item => !hash.Add(item)).ToList();
}
public static List<T> Duplicates<T>(this IEnumerable<T> source)
{
return source.Duplicates(EqualityComparer<T>.Default);
}
}
public enum CollectionMessage
{
[Description(" and ")]
And,
[Description(" or ")]
Or,
[Description("No {0} found")]
No0Found,
[Description("More than one {0} found")]
MoreThanOne0Found,
}
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
public class JoinStrictResult<O, N, R>
{
public List<O> Extra;
public List<N> Missing;
public List<R> Result;
}
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
public enum BiSelectOptions
{
None,
Initial,
Final,
InitialAndFinal,
Circular,
}
public struct Iteration<T>
{
readonly T value;
readonly bool isFirst;
readonly bool isLast;
readonly int position;
internal Iteration(T value, bool isFirst, bool isLast, int position)
{
this.value = value;
this.isFirst = isFirst;
this.isLast = isLast;
this.position = position;
}
public T Value { get { return value; } }
public bool IsFirst { get { return isFirst; } }
public bool IsLast { get { return isLast; } }
public int Position { get { return position; } }
public bool IsEven { get { return position % 2 == 0; } }
public bool IsOdd { get { return position % 1 == 0; } }
}
/// <summary>
/// Use this if you have a sample of the population
/// </summary>
public static class StandartDeviationExtensions
{
public static float? StdDev(this IEnumerable<float> source)
{
int count = source.Count();
if (count <= 1)
return null;
double avg = source.Average();
double sum = source.Sum(d => (d - avg) * (d - avg));
return (float)Math.Sqrt(sum / (count - 1));
}
public static double? StdDev(this IEnumerable<long?> source) => source.NotNull().Select(a => (double)a).StdDev();
public static float? StdDev(this IEnumerable<float?> source) => source.NotNull().StdDev();
public static double? StdDev(this IEnumerable<double> source)
{
int count = source.Count();
if (count <= 1)
return null;
double avg = source.Average();
double sum = source.Sum(d => (d - avg) * (d - avg));
return Math.Sqrt(sum / (count - 1));
}
public static double? StdDev(this IEnumerable<int> source) => source.Select(a => (double)a).StdDev();
public static decimal? StdDev(this IEnumerable<decimal> source)
{
int count = source.Count();
if (count <= 1)
return null;
decimal avg = source.Average();
decimal sum = source.Sum(d => (d - avg) * (d - avg));
return (decimal)Math.Sqrt((double)(sum / (count - 1)));
}
public static decimal? StdDev(this IEnumerable<decimal?> source) => source.NotNull().StdDev();
public static double? StdDev(this IEnumerable<long> source) => source.Select(a => (double)a).StdDev();
public static double? StdDev(this IEnumerable<double?> source) => source.NotNull().StdDev();
public static double? StdDev(this IEnumerable<int?> source) => source.NotNull().StdDev();
public static decimal? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector) => source.Select(selector).StdDev();
public static decimal? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector) => source.Select(selector).StdDev();
public static double? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, int?> selector) => source.Select(selector).StdDev();
public static double? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, long> selector) => source.Select(selector).StdDev();
public static double? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, long?> selector) => source.Select(selector).StdDev();
public static float? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector) => source.Select(selector).StdDev();
public static float? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, float?> selector) => source.Select(selector).StdDev();
public static double? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector) => source.Select(selector).StdDev();
public static double? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, double?> selector) => source.Select(selector).StdDev();
public static double? StdDev<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector) => source.Select(selector).StdDev();
public static decimal? StdDev(this IQueryable<decimal> source) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static double? StdDev(this IQueryable<double> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static double? StdDev(this IQueryable<int> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static double? StdDev(this IQueryable<long> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static decimal? StdDev(this IQueryable<decimal?> source) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static double? StdDev(this IQueryable<double?> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static double? StdDev(this IQueryable<int?> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static double? StdDev(this IQueryable<long?> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static float? StdDev(this IQueryable<float> source) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static float? StdDev(this IQueryable<float?> source) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static decimal? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal>> selector) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static double? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, double>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static double? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static double? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, long>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static decimal? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal?>> selector) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static double? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, double?>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static double? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int?>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static double? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, long?>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static float? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, float?>> selector) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static float? StdDev<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, float>> selector) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
}
/// <summary>
/// Use this if you have the full population
/// </summary>
public static class StandartDeviationPopulationExtensions
{
public static float? StdDevP(this IEnumerable<float> source)
{
int count = source.Count();
if (count == 0)
return null;
double avg = source.Average();
double sum = source.Sum(d => (d - avg) * (d - avg));
return (float)Math.Sqrt(sum / count);
}
public static double? StdDevP(this IEnumerable<long?> source) => source.NotNull().Select(a => (double)a).StdDevP();
public static float? StdDevP(this IEnumerable<float?> source) => source.NotNull().StdDevP();
public static double? StdDevP(this IEnumerable<double> source)
{
int count = source.Count();
if (count == 0)
return null;
double avg = source.Average();
double sum = source.Sum(d => (d - avg) * (d - avg));
return Math.Sqrt(sum / count);
}
public static double? StdDevP(this IEnumerable<int> source) => source.Select(a => (double)a).StdDevP();
public static decimal? StdDevP(this IEnumerable<decimal> source)
{
int count = source.Count();
if (count == 0)
return null;
decimal avg = source.Average();
decimal sum = source.Sum(d => (d - avg) * (d - avg));
return (decimal)Math.Sqrt((double)(sum / count));
}
public static decimal? StdDevP(this IEnumerable<decimal?> source) => source.NotNull().StdDevP();
public static double? StdDevP(this IEnumerable<long> source) => source.Select(a => (double)a).StdDevP();
public static double? StdDevP(this IEnumerable<double?> source) => source.NotNull().StdDevP();
public static double? StdDevP(this IEnumerable<int?> source) => source.NotNull().StdDevP();
public static decimal? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector) => source.Select(selector).StdDevP();
public static decimal? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector) => source.Select(selector).StdDevP();
public static double? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, int?> selector) => source.Select(selector).StdDevP();
public static double? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, long> selector) => source.Select(selector).StdDevP();
public static double? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, long?> selector) => source.Select(selector).StdDevP();
public static float? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector) => source.Select(selector).StdDevP();
public static float? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, float?> selector) => source.Select(selector).StdDevP();
public static double? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector) => source.Select(selector).StdDevP();
public static double? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, double?> selector) => source.Select(selector).StdDevP();
public static double? StdDevP<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector) => source.Select(selector).StdDevP();
public static decimal? StdDevP(this IQueryable<decimal> source) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static double? StdDevP(this IQueryable<double> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static double? StdDevP(this IQueryable<int> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static double? StdDevP(this IQueryable<long> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static decimal? StdDevP(this IQueryable<decimal?> source) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static double? StdDevP(this IQueryable<double?> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static double? StdDevP(this IQueryable<int?> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static double? StdDevP(this IQueryable<long?> source) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static float? StdDevP(this IQueryable<float> source) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static float? StdDevP(this IQueryable<float?> source) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression));
public static decimal? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal>> selector) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static double? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, double>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static double? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static double? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, long>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static decimal? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal?>> selector) => source.Provider.Execute<decimal?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static double? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, double?>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static double? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int?>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static double? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, long?>> selector) => source.Provider.Execute<double?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static float? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, float?>> selector) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
public static float? StdDevP<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, float>> selector) => source.Provider.Execute<float?>(Expression.Call((Expression?)null, (MethodInfo)MethodInfo.GetCurrentMethod()!, source.Expression, Expression.Quote(selector)));
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Net
{
[System.FlagsAttribute]
public enum AuthenticationSchemes
{
Anonymous = 32768,
Basic = 8,
Digest = 1,
IntegratedWindowsAuthentication = 6,
Negotiate = 2,
None = 0,
Ntlm = 4,
}
public sealed partial class Cookie
{
public Cookie() { }
public Cookie(string name, string value) { }
public Cookie(string name, string value, string path) { }
public Cookie(string name, string value, string path, string domain) { }
public string Comment { get { return default(string); } set { } }
public System.Uri CommentUri { get { return default(System.Uri); } set { } }
public bool Discard { get { return default(bool); } set { } }
public string Domain { get { return default(string); } set { } }
public bool Expired { get { return default(bool); } set { } }
public System.DateTime Expires { get { return default(System.DateTime); } set { } }
public bool HttpOnly { get { return default(bool); } set { } }
public string Name { get { return default(string); } set { } }
public string Path { get { return default(string); } set { } }
public string Port { get { return default(string); } set { } }
public bool Secure { get { return default(bool); } set { } }
public System.DateTime TimeStamp { get { return default(System.DateTime); } }
public string Value { get { return default(string); } set { } }
public int Version { get { return default(int); } set { } }
public override bool Equals(object comparand) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override string ToString() { return default(string); }
}
public partial class CookieCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
public CookieCollection() { }
public int Count { get { return default(int); } }
public System.Net.Cookie this[string name] { get { return default(System.Net.Cookie); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public void Add(System.Net.Cookie cookie) { }
public void Add(System.Net.CookieCollection cookies) { }
public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
}
public partial class CookieContainer
{
public const int DefaultCookieLengthLimit = 4096;
public const int DefaultCookieLimit = 300;
public const int DefaultPerDomainCookieLimit = 20;
public CookieContainer() { }
public int Capacity { get { return default(int); } set { } }
public int Count { get { return default(int); } }
public int MaxCookieSize { get { return default(int); } set { } }
public int PerDomainCapacity { get { return default(int); } set { } }
public void Add(System.Uri uri, System.Net.Cookie cookie) { }
public void Add(System.Uri uri, System.Net.CookieCollection cookies) { }
public string GetCookieHeader(System.Uri uri) { return default(string); }
public System.Net.CookieCollection GetCookies(System.Uri uri) { return default(System.Net.CookieCollection); }
public void SetCookies(System.Uri uri, string cookieHeader) { }
}
public partial class CookieException : System.FormatException
{
public CookieException() { }
}
public partial class CredentialCache : System.Collections.IEnumerable, System.Net.ICredentials, System.Net.ICredentialsByHost
{
public CredentialCache() { }
public static System.Net.ICredentials DefaultCredentials { get { return default(System.Net.ICredentials); } }
public static System.Net.NetworkCredential DefaultNetworkCredentials { get { return default(System.Net.NetworkCredential); } }
public void Add(string host, int port, string authenticationType, System.Net.NetworkCredential credential) { }
public void Add(System.Uri uriPrefix, string authType, System.Net.NetworkCredential cred) { }
public System.Net.NetworkCredential GetCredential(string host, int port, string authenticationType) { return default(System.Net.NetworkCredential); }
public System.Net.NetworkCredential GetCredential(System.Uri uriPrefix, string authType) { return default(System.Net.NetworkCredential); }
public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
public void Remove(string host, int port, string authenticationType) { }
public void Remove(System.Uri uriPrefix, string authType) { }
}
[System.FlagsAttribute]
public enum DecompressionMethods
{
Deflate = 2,
GZip = 1,
None = 0,
}
public partial class DnsEndPoint : System.Net.EndPoint
{
public DnsEndPoint(string host, int port) { }
public DnsEndPoint(string host, int port, System.Net.Sockets.AddressFamily addressFamily) { }
public override System.Net.Sockets.AddressFamily AddressFamily { get { return default(System.Net.Sockets.AddressFamily); } }
public string Host { get { return default(string); } }
public int Port { get { return default(int); } }
public override bool Equals(object comparand) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override string ToString() { return default(string); }
}
public abstract partial class EndPoint
{
protected EndPoint() { }
public virtual System.Net.Sockets.AddressFamily AddressFamily { get { return default(System.Net.Sockets.AddressFamily); } }
public virtual System.Net.EndPoint Create(System.Net.SocketAddress socketAddress) { return default(System.Net.EndPoint); }
public virtual System.Net.SocketAddress Serialize() { return default(System.Net.SocketAddress); }
}
public enum HttpStatusCode
{
Accepted = 202,
Ambiguous = 300,
BadGateway = 502,
BadRequest = 400,
Conflict = 409,
Continue = 100,
Created = 201,
ExpectationFailed = 417,
Forbidden = 403,
Found = 302,
GatewayTimeout = 504,
Gone = 410,
HttpVersionNotSupported = 505,
InternalServerError = 500,
LengthRequired = 411,
MethodNotAllowed = 405,
Moved = 301,
MovedPermanently = 301,
MultipleChoices = 300,
NoContent = 204,
NonAuthoritativeInformation = 203,
NotAcceptable = 406,
NotFound = 404,
NotImplemented = 501,
NotModified = 304,
OK = 200,
PartialContent = 206,
PaymentRequired = 402,
PreconditionFailed = 412,
ProxyAuthenticationRequired = 407,
Redirect = 302,
RedirectKeepVerb = 307,
RedirectMethod = 303,
RequestedRangeNotSatisfiable = 416,
RequestEntityTooLarge = 413,
RequestTimeout = 408,
RequestUriTooLong = 414,
ResetContent = 205,
SeeOther = 303,
ServiceUnavailable = 503,
SwitchingProtocols = 101,
TemporaryRedirect = 307,
Unauthorized = 401,
UnsupportedMediaType = 415,
Unused = 306,
UpgradeRequired = 426,
UseProxy = 305,
}
public partial interface ICredentials
{
System.Net.NetworkCredential GetCredential(System.Uri uri, string authType);
}
public partial interface ICredentialsByHost
{
System.Net.NetworkCredential GetCredential(string host, int port, string authenticationType);
}
public partial class IPAddress
{
public static readonly System.Net.IPAddress Any;
public static readonly System.Net.IPAddress Broadcast;
public static readonly System.Net.IPAddress IPv6Any;
public static readonly System.Net.IPAddress IPv6Loopback;
public static readonly System.Net.IPAddress IPv6None;
public static readonly System.Net.IPAddress Loopback;
public static readonly System.Net.IPAddress None;
public IPAddress(byte[] address) { }
public IPAddress(byte[] address, long scopeid) { }
public IPAddress(long newAddress) { }
public System.Net.Sockets.AddressFamily AddressFamily { get { return default(System.Net.Sockets.AddressFamily); } }
public bool IsIPv4MappedToIPv6 { get { return default(bool); } }
public bool IsIPv6LinkLocal { get { return default(bool); } }
public bool IsIPv6Multicast { get { return default(bool); } }
public bool IsIPv6SiteLocal { get { return default(bool); } }
public bool IsIPv6Teredo { get { return default(bool); } }
public long ScopeId { get { return default(long); } set { } }
public override bool Equals(object comparand) { return default(bool); }
public byte[] GetAddressBytes() { return default(byte[]); }
public override int GetHashCode() { return default(int); }
public static short HostToNetworkOrder(short host) { return default(short); }
public static int HostToNetworkOrder(int host) { return default(int); }
public static long HostToNetworkOrder(long host) { return default(long); }
public static bool IsLoopback(System.Net.IPAddress address) { return default(bool); }
public System.Net.IPAddress MapToIPv4() { return default(System.Net.IPAddress); }
public System.Net.IPAddress MapToIPv6() { return default(System.Net.IPAddress); }
public static short NetworkToHostOrder(short network) { return default(short); }
public static int NetworkToHostOrder(int network) { return default(int); }
public static long NetworkToHostOrder(long network) { return default(long); }
public static System.Net.IPAddress Parse(string ipString) { return default(System.Net.IPAddress); }
public override string ToString() { return default(string); }
public static bool TryParse(string ipString, out System.Net.IPAddress address) { address = default(System.Net.IPAddress); return default(bool); }
}
public partial class IPEndPoint : System.Net.EndPoint
{
public const int MaxPort = 65535;
public const int MinPort = 0;
public IPEndPoint(long address, int port) { }
public IPEndPoint(System.Net.IPAddress address, int port) { }
public System.Net.IPAddress Address { get { return default(System.Net.IPAddress); } set { } }
public override System.Net.Sockets.AddressFamily AddressFamily { get { return default(System.Net.Sockets.AddressFamily); } }
public int Port { get { return default(int); } set { } }
public override System.Net.EndPoint Create(System.Net.SocketAddress socketAddress) { return default(System.Net.EndPoint); }
public override bool Equals(object comparand) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override System.Net.SocketAddress Serialize() { return default(System.Net.SocketAddress); }
public override string ToString() { return default(string); }
}
public partial interface IWebProxy
{
System.Net.ICredentials Credentials { get; set; }
System.Uri GetProxy(System.Uri destination);
bool IsBypassed(System.Uri host);
}
public partial class NetworkCredential : System.Net.ICredentials, System.Net.ICredentialsByHost
{
public NetworkCredential() { }
public NetworkCredential(string userName, string password) { }
public NetworkCredential(string userName, string password, string domain) { }
public string Domain { get { return default(string); } set { } }
public string Password { get { return default(string); } set { } }
public string UserName { get { return default(string); } set { } }
public System.Net.NetworkCredential GetCredential(string host, int port, string authenticationType) { return default(System.Net.NetworkCredential); }
public System.Net.NetworkCredential GetCredential(System.Uri uri, string authType) { return default(System.Net.NetworkCredential); }
}
public partial class SocketAddress
{
public SocketAddress(System.Net.Sockets.AddressFamily family) { }
public SocketAddress(System.Net.Sockets.AddressFamily family, int size) { }
public System.Net.Sockets.AddressFamily Family { get { return default(System.Net.Sockets.AddressFamily); } }
public byte this[int offset] { get { return default(byte); } set { } }
public int Size { get { return default(int); } }
public override bool Equals(object comparand) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override string ToString() { return default(string); }
}
public abstract partial class TransportContext
{
protected TransportContext() { }
public abstract System.Security.Authentication.ExtendedProtection.ChannelBinding GetChannelBinding(System.Security.Authentication.ExtendedProtection.ChannelBindingKind kind);
}
}
namespace System.Net.NetworkInformation
{
public partial class IPAddressCollection : System.Collections.Generic.ICollection<System.Net.IPAddress>, System.Collections.Generic.IEnumerable<System.Net.IPAddress>, System.Collections.IEnumerable
{
protected internal IPAddressCollection() { }
public virtual int Count { get { return default(int); } }
public virtual bool IsReadOnly { get { return default(bool); } }
public virtual System.Net.IPAddress this[int index] { get { return default(System.Net.IPAddress); } }
public virtual void Add(System.Net.IPAddress address) { }
public virtual void Clear() { }
public virtual bool Contains(System.Net.IPAddress address) { return default(bool); }
public virtual void CopyTo(System.Net.IPAddress[] array, int offset) { }
public virtual System.Collections.Generic.IEnumerator<System.Net.IPAddress> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.IPAddress>); }
public virtual bool Remove(System.Net.IPAddress address) { return default(bool); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
}
}
namespace System.Net.Security
{
public enum AuthenticationLevel
{
MutualAuthRequested = 1,
MutualAuthRequired = 2,
None = 0,
}
[System.FlagsAttribute]
public enum SslPolicyErrors
{
None = 0,
RemoteCertificateChainErrors = 4,
RemoteCertificateNameMismatch = 2,
RemoteCertificateNotAvailable = 1,
}
}
namespace System.Net.Sockets
{
public enum AddressFamily
{
AppleTalk = 16,
Atm = 22,
Banyan = 21,
Ccitt = 10,
Chaos = 5,
Cluster = 24,
DataKit = 9,
DataLink = 13,
DecNet = 12,
Ecma = 8,
FireFox = 19,
HyperChannel = 15,
Ieee12844 = 25,
ImpLink = 3,
InterNetwork = 2,
InterNetworkV6 = 23,
Ipx = 6,
Irda = 26,
Iso = 7,
Lat = 14,
NetBios = 17,
NetworkDesigners = 28,
NS = 6,
Osi = 7,
Pup = 4,
Sna = 11,
Unix = 1,
Unknown = -1,
Unspecified = 0,
VoiceView = 18,
}
public enum SocketError
{
AccessDenied = 10013,
AddressAlreadyInUse = 10048,
AddressFamilyNotSupported = 10047,
AddressNotAvailable = 10049,
AlreadyInProgress = 10037,
ConnectionAborted = 10053,
ConnectionRefused = 10061,
ConnectionReset = 10054,
DestinationAddressRequired = 10039,
Disconnecting = 10101,
Fault = 10014,
HostDown = 10064,
HostNotFound = 11001,
HostUnreachable = 10065,
InProgress = 10036,
Interrupted = 10004,
InvalidArgument = 10022,
IOPending = 997,
IsConnected = 10056,
MessageSize = 10040,
NetworkDown = 10050,
NetworkReset = 10052,
NetworkUnreachable = 10051,
NoBufferSpaceAvailable = 10055,
NoData = 11004,
NoRecovery = 11003,
NotConnected = 10057,
NotInitialized = 10093,
NotSocket = 10038,
OperationAborted = 995,
OperationNotSupported = 10045,
ProcessLimit = 10067,
ProtocolFamilyNotSupported = 10046,
ProtocolNotSupported = 10043,
ProtocolOption = 10042,
ProtocolType = 10041,
Shutdown = 10058,
SocketError = -1,
SocketNotSupported = 10044,
Success = 0,
SystemNotReady = 10091,
TimedOut = 10060,
TooManyOpenSockets = 10024,
TryAgain = 11002,
TypeNotFound = 10109,
VersionNotSupported = 10092,
WouldBlock = 10035,
}
public partial class SocketException : System.Exception
{
public SocketException() { }
public SocketException(int errorCode) { }
public override string Message { get { return default(string); } }
public System.Net.Sockets.SocketError SocketErrorCode { get { return default(System.Net.Sockets.SocketError); } }
}
}
namespace System.Security.Authentication
{
public enum CipherAlgorithmType
{
Aes = 26129,
Aes128 = 26126,
Aes192 = 26127,
Aes256 = 26128,
Des = 26113,
None = 0,
Null = 24576,
Rc2 = 26114,
Rc4 = 26625,
TripleDes = 26115,
}
public enum ExchangeAlgorithmType
{
DiffieHellman = 43522,
None = 0,
RsaKeyX = 41984,
RsaSign = 9216,
}
public enum HashAlgorithmType
{
Md5 = 32771,
None = 0,
Sha1 = 32772,
}
[System.FlagsAttribute]
public enum SslProtocols
{
None = 0,
[Obsolete("This value has been deprecated. It is no longer supported. http://go.microsoft.com/fwlink/?linkid=14202")]
Ssl2 = 12,
[Obsolete("This value has been deprecated. It is no longer supported. http://go.microsoft.com/fwlink/?linkid=14202")]
Ssl3 = 48,
Tls = 192,
Tls11 = 768,
Tls12 = 3072,
}
}
namespace System.Security.Authentication.ExtendedProtection
{
public abstract partial class ChannelBinding : System.Runtime.InteropServices.SafeHandle
{
protected ChannelBinding() : base(default(System.IntPtr), default(bool)) { }
protected ChannelBinding(bool ownsHandle) : base(default(System.IntPtr), default(bool)) { }
public abstract int Size { get; }
}
public enum ChannelBindingKind
{
Endpoint = 26,
Unique = 25,
Unknown = 0,
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using Umbraco.Cms.Core.Models;
namespace Umbraco.Cms.Core.Services
{
/// <summary>
/// Defines the File Service, which is an easy access to operations involving <see cref="IFile"/> objects like Scripts, Stylesheets and Templates
/// </summary>
public interface IFileService : IService
{
IEnumerable<string> GetPartialViewSnippetNames(params string[] filterNames);
void CreatePartialViewFolder(string folderPath);
void CreatePartialViewMacroFolder(string folderPath);
void DeletePartialViewFolder(string folderPath);
void DeletePartialViewMacroFolder(string folderPath);
/// <summary>
/// Gets a list of all <see cref="IPartialView"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="IPartialView"/> objects</returns>
IEnumerable<IPartialView> GetPartialViews(params string[] names);
IPartialView GetPartialView(string path);
IPartialView GetPartialViewMacro(string path);
Attempt<IPartialView> CreatePartialView(IPartialView partialView, string snippetName = null, int userId = Constants.Security.SuperUserId);
Attempt<IPartialView> CreatePartialViewMacro(IPartialView partialView, string snippetName = null, int userId = Constants.Security.SuperUserId);
bool DeletePartialView(string path, int userId = Constants.Security.SuperUserId);
bool DeletePartialViewMacro(string path, int userId = Constants.Security.SuperUserId);
Attempt<IPartialView> SavePartialView(IPartialView partialView, int userId = Constants.Security.SuperUserId);
Attempt<IPartialView> SavePartialViewMacro(IPartialView partialView, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Gets the content of a partial view as a stream.
/// </summary>
/// <param name="filepath">The filesystem path to the partial view.</param>
/// <returns>The content of the partial view.</returns>
Stream GetPartialViewFileContentStream(string filepath);
/// <summary>
/// Sets the content of a partial view.
/// </summary>
/// <param name="filepath">The filesystem path to the partial view.</param>
/// <param name="content">The content of the partial view.</param>
void SetPartialViewFileContent(string filepath, Stream content);
/// <summary>
/// Gets the size of a partial view.
/// </summary>
/// <param name="filepath">The filesystem path to the partial view.</param>
/// <returns>The size of the partial view.</returns>
long GetPartialViewFileSize(string filepath);
/// <summary>
/// Gets the content of a macro partial view as a stream.
/// </summary>
/// <param name="filepath">The filesystem path to the macro partial view.</param>
/// <returns>The content of the macro partial view.</returns>
Stream GetPartialViewMacroFileContentStream(string filepath);
/// <summary>
/// Sets the content of a macro partial view.
/// </summary>
/// <param name="filepath">The filesystem path to the macro partial view.</param>
/// <param name="content">The content of the macro partial view.</param>
void SetPartialViewMacroFileContent(string filepath, Stream content);
/// <summary>
/// Gets the size of a macro partial view.
/// </summary>
/// <param name="filepath">The filesystem path to the macro partial view.</param>
/// <returns>The size of the macro partial view.</returns>
long GetPartialViewMacroFileSize(string filepath);
/// <summary>
/// Gets a list of all <see cref="IStylesheet"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="IStylesheet"/> objects</returns>
IEnumerable<IStylesheet> GetStylesheets(params string[] paths);
/// <summary>
/// Gets a <see cref="IStylesheet"/> object by its name
/// </summary>
/// <param name="path">Path of the stylesheet incl. extension</param>
/// <returns>A <see cref="IStylesheet"/> object</returns>
IStylesheet GetStylesheet(string path);
/// <summary>
/// Saves a <see cref="IStylesheet"/>
/// </summary>
/// <param name="stylesheet"><see cref="IStylesheet"/> to save</param>
/// <param name="userId">Optional id of the user saving the stylesheet</param>
void SaveStylesheet(IStylesheet stylesheet, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Deletes a stylesheet by its name
/// </summary>
/// <param name="path">Name incl. extension of the Stylesheet to delete</param>
/// <param name="userId">Optional id of the user deleting the stylesheet</param>
void DeleteStylesheet(string path, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Creates a folder for style sheets
/// </summary>
/// <param name="folderPath"></param>
/// <returns></returns>
void CreateStyleSheetFolder(string folderPath);
/// <summary>
/// Deletes a folder for style sheets
/// </summary>
/// <param name="folderPath"></param>
void DeleteStyleSheetFolder(string folderPath);
/// <summary>
/// Gets the content of a stylesheet as a stream.
/// </summary>
/// <param name="filepath">The filesystem path to the stylesheet.</param>
/// <returns>The content of the stylesheet.</returns>
Stream GetStylesheetFileContentStream(string filepath);
/// <summary>
/// Sets the content of a stylesheet.
/// </summary>
/// <param name="filepath">The filesystem path to the stylesheet.</param>
/// <param name="content">The content of the stylesheet.</param>
void SetStylesheetFileContent(string filepath, Stream content);
/// <summary>
/// Gets the size of a stylesheet.
/// </summary>
/// <param name="filepath">The filesystem path to the stylesheet.</param>
/// <returns>The size of the stylesheet.</returns>
long GetStylesheetFileSize(string filepath);
/// <summary>
/// Gets a list of all <see cref="IScript"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="IScript"/> objects</returns>
IEnumerable<IScript> GetScripts(params string[] names);
/// <summary>
/// Gets a <see cref="IScript"/> object by its name
/// </summary>
/// <param name="name">Name of the script incl. extension</param>
/// <returns>A <see cref="IScript"/> object</returns>
IScript GetScript(string name);
/// <summary>
/// Saves a <see cref="Script"/>
/// </summary>
/// <param name="script"><see cref="IScript"/> to save</param>
/// <param name="userId">Optional id of the user saving the script</param>
void SaveScript(IScript script, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Deletes a script by its name
/// </summary>
/// <param name="path">Name incl. extension of the Script to delete</param>
/// <param name="userId">Optional id of the user deleting the script</param>
void DeleteScript(string path, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Creates a folder for scripts
/// </summary>
/// <param name="folderPath"></param>
/// <returns></returns>
void CreateScriptFolder(string folderPath);
/// <summary>
/// Deletes a folder for scripts
/// </summary>
/// <param name="folderPath"></param>
void DeleteScriptFolder(string folderPath);
/// <summary>
/// Gets the content of a script file as a stream.
/// </summary>
/// <param name="filepath">The filesystem path to the script.</param>
/// <returns>The content of the script file.</returns>
Stream GetScriptFileContentStream(string filepath);
/// <summary>
/// Sets the content of a script file.
/// </summary>
/// <param name="filepath">The filesystem path to the script.</param>
/// <param name="content">The content of the script file.</param>
void SetScriptFileContent(string filepath, Stream content);
/// <summary>
/// Gets the size of a script file.
/// </summary>
/// <param name="filepath">The filesystem path to the script file.</param>
/// <returns>The size of the script file.</returns>
long GetScriptFileSize(string filepath);
/// <summary>
/// Gets a list of all <see cref="ITemplate"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns>
IEnumerable<ITemplate> GetTemplates(params string[] aliases);
/// <summary>
/// Gets a list of all <see cref="ITemplate"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns>
IEnumerable<ITemplate> GetTemplates(int masterTemplateId);
/// <summary>
/// Gets a <see cref="ITemplate"/> object by its alias.
/// </summary>
/// <param name="alias">The alias of the template.</param>
/// <returns>The <see cref="ITemplate"/> object matching the alias, or null.</returns>
ITemplate GetTemplate(string alias);
/// <summary>
/// Gets a <see cref="ITemplate"/> object by its identifier.
/// </summary>
/// <param name="id">The identifier of the template.</param>
/// <returns>The <see cref="ITemplate"/> object matching the identifier, or null.</returns>
ITemplate GetTemplate(int id);
/// <summary>
/// Gets a <see cref="ITemplate"/> object by its guid identifier.
/// </summary>
/// <param name="id">The guid identifier of the template.</param>
/// <returns>The <see cref="ITemplate"/> object matching the identifier, or null.</returns>
ITemplate GetTemplate(Guid id);
/// <summary>
/// Gets the template descendants
/// </summary>
/// <param name="masterTemplateId"></param>
/// <returns></returns>
IEnumerable<ITemplate> GetTemplateDescendants(int masterTemplateId);
/// <summary>
/// Saves a <see cref="ITemplate"/>
/// </summary>
/// <param name="template"><see cref="ITemplate"/> to save</param>
/// <param name="userId">Optional id of the user saving the template</param>
void SaveTemplate(ITemplate template, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Creates a template for a content type
/// </summary>
/// <param name="contentTypeAlias"></param>
/// <param name="contentTypeName"></param>
/// <param name="userId"></param>
/// <returns>
/// The template created
/// </returns>
Attempt<OperationResult<OperationResultType, ITemplate>> CreateTemplateForContentType(string contentTypeAlias, string contentTypeName, int userId = Constants.Security.SuperUserId);
ITemplate CreateTemplateWithIdentity(string name, string alias, string content, ITemplate masterTemplate = null, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Deletes a template by its alias
/// </summary>
/// <param name="alias">Alias of the <see cref="ITemplate"/> to delete</param>
/// <param name="userId">Optional id of the user deleting the template</param>
void DeleteTemplate(string alias, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Saves a collection of <see cref="Template"/> objects
/// </summary>
/// <param name="templates">List of <see cref="Template"/> to save</param>
/// <param name="userId">Optional id of the user</param>
void SaveTemplate(IEnumerable<ITemplate> templates, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Gets the content of a template as a stream.
/// </summary>
/// <param name="filepath">The filesystem path to the template.</param>
/// <returns>The content of the template.</returns>
Stream GetTemplateFileContentStream(string filepath);
/// <summary>
/// Sets the content of a template.
/// </summary>
/// <param name="filepath">The filesystem path to the template.</param>
/// <param name="content">The content of the template.</param>
void SetTemplateFileContent(string filepath, Stream content);
/// <summary>
/// Gets the size of a template.
/// </summary>
/// <param name="filepath">The filesystem path to the template.</param>
/// <returns>The size of the template.</returns>
long GetTemplateFileSize(string filepath);
/// <summary>
/// Gets the content of a macro partial view snippet as a string
/// </summary>
/// <param name="snippetName">The name of the snippet</param>
/// <returns></returns>
string GetPartialViewMacroSnippetContent(string snippetName);
/// <summary>
/// Gets the content of a partial view snippet as a string.
/// </summary>
/// <param name="snippetName">The name of the snippet</param>
/// <returns>The content of the partial view.</returns>
string GetPartialViewSnippetContent(string snippetName);
}
}
| |
#pragma warning disable 618, 649
//, 1734
#region Using
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using Emotion.Utility;
using Khronos;
#endregion
// ReSharper disable InheritdocConsiderUsage
// ReSharper disable SwitchStatementMissingSomeCases
// ReSharper disable RedundantIfElseBlock
// ReSharper disable once CheckNamespace
namespace OpenGL
{
/// <summary>
/// Modern OpenGL bindings.
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
public partial class Gl : KhronosApi
{
#region Versions, Extensions and Limits
/// <summary>
/// OpenGL version currently implemented.
/// </summary>
/// <remarks>
/// Higher OpenGL versions versions cannot be requested to be implemented.
/// </remarks>
public static KhronosVersion CurrentVersion { get; private set; }
/// <summary>
/// OpenGL Shading Language version currently implemented.
/// </summary>
/// <remarks>
/// Higher OpenGL Shading Language versions cannot be requested to be implemented.
/// </remarks>
public static GlslVersion CurrentShadingVersion { get; private set; }
/// <summary>
/// Get the OpenGL vendor.
/// </summary>
public static string CurrentVendor { get; private set; }
/// <summary>
/// Get the OpenGL renderer.
/// </summary>
public static string CurrentRenderer { get; private set; }
/// <summary>
/// OpenGL extension support.
/// </summary>
public static Extensions CurrentExtensions { get; private set; }
/// <summary>
/// OpenGL limits.
/// </summary>
public static Limits CurrentLimits { get; private set; }
#endregion
#region API Binding
/// <summary>
/// Bind the OpenGL delegates for the API corresponding to the current OpenGL context.
/// </summary>
/// <param name="procLoadFunction">
/// The function OpenGL functions will be loaded through. Should be provided by your context creator.
/// </param>
public static void BindAPI(Func<string, IntPtr> procLoadFunction)
{
// Set the function loading function.
ProcLoadFunction = procLoadFunction;
// Get version.
BindAPI<Gl>(QueryContextVersionCore(), CurrentExtensions);
// Query OpenGL informations
string glVersion = GetString(StringName.Version);
CurrentVersion = KhronosVersion.Parse(glVersion);
// Query OpenGL extensions (current OpenGL implementation, CurrentCaps)
CurrentExtensions = new Extensions();
CurrentExtensions.Query();
// Query OpenGL limits
CurrentLimits = Limits.Query(CurrentVersion, CurrentExtensions);
// Obtain current OpenGL Shading Language version
string glslVersion = null;
switch (CurrentVersion.Api)
{
case KhronosVersion.API_GL:
if (CurrentVersion >= Version200 || CurrentExtensions.ShadingLanguage100_ARB)
glslVersion = GetString(StringName.ShadingLanguageVersion);
break;
case KhronosVersion.API_GLES2:
glslVersion = GetString(StringName.ShadingLanguageVersion);
break;
}
if (glslVersion != null)
CurrentShadingVersion = GlslVersion.Parse(glslVersion, CurrentVersion.Api);
// Vendor/Render information
CurrentVendor = GetString(StringName.Vendor);
CurrentRenderer = GetString(StringName.Renderer);
}
/// <summary>
/// Query the version of the current OpenGL context.
/// </summary>
/// <returns>
/// It returns the <see cref="KhronosVersion" /> specifying the actual version of the context current on this thread.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Exception thrown if no GL context is current on the calling thread.
/// </exception>
public static KhronosVersion QueryContextVersion()
{
// Parse version string (effective for detecting Desktop and ES contextes)
string str = GetString(StringName.Version);
KhronosVersion glVersion = KhronosVersion.Parse(str);
// Context profile
if (glVersion.Api == KhronosVersion.API_GL && glVersion >= Version320)
{
string glProfile;
Get(CONTEXT_PROFILE_MASK, out int ctxProfile);
if ((ctxProfile & CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0)
glProfile = KhronosVersion.PROFILE_COMPATIBILITY;
else if ((ctxProfile & CONTEXT_CORE_PROFILE_BIT) != 0)
glProfile = KhronosVersion.PROFILE_CORE;
else
glProfile = KhronosVersion.PROFILE_COMPATIBILITY;
return new KhronosVersion(glVersion, glProfile);
}
else
{
return new KhronosVersion(glVersion, KhronosVersion.PROFILE_COMPATIBILITY);
}
}
/// <summary>
/// Query the version of the current OpenGL context.
/// </summary>
/// <returns>
/// It returns the <see cref="KhronosVersion" /> specifying the actual version of the context current on this thread.
/// </returns>
public static KhronosVersion QueryContextVersionCore()
{
BindAPIFunction<Gl>("glGetError", Version100, null);
BindAPIFunction<Gl>("glGetString", Version100, null);
BindAPIFunction<Gl>("glGetIntegerv", Version100, null);
return QueryContextVersion();
}
/// <summary>
/// Query the OpenGL version without binding the API.
/// </summary>
/// <param name="procLoadFunction">The function OpenGL functions will be loaded through (in this case glGetString only).</param>
/// <returns>
/// It returns the <see cref="KhronosVersion" /> specifying the actual version of the context current on this
/// thread.
/// </returns>
public static KhronosVersion QueryVersionExternal(Func<string, IntPtr> procLoadFunction)
{
IntPtr func = procLoadFunction("glGetString");
if (func == IntPtr.Zero) return null;
var getString = Marshal.GetDelegateForFunctionPointer<Delegates.glGetString>(func);
IntPtr ptr = getString((int) StringName.Version);
string str = NativeHelpers.StringFromPtr(ptr);
return KhronosVersion.Parse(str);
}
#endregion
#region Error Handling
/// <summary>
/// OpenGL error checking.
/// </summary>
public static void CheckErrors()
{
ErrorCode error = GetError();
if (error != ErrorCode.NoError)
throw new GlException(error);
}
/// <summary>
/// Flush GL errors queue.
/// </summary>
private static void ClearErrors()
{
while (GetError() != ErrorCode.NoError)
// ReSharper disable once EmptyEmbeddedStatement
;
}
/// <summary>
/// OpenGL error checking.
/// </summary>
/// <param name="returnValue">
/// A <see cref="Object" /> that specifies the function returned value, if any.
/// </param>
[Conditional("DEBUG")]
// ReSharper disable once UnusedParameter.Local
private static void DebugCheckErrors(object returnValue)
{
CheckErrors();
}
#endregion
#region Hand-crafted Bindings
/// <summary>
/// Specify a callback to receive debugging messages from the GL.
/// </summary>
/// <param name="source">
/// A <see cref="DebugSource" /> that specify the source of the message.
/// </param>
/// <param name="type">
/// A <see cref="DebugType" /> that specify the type of the message.
/// </param>
/// <param name="id">
/// A <see cref="UInt32" /> that specify the identifier of the message.
/// </param>
/// <param name="severity">
/// A <see cref="DebugSeverity" /> that specify the severity of the message.
/// </param>
/// <param name="length">
/// The length of the message.
/// </param>
/// <param name="message">
/// A <see cref="IntPtr" /> that specify a pointer to a null-terminated ASCII C string, representing the content of the
/// message.
/// </param>
/// <param name="userParam">
/// A <see cref="IntPtr" /> that specify the user-specified parameter.
/// </param>
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
public delegate void DebugProc(DebugSource source, DebugType type, uint id, DebugSeverity severity, int length, IntPtr message, IntPtr userParam);
/// <summary>
/// </summary>
/// <returns></returns>
public delegate IntPtr VulkanProc();
/// <summary>
/// specify values to record in transform feedback buffers
/// </summary>
/// <param name="program">
/// The name of the target program object.
/// </param>
/// <param name="varyings">
/// An array of zero-terminated strings specifying the names of the varying variables to use for
/// transform feedback.
/// </param>
/// <param name="bufferMode">
/// Identifies the mode used to capture the varying variables when transform feedback is active.
/// <paramref
/// name="bufferMode" />
/// must be Gl.INTERLEAVED_ATTRIBS or Gl.SEPARATE_ATTRIBS.
/// </param>
/// <remarks>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Gl.INVALID_VALUE is generated if <paramref name="program" /> is not the name of a program object.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Gl.INVALID_VALUE is generated if <paramref name="bufferMode" /> is Gl.SEPARATE_ATTRIBS and the length of
/// <paramref name="varyings" /> is
/// greater than the implementation-dependent limit Gl.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS.
/// </exception>
/// <seealso cref="Gl.BeginTransformFeedback" />
/// <seealso cref="Gl.EndTransformFeedback" />
/// <seealso cref="Gl.GetTransformFeedbackVarying" />
[RequiredByFeature("GL_VERSION_3_0")]
[RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")]
[RequiredByFeature("GL_EXT_transform_feedback")]
public static void TransformFeedbackVaryings(uint program, IntPtr[] varyings, int bufferMode)
{
unsafe
{
fixed (IntPtr* p_varyings = varyings)
{
Debug.Assert(Delegates.pglTransformFeedbackVaryings_Unmanaged != null, "pglTransformFeedbackVaryings not implemented");
Delegates.pglTransformFeedbackVaryings_Unmanaged(program, varyings.Length, p_varyings, bufferMode);
}
}
DebugCheckErrors(null);
}
internal static unsafe partial class Delegates
{
[SuppressUnmanagedCodeSecurity]
internal delegate void glTransformFeedbackVaryings_Unmanaged(uint program, int count, IntPtr* varyings, int bufferMode);
[RequiredByFeature("GL_VERSION_3_0", EntryPoint = "glTransformFeedbackVaryings")]
[RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2", EntryPoint = "glTransformFeedbackVaryings")]
[RequiredByFeature("GL_EXT_transform_feedback", EntryPoint = "glTransformFeedbackVaryingsEXT")]
[ThreadStatic]
internal static glTransformFeedbackVaryings_Unmanaged pglTransformFeedbackVaryings_Unmanaged;
}
#endregion
/// <summary>
/// Convert a pixel type enum to the number of bytes that type contains.
/// </summary>
/// <param name="pixelType">The pixel type to get the byte count of.</param>
/// <returns>The number of bytes that pixel type contains.</returns>
public static byte PixelTypeToByteCount(PixelType pixelType)
{
switch (pixelType)
{
case PixelType.UnsignedByte:
case PixelType.Byte:
return 1;
case PixelType.Double:
return 8;
case PixelType.UnsignedInt248:
case PixelType.Int:
case PixelType.UnsignedInt:
case PixelType.Float:
return 4;
case PixelType.UnsignedShort:
case PixelType.Short:
case PixelType.HalfFloat:
return 2;
default:
return 0;
}
}
/// <summary>
/// Gets the amount of components in the pixel format.
/// </summary>
/// <param name="pixelFormat">The pixel format to get the components of.</param>
/// <returns>How many components the pixel format has.</returns>
public static byte PixelTypeToComponentCount(PixelFormat pixelFormat)
{
switch (pixelFormat)
{
case PixelFormat.Bgra:
case PixelFormat.Rgba:
case PixelFormat.BgraInteger:
case PixelFormat.RgbaInteger:
return 4;
case PixelFormat.Red:
case PixelFormat.Green:
case PixelFormat.Blue:
case PixelFormat.Alpha:
case PixelFormat.RedInteger:
case PixelFormat.GreenInteger:
case PixelFormat.BlueInteger:
return 1;
case PixelFormat.DepthStencil:
case PixelFormat.DepthComponent:
return 1;
case PixelFormat.Rgb:
case PixelFormat.RgbInteger:
case PixelFormat.Bgr:
return 3;
default:
return 0;
}
}
}
}
| |
// LayoutDetails.cs
//
// Copyright (c) 2013 Brent Knowles (http://www.brentknowles.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.
//
// Review documentation at http://www.yourothermind.com for updated implementation notes, license updates
// or other general information/
//
// Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW
// Full source code: https://github.com/BrentKnowles/YourOtherMind
//###
using System;
using System.Collections;
using System.Collections.Generic;
using CoreUtilities;
using System.Windows.Forms;
using System.Drawing;
using Transactions;
using System.IO;
namespace Layout
{
/// <summary>
/// Wiill hold info about NoteTypes, About the active layoutpanel
/// </summary>
public class LayoutDetails
{
public static string SIDEDOCK = "system_sidedock";
public static string TABLEGUID = "tables"; // name of panel containing the tables on the system note
// the list of events (deleting, submissions, worklogs)
private List<Type> transactionsLIST = new List<Type>();
// this list TEMPORARILY stores, during a LayoutPanel Load, the list of notes requesting an Update-after-load-finishes. LayoutPanel does this form this. TODO: This is a poor implementation
public List<NoteDataInterface> UpdateAfterLoadList = new List<NoteDataInterface>();
public void AddTo_TransactionsLIST (Type newType)
{
try {
transactionsLIST.Add (newType);
} catch (Exception ex) {
NewMessage.Show (ex.ToString());
}
// NewMessage.Show (((TransactionBase)Activator.CreateInstance (newType)).Display);
}
#region constants
// for testing and want certain minor warnings not to trigger. use sparingly
public bool SuppressWarnings = false;
public static string SYSTEM_QUERIES ="list_queries";
public const string SYSTEM_RANDOM_TABLES = "list_randomtables";
public const string SYSTEM_NOTEBOOKS = "list_notebooks";
public const string SYSTEM_STATUS = "list_status";
public const string SYSTEM_SUBTYPE = "list_subtypes";
public const string SYSTEM_KEYWORDS = "list_keywords";
// March 2013
// these two tables need to be in System because of the way I'm storing and loading them from the serialized market table
//public const string SYSTEM_PUBLISHTYPES ="list_publishtypes";
//public const string SYSTEM_MARKETTYPES ="list_markettypes";
//public const string SYSTEM_WORKLOGCATEGORY="list_worklogcategory";
//public const string SYSTEM_GRAMMAR="list_grammar";
#endregion
#region variables
public NoteDataInterface currentCopiedNote=null;
/// <summary>
/// Gets or sets the current copied note.
/// </summary>
/// <value>
/// The current copied note.
/// </value>
public NoteDataInterface CurrentCopiedNote {
get {
return currentCopiedNote;
}
set {
currentCopiedNote = value;
}
}
protected static volatile LayoutDetails instance;
protected static object syncRoot = new Object();
// Used when forms have an OK and Cancel button; this the height of the panel
public const int ButtonHeight = 50;
// set in main constructor
public Icon MainFormIcon = null;
public FormUtils.FontSize MainFormFontSize = FormUtils.FontSize.Normal;
// used when needing random numbers
public Random RandomNumbers;
public List<Color> HighlightColorList = new List<Color>();
public LayoutPanelBase SystemLayout = null;
public LayoutPanelBase TableLayout = null;
ToolStripProgressBar progress=null;
public ToolStripProgressBar Progress {
get {
return progress;
}
set {
progress = value;
}
}
private WordsSystem wordSystemInUse = null;
public WordsSystem WordSystemInUse {
get {
if (null == wordSystemInUse)
{
// instead of setting in main form
// we just create a default if none was established
wordSystemInUse = new WordsSystem();
}
return wordSystemInUse;
}
set {
wordSystemInUse = value;
}
}
private LayoutPanelBase currentLayout;
public LayoutPanelBase CurrentLayout {
get { return currentLayout;}
set {
currentLayout = value;
if (null != value)
{
if (UpdateTitle != null )
{
//currentLayout
UpdateTitle(currentLayout.Caption);
}
lg.Instance.Line ("LayoutDetails->CurrentLayout", ProblemType.MESSAGE, "Setting Layout to " + currentLayout.GUID);
}
else
{
// if null, blank the title
UpdateTitle("");
}
}
}
public Action<string, string> LoadLayoutRef= null;
public Action<string> UpdateTitle = null;
private bool titleUpdateSuspended = false;
/// <summary>
/// Gets a value indicating whether this instance is title suspended.
/// </summary>
/// <value>
/// <c>true</c> if this instance is title suspended; otherwise, <c>false</c>.
/// </value>
public bool IsTitleSuspended {
get {
return titleUpdateSuspended;
}
}
/// <summary>
/// Suspends the title update.
/// </summary>
/// <param name='Suspend'>
/// If set to <c>true</c> suspend.
/// </param>
public void SuspendTitleUpdate (bool Suspend)
{
titleUpdateSuspended = Suspend;
}
private appframe.MainFormBase MainForm = null;
public void SetMainForm (appframe.MainFormBase mainForm)
{
MainForm = mainForm;
}
/// <summary>
/// Wrapper to run a hot-key from SOMEWHERE other than a key press
/// </summary>
/// <param name='code'>
/// Code.
/// </param>
public void ManualRunHotkeyOperation (string code)
{
if (MainForm != null) {
MainForm.ManualRunHotkeyOperation(code);
}
}
// in rare case of harddrive failure this variable can be set and checked when the application closes to prevent saving empty files (December 2012)
// for YOM this is Set ONLY IN MainformBase
public bool ForceShutdown = false;
// added this for testing purposes
public string OverridePath=Constants.BLANK;
public void DoUpdateTitle (string newTitle)
{
if (UpdateTitle != null) {
UpdateTitle(newTitle);
}
}
public string Path {
get {
string path = "";
#if(DEBUG)
path = System.IO.Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments), "YOMDEBUG");
#else
path =System.IO.Path.Combine ( Environment.CurrentDirectory, "YourOtherMind");
#endif
if (Constants.BLANK != OverridePath)
{
path = OverridePath;
}
if (!System.IO.Directory.Exists (path)) {
System.IO.Directory.CreateDirectory(path);
}
return path;
}
}
private string yom_database= Constants.BLANK;
// Moved from LayoutDatabase into ths so it can more easily be overridden by unit tests
// We return the standard name for database, with the path UNLESS it has been overridden by a set WHICH should only happen during unit testing
public virtual string YOM_DATABASE {
get {
string path = "";
if (yom_database == Constants.BLANK) {
path = System.IO.Path.Combine (LayoutDetails.Instance.Path, "yomdata.s3db");
} else
path=yom_database;
return path;
}
set {
yom_database = value;
}
}
#endregion;
#region callbacks
public delegate AppearanceClass GetAppearanceFromStorageTYPE(string Key);
public GetAppearanceFromStorageTYPE GetAppearanceFromStorage;
public Func<System.Collections.Generic.List<string>> GetListOfAppearancesDelegate=null;
#endregion
// other PLACES will modify this list, when registering new types
//private ArrayList TypeList = null;
//private ArrayList NameList = null;
private List<NoteTypeDetails> ListOfNoteTypes = new List<NoteTypeDetails>();
public List<NoteTypeDetails> GetListOfNoteTypeDetails ()
{
return ListOfNoteTypes;
}
public void WaitCursor (bool b)
{
if (LayoutDetails.Instance.CurrentLayout != null) {
if (true == b)
{
LayoutDetails.Instance.CurrentLayout.Cursor = Cursors.WaitCursor;
}
else{
LayoutDetails.Instance.CurrentLayout.Cursor = Cursors.Default;
}
}
}
/// <summary>
/// Clears the dragging of notes on A layout. If stuck in dragmode
/// </summary>
public void ClearDraggingOfNotesOnALayout ()
{
if (CurrentLayout != null) {
CurrentLayout.ClearDrag();
}
}
public LayoutDetails ()
{
RandomNumbers = new Random();
//TypeList = new Type[4] {typeof(NoteDataXML), typeof(NoteDataXML_RichText), typeof(NoteDataXML_NoteList), typeof(NoteDataXML_SystemOnly)};
// TypeList = new ArrayList();
// NameList = new ArrayList();
AddToList(typeof(NoteDataXML),new NoteDataXML().RegisterType());
AddToList(typeof(NoteDataXML_RichText),new NoteDataXML_RichText().RegisterType ());
AddToList (typeof(NoteDataXML_NoteList),new NoteDataXML_NoteList().RegisterType());
AddToList (typeof(NoteDataXML_Table),new NoteDataXML_Table().RegisterType());
AddToList(typeof(NoteDataXML_LinkNote), new NoteDataXML_LinkNote().RegisterType());
AddToList(typeof(NoteDataXML_Timeline), new NoteDataXML_Timeline().RegisterType());
AddToList(typeof(NoteDataXML_GroupEm), new NoteDataXML_GroupEm().RegisterType());
// AddToList (typeof(NoteDataXML_SystemOnly),new NoteDataXML_SystemOnly().RegisterType());
Markups = new List<iMarkupLanguage> ();
Markups.Add (new MarkupLanguageNone ());
}
public void DoForceShutDown(bool ShutDown)
{
Layout.LayoutDetails.Instance.ForceShutdown = ShutDown;
}
/// <summary>
/// This is how we decide to load a new layout. This is a link set in the MainForm
/// that calls the main LoadLayout routine therein.
///
/// If opened already, it will 'bring it to front'
///
/// </summary>
/// <param name='guid'>
/// GUID.
/// </param>
public void LoadLayout (string guid, string childGuid)
{
if (null != LoadLayoutRef) {
LoadLayoutRef (guid, childGuid);
} else {
throw new Exception("A reference needs to be set in the MainForm to the method to use when loading a new method. That did not happen today.");
}
}
/// <summary>
/// Loads the layout.
/// 30/06/2014
/// - can pass text that the layout attempts to find on the child note
/// </summary>
/// <param name='guid'>
/// GUID.
/// </param>
/// <param name='childGuid'>
/// Child GUID.
/// </param>
/// <param name='TextToSearchForOnChild'>
/// Text to search for on child.
/// </param>
public void LoadLayout (string guid, string childGuid, string TextToSearchForOnChild)
{
if (null != LoadLayoutRef) {
LoadLayoutRef (guid, childGuid);
if (CurrentLayout != null && CurrentLayout.CurrentTextNote != null)
{
FindBarStatusStrip find = CurrentLayout.GetFindbar();
if (find != null)
{
CurrentLayout.FocusOnFindBar();
find.DoFind (TextToSearchForOnChild, false, CurrentLayout.CurrentTextNote.GetRichTextBox() ,0);
}
}
} else {
throw new Exception("A reference needs to be set in the MainForm to the method to use when loading a new method. That did not happen today.");
}
}
public void LoadLayout (string guid)
{
if (null != LoadLayoutRef) {
LoadLayoutRef (guid, Constants.BLANK);
} else {
throw new Exception("A reference needs to be set in the MainForm to the method to use when loading a new method. That did not happen today.");
}
}
/// <summary>
/// Adds to both lists.
/// Will not add it if it already esxists
/// </summary>
/// <param name='newType'>
/// New type.
/// </param>
/// <param name='newAssembly'>
/// New assembly.
/// </param>
public void AddToList (Type newType, string name)
{
AddToList (newType, name, Constants.BLANK);
}
public void AddToList (Type newType, string name, string folder)
{
// if (TypeList.IndexOf (newType) == -1) {
// TypeList.Add (newType);
// NameList.Add (name);
//
// }
if (Constants.BLANK == folder) {
// probably do nothing
}
if (ListOfNoteTypes.Find (NoteTypeDetails=>NoteTypeDetails.TypeOfNote == newType) != null)
{
}
else
{
// A new one. Let us add it.
NoteTypeDetails newNoteType = new NoteTypeDetails();
newNoteType.TypeOfNote = newType;
newNoteType.NameOfNote = name;
newNoteType.Folder = folder;
ListOfNoteTypes.Add(newNoteType);
}
}
public void RemoveFromList (Type newType)
{
NoteTypeDetails newNoteType = ListOfNoteTypes.Find (NoteTypeDetails => NoteTypeDetails.TypeOfNote == newType);
if (null != newNoteType) {
ListOfNoteTypes.Remove (newNoteType);
}
// if (TypeList.IndexOf (newType) > -1) {
// TypeList.Remove(newType);
// }
}
/// <summary>
/// Gets the type of the name from.
/// Assumes namelist and typelist are equal at all times
/// </summary>
/// <returns>
/// The name from type.
/// </returns>
/// <param name='lookupType'>
/// Lookup type.
/// </param>
public string GetNameFromType (Type lookupType)
{
NoteTypeDetails newNoteType = ListOfNoteTypes.Find (NoteTypeDetails => NoteTypeDetails.TypeOfNote == lookupType);
if (newNoteType != null) {
return newNoteType.NameOfNote;
}
return Constants.ERROR;
// if (NameList.Count != TypeList.Count) {
// throw new Exception("Must be same number of type names as types");
// }
// int index = TypeList.IndexOf (lookupType);
// if (index >= 0) {
// return NameList[index].ToString ();
// }
// return Constants.ERROR;
}
public Type[] ListOfTypesToStoreInXML ()
{
ArrayList TypesA = new ArrayList ();
foreach (NoteTypeDetails nd in ListOfNoteTypes) {
TypesA.Add (nd.TypeOfNote);
}
Type[] ArrayOfTypes = new Type[ListOfNoteTypes.Count];
TypesA.CopyTo(ArrayOfTypes);
return ArrayOfTypes;
}
public static ToolStripMenuItem BuildMenuPropertyEdit (string Label, string Title, string ToolTip, KeyEventHandler action)
{
return BuildMenuPropertyEdit(Label, Title, ToolTip, action, -1);
}
/// <summary>
/// Convenience function to make it easier to build Menu option that show the 'Field' and then allow a sideclick to edit them.
/// </summary>
/// <returns>
/// The menu property edit.
/// </returns>
/// <param name='Title'>
/// Title.
/// </param>
/// <param name='ToolTip'>
/// Tool tip.
/// </param>
/// <param name='action'>
/// Action.
/// </param>
public static ToolStripMenuItem BuildMenuPropertyEdit (string Label, string Title, string ToolTip, KeyEventHandler action, int truncate)
{
ToolStripMenuItem TableCaptionLabel = new ToolStripMenuItem ();
TableCaptionLabel.Text = String.Format (Label, Title);
//
// Truncate text if specified
//
if (truncate > 0 && truncate < TableCaptionLabel.Text.Length) {
TableCaptionLabel.Text = TableCaptionLabel.Text.Substring(0, truncate) + "...";
}
TableCaptionLabel.ToolTipText = ToolTip;
ContextMenuStrip TableCaptionMenu = new ContextMenuStrip ();
ToolStripTextBox TableCaptionText = new ToolStripTextBox ();
TableCaptionLabel.Tag = Label; // this is the format label // label is a format string like "Field: {0}"
TableCaptionText.Tag = TableCaptionLabel;
TableCaptionText.Text = Title;
TableCaptionText.KeyDown += action;
TableCaptionMenu.Items.Add (TableCaptionText);
TableCaptionLabel.DropDown = TableCaptionMenu;
return TableCaptionLabel;
}
public static void HandleMenuLabelEdit (object sender, KeyEventArgs e, ref string Caption, Action<bool>SetSaveRequired)
{
if (e.KeyData == Keys.Enter) {
// the header is not updated unti enter pressed but the NAME is being updated
Caption = (sender as ToolStripTextBox).Text;
if ((sender as ToolStripTextBox).Tag != null && ((sender as ToolStripTextBox).Tag is ToolStripMenuItem)) {
string formatstring = ((sender as ToolStripTextBox).Tag as ToolStripMenuItem).Tag.ToString();
((sender as ToolStripTextBox).Tag as ToolStripMenuItem).Text = String.Format (formatstring, Caption);
}
// silenece beep
e.SuppressKeyPress = true;
SetSaveRequired (true);
}
}
public static LayoutDetails Instance
{
get
{
if (null == instance)
{
// only one instance is created and when needed
lock (syncRoot)
{
if (null == instance)
{
instance = new LayoutDetails();
instance.HighlightColorList.Add (Color.BurlyWood);
instance.HighlightColorList.Add (Color.Yellow);
instance.HighlightColorList.Add (Color.CornflowerBlue);
instance.HighlightColorList.Add (Color.Red);
instance.HighlightColorList.Add (Color.Green);
instance.HighlightColorList.Add (Color.White);
instance.HighlightColorList.Add (Color.Black);
instance.HighlightColorList.Add (Color.MediumSpringGreen);
instance.HighlightColorList.Add (Color.Aquamarine);
instance.HighlightColorList.Add (Color.GreenYellow);
instance.HighlightColorList.Add (Color.LightSalmon);
instance.HighlightColorList.Add (Color.Blue);
instance.HighlightColorList.Add (Color.Sienna);
instance.HighlightColorList.Add (Color.PeachPuff);
}
}
}
return (LayoutDetails)instance;
}
}
// The Data Wrappers -- Here is where the specific subclass/impelmentation of interfaces are used
public static LayoutInterface DATA_Layout(string GUID)
{
return new LayoutDatabase(GUID);
}
string layoutlink = Constants.BLANK;
public void PushLink(string identifier)
{
layoutlink = identifier;
}
/// <summary>
/// Grabs the existing link from the list and clears it
/// </summary>
/// <returns>
/// The link.
/// </returns>
public string PopLink()
{
string result = layoutlink;
layoutlink = Constants.BLANK;
return result;
}
private TransactionsTable transactionsList=null;
List<Type> GetListOfTransacitonTypesAddedByAddIns ()
{
return transactionsLIST;
}
/// <summary>
/// Access to the event table
/// </summary>
/// <value>
/// The events list.
/// </value>
public TransactionsTable TransactionsList {
get {
if (transactionsList == null) throw new Exception ("Tran list has not been setup.");
return transactionsList;
}
set {
// when we set the transaction list we set a callback to get the list of types
transactionsList = value;
transactionsList.TransactionTypesAddedThroughAddIns += GetListOfTransacitonTypesAddedByAddIns;
}
}
/// <summary>
/// Focuses the on find bar. Ctrl +F
/// </summary>
// public void FocusOnFindBar ()
// {
// if (CurrentLayout != null) {
// CurrentLayout.FocusOnFindBar();
// }
// }
#region markup
// List of available markup languages
List<iMarkupLanguage> Markups=null;
iMarkupLanguage CurrentMarkup=null;
public void AddMarkupToList (iMarkupLanguage newMarkup)
{
Markups.Add (newMarkup);
}
/// <summary>
/// Gets the markup match. Used in the Interfact options panel
/// to figure out which type was saved as the default
/// the value is the type stored in the database
/// </summary>
/// <param name='value'>
/// Value.
/// </param>
public iMarkupLanguage GetMarkupMatch (string value)
{
foreach (iMarkupLanguage mark in Markups) {
if (mark.GetType().AssemblyQualifiedName == value)
{
return mark;
}
}
return null;
}
public void RemoveMarkupFromList (Type markup)
{
iMarkupLanguage removeMe = null;
foreach (iMarkupLanguage Mark in Markups) {
if (Mark.GetType () == markup) {
removeMe = Mark;
}
}
if (null != removeMe) {
Markups.Remove(removeMe);
}
}
public iMarkupLanguage GetCurrentMarkup ()
{
if (null == CurrentMarkup) {
CurrentMarkup = new MarkupLanguageNone();
}
return CurrentMarkup;
}
public void SetCurrentMarkup (iMarkupLanguage newMarkup)
{
// set when options menu closes and when MainForm opens
if (null != newMarkup) {
CurrentMarkup = newMarkup;
}
}
public void BuildMarkupComboBox (ComboBox markupCombo)
{
foreach (iMarkupLanguage language in Markups) {
markupCombo.Items.Add (language);
}
}
public void BuildMarkupComboBox (ToolStripComboBox markupCombo)
{
foreach (iMarkupLanguage language in Markups) {
markupCombo.Items.Add (language);
}
}
/// <summary>
/// Returns a simple text form to use for Building Reports
/// </summary>
/// <returns>
/// The text form to use.
/// </returns>
public GenericTextForm GetTextFormToUse()
{
return new GenericTextForm();
}
public System.Collections.Generic.List<string> GetListOfAppearances ()
{
if (GetListOfAppearancesDelegate != null) {
return GetListOfAppearancesDelegate();
}
return null;
}
public void PurgeAppearanceCache ()
{
AppearanceCache = new Hashtable();
}
Hashtable AppearanceCache = new Hashtable();
// System.Collections.SortedList AppearanceCache = new SortedList();
//List<Appearance> AppearanceCache = new List<Appearance>();
public AppearanceClass GetAppearanceByName (string classic)
{
if (null == GetAppearanceFromStorage) {
throw new Exception("A callback to GetAppearanceFromStorage needs to be defined when application initalizes");
}
//Hashtable attempt 6.7 seconds to 6.4 on second attempt
AppearanceClass app = (AppearanceClass)AppearanceCache [classic];
if (app != null) {
} else {
app = GetAppearanceFromStorage(classic);
if (app == null)
{
NewMessage.Show (Loc.Instance.GetStringFmt("The appearance {0} no longer exists, reverting to default.", classic));
// somehow we have lost an appearance then we just use clasic
app = AppearanceClass.SetAsClassic();
}
//app = new Appearance();
//app.SetAsClassic();
AppearanceCache.Add (classic, app);
}
//6.4 seconds to 6.9
// Appearance app = (Appearance)AppearanceCache [classic];
// if (app != null) {
// } else {
// NewMessage.Show ("Hack : 'grabbing app from database. Should see this only once a session");
// app = new Appearance();
// app.SetAsClassic();
//
// AppearanceCache.Add (classic, app);
// }
//
// 1. Look to see if it already exist. If so, retrieve it. about 6.6 seconds on zombie
// IF NOT, load from database
/* This seemed faster than Sorted list
Appearance app = AppearanceCache.Find (Appearance => Appearance.Name == classic);
if (app != null) {
}
else
{
NewMessage.Show ("Hack : 'grabbing app from database. Should see this only once a session");
app = new Appearance();
app.SetAsClassic();
AppearanceCache.Add (app);
}
*/
return app;
}
#endregion
public static void SupressBeep (KeyPressEventArgs e)
{
//e.SuppressKeyPress = true;
e.Handled = true;
}
/// <summary>
/// called from SaveTextLineToFile
/// </summary>
/// <param name="NoteToOpen">if present and we encounter [[title]] we replace [[title]] with NoteToOpen /// </param>
/// <param name="sText"></param>
void SaveTextLineByLine (StreamWriter writer, string[] linesOfText, string empty)
{
foreach (string s in linesOfText)
{
writer.WriteLine(s);
}
}
int WriteANote (NoteDataInterface note, bool bGetWords, ref string sWordInformation, StreamWriter writer)
{
int words = 0;
if (note != null && (note is NoteDataXML_RichText))
{
RichTextBox tempBox = new RichTextBox();
tempBox.Rtf = note.Data1;
SaveTextLineByLine(writer, tempBox.Lines, note.Caption);
if (true == bGetWords)
{
int Words =
LayoutDetails.Instance.WordSystemInUse.CountWords(tempBox.Text);
words = Words;//TotalWords = TotalWords + Words;
sWordInformation = sWordInformation + String.Format("{0}: {1}{2}", note.Caption, Words.ToString(), Environment.NewLine);
}
tempBox.Dispose();
}
return words;
}
/// <summary>
/// Goes through rich edit line by line saving to a plain text file
///
/// December 2009
/// Here we need to do a redesign.
///
/// If we encounter [[index]] on the first line we know that we have an index page. So instead we need to do the following:
///
/// Each line is either a NOTE NAME to add to the text file (which will be parsed line by line and converted to plain text)
///
/// OR
///
/// It returns a list of names that are then parsed line by line as above, in the order of the list
///
/// An example index would be
/// [[index]]
/// _Header [[words]]
/// [[Group,Storyboard,Chapter*,words] !- This returns an array of note names that match the criteria (i.e., Chapter 01, Chapter 02)
/// _Footer
///
///
///
/// * Note: Choose not to let the groups handl
/// </summary>
/// <param name="sFile"></param>
public void SaveTextLineToFile (string[] LinesOfText, string sFilepath)
{
string sWordInformation = "";
int TotalWords = 0;
bool bGetWords = false;
// certain Addins like spellchecking won't both writing a file out
if (sFilepath != Constants.BLANK) {
try {
StreamWriter writer = new StreamWriter (sFilepath);
//
// if (LayoutDetails.Instance.CurrentLayout != null && LayoutDetails.Instance.CurrentLayout.CurrentTextNote != null)
// {
// NewMessage.Show (Loc.Instance.GetString ("The current markup does not support Sending-Away files correctly. Did you forget to set the current markup in the Options menu?"));
// if (LayoutDetails.Instance.CurrentLayout.CurrentTextNote is NoteData
// }
ArrayList ListOfParsePages = new ArrayList ();
if (LayoutDetails.Instance.GetCurrentMarkup().IsIndex(LinesOfText [0].ToLower ()) == true)
{
//if (LinesOfText [0].ToLower () == "[[index]]") {
// we are actually an index note
// which will instead list a bunch of other pages to use
// we now iterate through LinesOfText[1] to end and parse those instead
for (int i = 1; i < LinesOfText.Length; i++) {
string sLine = LinesOfText [i];
bool WordCountRequested = false;
if (LayoutDetails.Instance.GetCurrentMarkup().IsOver(sLine))
{
// if we hit a manual terminate then we exit adding pages
// this is used if we want notes on an index page but
// don't want to waste time trying to parse them
break;
}
if (LayoutDetails.Instance.GetCurrentMarkup().IsWordRequest(sLine))
{
// if we have the words keyword we know we want to display some word info at the end
sLine = LayoutDetails.Instance.GetCurrentMarkup().CleanWordRequest(sLine);
bGetWords = true;
WordCountRequested = true;
}
if (LayoutDetails.Instance.GetCurrentMarkup().IsGroupRequest(sLine)) {
ArrayList tmp = LayoutDetails.Instance.GetCurrentMarkup().GetListOfPages(sLine, ref bGetWords, LayoutDetails.Instance.CurrentLayout);
ListOfParsePages.AddRange(tmp);
// we have a group
} else {
if (false == WordCountRequested)
{
// at any point we encounter [[words]] we switch to counting words
ListOfParsePages.Add (sLine);
}
}
// panel.Dispose(); Don't think I can do this becauseit would dlette hte note, benig an ojbect
// may 2013 - moving the iteration outside generation loopListOfParsePages = null;
}
} else {
// not an index
SaveTextLineByLine (writer, LinesOfText, "");
}
if (ListOfParsePages != null)
{
// Now we go through the pages and write them into the text file
// feb 19 2010 - added because chapter notes were not coming out in alphaetical
ListOfParsePages.Sort ();
foreach (string notetoopen in ListOfParsePages) {
// DrawingTest.NotePanel panel = ((mdi)_CORE_GetActiveChild()).page_Visual.GetPanelByName(notetoopen);
NoteDataInterface note = LayoutDetails.Instance.CurrentLayout.FindNoteByName(notetoopen);
if (note != null)
{
// may 2013
// if a panel is specified then we open each note on that panel?
if (note.ListOfSubnotes() != null)
{
// we don't know about panels directly at this level
// so we query if there are subnotes
// IF SO: then we parse them
// may 27 2013 - also need to sort subpages coming from a panel
List<string> subpages = note.ListOfSubnotes();
subpages.Sort ();
foreach (string s in subpages)
{
NoteDataInterface subnote = LayoutDetails.Instance.CurrentLayout.FindNoteByName(s);
// subnote = LayoutDetails.Instance.CurrentLayout.GoToNote(subnote);
if (null != subnote)
{
TotalWords = TotalWords + WriteANote(subnote, bGetWords, ref sWordInformation, writer);
}
}
}
else
{
// just a normal note
TotalWords = TotalWords + WriteANote(note, bGetWords, ref sWordInformation, writer);
}
}
} //open each note list
}//list not nulls
writer.Close ();
writer.Dispose ();
if (sWordInformation != "") {
string sResult = Loc.Instance.GetStringFmt ("Total Words:{0}\n{1}", TotalWords.ToString (), sWordInformation);
Clipboard.SetText (sResult);
NewMessage.Show (Loc.Instance.GetString ("Your Text Has Been Sent! Press Ctrl + V to paste word count information into current note."));
//NewMessage.Show(sResult);
}
} catch (Exception) {
NewMessage.Show (Loc.Instance.GetStringFmt ("Unable to write to {0} please shut down and try again", sFilepath));
}
}
LinesOfText = null;
}
/// <summary>
/// Filters the by keyword.
///
/// Will *attempt* to find a Note List on the System Page and ask it to filter by the specified keyword
/// </summary>
/// <param name='text'>
/// Text.
/// </param>
public void FilterByKeyword (string text)
{
if (LayoutDetails.Instance.SystemLayout != null) {
LayoutDetails.Instance.SystemLayout.FilterByKeyword (text);
}
}
// used as an accessor to get the default font set in options
public Func<Font> GetDefaultFont = null;
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
namespace System.Collections
{
public class ArrayList
{
public object this [int index]
{
get
CodeContract.Requires(index >= 0);
CodeContract.Requires(index < this.Count);
set
CodeContract.Requires(index >= 0);
CodeContract.Requires(index < this.Count);
}
public int Capacity
{
get
CodeContract.Ensures(result >= 0);
set
CodeContract.Requires(value >= this.Count);
}
public int Count
{
get
CodeContract.Ensures(result >= 0);
}
public object SyncRoot
{
get;
}
public bool IsSynchronized
{
get;
}
public bool IsFixedSize
{
get;
}
public bool IsReadOnly
{
get;
}
public void TrimToSize () {
CodeContract.Requires(! this.IsReadOnly);
CodeContract.Requires(! this.IsFixedSize);
}
public Array ToArray (Type! type) {
CodeContract.Requires(type != null);
CodeContract.Ensures(CodeContract.Result<Array>() != null);
return default(Array);
}
public object[] ToArray () {
CodeContract.Ensures(CodeContract.Result<object[]>() != null);
return default(object[]);
}
public static ArrayList Synchronized (ArrayList! list) {
CodeContract.Requires(list != null);
CodeContract.Ensures(result.IsSynchronized);
return default(ArrayList);
}
public static IList Synchronized (IList! list) {
CodeContract.Requires(list != null);
CodeContract.Ensures(result.IsSynchronized);
return default(IList);
}
public void Sort (int index, int count, IComparer comparer) {
CodeContract.Requires(index >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Requires(index + count <= Count);
CodeContract.Requires(! this.IsReadOnly);
}
public void Sort (IComparer comparer) {
CodeContract.Requires(! this.IsReadOnly);
}
public void Sort () {
CodeContract.Requires(! this.IsReadOnly);
}
public ArrayList GetRange (int index, int count) {
CodeContract.Requires(index >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Requires(index + count <= Count);
return default(ArrayList);
}
public void SetRange (int index, ICollection! c) {
CodeContract.Requires(c != null);
CodeContract.Requires(index >= 0);
CodeContract.Requires(index + c.Count <= Count);
CodeContract.Requires(! this.IsReadOnly);
}
public void Reverse (int index, int count) {
CodeContract.Requires(index >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Requires(index + count <= Count);
CodeContract.Requires(! this.IsReadOnly);
}
public void Reverse () {
CodeContract.Requires(! this.IsReadOnly);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static ArrayList Repeat (object value, int count) {
CodeContract.Requires(count >= 0);
return default(ArrayList);
}
public void RemoveRange (int index, int count) {
CodeContract.Requires(index >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Requires(index + count <= Count);
CodeContract.Requires(! this.IsReadOnly);
CodeContract.Requires(! this.IsFixedSize);
}
public void RemoveAt (int index) {
CodeContract.Requires(index >= 0);
CodeContract.Requires(index < Count);
CodeContract.Requires(! this.IsReadOnly);
CodeContract.Requires(! this.IsFixedSize);
}
public void Remove (object obj) {
CodeContract.Requires(! this.IsReadOnly);
CodeContract.Requires(! this.IsFixedSize);
}
public static ArrayList ReadOnly (ArrayList list) {
CodeContract.Requires(list != null);
CodeContract.Ensures(result.IsReadOnly);
CodeContract.Ensures(CodeContract.Result<ArrayList>() != null);
return default(ArrayList);
}
public static IList ReadOnly (IList list) {
CodeContract.Requires(list != null);
CodeContract.Ensures(result.IsReadOnly);
CodeContract.Ensures(CodeContract.Result<IList>() != null);
return default(IList);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int LastIndexOf (object value, int startIndex, int count) {
CodeContract.Requires(0 <= count);
CodeContract.Requires(0 <= startIndex);
CodeContract.Requires(startIndex + count <= Count);
CodeContract.Ensures(-1 <= result && result < this.Count);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int LastIndexOf (object value, int startIndex) {
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(startIndex < this.Count);
CodeContract.Ensures(-1 <= result && result < this.Count);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int LastIndexOf (object value) {
CodeContract.Ensures(-1 <= result && result < this.Count);
return default(int);
}
public void InsertRange (int index, ICollection! c) {
CodeContract.Requires(c != null);
CodeContract.Requires(index >= 0);
CodeContract.Requires(index <= Count);
CodeContract.Requires(! this.IsReadOnly);
CodeContract.Requires(! this.IsFixedSize);
}
public void Insert (int index, object value) {
CodeContract.Requires(index >= 0);
CodeContract.Requires(index <= Count);
CodeContract.Requires(! this.IsReadOnly);
CodeContract.Requires(! this.IsFixedSize);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int IndexOf (object value, int startIndex, int count) {
CodeContract.Requires(0 <= count);
CodeContract.Requires(0 <= startIndex);
CodeContract.Requires(startIndex + count <= Count);
CodeContract.Ensures(-1 <= result && result < this.Count);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int IndexOf (object value, int startIndex) {
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(startIndex < this.Count);
CodeContract.Ensures(-1 <= result && result < this.Count);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int IndexOf (object value) {
CodeContract.Ensures(-1 <= result && result < this.Count);
return default(int);
}
[Pure] [GlobalAccess(false)] [Escapes(true,false)]
public IEnumerator GetEnumerator (int index, int count) {
CodeContract.Requires(index >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Ensures(result.IsNew);
CodeContract.Ensures(CodeContract.Result<IEnumerator>() != null);
return default(IEnumerator);
}
[Pure] [GlobalAccess(false)] [Escapes(true,false)]
public IEnumerator GetEnumerator () {
CodeContract.Ensures(result.IsNew);
CodeContract.Ensures(CodeContract.Result<IEnumerator>() != null);
return default(IEnumerator);
}
public static ArrayList FixedSize (ArrayList! list) {
CodeContract.Requires(list != null);
CodeContract.Ensures(result.IsFixedSize);
return default(ArrayList);
}
public static IList FixedSize (IList! list) {
CodeContract.Requires(list != null);
CodeContract.Ensures(result.IsFixedSize);
return default(IList);
}
public void CopyTo (int index, Array! array, int arrayIndex, int count) {
CodeContract.Requires(array != null);
CodeContract.Requires(array.Rank == 1);
CodeContract.Requires(index >= 0);
CodeContract.Requires(index < this.Count);
CodeContract.Requires(arrayIndex >= 0);
CodeContract.Requires(arrayIndex < array.Length);
CodeContract.Requires(count >= 0);
CodeContract.Requires(index + count <= Count);
CodeContract.Requires( arrayIndex + count <= array.Length);
}
public void CopyTo (Array! array, int arrayIndex) {
CodeContract.Requires(array != null);
CodeContract.Requires(array.Rank == 1);
CodeContract.Requires(arrayIndex >= 0);
CodeContract.Requires(arrayIndex < this.Count);
}
public void CopyTo (Array! array) {
CodeContract.Requires(array != null);
CodeContract.Requires(array.Rank == 1);
}
public bool Contains (object item) {
return default(bool);
}
public object Clone () {
return default(object);
}
public void Clear () {
CodeContract.Requires(! this.IsReadOnly);
CodeContract.Requires(! this.IsFixedSize);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int BinarySearch (object value, IComparer comparer) {
CodeContract.Ensures(-1 <= result && result < this.Count);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int BinarySearch (object value) {
CodeContract.Ensures(-1 <= result && result < this.Count);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int BinarySearch (int index, int count, object value, IComparer comparer) {
CodeContract.Requires(index >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Requires(index + count <= Count);
CodeContract.Ensures(-1 <= result && result < this.Count);
return default(int);
}
public void AddRange (ICollection! c) {
CodeContract.Requires(c != null);
CodeContract.Requires(! this.IsReadOnly);
CodeContract.Requires(! this.IsFixedSize);
}
public int Add (object value) {
CodeContract.Requires(! this.IsReadOnly);
CodeContract.Requires(! this.IsFixedSize);
CodeContract.Ensures(this.Count == old(this.Count) + 1);
return default(int);
}
public static ArrayList Adapter (IList! list) {
CodeContract.Requires(list != null);
return default(ArrayList);
}
public ArrayList (ICollection! c) {
CodeContract.Requires(c != null);
CodeContract.Ensures(this.Capacity == c.Count);
CodeContract.Ensures(this.Count == c.Count);
CodeContract.Ensures(!this.IsReadOnly && !this.IsFixedSize);
return default(ArrayList);
}
public ArrayList (int capacity) {
CodeContract.Requires(capacity >= 0);
CodeContract.Ensures(capacity == 0 ==> this.Capacity == 16);
CodeContract.Ensures(capacity > 0 ==> this.Capacity == capacity);
CodeContract.Ensures(!this.IsReadOnly && !this.IsFixedSize);
return default(ArrayList);
}
public ArrayList () {
CodeContract.Ensures(this.Count == 0);
CodeContract.Ensures(this.Capacity == 16); // stated in the documentation
CodeContract.Ensures(!this.IsReadOnly && !this.IsFixedSize);
return default(ArrayList);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
namespace System.Net.Sockets
{
public partial class Socket
{
private DynamicWinsockMethods _dynamicWinsockMethods;
private void EnsureDynamicWinsockMethods()
{
if (_dynamicWinsockMethods == null)
{
_dynamicWinsockMethods = DynamicWinsockMethods.GetMethods(_addressFamily, _socketType, _protocolType);
}
}
internal bool AcceptEx(SafeCloseSocket listenSocketHandle,
SafeCloseSocket acceptSocketHandle,
IntPtr buffer,
int len,
int localAddressLength,
int remoteAddressLength,
out int bytesReceived,
SafeHandle overlapped)
{
EnsureDynamicWinsockMethods();
AcceptExDelegate acceptEx = _dynamicWinsockMethods.GetDelegate<AcceptExDelegate>(listenSocketHandle);
return acceptEx(listenSocketHandle,
acceptSocketHandle,
buffer,
len,
localAddressLength,
remoteAddressLength,
out bytesReceived,
overlapped);
}
internal void GetAcceptExSockaddrs(IntPtr buffer,
int receiveDataLength,
int localAddressLength,
int remoteAddressLength,
out IntPtr localSocketAddress,
out int localSocketAddressLength,
out IntPtr remoteSocketAddress,
out int remoteSocketAddressLength)
{
EnsureDynamicWinsockMethods();
GetAcceptExSockaddrsDelegate getAcceptExSockaddrs = _dynamicWinsockMethods.GetDelegate<GetAcceptExSockaddrsDelegate>(_handle);
getAcceptExSockaddrs(buffer,
receiveDataLength,
localAddressLength,
remoteAddressLength,
out localSocketAddress,
out localSocketAddressLength,
out remoteSocketAddress,
out remoteSocketAddressLength);
}
internal bool DisconnectEx(SafeCloseSocket socketHandle, SafeHandle overlapped, int flags, int reserved)
{
EnsureDynamicWinsockMethods();
DisconnectExDelegate disconnectEx = _dynamicWinsockMethods.GetDelegate<DisconnectExDelegate>(socketHandle);
return disconnectEx(socketHandle, overlapped, flags, reserved);
}
internal bool DisconnectExBlocking(SafeCloseSocket socketHandle, IntPtr overlapped, int flags, int reserved)
{
EnsureDynamicWinsockMethods();
DisconnectExDelegateBlocking disconnectEx_Blocking = _dynamicWinsockMethods.GetDelegate<DisconnectExDelegateBlocking>(socketHandle);
return disconnectEx_Blocking(socketHandle, overlapped, flags, reserved);
}
internal bool ConnectEx(SafeCloseSocket socketHandle,
IntPtr socketAddress,
int socketAddressSize,
IntPtr buffer,
int dataLength,
out int bytesSent,
SafeHandle overlapped)
{
EnsureDynamicWinsockMethods();
ConnectExDelegate connectEx = _dynamicWinsockMethods.GetDelegate<ConnectExDelegate>(socketHandle);
return connectEx(socketHandle, socketAddress, socketAddressSize, buffer, dataLength, out bytesSent, overlapped);
}
internal SocketError WSARecvMsg(SafeCloseSocket socketHandle, IntPtr msg, out int bytesTransferred, SafeHandle overlapped, IntPtr completionRoutine)
{
EnsureDynamicWinsockMethods();
WSARecvMsgDelegate recvMsg = _dynamicWinsockMethods.GetDelegate<WSARecvMsgDelegate>(socketHandle);
return recvMsg(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
}
internal SocketError WSARecvMsgBlocking(IntPtr socketHandle, IntPtr msg, out int bytesTransferred, IntPtr overlapped, IntPtr completionRoutine)
{
EnsureDynamicWinsockMethods();
WSARecvMsgDelegateBlocking recvMsg_Blocking = _dynamicWinsockMethods.GetDelegate<WSARecvMsgDelegateBlocking>(_handle);
return recvMsg_Blocking(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
}
internal bool TransmitPackets(SafeCloseSocket socketHandle, IntPtr packetArray, int elementCount, int sendSize, SafeNativeOverlapped overlapped)
{
EnsureDynamicWinsockMethods();
TransmitPacketsDelegate transmitPackets = _dynamicWinsockMethods.GetDelegate<TransmitPacketsDelegate>(socketHandle);
// UseDefaultWorkerThread = 0.
return transmitPackets(socketHandle, packetArray, elementCount, sendSize, overlapped, 0);
}
internal static IntPtr[] SocketListToFileDescriptorSet(IList socketList)
{
if (socketList == null || socketList.Count == 0)
{
return null;
}
IntPtr[] fileDescriptorSet = new IntPtr[socketList.Count + 1];
fileDescriptorSet[0] = (IntPtr)socketList.Count;
for (int current = 0; current < socketList.Count; current++)
{
if (!(socketList[current] is Socket))
{
throw new ArgumentException(SR.Format(SR.net_sockets_select, socketList[current].GetType().FullName, typeof(System.Net.Sockets.Socket).FullName), nameof(socketList));
}
fileDescriptorSet[current + 1] = ((Socket)socketList[current])._handle.DangerousGetHandle();
}
return fileDescriptorSet;
}
// Transform the list socketList such that the only sockets left are those
// with a file descriptor contained in the array "fileDescriptorArray".
internal static void SelectFileDescriptor(IList socketList, IntPtr[] fileDescriptorSet)
{
// Walk the list in order.
//
// Note that the counter is not necessarily incremented at each step;
// when the socket is removed, advancing occurs automatically as the
// other elements are shifted down.
if (socketList == null || socketList.Count == 0)
{
return;
}
if ((int)fileDescriptorSet[0] == 0)
{
// No socket present, will never find any socket, remove them all.
socketList.Clear();
return;
}
lock (socketList)
{
for (int currentSocket = 0; currentSocket < socketList.Count; currentSocket++)
{
Socket socket = socketList[currentSocket] as Socket;
// Look for the file descriptor in the array.
int currentFileDescriptor;
for (currentFileDescriptor = 0; currentFileDescriptor < (int)fileDescriptorSet[0]; currentFileDescriptor++)
{
if (fileDescriptorSet[currentFileDescriptor + 1] == socket._handle.DangerousGetHandle())
{
break;
}
}
if (currentFileDescriptor == (int)fileDescriptorSet[0])
{
// Descriptor not found: remove the current socket and start again.
socketList.RemoveAt(currentSocket--);
}
}
}
}
private Socket GetOrCreateAcceptSocket(Socket acceptSocket, bool checkDisconnected, string propertyName, out SafeCloseSocket handle)
{
// If an acceptSocket isn't specified, then we need to create one.
if (acceptSocket == null)
{
acceptSocket = new Socket(_addressFamily, _socketType, _protocolType);
}
else
{
if (acceptSocket._rightEndPoint != null && (!checkDisconnected || !acceptSocket._isDisconnected))
{
throw new InvalidOperationException(SR.Format(SR.net_sockets_namedmustnotbebound, propertyName));
}
}
handle = acceptSocket._handle;
return acceptSocket;
}
}
}
| |
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class DefaultKeywordRecommenderTests : KeywordRecommenderTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AtRoot_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClass_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"class C { }
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalStatement_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalVariableDeclaration_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPreprocessor1()
{
VerifyAbsence(
@"class C {
#$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPreprocessor2()
{
VerifyAbsence(
@"class C {
#if $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterHash()
{
VerifyKeyword(
@"#line $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterHashAndSpace()
{
VerifyKeyword(
@"# line $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InEmptyStatement()
{
VerifyKeyword(AddInsideMethod(
@"$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InExpression()
{
VerifyKeyword(AddInsideMethod(
@"var q = $$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterSwitch()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterCase()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
case 0:
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDefault()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOneStatement()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
Console.WriteLine();
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterTwoStatements()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
Console.WriteLine();
Console.WriteLine();
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterBlock()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default: {
}
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIfElse()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
if (foo) {
} else {
}
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIncompleteStatement()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
Console.WriteLine(
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideBlock()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default: {
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterCompleteIf()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
if (foo)
Console.WriteLine();
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIncompleteIf()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
if (foo)
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterWhile()
{
VerifyKeyword(AddInsideMethod(
@"switch (expr) {
default:
while (true) {
}
$$"));
}
[WorkItem(552717)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGotoInSwitch()
{
VerifyAbsence(AddInsideMethod(
@"switch (expr) {
default:
goto $$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGotoOutsideSwitch()
{
VerifyAbsence(AddInsideMethod(
@"goto $$"));
}
[WorkItem(538804)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInTypeOf()
{
VerifyAbsence(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInDefault()
{
VerifyAbsence(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInSizeOf()
{
VerifyAbsence(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInObjectInitializerMemberContext()
{
VerifyAbsence(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// EventSource for Task.Parallel.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections.Generic;
using System.Text;
using System.Security;
using System.Diagnostics.Tracing;
namespace System.Threading.Tasks
{
/// <summary>Provides an event source for tracing TPL information.</summary>
[EventSource(Name = "System.Threading.Tasks.Parallel.EventSource")]
internal sealed class ParallelEtwProvider : EventSource
{
/// <summary>
/// Defines the singleton instance for the Task.Parallel ETW provider.
/// </summary>
public static readonly ParallelEtwProvider Log = new ParallelEtwProvider();
/// <summary>Prevent external instantiation. All logging should go through the Log instance.</summary>
private ParallelEtwProvider() { }
/// <summary>Type of a fork/join operation.</summary>
public enum ForkJoinOperationType
{
/// <summary>Parallel.Invoke.</summary>
ParallelInvoke = 1,
/// <summary>Parallel.For.</summary>
ParallelFor = 2,
/// <summary>Parallel.ForEach.</summary>
ParallelForEach = 3
}
/// <summary>ETW tasks that have start/stop events.</summary>
public class Tasks
{ // this name is important for EventSource
/// <summary>A parallel loop.</summary>
public const EventTask Loop = (EventTask)1;
/// <summary>A parallel invoke.</summary>
public const EventTask Invoke = (EventTask)2;
// Do not use 3, it is used for "TaskExecute" in the TPL provider.
// Do not use 4, it is used for "TaskWait" in the TPL provider.
/// <summary>A fork/join task within a loop or invoke.</summary>
public const EventTask ForkJoin = (EventTask)5;
}
/// <summary>Enabled for all keywords.</summary>
private const EventKeywords ALL_KEYWORDS = (EventKeywords)(-1);
//-----------------------------------------------------------------------------------
//
// TPL Event IDs (must be unique)
//
/// <summary>The beginning of a parallel loop.</summary>
private const Int32 PARALLELLOOPBEGIN_ID = 1;
/// <summary>The ending of a parallel loop.</summary>
private const Int32 PARALLELLOOPEND_ID = 2;
/// <summary>The beginning of a parallel invoke.</summary>
private const Int32 PARALLELINVOKEBEGIN_ID = 3;
/// <summary>The ending of a parallel invoke.</summary>
private const Int32 PARALLELINVOKEEND_ID = 4;
/// <summary>A task entering a fork/join construct.</summary>
private const Int32 PARALLELFORK_ID = 5;
/// <summary>A task leaving a fork/join construct.</summary>
private const Int32 PARALLELJOIN_ID = 6;
//-----------------------------------------------------------------------------------
//
// Parallel Events
//
#region ParallelLoopBegin
/// <summary>
/// Denotes the entry point for a Parallel.For or Parallel.ForEach loop
/// </summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="ForkJoinContextID">The loop ID.</param>
/// <param name="OperationType">The kind of fork/join operation.</param>
/// <param name="InclusiveFrom">The lower bound of the loop.</param>
/// <param name="ExclusiveTo">The upper bound of the loop.</param>
[SecuritySafeCritical]
[Event(PARALLELLOOPBEGIN_ID, Level = EventLevel.Informational, Task = ParallelEtwProvider.Tasks.Loop, Opcode = EventOpcode.Start)]
public void ParallelLoopBegin(Int32 OriginatingTaskSchedulerID, Int32 OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
Int32 ForkJoinContextID, ForkJoinOperationType OperationType, // PFX_FORKJOIN_COMMON_EVENT_HEADER
Int64 InclusiveFrom, Int64 ExclusiveTo)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
// There is no explicit WriteEvent() overload matching this event's fields. Therefore calling
// WriteEvent() would hit the "params" overload, which leads to an object allocation every time
// this event is fired. To prevent that problem we will call WriteEventCore(), which works with
// a stack based EventData array populated with the event fields.
unsafe
{
EventData* eventPayload = stackalloc EventData[6];
eventPayload[0].Size = sizeof(Int32);
eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
eventPayload[1].Size = sizeof(Int32);
eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
eventPayload[2].Size = sizeof(Int32);
eventPayload[2].DataPointer = ((IntPtr)(&ForkJoinContextID));
eventPayload[3].Size = sizeof(Int32);
eventPayload[3].DataPointer = ((IntPtr)(&OperationType));
eventPayload[4].Size = sizeof(Int64);
eventPayload[4].DataPointer = ((IntPtr)(&InclusiveFrom));
eventPayload[5].Size = sizeof(Int64);
eventPayload[5].DataPointer = ((IntPtr)(&ExclusiveTo));
WriteEventCore(PARALLELLOOPBEGIN_ID, 6, eventPayload);
}
}
}
#endregion ParallelLoopBegin
#region ParallelLoopEnd
/// <summary>
/// Denotes the end of a Parallel.For or Parallel.ForEach loop.
/// </summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="ForkJoinContextID">The loop ID.</param>
/// <param name="TotalIterations">the total number of iterations processed.</param>
[SecuritySafeCritical]
[Event(PARALLELLOOPEND_ID, Level = EventLevel.Informational, Task = ParallelEtwProvider.Tasks.Loop, Opcode = EventOpcode.Stop)]
public void ParallelLoopEnd(Int32 OriginatingTaskSchedulerID, Int32 OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
Int32 ForkJoinContextID, Int64 TotalIterations)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
// There is no explicit WriteEvent() overload matching this event's fields.
// Therefore calling WriteEvent() would hit the "params" overload, which leads to an object allocation every time this event is fired.
// To prevent that problem we will call WriteEventCore(), which works with a stack based EventData array populated with the event fields
unsafe
{
EventData* eventPayload = stackalloc EventData[4];
eventPayload[0].Size = sizeof(Int32);
eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
eventPayload[1].Size = sizeof(Int32);
eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
eventPayload[2].Size = sizeof(Int32);
eventPayload[2].DataPointer = ((IntPtr)(&ForkJoinContextID));
eventPayload[3].Size = sizeof(Int64);
eventPayload[3].DataPointer = ((IntPtr)(&TotalIterations));
WriteEventCore(PARALLELLOOPEND_ID, 4, eventPayload);
}
}
}
#endregion ParallelLoopEnd
#region ParallelInvokeBegin
/// <summary>Denotes the entry point for a Parallel.Invoke call.</summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="ForkJoinContextID">The invoke ID.</param>
/// <param name="OperationType">The kind of fork/join operation.</param>
/// <param name="ActionCount">The number of actions being invoked.</param>
[SecuritySafeCritical]
[Event(PARALLELINVOKEBEGIN_ID, Level = EventLevel.Informational, Task = ParallelEtwProvider.Tasks.Invoke, Opcode = EventOpcode.Start)]
public void ParallelInvokeBegin(Int32 OriginatingTaskSchedulerID, Int32 OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
Int32 ForkJoinContextID, ForkJoinOperationType OperationType, // PFX_FORKJOIN_COMMON_EVENT_HEADER
Int32 ActionCount)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
// There is no explicit WriteEvent() overload matching this event's fields.
// Therefore calling WriteEvent() would hit the "params" overload, which leads to an object allocation every time this event is fired.
// To prevent that problem we will call WriteEventCore(), which works with a stack based EventData array populated with the event fields
unsafe
{
EventData* eventPayload = stackalloc EventData[5];
eventPayload[0].Size = sizeof(Int32);
eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
eventPayload[1].Size = sizeof(Int32);
eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
eventPayload[2].Size = sizeof(Int32);
eventPayload[2].DataPointer = ((IntPtr)(&ForkJoinContextID));
eventPayload[3].Size = sizeof(Int32);
eventPayload[3].DataPointer = ((IntPtr)(&OperationType));
eventPayload[4].Size = sizeof(Int32);
eventPayload[4].DataPointer = ((IntPtr)(&ActionCount));
WriteEventCore(PARALLELINVOKEBEGIN_ID, 5, eventPayload);
}
}
}
#endregion ParallelInvokeBegin
#region ParallelInvokeEnd
/// <summary>
/// Denotes the exit point for a Parallel.Invoke call.
/// </summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="ForkJoinContextID">The invoke ID.</param>
[Event(PARALLELINVOKEEND_ID, Level = EventLevel.Informational, Task = ParallelEtwProvider.Tasks.Invoke, Opcode = EventOpcode.Stop)]
public void ParallelInvokeEnd(Int32 OriginatingTaskSchedulerID, Int32 OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
Int32 ForkJoinContextID)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
WriteEvent(PARALLELINVOKEEND_ID, OriginatingTaskSchedulerID, OriginatingTaskID, ForkJoinContextID);
}
#endregion ParallelInvokeEnd
#region ParallelFork
/// <summary>
/// Denotes the start of an individual task that's part of a fork/join context.
/// Before this event is fired, the start of the new fork/join context will be marked
/// with another event that declares a unique context ID.
/// </summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="ForkJoinContextID">The invoke ID.</param>
[Event(PARALLELFORK_ID, Level = EventLevel.Verbose, Task = ParallelEtwProvider.Tasks.ForkJoin, Opcode = EventOpcode.Start)]
public void ParallelFork(Int32 OriginatingTaskSchedulerID, Int32 OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
Int32 ForkJoinContextID)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
WriteEvent(PARALLELFORK_ID, OriginatingTaskSchedulerID, OriginatingTaskID, ForkJoinContextID);
}
#endregion ParallelFork
#region ParallelJoin
/// <summary>
/// Denotes the end of an individual task that's part of a fork/join context.
/// This should match a previous ParallelFork event with a matching "OriginatingTaskID"
/// </summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="ForkJoinContextID">The invoke ID.</param>
[Event(PARALLELJOIN_ID, Level = EventLevel.Verbose, Task = ParallelEtwProvider.Tasks.ForkJoin, Opcode = EventOpcode.Stop)]
public void ParallelJoin(Int32 OriginatingTaskSchedulerID, Int32 OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
Int32 ForkJoinContextID)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
WriteEvent(PARALLELJOIN_ID, OriginatingTaskSchedulerID, OriginatingTaskID, ForkJoinContextID);
}
#endregion ParallelJoin
} // class ParallelEtwProvider
} // namespace
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Streams;
using Orleans.TestingHost;
using Orleans.TestingHost.Utils;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
namespace UnitTests.StreamingTests
{
[TestCategory("Streaming")]
public class SampleSmsStreamingTests : OrleansTestingBase, IClassFixture<SampleSmsStreamingTests.Fixture>
{
private readonly Fixture fixture;
private readonly ILogger logger;
public class Fixture : BaseTestClusterFixture
{
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.AddSiloBuilderConfigurator<SiloConfigurator>();
builder.AddClientBuilderConfigurator<ClientConfiguretor>();
}
public class SiloConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.AddSimpleMessageStreamProvider(StreamProvider)
.AddMemoryGrainStorage("PubSubStore");
}
}
public class ClientConfiguretor : IClientBuilderConfigurator
{
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder.AddSimpleMessageStreamProvider(StreamProvider);
}
}
}
private const string StreamProvider = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME;
public SampleSmsStreamingTests(Fixture fixture)
{
this.fixture = fixture;
logger = this.fixture.Logger;
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public void SampleStreamingTests_StreamTypeMismatch_ShouldThrowOrleansException()
{
var streamId = Guid.NewGuid();
var streamNameSpace = "SmsStream";
var stream = this.fixture.Client.GetStreamProvider(StreamProvider).GetStream<int>(streamId, streamNameSpace);
Assert.Throws<Orleans.Runtime.OrleansException>(() => {
this.fixture.Client.GetStreamProvider(StreamProvider).GetStream<string>(streamId, streamNameSpace);
});
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task SampleStreamingTests_1()
{
this.logger.Info("************************ SampleStreamingTests_1 *********************************");
var runner = new SampleStreamingTests(StreamProvider, this.logger, this.fixture.HostedCluster);
await runner.StreamingTests_Consumer_Producer(Guid.NewGuid());
}
[Fact, TestCategory("Functional")]
public async Task SampleStreamingTests_2()
{
this.logger.Info("************************ SampleStreamingTests_2 *********************************");
var runner = new SampleStreamingTests(StreamProvider, this.logger, this.fixture.HostedCluster);
await runner.StreamingTests_Producer_Consumer(Guid.NewGuid());
}
[Fact, TestCategory("Functional")]
public async Task SampleStreamingTests_3()
{
this.logger.Info("************************ SampleStreamingTests_3 *********************************");
var runner = new SampleStreamingTests(StreamProvider, this.logger, this.fixture.HostedCluster);
await runner.StreamingTests_Producer_InlineConsumer(Guid.NewGuid());
}
[Fact, TestCategory("Functional")]
public async Task MultipleImplicitSubscriptionTest()
{
this.logger.Info("************************ MultipleImplicitSubscriptionTest *********************************");
var streamId = Guid.NewGuid();
const int nRedEvents = 5, nBlueEvents = 3;
var provider = this.fixture.HostedCluster.ServiceProvider.GetServiceByName<IStreamProvider>(StreamTestsConstants.SMS_STREAM_PROVIDER_NAME);
var redStream = provider.GetStream<int>(streamId, "red");
var blueStream = provider.GetStream<int>(streamId, "blue");
for (int i = 0; i < nRedEvents; i++)
await redStream.OnNextAsync(i);
for (int i = 0; i < nBlueEvents; i++)
await blueStream.OnNextAsync(i);
var grain = this.fixture.GrainFactory.GetGrain<IMultipleImplicitSubscriptionGrain>(streamId);
var counters = await grain.GetCounters();
Assert.Equal(nRedEvents, counters.Item1);
Assert.Equal(nBlueEvents, counters.Item2);
}
[Fact, TestCategory("Functional")]
public async Task FilteredImplicitSubscriptionGrainTest()
{
this.logger.Info($"************************ {nameof(FilteredImplicitSubscriptionGrainTest)} *********************************");
var streamNamespaces = new[] { "red1", "red2", "blue3", "blue4" };
var events = new[] { 3, 5, 2, 4 };
var testData = streamNamespaces.Zip(events, (s, e) => new
{
Namespace = s,
Events = e,
StreamId = Guid.NewGuid()
}).ToList();
var provider = this.fixture.HostedCluster.ServiceProvider.GetServiceByName<IStreamProvider>(StreamTestsConstants.SMS_STREAM_PROVIDER_NAME);
foreach (var item in testData)
{
var stream = provider.GetStream<int>(item.StreamId, item.Namespace);
for (int i = 0; i < item.Events; i++)
await stream.OnNextAsync(i);
}
foreach (var item in testData)
{
var grain = this.fixture.GrainFactory.GetGrain<IFilteredImplicitSubscriptionGrain>(item.StreamId);
var actual = await grain.GetCounter(item.Namespace);
var expected = item.Namespace.StartsWith("red") ? item.Events : 0;
Assert.Equal(expected, actual);
}
}
[Fact, TestCategory("Functional")]
public async Task FilteredImplicitSubscriptionWithExtensionGrainTest()
{
logger.Info($"************************ {nameof(FilteredImplicitSubscriptionWithExtensionGrainTest)} *********************************");
var redEvents = new[] { 3, 5, 2, 4 };
var blueEvents = new[] { 7, 3, 6 };
var streamId = Guid.NewGuid();
var provider = this.fixture.HostedCluster.ServiceProvider.GetServiceByName<IStreamProvider>(StreamTestsConstants.SMS_STREAM_PROVIDER_NAME);
for (int i = 0; i < redEvents.Length; i++)
{
var stream = provider.GetStream<int>(streamId, "red" + i);
for (int j = 0; j < redEvents[i]; j++)
await stream.OnNextAsync(j);
}
for (int i = 0; i < blueEvents.Length; i++)
{
var stream = provider.GetStream<int>(streamId, "blue" + i);
for (int j = 0; j < blueEvents[i]; j++)
await stream.OnNextAsync(j);
}
for (int i = 0; i < redEvents.Length; i++)
{
var grain = this.fixture.GrainFactory.GetGrain<IFilteredImplicitSubscriptionWithExtensionGrain>(
streamId, "red" + i, null);
var actual = await grain.GetCounter();
Assert.Equal(redEvents[i], actual);
}
for (int i = 0; i < blueEvents.Length; i++)
{
var grain = this.fixture.GrainFactory.GetGrain<IFilteredImplicitSubscriptionWithExtensionGrain>(
streamId, "blue" + i, null);
var actual = await grain.GetCounter();
Assert.Equal(0, actual);
}
}
}
public class SampleStreamingTests
{
private const string StreamNamespace = "SampleStreamNamespace";
private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(30);
private readonly string streamProvider;
private readonly ILogger logger;
private readonly TestCluster cluster;
public SampleStreamingTests(string streamProvider, ILogger logger, TestCluster cluster)
{
this.streamProvider = streamProvider;
this.logger = logger;
this.cluster = cluster;
}
public async Task StreamingTests_Consumer_Producer(Guid streamId)
{
// consumer joins first, producer later
var consumer = this.cluster.GrainFactory.GetGrain<ISampleStreaming_ConsumerGrain>(Guid.NewGuid());
await consumer.BecomeConsumer(streamId, StreamNamespace, streamProvider);
var producer = this.cluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid());
await producer.BecomeProducer(streamId, StreamNamespace, streamProvider);
await producer.StartPeriodicProducing();
await Task.Delay(TimeSpan.FromMilliseconds(1000));
await producer.StopPeriodicProducing();
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, lastTry), _timeout);
await consumer.StopConsuming();
}
public async Task StreamingTests_Producer_Consumer(Guid streamId)
{
// producer joins first, consumer later
var producer = this.cluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid());
await producer.BecomeProducer(streamId, StreamNamespace, streamProvider);
var consumer = this.cluster.GrainFactory.GetGrain<ISampleStreaming_ConsumerGrain>(Guid.NewGuid());
await consumer.BecomeConsumer(streamId, StreamNamespace, streamProvider);
await producer.StartPeriodicProducing();
await Task.Delay(TimeSpan.FromMilliseconds(1000));
await producer.StopPeriodicProducing();
//int numProduced = await producer.NumberProduced;
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, lastTry), _timeout);
await consumer.StopConsuming();
}
public async Task StreamingTests_Producer_InlineConsumer(Guid streamId)
{
// producer joins first, consumer later
var producer = this.cluster.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid());
await producer.BecomeProducer(streamId, StreamNamespace, streamProvider);
var consumer = this.cluster.GrainFactory.GetGrain<ISampleStreaming_InlineConsumerGrain>(Guid.NewGuid());
await consumer.BecomeConsumer(streamId, StreamNamespace, streamProvider);
await producer.StartPeriodicProducing();
await Task.Delay(TimeSpan.FromMilliseconds(1000));
await producer.StopPeriodicProducing();
//int numProduced = await producer.NumberProduced;
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, lastTry), _timeout);
await consumer.StopConsuming();
}
private async Task<bool> CheckCounters(ISampleStreaming_ProducerGrain producer, ISampleStreaming_ConsumerGrain consumer, bool assertIsTrue)
{
var numProduced = await producer.GetNumberProduced();
var numConsumed = await consumer.GetNumberConsumed();
this.logger.Info("CheckCounters: numProduced = {0}, numConsumed = {1}", numProduced, numConsumed);
if (assertIsTrue)
{
Assert.Equal(numProduced, numConsumed);
return true;
}
else
{
return numProduced == numConsumed;
}
}
}
}
| |
using System;
using System.Drawing;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Audio;
using OpenTK.Audio.OpenAL;
using OpenTK.Input;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using OpenTK.Platform;
namespace Terrain {
public class Terrain : ILoadable, IRenderable {
public int subdivisions = 5;
public float gridSpacing = 5f;
public int MapSize { get; set; }
public float[,] RandomMap { get; set; }
public float[,] Heightmap { get; set; }
public Vector3 [,] NormalMap { get; set; }
public int PageSideLength { get; set; }
public float minHeight = float.MaxValue;
public float maxHeight = float.MinValue;
public float deltaHeight = 0;
public int DARK_GRASS = 0;
public int MUD = 1;
public int LIGHT_GRASS = 2;
public int ROCK = 3;
public int SNOW = 4;
public int NOISE = 5;
public int SAND = 6;
public int WATER = 7;
private List<TerrainPage> pages = new List<TerrainPage>();
public int[,] Texturemap { get; set; }
public static Terrain Instance {
get { return instance == null ? (instance = new Terrain()) : instance; }
}
private static Terrain instance = null;
private Terrain() {
PageSideLength = 0;
}
public void Load() {
Util.Profile("BuildRandomMap", () => BuildRandomMap());
Util.Profile("LoadTextures", () => LoadTextures());
Util.Profile("BuildHeightMap", () => BuildHeightmap());
Util.Profile("BuildNormalMap", () => BuildNormalmap());
Util.Profile("BuildTextureMap", () => BuildTexturemap());
Util.Profile("BuildTerrainPages", () => BuildTerrainPages());
}
private void LoadTextures() {
DARK_GRASS = Util.LoadTexture("Terrain.Assets.DARK_GRASS_2.jpg");
MUD = Util.LoadTexture("Terrain.Assets.MUD_2.jpg");
LIGHT_GRASS = Util.LoadTexture("Terrain.Assets.LIGHT_GRASS.jpg");
ROCK = Util.LoadTexture("Terrain.Assets.ROCK.jpg");
SNOW = Util.LoadTexture("Terrain.Assets.SNOW.jpg");
NOISE = Util.LoadTexture("Terrain.Assets.NOISE.jpg");
SAND = Util.LoadTexture("Terrain.Assets.SAND.jpg");
WATER = Util.LoadTexture("Terrain.Assets.WATER.jpg");
}
private void BuildRandomMap() {
Bitmap bmp = new Bitmap(Assembly.GetEntryAssembly().GetManifestResourceStream("Terrain.Assets.NOISE.jpg"));
RandomMap = new float[bmp.Width, bmp.Height];
for (int x = 0; x < bmp.Width; x++) {
for (int y = 0; y < bmp.Height; y++) {
Color color = bmp.GetPixel(x, y);
float merged = (color.R + color.G + color.B) / 765f;
RandomMap[x, y] = merged;
}
}
}
private void BuildHeightmap() {
//Bitmap bmp = new Bitmap(Assembly.GetEntryAssembly().GetManifestResourceStream("Terrain.Assets.HEIGHTMAP_2_1024.jpg"));
////Bitmap bmp = new Bitmap(Assembly.GetEntryAssembly().GetManifestResourceStream("Terrain.Assets.HEIGHTMAP_3_1024.jpg"));
Noise noise = new Noise();
//Heightmap = new float[bmp.Width, bmp.Height];
int width = 1024;
int height = width;
float halfWidth = width / 2f;
Heightmap = new float[width, height];
Vector2 center = new Vector2(Heightmap.GetLength(0) / 2f, Heightmap.GetLength(1) / 2f);
for (int x = 0; x < Heightmap.GetLength(0); x++) {
for (int y = 0; y < Heightmap.GetLength(1); y++) {
float distance = (float)Math.Abs(Math.Sqrt(Math.Pow(center.X - x, 2) + Math.Pow(center.Y - y, 2)));
float attenuation = 0.3f;
float influence = 1f - (distance / (width / 2f)) * attenuation;
//Color color = bmp.GetPixel(x % width, y % height);
//Heightmap[x, y] = (color.R + color.B + color.G) * 1.2f * influence;
int passes = 10;
float detail = 40f;
float scale = 20f;
Heightmap[x, y] = noise.NoiseAt((x / (float)width * detail), (y / (float)height * detail), passes) * influence * scale + 8f * scale;
//if (Heightmap[x, y] < minHeight) minHeight = Heightmap[x, y];
//if (Heightmap[x, y] > maxHeight) maxHeight = Heightmap[x, y];
float affect = -1f * (float)Math.Log(distance / halfWidth + .1f);
Heightmap[x, y] *= affect;
if (Heightmap[x, y] < minHeight) minHeight = Heightmap[x, y];
if (Heightmap[x, y] > maxHeight) maxHeight = Heightmap[x, y];
}
}
MapSize = Heightmap.GetLength(0);
deltaHeight = maxHeight - minHeight;
}
private void BuildTexturemap() {
Texturemap = new int[Heightmap.GetLength(0), Heightmap.GetLength(1)];
float middleHeight = minHeight + (deltaHeight / 2f);
//float snowHeight = minHeight + (deltaHeight * 8.5f / 10f);
float sandHeight = minHeight + (deltaHeight * 2.1f / 10f);
float waterHeight = minHeight + (deltaHeight * 2f / 10f);
for (int x = 0; x < Texturemap.GetLength(0); x++) {
for (int z = 0; z < Texturemap.GetLength(1); z++) {
Vector3 normal = NormalAt(x, z);
double angle = Math.Abs(Math.Acos(normal.Y / normal.Length));
float avgHeight = HeightAt(x, z);
float randomInfluence = 0.20f;
bool low = avgHeight * (1f - randomInfluence) + avgHeight * randomInfluence * RandomAt(x, z) * 2f < middleHeight;
randomInfluence = 0.25f;
bool steep = angle * (1f - randomInfluence) + angle * randomInfluence * RandomAt(x, z) * 2f > MathHelper.PiOver4;
randomInfluence = 0.10f;
bool sand = avgHeight * (1f - randomInfluence) + avgHeight * randomInfluence * RandomAt(x, z) * 2f < sandHeight;
randomInfluence = 0.001f;
bool water = avgHeight * (1f - randomInfluence) + avgHeight * randomInfluence * RandomAt(x, z) * 2f < waterHeight;
randomInfluence = 0.025f;
bool snow = false;//avgHeight * (1f - randomInfluence) + avgHeight * randomInfluence * RandomAt(x, z) * 2f > snowHeight;
if (snow) {
Texturemap[x, z] = SNOW;
} else if (water) {
Texturemap[x, z] = WATER;
} else if (sand) {
Texturemap[x, z] = SAND;
} else {
if (low) {
Texturemap[x, z] = steep ? MUD : DARK_GRASS;
} else {
Texturemap[x, z] = steep ? ROCK : LIGHT_GRASS;
}
}
}
}
}
private void BuildNormalmap() {
NormalMap = new Vector3[Heightmap.GetLength(0), Heightmap.GetLength(1)];
for (int x = 0; x < NormalMap.GetLength(0); x++) {
for (int z = 0; z < NormalMap.GetLength(1); z++) {
var v1 = HeightVectorAt(x, z);
var v2 = HeightVectorAt(x - 1, z);
var v3 = HeightVectorAt(x, z + 1);
var v4 = HeightVectorAt(x + 1, z + 1);
var v5 = HeightVectorAt(x + 1, z);
var v6 = HeightVectorAt(x, z - 1);
var v7 = HeightVectorAt(x - 1, z - 1);
var normal = CalculateNormal(v1, v2, v3, v4, v5, v6, v7, v2, v3, v5, v6, v1, v1, v1, v1, v1);
NormalMap[x, z] = normal;
}
}
}
private void BuildTerrainPages() {
int pagesPerDimension = subdivisions;
createTerrainPage(0, 0, Heightmap.GetLength(0), Heightmap.GetLength(1), pagesPerDimension);
PageSideLength = (int)(Heightmap.GetLength(0) / Math.Sqrt(pages.Count));
Util.Debug("Built {0} x {1} = {2} terrain pages", Math.Sqrt(pages.Count), Math.Sqrt(pages.Count), pages.Count);
Util.Debug("Each page is {0} verts per side", PageSideLength);
}
private Vector3 CalculateNormal(params Vector3[] points) {
Vector3 normal = new Vector3(0f, 1f, 0f);
for (int n = 0; n < points.Length; n++) {
Vector3 current = points[n];
Vector3 next = points[(n + 1) % points.Length];
normal.X = normal.X + ((current.Y - next.Y) * (current.Z + next.Z));
normal.Y = normal.Y + ((current.Z - next.Z) * (current.X + next.X));
normal.Z = normal.Z + ((current.X - next.X) * (current.Y + next.Y));
}
normal.Normalize();
return normal;
}
private void createTerrainPage(int startX, int startZ, int width, int height, int pagesPerDimensions) {
if (pagesPerDimensions > 1) { //recurse to subdivide further
int newPagesPerDimension = pagesPerDimensions - 1;
int newWidth = width / 2;
int newHeight = height / 2;
createTerrainPage(startX, startZ, newWidth, newHeight, newPagesPerDimension);
createTerrainPage(startX + newWidth, startZ, newWidth, newHeight, newPagesPerDimension);
createTerrainPage(startX + newWidth, startZ + newHeight, newWidth, newHeight, newPagesPerDimension);
createTerrainPage(startX, startZ + newHeight, newWidth, newHeight, newPagesPerDimension);
} else { //actually create page
//Console.WriteLine("Creating terrain page: (x: {0}, z: {1}, width: {2}, height: {3})", startX, startZ, width, height);
pages.Add(new TerrainPage(startX, startZ, width, height));
}
}
public void Render() {
GL.Color3(Color.White);
GL.PushClientAttrib(ClientAttribMask.ClientVertexArrayBit);
GL.Enable(EnableCap.CullFace);
GL.Enable(EnableCap.DepthTest);
GL.Enable(EnableCap.Lighting);
GL.Enable(EnableCap.Light0);
//GL.Enable(EnableCap.ColorMaterial); //necessary to use color array
GL.LightModel(LightModelParameter.LightModelAmbient, new float[] { 0.2f, 0.2f, 0.2f, 1.0f });
GL.Light(LightName.Light0, LightParameter.Position, new float[] { -1000, 800, 0 });
GL.ColorMaterial(MaterialFace.Front, ColorMaterialParameter.AmbientAndDiffuse);
GL.Enable(EnableCap.Texture2D);
// GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
// GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
// GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToBorder);
// GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToBorder);
GL.Material(MaterialFace.Front, MaterialParameter.Diffuse, new float[] { 1, 1, 1, 1 });
GL.Material(MaterialFace.Front, MaterialParameter.Ambient, new float[] { 0.5f, 0.5f, 0.5f, 1 });
// GL.Material(MaterialFace.Front, MaterialParameter.Emission, new float[] { 0, 0, 0, 1 });
// GL.Material(MaterialFace.Front, MaterialParameter.Specular, new float[] { 0, 0, 0, 1 });
// GL.ColorMaterial(MaterialFace.FrontAndBack, ColorMaterialParameter.AmbientAndDiffuse);
//
// GL.MatrixMode(MatrixMode.Modelview);
// GL.PushMatrix();
// GL.LoadIdentity();
// GL.Rotate(-90, Vector3.UnitX);
// GL.Light(LightName.Light0, LightParameter.Position, new float[] { -1f, -1f, -0f, 0f });
// GL.PopMatrix();
// GL.Light(LightName.Light0, LightParameter.Diffuse, new float[] { .8f, .8f, .8f, 1 });
// GL.Light(LightName.Light0, LightParameter.Ambient, new float[] { .2f, .2f, .2f, 1 });
GL.PolygonMode(MaterialFace.Front, PolygonMode.Fill);
int pagesCount = 0;
int triangles = 0;
int totalTriangles = 0;
int bytesOfMemory = 0;
foreach (TerrainPage page in pages) {
if (page.Visible()) {
page.VBO.Render();
triangles += page.Triangles;
pagesCount++;
}
totalTriangles += page.Triangles;
bytesOfMemory += page.TextureSize * page.TextureSize * 4;
}
HUD.Instance.Triangles = String.Format("Triangles: {0} of {1}", triangles, totalTriangles);
HUD.Instance.Pages = String.Format("Pages: {0} of {1}", pagesCount, pages.Count);
HUD.Instance.TextureMemory = String.Format("Texture memory: {0} MB", bytesOfMemory / 1024 / 1024);
GL.Disable(EnableCap.CullFace);
GL.PopClientAttrib();
}
public Vector3 NormalAt(int x, int y) {
if (x >= NormalMap.GetLength(0)) x = NormalMap.GetLength(0) - 1;
if (y >= NormalMap.GetLength(1)) y = NormalMap.GetLength(1) - 1;
if (x < 0) x = 0;
if (y < 0) y = 0;
return NormalMap[x, y];
}
public Vector3 HeightVectorAt(int x, int z) {
float y = HeightAt(x, z);
return new Vector3(gridSpacing * x, y, gridSpacing * z);
}
public float RandomAt(int x, int y) {
x = x % RandomMap.GetLength(0);
y = y % RandomMap.GetLength(1);
return RandomMap[x, y];
}
public float HeightAt(int x, int y) {
if (x >= Heightmap.GetLength(0)) x = Heightmap.GetLength(0) - 1;
if (y >= Heightmap.GetLength(1)) y = Heightmap.GetLength(1) - 1;
if (x < 0) x = 0;
if (y < 0) y = 0;
return Heightmap[x, y];
}
public int TextureAt(int x, int y) {
if (x >= Texturemap.GetLength(0)) x = Texturemap.GetLength(0) - 1;
if (y >= Texturemap.GetLength(1)) y = Texturemap.GetLength(1) - 1;
if (x < 0) x = 0;
if (y < 0) y = 0;
return Texturemap[x, y];
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using OpenHome.Net.Core;
namespace OpenHome.Net.Device.Providers
{
public interface IDvProviderAvOpenhomeOrgExakt2 : IDisposable
{
/// <summary>
/// Set the value of the DeviceList property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyDeviceList(string aValue);
/// <summary>
/// Get a copy of the value of the DeviceList property
/// </summary>
/// <returns>Value of the DeviceList property.</param>
string PropertyDeviceList();
/// <summary>
/// Set the value of the ConnectionStatus property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyConnectionStatus(string aValue);
/// <summary>
/// Get a copy of the value of the ConnectionStatus property
/// </summary>
/// <returns>Value of the ConnectionStatus property.</param>
string PropertyConnectionStatus();
/// <summary>
/// Set the value of the Version property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyVersion(string aValue);
/// <summary>
/// Get a copy of the value of the Version property
/// </summary>
/// <returns>Value of the Version property.</param>
string PropertyVersion();
}
/// <summary>
/// Provider for the av.openhome.org:Exakt:2 UPnP service
/// </summary>
public class DvProviderAvOpenhomeOrgExakt2 : DvProvider, IDisposable, IDvProviderAvOpenhomeOrgExakt2
{
private GCHandle iGch;
private ActionDelegate iDelegateDeviceList;
private ActionDelegate iDelegateDeviceSettings;
private ActionDelegate iDelegateConnectionStatus;
private ActionDelegate iDelegateSet;
private ActionDelegate iDelegateReprogram;
private ActionDelegate iDelegateReprogramFallback;
private ActionDelegate iDelegateVersion;
private PropertyString iPropertyDeviceList;
private PropertyString iPropertyConnectionStatus;
private PropertyString iPropertyVersion;
/// <summary>
/// Constructor
/// </summary>
/// <param name="aDevice">Device which owns this provider</param>
protected DvProviderAvOpenhomeOrgExakt2(DvDevice aDevice)
: base(aDevice, "av.openhome.org", "Exakt", 2)
{
iGch = GCHandle.Alloc(this);
}
/// <summary>
/// Enable the DeviceList property.
/// </summary>
public void EnablePropertyDeviceList()
{
List<String> allowedValues = new List<String>();
iPropertyDeviceList = new PropertyString(new ParameterString("DeviceList", allowedValues));
AddProperty(iPropertyDeviceList);
}
/// <summary>
/// Enable the ConnectionStatus property.
/// </summary>
public void EnablePropertyConnectionStatus()
{
List<String> allowedValues = new List<String>();
iPropertyConnectionStatus = new PropertyString(new ParameterString("ConnectionStatus", allowedValues));
AddProperty(iPropertyConnectionStatus);
}
/// <summary>
/// Enable the Version property.
/// </summary>
public void EnablePropertyVersion()
{
List<String> allowedValues = new List<String>();
iPropertyVersion = new PropertyString(new ParameterString("Version", allowedValues));
AddProperty(iPropertyVersion);
}
/// <summary>
/// Set the value of the DeviceList property
/// </summary>
/// <remarks>Can only be called if EnablePropertyDeviceList has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyDeviceList(string aValue)
{
if (iPropertyDeviceList == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyDeviceList, aValue);
}
/// <summary>
/// Get a copy of the value of the DeviceList property
/// </summary>
/// <remarks>Can only be called if EnablePropertyDeviceList has previously been called.</remarks>
/// <returns>Value of the DeviceList property.</returns>
public string PropertyDeviceList()
{
if (iPropertyDeviceList == null)
throw new PropertyDisabledError();
return iPropertyDeviceList.Value();
}
/// <summary>
/// Set the value of the ConnectionStatus property
/// </summary>
/// <remarks>Can only be called if EnablePropertyConnectionStatus has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyConnectionStatus(string aValue)
{
if (iPropertyConnectionStatus == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyConnectionStatus, aValue);
}
/// <summary>
/// Get a copy of the value of the ConnectionStatus property
/// </summary>
/// <remarks>Can only be called if EnablePropertyConnectionStatus has previously been called.</remarks>
/// <returns>Value of the ConnectionStatus property.</returns>
public string PropertyConnectionStatus()
{
if (iPropertyConnectionStatus == null)
throw new PropertyDisabledError();
return iPropertyConnectionStatus.Value();
}
/// <summary>
/// Set the value of the Version property
/// </summary>
/// <remarks>Can only be called if EnablePropertyVersion has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyVersion(string aValue)
{
if (iPropertyVersion == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyVersion, aValue);
}
/// <summary>
/// Get a copy of the value of the Version property
/// </summary>
/// <remarks>Can only be called if EnablePropertyVersion has previously been called.</remarks>
/// <returns>Value of the Version property.</returns>
public string PropertyVersion()
{
if (iPropertyVersion == null)
throw new PropertyDisabledError();
return iPropertyVersion.Value();
}
/// <summary>
/// Signal that the action DeviceList is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// DeviceList must be overridden if this is called.</remarks>
protected void EnableActionDeviceList()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("DeviceList");
action.AddOutputParameter(new ParameterRelated("List", iPropertyDeviceList));
iDelegateDeviceList = new ActionDelegate(DoDeviceList);
EnableAction(action, iDelegateDeviceList, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action DeviceSettings is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// DeviceSettings must be overridden if this is called.</remarks>
protected void EnableActionDeviceSettings()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("DeviceSettings");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("DeviceId", allowedValues));
action.AddOutputParameter(new ParameterString("Settings", allowedValues));
iDelegateDeviceSettings = new ActionDelegate(DoDeviceSettings);
EnableAction(action, iDelegateDeviceSettings, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action ConnectionStatus is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// ConnectionStatus must be overridden if this is called.</remarks>
protected void EnableActionConnectionStatus()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("ConnectionStatus");
action.AddOutputParameter(new ParameterRelated("ConnectionStatus", iPropertyConnectionStatus));
iDelegateConnectionStatus = new ActionDelegate(DoConnectionStatus);
EnableAction(action, iDelegateConnectionStatus, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Set is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Set must be overridden if this is called.</remarks>
protected void EnableActionSet()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Set");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("DeviceId", allowedValues));
action.AddInputParameter(new ParameterUint("BankId"));
action.AddInputParameter(new ParameterString("FileUri", allowedValues));
action.AddInputParameter(new ParameterBool("Mute"));
action.AddInputParameter(new ParameterBool("Persist"));
iDelegateSet = new ActionDelegate(DoSet);
EnableAction(action, iDelegateSet, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Reprogram is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Reprogram must be overridden if this is called.</remarks>
protected void EnableActionReprogram()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Reprogram");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("DeviceId", allowedValues));
action.AddInputParameter(new ParameterString("FileUri", allowedValues));
iDelegateReprogram = new ActionDelegate(DoReprogram);
EnableAction(action, iDelegateReprogram, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action ReprogramFallback is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// ReprogramFallback must be overridden if this is called.</remarks>
protected void EnableActionReprogramFallback()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("ReprogramFallback");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("DeviceId", allowedValues));
action.AddInputParameter(new ParameterString("FileUri", allowedValues));
iDelegateReprogramFallback = new ActionDelegate(DoReprogramFallback);
EnableAction(action, iDelegateReprogramFallback, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Version is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Version must be overridden if this is called.</remarks>
protected void EnableActionVersion()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Version");
action.AddOutputParameter(new ParameterRelated("Version", iPropertyVersion));
iDelegateVersion = new ActionDelegate(DoVersion);
EnableAction(action, iDelegateVersion, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// DeviceList action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// DeviceList action for the owning device.
///
/// Must be implemented iff EnableActionDeviceList was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aList"></param>
protected virtual void DeviceList(IDvInvocation aInvocation, out string aList)
{
throw (new ActionDisabledError());
}
/// <summary>
/// DeviceSettings action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// DeviceSettings action for the owning device.
///
/// Must be implemented iff EnableActionDeviceSettings was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aDeviceId"></param>
/// <param name="aSettings"></param>
protected virtual void DeviceSettings(IDvInvocation aInvocation, string aDeviceId, out string aSettings)
{
throw (new ActionDisabledError());
}
/// <summary>
/// ConnectionStatus action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// ConnectionStatus action for the owning device.
///
/// Must be implemented iff EnableActionConnectionStatus was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aConnectionStatus"></param>
protected virtual void ConnectionStatus(IDvInvocation aInvocation, out string aConnectionStatus)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Set action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Set action for the owning device.
///
/// Must be implemented iff EnableActionSet was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aDeviceId"></param>
/// <param name="aBankId"></param>
/// <param name="aFileUri"></param>
/// <param name="aMute"></param>
/// <param name="aPersist"></param>
protected virtual void Set(IDvInvocation aInvocation, string aDeviceId, uint aBankId, string aFileUri, bool aMute, bool aPersist)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Reprogram action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Reprogram action for the owning device.
///
/// Must be implemented iff EnableActionReprogram was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aDeviceId"></param>
/// <param name="aFileUri"></param>
protected virtual void Reprogram(IDvInvocation aInvocation, string aDeviceId, string aFileUri)
{
throw (new ActionDisabledError());
}
/// <summary>
/// ReprogramFallback action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// ReprogramFallback action for the owning device.
///
/// Must be implemented iff EnableActionReprogramFallback was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aDeviceId"></param>
/// <param name="aFileUri"></param>
protected virtual void ReprogramFallback(IDvInvocation aInvocation, string aDeviceId, string aFileUri)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Version action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Version action for the owning device.
///
/// Must be implemented iff EnableActionVersion was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aVersion"></param>
protected virtual void Version(IDvInvocation aInvocation, out string aVersion)
{
throw (new ActionDisabledError());
}
private static int DoDeviceList(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgExakt2 self = (DvProviderAvOpenhomeOrgExakt2)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string list;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.DeviceList(invocation, out list);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "DeviceList");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "DeviceList"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "DeviceList", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("List", list);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "DeviceList", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoDeviceSettings(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgExakt2 self = (DvProviderAvOpenhomeOrgExakt2)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string deviceId;
string settings;
try
{
invocation.ReadStart();
deviceId = invocation.ReadString("DeviceId");
invocation.ReadEnd();
self.DeviceSettings(invocation, deviceId, out settings);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "DeviceSettings");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "DeviceSettings"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "DeviceSettings", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("Settings", settings);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "DeviceSettings", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoConnectionStatus(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgExakt2 self = (DvProviderAvOpenhomeOrgExakt2)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string connectionStatus;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.ConnectionStatus(invocation, out connectionStatus);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "ConnectionStatus");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "ConnectionStatus"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "ConnectionStatus", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("ConnectionStatus", connectionStatus);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "ConnectionStatus", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoSet(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgExakt2 self = (DvProviderAvOpenhomeOrgExakt2)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string deviceId;
uint bankId;
string fileUri;
bool mute;
bool persist;
try
{
invocation.ReadStart();
deviceId = invocation.ReadString("DeviceId");
bankId = invocation.ReadUint("BankId");
fileUri = invocation.ReadString("FileUri");
mute = invocation.ReadBool("Mute");
persist = invocation.ReadBool("Persist");
invocation.ReadEnd();
self.Set(invocation, deviceId, bankId, fileUri, mute, persist);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Set");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "Set"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Set", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Set", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoReprogram(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgExakt2 self = (DvProviderAvOpenhomeOrgExakt2)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string deviceId;
string fileUri;
try
{
invocation.ReadStart();
deviceId = invocation.ReadString("DeviceId");
fileUri = invocation.ReadString("FileUri");
invocation.ReadEnd();
self.Reprogram(invocation, deviceId, fileUri);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Reprogram");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "Reprogram"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Reprogram", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Reprogram", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoReprogramFallback(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgExakt2 self = (DvProviderAvOpenhomeOrgExakt2)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string deviceId;
string fileUri;
try
{
invocation.ReadStart();
deviceId = invocation.ReadString("DeviceId");
fileUri = invocation.ReadString("FileUri");
invocation.ReadEnd();
self.ReprogramFallback(invocation, deviceId, fileUri);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "ReprogramFallback");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "ReprogramFallback"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "ReprogramFallback", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "ReprogramFallback", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoVersion(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgExakt2 self = (DvProviderAvOpenhomeOrgExakt2)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string version;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.Version(invocation, out version);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Version");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "Version"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Version", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("Version", version);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Version", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
/// <summary>
/// Must be called for each class instance. Must be called before Core.Library.Close().
/// </summary>
public virtual void Dispose()
{
if (DisposeProvider())
iGch.Free();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
public class Int32Tests
{
[Fact]
public static void Ctor_Empty()
{
var i = new int();
Assert.Equal(0, i);
}
[Fact]
public static void Ctor_Value()
{
int i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0x7FFFFFFF, int.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(unchecked((int)0x80000000), int.MinValue);
}
[Theory]
[InlineData(234, 234, 0)]
[InlineData(234, int.MinValue, 1)]
[InlineData(-234, int.MinValue, 1)]
[InlineData(int.MinValue, int.MinValue, 0)]
[InlineData(234, -123, 1)]
[InlineData(234, 0, 1)]
[InlineData(234, 123, 1)]
[InlineData(234, 456, -1)]
[InlineData(234, int.MaxValue, -1)]
[InlineData(-234, int.MaxValue, -1)]
[InlineData(int.MaxValue, int.MaxValue, 0)]
[InlineData(-234, -234, 0)]
[InlineData(-234, 234, -1)]
[InlineData(-234, -432, 1)]
[InlineData(234, null, 1)]
public void CompareTo_Other_ReturnsExpected(int i, object value, int expected)
{
if (value is int intValue)
{
Assert.Equal(expected, Math.Sign(i.CompareTo(intValue)));
Assert.Equal(-expected, Math.Sign(intValue.CompareTo(i)));
}
Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
[Theory]
[InlineData("a")]
[InlineData((long)234)]
public void CompareTo_ObjectNotInt_ThrowsArgumentException(object value)
{
AssertExtensions.Throws<ArgumentException>(null, () => 123.CompareTo(value));
}
[Theory]
[InlineData(789, 789, true)]
[InlineData(789, -789, false)]
[InlineData(789, 0, false)]
[InlineData(0, 0, true)]
[InlineData(-789, -789, true)]
[InlineData(-789, 789, false)]
[InlineData(789, null, false)]
[InlineData(789, "789", false)]
[InlineData(789, (long)789, false)]
public static void Equals(int i1, object obj, bool expected)
{
if (obj is int)
{
int i2 = (int)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
}
Assert.Equal(expected, i1.Equals(obj));
}
[Fact]
public void GetTypeCode_Invoke_ReturnsInt32()
{
Assert.Equal(TypeCode.Int32, 1.GetTypeCode());
}
public static IEnumerable<object[]> ToString_TestData()
{
foreach (NumberFormatInfo defaultFormat in new[] { null, NumberFormatInfo.CurrentInfo })
{
foreach (string defaultSpecifier in new[] { "G", "G\0", "\0N222", "\0", "" })
{
yield return new object[] { int.MinValue, defaultSpecifier, defaultFormat, "-2147483648" };
yield return new object[] { -4567, defaultSpecifier, defaultFormat, "-4567" };
yield return new object[] { 0, defaultSpecifier, defaultFormat, "0" };
yield return new object[] { 4567, defaultSpecifier, defaultFormat, "4567" };
yield return new object[] { int.MaxValue, defaultSpecifier, defaultFormat, "2147483647" };
}
yield return new object[] { 4567, "D", defaultFormat, "4567" };
yield return new object[] { 4567, "D99", defaultFormat, "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004567" };
yield return new object[] { 4567, "D99\09", defaultFormat, "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004567" };
yield return new object[] { -4567, "D99\09", defaultFormat, "-000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004567" };
yield return new object[] { 0x2468, "x", defaultFormat, "2468" };
yield return new object[] { -0x2468, "x", defaultFormat, "ffffdb98" };
yield return new object[] { 2468, "N", defaultFormat, string.Format("{0:N}", 2468.00) };
}
var customFormat = new NumberFormatInfo()
{
NegativeSign = "#",
NumberDecimalSeparator = "~",
NumberGroupSeparator = "*",
PositiveSign = "&",
NumberDecimalDigits = 2,
PercentSymbol = "@",
PercentGroupSeparator = ",",
PercentDecimalSeparator = ".",
PercentDecimalDigits = 5
};
yield return new object[] { -2468, "N", customFormat, "#2*468~00" };
yield return new object[] { 2468, "N", customFormat, "2*468~00" };
yield return new object[] { 123, "E", customFormat, "1~230000E&002" };
yield return new object[] { 123, "F", customFormat, "123~00" };
yield return new object[] { 123, "P", customFormat, "12,300.00000 @" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(int i, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
int i = 123;
Assert.Throws<FormatException>(() => i.ToString("r")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("r", null)); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("R")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("R", null)); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberFormatInfo samePositiveNegativeFormat = new NumberFormatInfo()
{
PositiveSign = "|",
NegativeSign = "|"
};
NumberFormatInfo emptyPositiveFormat = new NumberFormatInfo() { PositiveSign = "" };
NumberFormatInfo emptyNegativeFormat = new NumberFormatInfo() { NegativeSign = "" };
// None
yield return new object[] { "0", NumberStyles.None, null, 0 };
yield return new object[] { "0000000000000000000000000000000000000000000000000000000000", NumberStyles.None, null, 0 };
yield return new object[] { "0000000000000000000000000000000000000000000000000000000001", NumberStyles.None, null, 1 };
yield return new object[] { "2147483647", NumberStyles.None, null, 2147483647 };
yield return new object[] { "02147483647", NumberStyles.None, null, 2147483647 };
yield return new object[] { "00000000000000000000000000000000000000000000000002147483647", NumberStyles.None, null, 2147483647 };
yield return new object[] { "123\0\0", NumberStyles.None, null, 123 };
// All lengths decimal
foreach (bool neg in new[] { false, true })
{
string s = neg ? "-" : "";
int result = 0;
for (int i = 1; i <= 10; i++)
{
result = result * 10 + (i % 10);
s += (i % 10).ToString();
yield return new object[] { s, NumberStyles.Integer, null, neg ? result * -1 : result };
}
}
// All lengths hexadecimal
{
string s = "";
int result = 0;
for (int i = 1; i <= 8; i++)
{
result = (result * 16) + (i % 16);
s += (i % 16).ToString("X");
yield return new object[] { s, NumberStyles.HexNumber, null, result };
}
}
// HexNumber
yield return new object[] { "123", NumberStyles.HexNumber, null, 0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, null, 0xabc };
yield return new object[] { "ABC", NumberStyles.HexNumber, null, 0xabc };
yield return new object[] { "12", NumberStyles.HexNumber, null, 0x12 };
yield return new object[] { "80000000", NumberStyles.HexNumber, null, int.MinValue };
yield return new object[] { "FFFFFFFF", NumberStyles.HexNumber, null, -1 };
// Currency
NumberFormatInfo currencyFormat = new NumberFormatInfo()
{
CurrencySymbol = "$",
CurrencyGroupSeparator = "|",
NumberGroupSeparator = "/"
};
yield return new object[] { "$1|000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$ 1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$(1000)", NumberStyles.Currency, currencyFormat, -1000};
yield return new object[] { "($1000)", NumberStyles.Currency, currencyFormat, -1000 };
yield return new object[] { "$-1000", NumberStyles.Currency, currencyFormat, -1000 };
yield return new object[] { "-$1000", NumberStyles.Currency, currencyFormat, -1000 };
NumberFormatInfo emptyCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "" };
yield return new object[] { "100", NumberStyles.Currency, emptyCurrencyFormat, 100 };
// If CurrencySymbol and Negative are the same, NegativeSign is preferred
NumberFormatInfo sameCurrencyNegativeSignFormat = new NumberFormatInfo()
{
NegativeSign = "|",
CurrencySymbol = "|"
};
yield return new object[] { "|1000", NumberStyles.AllowCurrencySymbol | NumberStyles.AllowLeadingSign, sameCurrencyNegativeSignFormat, -1000 };
// Any
yield return new object[] { "123", NumberStyles.Any, null, 123 };
// AllowLeadingSign
yield return new object[] { "-2147483648", NumberStyles.AllowLeadingSign, null, -2147483648 };
yield return new object[] { "-123", NumberStyles.AllowLeadingSign, null, -123 };
yield return new object[] { "+0", NumberStyles.AllowLeadingSign, null, 0 };
yield return new object[] { "-0", NumberStyles.AllowLeadingSign, null, 0 };
yield return new object[] { "+123", NumberStyles.AllowLeadingSign, null, 123 };
// If PositiveSign and NegativeSign are the same, PositiveSign is preferred
yield return new object[] { "|123", NumberStyles.AllowLeadingSign, samePositiveNegativeFormat, 123 };
// Empty PositiveSign or NegativeSign
yield return new object[] { "100", NumberStyles.AllowLeadingSign, emptyPositiveFormat, 100 };
yield return new object[] { "100", NumberStyles.AllowLeadingSign, emptyNegativeFormat, 100 };
// AllowTrailingSign
yield return new object[] { "123", NumberStyles.AllowTrailingSign, null, 123 };
yield return new object[] { "123+", NumberStyles.AllowTrailingSign, null, 123 };
yield return new object[] { "123-", NumberStyles.AllowTrailingSign, null, -123 };
// If PositiveSign and NegativeSign are the same, PositiveSign is preferred
yield return new object[] { "123|", NumberStyles.AllowTrailingSign, samePositiveNegativeFormat, 123 };
// Empty PositiveSign or NegativeSign
yield return new object[] { "100", NumberStyles.AllowTrailingSign, emptyPositiveFormat, 100 };
yield return new object[] { "100", NumberStyles.AllowTrailingSign, emptyNegativeFormat, 100 };
// AllowLeadingWhite and AllowTrailingWhite
yield return new object[] { " 123", NumberStyles.AllowLeadingWhite, null, 123 };
yield return new object[] { " 123 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { "123 ", NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { "123 \0\0", NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { " 2147483647 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 2147483647 };
yield return new object[] { " -2147483648 ", NumberStyles.Integer, null, -2147483648 };
foreach (char c in new[] { (char)0x9, (char)0xA, (char)0xB, (char)0xC, (char)0xD })
{
string cs = c.ToString();
yield return new object[] { cs + cs + "123" + cs + cs, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 };
}
yield return new object[] { " 0 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 0 };
yield return new object[] { " 000000000 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 0 };
// AllowThousands
NumberFormatInfo thousandsFormat = new NumberFormatInfo() { NumberGroupSeparator = "|" };
yield return new object[] { "1000", NumberStyles.AllowThousands, thousandsFormat, 1000 };
yield return new object[] { "1|0|0|0", NumberStyles.AllowThousands, thousandsFormat, 1000 };
yield return new object[] { "1|||", NumberStyles.AllowThousands, thousandsFormat, 1 };
NumberFormatInfo integerNumberSeparatorFormat = new NumberFormatInfo() { NumberGroupSeparator = "1" };
yield return new object[] { "1111", NumberStyles.AllowThousands, integerNumberSeparatorFormat, 1111 };
// AllowExponent
yield return new object[] { "1E2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1E+2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1e2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1E0", NumberStyles.AllowExponent, null, 1 };
yield return new object[] { "(1E2)", NumberStyles.AllowExponent | NumberStyles.AllowParentheses, null, -100 };
yield return new object[] { "-1E2", NumberStyles.AllowExponent | NumberStyles.AllowLeadingSign, null, -100 };
NumberFormatInfo negativeFormat = new NumberFormatInfo() { PositiveSign = "|" };
yield return new object[] { "1E|2", NumberStyles.AllowExponent, negativeFormat, 100 };
// AllowParentheses
yield return new object[] { "123", NumberStyles.AllowParentheses, null, 123 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, -123 };
// AllowDecimalPoint
NumberFormatInfo decimalFormat = new NumberFormatInfo() { NumberDecimalSeparator = "|" };
yield return new object[] { "67|", NumberStyles.AllowDecimalPoint, decimalFormat, 67 };
// NumberFormatInfo has a custom property with length > 1
NumberFormatInfo integerCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "123" };
yield return new object[] { "123123", NumberStyles.AllowCurrencySymbol, integerCurrencyFormat, 123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { PositiveSign = "1" }, 23123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { NegativeSign = "1" }, -23123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { PositiveSign = "123" }, 123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { NegativeSign = "123" }, -123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { PositiveSign = "12312" }, 3 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { NegativeSign = "12312" }, -3 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse_Valid(string value, NumberStyles style, IFormatProvider provider, int expected)
{
int result;
// Default style and provider
if (style == NumberStyles.Integer && provider == null)
{
Assert.True(int.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value));
}
// Default provider
if (provider == null)
{
Assert.Equal(expected, int.Parse(value, style));
// Substitute default NumberFormatInfo
Assert.True(int.TryParse(value, style, new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value, style, new NumberFormatInfo()));
}
// Default style
if (style == NumberStyles.Integer)
{
Assert.Equal(expected, int.Parse(value, provider));
}
// Full overloads
Assert.True(int.TryParse(value, style, provider, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value, style, provider));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
// String is null, empty or entirely whitespace
yield return new object[] { null, NumberStyles.Integer, null, typeof(ArgumentNullException) };
yield return new object[] { null, NumberStyles.Any, null, typeof(ArgumentNullException) };
// String contains is null, empty or enitrely whitespace.
foreach (NumberStyles style in new[] { NumberStyles.Integer, NumberStyles.HexNumber, NumberStyles.Any })
{
yield return new object[] { null, style, null, typeof(ArgumentNullException) };
yield return new object[] { "", style, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", style, null, typeof(FormatException) };
yield return new object[] { " \0\0", style, null, typeof(FormatException) };
}
// Leading or trailing chars for which char.IsWhiteSpace is true but that's not valid for leading/trailing whitespace
foreach (string c in new[] { "\x0085", "\x00A0", "\x1680", "\x2000", "\x2001", "\x2002", "\x2003", "\x2004", "\x2005", "\x2006", "\x2007", "\x2008", "\x2009", "\x200A", "\x2028", "\x2029", "\x202F", "\x205F", "\x3000" })
{
yield return new object[] { c + "123", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "123" + c, NumberStyles.Integer, null, typeof(FormatException) };
}
// String contains garbage
foreach (NumberStyles style in new[] { NumberStyles.Integer, NumberStyles.HexNumber, NumberStyles.Any })
{
yield return new object[] { "Garbage", style, null, typeof(FormatException) };
yield return new object[] { "g", style, null, typeof(FormatException) };
yield return new object[] { "g1", style, null, typeof(FormatException) };
yield return new object[] { "1g", style, null, typeof(FormatException) };
yield return new object[] { "123g", style, null, typeof(FormatException) };
yield return new object[] { "g123", style, null, typeof(FormatException) };
yield return new object[] { "214748364g", style, null, typeof(FormatException) };
}
// String has leading zeros
yield return new object[] { "\0\0123", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "\0\0123", NumberStyles.Any, null, typeof(FormatException) };
// String has internal zeros
yield return new object[] { "1\023", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "1\023", NumberStyles.Any, null, typeof(FormatException) };
// String has trailing zeros but with whitespace after
yield return new object[] { "123\0\0 ", NumberStyles.Integer, null, typeof(FormatException) };
// Integer doesn't allow hex, exponents, paretheses, currency, thousands, decimal
yield return new object[] { "abc", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "1E23", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "(123)", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 1000.ToString("C0"), NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 1000.ToString("N0"), NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 678.90.ToString("F2"), NumberStyles.Integer, null, typeof(FormatException) };
// HexNumber
yield return new object[] { "0xabc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "&habc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "G1", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "g1", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
// None doesn't allow hex or leading or trailing whitespace
yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { "123 ", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { " 123", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) };
// AllowLeadingSign
yield return new object[] { "+", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "+-123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-+123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "- 123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "+ 123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
// AllowTrailingSign
yield return new object[] { "123-+", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123+-", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123 -", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123 +", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
// Parentheses has priority over CurrencySymbol and PositiveSign
NumberFormatInfo currencyNegativeParenthesesFormat = new NumberFormatInfo()
{
CurrencySymbol = "(",
PositiveSign = "))"
};
yield return new object[] { "(100))", NumberStyles.AllowParentheses | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowTrailingSign, currencyNegativeParenthesesFormat, typeof(FormatException) };
// AllowTrailingSign and AllowLeadingSign
yield return new object[] { "+123+", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "+123-", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "-123+", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "-123-", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
// AllowLeadingSign and AllowParentheses
yield return new object[] { "-(1000)", NumberStyles.AllowLeadingSign | NumberStyles.AllowParentheses, null, typeof(FormatException) };
yield return new object[] { "(-1000)", NumberStyles.AllowLeadingSign | NumberStyles.AllowParentheses, null, typeof(FormatException) };
// AllowLeadingWhite
yield return new object[] { "1 ", NumberStyles.AllowLeadingWhite, null, typeof(FormatException) };
yield return new object[] { " 1 ", NumberStyles.AllowLeadingWhite, null, typeof(FormatException) };
// AllowTrailingWhite
yield return new object[] { " 1 ", NumberStyles.AllowTrailingWhite, null, typeof(FormatException) };
yield return new object[] { " 1", NumberStyles.AllowTrailingWhite, null, typeof(FormatException) };
// AllowThousands
NumberFormatInfo thousandsFormat = new NumberFormatInfo() { NumberGroupSeparator = "|" };
yield return new object[] { "|||1", NumberStyles.AllowThousands, null, typeof(FormatException) };
// AllowExponent
yield return new object[] { "65E", NumberStyles.AllowExponent, null, typeof(FormatException) };
yield return new object[] { "65E10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
yield return new object[] { "65E+10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
yield return new object[] { "65E-1", NumberStyles.AllowExponent, null, typeof(OverflowException) };
// AllowDecimalPoint
NumberFormatInfo decimalFormat = new NumberFormatInfo() { NumberDecimalSeparator = "." };
yield return new object[] { "67.9", NumberStyles.AllowDecimalPoint, decimalFormat, typeof(OverflowException) };
// Parsing integers doesn't allow NaN, PositiveInfinity or NegativeInfinity
NumberFormatInfo doubleFormat = new NumberFormatInfo()
{
NaNSymbol = "NaN",
PositiveInfinitySymbol = "Infinity",
NegativeInfinitySymbol = "-Infinity"
};
yield return new object[] { "NaN", NumberStyles.Any, doubleFormat, typeof(FormatException) };
yield return new object[] { "Infinity", NumberStyles.Any, doubleFormat, typeof(FormatException) };
yield return new object[] { "-Infinity", NumberStyles.Any, doubleFormat, typeof(FormatException) };
// Only has a leading sign
yield return new object[] { "+", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { " +", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { " -", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "+ ", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "- ", NumberStyles.Integer, null, typeof(FormatException) };
// NumberFormatInfo has a custom property with length > 1
NumberFormatInfo integerCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "123" };
yield return new object[] { "123", NumberStyles.AllowCurrencySymbol, integerCurrencyFormat, typeof(FormatException) };
yield return new object[] { "123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { PositiveSign = "123" }, typeof(FormatException) };
yield return new object[] { "123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { NegativeSign = "123" }, typeof(FormatException) };
// Decimals not in range of Int32
foreach (string s in new[]
{
"2147483648", // int.MaxValue + 1
"2147483650", // 10s digit incremented above int.MaxValue
"10000000000", // extra digit after int.MaxValue
"4294967296", // uint.MaxValue + 1
"4294967300", // 100s digit incremented above uint.MaxValue
"9223372036854775808", // long.MaxValue + 1
"9223372036854775810", // 10s digit incremented above long.MaxValue
"10000000000000000000", // extra digit after long.MaxValue
"18446744073709551616", // ulong.MaxValue + 1
"18446744073709551620", // 10s digit incremented above ulong.MaxValue
"100000000000000000000", // extra digit after ulong.MaxValue
"-2147483649", // int.MinValue - 1
"-2147483650", // 10s digit decremented below int.MinValue
"-10000000000", // extra digit after int.MinValue
"-9223372036854775809", // long.MinValue - 1
"-9223372036854775810", // 10s digit decremented below long.MinValue
"-10000000000000000000", // extra digit after long.MinValue
"100000000000000000000000000000000000000000000000000000000000000000000000000000000000000", // really big
"-100000000000000000000000000000000000000000000000000000000000000000000000000000000000000" // really small
})
{
foreach (NumberStyles styles in new[] { NumberStyles.Any, NumberStyles.Integer })
{
yield return new object[] { s, styles, null, typeof(OverflowException) };
yield return new object[] { s + " ", styles, null, typeof(OverflowException) };
yield return new object[] { s + " " + "\0\0\0", styles, null, typeof(OverflowException) };
yield return new object[] { s + "g", styles, null, typeof(FormatException) };
yield return new object[] { s + "\0g", styles, null, typeof(FormatException) };
yield return new object[] { s + " g", styles, null, typeof(FormatException) };
}
}
// Hexadecimals not in range of Int32
foreach (string s in new[]
{
"100000000", // uint.MaxValue + 1
"FFFFFFFF0", // extra digit after uint.MaxValue
"10000000000000000", // ulong.MaxValue + 1
"FFFFFFFFFFFFFFFF0", // extra digit after ulong.MaxValue
"100000000000000000000000000000000000000000000000000000000000000000000000000000000000000" // really big
})
{
yield return new object[] { s, NumberStyles.HexNumber, null, typeof(OverflowException) };
yield return new object[] { s + " ", NumberStyles.HexNumber, null, typeof(OverflowException) };
yield return new object[] { s + " " + "\0\0", NumberStyles.HexNumber, null, typeof(OverflowException) };
yield return new object[] { s + "g", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { s + "\0g", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { s + " g", NumberStyles.HexNumber, null, typeof(FormatException) };
}
yield return new object[] { "2147483649-", NumberStyles.AllowTrailingSign, null, typeof(OverflowException) };
yield return new object[] { "(2147483649)", NumberStyles.AllowParentheses, null, typeof(OverflowException) };
yield return new object[] { "2E10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
int result;
// Default style and provider
if (style == NumberStyles.Integer && provider == null)
{
Assert.False(int.TryParse(value, out result));
Assert.Equal(default, result);
Assert.Throws(exceptionType, () => int.Parse(value));
}
// Default provider
if (provider == null)
{
Assert.Throws(exceptionType, () => int.Parse(value, style));
// Substitute default NumberFormatInfo
Assert.False(int.TryParse(value, style, new NumberFormatInfo(), out result));
Assert.Equal(default, result);
Assert.Throws(exceptionType, () => int.Parse(value, style, new NumberFormatInfo()));
}
// Default style
if (style == NumberStyles.Integer)
{
Assert.Throws(exceptionType, () => int.Parse(value, provider));
}
// Full overloads
Assert.False(int.TryParse(value, style, provider, out result));
Assert.Equal(default, result);
Assert.Throws(exceptionType, () => int.Parse(value, style, provider));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName)
{
int result = 0;
AssertExtensions.Throws<ArgumentException>(paramName, () => int.TryParse("1", style, null, out result));
Assert.Equal(default(int), result);
AssertExtensions.Throws<ArgumentException>(paramName, () => int.Parse("1", style));
AssertExtensions.Throws<ArgumentException>(paramName, () => int.Parse("1", style, null));
}
[Theory]
[InlineData("N")]
[InlineData("F")]
public static void ToString_N_F_EmptyNumberGroup_Success(string specifier)
{
var nfi = (NumberFormatInfo)NumberFormatInfo.InvariantInfo.Clone();
nfi.NumberGroupSizes = new int[0];
nfi.NumberGroupSeparator = ",";
Assert.Equal("1234", 1234.ToString($"{specifier}0", nfi));
}
[Fact]
public static void ToString_P_EmptyPercentGroup_Success()
{
var nfi = (NumberFormatInfo)NumberFormatInfo.InvariantInfo.Clone();
nfi.PercentGroupSizes = new int[0];
nfi.PercentSymbol = "%";
Assert.Equal("123400 %", 1234.ToString("P0", nfi));
}
[Fact]
public static void ToString_C_EmptyPercentGroup_Success()
{
var nfi = (NumberFormatInfo)NumberFormatInfo.InvariantInfo.Clone();
nfi.CurrencyGroupSizes = new int[0];
nfi.CurrencySymbol = "$";
Assert.Equal("$1234", 1234.ToString("C0", nfi));
}
public static IEnumerable<object[]> Parse_ValidWithOffsetCount_TestData()
{
foreach (object[] inputs in Parse_Valid_TestData())
{
yield return new object[] { inputs[0], 0, ((string)inputs[0]).Length, inputs[1], inputs[2], inputs[3] };
}
NumberFormatInfo samePositiveNegativeFormat = new NumberFormatInfo()
{
PositiveSign = "|",
NegativeSign = "|"
};
NumberFormatInfo emptyPositiveFormat = new NumberFormatInfo() { PositiveSign = "" };
NumberFormatInfo emptyNegativeFormat = new NumberFormatInfo() { NegativeSign = "" };
// None
yield return new object[] { "2147483647", 1, 9, NumberStyles.None, null, 147483647 };
yield return new object[] { "2147483647", 1, 1, NumberStyles.None, null, 1 };
yield return new object[] { "123\0\0", 2, 2, NumberStyles.None, null, 3 };
// Hex
yield return new object[] { "abc", 0, 1, NumberStyles.HexNumber, null, 0xa };
yield return new object[] { "ABC", 1, 1, NumberStyles.HexNumber, null, 0xB };
yield return new object[] { "FFFFFFFF", 6, 2, NumberStyles.HexNumber, null, 0xFF };
yield return new object[] { "FFFFFFFF", 0, 1, NumberStyles.HexNumber, null, 0xF };
// Currency
yield return new object[] { "-$1000", 1, 5, NumberStyles.Currency, new NumberFormatInfo()
{
CurrencySymbol = "$",
CurrencyGroupSeparator = "|",
NumberGroupSeparator = "/"
}, 1000 };
NumberFormatInfo emptyCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "" };
yield return new object[] { "100", 1, 2, NumberStyles.Currency, emptyCurrencyFormat, 0 };
yield return new object[] { "100", 0, 1, NumberStyles.Currency, emptyCurrencyFormat, 1 };
// If CurrencySymbol and Negative are the same, NegativeSign is preferred
NumberFormatInfo sameCurrencyNegativeSignFormat = new NumberFormatInfo()
{
NegativeSign = "|",
CurrencySymbol = "|"
};
yield return new object[] { "1000", 1, 3, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowLeadingSign, sameCurrencyNegativeSignFormat, 0 };
yield return new object[] { "|1000", 0, 2, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowLeadingSign, sameCurrencyNegativeSignFormat, -1 };
// Any
yield return new object[] { "123", 0, 2, NumberStyles.Any, null, 12 };
// AllowLeadingSign
yield return new object[] { "-2147483648", 0, 10, NumberStyles.AllowLeadingSign, null, -214748364 };
// AllowTrailingSign
yield return new object[] { "123-", 0, 3, NumberStyles.AllowTrailingSign, null, 123 };
// AllowExponent
yield return new object[] { "1E2", 0, 1, NumberStyles.AllowExponent, null, 1 };
yield return new object[] { "1E+2", 3, 1, NumberStyles.AllowExponent, null, 2 };
yield return new object[] { "(1E2)", 1, 3, NumberStyles.AllowExponent | NumberStyles.AllowParentheses, null, 1E2 };
yield return new object[] { "-1E2", 1, 3, NumberStyles.AllowExponent | NumberStyles.AllowLeadingSign, null, 1E2 };
}
[Theory]
[MemberData(nameof(Parse_ValidWithOffsetCount_TestData))]
public static void Parse_Span_Valid(string value, int offset, int count, NumberStyles style, IFormatProvider provider, int expected)
{
int result;
// Default style and provider
if (style == NumberStyles.Integer && provider == null)
{
Assert.True(int.TryParse(value.AsSpan(offset, count), out result));
Assert.Equal(expected, result);
}
Assert.Equal(expected, int.Parse(value.AsSpan(offset, count), style, provider));
Assert.True(int.TryParse(value.AsSpan(offset, count), style, provider, out result));
Assert.Equal(expected, result);
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Span_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
if (value != null)
{
int result;
// Default style and provider
if (style == NumberStyles.Integer && provider == null)
{
Assert.False(int.TryParse(value.AsSpan(), out result));
Assert.Equal(0, result);
}
Assert.Throws(exceptionType, () => int.Parse(value.AsSpan(), style, provider));
Assert.False(int.TryParse(value.AsSpan(), style, provider, out result));
Assert.Equal(0, result);
}
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void TryFormat(int i, string format, IFormatProvider provider, string expected)
{
char[] actual;
int charsWritten;
// Just right
actual = new char[expected.Length];
Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten, format, provider));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal(expected, new string(actual));
// Longer than needed
actual = new char[expected.Length + 1];
Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten, format, provider));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal(expected, new string(actual, 0, charsWritten));
// Too short
if (expected.Length > 0)
{
actual = new char[expected.Length - 1];
Assert.False(i.TryFormat(actual.AsSpan(), out charsWritten, format, provider));
Assert.Equal(0, charsWritten);
}
if (format != null)
{
// Upper format
actual = new char[expected.Length];
Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten, format.ToUpperInvariant(), provider));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal(expected.ToUpperInvariant(), new string(actual));
// Lower format
actual = new char[expected.Length];
Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten, format.ToLowerInvariant(), provider));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal(expected.ToLowerInvariant(), new string(actual));
}
}
}
}
| |
using System;
using System.Linq;
using System.Net;
using System.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using Orleans.Configuration;
using Orleans.Messaging;
using Orleans.Runtime;
using System.Threading;
using System.Threading.Tasks;
namespace Orleans
{
/// <summary>
/// Extension methods for <see cref="IClientBuilder"/>.
/// </summary>
public static class ClientBuilderExtensions
{
/// <summary>
/// Configures the provided delegate as a connection retry filter, used to determine whether initial connection to the Orleans cluster should be retried after a failure.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <param name="connectionRetryFilter">The connection retry filter.</param>
/// <returns>The same instance of the <see cref="IClientBuilder"/> for chaining.</returns>
public static IClientBuilder UseConnectionRetryFilter(this IClientBuilder builder, Func<Exception, CancellationToken, Task<bool>> connectionRetryFilter)
{
return builder.ConfigureServices(collection => collection.AddSingleton<IClientConnectionRetryFilter>(new DelegateConnectionRetryFilter(connectionRetryFilter)));
}
/// <summary>
/// Configures the provided delegate as a connection retry filter, used to determine whether initial connection to the Orleans cluster should be retried after a failure.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <param name="connectionRetryFilter">The connection retry filter.</param>
/// <returns>The same instance of the <see cref="IClientBuilder"/> for chaining.</returns>
public static IClientBuilder UseConnectionRetryFilter(this IClientBuilder builder, IClientConnectionRetryFilter connectionRetryFilter)
{
return builder.ConfigureServices(collection => collection.AddSingleton<IClientConnectionRetryFilter>(connectionRetryFilter));
}
/// <summary>
/// Configures the provided <typeparamref name="TConnectionRetryFilter"/> type as a connection retry filter, used to determine whether initial connection to the Orleans cluster should be retried after a failure.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <returns>The same instance of the <see cref="IClientBuilder"/> for chaining.</returns>
public static IClientBuilder UseConnectionRetryFilter<TConnectionRetryFilter>(this IClientBuilder builder) where TConnectionRetryFilter : class, IClientConnectionRetryFilter
{
return builder.ConfigureServices(collection => collection.AddSingleton<IClientConnectionRetryFilter, TConnectionRetryFilter>());
}
private sealed class DelegateConnectionRetryFilter : IClientConnectionRetryFilter
{
private readonly Func<Exception, CancellationToken, Task<bool>> _filter;
public DelegateConnectionRetryFilter(Func<Exception, CancellationToken, Task<bool>> connectionRetryFilter) => _filter = connectionRetryFilter ?? throw new ArgumentNullException(nameof(connectionRetryFilter));
public Task<bool> ShouldRetryConnectionAttempt(Exception exception, CancellationToken cancellationToken) => _filter(exception, cancellationToken);
}
/// <summary>
/// Adds services to the container. This can be called multiple times and the results will be additive.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <param name="configureDelegate"></param>
/// <returns>The same instance of the <see cref="IClientBuilder"/> for chaining.</returns>
public static IClientBuilder ConfigureServices(this IClientBuilder builder, Action<IServiceCollection> configureDelegate)
{
if (configureDelegate == null) throw new ArgumentNullException(nameof(configureDelegate));
configureDelegate(builder.Services);
return builder;
}
/// <summary>
/// Registers an action used to configure a particular type of options.
/// </summary>
/// <typeparam name="TOptions">The options type to be configured.</typeparam>
/// <param name="builder">The host builder.</param>
/// <param name="configureOptions">The action used to configure the options.</param>
/// <returns>The client builder.</returns>
public static IClientBuilder Configure<TOptions>(this IClientBuilder builder, Action<TOptions> configureOptions) where TOptions : class
{
return builder.ConfigureServices(services => services.Configure(configureOptions));
}
/// <summary>
/// Registers a configuration instance which <typeparamref name="TOptions"/> will bind against.
/// </summary>
/// <typeparam name="TOptions">The options type to be configured.</typeparam>
/// <param name="builder">The host builder.</param>
/// <param name="configuration">The configuration.</param>
/// <returns>The client builder.</returns>
public static IClientBuilder Configure<TOptions>(this IClientBuilder builder, IConfiguration configuration) where TOptions : class
{
return builder.ConfigureServices(services => services.AddOptions<TOptions>().Bind(configuration));
}
/// <summary>
/// Registers a <see cref="GatewayCountChangedHandler"/> event handler.
/// </summary>
public static IClientBuilder AddGatewayCountChangedHandler(this IClientBuilder builder, GatewayCountChangedHandler handler)
{
builder.ConfigureServices(services => services.AddSingleton(handler));
return builder;
}
/// <summary>
/// Registers a <see cref="ConnectionToClusterLostHandler"/> event handler.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="handler">The handler.</param>
/// <returns>The builder.</returns>
public static IClientBuilder AddClusterConnectionLostHandler(this IClientBuilder builder, ConnectionToClusterLostHandler handler)
{
builder.ConfigureServices(services => services.AddSingleton(handler));
return builder;
}
/// <summary>
/// Add <see cref="Activity.Current"/> propagation through grain calls.
/// Note: according to <see cref="ActivitySource.StartActivity(string, ActivityKind)"/> activity will be created only when any listener for activity exists <see cref="ActivitySource.HasListeners()"/> and <see cref="ActivityListener.Sample"/> returns <see cref="ActivitySamplingResult.PropagationData"/>.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns>The builder.</returns>
public static IClientBuilder AddActivityPropagation(this IClientBuilder builder)
{
if (Activity.DefaultIdFormat != ActivityIdFormat.W3C)
{
throw new InvalidOperationException("Activity propagation available only for Activities in W3C format. Set Activity.DefaultIdFormat into ActivityIdFormat.W3C.");
}
return builder
.AddOutgoingGrainCallFilter<ActivityPropagationOutgoingGrainCallFilter>();
}
/// <summary>
/// Configures the client to connect to a silo on the localhost.
/// </summary>
/// <param name="builder"></param>
/// <param name="gatewayPort">The local silo's gateway port.</param>
/// <param name="serviceId">The service id.</param>
/// <param name="clusterId">The cluster id.</param>
public static IClientBuilder UseLocalhostClustering(
this IClientBuilder builder,
int gatewayPort = 30000,
string serviceId = ClusterOptions.DevelopmentServiceId,
string clusterId = ClusterOptions.DevelopmentClusterId)
{
return builder.UseLocalhostClustering(new [] {gatewayPort}, serviceId, clusterId);
}
/// <summary>
/// Configures the client to connect to a silo on the localhost.
/// </summary>
/// <param name="builder"></param>
/// <param name="gatewayPorts">The local silo gateway ports.</param>
/// <param name="serviceId">The service id.</param>
/// <param name="clusterId">The cluster id.</param>
public static IClientBuilder UseLocalhostClustering(this IClientBuilder builder,
int[] gatewayPorts,
string serviceId = ClusterOptions.DevelopmentServiceId,
string clusterId = ClusterOptions.DevelopmentClusterId)
{
return builder.UseStaticClustering(gatewayPorts.Select(p => new IPEndPoint(IPAddress.Loopback, p)).ToArray())
.ConfigureServices(services =>
{
// If the caller did not override service id or cluster id, configure default values as a fallback.
if (string.Equals(serviceId, ClusterOptions.DevelopmentServiceId) && string.Equals(clusterId, ClusterOptions.DevelopmentClusterId))
{
services.PostConfigure<ClusterOptions>(options =>
{
if (string.IsNullOrWhiteSpace(options.ClusterId)) options.ClusterId = ClusterOptions.DevelopmentClusterId;
if (string.IsNullOrWhiteSpace(options.ServiceId)) options.ServiceId = ClusterOptions.DevelopmentServiceId;
});
}
else
{
services.Configure<ClusterOptions>(options =>
{
options.ServiceId = serviceId;
options.ClusterId = clusterId;
});
}
});
}
/// <summary>
/// Configures the client to use static clustering.
/// </summary>
/// <param name="builder"></param>
/// <param name="endpoints">The gateway endpoints.</param>
public static IClientBuilder UseStaticClustering(this IClientBuilder builder, params IPEndPoint[] endpoints)
{
return builder.UseStaticClustering(options => options.Gateways = endpoints.Select(ep => ep.ToGatewayUri()).ToList());
}
/// <summary>
/// Configures the client to use static clustering.
/// </summary>
public static IClientBuilder UseStaticClustering(this IClientBuilder builder, Action<StaticGatewayListProviderOptions> configureOptions)
{
return builder.ConfigureServices(
collection =>
{
if (configureOptions != null)
{
collection.Configure(configureOptions);
}
collection.AddSingleton<IGatewayListProvider, StaticGatewayListProvider>()
.ConfigureFormatter<StaticGatewayListProviderOptions>();
});
}
/// <summary>
/// Configures the client to use static clustering.
/// </summary>
public static IClientBuilder UseStaticClustering(this IClientBuilder builder, Action<OptionsBuilder<StaticGatewayListProviderOptions>> configureOptions)
{
return builder.ConfigureServices(
collection =>
{
configureOptions?.Invoke(collection.AddOptions<StaticGatewayListProviderOptions>());
collection.AddSingleton<IGatewayListProvider, StaticGatewayListProvider>()
.ConfigureFormatter<StaticGatewayListProviderOptions>();
});
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GraphBalanceSpec.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.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using FluentAssertions;
using Reactive.Streams;
using Xunit;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class GraphBalanceSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public GraphBalanceSpec()
{
var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 16);
Materializer = ActorMaterializer.Create(Sys, settings);
}
[Fact]
public void A_Balance_must_balance_between_subscribers_which_signal_demand()
{
this.AssertAllStagesStopped(() =>
{
var c1 = TestSubscriber.CreateManualProbe<int>(this);
var c2 = TestSubscriber.CreateManualProbe<int>(this);
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var balance = b.Add(new Balance<int>(2));
var source = Source.From(Enumerable.Range(1, 3));
b.From(source).To(balance.In);
b.From(balance.Out(0)).To(Sink.FromSubscriber(c1));
b.From(balance.Out(1)).To(Sink.FromSubscriber(c2));
return ClosedShape.Instance;
})).Run(Materializer);
var sub1 = c1.ExpectSubscription();
var sub2 = c2.ExpectSubscription();
sub1.Request(1);
c1.ExpectNext(1).ExpectNoMsg(TimeSpan.FromMilliseconds(100));
sub2.Request(2);
c2.ExpectNext(2, 3);
c1.ExpectComplete();
c2.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Balance_must_support_waiting_for_demand_from_all_downstream_subscriptions()
{
this.AssertAllStagesStopped(() =>
{
var s1 = TestSubscriber.CreateManualProbe<int>(this);
var p2 = RunnableGraph.FromGraph(GraphDsl.Create(Sink.AsPublisher<int>(false), (b, p2Sink) =>
{
var balance = b.Add(new Balance<int>(2, true));
var source = Source.From(Enumerable.Range(1, 3)).MapMaterializedValue<IPublisher<int>>(_ => null);
b.From(source).To(balance.In);
b.From(balance.Out(0)).To(Sink.FromSubscriber(s1).MapMaterializedValue<IPublisher<int>>(_ => null));
b.From(balance.Out(1)).To(p2Sink);
return ClosedShape.Instance;
})).Run(Materializer);
var sub1 = s1.ExpectSubscription();
sub1.Request(1);
s1.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
var s2 = TestSubscriber.CreateManualProbe<int>(this);
p2.Subscribe(s2);
var sub2 = s2.ExpectSubscription();
// still no demand from s2
s2.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
sub2.Request(2);
s1.ExpectNext(1);
s2.ExpectNext(2, 3);
s1.ExpectComplete();
s2.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Balance_must_support_waiting_for_demand_from_all_non_cancelled_downstream_subscriptions()
{
this.AssertAllStagesStopped(() =>
{
var s1 = TestSubscriber.CreateManualProbe<int>(this);
var t = RunnableGraph.FromGraph(GraphDsl.Create(Sink.AsPublisher<int>(false),
Sink.AsPublisher<int>(false), Keep.Both, (b, p2Sink, p3Sink) =>
{
var balance = b.Add(new Balance<int>(3, true));
var source =
Source.From(Enumerable.Range(1, 3))
.MapMaterializedValue<Tuple<IPublisher<int>, IPublisher<int>>>(_ => null);
b.From(source).To(balance.In);
b.From(balance.Out(0))
.To(
Sink.FromSubscriber(s1)
.MapMaterializedValue<Tuple<IPublisher<int>, IPublisher<int>>>(_ => null));
b.From(balance.Out(1)).To(p2Sink);
b.From(balance.Out(2)).To(p3Sink);
return ClosedShape.Instance;
})).Run(Materializer);
var p2 = t.Item1;
var p3 = t.Item2;
var sub1 = s1.ExpectSubscription();
sub1.Request(1);
var s2 = TestSubscriber.CreateManualProbe<int>(this);
p2.Subscribe(s2);
var sub2 = s2.ExpectSubscription();
var s3 = TestSubscriber.CreateManualProbe<int>(this);
p3.Subscribe(s3);
var sub3 = s3.ExpectSubscription();
sub2.Request(2);
s1.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
sub3.Cancel();
s1.ExpectNext(1);
s2.ExpectNextN(2).ShouldAllBeEquivalentTo(new[] {2, 3});
s1.ExpectComplete();
s2.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Balance_must_work_with_1_way_balance()
{
this.AssertAllStagesStopped(() =>
{
var task = Source.FromGraph(GraphDsl.Create(b =>
{
var balance = b.Add(new Balance<int>(1));
var source = b.Add(Source.From(Enumerable.Range(1, 3)));
b.From(source).To(balance.In);
return new SourceShape<int>(balance.Out(0));
})).RunAggregate(new List<int>(), (list, i) =>
{
list.Add(i);
return list;
}, Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(new[] {1, 2, 3});
}, Materializer);
}
[Fact]
public void A_Balance_must_work_with_5_way_balance()
{
this.AssertAllStagesStopped(() =>
{
var sink = Sink.First<IEnumerable<int>>();
var t = RunnableGraph.FromGraph(GraphDsl.Create(sink, sink, sink, sink, sink, Tuple.Create,
(b, s1, s2, s3, s4, s5) =>
{
var balance = b.Add(new Balance<int>(5, true));
var source = Source.From(Enumerable.Range(0, 15)).MapMaterializedValue<Tuple<Task<IEnumerable<int>>, Task<IEnumerable<int>>, Task<IEnumerable<int>>, Task<IEnumerable<int>>, Task<IEnumerable<int>>>>(_=> null);
b.From(source).To(balance.In);
b.From(balance.Out(0)).Via(Flow.Create<int>().Grouped(15)).To(s1);
b.From(balance.Out(1)).Via(Flow.Create<int>().Grouped(15)).To(s2);
b.From(balance.Out(2)).Via(Flow.Create<int>().Grouped(15)).To(s3);
b.From(balance.Out(3)).Via(Flow.Create<int>().Grouped(15)).To(s4);
b.From(balance.Out(4)).Via(Flow.Create<int>().Grouped(15)).To(s5);
return ClosedShape.Instance;
})).Run(Materializer);
var task = Task.WhenAll(t.Item1, t.Item2, t.Item3, t.Item4, t.Item5);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.SelectMany(l=>l).ShouldAllBeEquivalentTo(Enumerable.Range(0, 15));
}, Materializer);
}
[Fact]
public void A_Balance_must_balance_between_all_three_outputs()
{
this.AssertAllStagesStopped(() =>
{
const int numElementsForSink = 10000;
var outputs = Sink.Aggregate<int, int>(0, (sum, i) => sum + i);
var t = RunnableGraph.FromGraph(GraphDsl.Create(outputs, outputs, outputs, Tuple.Create,
(b, o1, o2, o3) =>
{
var balance = b.Add(new Balance<int>(3, true));
var source =
Source.Repeat(1)
.Take(numElementsForSink*3)
.MapMaterializedValue<Tuple<Task<int>, Task<int>, Task<int>>>(_ => null);
b.From(source).To(balance.In);
b.From(balance.Out(0)).To(o1);
b.From(balance.Out(1)).To(o2);
b.From(balance.Out(2)).To(o3);
return ClosedShape.Instance;
})).Run(Materializer);
var task = Task.WhenAll(t.Item1, t.Item2, t.Item3);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.Should().NotContain(0);
task.Result.Sum().Should().Be(numElementsForSink*3);
}, Materializer);
}
[Fact]
public void A_Balance_must_fairly_balance_between_three_outputs()
{
this.AssertAllStagesStopped(() =>
{
var probe = this.SinkProbe<int>();
var t = RunnableGraph.FromGraph(GraphDsl.Create(probe, probe, probe, Tuple.Create,
(b, o1, o2, o3) =>
{
var balance = b.Add(new Balance<int>(3));
var source =
Source.From(Enumerable.Range(1,7))
.MapMaterializedValue<Tuple<TestSubscriber.Probe<int>, TestSubscriber.Probe<int>, TestSubscriber.Probe<int>>>(_ => null);
b.From(source).To(balance.In);
b.From(balance.Out(0)).To(o1);
b.From(balance.Out(1)).To(o2);
b.From(balance.Out(2)).To(o3);
return ClosedShape.Instance;
})).Run(Materializer);
var p1 = t.Item1;
var p2 = t.Item2;
var p3 = t.Item3;
p1.RequestNext(1);
p2.RequestNext(2);
p3.RequestNext(3);
p2.RequestNext(4);
p1.RequestNext(5);
p3.RequestNext(6);
p1.RequestNext(7);
p1.ExpectComplete();
p2.ExpectComplete();
p3.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Balance_must_produce_to_second_even_though_first_cancels()
{
this.AssertAllStagesStopped(() =>
{
var c1 = TestSubscriber.CreateManualProbe<int>(this);
var c2 = TestSubscriber.CreateManualProbe<int>(this);
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var balance = b.Add(new Balance<int>(2));
var source = Source.From(Enumerable.Range(1, 3));
b.From(source).To(balance.In);
b.From(balance.Out(0)).To(Sink.FromSubscriber(c1));
b.From(balance.Out(1)).To(Sink.FromSubscriber(c2));
return ClosedShape.Instance;
})).Run(Materializer);
var sub1 = c1.ExpectSubscription();
sub1.Cancel();
var sub2 = c2.ExpectSubscription();
sub2.Request(3);
c2.ExpectNext(1, 2, 3);
c2.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Balance_must_produce_to_first_even_though_second_cancels()
{
this.AssertAllStagesStopped(() =>
{
var c1 = TestSubscriber.CreateManualProbe<int>(this);
var c2 = TestSubscriber.CreateManualProbe<int>(this);
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var balance = b.Add(new Balance<int>(2));
var source = Source.From(Enumerable.Range(1, 3));
b.From(source).To(balance.In);
b.From(balance.Out(0)).To(Sink.FromSubscriber(c1));
b.From(balance.Out(1)).To(Sink.FromSubscriber(c2));
return ClosedShape.Instance;
})).Run(Materializer);
var sub1 = c1.ExpectSubscription();
var sub2 = c2.ExpectSubscription();
sub2.Cancel();
sub1.Request(3);
c1.ExpectNext(1, 2, 3);
c1.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Balance_must_cancel_upstream_when_downstream_cancel()
{
this.AssertAllStagesStopped(() =>
{
var p1 = TestPublisher.CreateManualProbe<int>(this);
var c1 = TestSubscriber.CreateManualProbe<int>(this);
var c2 = TestSubscriber.CreateManualProbe<int>(this);
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var balance = b.Add(new Balance<int>(2));
var source = Source.FromPublisher(p1.Publisher);
b.From(source).To(balance.In);
b.From(balance.Out(0)).To(Sink.FromSubscriber(c1));
b.From(balance.Out(1)).To(Sink.FromSubscriber(c2));
return ClosedShape.Instance;
})).Run(Materializer);
var bsub = p1.ExpectSubscription();
var sub1 = c1.ExpectSubscription();
var sub2 = c2.ExpectSubscription();
sub1.Request(1);
p1.ExpectRequest(bsub, 16);
bsub.SendNext(1);
c1.ExpectNext(1);
sub2.Request(1);
bsub.SendNext(2);
c2.ExpectNext(2);
sub1.Cancel();
sub2.Cancel();
bsub.ExpectCancellation();
}, Materializer);
}
}
}
| |
//
// PlayerEngine.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2006-2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using Hyena;
using Banshee.Base;
using Banshee.Streaming;
using Banshee.Collection;
using Banshee.ServiceStack;
namespace Banshee.MediaEngine
{
public abstract class PlayerEngine
{
public const int VolumeDelta = 10;
public const int SkipDelta = 10;
public event PlayerEventHandler EventChanged;
private TrackInfo current_track;
private TrackInfo pending_track;
private PlayerState current_state = PlayerState.NotReady;
private PlayerState last_state = PlayerState.NotReady;
// will be changed to PlayerState.Idle after going to PlayerState.Ready
private PlayerState idle_state = PlayerState.NotReady;
protected abstract void OpenUri (SafeUri uri);
internal protected virtual bool DelayedInitialize {
get { return false; }
}
public bool IsInitialized { get; internal set; }
internal protected virtual void Initialize ()
{
}
public void Reset ()
{
current_track = null;
OnStateChanged (idle_state);
}
public virtual void Close (bool fullShutdown)
{
if (fullShutdown) {
Reset ();
} else {
OnStateChanged (idle_state);
}
}
public virtual void Dispose ()
{
Close (true);
}
public void Open (SafeUri uri)
{
HandleOpen (new UnknownTrackInfo (uri));
}
public void Open (TrackInfo track)
{
HandleOpen (track);
}
public void SetNextTrack (SafeUri uri)
{
SetNextTrack (new UnknownTrackInfo (uri));
}
public void SetNextTrack (TrackInfo track)
{
HandleNextTrack (track);
}
private void HandleNextTrack (TrackInfo track)
{
pending_track = track;
if (current_state != PlayerState.Playing) {
// Pre-buffering the next track only makes sense when we're currently playing
// Instead, just open.
if (track != null && track.Uri != null) {
HandleOpen (track);
Play ();
}
return;
}
try {
// Setting the next track doesn't change the player state.
SetNextTrackUri (track == null ? null : track.Uri);
} catch (Exception e) {
Log.Exception ("Failed to pre-buffer next track", e);
}
}
private void HandleOpen (TrackInfo track)
{
Log.Warning ("Handling track open");
var uri = track.Uri;
if (current_state != PlayerState.Idle && current_state != PlayerState.NotReady && current_state != PlayerState.Contacting) {
Log.Warning ("Closing");
Close (false);
}
try {
Log.Warning ("setting state to Loading");
current_track = track;
OnStateChanged (PlayerState.Loading);
OpenUri (uri);
} catch (Exception e) {
Close (true);
OnEventChanged (new PlayerEventErrorArgs (e.Message));
}
}
public abstract void Play ();
public abstract void Pause ();
public virtual void SetNextTrackUri (SafeUri uri)
{
// Opening files on SetNextTrack is a sane default behaviour.
// This only wants to be overridden if the PlayerEngine sends out RequestNextTrack signals before EoS
OpenUri (uri);
}
public virtual void VideoExpose (IntPtr displayContext, bool direct)
{
throw new NotImplementedException ("Engine must implement VideoExpose since this method only gets called when SupportsVideo is true");
}
public virtual void VideoWindowRealize (IntPtr displayContext)
{
throw new NotImplementedException ("Engine must implement VideoWindowRealize since this method only gets called when SupportsVideo is true");
}
public virtual IntPtr [] GetBaseElements ()
{
return null;
}
protected virtual void OnStateChanged (PlayerState state)
{
if (current_state == state) {
return;
}
if (idle_state == PlayerState.NotReady && state != PlayerState.Ready) {
Hyena.Log.Warning ("Engine must transition to the ready state before other states can be entered", false);
return;
} else if (idle_state == PlayerState.NotReady && state == PlayerState.Ready) {
idle_state = PlayerState.Idle;
}
last_state = current_state;
current_state = state;
Log.DebugFormat ("Player state change: {0} -> {1}", last_state, current_state);
OnEventChanged (new PlayerEventStateChangeArgs (last_state, current_state));
// Going to the Ready state automatically transitions to the Idle state
// The Ready state is advertised so one-time startup processes can easily
// happen outside of the engine itself
if (state == PlayerState.Ready) {
OnStateChanged (PlayerState.Idle);
}
}
protected void OnEventChanged (PlayerEvent evnt)
{
OnEventChanged (new PlayerEventArgs (evnt));
}
protected virtual void OnEventChanged (PlayerEventArgs args)
{
if (args.Event == PlayerEvent.StartOfStream && pending_track != null) {
Log.DebugFormat ("OnEventChanged called with StartOfStream. Replacing current_track with pending_track: \"{0}\"",
pending_track.DisplayTrackTitle);
current_track = pending_track;
pending_track = null;
}
if (ThreadAssist.InMainThread) {
RaiseEventChanged (args);
} else {
ThreadAssist.ProxyToMain (delegate {
RaiseEventChanged (args);
});
}
}
private void RaiseEventChanged (PlayerEventArgs args)
{
PlayerEventHandler handler = EventChanged;
if (handler != null) {
handler (args);
}
}
private uint track_info_updated_timeout = 0;
protected void OnTagFound (StreamTag tag)
{
if (tag.Equals (StreamTag.Zero) || current_track == null || current_track.Uri.IsFile) {
return;
}
StreamTagger.TrackInfoMerge (current_track, tag);
if (track_info_updated_timeout <= 0) {
track_info_updated_timeout = Application.RunTimeout (250, OnTrackInfoUpdated);
}
}
private bool OnTrackInfoUpdated ()
{
TrackInfoUpdated ();
track_info_updated_timeout = 0;
return false;
}
public void TrackInfoUpdated ()
{
OnEventChanged (PlayerEvent.TrackInfoUpdated);
}
public TrackInfo CurrentTrack {
get { return current_track; }
}
public SafeUri CurrentUri {
get { return current_track == null ? null : current_track.Uri; }
}
public PlayerState CurrentState {
get { return current_state; }
}
public PlayerState LastState {
get { return last_state; }
}
public abstract ushort Volume {
get;
set;
}
public virtual bool CanSeek {
get { return true; }
}
public abstract uint Position {
get;
set;
}
public abstract uint Length {
get;
}
public abstract IEnumerable SourceCapabilities {
get;
}
public abstract IEnumerable ExplicitDecoderCapabilities {
get;
}
public abstract string Id {
get;
}
public abstract string Name {
get;
}
public abstract bool SupportsEqualizer {
get;
}
public abstract VideoDisplayContextType VideoDisplayContextType {
get;
}
public virtual IntPtr VideoDisplayContext {
set { }
get { return IntPtr.Zero; }
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the directconnect-2012-10-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DirectConnect.Model
{
/// <summary>
/// A virtual interface (VLAN) transmits the traffic between the AWS Direct Connect location
/// and the customer.
/// </summary>
public partial class AllocatePrivateVirtualInterfaceResponse : AmazonWebServiceResponse
{
private string _amazonAddress;
private int? _asn;
private string _authKey;
private string _connectionId;
private string _customerAddress;
private string _customerRouterConfig;
private string _location;
private string _ownerAccount;
private List<RouteFilterPrefix> _routeFilterPrefixes = new List<RouteFilterPrefix>();
private string _virtualGatewayId;
private string _virtualInterfaceId;
private string _virtualInterfaceName;
private VirtualInterfaceState _virtualInterfaceState;
private string _virtualInterfaceType;
private int? _vlan;
/// <summary>
/// Gets and sets the property AmazonAddress.
/// </summary>
public string AmazonAddress
{
get { return this._amazonAddress; }
set { this._amazonAddress = value; }
}
// Check to see if AmazonAddress property is set
internal bool IsSetAmazonAddress()
{
return this._amazonAddress != null;
}
/// <summary>
/// Gets and sets the property Asn.
/// </summary>
public int Asn
{
get { return this._asn.GetValueOrDefault(); }
set { this._asn = value; }
}
// Check to see if Asn property is set
internal bool IsSetAsn()
{
return this._asn.HasValue;
}
/// <summary>
/// Gets and sets the property AuthKey.
/// </summary>
public string AuthKey
{
get { return this._authKey; }
set { this._authKey = value; }
}
// Check to see if AuthKey property is set
internal bool IsSetAuthKey()
{
return this._authKey != null;
}
/// <summary>
/// Gets and sets the property ConnectionId.
/// </summary>
public string ConnectionId
{
get { return this._connectionId; }
set { this._connectionId = value; }
}
// Check to see if ConnectionId property is set
internal bool IsSetConnectionId()
{
return this._connectionId != null;
}
/// <summary>
/// Gets and sets the property CustomerAddress.
/// </summary>
public string CustomerAddress
{
get { return this._customerAddress; }
set { this._customerAddress = value; }
}
// Check to see if CustomerAddress property is set
internal bool IsSetCustomerAddress()
{
return this._customerAddress != null;
}
/// <summary>
/// Gets and sets the property CustomerRouterConfig.
/// <para>
/// Information for generating the customer router configuration.
/// </para>
/// </summary>
public string CustomerRouterConfig
{
get { return this._customerRouterConfig; }
set { this._customerRouterConfig = value; }
}
// Check to see if CustomerRouterConfig property is set
internal bool IsSetCustomerRouterConfig()
{
return this._customerRouterConfig != null;
}
/// <summary>
/// Gets and sets the property Location.
/// </summary>
public string Location
{
get { return this._location; }
set { this._location = value; }
}
// Check to see if Location property is set
internal bool IsSetLocation()
{
return this._location != null;
}
/// <summary>
/// Gets and sets the property OwnerAccount.
/// </summary>
public string OwnerAccount
{
get { return this._ownerAccount; }
set { this._ownerAccount = value; }
}
// Check to see if OwnerAccount property is set
internal bool IsSetOwnerAccount()
{
return this._ownerAccount != null;
}
/// <summary>
/// Gets and sets the property RouteFilterPrefixes.
/// </summary>
public List<RouteFilterPrefix> RouteFilterPrefixes
{
get { return this._routeFilterPrefixes; }
set { this._routeFilterPrefixes = value; }
}
// Check to see if RouteFilterPrefixes property is set
internal bool IsSetRouteFilterPrefixes()
{
return this._routeFilterPrefixes != null && this._routeFilterPrefixes.Count > 0;
}
/// <summary>
/// Gets and sets the property VirtualGatewayId.
/// </summary>
public string VirtualGatewayId
{
get { return this._virtualGatewayId; }
set { this._virtualGatewayId = value; }
}
// Check to see if VirtualGatewayId property is set
internal bool IsSetVirtualGatewayId()
{
return this._virtualGatewayId != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceId.
/// </summary>
public string VirtualInterfaceId
{
get { return this._virtualInterfaceId; }
set { this._virtualInterfaceId = value; }
}
// Check to see if VirtualInterfaceId property is set
internal bool IsSetVirtualInterfaceId()
{
return this._virtualInterfaceId != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceName.
/// </summary>
public string VirtualInterfaceName
{
get { return this._virtualInterfaceName; }
set { this._virtualInterfaceName = value; }
}
// Check to see if VirtualInterfaceName property is set
internal bool IsSetVirtualInterfaceName()
{
return this._virtualInterfaceName != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceState.
/// </summary>
public VirtualInterfaceState VirtualInterfaceState
{
get { return this._virtualInterfaceState; }
set { this._virtualInterfaceState = value; }
}
// Check to see if VirtualInterfaceState property is set
internal bool IsSetVirtualInterfaceState()
{
return this._virtualInterfaceState != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceType.
/// </summary>
public string VirtualInterfaceType
{
get { return this._virtualInterfaceType; }
set { this._virtualInterfaceType = value; }
}
// Check to see if VirtualInterfaceType property is set
internal bool IsSetVirtualInterfaceType()
{
return this._virtualInterfaceType != null;
}
/// <summary>
/// Gets and sets the property Vlan.
/// </summary>
public int Vlan
{
get { return this._vlan.GetValueOrDefault(); }
set { this._vlan = value; }
}
// Check to see if Vlan property is set
internal bool IsSetVlan()
{
return this._vlan.HasValue;
}
}
}
| |
#pragma warning disable 0168
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using nHydrate.Generator.Common.Util;
namespace nHydrate.DataImport.SqlClient
{
public class ImportDomain : IImportDomain
{
#region Class Members
public string ProgressText { get; private set; }
public int ProgressValue { get; private set; }
#endregion
#region Constructors
public ImportDomain()
{
}
#endregion
#region Import
public Database Import(string connectionString, IEnumerable<SpecialField> auditFields)
{
try
{
var database = new Database();
#region Load user defined types
LoadUdts(database, connectionString);
#endregion
#region Load Entities
this.ProgressText = "Loading Entities...";
using (var tableReader = DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, SchemaModelHelper.GetSqlDatabaseTables()))
{
while (tableReader.Read())
{
var newEntity = new Entity();
newEntity.Name = tableReader["name"].ToString();
database.EntityList.Add(newEntity);
newEntity.Schema = tableReader["schema"].ToString();
}
}
#endregion
#region Load Entity Fields
using (var columnReader = DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, SchemaModelHelper.GetSqlColumnsForTable()))
{
while (columnReader.Read())
{
var columnName = columnReader["columnName"].ToString();
var tableName = columnReader["tableName"].ToString();
var entity = database.EntityList.FirstOrDefault(x => x.Name == tableName);
//Ensure the field name is not an Audit field
if (entity != null && !auditFields.Any(x => x.Name.Match(columnName)))
{
var maxSortOrder = 0;
if (entity.FieldList.Count > 0) maxSortOrder = entity.FieldList.Max(x => x.SortOrder);
var newColumn = new Field() { Name = columnName, SortOrder = ++maxSortOrder };
entity.FieldList.Add(newColumn);
newColumn.Nullable = (int)columnReader["allow_null"] == 1;
if ((int)columnReader["is_identity"] == 1)
newColumn.Identity = true;
if (columnReader["isPrimaryKey"] != System.DBNull.Value)
newColumn.PrimaryKey = true;
try
{
newColumn.DataType = DatabaseHelper.GetSQLDataType(columnReader["system_type_id"].ToString(), database.UserDefinedTypes);
}
catch { }
var defaultvalue = columnReader["default_value"].ToString();
SetupDefault(newColumn, defaultvalue);
//newColumn.ImportedDefaultName = "";
newColumn.Length = (int)columnReader["max_length"];
//Decimals are a little different
if (newColumn.DataType == SqlDbType.Decimal)
{
newColumn.Length = (byte)columnReader["precision"];
newColumn.Scale = (int)columnReader["scale"];
}
}
else if (entity != null)
{
if (auditFields.Any(x => (x.Type == SpecialFieldTypeConstants.CreatedDate ||
x.Type == SpecialFieldTypeConstants.CreatedBy) &&
x.Name.ToLower() == columnName.ToLower()))
{
entity.AllowCreateAudit = true;
}
if (auditFields.Any(x => (x.Type == SpecialFieldTypeConstants.ModifiedDate ||
x.Type == SpecialFieldTypeConstants.ModifiedBy) &&
x.Name.ToLower() == columnName.ToLower()))
{
entity.AllowModifyAudit = true;
}
if (auditFields.Any(x => x.Type == SpecialFieldTypeConstants.Timestamp &&
x.Name.ToLower() == columnName.ToLower()))
{
entity.AllowTimestamp = true;
}
if (auditFields.Any(x => x.Type == SpecialFieldTypeConstants.Tenant &&
x.Name.ToLower() == columnName.ToLower()))
{
entity.IsTenant = true;
}
}
}
}
using (var columnReader = DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, SchemaModelHelper.GetSqlColumnsForComputed()))
{
while (columnReader.Read())
{
var tableName = columnReader["tableName"].ToString();
var columnName = columnReader["columnName"].ToString();
var entity = database.EntityList.FirstOrDefault(x => x.Name == tableName);
if (entity != null)
{
var column = entity.FieldList.FirstOrDefault(x => x.Name.ToLower() == columnName.ToLower());
if (column != null)
{
column.IsComputed = true;
column.Formula = columnReader["definition"].ToString();
}
}
}
}
#endregion
#region Load Entity Indexes
using (var indexReader = DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, SchemaModelHelper.GetSqlIndexesForTable()))
{
while (indexReader.Read())
{
var indexName = indexReader["indexname"].ToString();
var columnName = indexReader["columnname"].ToString();
var tableName = indexReader["tableName"].ToString();
var entity = database.EntityList.FirstOrDefault(x => x.Name == tableName);
if (entity != null)
{
var pk = bool.Parse(indexReader["is_primary_key"].ToString());
var column = entity.FieldList.FirstOrDefault(x => x.Name == columnName);
if (column != null && !pk)
column.IsIndexed = true;
}
}
}
#endregion
#region Load Relations
var dsRelationship = DatabaseHelper.ExecuteDataset(connectionString, SchemaModelHelper.GetSqlForRelationships());
foreach (DataRow rowRelationship in dsRelationship.Tables[0].Rows)
{
var constraintName = rowRelationship["FK_CONSTRAINT_NAME"].ToString();
var parentTableName = (string)rowRelationship["UQ_TABLE_NAME"];
var childTableName = (string)rowRelationship["FK_TABLE_NAME"];
var parentTable = database.EntityList.FirstOrDefault(x => x.Name == parentTableName);
var childTable = database.EntityList.FirstOrDefault(x => x.Name == childTableName);
if (parentTable != null && childTable != null)
{
Relationship newRelation = null;
var isAdd = false;
if (database.RelationshipList.Count(x => x.ConstraintName == constraintName) == 0)
{
newRelation = new Relationship();
if (rowRelationship["object_id"] != System.DBNull.Value)
newRelation.ImportData = rowRelationship["object_id"].ToString();
newRelation.SourceEntity = parentTable;
newRelation.TargetEntity = childTable;
newRelation.ConstraintName = constraintName;
var search = ("_" + childTable.Name + "_" + parentTable.Name).ToLower();
var roleName = constraintName.ToLower().Replace(search, string.Empty);
if (roleName.Length >= 3) roleName = roleName.Remove(0, 3);
var v = roleName.ToLower();
if (v != "fk") newRelation.RoleName = v;
isAdd = true;
}
else
{
newRelation = database.RelationshipList.First(x => x.ConstraintName == constraintName);
}
//add the column relationship to the relation
var columnRelationship = new RelationshipDetail();
var parentColumnName = (string)rowRelationship["UQ_COLUMN_NAME"];
var childColumnName = (string)rowRelationship["FK_COLUMN_NAME"];
if (parentTable.FieldList.Count(x => x.Name == parentColumnName) == 1 && (childTable.FieldList.Count(x => x.Name == childColumnName) == 1))
{
columnRelationship.ParentField = parentTable.FieldList.First(x => x.Name == parentColumnName);
columnRelationship.ChildField = childTable.FieldList.First(x => x.Name == childColumnName);
newRelation.RelationshipColumnList.Add(columnRelationship);
//ONLY ADD THIS RELATION IF ALL WENT WELL
if (isAdd)
parentTable.RelationshipList.Add(newRelation);
}
else
{
System.Diagnostics.Debug.Write(string.Empty);
}
}
}
#endregion
#region Load Views
this.ProgressText = "Loading Views...";
LoadViews(database, connectionString);
#endregion
#region Load Indexes
this.ProgressText = "Loading Indexes...";
LoadIndexes(database, connectionString);
#endregion
LoadUniqueFields(database, connectionString);
return database;
}
catch (Exception ex /*ignored*/)
{
throw;
}
finally
{
this.ProgressText = string.Empty;
this.ProgressValue = 0;
}
}
#endregion
#region DatabaseDomain
public IDatabaseHelper DatabaseDomain
{
get { return new DatabaseHelper(); }
}
#endregion
#region Load user Defined Types
private static void LoadUdts(Database database, string connectionString)
{
const string sql = "select t.name as udt_name, s.name as replacer, t.max_length as length from sys.types t" +
" left join sys.types s on t.system_type_id = s.system_type_id and s.system_type_id = s.user_type_id" +
" where t.is_user_defined = 1 and s.name IS NOT NULL";
try
{
var dsUdts = DatabaseHelper.ExecuteDataset(connectionString, sql);
foreach (DataTable dt in dsUdts.Tables)
{
if (dt.Columns.Contains("replacer"))
{
foreach (DataRow dr in dt.Rows)
{
var udtTypeName = (string)dr["udt_name"];
var sysTypeName = (string)dr["replacer"];
if (!database.UserDefinedTypes.ContainsKey(udtTypeName))
database.UserDefinedTypes.Add(udtTypeName, sysTypeName);
}
break;
}
}
}
catch (Exception ex)
{
throw;
}
}
#endregion
#region LoadViews
private static void LoadViews(Database database, string connectionString)
{
var dsView = DatabaseHelper.ExecuteDataset(connectionString, SchemaModelHelper.GetSqlForViews());
var dsViewColumn = DatabaseHelper.ExecuteDataset(connectionString, SchemaModelHelper.GetSqlForViewsColumns());
//Add the Views
if (dsView.Tables.Count > 0)
{
foreach (DataRow rowView in dsView.Tables[0].Rows)
{
var name = (string)rowView["name"];
var schema = (string)rowView["schemaname"];
var sql = SchemaModelHelper.GetViewBody((string)rowView["definition"]);
var view = database.ViewList.FirstOrDefault(x => x.Name == name);
if (view == null)
{
view = new View();
view.Name = name;
view.SQL = sql;
view.Schema = schema;
database.ViewList.Add(view);
}
}
}
//Add the columns
if (dsViewColumn.Tables.Count > 0)
{
foreach (DataRow rowView in dsViewColumn.Tables[0].Rows)
{
var viewName = (string)rowView["viewname"];
var columnName = (string)rowView["columnname"];
var dataType = DatabaseHelper.GetSQLDataType(rowView["system_type_id"].ToString(), database.UserDefinedTypes);
var length = int.Parse(rowView["max_length"].ToString());
var view = database.ViewList.FirstOrDefault(x => x.Name.ToLower() == viewName.ToLower());
//The length is half the bytes for these types
if ((dataType == SqlDbType.NChar) || (dataType == SqlDbType.NVarChar))
{
length /= 2;
}
else if (dataType == SqlDbType.DateTime2)
{
length = int.Parse(rowView["scale"].ToString());
}
if (view != null)
{
var field = new Field();
field.Name = columnName;
field.DataType = dataType;
field.Length = length;
field.Scale = int.Parse(rowView["scale"].ToString());
field.Nullable = (bool)rowView["is_nullable"];
view.FieldList.Add(field);
}
}
}
}
#endregion
#region LoadIndexes
private static void LoadIndexes(Database database, string connectionString)
{
try
{
//Add the Indexes
var dsIndexes = DatabaseHelper.ExecuteDataset(connectionString, SchemaModelHelper.GetSqlForIndexes());
if (dsIndexes.Tables.Count > 0)
{
foreach (DataRow rowFunction in dsIndexes.Tables[0].Rows)
{
var indexName = (string)rowFunction["indexname"];
var tableName = (string)rowFunction["tablename"];
var pk = (bool)rowFunction["is_primary_key"];
var clustered = (string)rowFunction["type_desc"] == "CLUSTERED";
var isUnique = (bool)rowFunction["is_unique_constraint"];
var index = database.IndexList.FirstOrDefault(x => x.IndexName == indexName && x.TableName == tableName);
if (index == null)
{
index = new Index()
{
IndexName = indexName,
TableName = tableName,
IsPrimaryKey = pk,
Clustered = clustered,
IsUnique = isUnique,
};
database.IndexList.Add(index);
}
//Add the Field
index.FieldList.Add(new IndexField()
{
Name = (string)rowFunction["columnname"],
IsDescending = (bool)rowFunction["is_descending_key"],
OrderIndex = int.Parse(rowFunction["key_ordinal"].ToString()),
});
}
}
}
catch (Exception /*ignored*/)
{
throw;
}
}
#endregion
#region LoadUniqueFields
private static void LoadUniqueFields(Database database, string connectionString)
{
try
{
//Add the Functions
var dsIndexes = DatabaseHelper.ExecuteDataset(connectionString, SchemaModelHelper.GetSqlForUniqueConstraints());
if (dsIndexes.Tables.Count > 0)
{
foreach (DataRow rowFunction in dsIndexes.Tables[0].Rows)
{
var tableName = (string)rowFunction["tablename"];
var columnName = (string)rowFunction["columnname"];
var entity = database.EntityList.FirstOrDefault(x => x.Name == tableName);
if (entity != null)
{
var field = entity.FieldList.FirstOrDefault(x => x.Name == columnName);
if (field != null)
{
field.IsUnique = true;
}
}
}
}
}
catch (Exception /*ignored*/)
{
throw;
}
}
#endregion
#region GetEntityList
public IEnumerable<string> GetEntityList(string connectionString)
{
var retval = new List<string>();
using (var tableReader = DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, SchemaModelHelper.GetSqlDatabaseTables()))
{
while (tableReader.Read())
{
var newEntity = new Entity();
newEntity.Name = tableReader["name"].ToString();
retval.Add(newEntity.Name);
newEntity.Schema = tableReader["schema"].ToString();
}
}
return retval;
}
#endregion
#region GetViewList
public IEnumerable<string> GetViewList(string connectionString)
{
var retval = new List<string>();
using (var tableReader = DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, SchemaModelHelper.GetSqlForViews()))
{
while (tableReader.Read())
{
var newEntity = new View();
newEntity.Name = tableReader["name"].ToString();
retval.Add(newEntity.Name);
//newEntity.Schema = tableReader["schema"].ToString();
}
}
return retval;
}
#endregion
#region GetEntity
public Entity GetEntity(string connectionString, string name, IEnumerable<SpecialField> auditFields)
{
var database = new Database();
#region Load Entities
using (var tableReader = DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, SchemaModelHelper.GetSqlDatabaseTables()))
{
while (tableReader.Read())
{
var newEntity = new Entity();
newEntity.Name = tableReader["name"].ToString();
if (newEntity.Name.Match(name)) //Only the specified item
database.EntityList.Add(newEntity);
newEntity.Schema = tableReader["schema"].ToString();
}
}
#endregion
#region Load Entity Fields
using (var columnReader = DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, SchemaModelHelper.GetSqlColumnsForTable(name)))
{
while (columnReader.Read())
{
var columnName = columnReader["columnName"].ToString();
var tableName = columnReader["tableName"].ToString();
var entity = database.EntityList.FirstOrDefault(x => x.Name == tableName);
//Ensure the field name is not an Audit field
if (entity != null && !auditFields.Any(x => x.Name.ToLower() == columnName.ToLower()))
{
var maxSortOrder = 0;
if (entity.FieldList.Count > 0) maxSortOrder = entity.FieldList.Max(x => x.SortOrder);
var newColumn = new Field() { Name = columnName, SortOrder = ++maxSortOrder };
entity.FieldList.Add(newColumn);
newColumn.Nullable = (int)columnReader["allow_null"] == 1;
if (bool.Parse(columnReader["is_identity"].ToString()))
newColumn.Identity = true;
if (columnReader["isPrimaryKey"] != System.DBNull.Value)
newColumn.PrimaryKey = true;
try
{
newColumn.DataType = DatabaseHelper.GetSQLDataType(columnReader["system_type_id"].ToString(), database.UserDefinedTypes);
}
catch { }
var defaultvalue = columnReader["default_value"].ToString();
SetupDefault(newColumn, defaultvalue);
newColumn.Length = (int)columnReader["max_length"];
//Decimals are a little different
if (newColumn.DataType == SqlDbType.Decimal)
{
newColumn.Length = (byte)columnReader["precision"];
newColumn.Scale = (int)columnReader["scale"];
}
}
else if (entity != null)
{
if (auditFields.Any(x => (x.Type == SpecialFieldTypeConstants.CreatedDate ||
x.Type == SpecialFieldTypeConstants.CreatedBy) &&
x.Name.ToLower() == columnName.ToLower()))
{
entity.AllowCreateAudit = true;
}
if (auditFields.Any(x => (x.Type == SpecialFieldTypeConstants.ModifiedDate ||
x.Type == SpecialFieldTypeConstants.ModifiedBy) &&
x.Name.ToLower() == columnName.ToLower()))
{
entity.AllowModifyAudit = true;
}
if (auditFields.Any(x => x.Type == SpecialFieldTypeConstants.Timestamp &&
x.Name.ToLower() == columnName.ToLower()))
{
entity.AllowTimestamp = true;
}
if (auditFields.Any(x => x.Type == SpecialFieldTypeConstants.Tenant &&
x.Name.ToLower() == columnName.ToLower()))
{
entity.IsTenant = true;
}
}
}
}
#endregion
#region Load Entity Fields Extra
using (var indexReader = DatabaseHelper.ExecuteReader(connectionString, CommandType.Text, SchemaModelHelper.GetSqlIndexesForTable()))
{
while (indexReader.Read())
{
var indexName = indexReader["indexname"].ToString();
var columnName = indexReader["columnname"].ToString();
var tableName = indexReader["tableName"].ToString();
var entity = database.EntityList.FirstOrDefault(x => x.Name == tableName);
if (entity != null)
{
var pk = bool.Parse(indexReader["is_primary_key"].ToString());
var column = entity.FieldList.FirstOrDefault(x => x.Name == columnName);
if (column != null && !pk)
column.IsIndexed = true;
}
}
}
#endregion
LoadIndexes(database, connectionString);
LoadUniqueFields(database, connectionString);
return database.EntityList.FirstOrDefault();
}
#endregion
#region GetView
public View GetView(string connectionString, string name, IEnumerable<SpecialField> auditFields)
{
var database = new Database();
LoadViews(database, connectionString);
var l = database.ViewList.Where(x => x.Name != name).ToList();
database.ViewList.RemoveAll(x => l.Contains(x));
return database.ViewList.FirstOrDefault();
}
#endregion
#region Helpers
private static void SetupDefault(Field field, string defaultvalue)
{
if (defaultvalue == null) defaultvalue = string.Empty;
//This is some sort of default pointer, we do not handle this.
if (defaultvalue.Contains("create default ["))
defaultvalue = string.Empty;
//Just in case some put 'null' in to the default field
if (field.Nullable && defaultvalue.ToLower() == "null")
defaultvalue = string.Empty;
if (field.DataType.IsNumericType() || field.DataType == SqlDbType.Bit || field.DataType.IsDateType() || field.DataType.IsBinaryType())
{
field.DefaultValue = defaultvalue.Replace("(", string.Empty).Replace(")", string.Empty); //remove any parens
}
else if (field.DataType == SqlDbType.UniqueIdentifier)
{
if (!string.IsNullOrEmpty(defaultvalue) && defaultvalue.Contains("newid"))
field.DefaultValue = "newid";
if (!string.IsNullOrEmpty(defaultvalue) && defaultvalue.Contains("newsequentialid"))
field.DefaultValue = "newsequentialid";
else
field.DefaultValue = defaultvalue.Replace("(", string.Empty).Replace(")", string.Empty).Replace("'", string.Empty); //Format: ('000...0000')
}
else if (field.DataType.IsTextType())
{
if (defaultvalue.StartsWith("(N'")) defaultvalue = defaultvalue.Substring(3, defaultvalue.Length - 3);
while (defaultvalue.StartsWith("('")) defaultvalue = defaultvalue.Substring(2, defaultvalue.Length - 2);
while (defaultvalue.EndsWith("')")) defaultvalue = defaultvalue.Substring(0, defaultvalue.Length - 2);
field.DefaultValue = defaultvalue;
}
else
field.DefaultValue = defaultvalue;
//Check for NULL value. There is no need to add a NULL default for a nullable field
if (!string.IsNullOrEmpty(field.DefaultValue) && field.Nullable && (field.DefaultValue.ToLower() == "null"))
{
field.DefaultValue = string.Empty;
}
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.