context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/*
* 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.Drawing;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
public enum DrawRoutine
{
Rectangle,
Polygon,
Ellipse
}
public struct face
{
public Point[] pts;
}
public struct DrawStruct
{
public DrawRoutine dr;
public Rectangle rect;
public SolidBrush brush;
public face[] trns;
}
public class MapImageModule : IMapImageGenerator, IRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
private IConfigSource m_config;
private IMapTileTerrainRenderer terrainRenderer;
#region IMapImageGenerator Members
public Bitmap CreateMapTile(string gradientmap)
{
bool drawPrimVolume = true;
bool textureTerrain = false;
try
{
IConfig startupConfig = m_config.Configs["Startup"];
drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume);
textureTerrain = startupConfig.GetBoolean("TextureOnMapTile", textureTerrain);
}
catch
{
m_log.Warn("[MAPTILE]: Failed to load StartupConfig");
}
if (textureTerrain)
{
terrainRenderer = new TexturedMapTileRenderer();
}
else
{
terrainRenderer = new ShadedMapTileRenderer();
}
terrainRenderer.Initialise(m_scene, m_config);
Bitmap mapbmp = new Bitmap((int)Constants.RegionSize, (int)Constants.RegionSize, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
//long t = System.Environment.TickCount;
//for (int i = 0; i < 10; ++i) {
terrainRenderer.TerrainToBitmap(mapbmp);
//}
//t = System.Environment.TickCount - t;
//m_log.InfoFormat("[MAPTILE] generation of 10 maptiles needed {0} ms", t);
if (drawPrimVolume)
{
DrawObjectVolume(m_scene, mapbmp);
}
return mapbmp;
}
public byte[] WriteJpeg2000Image(string gradientmap)
{
try
{
using (Bitmap mapbmp = CreateMapTile(gradientmap))
return OpenJPEG.EncodeFromImage(mapbmp, true);
}
catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke
{
m_log.Error("Failed generating terrain map: " + e);
}
return null;
}
#endregion
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource source)
{
m_scene = scene;
m_config = source;
IConfig startupConfig = m_config.Configs["Startup"];
if (startupConfig.GetString("MapImageModule", "MapImageModule") !=
"MapImageModule")
return;
m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "MapImageModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
// TODO: unused:
// private void ShadeBuildings(Bitmap map)
// {
// lock (map)
// {
// lock (m_scene.Entities)
// {
// foreach (EntityBase entity in m_scene.Entities.Values)
// {
// if (entity is SceneObjectGroup)
// {
// SceneObjectGroup sog = (SceneObjectGroup) entity;
//
// foreach (SceneObjectPart primitive in sog.Children.Values)
// {
// int x = (int) (primitive.AbsolutePosition.X - (primitive.Scale.X / 2));
// int y = (int) (primitive.AbsolutePosition.Y - (primitive.Scale.Y / 2));
// int w = (int) primitive.Scale.X;
// int h = (int) primitive.Scale.Y;
//
// int dx;
// for (dx = x; dx < x + w; dx++)
// {
// int dy;
// for (dy = y; dy < y + h; dy++)
// {
// if (x < 0 || y < 0)
// continue;
// if (x >= map.Width || y >= map.Height)
// continue;
//
// map.SetPixel(dx, dy, Color.DarkGray);
// }
// }
// }
// }
// }
// }
// }
// }
private Bitmap DrawObjectVolume(Scene whichScene, Bitmap mapbmp)
{
int tc = 0;
double[,] hm = whichScene.Heightmap.GetDoubles();
tc = Environment.TickCount;
m_log.Info("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile");
List<EntityBase> objs = whichScene.GetEntities();
Dictionary<uint, DrawStruct> z_sort = new Dictionary<uint, DrawStruct>();
//SortedList<float, RectangleDrawStruct> z_sort = new SortedList<float, RectangleDrawStruct>();
List<float> z_sortheights = new List<float>();
List<uint> z_localIDs = new List<uint>();
lock (objs)
{
foreach (EntityBase obj in objs)
{
// Only draw the contents of SceneObjectGroup
if (obj is SceneObjectGroup)
{
SceneObjectGroup mapdot = (SceneObjectGroup)obj;
Color mapdotspot = Color.Gray; // Default color when prim color is white
// Loop over prim in group
foreach (SceneObjectPart part in mapdot.Children.Values)
{
if (part == null)
continue;
// Draw if the object is at least 1 meter wide in any direction
if (part.Scale.X > 1f || part.Scale.Y > 1f || part.Scale.Z > 1f)
{
// Try to get the RGBA of the default texture entry..
//
try
{
// get the null checks out of the way
// skip the ones that break
if (part == null)
continue;
if (part.Shape == null)
continue;
if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree || part.Shape.PCode == (byte)PCode.Grass)
continue; // eliminates trees from this since we don't really have a good tree representation
// if you want tree blocks on the map comment the above line and uncomment the below line
//mapdotspot = Color.PaleGreen;
Primitive.TextureEntry textureEntry = part.Shape.Textures;
if (textureEntry == null || textureEntry.DefaultTexture == null)
continue;
Color4 texcolor = textureEntry.DefaultTexture.RGBA;
// Not sure why some of these are null, oh well.
int colorr = 255 - (int)(texcolor.R * 255f);
int colorg = 255 - (int)(texcolor.G * 255f);
int colorb = 255 - (int)(texcolor.B * 255f);
if (!(colorr == 255 && colorg == 255 && colorb == 255))
{
//Try to set the map spot color
try
{
// If the color gets goofy somehow, skip it *shakes fist at Color4
mapdotspot = Color.FromArgb(colorr, colorg, colorb);
}
catch (ArgumentException)
{
}
}
}
catch (IndexOutOfRangeException)
{
// Windows Array
}
catch (ArgumentOutOfRangeException)
{
// Mono Array
}
Vector3 pos = part.GetWorldPosition();
// skip prim outside of retion
if (pos.X < 0f || pos.X > 256f || pos.Y < 0f || pos.Y > 256f)
continue;
// skip prim in non-finite position
if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) ||
Single.IsInfinity(pos.X) || Single.IsInfinity(pos.Y))
continue;
// Figure out if object is under 256m above the height of the terrain
bool isBelow256AboveTerrain = false;
try
{
isBelow256AboveTerrain = (pos.Z < ((float)hm[(int)pos.X, (int)pos.Y] + 256f));
}
catch (Exception)
{
}
if (isBelow256AboveTerrain)
{
// Translate scale by rotation so scale is represented properly when object is rotated
Vector3 lscale = new Vector3(part.Shape.Scale.X, part.Shape.Scale.Y, part.Shape.Scale.Z);
Vector3 scale = new Vector3();
Vector3 tScale = new Vector3();
Vector3 axPos = new Vector3(pos.X,pos.Y,pos.Z);
Quaternion llrot = part.GetWorldRotation();
Quaternion rot = new Quaternion(llrot.W, llrot.X, llrot.Y, llrot.Z);
scale = lscale * rot;
// negative scales don't work in this situation
scale.X = Math.Abs(scale.X);
scale.Y = Math.Abs(scale.Y);
scale.Z = Math.Abs(scale.Z);
// This scaling isn't very accurate and doesn't take into account the face rotation :P
int mapdrawstartX = (int)(pos.X - scale.X);
int mapdrawstartY = (int)(pos.Y - scale.Y);
int mapdrawendX = (int)(pos.X + scale.X);
int mapdrawendY = (int)(pos.Y + scale.Y);
// If object is beyond the edge of the map, don't draw it to avoid errors
if (mapdrawstartX < 0 || mapdrawstartX > ((int)Constants.RegionSize - 1) || mapdrawendX < 0 || mapdrawendX > ((int)Constants.RegionSize - 1)
|| mapdrawstartY < 0 || mapdrawstartY > ((int)Constants.RegionSize - 1) || mapdrawendY < 0
|| mapdrawendY > ((int)Constants.RegionSize - 1))
continue;
#region obb face reconstruction part duex
Vector3[] vertexes = new Vector3[8];
// float[] distance = new float[6];
Vector3[] FaceA = new Vector3[6]; // vertex A for Facei
Vector3[] FaceB = new Vector3[6]; // vertex B for Facei
Vector3[] FaceC = new Vector3[6]; // vertex C for Facei
Vector3[] FaceD = new Vector3[6]; // vertex D for Facei
tScale = new Vector3(lscale.X, -lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[0] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[0].x = pos.X + vertexes[0].x;
//vertexes[0].y = pos.Y + vertexes[0].y;
//vertexes[0].z = pos.Z + vertexes[0].z;
FaceA[0] = vertexes[0];
FaceB[3] = vertexes[0];
FaceA[4] = vertexes[0];
tScale = lscale;
scale = ((tScale * rot));
vertexes[1] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[1].x = pos.X + vertexes[1].x;
// vertexes[1].y = pos.Y + vertexes[1].y;
//vertexes[1].z = pos.Z + vertexes[1].z;
FaceB[0] = vertexes[1];
FaceA[1] = vertexes[1];
FaceC[4] = vertexes[1];
tScale = new Vector3(lscale.X, -lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[2] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
//vertexes[2].x = pos.X + vertexes[2].x;
//vertexes[2].y = pos.Y + vertexes[2].y;
//vertexes[2].z = pos.Z + vertexes[2].z;
FaceC[0] = vertexes[2];
FaceD[3] = vertexes[2];
FaceC[5] = vertexes[2];
tScale = new Vector3(lscale.X, lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[3] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
//vertexes[3].x = pos.X + vertexes[3].x;
// vertexes[3].y = pos.Y + vertexes[3].y;
// vertexes[3].z = pos.Z + vertexes[3].z;
FaceD[0] = vertexes[3];
FaceC[1] = vertexes[3];
FaceA[5] = vertexes[3];
tScale = new Vector3(-lscale.X, lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[4] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[4].x = pos.X + vertexes[4].x;
// vertexes[4].y = pos.Y + vertexes[4].y;
// vertexes[4].z = pos.Z + vertexes[4].z;
FaceB[1] = vertexes[4];
FaceA[2] = vertexes[4];
FaceD[4] = vertexes[4];
tScale = new Vector3(-lscale.X, lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[5] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[5].x = pos.X + vertexes[5].x;
// vertexes[5].y = pos.Y + vertexes[5].y;
// vertexes[5].z = pos.Z + vertexes[5].z;
FaceD[1] = vertexes[5];
FaceC[2] = vertexes[5];
FaceB[5] = vertexes[5];
tScale = new Vector3(-lscale.X, -lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[6] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[6].x = pos.X + vertexes[6].x;
// vertexes[6].y = pos.Y + vertexes[6].y;
// vertexes[6].z = pos.Z + vertexes[6].z;
FaceB[2] = vertexes[6];
FaceA[3] = vertexes[6];
FaceB[4] = vertexes[6];
tScale = new Vector3(-lscale.X, -lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[7] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[7].x = pos.X + vertexes[7].x;
// vertexes[7].y = pos.Y + vertexes[7].y;
// vertexes[7].z = pos.Z + vertexes[7].z;
FaceD[2] = vertexes[7];
FaceC[3] = vertexes[7];
FaceD[5] = vertexes[7];
#endregion
//int wy = 0;
//bool breakYN = false; // If we run into an error drawing, break out of the
// loop so we don't lag to death on error handling
DrawStruct ds = new DrawStruct();
ds.brush = new SolidBrush(mapdotspot);
//ds.rect = new Rectangle(mapdrawstartX, (255 - mapdrawstartY), mapdrawendX - mapdrawstartX, mapdrawendY - mapdrawstartY);
ds.trns = new face[FaceA.Length];
for (int i = 0; i < FaceA.Length; i++)
{
Point[] working = new Point[5];
working[0] = project(FaceA[i], axPos);
working[1] = project(FaceB[i], axPos);
working[2] = project(FaceD[i], axPos);
working[3] = project(FaceC[i], axPos);
working[4] = project(FaceA[i], axPos);
face workingface = new face();
workingface.pts = working;
ds.trns[i] = workingface;
}
z_sort.Add(part.LocalId, ds);
z_localIDs.Add(part.LocalId);
z_sortheights.Add(pos.Z);
//for (int wx = mapdrawstartX; wx < mapdrawendX; wx++)
//{
//for (wy = mapdrawstartY; wy < mapdrawendY; wy++)
//{
//m_log.InfoFormat("[MAPDEBUG]: {0},{1}({2})", wx, (255 - wy),wy);
//try
//{
// Remember, flip the y!
// mapbmp.SetPixel(wx, (255 - wy), mapdotspot);
//}
//catch (ArgumentException)
//{
// breakYN = true;
//}
//if (breakYN)
// break;
//}
//if (breakYN)
// break;
//}
} // Object is within 256m Z of terrain
} // object is at least a meter wide
} // loop over group children
} // entitybase is sceneobject group
} // foreach loop over entities
float[] sortedZHeights = z_sortheights.ToArray();
uint[] sortedlocalIds = z_localIDs.ToArray();
// Sort prim by Z position
Array.Sort(sortedZHeights, sortedlocalIds);
Graphics g = Graphics.FromImage(mapbmp);
for (int s = 0; s < sortedZHeights.Length; s++)
{
if (z_sort.ContainsKey(sortedlocalIds[s]))
{
DrawStruct rectDrawStruct = z_sort[sortedlocalIds[s]];
for (int r = 0; r < rectDrawStruct.trns.Length; r++)
{
g.FillPolygon(rectDrawStruct.brush,rectDrawStruct.trns[r].pts);
}
//g.FillRectangle(rectDrawStruct.brush , rectDrawStruct.rect);
}
}
g.Dispose();
} // lock entities objs
m_log.Info("[MAPTILE]: Generating Maptile Step 2: Done in " + (Environment.TickCount - tc) + " ms");
return mapbmp;
}
private Point project(Vector3 point3d, Vector3 originpos)
{
Point returnpt = new Point();
//originpos = point3d;
//int d = (int)(256f / 1.5f);
//Vector3 topos = new Vector3(0, 0, 0);
// float z = -point3d.z - topos.z;
returnpt.X = (int)point3d.X;//(int)((topos.x - point3d.x) / z * d);
returnpt.Y = (int)(((int)Constants.RegionSize - 1) - point3d.Y);//(int)(255 - (((topos.y - point3d.y) / z * d)));
return returnpt;
}
// TODO: unused:
// #region Deprecated Maptile Generation. Adam may update this
// private Bitmap TerrainToBitmap(string gradientmap)
// {
// Bitmap gradientmapLd = new Bitmap(gradientmap);
//
// int pallete = gradientmapLd.Height;
//
// Bitmap bmp = new Bitmap(m_scene.Heightmap.Width, m_scene.Heightmap.Height);
// Color[] colours = new Color[pallete];
//
// for (int i = 0; i < pallete; i++)
// {
// colours[i] = gradientmapLd.GetPixel(0, i);
// }
//
// lock (m_scene.Heightmap)
// {
// ITerrainChannel copy = m_scene.Heightmap;
// for (int y = 0; y < copy.Height; y++)
// {
// for (int x = 0; x < copy.Width; x++)
// {
// // 512 is the largest possible height before colours clamp
// int colorindex = (int) (Math.Max(Math.Min(1.0, copy[x, y] / 512.0), 0.0) * (pallete - 1));
//
// // Handle error conditions
// if (colorindex > pallete - 1 || colorindex < 0)
// bmp.SetPixel(x, copy.Height - y - 1, Color.Red);
// else
// bmp.SetPixel(x, copy.Height - y - 1, colours[colorindex]);
// }
// }
// ShadeBuildings(bmp);
// return bmp;
// }
// }
// #endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
namespace ServiceStack.Text.Common
{
internal static class DeserializeSpecializedCollections<T, TSerializer>
where TSerializer : ITypeSerializer
{
private readonly static ParseStringDelegate CacheFn;
static DeserializeSpecializedCollections()
{
CacheFn = GetParseFn();
}
public static ParseStringDelegate Parse
{
get { return CacheFn; }
}
public static ParseStringDelegate GetParseFn()
{
if (typeof(T).HasAnyTypeDefinitionsOf(typeof(Queue<>)))
{
if (typeof(T) == typeof(Queue<string>))
return ParseStringQueue;
if (typeof(T) == typeof(Queue<int>))
return ParseIntQueue;
return GetGenericQueueParseFn();
}
if (typeof(T).HasAnyTypeDefinitionsOf(typeof(Stack<>)))
{
if (typeof(T) == typeof(Stack<string>))
return ParseStringStack;
if (typeof(T) == typeof(Stack<int>))
return ParseIntStack;
return GetGenericStackParseFn();
}
#if !SILVERLIGHT
if (typeof(T) == typeof(StringCollection))
{
return ParseStringCollection<TSerializer>;
}
#endif
return GetGenericEnumerableParseFn();
}
public static Queue<string> ParseStringQueue(string value)
{
var parse = (IEnumerable<string>)DeserializeList<List<string>, TSerializer>.Parse(value);
return new Queue<string>(parse);
}
public static Queue<int> ParseIntQueue(string value)
{
var parse = (IEnumerable<int>)DeserializeList<List<int>, TSerializer>.Parse(value);
return new Queue<int>(parse);
}
#if !SILVERLIGHT
public static StringCollection ParseStringCollection<TSerializer>(string value) where TSerializer : ITypeSerializer
{
if ((value = DeserializeListWithElements<TSerializer>.StripList(value)) == null) return null;
return value == String.Empty
? new StringCollection()
: ToStringCollection(DeserializeListWithElements<TSerializer>.ParseStringList(value));
}
public static StringCollection ToStringCollection(List<string> items)
{
var to = new StringCollection();
foreach (var item in items)
{
to.Add(item);
}
return to;
}
#endif
internal static ParseStringDelegate GetGenericQueueParseFn()
{
var enumerableInterface = typeof(T).GetTypeWithGenericInterfaceOf(typeof(IEnumerable<>));
var elementType = enumerableInterface.GetGenericArguments()[0];
var genericType = typeof(SpecializedQueueElements<>).MakeGenericType(elementType);
var mi = genericType.GetMethod("ConvertToQueue", BindingFlags.Static | BindingFlags.Public);
var convertToQueue = (ConvertObjectDelegate)Delegate.CreateDelegate(typeof(ConvertObjectDelegate), mi);
var parseFn = DeserializeEnumerable<T, TSerializer>.GetParseFn();
return x => convertToQueue(parseFn(x));
}
public static Stack<string> ParseStringStack(string value)
{
var parse = (IEnumerable<string>)DeserializeList<List<string>, TSerializer>.Parse(value);
return new Stack<string>(parse);
}
public static Stack<int> ParseIntStack(string value)
{
var parse = (IEnumerable<int>)DeserializeList<List<int>, TSerializer>.Parse(value);
return new Stack<int>(parse);
}
internal static ParseStringDelegate GetGenericStackParseFn()
{
var enumerableInterface = typeof(T).GetTypeWithGenericInterfaceOf(typeof(IEnumerable<>));
var elementType = enumerableInterface.GetGenericArguments()[0];
var genericType = typeof(SpecializedQueueElements<>).MakeGenericType(elementType);
var mi = genericType.GetMethod("ConvertToStack", BindingFlags.Static | BindingFlags.Public);
var convertToQueue = (ConvertObjectDelegate)Delegate.CreateDelegate(typeof(ConvertObjectDelegate), mi);
var parseFn = DeserializeEnumerable<T, TSerializer>.GetParseFn();
return x => convertToQueue(parseFn(x));
}
public static ParseStringDelegate GetGenericEnumerableParseFn()
{
var enumerableInterface = typeof(T).GetTypeWithGenericInterfaceOf(typeof(IEnumerable<>));
var elementType = enumerableInterface.GetGenericArguments()[0];
var genericType = typeof(SpecializedEnumerableElements<,>).MakeGenericType(typeof(T), elementType);
var fi = genericType.GetField("ConvertFn", BindingFlags.Static | BindingFlags.Public);
var convertFn = fi.GetValue(null) as ConvertObjectDelegate;
if (convertFn == null) return null;
var parseFn = DeserializeEnumerable<T, TSerializer>.GetParseFn();
return x => convertFn(parseFn(x));
}
}
internal class SpecializedQueueElements<T>
{
public static Queue<T> ConvertToQueue(object enumerable)
{
if (enumerable == null) return null;
return new Queue<T>((IEnumerable<T>)enumerable);
}
public static Stack<T> ConvertToStack(object enumerable)
{
if (enumerable == null) return null;
return new Stack<T>((IEnumerable<T>)enumerable);
}
}
internal class SpecializedEnumerableElements<TCollection, T>
{
public static ConvertObjectDelegate ConvertFn;
static SpecializedEnumerableElements()
{
foreach (var ctorInfo in typeof(TCollection).GetConstructors())
{
var ctorParams = ctorInfo.GetParameters();
if (ctorParams.Length != 1) continue;
var ctorParam = ctorParams[0];
if (typeof(IEnumerable).IsAssignableFrom(ctorParam.ParameterType)
|| ctorParam.ParameterType.IsOrHasGenericInterfaceTypeOf(typeof(IEnumerable<>)))
{
ConvertFn = fromObject => {
var to = Activator.CreateInstance(typeof(TCollection), fromObject);
return to;
};
return;
}
}
if (typeof(TCollection).IsOrHasGenericInterfaceTypeOf(typeof(ICollection<>)))
{
ConvertFn = ConvertFromCollection;
}
}
public static object Convert(object enumerable)
{
return ConvertFn(enumerable);
}
public static object ConvertFromCollection(object enumerable)
{
var to = (ICollection<T>)typeof(TCollection).CreateInstance();
var from = (IEnumerable<T>)enumerable;
foreach (var item in from)
{
to.Add(item);
}
return to;
}
}
}
| |
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
namespace PubNubMessaging.Core
{
#region "Crypto"
/// <summary>
/// MD5 Service provider
/// </summary>
internal class MD5CryptoServiceProvider : MD5
{
public MD5CryptoServiceProvider ()
: base ()
{
}
}
/// <summary>
/// MD5 messaging-digest algorithm is a widely used cryptographic hash function that produces 128-bit hash value.
/// </summary>
internal class MD5 : IDisposable
{
static public MD5 Create (string hashName)
{
if (hashName == "MD5")
return new MD5 ();
else
throw new NotSupportedException ();
}
static public String GetMd5String (String source)
{
MD5 md = MD5CryptoServiceProvider.Create ();
byte[] hash;
//Create a new instance of ASCIIEncoding to
//convert the string into an array of Unicode bytes.
UTF8Encoding enc = new UTF8Encoding ();
//Convert the string into an array of bytes.
byte[] buffer = enc.GetBytes (source);
//Create the hash value from the array of bytes.
hash = md.ComputeHash (buffer);
StringBuilder sb = new StringBuilder ();
foreach (byte b in hash)
sb.Append (b.ToString ("x2"));
return sb.ToString ();
}
static public MD5 Create ()
{
return new MD5 ();
}
#region base implementation of the MD5
#region constants
private const byte S11 = 7;
private const byte S12 = 12;
private const byte S13 = 17;
private const byte S14 = 22;
private const byte S21 = 5;
private const byte S22 = 9;
private const byte S23 = 14;
private const byte S24 = 20;
private const byte S31 = 4;
private const byte S32 = 11;
private const byte S33 = 16;
private const byte S34 = 23;
private const byte S41 = 6;
private const byte S42 = 10;
private const byte S43 = 15;
private const byte S44 = 21;
static private byte[] PADDING = new byte[] {
0x80, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
#endregion
#region F, G, H and I are basic MD5 functions.
static private uint F (uint x, uint y, uint z)
{
return (((x) & (y)) | ((~x) & (z)));
}
static private uint G (uint x, uint y, uint z)
{
return (((x) & (z)) | ((y) & (~z)));
}
static private uint H (uint x, uint y, uint z)
{
return ((x) ^ (y) ^ (z));
}
static private uint I (uint x, uint y, uint z)
{
return ((y) ^ ((x) | (~z)));
}
#endregion
#region rotates x left n bits.
/// <summary>
/// rotates x left n bits.
/// </summary>
/// <param name="x"></param>
/// <param name="n"></param>
/// <returns></returns>
static private uint ROTATE_LEFT (uint x, byte n)
{
return (((x) << (n)) | ((x) >> (32 - (n))));
}
#endregion
#region FF, GG, HH, and II transformations
/// FF, GG, HH, and II transformations
/// for rounds 1, 2, 3, and 4.
/// Rotation is separate from addition to prevent re-computation.
static private void FF (ref uint a, uint b, uint c, uint d, uint x, byte s, uint ac)
{
(a) += F ((b), (c), (d)) + (x) + (uint)(ac);
(a) = ROTATE_LEFT ((a), (s));
(a) += (b);
}
static private void GG (ref uint a, uint b, uint c, uint d, uint x, byte s, uint ac)
{
(a) += G ((b), (c), (d)) + (x) + (uint)(ac);
(a) = ROTATE_LEFT ((a), (s));
(a) += (b);
}
static private void HH (ref uint a, uint b, uint c, uint d, uint x, byte s, uint ac)
{
(a) += H ((b), (c), (d)) + (x) + (uint)(ac);
(a) = ROTATE_LEFT ((a), (s));
(a) += (b);
}
static private void II (ref uint a, uint b, uint c, uint d, uint x, byte s, uint ac)
{
(a) += I ((b), (c), (d)) + (x) + (uint)(ac);
(a) = ROTATE_LEFT ((a), (s));
(a) += (b);
}
#endregion
#region context info
/// <summary>
/// state (ABCD)
/// </summary>
uint[] state = new uint[4];
/// <summary>
/// number of bits, modulo 2^64 (LSB first)
/// </summary>
uint[] count = new uint[2];
/// <summary>
/// input buffer
/// </summary>
byte[] buffer = new byte[64];
#endregion
internal MD5 ()
{
Initialize ();
}
/// <summary>
/// MD5 initialization. Begins an MD5 operation, writing a new context.
/// </summary>
/// <remarks>
/// The RFC named it "MD5Init"
/// </remarks>
public virtual void Initialize ()
{
count [0] = count [1] = 0;
// Load magic initialization constants.
state [0] = 0x67452301;
state [1] = 0xefcdab89;
state [2] = 0x98badcfe;
state [3] = 0x10325476;
}
/// <summary>
/// MD5 block update operation. Continues an MD5 message-digest
/// operation, processing another message block, and updating the
/// context.
/// </summary>
/// <param name="input"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <remarks>The RFC Named it MD5Update</remarks>
protected virtual void HashCore (byte[] input, int offset, int count)
{
int i;
int index;
int partLen;
// Compute number of bytes mod 64
index = (int)((this.count [0] >> 3) & 0x3F);
// Update number of bits
if ((this.count [0] += (uint)((uint)count << 3)) < ((uint)count << 3))
this.count [1]++;
this.count [1] += ((uint)count >> 29);
partLen = 64 - index;
// Transform as many times as possible.
if (count >= partLen) {
Buffer.BlockCopy (input, offset, this.buffer, index, partLen);
Transform (this.buffer, 0);
for (i = partLen; i + 63 < count; i += 64)
Transform (input, offset + i);
index = 0;
} else
i = 0;
// Buffer remaining input
Buffer.BlockCopy (input, offset + i, this.buffer, index, count - i);
}
/// <summary>
/// MD5 finalization. Ends an MD5 message-digest operation, writing the
/// the message digest and zeroizing the context.
/// </summary>
/// <returns>message digest</returns>
/// <remarks>The RFC named it MD5Final</remarks>
protected virtual byte[] HashFinal ()
{
byte[] digest = new byte[16];
byte[] bits = new byte[8];
int index, padLen;
// Save number of bits
Encode (bits, 0, this.count, 0, 8);
// Pad out to 56 mod 64.
index = (int)((uint)(this.count [0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
HashCore (PADDING, 0, padLen);
// Append length (before padding)
HashCore (bits, 0, 8);
// Store state in digest
Encode (digest, 0, state, 0, 16);
// Zeroize sensitive information.
count [0] = count [1] = 0;
state [0] = 0;
state [1] = 0;
state [2] = 0;
state [3] = 0;
// initialize again, to be ready to use
Initialize ();
return digest;
}
/// <summary>
/// MD5 basic transformation. Transforms state based on 64 bytes block.
/// </summary>
/// <param name="block"></param>
/// <param name="offset"></param>
private void Transform (byte[] block, int offset)
{
uint a = state [0], b = state [1], c = state [2], d = state [3];
uint[] x = new uint[16];
Decode (x, 0, block, offset, 64);
// Round 1
FF (ref a, b, c, d, x [0], S11, 0xd76aa478); /* 1 */
FF (ref d, a, b, c, x [1], S12, 0xe8c7b756); /* 2 */
FF (ref c, d, a, b, x [2], S13, 0x242070db); /* 3 */
FF (ref b, c, d, a, x [3], S14, 0xc1bdceee); /* 4 */
FF (ref a, b, c, d, x [4], S11, 0xf57c0faf); /* 5 */
FF (ref d, a, b, c, x [5], S12, 0x4787c62a); /* 6 */
FF (ref c, d, a, b, x [6], S13, 0xa8304613); /* 7 */
FF (ref b, c, d, a, x [7], S14, 0xfd469501); /* 8 */
FF (ref a, b, c, d, x [8], S11, 0x698098d8); /* 9 */
FF (ref d, a, b, c, x [9], S12, 0x8b44f7af); /* 10 */
FF (ref c, d, a, b, x [10], S13, 0xffff5bb1); /* 11 */
FF (ref b, c, d, a, x [11], S14, 0x895cd7be); /* 12 */
FF (ref a, b, c, d, x [12], S11, 0x6b901122); /* 13 */
FF (ref d, a, b, c, x [13], S12, 0xfd987193); /* 14 */
FF (ref c, d, a, b, x [14], S13, 0xa679438e); /* 15 */
FF (ref b, c, d, a, x [15], S14, 0x49b40821); /* 16 */
// Round 2
GG (ref a, b, c, d, x [1], S21, 0xf61e2562); /* 17 */
GG (ref d, a, b, c, x [6], S22, 0xc040b340); /* 18 */
GG (ref c, d, a, b, x [11], S23, 0x265e5a51); /* 19 */
GG (ref b, c, d, a, x [0], S24, 0xe9b6c7aa); /* 20 */
GG (ref a, b, c, d, x [5], S21, 0xd62f105d); /* 21 */
GG (ref d, a, b, c, x [10], S22, 0x2441453); /* 22 */
GG (ref c, d, a, b, x [15], S23, 0xd8a1e681); /* 23 */
GG (ref b, c, d, a, x [4], S24, 0xe7d3fbc8); /* 24 */
GG (ref a, b, c, d, x [9], S21, 0x21e1cde6); /* 25 */
GG (ref d, a, b, c, x [14], S22, 0xc33707d6); /* 26 */
GG (ref c, d, a, b, x [3], S23, 0xf4d50d87); /* 27 */
GG (ref b, c, d, a, x [8], S24, 0x455a14ed); /* 28 */
GG (ref a, b, c, d, x [13], S21, 0xa9e3e905); /* 29 */
GG (ref d, a, b, c, x [2], S22, 0xfcefa3f8); /* 30 */
GG (ref c, d, a, b, x [7], S23, 0x676f02d9); /* 31 */
GG (ref b, c, d, a, x [12], S24, 0x8d2a4c8a); /* 32 */
// Round 3
HH (ref a, b, c, d, x [5], S31, 0xfffa3942); /* 33 */
HH (ref d, a, b, c, x [8], S32, 0x8771f681); /* 34 */
HH (ref c, d, a, b, x [11], S33, 0x6d9d6122); /* 35 */
HH (ref b, c, d, a, x [14], S34, 0xfde5380c); /* 36 */
HH (ref a, b, c, d, x [1], S31, 0xa4beea44); /* 37 */
HH (ref d, a, b, c, x [4], S32, 0x4bdecfa9); /* 38 */
HH (ref c, d, a, b, x [7], S33, 0xf6bb4b60); /* 39 */
HH (ref b, c, d, a, x [10], S34, 0xbebfbc70); /* 40 */
HH (ref a, b, c, d, x [13], S31, 0x289b7ec6); /* 41 */
HH (ref d, a, b, c, x [0], S32, 0xeaa127fa); /* 42 */
HH (ref c, d, a, b, x [3], S33, 0xd4ef3085); /* 43 */
HH (ref b, c, d, a, x [6], S34, 0x4881d05); /* 44 */
HH (ref a, b, c, d, x [9], S31, 0xd9d4d039); /* 45 */
HH (ref d, a, b, c, x [12], S32, 0xe6db99e5); /* 46 */
HH (ref c, d, a, b, x [15], S33, 0x1fa27cf8); /* 47 */
HH (ref b, c, d, a, x [2], S34, 0xc4ac5665); /* 48 */
// Round 4
II (ref a, b, c, d, x [0], S41, 0xf4292244); /* 49 */
II (ref d, a, b, c, x [7], S42, 0x432aff97); /* 50 */
II (ref c, d, a, b, x [14], S43, 0xab9423a7); /* 51 */
II (ref b, c, d, a, x [5], S44, 0xfc93a039); /* 52 */
II (ref a, b, c, d, x [12], S41, 0x655b59c3); /* 53 */
II (ref d, a, b, c, x [3], S42, 0x8f0ccc92); /* 54 */
II (ref c, d, a, b, x [10], S43, 0xffeff47d); /* 55 */
II (ref b, c, d, a, x [1], S44, 0x85845dd1); /* 56 */
II (ref a, b, c, d, x [8], S41, 0x6fa87e4f); /* 57 */
II (ref d, a, b, c, x [15], S42, 0xfe2ce6e0); /* 58 */
II (ref c, d, a, b, x [6], S43, 0xa3014314); /* 59 */
II (ref b, c, d, a, x [13], S44, 0x4e0811a1); /* 60 */
II (ref a, b, c, d, x [4], S41, 0xf7537e82); /* 61 */
II (ref d, a, b, c, x [11], S42, 0xbd3af235); /* 62 */
II (ref c, d, a, b, x [2], S43, 0x2ad7d2bb); /* 63 */
II (ref b, c, d, a, x [9], S44, 0xeb86d391); /* 64 */
state [0] += a;
state [1] += b;
state [2] += c;
state [3] += d;
// Zeroize sensitive information.
for (int i = 0; i < x.Length; i++)
x [i] = 0;
}
/// <summary>
/// Encodes input (uint) into output (byte). Assumes len is
/// multiple of 4.
/// </summary>
/// <param name="output"></param>
/// <param name="outputOffset"></param>
/// <param name="input"></param>
/// <param name="inputOffset"></param>
/// <param name="count"></param>
private static void Encode (byte[] output, int outputOffset, uint[] input, int inputOffset, int count)
{
int i, j;
int end = outputOffset + count;
for (i = inputOffset, j = outputOffset; j < end; i++, j += 4) {
output [j] = (byte)(input [i] & 0xff);
output [j + 1] = (byte)((input [i] >> 8) & 0xff);
output [j + 2] = (byte)((input [i] >> 16) & 0xff);
output [j + 3] = (byte)((input [i] >> 24) & 0xff);
}
}
/// <summary>
/// Decodes input (byte) into output (uint). Assumes len is
/// a multiple of 4.
/// </summary>
/// <param name="output"></param>
/// <param name="outputOffset"></param>
/// <param name="input"></param>
/// <param name="inputOffset"></param>
/// <param name="count"></param>
static private void Decode (uint[] output, int outputOffset, byte[] input, int inputOffset, int count)
{
int i, j;
int end = inputOffset + count;
for (i = outputOffset, j = inputOffset; j < end; i++, j += 4)
output [i] = ((uint)input [j]) | (((uint)input [j + 1]) << 8) | (((uint)input [j + 2]) << 16) | (((uint)input [j + 3]) <<
24);
}
#endregion
#region expose the same interface as the regular MD5 object
protected byte[] HashValue;
protected int State;
public virtual bool CanReuseTransform {
get {
return true;
}
}
public virtual bool CanTransformMultipleBlocks {
get {
return true;
}
}
public virtual byte[] Hash {
get {
if (this.State != 0)
throw new InvalidOperationException ();
return (byte[])HashValue.Clone ();
}
}
public virtual int HashSize {
get {
return HashSizeValue;
}
}
protected int HashSizeValue = 128;
public virtual int InputBlockSize {
get {
return 1;
}
}
public virtual int OutputBlockSize {
get {
return 1;
}
}
public void Clear ()
{
Dispose (true);
}
public byte[] ComputeHash (byte[] buffer)
{
return ComputeHash (buffer, 0, buffer.Length);
}
public byte[] ComputeHash (byte[] buffer, int offset, int count)
{
Initialize ();
HashCore (buffer, offset, count);
HashValue = HashFinal ();
return (byte[])HashValue.Clone ();
}
public byte[] ComputeHash (Stream inputStream)
{
Initialize ();
int count;
byte[] buffer = new byte[4096];
while (0 < (count = inputStream.Read (buffer, 0, 4096))) {
HashCore (buffer, 0, count);
}
HashValue = HashFinal ();
return (byte[])HashValue.Clone ();
}
public int TransformBlock (
byte[] inputBuffer,
int inputOffset,
int inputCount,
byte[] outputBuffer,
int outputOffset
)
{
if (inputBuffer == null) {
throw new ArgumentNullException ("inputBuffer");
}
if (inputOffset < 0) {
throw new ArgumentOutOfRangeException ("inputOffset");
}
if ((inputCount < 0) || (inputCount > inputBuffer.Length)) {
throw new ArgumentException ("inputCount");
}
if ((inputBuffer.Length - inputCount) < inputOffset) {
throw new ArgumentOutOfRangeException ("inputOffset");
}
if (this.State == 0) {
Initialize ();
this.State = 1;
}
HashCore (inputBuffer, inputOffset, inputCount);
if ((inputBuffer != outputBuffer) || (inputOffset != outputOffset)) {
Buffer.BlockCopy (inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
}
return inputCount;
}
public byte[] TransformFinalBlock (
byte[] inputBuffer,
int inputOffset,
int inputCount
)
{
if (inputBuffer == null) {
throw new ArgumentNullException ("inputBuffer");
}
if (inputOffset < 0) {
throw new ArgumentOutOfRangeException ("inputOffset");
}
if ((inputCount < 0) || (inputCount > inputBuffer.Length)) {
throw new ArgumentException ("inputCount");
}
if ((inputBuffer.Length - inputCount) < inputOffset) {
throw new ArgumentOutOfRangeException ("inputOffset");
}
if (this.State == 0) {
Initialize ();
}
HashCore (inputBuffer, inputOffset, inputCount);
HashValue = HashFinal ();
byte[] buffer = new byte[inputCount];
Buffer.BlockCopy (inputBuffer, inputOffset, buffer, 0, inputCount);
this.State = 0;
return buffer;
}
#endregion
protected virtual void Dispose (bool disposing)
{
if (!disposing)
Initialize ();
}
public void Dispose ()
{
Dispose (true);
}
}
public abstract class PubnubCryptoBase
{
private string cipherKey = "";
public PubnubCryptoBase (string cipher_key)
{
this.cipherKey = cipher_key;
}
/// <summary>
/// Computes the hash using the specified algo
/// </summary>
/// <returns>
/// The hash.
/// </returns>
/// <param name='input'>
/// Input string
/// </param>
/// <param name='algorithm'>
/// Algorithm to use for Hashing
/// </param>
//private string ComputeHash(string input, HashAlgorithm algorithm)
protected abstract string ComputeHashRaw (string input);
protected string GetEncryptionKey ()
{
//Compute Hash using the SHA256
string strKeySHA256HashRaw = ComputeHashRaw (this.cipherKey);
//delete the "-" that appear after every 2 chars
string strKeySHA256Hash = (strKeySHA256HashRaw.Replace ("-", "")).Substring (0, 32);
//convert to lower case
return strKeySHA256Hash.ToLower ();
}
/**
* EncryptOrDecrypt
*
* Basic function for encrypt or decrypt a string
* for encrypt type = true
* for decrypt type = false
*/
//private string EncryptOrDecrypt(bool type, string plainStr)
protected abstract string EncryptOrDecrypt (bool type, string plainStr);
// encrypt string
public string Encrypt (string plainText)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException ("plainText");
return EncryptOrDecrypt (true, plainText);
}
// decrypt string
public string Decrypt (string cipherText)
{
if (cipherText == null)
throw new ArgumentNullException ("cipherText");
return EncryptOrDecrypt (false, cipherText);
}
//md5 used for AES encryption key
/*private static byte[] Md5(string cipherKey)
{
MD5 obj = new MD5CryptoServiceProvider();
#if (SILVERLIGHT || WINDOWS_PHONE)
byte[] data = Encoding.UTF8.GetBytes(cipherKey);
#else
byte[] data = Encoding.Default.GetBytes(cipherKey);
#endif
return obj.ComputeHash(data);
}*/
/// <summary>
/// Converts the upper case hex to lower case hex.
/// </summary>
/// <returns>The lower case hex.</returns>
/// <param name="value">Hex Value.</param>
public static string ConvertHexToUnicodeChars (string value)
{
//if(;
return Regex.Replace (
value,
@"\\u(?<Value>[a-zA-Z0-9]{4})",
m => {
return ((char)int.Parse (m.Groups ["Value"].Value, NumberStyles.HexNumber)).ToString ();
}
);
}
/// <summary>
/// Encodes the non ASCII characters.
/// </summary>
/// <returns>
/// The non ASCII characters.
/// </returns>
/// <param name='value'>
/// Value.
/// </param>
protected string EncodeNonAsciiCharacters (string value)
{
#if (USE_JSONFX_UNITY || USE_JSONFX_UNITY_IOS)
value = ConvertHexToUnicodeChars(value);
#endif
StringBuilder sb = new StringBuilder ();
foreach (char c in value) {
if (c > 127) {
// This character is too big for ASCII
string encodedValue = "\\u" + ((int)c).ToString ("x4");
sb.Append (encodedValue);
} else {
sb.Append (c);
}
}
return sb.ToString ();
}
public string PubnubAccessManagerSign (string key, string data)
{
string secret = key;
string message = data;
var encoding = new System.Text.UTF8Encoding ();
byte[] keyByte = encoding.GetBytes (secret);
byte[] messageBytes = encoding.GetBytes (message);
using (var hmacsha256 = new HMACSHA256 (keyByte)) {
byte[] hashmessage = hmacsha256.ComputeHash (messageBytes);
return Convert.ToBase64String (hashmessage).Replace ('+', '-').Replace ('/', '_');
;
}
}
}
#endregion
}
| |
namespace AjTalk.Tests.Compiler
{
using System;
using System.Collections.Generic;
using System.Text;
using AjTalk;
using AjTalk.Compiler;
using AjTalk.Language;
using AjTalk.Tests.Language;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class VmCompilerTests
{
private VmCompiler compiler;
[TestInitialize]
public void Setup()
{
this.compiler = new VmCompiler();
}
[TestMethod]
public void CompileInstanceMethod()
{
Machine machine = new Machine();
IClass cls = machine.CreateClass("Rectangle");
cls.DefineInstanceVariable("x");
var method = this.compiler.CompileInstanceMethod("x ^x", cls);
Assert.IsNotNull(method);
Assert.IsNotNull(method.ByteCodes);
Assert.AreEqual("x ^x", method.SourceCode);
var result = (new BlockDecompiler(method)).Decompile();
Assert.IsNotNull(result);
Assert.AreEqual(2, result.Count);
Assert.AreEqual("GetInstanceVariable x", result[0]);
Assert.AreEqual("ReturnPop", result[1]);
}
[TestMethod]
public void CompileInstanceVariableInBlockInsideAMethod()
{
Machine machine = new Machine();
IClass cls = machine.CreateClass("Rectangle");
cls.DefineInstanceVariable("x");
var method = this.compiler.CompileInstanceMethod("x ^[x] value", cls);
Assert.IsNotNull(method);
Assert.IsNotNull(method.ByteCodes);
Assert.AreEqual("x ^[x] value", method.SourceCode);
Assert.IsTrue(method.NoConstants > 0);
Assert.IsInstanceOfType(method.GetConstant(0), typeof(Block));
var block = (Block)method.GetConstant(0);
var result = (new BlockDecompiler(block)).Decompile();
Assert.IsNotNull(result);
Assert.AreEqual(1, result.Count);
Assert.AreEqual("GetInstanceVariable x", result[0]);
}
[TestMethod]
public void CompileClassMethod()
{
Machine machine = new Machine();
IClass cls = machine.CreateClass("Rectangle");
cls.DefineClassVariable("x");
var method = this.compiler.CompileClassMethod("x ^x", cls);
Assert.IsNotNull(method);
Assert.IsNotNull(method.ByteCodes);
Assert.AreEqual("x ^x", method.SourceCode);
}
[TestMethod]
public void CompileMethodWithLocals()
{
Machine machine = new Machine();
IClass cls = machine.CreateClass("Rectangle");
cls.DefineInstanceVariable("x");
var method = this.compiler.CompileInstanceMethod("x | temp | temp := x. ^temp", cls);
Assert.IsNotNull(method);
Assert.IsNotNull(method.ByteCodes);
}
[TestMethod]
public void CompileSetMethod()
{
Machine machine = new Machine();
IClass cls = machine.CreateClass("Rectangle");
cls.DefineInstanceVariable("x");
var method = this.compiler.CompileInstanceMethod("x: newX x := newX", cls);
Assert.IsNotNull(method);
Assert.IsNotNull(method.ByteCodes);
}
[TestMethod]
public void CompileSimpleCommand()
{
Block block = this.compiler.CompileBlock("nil invokeWith: 10");
Assert.IsNotNull(block);
Assert.AreEqual(2, block.NoConstants);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(6, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileSimpleSendToSelf()
{
Block block = this.compiler.CompileBlock("self invokeWith: 10");
Assert.IsNotNull(block);
Assert.AreEqual(2, block.NoConstants);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(6, block.ByteCodes.Length);
Assert.AreEqual(ByteCode.GetSelf, (ByteCode)block.ByteCodes[0]);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileSimpleSum()
{
Block block = this.compiler.CompileBlock("1 + 2");
Assert.IsNotNull(block);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(7, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileSimpleRealSum()
{
Block block = this.compiler.CompileBlock("1.2 + 3.4");
Assert.IsNotNull(block);
Assert.AreEqual(3, block.NoConstants);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(7, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileSimpleArithmeticWithParenthesis()
{
Block block = this.compiler.CompileBlock("1 * (2 + 3)");
Assert.IsNotNull(block);
Assert.AreEqual(5, block.NoConstants);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(12, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileTwoSimpleCommand()
{
Block block = this.compiler.CompileBlock("a := 1. b := 2");
Assert.IsNotNull(block);
Assert.AreEqual(2, block.NoConstants);
Assert.AreEqual(0, block.NoLocals);
Assert.AreEqual(2, block.NoGlobalNames);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(8, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileSimpleCommandWithParenthesis()
{
Block block = this.compiler.CompileBlock("a := b with: (anObject class)");
Assert.IsNotNull(block);
Assert.AreEqual(1, block.NoConstants);
Assert.AreEqual(3, block.NoGlobalNames);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(10, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileSimpleCommandWithParenthesisAndBang()
{
Block block = this.compiler.CompileBlock("a := b with: (anObject !nativeMethod)");
Assert.IsNotNull(block);
Assert.AreEqual(3, block.NoGlobalNames);
Assert.AreEqual(2, block.NoConstants);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(12, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileSimpleCommandWithParenthesisAndBangKeyword()
{
Block block = this.compiler.CompileBlock("a := b with: (anObject !nativeMethod: 1)");
Assert.IsNotNull(block);
Assert.AreEqual(3, block.NoGlobalNames);
Assert.AreEqual(3, block.NoConstants);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(14, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileAndExecuteTwoSimpleCommand()
{
Block block = this.compiler.CompileBlock("a := 1. b := 2");
Machine machine = new Machine();
block.Execute(machine, null);
Assert.AreEqual(1, machine.GetGlobalObject("a"));
Assert.AreEqual(2, machine.GetGlobalObject("b"));
}
[TestMethod]
public void CompileGlobalVariable()
{
Block block = this.compiler.CompileBlock("AClass");
Assert.IsNotNull(block);
Assert.AreEqual(1, block.NoGlobalNames);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(2, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileSubClassDefinition()
{
Block block = this.compiler.CompileBlock("nil subclass: #Object");
Assert.IsNotNull(block);
Assert.AreEqual(2, block.NoConstants);
Assert.AreEqual(0, block.NoGlobalNames);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(6, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileSubClassDefinitionWithInstances()
{
Block block = this.compiler.CompileBlock("nil subclass: #Object instanceVariables: 'a b c'");
Assert.IsNotNull(block);
Assert.AreEqual(3, block.NoConstants);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(8, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileTwoCommands()
{
Block block = this.compiler.CompileBlock("nil invokeWith: 10. Global := 20");
Assert.IsNotNull(block);
Assert.AreEqual(3, block.NoConstants);
Assert.AreEqual(1, block.NoGlobalNames);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(10, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileTwoCommandsUsingSemicolon()
{
Block block = this.compiler.CompileBlock("nil invokeWith: 10; invokeWith: 20");
Assert.IsNotNull(block);
Assert.AreEqual(3, block.NoConstants);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(12, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
}
[TestMethod]
public void CompileBlockWithSourceCode()
{
string source = "nil invokeWith: 10; invokeWith: 20";
Block block = this.compiler.CompileBlock(source);
Assert.AreEqual(source, block.SourceCode);
}
[TestMethod]
public void CompileBlock()
{
Block block = this.compiler.CompileBlock("nil ifFalse: [self halt]");
Assert.IsNotNull(block);
Assert.AreEqual(1, block.NoConstants);
Assert.AreEqual(0, block.NoLocals);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(11, block.ByteCodes.Length);
Assert.AreEqual(0, block.Arity);
object constant = block.GetConstant(0);
Assert.IsNotNull(constant);
Assert.IsInstanceOfType(constant, typeof(Block));
var newblock = (Block)constant;
Assert.AreEqual(0, newblock.Arity);
Assert.AreEqual(0, newblock.NoLocals);
Assert.IsNotNull(newblock.ByteCodes);
Assert.AreEqual(4, newblock.ByteCodes.Length);
BlockDecompiler decompiler = new BlockDecompiler(block);
var result = decompiler.Decompile();
Assert.IsNotNull(result);
Assert.AreEqual("GetNil", result[0]);
Assert.AreEqual("JumpIfFalse 8", result[1]);
Assert.AreEqual("GetNil", result[2]);
Assert.AreEqual("Jump 11", result[3]);
Assert.AreEqual("GetBlock { GetSelf; Send halt 0 }", result[4]);
}
[TestMethod]
public void CompileBlockWithParameter()
{
Block block = this.compiler.CompileBlock(" :a | a doSomething");
Assert.IsNotNull(block);
Assert.AreEqual(0, block.NoGlobalNames);
Assert.AreEqual(0, block.NoLocals);
Assert.AreEqual(1, block.NoConstants);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(5, block.ByteCodes.Length);
Assert.AreEqual(1, block.Arity);
object constant = block.GetConstant(0);
Assert.IsNotNull(constant);
Assert.IsInstanceOfType(constant, typeof(string));
Assert.AreEqual("doSomething", constant);
}
[TestMethod]
public void CompileBlockWithTwoParameters()
{
Block block = this.compiler.CompileBlock(" :a :b | a+b");
Assert.IsNotNull(block);
Assert.AreEqual(0, block.NoLocals);
Assert.AreEqual(0, block.NoGlobalNames);
Assert.AreEqual(1, block.NoConstants);
Assert.IsNotNull(block.ByteCodes);
Assert.AreEqual(7, block.ByteCodes.Length);
Assert.AreEqual(2, block.Arity);
}
[TestMethod]
public void ExecuteBlock()
{
Machine machine = new Machine();
object nil = machine.UndefinedObjectClass;
Assert.IsNotNull(nil);
Assert.IsInstanceOfType(nil, typeof(IClass));
Block block = this.compiler.CompileBlock("nil ifNil: [GlobalName := 'foo']");
Assert.IsNotNull(block);
block.Execute(machine, null);
Assert.IsNotNull(machine.GetGlobalObject("GlobalName"));
}
[TestMethod]
public void ExecuteTrueIfFalse()
{
Machine machine = new Machine();
Block block = this.compiler.CompileBlock("true ifFalse: [GlobalName := 'foo']");
Assert.IsNotNull(block);
block.Execute(machine, null);
Assert.IsNull(machine.GetGlobalObject("GlobalName"));
}
[TestMethod]
public void ExecuteTrueIfTrueIfFalse()
{
Machine machine = new Machine();
Block block = this.compiler.CompileBlock("true ifTrue: [GlobalName := 'bar'] ifFalse: [GlobalName := 'foo']");
Assert.IsNotNull(block);
block.Execute(machine, null);
Assert.AreEqual("bar", machine.GetGlobalObject("GlobalName"));
}
[TestMethod]
public void ExecuteBasicInstSize()
{
Machine machine = new Machine();
object nil = machine.UndefinedObjectClass;
Assert.IsNotNull(nil);
Assert.IsInstanceOfType(nil, typeof(IClass));
Block block = this.compiler.CompileBlock("^UndefinedObject new basicInstSize");
Assert.IsNotNull(block);
object result = block.Execute(machine, null);
Assert.AreEqual(0, result);
}
[TestMethod]
public void ExecuteBasicInstSizeInRectangle()
{
Machine machine = new Machine();
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
new string[] { "x ^x", "x: newX x := newX", "y ^y", "y: newY y := newY" });
machine.SetGlobalObject("aRectangle", cls.NewObject());
Block block = this.compiler.CompileBlock("^aRectangle basicInstSize");
Assert.IsNotNull(block);
object result = block.Execute(machine, null);
Assert.AreEqual(2, result);
}
[TestMethod]
public void ExecuteBasicInstVarAt()
{
Machine machine = new Machine();
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
new string[] { "x ^x", "x: newX x := newX", "y ^y", "y: newY y := newY" });
IObject iobj = (IObject)cls.NewObject();
machine.SetGlobalObject("aRectangle", iobj);
iobj[0] = 100;
Block block = this.compiler.CompileBlock("^aRectangle basicInstVarAt: 1");
Assert.IsNotNull(block);
object result = block.Execute(machine, null);
Assert.AreEqual(100, result);
}
[TestMethod]
public void ExecuteBasicInstVarAtPut()
{
Machine machine = new Machine();
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
new string[] { "x ^x", "x: newX x := newX", "y ^y", "y: newY y := newY" });
IObject iobj = (IObject)cls.NewObject();
machine.SetGlobalObject("aRectangle", iobj);
Block block = this.compiler.CompileBlock("aRectangle basicInstVarAt: 1 put: 200");
Assert.IsNotNull(block);
block.Execute(machine, null);
Assert.AreEqual(200, iobj[0]);
Assert.IsNull(iobj[1]);
}
[TestMethod]
public void ExecuteNew()
{
Machine machine = new Machine();
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
null);
cls.DefineClassMethod(new BehaviorDoesNotUnderstandMethod(machine, cls));
machine.SetGlobalObject("Rectangle", cls);
Block block = this.compiler.CompileBlock("^Rectangle new");
Assert.IsNotNull(block);
object obj = block.Execute(machine, null);
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IObject));
Assert.AreEqual(cls, ((IObject)obj).Behavior);
}
[TestMethod]
public void ExecuteRedefinedNew()
{
Machine machine = new Machine();
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
new string[] { "initialize x := 10. y := 20" },
new string[] { "new ^self basicNew initialize" });
machine.SetGlobalObject("Rectangle", cls);
Block block = this.compiler.CompileBlock("^Rectangle new");
Assert.IsNotNull(block);
object obj = block.Execute(machine, null);
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IObject));
Assert.AreEqual(cls, ((IObject)obj).Behavior);
IObject iobj = (IObject)obj;
Assert.AreEqual(2, iobj.Behavior.NoInstanceVariables);
Assert.AreEqual(10, iobj[0]);
Assert.AreEqual(20, iobj[1]);
}
[TestMethod]
public void ExecuteBasicNew()
{
Machine machine = new Machine();
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
null);
machine.SetGlobalObject("Rectangle", cls);
Block block = this.compiler.CompileBlock("^Rectangle basicNew");
Assert.IsNotNull(block);
object obj = block.Execute(machine, null);
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IObject));
Assert.AreEqual(cls, ((IObject)obj).Behavior);
}
[TestMethod]
public void CompileMethods()
{
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
new string[] { "x ^x", "x: newX x := newX", "y ^y", "y: newY y := newY" });
Assert.IsNotNull(cls);
Assert.IsNotNull(cls.GetInstanceMethod("x"));
Assert.IsNotNull(cls.GetInstanceMethod("y"));
Assert.IsNotNull(cls.GetInstanceMethod("x:"));
Assert.IsNotNull(cls.GetInstanceMethod("y:"));
}
[TestMethod]
public void RunMethods()
{
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
new string[] { "x ^x", "x: newX x := newX", "y ^y", "y: newY y := newY" });
Assert.IsNotNull(cls);
IObject obj = (IObject)cls.NewObject();
cls.GetInstanceMethod("x:").Execute(null, obj, new object[] { 10 });
Assert.AreEqual(10, obj[0]);
cls.GetInstanceMethod("y:").Execute(null, obj, new object[] { 20 });
Assert.AreEqual(20, obj[1]);
Assert.AreEqual(10, cls.GetInstanceMethod("x").Execute(null, obj, new object[] { }));
Assert.AreEqual(20, cls.GetInstanceMethod("y").Execute(null, obj, new object[] { }));
}
[TestMethod]
public void CompileMultiCommandMethod()
{
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
new string[] { "side: newSide x := newSide. y := newSide" });
Assert.IsNotNull(cls);
Assert.IsNotNull(cls.GetInstanceMethod("side:"));
}
[TestMethod]
public void CompileMultiCommandMethodWithLocal()
{
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
new string[] { "side: newSide | temp | temp := x. x := temp. y := temp" });
Assert.IsNotNull(cls);
Assert.IsNotNull(cls.GetInstanceMethod("side:"));
}
[TestMethod]
public void CompileSameOperator()
{
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
new string[] { "== aRect ^x == aRect x ifTrue: [^y == aRect y] ifFalse: [^false]" });
Assert.IsNotNull(cls);
Assert.IsNotNull(cls.GetInstanceMethod("=="));
}
[TestMethod]
public void CompileAndEvaluateInnerBlockWithClosure()
{
IClass cls = this.CompileClass(
"Adder",
new string[] { },
new string[] { "add: aVector | sum | sum := 0. aVector do: [ :x | sum := sum + x ]. ^sum" });
Assert.IsNotNull(cls);
IMethod method = cls.GetInstanceMethod("add:");
Assert.IsNotNull(method);
IObject obj = (IObject)cls.NewObject();
Assert.AreEqual(6, method.Execute(cls.Machine, obj, new object[] { new int[] { 1, 2, 3 } }));
}
[TestMethod]
public void CompileAndEvaluateInnerBlockWithClosureUsingExternalArgument()
{
IClass cls = this.CompileClass(
"Adder",
new string[] { },
new string[] { "add: aVector with: aNumber | sum | sum := 0. aVector do: [ :x | sum := sum + x + aNumber ]. ^sum" });
Assert.IsNotNull(cls);
IMethod method = cls.GetInstanceMethod("add:with:");
Assert.IsNotNull(method);
IObject obj = (IObject)cls.NewObject();
Assert.AreEqual(9, method.Execute(cls.Machine, obj, new object[] { new int[] { 1, 2, 3 }, 1 }));
}
[TestMethod]
public void RunMultiCommandMethod()
{
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
new string[] { "side: newSide x := newSide. y := newSide" });
Assert.IsNotNull(cls);
IObject obj = (IObject)cls.NewObject();
cls.GetInstanceMethod("side:").Execute(null, obj, new object[] { 10 });
Assert.AreEqual(10, obj[0]);
Assert.AreEqual(10, obj[1]);
}
[TestMethod]
public void RunMultiCommandMethodWithLocal()
{
IClass cls = this.CompileClass(
"Rectangle",
new string[] { "x", "y" },
new string[] { "side: newSide | temp | temp := newSide. x := temp. y := temp" });
Assert.IsNotNull(cls);
IObject obj = (IObject)cls.NewObject();
cls.GetInstanceMethod("side:").Execute(null, obj, new object[] { 10 });
Assert.AreEqual(10, obj[0]);
Assert.AreEqual(10, obj[1]);
}
[TestMethod]
public void CompileSimpleSetExpression()
{
var result = this.compiler.CompileBlock("a := 1");
Assert.IsNotNull(result);
Assert.IsNotNull(result.ByteCodes);
Assert.AreEqual(ByteCode.SetGlobalVariable, (ByteCode)result.ByteCodes[2]);
BlockDecompiler decompiler = new BlockDecompiler(result);
var ops = decompiler.Decompile();
Assert.IsNotNull(ops);
Assert.AreEqual("SetGlobalVariable a", ops[1]);
}
[TestMethod]
public void CompileBlockWithLocalVariable()
{
var result = this.compiler.CompileBlock("|a| a := 1");
Assert.IsNotNull(result);
Assert.IsNotNull(result.ByteCodes);
BlockDecompiler decompiler = new BlockDecompiler(result);
var ops = decompiler.Decompile();
Assert.IsNotNull(ops);
Assert.AreEqual("SetLocal a", ops[1]);
}
[TestMethod]
public void CompileBlockInBrackets()
{
var result = this.compiler.CompileBlock("[a := 1]");
Assert.IsNotNull(result);
Assert.IsNotNull(result.ByteCodes);
BlockDecompiler decompiler = new BlockDecompiler(result);
var ops = decompiler.Decompile();
Assert.IsNotNull(ops);
Assert.AreEqual("GetBlock { GetConstant 1; SetGlobalVariable a }", ops[0]);
}
[TestMethod]
public void CompileIntegerArray()
{
var result = this.compiler.CompileBlock("#(1 2 3)");
Assert.IsNotNull(result);
Assert.IsNotNull(result.ByteCodes);
BlockDecompiler decompiler = new BlockDecompiler(result);
var ops = decompiler.Decompile();
Assert.IsNotNull(ops);
Assert.AreEqual(1, ops.Count);
Assert.AreEqual("GetConstant System.Object[]", ops[0]);
}
[TestMethod]
public void CompileDynamicArray()
{
var result = this.compiler.CompileBlock("{a. b. 3}");
Assert.IsNotNull(result);
Assert.IsNotNull(result.ByteCodes);
BlockDecompiler decompiler = new BlockDecompiler(result);
var ops = decompiler.Decompile();
Assert.IsNotNull(ops);
Assert.AreEqual(4, ops.Count);
Assert.AreEqual("GetGlobalVariable a", ops[0]);
Assert.AreEqual("GetGlobalVariable b", ops[1]);
Assert.AreEqual("GetConstant 3", ops[2]);
Assert.AreEqual("MakeCollection 3", ops[3]);
}
[TestMethod]
public void CompileSimpleExpressionInParenthesis()
{
var block = this.compiler.CompileBlock("(1+2)");
Assert.IsNotNull(block);
Assert.AreEqual(0, block.NoLocals);
Assert.AreEqual(3, block.NoConstants);
Assert.AreEqual(0, block.NoGlobalNames);
BlockDecompiler decompiler = new BlockDecompiler(block);
var result = decompiler.Decompile();
Assert.IsNotNull(result);
Assert.AreEqual(3, result.Count);
Assert.AreEqual("GetConstant 1", result[0]);
Assert.AreEqual("GetConstant 2", result[1]);
Assert.AreEqual("Send + 1", result[2]);
}
[TestMethod]
public void CompileSimpleExpressionInParenthesisUsingYourself()
{
var block = this.compiler.CompileBlock("(1+2;yourself)");
Assert.IsNotNull(block);
Assert.AreEqual(0, block.NoLocals);
Assert.AreEqual(4, block.NoConstants);
Assert.AreEqual(0, block.NoGlobalNames);
BlockDecompiler decompiler = new BlockDecompiler(block);
var result = decompiler.Decompile();
Assert.IsNotNull(result);
Assert.AreEqual(5, result.Count);
Assert.AreEqual("GetConstant 1", result[0]);
Assert.AreEqual("GetConstant 2", result[1]);
Assert.AreEqual("Send + 1", result[2]);
Assert.AreEqual("ChainedSend", result[3]);
Assert.AreEqual("Send yourself 0", result[4]);
}
[TestMethod]
public void CompileGetLocalInBlock()
{
Block block = this.compiler.CompileBlock("| env | [env at: #MyGlobal] value");
Assert.IsNotNull(block);
Assert.IsTrue(block.NoConstants > 0);
var result = block.GetConstant(0);
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(Block));
var decompiler = new BlockDecompiler((Block)result);
var steps = decompiler.Decompile();
Assert.IsTrue(steps.Contains("GetLocal env"));
}
[TestMethod]
public void CompileDottedName()
{
Block block = this.compiler.CompileBlock("Smalltalk.MyPackage.MyClass");
Assert.IsNotNull(block);
Assert.IsTrue(block.NoConstants > 0);
var decompiler = new BlockDecompiler(block);
var steps = decompiler.Decompile();
Assert.IsNotNull(steps);
Assert.AreEqual(5, steps.Count);
Assert.AreEqual("GetGlobalVariable Smalltalk", steps[0]);
Assert.AreEqual("GetConstant \"MyPackage\"", steps[1]);
Assert.AreEqual("Send at: 1", steps[2]);
Assert.AreEqual("GetConstant \"MyClass\"", steps[3]);
Assert.AreEqual("Send at: 1", steps[4]);
}
[TestMethod]
public void CompileBlockWithDot()
{
Block block = this.compiler.CompileBlock("[. 1. 2]");
Assert.IsNotNull(block);
}
[TestMethod]
public void CompileSuperNew()
{
Block block = this.compiler.CompileInstanceMethod("new super new", null);
Assert.IsNotNull(block);
var decompiler = new BlockDecompiler(block);
var steps = decompiler.Decompile();
Assert.IsNotNull(steps);
Assert.AreEqual(2, steps.Count);
Assert.AreEqual("GetSuper", steps[0]);
Assert.AreEqual("Send new 0", steps[1]);
}
[TestMethod]
public void CompileWhileFalse()
{
Block block = this.compiler.CompileBlock(":arg | [arg < 3] whileFalse: [arg := arg + 1]");
Assert.IsNotNull(block);
Assert.AreEqual(13, block.Bytecodes.Length);
var decompiler = new BlockDecompiler(block);
var steps = decompiler.Decompile();
Assert.IsNotNull(steps);
Assert.AreEqual(7, steps.Count);
Assert.AreEqual("GetBlock { GetArgument arg; GetConstant 3; Send < 1 }", steps[0]);
Assert.AreEqual("Value", steps[1]);
Assert.AreEqual("JumpIfTrue 13", steps[2]);
Assert.AreEqual("GetBlock { GetArgument arg; GetConstant 1; Send + 1; SetArgument arg }", steps[3]);
Assert.AreEqual("Value", steps[4]);
Assert.AreEqual("Pop", steps[5]);
Assert.AreEqual("Jump 0", steps[6]);
}
[TestMethod]
public void CompileWhileTrue()
{
Block block = this.compiler.CompileBlock(":arg | [arg < 3] whileTrue: [arg := arg + 1]");
Assert.IsNotNull(block);
Assert.AreEqual(13, block.Bytecodes.Length);
var decompiler = new BlockDecompiler(block);
var steps = decompiler.Decompile();
Assert.IsNotNull(steps);
Assert.AreEqual(7, steps.Count);
Assert.AreEqual("GetBlock { GetArgument arg; GetConstant 3; Send < 1 }", steps[0]);
Assert.AreEqual("Value", steps[1]);
Assert.AreEqual("JumpIfFalse 13", steps[2]);
Assert.AreEqual("GetBlock { GetArgument arg; GetConstant 1; Send + 1; SetArgument arg }", steps[3]);
Assert.AreEqual("Value", steps[4]);
Assert.AreEqual("Pop", steps[5]);
Assert.AreEqual("Jump 0", steps[6]);
}
internal IClass CompileClass(string clsname, string[] varnames, string[] methods)
{
return this.CompileClass(clsname, varnames, methods, null);
}
internal IClass CompileClass(string clsname, string[] varnames, string[] methods, string[] clsmethods)
{
Machine machine = new Machine();
IClass cls = machine.CreateClass(clsname);
if (varnames != null)
{
foreach (string varname in varnames)
{
cls.DefineInstanceVariable(varname);
}
}
if (methods != null)
foreach (string method in methods)
cls.DefineInstanceMethod(this.compiler.CompileInstanceMethod(method, cls));
if (clsmethods != null)
foreach (string method in clsmethods)
cls.DefineClassMethod(this.compiler.CompileClassMethod(method, cls));
return cls;
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
// Code for the toolbox tab of the Gui Editor sidebar.
//---------------------------------------------------------------------------------------------
function GuiEditorToolbox::initialize( %this )
{
// Set up contents.
%viewType = %this.currentViewType;
if( %viewType $= "" )
%viewType = "Categorized";
%this.currentViewType = "";
%this.setViewType( %viewType );
%this.isInitialized = true;
}
//---------------------------------------------------------------------------------------------
function GuiEditorToolbox::getViewType( %this )
{
return %this.currentViewType;
}
//---------------------------------------------------------------------------------------------
function GuiEditorToolbox::setViewType( %this, %viewType )
{
if( %this.currentViewType $= %viewType
|| !%this.isMethod( "setViewType" @ %viewType ) )
return;
%this.clear();
eval( %this @ ".setViewType" @ %viewType @ "();" );
}
//---------------------------------------------------------------------------------------------
function GuiEditorToolbox::setViewTypeAlphabetical( %this )
{
%controls = enumerateConsoleClassesByCategory( "Gui" );
%classes = new ArrayObject();
// Collect relevant classes.
foreach$( %className in %controls )
{
if( GuiEditor.isFilteredClass( %className )
|| !isMemberOfClass( %className, "GuiControl" ) )
continue;
%classes.push_back( %className );
}
// Sort classes alphabetically.
%classes.sortk( true );
// Add toolbox buttons.
%numClasses = %classes.count();
for( %i = 0; %i < %numClasses; %i ++ )
{
%className = %classes.getKey( %i );
%ctrl = new GuiIconButtonCtrl()
{
profile = "GuiIconButtonSmallProfile";
extent = "128 18";
text = %className;
iconBitmap = EditorIconRegistry::findIconByClassName( %className );
buttonMargin = "2 2";
iconLocation = "left";
textLocation = "left";
textMargin = "24";
AutoSize = true;
command = "GuiEditor.createControl( " @ %className @ " );";
useMouseEvents = true;
className = "GuiEditorToolboxButton";
tooltip = %className NL "\n" @ getDescriptionOfClass( %className );
tooltipProfile = "GuiToolTipProfile";
};
%this.add( %ctrl );
}
%classes.delete();
%this.currentViewType = "Alphabetical";
}
//---------------------------------------------------------------------------------------------
function GuiEditorToolbox::setViewTypeCategorized( %this )
{
// Create rollouts for each class category we have and
// record the classes in each category in a temporary array
// on the rollout so we can later sort the class names before
// creating the actual controls in the toolbox.
%controls = enumerateConsoleClassesByCategory( "Gui" );
foreach$( %className in %controls )
{
if( GuiEditor.isFilteredClass( %className )
|| !isMemberOfClass( %className, "GuiControl" ) )
continue;
// Get the class's next category under Gui.
%category = getWord( getCategoryOfClass( %className ), 1 );
if( %category $= "" )
continue;
// Find or create the rollout for the category.
%rollout = %this.getOrCreateRolloutForCategory( %category );
// Insert the item.
if( !%rollout.classes )
%rollout.classes = new ArrayObject();
%rollout.classes.push_back( %className );
}
// Go through the rollouts, sort the class names, and
// create the toolbox controls.
foreach( %rollout in %this )
{
if( !%rollout.isMemberOfClass( "GuiRolloutCtrl" ) )
continue;
// Get the array with the class names and sort it.
// Sort in descending order to counter reversal of order
// when we later add the controls to the stack.
%classes = %rollout.classes;
%classes.sortk( true );
// Add a control for each of the classes to the
// rollout's stack control.
%stack = %rollout-->array;
%numClasses = %classes.count();
for( %n = 0; %n < %numClasses; %n ++ )
{
%className = %classes.getKey( %n );
%ctrl = new GuiIconButtonCtrl()
{
profile = "GuiIconButtonSmallProfile";
extent = "128 18";
text = %className;
iconBitmap = EditorIconRegistry::findIconByClassName( %className );
buttonMargin = "2 2";
iconLocation = "left";
textLocation = "left";
textMargin = "24";
AutoSize = true;
command = "GuiEditor.createControl( " @ %className @ " );";
useMouseEvents = true;
className = "GuiEditorToolboxButton";
tooltip = %className NL "\n" @ getDescriptionOfClass( %className );
tooltipProfile = "GuiToolTipProfile";
};
%stack.add( %ctrl );
}
// Delete the temporary array.
%rollout.classes = "";
%classes.delete();
}
%this.currentViewType = "Categorized";
}
//---------------------------------------------------------------------------------------------
function GuiEditorToolbox::getOrCreateRolloutForCategory( %this, %category )
{
// Try to find an existing rollout.
%ctrl = %this.getRolloutForCategory( %category );
if( %ctrl != 0 )
return %ctrl;
// None there. Create a new one.
%ctrl = new GuiRolloutCtrl() {
Margin = "0 0 0 0";
DefaultHeight = "40";
Expanded = "1";
ClickCollapse = "1";
HideHeader = "0";
isContainer = "1";
Profile = "GuiRolloutProfile";
HorizSizing = "right";
VertSizing = "bottom";
position = "0 0";
Extent = "421 114";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
tooltipprofile = "GuiToolTipProfile";
hovertime = "1000";
canSaveDynamicFields = "0";
autoCollapseSiblings = true;
caption = %category;
class = "GuiEditorToolboxRolloutCtrl";
new GuiDynamicCtrlArrayControl() {
isContainer = "1";
Profile = "GuiDefaultProfile";
HorizSizing = "right";
VertSizing = "bottom";
position = "0 0";
Extent = "421 64";
MinExtent = "64 64";
canSave = "1";
Visible = "1";
tooltipprofile = "GuiToolTipProfile";
hovertime = "1000";
canSaveDynamicFields = "0";
padding = "6 2 4 0";
colSpacing = "1";
rowSpacing = "9";
dynamicSize = true;
autoCellSize = true;
internalName = "array";
};
};
%this.add( %ctrl );
%ctrl.collapse();
// Sort the rollouts by their caption.
%this.sort( "_GuiEditorToolboxSortRollouts" );
return %ctrl;
}
//---------------------------------------------------------------------------------------------
function GuiEditorToolbox::getRolloutForCategory( %this, %category )
{
foreach( %obj in %this )
{
if( !%obj.isMemberOfClass( "GuiRolloutCtrl" ) )
continue;
if( stricmp( %obj.caption, %category ) == 0 )
return %obj;
}
return 0;
}
//---------------------------------------------------------------------------------------------
function GuiEditorToolbox::startGuiControlDrag( %this, %class )
{
// Create a new control of the given class.
%payload = eval( "return new " @ %class @ "();" );
if( !isObject( %payload ) )
return;
// this offset puts the cursor in the middle of the dragged object.
%xOffset = getWord( %payload.extent, 0 ) / 2;
%yOffset = getWord( %payload.extent, 1 ) / 2;
// position where the drag will start, to prevent visible jumping.
%cursorpos = Canvas.getCursorPos();
%xPos = getWord( %cursorpos, 0 ) - %xOffset;
%yPos = getWord( %cursorpos, 1 ) - %yOffset;
// Create drag&drop control.
%dragCtrl = new GuiDragAndDropControl()
{
canSaveDynamicFields = "0";
Profile = "GuiSolidDefaultProfile";
HorizSizing = "right";
VertSizing = "bottom";
Position = %xPos SPC %yPos;
extent = %payload.extent;
MinExtent = "32 32";
canSave = "1";
Visible = "1";
hovertime = "1000";
deleteOnMouseUp = true;
class = "GuiDragAndDropControlType_GuiControl";
};
%dragCtrl.add( %payload );
Canvas.getContent().add( %dragCtrl );
// Start drag.
%dragCtrl.startDragging( %xOffset, %yOffset );
}
//=============================================================================================
// GuiEditorToolboxRolloutCtrl.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function GuiEditorToolboxRolloutCtrl::onHeaderRightClick( %this )
{
if( !isObject( GuiEditorToolboxRolloutCtrlMenu ) )
new PopupMenu( GuiEditorToolboxRolloutCtrlMenu )
{
superClass = "MenuBuilder";
isPopup = true;
item[ 0 ] = "Expand All" TAB "" TAB %this @ ".expandAll();";
item[ 1 ] = "Collapse All" TAB "" TAB %this @ ".collapseAll();";
};
GuiEditorToolboxRolloutCtrlMenu.showPopup( %this.getRoot() );
}
//---------------------------------------------------------------------------------------------
function GuiEditorToolboxRolloutCtrl::expandAll( %this )
{
foreach( %ctrl in %this.parentGroup )
{
if( %ctrl.isMemberOfClass( "GuiRolloutCtrl" ) )
%ctrl.instantExpand();
}
}
//---------------------------------------------------------------------------------------------
function GuiEditorToolboxRolloutCtrl::collapseAll( %this )
{
foreach( %ctrl in %this.parentGroup )
{
if( %ctrl.isMemberOfClass( "GuiRolloutCtrl" ) )
%ctrl.instantCollapse();
}
}
//=============================================================================================
// GuiEditorToolboxButton.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function GuiEditorToolboxButton::onMouseDragged( %this )
{
GuiEditorToolbox.startGuiControlDrag( %this.text );
}
//=============================================================================================
// Misc.
//=============================================================================================
//---------------------------------------------------------------------------------------------
/// Utility function to sort rollouts by their caption.
function _GuiEditorToolboxSortRollouts( %a, %b )
{
return strinatcmp( %a.caption, %b.caption );
}
| |
// Lucene version compatibility level 4.8.1
#if FEATURE_COLLATION
using Icu;
using Icu.Collation;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace Lucene.Net.Collation
{
/*
* 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.
*/
/// <summary>
/// Factory for <see cref="CollationKeyFilter"/>.
/// <para>
/// This factory can be created in two ways:
/// <list type="bullet">
/// <item><description>Based upon a system collator associated with a <see cref="System.Globalization.CultureInfo"/>.</description></item>
/// <item><description>Based upon a tailored ruleset.</description></item>
/// </list>
/// </para>
/// <para>
/// Using a System collator:
/// <list type="bullet">
/// <item><description>language: ISO-639 language code (mandatory)</description></item>
/// <item><description>country: ISO-3166 country code (optional)</description></item>
/// <item><description>variant: vendor or browser-specific code (optional)</description></item>
/// <item><description>strength: 'primary','secondary','tertiary', or 'identical' (optional)</description></item>
/// <item><description>decomposition: 'no','canonical', or 'full' (optional)</description></item>
/// </list>
/// </para>
/// <para>
/// Using a Tailored ruleset:
/// <list type="bullet">
/// <item><description>custom: UTF-8 text file containing rules supported by RuleBasedCollator (mandatory)</description></item>
/// <item><description>strength: 'primary','secondary','tertiary', or 'identical' (optional)</description></item>
/// <item><description>decomposition: 'no','canonical', or 'full' (optional)</description></item>
/// </list>
///
/// <code>
/// <fieldType name="text_clltnky" class="solr.TextField" positionIncrementGap="100">
/// <analyzer>
/// <tokenizer class="solr.KeywordTokenizerFactory"/>
/// <filter class="solr.CollationKeyFilterFactory" language="ja" country="JP"/>
/// </analyzer>
/// </fieldType></code>
///
/// </para>
/// </summary>
/// <seealso cref="Collator"/>
/// <seealso cref="CultureInfo"/>
/// <seealso cref="RuleBasedCollator"/>
/// @since solr 3.1
/// @deprecated use <see cref="CollationKeyAnalyzer"/> instead.
[Obsolete("use <seealso cref=\"CollationKeyAnalyzer\"/> instead.")]
public class CollationKeyFilterFactory : TokenFilterFactory, IMultiTermAwareComponent, IResourceLoaderAware
{
private Collator collator;
private readonly string custom;
private readonly string language;
private readonly string country;
private readonly string variant;
private readonly string strength;
private readonly string decomposition;
public CollationKeyFilterFactory(IDictionary<string, string> args) : base(args)
{
this.custom = this.RemoveFromDictionary(args, "custom");
this.language = this.RemoveFromDictionary(args, "language");
this.country = this.RemoveFromDictionary(args, "country");
this.variant = this.RemoveFromDictionary(args, "variant");
this.strength = this.RemoveFromDictionary(args, "strength");
this.decomposition = this.RemoveFromDictionary(args, "decomposition");
if (this.custom is null && this.language is null)
{
throw new ArgumentException("Either custom or language is required.");
}
if (this.custom != null && (this.language != null || this.country != null || this.variant != null))
{
throw new ArgumentException("Cannot specify both language and custom. " + "To tailor rules for a built-in language, see the javadocs for RuleBasedCollator. " + "Then save the entire customized ruleset to a file, and use with the custom parameter");
}
if (args.Count > 0)
{
throw new ArgumentException(string.Format(J2N.Text.StringFormatter.CurrentCulture, "Unknown parameters: {0}", args));
}
}
public virtual void Inform(IResourceLoader loader)
{
if (this.language != null)
{
// create from a system collator, based on Locale.
this.collator = this.CreateFromLocale(this.language, this.country, this.variant);
}
else
{
// create from a custom ruleset
this.collator = this.CreateFromRules(this.custom, loader);
}
// set the strength flag, otherwise it will be the default.
if (this.strength != null)
{
if (this.strength.Equals("primary", StringComparison.OrdinalIgnoreCase))
{
this.collator.Strength = CollationStrength.Primary;
}
else if (this.strength.Equals("secondary", StringComparison.OrdinalIgnoreCase))
{
this.collator.Strength = CollationStrength.Secondary;
}
else if (this.strength.Equals("tertiary", StringComparison.OrdinalIgnoreCase))
{
this.collator.Strength = CollationStrength.Tertiary;
}
else if (this.strength.Equals("identical", StringComparison.OrdinalIgnoreCase))
{
this.collator.Strength = CollationStrength.Identical;
}
else
{
throw new ArgumentException("Invalid strength: " + this.strength);
}
}
// LUCENENET TODO: Verify Decomposition > NormalizationMode mapping between the JDK and icu-dotnet
// set the decomposition flag, otherwise it will be the default.
if (this.decomposition != null)
{
if (this.decomposition.Equals("no", StringComparison.OrdinalIgnoreCase))
{
this.collator.NormalizationMode = NormalizationMode.Default; // .Decomposition = Collator.NoDecomposition;
}
else if (this.decomposition.Equals("canonical", StringComparison.OrdinalIgnoreCase))
{
this.collator.NormalizationMode = NormalizationMode.Off; //.Decomposition = Collator.CannonicalDecomposition;
}
else if (this.decomposition.Equals("full", StringComparison.OrdinalIgnoreCase))
{
this.collator.NormalizationMode = NormalizationMode.On; //.Decomposition = Collator.FullDecomposition;
}
else
{
throw new ArgumentException("Invalid decomposition: " + this.decomposition);
}
}
}
public override TokenStream Create(TokenStream input)
{
return new CollationKeyFilter(input, this.collator);
}
/// <summary>
/// Create a locale from language, with optional country and variant.
/// Then return the appropriate collator for the locale.
/// </summary>
private Collator CreateFromLocale(string language, string country, string variant)
{
CultureInfo cultureInfo;
if (language is null)
{
throw new ArgumentException("Language is required");
}
if (language != null && country is null && variant != null)
{
throw new ArgumentException("To specify variant, country is required");
}
if (country != null && variant != null)
{
cultureInfo = new CultureInfo(string.Concat(language, "-", country, "-", variant));
// LUCENENET TODO: This method won't work on .NET core - confirm the above solution works as expected.
//cultureInfo = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Single(x =>
//{
// if (!x.TwoLetterISOLanguageName.Equals(language, StringComparison.OrdinalIgnoreCase) &&
// !x.ThreeLetterISOLanguageName.Equals(language, StringComparison.OrdinalIgnoreCase) &&
// !x.ThreeLetterWindowsLanguageName.Equals(language, StringComparison.OrdinalIgnoreCase))
// {
// return false;
// }
// var region = new RegionInfo(x.Name);
// if (!region.TwoLetterISORegionName.Equals(country, StringComparison.OrdinalIgnoreCase) &&
// !region.ThreeLetterISORegionName.Equals(country, StringComparison.OrdinalIgnoreCase) &&
// !region.ThreeLetterWindowsRegionName.Equals(country, StringComparison.OrdinalIgnoreCase)
// )
// {
// return false;
// }
// return x.Name
// .Replace(x.TwoLetterISOLanguageName, string.Empty)
// .Replace(region.TwoLetterISORegionName, string.Empty)
// .Replace("-", string.Empty)
// .Equals(variant, StringComparison.OrdinalIgnoreCase);
//});
}
else if (country != null)
{
cultureInfo = new CultureInfo(string.Concat(language, "-", country));
}
else
{
cultureInfo = new CultureInfo(language);
}
return Collator.Create(cultureInfo);
}
/// <summary>
/// Read custom rules from a file, and create a RuleBasedCollator
/// The file cannot support comments, as # might be in the rules!
/// </summary>
private Collator CreateFromRules(string fileName, IResourceLoader loader)
{
Stream input = null;
try
{
input = loader.OpenResource(fileName);
var rules = ToUTF8String(input);
return new RuleBasedCollator(rules);
}
catch (TransliteratorParseException e)
{
// invalid rules
throw new IOException("ParseException thrown while parsing rules", e);
}
catch (SyntaxErrorException e)
{
// invalid rules
throw new IOException("ParseException thrown while parsing rules", e);
}
finally
{
IOUtils.CloseWhileHandlingException(input);
}
}
public virtual AbstractAnalysisFactory GetMultiTermComponent()
{
return this;
}
private static string ToUTF8String(Stream @in)
{
var builder = new StringBuilder();
var buffer = new char[1024];
var reader = IOUtils.GetDecodingReader(@in, Encoding.UTF8);
var index = 0;
while ((index = reader.Read(buffer, index, 1)) > 0)
{
builder.Append(buffer, 0, index);
}
return builder.ToString();
}
/// <summary>
/// Trys to gets the value of a key from a dictionary and removes the value after.
/// This is to mimic java's Dictionary.Remove method.
/// </summary>
/// <returns>The value for the given key; otherwise null.</returns>
private string RemoveFromDictionary(IDictionary<string, string> args, string key)
{
string value = null;
if (args.TryGetValue(key, out value))
{
args.Remove(key);
}
return value;
}
}
}
#endif
| |
#region Apache License
//
// 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.
//
#endregion
using System;
using System.Configuration;
using System.Reflection;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;
namespace log4net.Util
{
/// <summary>
/// Utility class for system specific information.
/// </summary>
/// <remarks>
/// <para>
/// Utility class of static methods for system specific information.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Alexey Solofnenko</author>
public sealed class SystemInfo
{
#region Private Constants
private const string DEFAULT_NULL_TEXT = "(null)";
private const string DEFAULT_NOT_AVAILABLE_TEXT = "NOT AVAILABLE";
#endregion
#region Private Instance Constructors
/// <summary>
/// Private constructor to prevent instances.
/// </summary>
/// <remarks>
/// <para>
/// Only static methods are exposed from this type.
/// </para>
/// </remarks>
private SystemInfo()
{
}
#endregion Private Instance Constructors
#region Public Static Constructor
/// <summary>
/// Initialize default values for private static fields.
/// </summary>
/// <remarks>
/// <para>
/// Only static methods are exposed from this type.
/// </para>
/// </remarks>
static SystemInfo()
{
string nullText = DEFAULT_NULL_TEXT;
string notAvailableText = DEFAULT_NOT_AVAILABLE_TEXT;
#if !NETCF
// Look for log4net.NullText in AppSettings
string nullTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NullText");
if (nullTextAppSettingsKey != null && nullTextAppSettingsKey.Length > 0)
{
LogLog.Debug(declaringType, "Initializing NullText value to [" + nullTextAppSettingsKey + "].");
nullText = nullTextAppSettingsKey;
}
// Look for log4net.NotAvailableText in AppSettings
string notAvailableTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NotAvailableText");
if (notAvailableTextAppSettingsKey != null && notAvailableTextAppSettingsKey.Length > 0)
{
LogLog.Debug(declaringType, "Initializing NotAvailableText value to [" + notAvailableTextAppSettingsKey + "].");
notAvailableText = notAvailableTextAppSettingsKey;
}
#endif
s_notAvailableText = notAvailableText;
s_nullText = nullText;
}
#endregion
#region Public Static Properties
/// <summary>
/// Gets the system dependent line terminator.
/// </summary>
/// <value>
/// The system dependent line terminator.
/// </value>
/// <remarks>
/// <para>
/// Gets the system dependent line terminator.
/// </para>
/// </remarks>
public static string NewLine
{
get
{
#if NETCF
return "\r\n";
#else
return System.Environment.NewLine;
#endif
}
}
/// <summary>
/// Gets the base directory for this <see cref="AppDomain"/>.
/// </summary>
/// <value>The base directory path for the current <see cref="AppDomain"/>.</value>
/// <remarks>
/// <para>
/// Gets the base directory for this <see cref="AppDomain"/>.
/// </para>
/// <para>
/// The value returned may be either a local file path or a URI.
/// </para>
/// </remarks>
public static string ApplicationBaseDirectory
{
get
{
#if NETCF
return System.IO.Path.GetDirectoryName(SystemInfo.EntryAssemblyLocation) + System.IO.Path.DirectorySeparatorChar;
#else
return AppDomain.CurrentDomain.BaseDirectory;
#endif
}
}
/// <summary>
/// Gets the path to the configuration file for the current <see cref="AppDomain"/>.
/// </summary>
/// <value>The path to the configuration file for the current <see cref="AppDomain"/>.</value>
/// <remarks>
/// <para>
/// The .NET Compact Framework 1.0 does not have a concept of a configuration
/// file. For this runtime, we use the entry assembly location as the root for
/// the configuration file name.
/// </para>
/// <para>
/// The value returned may be either a local file path or a URI.
/// </para>
/// </remarks>
public static string ConfigurationFileLocation
{
get
{
#if NETCF
return SystemInfo.EntryAssemblyLocation+".config";
#else
return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
#endif
}
}
/// <summary>
/// Gets the path to the file that first executed in the current <see cref="AppDomain"/>.
/// </summary>
/// <value>The path to the entry assembly.</value>
/// <remarks>
/// <para>
/// Gets the path to the file that first executed in the current <see cref="AppDomain"/>.
/// </para>
/// </remarks>
public static string EntryAssemblyLocation
{
get
{
#if NETCF
return SystemInfo.NativeEntryAssemblyLocation;
#else
return System.Reflection.Assembly.GetEntryAssembly().Location;
#endif
}
}
/// <summary>
/// Gets the ID of the current thread.
/// </summary>
/// <value>The ID of the current thread.</value>
/// <remarks>
/// <para>
/// On the .NET framework, the <c>AppDomain.GetCurrentThreadId</c> method
/// is used to obtain the thread ID for the current thread. This is the
/// operating system ID for the thread.
/// </para>
/// <para>
/// On the .NET Compact Framework 1.0 it is not possible to get the
/// operating system thread ID for the current thread. The native method
/// <c>GetCurrentThreadId</c> is implemented inline in a header file
/// and cannot be called.
/// </para>
/// <para>
/// On the .NET Framework 2.0 the <c>Thread.ManagedThreadId</c> is used as this
/// gives a stable id unrelated to the operating system thread ID which may
/// change if the runtime is using fibers.
/// </para>
/// </remarks>
public static int CurrentThreadId
{
get
{
#if NETCF_1_0
return System.Threading.Thread.CurrentThread.GetHashCode();
#elif NET_2_0 || NETCF_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0
return System.Threading.Thread.CurrentThread.ManagedThreadId;
#else
return AppDomain.GetCurrentThreadId();
#endif
}
}
/// <summary>
/// Get the host name or machine name for the current machine
/// </summary>
/// <value>
/// The hostname or machine name
/// </value>
/// <remarks>
/// <para>
/// Get the host name or machine name for the current machine
/// </para>
/// <para>
/// The host name (<see cref="System.Net.Dns.GetHostName"/>) or
/// the machine name (<c>Environment.MachineName</c>) for
/// the current machine, or if neither of these are available
/// then <c>NOT AVAILABLE</c> is returned.
/// </para>
/// </remarks>
public static string HostName
{
get
{
if (s_hostName == null)
{
// Get the DNS host name of the current machine
try
{
// Lookup the host name
s_hostName = System.Net.Dns.GetHostName();
}
catch (System.Net.Sockets.SocketException)
{
LogLog.Debug(declaringType, "Socket exception occurred while getting the dns hostname. Error Ignored.");
}
catch (System.Security.SecurityException)
{
// We may get a security exception looking up the hostname
// You must have Unrestricted DnsPermission to access resource
LogLog.Debug(declaringType, "Security exception occurred while getting the dns hostname. Error Ignored.");
}
catch (Exception ex)
{
LogLog.Debug(declaringType, "Some other exception occurred while getting the dns hostname. Error Ignored.", ex);
}
// Get the NETBIOS machine name of the current machine
if (s_hostName == null || s_hostName.Length == 0)
{
try
{
#if (!SSCLI && !NETCF)
s_hostName = Environment.MachineName;
#endif
}
catch(InvalidOperationException)
{
}
catch(System.Security.SecurityException)
{
// We may get a security exception looking up the machine name
// You must have Unrestricted EnvironmentPermission to access resource
}
}
// Couldn't find a value
if (s_hostName == null || s_hostName.Length == 0)
{
s_hostName = s_notAvailableText;
LogLog.Debug(declaringType, "Could not determine the hostname. Error Ignored. Empty host name will be used");
}
}
return s_hostName;
}
}
/// <summary>
/// Get this application's friendly name
/// </summary>
/// <value>
/// The friendly name of this application as a string
/// </value>
/// <remarks>
/// <para>
/// If available the name of the application is retrieved from
/// the <c>AppDomain</c> using <c>AppDomain.CurrentDomain.FriendlyName</c>.
/// </para>
/// <para>
/// Otherwise the file name of the entry assembly is used.
/// </para>
/// </remarks>
public static string ApplicationFriendlyName
{
get
{
if (s_appFriendlyName == null)
{
try
{
#if !NETCF
s_appFriendlyName = AppDomain.CurrentDomain.FriendlyName;
#endif
}
catch(System.Security.SecurityException)
{
// This security exception will occur if the caller does not have
// some undefined set of SecurityPermission flags.
LogLog.Debug(declaringType, "Security exception while trying to get current domain friendly name. Error Ignored.");
}
if (s_appFriendlyName == null || s_appFriendlyName.Length == 0)
{
try
{
string assemblyLocation = SystemInfo.EntryAssemblyLocation;
s_appFriendlyName = System.IO.Path.GetFileName(assemblyLocation);
}
catch(System.Security.SecurityException)
{
// Caller needs path discovery permission
}
}
if (s_appFriendlyName == null || s_appFriendlyName.Length == 0)
{
s_appFriendlyName = s_notAvailableText;
}
}
return s_appFriendlyName;
}
}
/// <summary>
/// Get the start time for the current process.
/// </summary>
/// <remarks>
/// <para>
/// This is the time at which the log4net library was loaded into the
/// AppDomain. Due to reports of a hang in the call to <c>System.Diagnostics.Process.StartTime</c>
/// this is not the start time for the current process.
/// </para>
/// <para>
/// The log4net library should be loaded by an application early during its
/// startup, therefore this start time should be a good approximation for
/// the actual start time.
/// </para>
/// <para>
/// Note that AppDomains may be loaded and unloaded within the
/// same process without the process terminating, however this start time
/// will be set per AppDomain.
/// </para>
/// </remarks>
public static DateTime ProcessStartTime
{
get { return s_processStartTime; }
}
/// <summary>
/// Text to output when a <c>null</c> is encountered.
/// </summary>
/// <remarks>
/// <para>
/// Use this value to indicate a <c>null</c> has been encountered while
/// outputting a string representation of an item.
/// </para>
/// <para>
/// The default value is <c>(null)</c>. This value can be overridden by specifying
/// a value for the <c>log4net.NullText</c> appSetting in the application's
/// .config file.
/// </para>
/// </remarks>
public static string NullText
{
get { return s_nullText; }
set { s_nullText = value; }
}
/// <summary>
/// Text to output when an unsupported feature is requested.
/// </summary>
/// <remarks>
/// <para>
/// Use this value when an unsupported feature is requested.
/// </para>
/// <para>
/// The default value is <c>NOT AVAILABLE</c>. This value can be overridden by specifying
/// a value for the <c>log4net.NotAvailableText</c> appSetting in the application's
/// .config file.
/// </para>
/// </remarks>
public static string NotAvailableText
{
get { return s_notAvailableText; }
set { s_notAvailableText = value; }
}
#endregion Public Static Properties
#region Public Static Methods
/// <summary>
/// Gets the assembly location path for the specified assembly.
/// </summary>
/// <param name="myAssembly">The assembly to get the location for.</param>
/// <returns>The location of the assembly.</returns>
/// <remarks>
/// <para>
/// This method does not guarantee to return the correct path
/// to the assembly. If only tries to give an indication as to
/// where the assembly was loaded from.
/// </para>
/// </remarks>
public static string AssemblyLocationInfo(Assembly myAssembly)
{
#if NETCF
return "Not supported on Microsoft .NET Compact Framework";
#else
if (myAssembly.GlobalAssemblyCache)
{
return "Global Assembly Cache";
}
else
{
try
{
#if NET_4_0 || MONO_4_0
if (myAssembly.IsDynamic)
{
return "Dynamic Assembly";
}
#else
if (myAssembly is System.Reflection.Emit.AssemblyBuilder)
{
return "Dynamic Assembly";
}
else if(myAssembly.GetType().FullName == "System.Reflection.Emit.InternalAssemblyBuilder")
{
return "Dynamic Assembly";
}
#endif
else
{
// This call requires FileIOPermission for access to the path
// if we don't have permission then we just ignore it and
// carry on.
return myAssembly.Location;
}
}
catch (NotSupportedException)
{
// The location information may be unavailable for dynamic assemblies and a NotSupportedException
// is thrown in those cases. See: http://msdn.microsoft.com/de-de/library/system.reflection.assembly.location.aspx
return "Dynamic Assembly";
}
catch (TargetInvocationException ex)
{
return "Location Detect Failed (" + ex.Message + ")";
}
catch (ArgumentException ex)
{
return "Location Detect Failed (" + ex.Message + ")";
}
catch (System.Security.SecurityException)
{
return "Location Permission Denied";
}
}
#endif
}
/// <summary>
/// Gets the fully qualified name of the <see cref="Type" />, including
/// the name of the assembly from which the <see cref="Type" /> was
/// loaded.
/// </summary>
/// <param name="type">The <see cref="Type" /> to get the fully qualified name for.</param>
/// <returns>The fully qualified name for the <see cref="Type" />.</returns>
/// <remarks>
/// <para>
/// This is equivalent to the <c>Type.AssemblyQualifiedName</c> property,
/// but this method works on the .NET Compact Framework 1.0 as well as
/// the full .NET runtime.
/// </para>
/// </remarks>
public static string AssemblyQualifiedName(Type type)
{
return type.FullName + ", " + type.Assembly.FullName;
}
/// <summary>
/// Gets the short name of the <see cref="Assembly" />.
/// </summary>
/// <param name="myAssembly">The <see cref="Assembly" /> to get the name for.</param>
/// <returns>The short name of the <see cref="Assembly" />.</returns>
/// <remarks>
/// <para>
/// The short name of the assembly is the <see cref="Assembly.FullName" />
/// without the version, culture, or public key. i.e. it is just the
/// assembly's file name without the extension.
/// </para>
/// <para>
/// Use this rather than <c>Assembly.GetName().Name</c> because that
/// is not available on the Compact Framework.
/// </para>
/// <para>
/// Because of a FileIOPermission security demand we cannot do
/// the obvious Assembly.GetName().Name. We are allowed to get
/// the <see cref="Assembly.FullName" /> of the assembly so we
/// start from there and strip out just the assembly name.
/// </para>
/// </remarks>
public static string AssemblyShortName(Assembly myAssembly)
{
string name = myAssembly.FullName;
int offset = name.IndexOf(',');
if (offset > 0)
{
name = name.Substring(0, offset);
}
return name.Trim();
// TODO: Do we need to unescape the assembly name string?
// Doc says '\' is an escape char but has this already been
// done by the string loader?
}
/// <summary>
/// Gets the file name portion of the <see cref="Assembly" />, including the extension.
/// </summary>
/// <param name="myAssembly">The <see cref="Assembly" /> to get the file name for.</param>
/// <returns>The file name of the assembly.</returns>
/// <remarks>
/// <para>
/// Gets the file name portion of the <see cref="Assembly" />, including the extension.
/// </para>
/// </remarks>
public static string AssemblyFileName(Assembly myAssembly)
{
#if NETCF
// This is not very good because it assumes that only
// the entry assembly can be an EXE. In fact multiple
// EXEs can be loaded in to a process.
string assemblyShortName = SystemInfo.AssemblyShortName(myAssembly);
string entryAssemblyShortName = System.IO.Path.GetFileNameWithoutExtension(SystemInfo.EntryAssemblyLocation);
if (string.Compare(assemblyShortName, entryAssemblyShortName, true) == 0)
{
// assembly is entry assembly
return assemblyShortName + ".exe";
}
else
{
// assembly is not entry assembly
return assemblyShortName + ".dll";
}
#else
return System.IO.Path.GetFileName(myAssembly.Location);
#endif
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeType">A sibling type to use to load the type.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified, it will be loaded from the assembly
/// containing the specified relative type. If the type is not found in the assembly
/// then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase);
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the
/// assembly that is directly calling this method. If the type is not found
/// in the assembly then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase);
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeAssembly">An assembly to load the type from.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the specified
/// assembly. If the type is not found in the assembly then all the loaded assemblies
/// will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase)
{
// Check if the type name specifies the assembly name
if(typeName.IndexOf(',') == -1)
{
//LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
#if NETCF
return relativeAssembly.GetType(typeName, throwOnError);
#else
// Attempt to lookup the type from the relativeAssembly
Type type = relativeAssembly.GetType(typeName, false, ignoreCase);
if (type != null)
{
// Found type in relative assembly
//LogLog.Debug(declaringType, "SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
return type;
}
Assembly[] loadedAssemblies = null;
try
{
loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
}
catch(System.Security.SecurityException)
{
// Insufficient permissions to get the list of loaded assemblies
}
if (loadedAssemblies != null)
{
Type fallback = null;
// Search the loaded assemblies for the type
foreach (Assembly assembly in loadedAssemblies)
{
Type t = assembly.GetType(typeName, false, ignoreCase);
if (t != null)
{
// Found type in loaded assembly
LogLog.Debug(declaringType, "Loaded type ["+typeName+"] from assembly ["+assembly.FullName+"] by searching loaded assemblies.");
if (assembly.GlobalAssemblyCache)
{
fallback = t;
}
else
{
return t;
}
}
}
if (fallback != null)
{
return fallback;
}
}
// Didn't find the type
if (throwOnError)
{
throw new TypeLoadException("Could not load type ["+typeName+"]. Tried assembly ["+relativeAssembly.FullName+"] and all loaded assemblies");
}
return null;
#endif
}
else
{
// Includes explicit assembly name
//LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from global Type");
#if NETCF
// In NETCF 2 and 3 arg versions seem to behave differently
// https://issues.apache.org/jira/browse/LOG4NET-113
return Type.GetType(typeName, throwOnError);
#else
return Type.GetType(typeName, throwOnError, ignoreCase);
#endif
}
}
/// <summary>
/// Generate a new guid
/// </summary>
/// <returns>A new Guid</returns>
/// <remarks>
/// <para>
/// Generate a new guid
/// </para>
/// </remarks>
public static Guid NewGuid()
{
#if NETCF_1_0
return PocketGuid.NewGuid();
#else
return Guid.NewGuid();
#endif
}
/// <summary>
/// Create an <see cref="ArgumentOutOfRangeException"/>
/// </summary>
/// <param name="parameterName">The name of the parameter that caused the exception</param>
/// <param name="actualValue">The value of the argument that causes this exception</param>
/// <param name="message">The message that describes the error</param>
/// <returns>the ArgumentOutOfRangeException object</returns>
/// <remarks>
/// <para>
/// Create a new instance of the <see cref="ArgumentOutOfRangeException"/> class
/// with a specified error message, the parameter name, and the value
/// of the argument.
/// </para>
/// <para>
/// The Compact Framework does not support the 3 parameter constructor for the
/// <see cref="ArgumentOutOfRangeException"/> type. This method provides an
/// implementation that works for all platforms.
/// </para>
/// </remarks>
public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message)
{
#if NETCF_1_0
return new ArgumentOutOfRangeException(message + " [param=" + parameterName + "] [value=" + actualValue + "]");
#elif NETCF_2_0
return new ArgumentOutOfRangeException(parameterName, message + " [value=" + actualValue + "]");
#else
return new ArgumentOutOfRangeException(parameterName, actualValue, message);
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int32"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out int val)
{
#if NETCF
val = 0;
try
{
val = int.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt32(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int64"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out long val)
{
#if NETCF
val = 0;
try
{
val = long.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt64(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int16"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out short val)
{
#if NETCF
val = 0;
try
{
val = short.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt16(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Lookup an application setting
/// </summary>
/// <param name="key">the application settings key to lookup</param>
/// <returns>the value for the key, or <c>null</c></returns>
/// <remarks>
/// <para>
/// Configuration APIs are not supported under the Compact Framework
/// </para>
/// </remarks>
public static string GetAppSetting(string key)
{
try
{
#if NETCF
// Configuration APIs are not suported under the Compact Framework
#elif NET_2_0
return ConfigurationManager.AppSettings[key];
#else
return ConfigurationSettings.AppSettings[key];
#endif
}
catch(Exception ex)
{
// If an exception is thrown here then it looks like the config file does not parse correctly.
LogLog.Error(declaringType, "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex);
}
return null;
}
/// <summary>
/// Convert a path into a fully qualified local file path.
/// </summary>
/// <param name="path">The path to convert.</param>
/// <returns>The fully qualified path.</returns>
/// <remarks>
/// <para>
/// Converts the path specified to a fully
/// qualified path. If the path is relative it is
/// taken as relative from the application base
/// directory.
/// </para>
/// <para>
/// The path specified must be a local file path, a URI is not supported.
/// </para>
/// </remarks>
public static string ConvertToFullPath(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
string baseDirectory = "";
try
{
string applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
if (applicationBaseDirectory != null)
{
// applicationBaseDirectory may be a URI not a local file path
Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory);
if (applicationBaseDirectoryUri.IsFile)
{
baseDirectory = applicationBaseDirectoryUri.LocalPath;
}
}
}
catch
{
// Ignore URI exceptions & SecurityExceptions from SystemInfo.ApplicationBaseDirectory
}
if (baseDirectory != null && baseDirectory.Length > 0)
{
// Note that Path.Combine will return the second path if it is rooted
return Path.GetFullPath(Path.Combine(baseDirectory, path));
}
return Path.GetFullPath(path);
}
/// <summary>
/// Creates a new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity.
/// </summary>
/// <returns>A new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity</returns>
/// <remarks>
/// <para>
/// The new Hashtable instance uses the default load factor, the CaseInsensitiveHashCodeProvider, and the CaseInsensitiveComparer.
/// </para>
/// </remarks>
public static Hashtable CreateCaseInsensitiveHashtable()
{
#if NETCF_1_0
return new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default);
#elif NETCF_2_0 || NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0
return new Hashtable(StringComparer.OrdinalIgnoreCase);
#else
return System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable();
#endif
}
#endregion Public Static Methods
#region Private Static Methods
#if NETCF
private static string NativeEntryAssemblyLocation
{
get
{
StringBuilder moduleName = null;
IntPtr moduleHandle = GetModuleHandle(IntPtr.Zero);
if (moduleHandle != IntPtr.Zero)
{
moduleName = new StringBuilder(255);
if (GetModuleFileName(moduleHandle, moduleName, moduleName.Capacity) == 0)
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
}
else
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
return moduleName.ToString();
}
}
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern IntPtr GetModuleHandle(IntPtr ModuleName);
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern Int32 GetModuleFileName(
IntPtr hModule,
StringBuilder ModuleName,
Int32 cch);
#endif
#endregion Private Static Methods
#region Public Static Fields
/// <summary>
/// Gets an empty array of types.
/// </summary>
/// <remarks>
/// <para>
/// The <c>Type.EmptyTypes</c> field is not available on
/// the .NET Compact Framework 1.0.
/// </para>
/// </remarks>
public static readonly Type[] EmptyTypes = new Type[0];
#endregion Public Static Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the SystemInfo class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(SystemInfo);
/// <summary>
/// Cache the host name for the current machine
/// </summary>
private static string s_hostName;
/// <summary>
/// Cache the application friendly name
/// </summary>
private static string s_appFriendlyName;
/// <summary>
/// Text to output when a <c>null</c> is encountered.
/// </summary>
private static string s_nullText;
/// <summary>
/// Text to output when an unsupported feature is requested.
/// </summary>
private static string s_notAvailableText;
/// <summary>
/// Start time for the current process.
/// </summary>
private static DateTime s_processStartTime = DateTime.Now;
#endregion
#region Compact Framework Helper Classes
#if NETCF_1_0
/// <summary>
/// Generate GUIDs on the .NET Compact Framework.
/// </summary>
public class PocketGuid
{
// guid variant types
private enum GuidVariant
{
ReservedNCS = 0x00,
Standard = 0x02,
ReservedMicrosoft = 0x06,
ReservedFuture = 0x07
}
// guid version types
private enum GuidVersion
{
TimeBased = 0x01,
Reserved = 0x02,
NameBased = 0x03,
Random = 0x04
}
// constants that are used in the class
private class Const
{
// number of bytes in guid
public const int ByteArraySize = 16;
// multiplex variant info
public const int VariantByte = 8;
public const int VariantByteMask = 0x3f;
public const int VariantByteShift = 6;
// multiplex version info
public const int VersionByte = 7;
public const int VersionByteMask = 0x0f;
public const int VersionByteShift = 4;
}
// imports for the crypto api functions
private class WinApi
{
public const uint PROV_RSA_FULL = 1;
public const uint CRYPT_VERIFYCONTEXT = 0xf0000000;
[DllImport("CoreDll.dll")]
public static extern bool CryptAcquireContext(
ref IntPtr phProv, string pszContainer, string pszProvider,
uint dwProvType, uint dwFlags);
[DllImport("CoreDll.dll")]
public static extern bool CryptReleaseContext(
IntPtr hProv, uint dwFlags);
[DllImport("CoreDll.dll")]
public static extern bool CryptGenRandom(
IntPtr hProv, int dwLen, byte[] pbBuffer);
}
// all static methods
private PocketGuid()
{
}
/// <summary>
/// Return a new System.Guid object.
/// </summary>
public static Guid NewGuid()
{
IntPtr hCryptProv = IntPtr.Zero;
Guid guid = Guid.Empty;
try
{
// holds random bits for guid
byte[] bits = new byte[Const.ByteArraySize];
// get crypto provider handle
if (!WinApi.CryptAcquireContext(ref hCryptProv, null, null,
WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT))
{
throw new SystemException(
"Failed to acquire cryptography handle.");
}
// generate a 128 bit (16 byte) cryptographically random number
if (!WinApi.CryptGenRandom(hCryptProv, bits.Length, bits))
{
throw new SystemException(
"Failed to generate cryptography random bytes.");
}
// set the variant
bits[Const.VariantByte] &= Const.VariantByteMask;
bits[Const.VariantByte] |=
((int)GuidVariant.Standard << Const.VariantByteShift);
// set the version
bits[Const.VersionByte] &= Const.VersionByteMask;
bits[Const.VersionByte] |=
((int)GuidVersion.Random << Const.VersionByteShift);
// create the new System.Guid object
guid = new Guid(bits);
}
finally
{
// release the crypto provider handle
if (hCryptProv != IntPtr.Zero)
WinApi.CryptReleaseContext(hCryptProv, 0);
}
return guid;
}
}
#endif
#endregion Compact Framework Helper Classes
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.IO;
using System.Linq;
using Xunit;
namespace System.Diagnostics.Tests
{
public class EventLogTests : FileCleanupTestBase
{
[ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))]
public void EventLogReinitializationException()
{
using (EventLog eventLog = new EventLog())
{
eventLog.BeginInit();
Assert.Throws<InvalidOperationException>(() => eventLog.BeginInit());
eventLog.EndInit();
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void ClearLog()
{
string log = "ClearTest";
string source = "Source_" + nameof(ClearLog);
try
{
EventLog.CreateEventSource(source, log);
using (EventLog eventLog = new EventLog())
{
eventLog.Source = source;
Helpers.Retry(() => eventLog.Clear());
Assert.Equal(0, Helpers.Retry((() => eventLog.Entries.Count)));
Helpers.Retry(() => eventLog.WriteEntry("Writing to event log."));
Helpers.WaitForEventLog(eventLog, 1);
Assert.Equal(1, Helpers.Retry((() => eventLog.Entries.Count)));
}
}
finally
{
EventLog.DeleteEventSource(source);
Helpers.RetrySilently(() => EventLog.Delete(log));
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))]
public void ApplicationEventLog_Count()
{
using (EventLog eventLog = new EventLog("Application"))
{
Assert.InRange(Helpers.Retry((() => eventLog.Entries.Count)), 1, int.MaxValue);
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void DeleteLog()
{
string log = "DeleteTest";
string source = "Source_" + nameof(DeleteLog);
try
{
EventLog.CreateEventSource(source, log);
Assert.True(EventLog.Exists(log));
}
finally
{
EventLog.DeleteEventSource(source);
Helpers.Retry(() => EventLog.Delete(log)); // unlike other tests, throw if delete fails
Assert.False(EventLog.Exists(log));
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))]
public void CheckLogName_Get()
{
using (EventLog eventLog = new EventLog("Application"))
{
Assert.False(string.IsNullOrEmpty(eventLog.LogDisplayName));
if (CultureInfo.CurrentCulture.Name.Split('-')[0] == "en" )
Assert.Equal("Application", eventLog.LogDisplayName);
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))]
public void CheckMachineName_Get()
{
using (EventLog eventLog = new EventLog("Application"))
{
Assert.Equal(".", eventLog.MachineName);
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))]
public void GetLogDisplayName_NotSet_Throws()
{
using (EventLog eventLog = new EventLog())
{
eventLog.Log = Guid.NewGuid().ToString("N");
Assert.Throws<InvalidOperationException>(() => eventLog.LogDisplayName);
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))]
public void GetLogDisplayName_Set()
{
using (EventLog eventLog = new EventLog())
{
eventLog.Log = "Application";
Assert.False(string.IsNullOrEmpty(eventLog.LogDisplayName));
if (CultureInfo.CurrentCulture.Name.Split('-')[0] == "en" )
Assert.Equal("Application", eventLog.LogDisplayName);
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))]
public void EventLogs_Get()
{
Assert.Throws<ArgumentException>(() => EventLog.GetEventLogs(""));
EventLog[] eventLogCollection = EventLog.GetEventLogs();
Assert.Contains(eventLogCollection, eventlog => eventlog.Log.Equals("Application"));
Assert.Contains(eventLogCollection, eventlog => eventlog.Log.Equals("System"));
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void GetMaxKilobytes_Set()
{
string source = "Source_" + nameof(GetMaxKilobytes_Set);
string log = "maxKilobytesLog";
try
{
EventLog.CreateEventSource(source, log);
using (EventLog eventLog = new EventLog())
{
eventLog.Source = source;
eventLog.MaximumKilobytes = 0x400;
Assert.Equal(0x400, eventLog.MaximumKilobytes);
}
}
finally
{
EventLog.DeleteEventSource(source);
Helpers.RetrySilently(() => EventLog.Delete(log));
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))]
public void MaxKilobytesOutOfRangeException()
{
using (EventLog eventLog = new EventLog())
{
eventLog.Log = "Application";
Assert.Throws<ArgumentOutOfRangeException>(() => eventLog.MaximumKilobytes = 2);
Assert.Throws<ArgumentOutOfRangeException>(() => eventLog.MaximumKilobytes = 0x3FFFC1);
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void OverflowAndRetention_Set()
{
string source = "Source_" + nameof(OverflowAndRetention_Set);
string log = "Overflow_Set";
try
{
EventLog.CreateEventSource(source, log);
using (EventLog eventLog = new EventLog())
{
eventLog.Source = source;
// The second argument is only used when the overflow policy is set to OverWrite Older
eventLog.ModifyOverflowPolicy(OverflowAction.DoNotOverwrite, 1);
Assert.Equal(OverflowAction.DoNotOverwrite, eventLog.OverflowAction);
// -1 means overflow action is donot OverWrite
Assert.Equal(-1, eventLog.MinimumRetentionDays);
}
}
finally
{
EventLog.DeleteEventSource(source);
Helpers.RetrySilently(() => EventLog.Delete(log));
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void Overflow_OverWriteOlderAndRetention_Set()
{
string source = "Source_" + nameof(OverflowAndRetention_Set);
string log = "Overflow_Set";
int retentionDays = 30; // A number between 0 and 365 should work
try
{
EventLog.CreateEventSource(source, log);
using (EventLog eventLog = new EventLog())
{
eventLog.Source = source;
// The second argument is only used when the overflow policy is set to OverWrite Older
eventLog.ModifyOverflowPolicy(OverflowAction.OverwriteOlder, retentionDays);
Assert.Equal(OverflowAction.OverwriteOlder, eventLog.OverflowAction);
Assert.Equal(retentionDays, eventLog.MinimumRetentionDays);
}
}
finally
{
EventLog.DeleteEventSource(source);
Helpers.RetrySilently(() => EventLog.Delete(log));
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void OverflowAndRetentionDaysOutOfRange()
{
using (EventLog eventLog = new EventLog())
{
eventLog.Log = "Application";
Assert.Throws<ArgumentOutOfRangeException>(() => eventLog.ModifyOverflowPolicy(OverflowAction.OverwriteOlder, 400));
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void MachineName_Set()
{
string source = "Source_" + nameof(MachineName_Set);
using (EventLog eventLog = new EventLog())
{
eventLog.Log = "Application";
eventLog.MachineName = Environment.MachineName.ToLowerInvariant();
try
{
EventLog.CreateEventSource(source, eventLog.LogDisplayName);
Assert.Equal(eventLog.MachineName, Environment.MachineName.ToLowerInvariant());
Assert.True(EventLog.SourceExists(source, Environment.MachineName.ToLowerInvariant()));
}
finally
{
EventLog.DeleteEventSource(source);
}
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void RegisterDisplayLogName()
{
string log = "DisplayName";
string source = "Source_" + nameof(RegisterDisplayLogName);
string messageFile = GetTestFilePath();
long DisplayNameMsgId = 42; // It could be any number
EventSourceCreationData sourceData = new EventSourceCreationData(source, log);
try
{
EventLog.CreateEventSource(sourceData);
log = EventLog.LogNameFromSourceName(source, ".");
using (EventLog eventLog = new EventLog(log, ".", source))
{
if (messageFile.Length > 0)
{
eventLog.RegisterDisplayName(messageFile, DisplayNameMsgId);
}
Assert.Equal(log, eventLog.LogDisplayName);
}
}
finally
{
EventLog.DeleteEventSource(source);
Helpers.RetrySilently(() => EventLog.Delete(log));
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))]
public void InvalidFormatOrNullLogName()
{
Assert.Throws<ArgumentNullException>(() => new EventLog(null));
Assert.Throws<ArgumentException>(() => new EventLog("?"));
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))]
public void EventLog_EnableRaisingEvents_DefaultFalse()
{
using (EventLog eventLog = new EventLog("log"))
{
Assert.False(eventLog.EnableRaisingEvents);
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void InvalidFormatOrNullDeleteLogName()
{
Assert.Throws<ArgumentException>(() => EventLog.Delete(null));
Assert.Throws<InvalidOperationException>(() => EventLog.Delete("?"));
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void InvalidLogExistsLogName()
{
Assert.False(EventLog.Exists(null));
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void InvalidMachineName()
{
Assert.Throws<ArgumentException>(() => EventLog.Exists("Application", ""));
Assert.Throws<ArgumentException>(() => EventLog.Delete("", ""));
Assert.Throws<ArgumentException>(() => EventLog.DeleteEventSource("", ""));
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void LogDisplayNameDefault()
{
string source = "Source_" + nameof(LogDisplayNameDefault);
string log = "MyLogDisplay";
try
{
EventLog.CreateEventSource(source, log);
using (EventLog eventlog = new EventLog())
{
eventlog.Source = source;
Assert.Equal(log, eventlog.LogDisplayName);
}
}
finally
{
EventLog.DeleteEventSource(source);
Helpers.RetrySilently(() => EventLog.Delete(log));
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
public void GetMessageUsingEventMessageDLL()
{
if (CultureInfo.CurrentCulture.ToString() != "en-US")
{
return;
}
using (EventLog eventlog = new EventLog("Security"))
{
eventlog.Source = "Security";
Assert.Contains("", eventlog.Entries.LastOrDefault()?.Message ?? "");
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void GetEventLogEntriesTest()
{
foreach (var eventLog in EventLog.GetEventLogs())
{
// Accessing eventlog properties should not throw.
Assert.True(Helpers.Retry(() => eventLog.Entries.Count) >= 0);
}
}
[ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void GetEventLogContainsSecurityLogTest()
{
EventLog[] eventlogs = EventLog.GetEventLogs();
Assert.Contains("Security", eventlogs.Select(t => t.Log), StringComparer.OrdinalIgnoreCase);
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Params.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Params
{
/// <java-name>
/// org/apache/http/params/HttpAbstractParamBean
/// </java-name>
[Dot42.DexImport("org/apache/http/params/HttpAbstractParamBean", AccessFlags = 1057)]
public abstract partial class HttpAbstractParamBean
/* scope: __dot42__ */
{
/// <java-name>
/// params
/// </java-name>
[Dot42.DexImport("params", "Lorg/apache/http/params/HttpParams;", AccessFlags = 20)]
protected internal readonly global::Org.Apache.Http.Params.IHttpParams Params;
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public HttpAbstractParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal HttpAbstractParamBean() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Represents a collection of HTTP protocol and framework parameters.</para><para><para></para><para></para><title>Revision:</title><para>610763 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/HttpParams
/// </java-name>
[Dot42.DexImport("org/apache/http/params/HttpParams", AccessFlags = 1537)]
public partial interface IHttpParams
/* scope: __dot42__ */
{
/// <summary>
/// <para>Obtains the value of the given parameter.</para><para><para>setParameter(String, Object) </para></para>
/// </summary>
/// <returns>
/// <para>an object that represents the value of the parameter, <code>null</code> if the parameter is not set or if it is explicitly set to <code>null</code></para>
/// </returns>
/// <java-name>
/// getParameter
/// </java-name>
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1025)]
object GetParameter(string name) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Assigns the value to the parameter with the given name.</para><para></para>
/// </summary>
/// <java-name>
/// setParameter
/// </java-name>
[Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Creates a copy of these parameters.</para><para></para>
/// </summary>
/// <returns>
/// <para>a new set of parameters holding the same values as this one </para>
/// </returns>
/// <java-name>
/// copy
/// </java-name>
[Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Removes the parameter with the specified name.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if the parameter existed and has been removed, false else. </para>
/// </returns>
/// <java-name>
/// removeParameter
/// </java-name>
[Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
bool RemoveParameter(string name) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a Long parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setLongParameter(String, long) </para></para>
/// </summary>
/// <returns>
/// <para>a Long that represents the value of the parameter.</para>
/// </returns>
/// <java-name>
/// getLongParameter
/// </java-name>
[Dot42.DexImport("getLongParameter", "(Ljava/lang/String;J)J", AccessFlags = 1025)]
long GetLongParameter(string name, long defaultValue) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Assigns a Long to the parameter with the given name</para><para></para>
/// </summary>
/// <java-name>
/// setLongParameter
/// </java-name>
[Dot42.DexImport("setLongParameter", "(Ljava/lang/String;J)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams SetLongParameter(string name, long value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns an Integer parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setIntParameter(String, int) </para></para>
/// </summary>
/// <returns>
/// <para>a Integer that represents the value of the parameter.</para>
/// </returns>
/// <java-name>
/// getIntParameter
/// </java-name>
[Dot42.DexImport("getIntParameter", "(Ljava/lang/String;I)I", AccessFlags = 1025)]
int GetIntParameter(string name, int defaultValue) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Assigns an Integer to the parameter with the given name</para><para></para>
/// </summary>
/// <java-name>
/// setIntParameter
/// </java-name>
[Dot42.DexImport("setIntParameter", "(Ljava/lang/String;I)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams SetIntParameter(string name, int value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a Double parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setDoubleParameter(String, double) </para></para>
/// </summary>
/// <returns>
/// <para>a Double that represents the value of the parameter.</para>
/// </returns>
/// <java-name>
/// getDoubleParameter
/// </java-name>
[Dot42.DexImport("getDoubleParameter", "(Ljava/lang/String;D)D", AccessFlags = 1025)]
double GetDoubleParameter(string name, double defaultValue) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Assigns a Double to the parameter with the given name</para><para></para>
/// </summary>
/// <java-name>
/// setDoubleParameter
/// </java-name>
[Dot42.DexImport("setDoubleParameter", "(Ljava/lang/String;D)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams SetDoubleParameter(string name, double value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a Boolean parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setBooleanParameter(String, boolean) </para></para>
/// </summary>
/// <returns>
/// <para>a Boolean that represents the value of the parameter.</para>
/// </returns>
/// <java-name>
/// getBooleanParameter
/// </java-name>
[Dot42.DexImport("getBooleanParameter", "(Ljava/lang/String;Z)Z", AccessFlags = 1025)]
bool GetBooleanParameter(string name, bool defaultValue) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Assigns a Boolean to the parameter with the given name</para><para></para>
/// </summary>
/// <java-name>
/// setBooleanParameter
/// </java-name>
[Dot42.DexImport("setBooleanParameter", "(Ljava/lang/String;Z)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams SetBooleanParameter(string name, bool value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks if a boolean parameter is set to <code>true</code>.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the parameter is set to value <code>true</code>, <code>false</code> if it is not set or set to <code>false</code> </para>
/// </returns>
/// <java-name>
/// isParameterTrue
/// </java-name>
[Dot42.DexImport("isParameterTrue", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
bool IsParameterTrue(string name) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks if a boolean parameter is not set or <code>false</code>.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the parameter is either not set or set to value <code>false</code>, <code>false</code> if it is set to <code>true</code> </para>
/// </returns>
/// <java-name>
/// isParameterFalse
/// </java-name>
[Dot42.DexImport("isParameterFalse", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
bool IsParameterFalse(string name) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>This class represents a collection of HTTP protocol parameters. Protocol parameters may be linked together to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the parent collection of parameters.</para><para><para></para><para></para><title>Revision:</title><para>610464 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/BasicHttpParams
/// </java-name>
[Dot42.DexImport("org/apache/http/params/BasicHttpParams", AccessFlags = 49)]
public sealed partial class BasicHttpParams : global::Org.Apache.Http.Params.AbstractHttpParams, global::Java.Io.ISerializable, global::Java.Lang.ICloneable
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public BasicHttpParams() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getParameter
/// </java-name>
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1)]
public override object GetParameter(string name) /* MethodBuilder.Create */
{
return default(object);
}
/// <java-name>
/// setParameter
/// </java-name>
[Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public override global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <summary>
/// <para>Removes the parameter with the specified name.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if the parameter existed and has been removed, false else. </para>
/// </returns>
/// <java-name>
/// removeParameter
/// </java-name>
[Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public override bool RemoveParameter(string name) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Assigns the value to all the parameter with the given names</para><para></para>
/// </summary>
/// <java-name>
/// setParameters
/// </java-name>
[Dot42.DexImport("setParameters", "([Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 1)]
public void SetParameters(string[] names, object value) /* MethodBuilder.Create */
{
}
/// <java-name>
/// isParameterSet
/// </java-name>
[Dot42.DexImport("isParameterSet", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public bool IsParameterSet(string name) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isParameterSetLocally
/// </java-name>
[Dot42.DexImport("isParameterSetLocally", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public bool IsParameterSetLocally(string name) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Removes all parameters from this collection. </para>
/// </summary>
/// <java-name>
/// clear
/// </java-name>
[Dot42.DexImport("clear", "()V", AccessFlags = 1)]
public void Clear() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a copy of these parameters. The implementation here instantiates BasicHttpParams, then calls copyParams(HttpParams) to populate the copy.</para><para></para>
/// </summary>
/// <returns>
/// <para>a new set of params holding a copy of the <b>local</b> parameters in this object. </para>
/// </returns>
/// <java-name>
/// copy
/// </java-name>
[Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public override global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)]
public object Clone() /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Copies the locally defined parameters to the argument parameters. This method is called from copy().</para><para></para>
/// </summary>
/// <java-name>
/// copyParams
/// </java-name>
[Dot42.DexImport("copyParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 4)]
internal void CopyParams(global::Org.Apache.Http.Params.IHttpParams target) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>HttpParams implementation that delegates resolution of a parameter to the given default HttpParams instance if the parameter is not present in the local one. The state of the local collection can be mutated, whereas the default collection is treated as read-only.</para><para><para></para><para></para><title>Revision:</title><para>610763 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/DefaultedHttpParams
/// </java-name>
[Dot42.DexImport("org/apache/http/params/DefaultedHttpParams", AccessFlags = 49)]
public sealed partial class DefaultedHttpParams : global::Org.Apache.Http.Params.AbstractHttpParams
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public DefaultedHttpParams(global::Org.Apache.Http.Params.IHttpParams local, global::Org.Apache.Http.Params.IHttpParams defaults) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a copy of the local collection with the same default </para>
/// </summary>
/// <java-name>
/// copy
/// </java-name>
[Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public override global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <summary>
/// <para>Retrieves the value of the parameter from the local collection and, if the parameter is not set locally, delegates its resolution to the default collection. </para>
/// </summary>
/// <java-name>
/// getParameter
/// </java-name>
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1)]
public override object GetParameter(string name) /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Attempts to remove the parameter from the local collection. This method <b>does not</b> modify the default collection. </para>
/// </summary>
/// <java-name>
/// removeParameter
/// </java-name>
[Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public override bool RemoveParameter(string name) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Sets the parameter in the local collection. This method <b>does not</b> modify the default collection. </para>
/// </summary>
/// <java-name>
/// setParameter
/// </java-name>
[Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public override global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <java-name>
/// getDefaults
/// </java-name>
[Dot42.DexImport("getDefaults", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public global::Org.Apache.Http.Params.IHttpParams GetDefaults() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal DefaultedHttpParams() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getDefaults
/// </java-name>
public global::Org.Apache.Http.Params.IHttpParams Defaults
{
[Dot42.DexImport("getDefaults", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
get{ return GetDefaults(); }
}
}
/// <summary>
/// <para>Defines parameter names for connections in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/CoreConnectionPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/params/CoreConnectionPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class ICoreConnectionPNamesConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Defines the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters. </para><para>This parameter expects a value of type Integer. </para><para><para>java.net.SocketOptions::SO_TIMEOUT </para></para>
/// </summary>
/// <java-name>
/// SO_TIMEOUT
/// </java-name>
[Dot42.DexImport("SO_TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)]
public const string SO_TIMEOUT = "http.socket.timeout";
/// <summary>
/// <para>Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption. </para><para>This parameter expects a value of type Boolean. </para><para><para>java.net.SocketOptions::TCP_NODELAY </para></para>
/// </summary>
/// <java-name>
/// TCP_NODELAY
/// </java-name>
[Dot42.DexImport("TCP_NODELAY", "Ljava/lang/String;", AccessFlags = 25)]
public const string TCP_NODELAY = "http.tcp.nodelay";
/// <summary>
/// <para>Determines the size of the internal socket buffer used to buffer data while receiving / transmitting HTTP messages. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// SOCKET_BUFFER_SIZE
/// </java-name>
[Dot42.DexImport("SOCKET_BUFFER_SIZE", "Ljava/lang/String;", AccessFlags = 25)]
public const string SOCKET_BUFFER_SIZE = "http.socket.buffer-size";
/// <summary>
/// <para>Sets SO_LINGER with the specified linger time in seconds. The maximum timeout value is platform specific. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used. The setting only affects socket close. </para><para>This parameter expects a value of type Integer. </para><para><para>java.net.SocketOptions::SO_LINGER </para></para>
/// </summary>
/// <java-name>
/// SO_LINGER
/// </java-name>
[Dot42.DexImport("SO_LINGER", "Ljava/lang/String;", AccessFlags = 25)]
public const string SO_LINGER = "http.socket.linger";
/// <summary>
/// <para>Determines the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// CONNECTION_TIMEOUT
/// </java-name>
[Dot42.DexImport("CONNECTION_TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)]
public const string CONNECTION_TIMEOUT = "http.connection.timeout";
/// <summary>
/// <para>Determines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side. </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// STALE_CONNECTION_CHECK
/// </java-name>
[Dot42.DexImport("STALE_CONNECTION_CHECK", "Ljava/lang/String;", AccessFlags = 25)]
public const string STALE_CONNECTION_CHECK = "http.connection.stalecheck";
/// <summary>
/// <para>Determines the maximum line length limit. If set to a positive value, any HTTP line exceeding this limit will cause an IOException. A negative or zero value will effectively disable the check. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// MAX_LINE_LENGTH
/// </java-name>
[Dot42.DexImport("MAX_LINE_LENGTH", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_LINE_LENGTH = "http.connection.max-line-length";
/// <summary>
/// <para>Determines the maximum HTTP header count allowed. If set to a positive value, the number of HTTP headers received from the data stream exceeding this limit will cause an IOException. A negative or zero value will effectively disable the check. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// MAX_HEADER_COUNT
/// </java-name>
[Dot42.DexImport("MAX_HEADER_COUNT", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_HEADER_COUNT = "http.connection.max-header-count";
}
/// <summary>
/// <para>Defines parameter names for connections in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/CoreConnectionPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/params/CoreConnectionPNames", AccessFlags = 1537)]
public partial interface ICoreConnectionPNames
/* scope: __dot42__ */
{
}
/// <java-name>
/// org/apache/http/params/HttpConnectionParamBean
/// </java-name>
[Dot42.DexImport("org/apache/http/params/HttpConnectionParamBean", AccessFlags = 33)]
public partial class HttpConnectionParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public HttpConnectionParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setSoTimeout
/// </java-name>
[Dot42.DexImport("setSoTimeout", "(I)V", AccessFlags = 1)]
public virtual void SetSoTimeout(int soTimeout) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setTcpNoDelay
/// </java-name>
[Dot42.DexImport("setTcpNoDelay", "(Z)V", AccessFlags = 1)]
public virtual void SetTcpNoDelay(bool tcpNoDelay) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setSocketBufferSize
/// </java-name>
[Dot42.DexImport("setSocketBufferSize", "(I)V", AccessFlags = 1)]
public virtual void SetSocketBufferSize(int socketBufferSize) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setLinger
/// </java-name>
[Dot42.DexImport("setLinger", "(I)V", AccessFlags = 1)]
public virtual void SetLinger(int linger) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setConnectionTimeout
/// </java-name>
[Dot42.DexImport("setConnectionTimeout", "(I)V", AccessFlags = 1)]
public virtual void SetConnectionTimeout(int connectionTimeout) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setStaleCheckingEnabled
/// </java-name>
[Dot42.DexImport("setStaleCheckingEnabled", "(Z)V", AccessFlags = 1)]
public virtual void SetStaleCheckingEnabled(bool staleCheckingEnabled) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal HttpConnectionParamBean() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Defines parameter names for protocol execution in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/CoreProtocolPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/params/CoreProtocolPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class ICoreProtocolPNamesConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Defines the protocol version used per default. </para><para>This parameter expects a value of type org.apache.http.ProtocolVersion. </para>
/// </summary>
/// <java-name>
/// PROTOCOL_VERSION
/// </java-name>
[Dot42.DexImport("PROTOCOL_VERSION", "Ljava/lang/String;", AccessFlags = 25)]
public const string PROTOCOL_VERSION = "http.protocol.version";
/// <summary>
/// <para>Defines the charset to be used for encoding HTTP protocol elements. </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// HTTP_ELEMENT_CHARSET
/// </java-name>
[Dot42.DexImport("HTTP_ELEMENT_CHARSET", "Ljava/lang/String;", AccessFlags = 25)]
public const string HTTP_ELEMENT_CHARSET = "http.protocol.element-charset";
/// <summary>
/// <para>Defines the charset to be used per default for encoding content body. </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// HTTP_CONTENT_CHARSET
/// </java-name>
[Dot42.DexImport("HTTP_CONTENT_CHARSET", "Ljava/lang/String;", AccessFlags = 25)]
public const string HTTP_CONTENT_CHARSET = "http.protocol.content-charset";
/// <summary>
/// <para>Defines the content of the <code>User-Agent</code> header. </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// USER_AGENT
/// </java-name>
[Dot42.DexImport("USER_AGENT", "Ljava/lang/String;", AccessFlags = 25)]
public const string USER_AGENT = "http.useragent";
/// <summary>
/// <para>Defines the content of the <code>Server</code> header. </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// ORIGIN_SERVER
/// </java-name>
[Dot42.DexImport("ORIGIN_SERVER", "Ljava/lang/String;", AccessFlags = 25)]
public const string ORIGIN_SERVER = "http.origin-server";
/// <summary>
/// <para>Defines whether responses with an invalid <code>Transfer-Encoding</code> header should be rejected. </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// STRICT_TRANSFER_ENCODING
/// </java-name>
[Dot42.DexImport("STRICT_TRANSFER_ENCODING", "Ljava/lang/String;", AccessFlags = 25)]
public const string STRICT_TRANSFER_ENCODING = "http.protocol.strict-transfer-encoding";
/// <summary>
/// <para>Activates 'Expect: 100-continue' handshake for the entity enclosing methods. The purpose of the 'Expect: 100-continue' handshake to allow a client that is sending a request message with a request body to determine if the origin server is willing to accept the request (based on the request headers) before the client sends the request body. </para><para>The use of the 'Expect: 100-continue' handshake can result in noticable peformance improvement for entity enclosing requests (such as POST and PUT) that require the target server's authentication. </para><para>'Expect: 100-continue' handshake should be used with caution, as it may cause problems with HTTP servers and proxies that do not support HTTP/1.1 protocol. </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// USE_EXPECT_CONTINUE
/// </java-name>
[Dot42.DexImport("USE_EXPECT_CONTINUE", "Ljava/lang/String;", AccessFlags = 25)]
public const string USE_EXPECT_CONTINUE = "http.protocol.expect-continue";
/// <summary>
/// <para>Defines the maximum period of time in milliseconds the client should spend waiting for a 100-continue response. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// WAIT_FOR_CONTINUE
/// </java-name>
[Dot42.DexImport("WAIT_FOR_CONTINUE", "Ljava/lang/String;", AccessFlags = 25)]
public const string WAIT_FOR_CONTINUE = "http.protocol.wait-for-continue";
}
/// <summary>
/// <para>Defines parameter names for protocol execution in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/CoreProtocolPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/params/CoreProtocolPNames", AccessFlags = 1537)]
public partial interface ICoreProtocolPNames
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>Abstract base class for parameter collections. Type specific setters and getters are mapped to the abstract, generic getters and setters.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para></para><title>Revision:</title><para>542224 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/AbstractHttpParams
/// </java-name>
[Dot42.DexImport("org/apache/http/params/AbstractHttpParams", AccessFlags = 1057)]
public abstract partial class AbstractHttpParams : global::Org.Apache.Http.Params.IHttpParams
/* scope: __dot42__ */
{
/// <summary>
/// <para>Instantiates parameters. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal AbstractHttpParams() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getLongParameter
/// </java-name>
[Dot42.DexImport("getLongParameter", "(Ljava/lang/String;J)J", AccessFlags = 1)]
public virtual long GetLongParameter(string name, long defaultValue) /* MethodBuilder.Create */
{
return default(long);
}
/// <java-name>
/// setLongParameter
/// </java-name>
[Dot42.DexImport("setLongParameter", "(Ljava/lang/String;J)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Params.IHttpParams SetLongParameter(string name, long value) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <java-name>
/// getIntParameter
/// </java-name>
[Dot42.DexImport("getIntParameter", "(Ljava/lang/String;I)I", AccessFlags = 1)]
public virtual int GetIntParameter(string name, int defaultValue) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// setIntParameter
/// </java-name>
[Dot42.DexImport("setIntParameter", "(Ljava/lang/String;I)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Params.IHttpParams SetIntParameter(string name, int value) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <java-name>
/// getDoubleParameter
/// </java-name>
[Dot42.DexImport("getDoubleParameter", "(Ljava/lang/String;D)D", AccessFlags = 1)]
public virtual double GetDoubleParameter(string name, double defaultValue) /* MethodBuilder.Create */
{
return default(double);
}
/// <java-name>
/// setDoubleParameter
/// </java-name>
[Dot42.DexImport("setDoubleParameter", "(Ljava/lang/String;D)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Params.IHttpParams SetDoubleParameter(string name, double value) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <java-name>
/// getBooleanParameter
/// </java-name>
[Dot42.DexImport("getBooleanParameter", "(Ljava/lang/String;Z)Z", AccessFlags = 1)]
public virtual bool GetBooleanParameter(string name, bool defaultValue) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// setBooleanParameter
/// </java-name>
[Dot42.DexImport("setBooleanParameter", "(Ljava/lang/String;Z)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Params.IHttpParams SetBooleanParameter(string name, bool value) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <java-name>
/// isParameterTrue
/// </java-name>
[Dot42.DexImport("isParameterTrue", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public virtual bool IsParameterTrue(string name) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isParameterFalse
/// </java-name>
[Dot42.DexImport("isParameterFalse", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public virtual bool IsParameterFalse(string name) /* MethodBuilder.Create */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/params/HttpParams", "getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1025)]
public virtual object GetParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(object);
}
[Dot42.DexImport("org/apache/http/params/HttpParams", "setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
public virtual global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[Dot42.DexImport("org/apache/http/params/HttpParams", "copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
public virtual global::Org.Apache.Http.Params.IHttpParams Copy() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[Dot42.DexImport("org/apache/http/params/HttpParams", "removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
public virtual bool RemoveParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
}
/// <java-name>
/// org/apache/http/params/HttpProtocolParamBean
/// </java-name>
[Dot42.DexImport("org/apache/http/params/HttpProtocolParamBean", AccessFlags = 33)]
public partial class HttpProtocolParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public HttpProtocolParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setHttpElementCharset
/// </java-name>
[Dot42.DexImport("setHttpElementCharset", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetHttpElementCharset(string httpElementCharset) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setContentCharset
/// </java-name>
[Dot42.DexImport("setContentCharset", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetContentCharset(string contentCharset) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setVersion
/// </java-name>
[Dot42.DexImport("setVersion", "(Lorg/apache/http/HttpVersion;)V", AccessFlags = 1)]
public virtual void SetVersion(global::Org.Apache.Http.HttpVersion version) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setUserAgent
/// </java-name>
[Dot42.DexImport("setUserAgent", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetUserAgent(string userAgent) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setUseExpectContinue
/// </java-name>
[Dot42.DexImport("setUseExpectContinue", "(Z)V", AccessFlags = 1)]
public virtual void SetUseExpectContinue(bool useExpectContinue) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal HttpProtocolParamBean() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>This class implements an adaptor around the HttpParams interface to simplify manipulation of the HTTP protocol specific parameters. <br></br> Note that the <b>implements</b> relation to CoreProtocolPNames is for compatibility with existing application code only. References to the parameter names should use the interface, not this class.</para><para><para></para><para></para><title>Revision:</title><para>576089 </para></para><para><para>4.0</para><para>CoreProtocolPNames </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/HttpProtocolParams
/// </java-name>
[Dot42.DexImport("org/apache/http/params/HttpProtocolParams", AccessFlags = 49)]
public sealed partial class HttpProtocolParams : global::Org.Apache.Http.Params.ICoreProtocolPNames
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal HttpProtocolParams() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the charset to be used for writing HTTP headers. </para>
/// </summary>
/// <returns>
/// <para>The charset </para>
/// </returns>
/// <java-name>
/// getHttpElementCharset
/// </java-name>
[Dot42.DexImport("getHttpElementCharset", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetHttpElementCharset(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Sets the charset to be used for writing HTTP headers. </para>
/// </summary>
/// <java-name>
/// setHttpElementCharset
/// </java-name>
[Dot42.DexImport("setHttpElementCharset", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)]
public static void SetHttpElementCharset(global::Org.Apache.Http.Params.IHttpParams @params, string charset) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the default charset to be used for writing content body, when no charset explicitly specified. </para>
/// </summary>
/// <returns>
/// <para>The charset </para>
/// </returns>
/// <java-name>
/// getContentCharset
/// </java-name>
[Dot42.DexImport("getContentCharset", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetContentCharset(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Sets the default charset to be used for writing content body, when no charset explicitly specified. </para>
/// </summary>
/// <java-name>
/// setContentCharset
/// </java-name>
[Dot42.DexImport("setContentCharset", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)]
public static void SetContentCharset(global::Org.Apache.Http.Params.IHttpParams @params, string charset) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns protocol version to be used per default.</para><para></para>
/// </summary>
/// <returns>
/// <para>protocol version </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/ProtocolVersion;", AccessFlags = 9)]
public static global::Org.Apache.Http.ProtocolVersion GetVersion(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.ProtocolVersion);
}
/// <summary>
/// <para>Assigns the protocol version to be used by the HTTP methods that this collection of parameters applies to.</para><para></para>
/// </summary>
/// <java-name>
/// setVersion
/// </java-name>
[Dot42.DexImport("setVersion", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/ProtocolVersion;)V", AccessFlags = 9)]
public static void SetVersion(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.ProtocolVersion version) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getUserAgent
/// </java-name>
[Dot42.DexImport("getUserAgent", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetUserAgent(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// setUserAgent
/// </java-name>
[Dot42.DexImport("setUserAgent", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)]
public static void SetUserAgent(global::Org.Apache.Http.Params.IHttpParams @params, string useragent) /* MethodBuilder.Create */
{
}
/// <java-name>
/// useExpectContinue
/// </java-name>
[Dot42.DexImport("useExpectContinue", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)]
public static bool UseExpectContinue(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// setUseExpectContinue
/// </java-name>
[Dot42.DexImport("setUseExpectContinue", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)]
public static void SetUseExpectContinue(global::Org.Apache.Http.Params.IHttpParams @params, bool b) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>An adaptor for accessing connection parameters in HttpParams. <br></br> Note that the <b>implements</b> relation to CoreConnectionPNames is for compatibility with existing application code only. References to the parameter names should use the interface, not this class.</para><para><para></para><para></para><title>Revision:</title><para>576089 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/params/HttpConnectionParams
/// </java-name>
[Dot42.DexImport("org/apache/http/params/HttpConnectionParams", AccessFlags = 49)]
public sealed partial class HttpConnectionParams : global::Org.Apache.Http.Params.ICoreConnectionPNames
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal HttpConnectionParams() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters.</para><para></para>
/// </summary>
/// <returns>
/// <para>timeout in milliseconds </para>
/// </returns>
/// <java-name>
/// getSoTimeout
/// </java-name>
[Dot42.DexImport("getSoTimeout", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)]
public static int GetSoTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Sets the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters.</para><para></para>
/// </summary>
/// <java-name>
/// setSoTimeout
/// </java-name>
[Dot42.DexImport("setSoTimeout", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)]
public static void SetSoTimeout(global::Org.Apache.Http.Params.IHttpParams @params, int timeout) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests if Nagle's algorithm is to be used.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the Nagle's algorithm is to NOT be used (that is enable TCP_NODELAY), <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// getTcpNoDelay
/// </java-name>
[Dot42.DexImport("getTcpNoDelay", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)]
public static bool GetTcpNoDelay(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption.</para><para></para>
/// </summary>
/// <java-name>
/// setTcpNoDelay
/// </java-name>
[Dot42.DexImport("setTcpNoDelay", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)]
public static void SetTcpNoDelay(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getSocketBufferSize
/// </java-name>
[Dot42.DexImport("getSocketBufferSize", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)]
public static int GetSocketBufferSize(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// setSocketBufferSize
/// </java-name>
[Dot42.DexImport("setSocketBufferSize", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)]
public static void SetSocketBufferSize(global::Org.Apache.Http.Params.IHttpParams @params, int size) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns linger-on-close timeout. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used.</para><para></para>
/// </summary>
/// <returns>
/// <para>the linger-on-close timeout </para>
/// </returns>
/// <java-name>
/// getLinger
/// </java-name>
[Dot42.DexImport("getLinger", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)]
public static int GetLinger(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns linger-on-close timeout. This option disables/enables immediate return from a close() of a TCP Socket. Enabling this option with a non-zero Integer timeout means that a close() will block pending the transmission and acknowledgement of all data written to the peer, at which point the socket is closed gracefully. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used.</para><para></para>
/// </summary>
/// <java-name>
/// setLinger
/// </java-name>
[Dot42.DexImport("setLinger", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)]
public static void SetLinger(global::Org.Apache.Http.Params.IHttpParams @params, int value) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.</para><para></para>
/// </summary>
/// <returns>
/// <para>timeout in milliseconds. </para>
/// </returns>
/// <java-name>
/// getConnectionTimeout
/// </java-name>
[Dot42.DexImport("getConnectionTimeout", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)]
public static int GetConnectionTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Sets the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.</para><para></para>
/// </summary>
/// <java-name>
/// setConnectionTimeout
/// </java-name>
[Dot42.DexImport("setConnectionTimeout", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)]
public static void SetConnectionTimeout(global::Org.Apache.Http.Params.IHttpParams @params, int timeout) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if stale connection check is to be used, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isStaleCheckingEnabled
/// </java-name>
[Dot42.DexImport("isStaleCheckingEnabled", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)]
public static bool IsStaleCheckingEnabled(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Defines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.</para><para></para>
/// </summary>
/// <java-name>
/// setStaleCheckingEnabled
/// </java-name>
[Dot42.DexImport("setStaleCheckingEnabled", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)]
public static void SetStaleCheckingEnabled(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */
{
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Extensions.ExceptionExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.Multiplayer;
using osu.Game.Online.Rooms;
using osu.Game.Overlays;
using osu.Game.Rulesets;
using osu.Game.Screens.OnlinePlay.Match.Components;
using osuTK;
namespace osu.Game.Screens.OnlinePlay.Multiplayer.Match
{
public class MultiplayerMatchSettingsOverlay : RoomSettingsOverlay
{
private MatchSettings settings;
protected override OsuButton SubmitButton => settings.ApplyButton;
[Resolved]
private OngoingOperationTracker ongoingOperationTracker { get; set; }
protected override bool IsLoading => ongoingOperationTracker.InProgress.Value;
public MultiplayerMatchSettingsOverlay(Room room)
: base(room)
{
}
protected override void SelectBeatmap() => settings.SelectBeatmap();
protected override OnlinePlayComposite CreateSettings(Room room) => settings = new MatchSettings(room)
{
RelativeSizeAxes = Axes.Both,
RelativePositionAxes = Axes.Y,
SettingsApplied = Hide
};
protected class MatchSettings : OnlinePlayComposite
{
private const float disabled_alpha = 0.2f;
public Action SettingsApplied;
public OsuTextBox NameField, MaxParticipantsField;
public RoomAvailabilityPicker AvailabilityPicker;
public MatchTypePicker TypePicker;
public OsuTextBox PasswordTextBox;
public TriangleButton ApplyButton;
public OsuSpriteText ErrorText;
private OsuSpriteText typeLabel;
private LoadingLayer loadingLayer;
private BeatmapSelectionControl initialBeatmapControl;
public void SelectBeatmap() => initialBeatmapControl.BeginSelection();
[Resolved]
private IRoomManager manager { get; set; }
[Resolved]
private MultiplayerClient client { get; set; }
[Resolved]
private Bindable<WorkingBeatmap> beatmap { get; set; }
[Resolved]
private Bindable<RulesetInfo> ruleset { get; set; }
[Resolved]
private OngoingOperationTracker ongoingOperationTracker { get; set; }
private readonly IBindable<bool> operationInProgress = new BindableBool();
[CanBeNull]
private IDisposable applyingSettingsOperation;
private readonly Room room;
public MatchSettings(Room room)
{
this.room = room;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider, OsuColour colours)
{
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider.Background4
},
new GridContainer
{
RelativeSizeAxes = Axes.Both,
RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
},
Content = new[]
{
new Drawable[]
{
new OsuScrollContainer
{
Padding = new MarginPadding
{
Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING,
Vertical = 10
},
RelativeSizeAxes = Axes.Both,
Children = new[]
{
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 10),
Children = new Drawable[]
{
new Container
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Padding = new MarginPadding { Horizontal = WaveOverlayContainer.WIDTH_PADDING },
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new SectionContainer
{
Padding = new MarginPadding { Right = FIELD_PADDING / 2 },
Children = new[]
{
new Section("Room name")
{
Child = NameField = new OsuTextBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
LengthLimit = 100,
},
},
new Section("Room visibility")
{
Alpha = disabled_alpha,
Child = AvailabilityPicker = new RoomAvailabilityPicker
{
Enabled = { Value = false }
},
},
new Section("Game type")
{
Child = new FillFlowContainer
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Direction = FillDirection.Vertical,
Spacing = new Vector2(7),
Children = new Drawable[]
{
TypePicker = new MatchTypePicker
{
RelativeSizeAxes = Axes.X,
},
typeLabel = new OsuSpriteText
{
Font = OsuFont.GetFont(size: 14),
Colour = colours.Yellow
},
},
},
},
},
},
new SectionContainer
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Padding = new MarginPadding { Left = FIELD_PADDING / 2 },
Children = new[]
{
new Section("Max participants")
{
Alpha = disabled_alpha,
Child = MaxParticipantsField = new OsuNumberBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
ReadOnly = true,
},
},
new Section("Password (optional)")
{
Child = PasswordTextBox = new OsuPasswordTextBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
LengthLimit = 255,
},
},
}
}
},
},
initialBeatmapControl = new BeatmapSelectionControl
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.X,
Width = 0.5f
}
}
}
},
},
},
new Drawable[]
{
new Container
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Y = 2,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider.Background5
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 20),
Margin = new MarginPadding { Vertical = 20 },
Padding = new MarginPadding { Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING },
Children = new Drawable[]
{
ApplyButton = new CreateOrUpdateButton
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Size = new Vector2(230, 55),
Enabled = { Value = false },
Action = apply,
},
ErrorText = new OsuSpriteText
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Alpha = 0,
Depth = 1,
Colour = colours.RedDark
}
}
}
}
}
}
}
},
loadingLayer = new LoadingLayer(true)
};
TypePicker.Current.BindValueChanged(type => typeLabel.Text = type.NewValue.GetLocalisableDescription(), true);
RoomName.BindValueChanged(name => NameField.Text = name.NewValue, true);
Availability.BindValueChanged(availability => AvailabilityPicker.Current.Value = availability.NewValue, true);
Type.BindValueChanged(type => TypePicker.Current.Value = type.NewValue, true);
MaxParticipants.BindValueChanged(count => MaxParticipantsField.Text = count.NewValue?.ToString(), true);
RoomID.BindValueChanged(roomId => initialBeatmapControl.Alpha = roomId.NewValue == null ? 1 : 0, true);
Password.BindValueChanged(password => PasswordTextBox.Text = password.NewValue ?? string.Empty, true);
operationInProgress.BindTo(ongoingOperationTracker.InProgress);
operationInProgress.BindValueChanged(v =>
{
if (v.NewValue)
loadingLayer.Show();
else
loadingLayer.Hide();
});
}
protected override void Update()
{
base.Update();
ApplyButton.Enabled.Value = Playlist.Count > 0 && NameField.Text.Length > 0 && !operationInProgress.Value;
}
private void apply()
{
if (!ApplyButton.Enabled.Value)
return;
hideError();
Debug.Assert(applyingSettingsOperation == null);
applyingSettingsOperation = ongoingOperationTracker.BeginOperation();
// If the client is already in a room, update via the client.
// Otherwise, update the room directly in preparation for it to be submitted to the API on match creation.
if (client.Room != null)
{
client.ChangeSettings(name: NameField.Text, password: PasswordTextBox.Text, matchType: TypePicker.Current.Value).ContinueWith(t => Schedule(() =>
{
if (t.IsCompletedSuccessfully)
onSuccess(room);
else
onError(t.Exception?.AsSingular().Message ?? "Error changing settings.");
}));
}
else
{
room.Name.Value = NameField.Text;
room.Availability.Value = AvailabilityPicker.Current.Value;
room.Type.Value = TypePicker.Current.Value;
room.Password.Value = PasswordTextBox.Current.Value;
if (int.TryParse(MaxParticipantsField.Text, out int max))
room.MaxParticipants.Value = max;
else
room.MaxParticipants.Value = null;
manager?.CreateRoom(room, onSuccess, onError);
}
}
private void hideError() => ErrorText.FadeOut(50);
private void onSuccess(Room room)
{
Debug.Assert(applyingSettingsOperation != null);
SettingsApplied?.Invoke();
applyingSettingsOperation.Dispose();
applyingSettingsOperation = null;
}
private void onError(string text)
{
Debug.Assert(applyingSettingsOperation != null);
ErrorText.Text = text;
ErrorText.FadeIn(50);
applyingSettingsOperation.Dispose();
applyingSettingsOperation = null;
}
}
public class CreateOrUpdateButton : TriangleButton
{
[Resolved(typeof(Room), nameof(Room.RoomID))]
private Bindable<long?> roomId { get; set; }
protected override void LoadComplete()
{
base.LoadComplete();
roomId.BindValueChanged(id => Text = id.NewValue == null ? "Create" : "Update", true);
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
BackgroundColour = colours.Yellow;
Triangles.ColourLight = colours.YellowLight;
Triangles.ColourDark = colours.YellowDark;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
[Export(typeof(ISuggestedActionsSourceProvider))]
[VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)]
[VisualStudio.Utilities.Name("Roslyn Code Fix")]
[VisualStudio.Utilities.Order]
internal class SuggestedActionsSourceProvider : ISuggestedActionsSourceProvider
{
private static readonly Guid s_CSharpSourceGuid = new Guid("b967fea8-e2c3-4984-87d4-71a38f49e16a");
private static readonly Guid s_visualBasicSourceGuid = new Guid("4de30e93-3e0c-40c2-a4ba-1124da4539f6");
private const int InvalidSolutionVersion = -1;
private readonly ICodeRefactoringService _codeRefactoringService;
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly ICodeFixService _codeFixService;
private readonly ICodeActionEditHandlerService _editHandler;
private readonly IAsynchronousOperationListener _listener;
private readonly IWaitIndicator _waitIndicator;
[ImportingConstructor]
public SuggestedActionsSourceProvider(
ICodeRefactoringService codeRefactoringService,
IDiagnosticAnalyzerService diagnosticService,
ICodeFixService codeFixService,
ICodeActionEditHandlerService editHandler,
IWaitIndicator waitIndicator,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
{
_codeRefactoringService = codeRefactoringService;
_diagnosticService = diagnosticService;
_codeFixService = codeFixService;
_editHandler = editHandler;
_waitIndicator = waitIndicator;
_listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.LightBulb);
}
public ISuggestedActionsSource CreateSuggestedActionsSource(ITextView textView, ITextBuffer textBuffer)
{
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(textBuffer);
return new Source(this, textView, textBuffer);
}
private class Source : ForegroundThreadAffinitizedObject, ISuggestedActionsSource
{
// state that will be only reset when source is disposed.
private SuggestedActionsSourceProvider _owner;
private ITextView _textView;
private ITextBuffer _subjectBuffer;
private WorkspaceRegistration _registration;
// mutable state
private Workspace _workspace;
private int _lastSolutionVersionReported;
public Source(SuggestedActionsSourceProvider owner, ITextView textView, ITextBuffer textBuffer)
{
_owner = owner;
_textView = textView;
_textView.Closed += OnTextViewClosed;
_subjectBuffer = textBuffer;
_registration = Workspace.GetWorkspaceRegistration(textBuffer.AsTextContainer());
_lastSolutionVersionReported = InvalidSolutionVersion;
var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService;
updateSource.DiagnosticsUpdated += OnDiagnosticsUpdated;
if (_registration.Workspace != null)
{
_workspace = _registration.Workspace;
_workspace.DocumentActiveContextChanged += OnActiveContextChanged;
}
_registration.WorkspaceChanged += OnWorkspaceChanged;
}
public event EventHandler<EventArgs> SuggestedActionsChanged;
public bool TryGetTelemetryId(out Guid telemetryId)
{
telemetryId = default(Guid);
var workspace = _workspace;
if (workspace == null || _subjectBuffer == null)
{
return false;
}
var documentId = workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer());
if (documentId == null)
{
return false;
}
var project = workspace.CurrentSolution.GetProject(documentId.ProjectId);
if (project == null)
{
return false;
}
switch (project.Language)
{
case LanguageNames.CSharp:
telemetryId = s_CSharpSourceGuid;
return true;
case LanguageNames.VisualBasic:
telemetryId = s_visualBasicSourceGuid;
return true;
default:
return false;
}
}
public IEnumerable<SuggestedActionSet> GetSuggestedActions(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken)
{
AssertIsForeground();
using (Logger.LogBlock(FunctionId.SuggestedActions_GetSuggestedActions, cancellationToken))
{
var documentAndSnapshot = GetMatchingDocumentAndSnapshotAsync(range.Snapshot, cancellationToken).WaitAndGetResult(cancellationToken);
if (!documentAndSnapshot.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return null;
}
var document = documentAndSnapshot.Value.Item1;
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>();
var fixes = GetCodeFixes(supportsFeatureService, requestedActionCategories, workspace, document, range, cancellationToken);
var refactorings = GetRefactorings(supportsFeatureService, requestedActionCategories, workspace, document, range, cancellationToken);
var result = fixes == null ? refactorings : refactorings == null
? fixes : fixes.Concat(refactorings);
if (result == null)
{
return null;
}
var allActionSets = result.ToList();
allActionSets = InlineActionSetsIfDesirable(allActionSets);
return allActionSets;
}
}
private List<SuggestedActionSet> InlineActionSetsIfDesirable(List<SuggestedActionSet> allActionSets)
{
// If we only have a single set of items, and that set only has three max suggestion
// offered. Then we can consider inlining any nested actions into the top level list.
// (but we only do this if the parent of the nested actions isn't invokable itself).
if (allActionSets.Sum(a => a.Actions.Count()) > 3)
{
return allActionSets;
}
return allActionSets.Select(InlineActions).ToList();
}
private bool IsInlineable(ISuggestedAction action)
{
var suggestedAction = action as SuggestedAction;
return suggestedAction != null &&
!suggestedAction.CodeAction.IsInvokable &&
suggestedAction.CodeAction.HasCodeActions;
}
private SuggestedActionSet InlineActions(SuggestedActionSet actionSet)
{
if (!actionSet.Actions.Any(IsInlineable))
{
return actionSet;
}
var newActions = new List<ISuggestedAction>();
foreach (var action in actionSet.Actions)
{
if (IsInlineable(action))
{
// Looks like something we can inline.
var childActionSets = ((SuggestedAction)action).GetActionSets();
if (childActionSets.Length != 1)
{
return actionSet;
}
newActions.AddRange(childActionSets[0].Actions);
continue;
}
newActions.Add(action);
}
return new SuggestedActionSet(newActions, actionSet.Title, actionSet.Priority, actionSet.ApplicableToSpan);
}
private IEnumerable<SuggestedActionSet> GetCodeFixes(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
Workspace workspace,
Document document,
SnapshotSpan range,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
if (_owner._codeFixService != null && supportsFeatureService.SupportsCodeFixes(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix))
{
// We only include suppressions if lightbulb is asking for everything.
// If the light bulb is only asking for code fixes, then we don't include suppressions.
var includeSuppressionFixes = requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Any);
var fixes = Task.Run(
async () =>
{
var stream = await _owner._codeFixService.GetFixesAsync(
document, range.Span.ToTextSpan(), includeSuppressionFixes, cancellationToken).ConfigureAwait(false);
return stream.ToList();
},
cancellationToken).WaitAndGetResult(cancellationToken);
var filteredFixes = FilterOnUIThread(fixes, workspace);
return OrganizeFixes(workspace, filteredFixes, hasSuppressionFixes: includeSuppressionFixes);
}
return null;
}
private List<CodeFixCollection> FilterOnUIThread(List<CodeFixCollection> collections, Workspace workspace)
{
this.AssertIsForeground();
return collections.Select(c => FilterOnUIThread(c, workspace)).WhereNotNull().ToList();
}
private CodeFixCollection FilterOnUIThread(CodeFixCollection collection, Workspace workspace)
{
this.AssertIsForeground();
var applicableFixes = collection.Fixes.Where(f => IsApplicable(f.Action, workspace)).ToList();
return applicableFixes.Count == 0
? null
: applicableFixes.Count == collection.Fixes.Length
? collection
: new CodeFixCollection(collection.Provider, collection.TextSpan, applicableFixes, collection.FixAllContext);
}
private bool IsApplicable(CodeAction action, Workspace workspace)
{
if (!action.PerformFinalApplicabilityCheck)
{
// If we don't even need to perform the final applicability check,
// then the code actoin is applicable.
return true;
}
// Otherwise, defer to the action to make the decision.
this.AssertIsForeground();
return action.IsApplicable(workspace);
}
private List<CodeRefactoring> FilterOnUIThread(List<CodeRefactoring> refactorings, Workspace workspace)
{
return refactorings.Select(r => FilterOnUIThread(r, workspace)).WhereNotNull().ToList();
}
private CodeRefactoring FilterOnUIThread(CodeRefactoring refactoring, Workspace workspace)
{
var actions = refactoring.Actions.Where(a => IsApplicable(a, workspace)).ToList();
return actions.Count == 0
? null
: actions.Count == refactoring.Actions.Count
? refactoring
: new CodeRefactoring(refactoring.Provider, actions);
}
/// <summary>
/// Arrange fixes into groups based on the issue (diagnostic being fixed) and prioritize these groups.
/// </summary>
private IEnumerable<SuggestedActionSet> OrganizeFixes(Workspace workspace, IEnumerable<CodeFixCollection> fixCollections, bool hasSuppressionFixes)
{
var map = ImmutableDictionary.CreateBuilder<DiagnosticData, IList<SuggestedAction>>();
var order = ImmutableArray.CreateBuilder<DiagnosticData>();
// First group fixes by issue (diagnostic).
GroupFixes(workspace, fixCollections, map, order, hasSuppressionFixes);
// Then prioritize between the groups.
return PrioritizeFixGroups(map.ToImmutable(), order.ToImmutable());
}
/// <summary>
/// Groups fixes by the diagnostic being addressed by each fix.
/// </summary>
private void GroupFixes(Workspace workspace, IEnumerable<CodeFixCollection> fixCollections, IDictionary<DiagnosticData, IList<SuggestedAction>> map, IList<DiagnosticData> order, bool hasSuppressionFixes)
{
foreach (var fixCollection in fixCollections)
{
var fixes = fixCollection.Fixes;
var fixCount = fixes.Length;
Func<CodeAction, SuggestedActionSet> getFixAllSuggestedActionSet = codeAction =>
CodeFixSuggestedAction.GetFixAllSuggestedActionSet(codeAction, fixCount, fixCollection.FixAllContext,
workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator);
foreach (var fix in fixes)
{
// Suppression fixes are handled below.
if (!(fix.Action is SuppressionCodeAction))
{
SuggestedAction suggestedAction;
if (fix.Action.HasCodeActions)
{
var nestedActions = new List<SuggestedAction>();
foreach (var nestedAction in fix.Action.GetCodeActions())
{
nestedActions.Add(new CodeFixSuggestedAction(workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator,
fix, nestedAction, fixCollection.Provider, getFixAllSuggestedActionSet(nestedAction)));
}
var diag = fix.PrimaryDiagnostic;
var set = new SuggestedActionSet(nestedActions, SuggestedActionSetPriority.Medium, diag.Location.SourceSpan.ToSpan());
suggestedAction = new SuggestedAction(workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator,
fix.Action, fixCollection.Provider, new[] { set });
}
else
{
suggestedAction = new CodeFixSuggestedAction(workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator,
fix, fix.Action, fixCollection.Provider, getFixAllSuggestedActionSet(fix.Action));
}
AddFix(fix, suggestedAction, map, order);
}
}
if (hasSuppressionFixes)
{
// Add suppression fixes to the end of a given SuggestedActionSet so that they always show up last in a group.
foreach (var fix in fixes)
{
if (fix.Action is SuppressionCodeAction)
{
SuggestedAction suggestedAction;
if (fix.Action.HasCodeActions)
{
suggestedAction = new SuppressionSuggestedAction(workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator,
fix, fixCollection.Provider, getFixAllSuggestedActionSet);
}
else
{
suggestedAction = new CodeFixSuggestedAction(workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator,
fix, fix.Action, fixCollection.Provider, getFixAllSuggestedActionSet(fix.Action));
}
AddFix(fix, suggestedAction, map, order);
}
}
}
}
}
private static void AddFix(CodeFix fix, SuggestedAction suggestedAction, IDictionary<DiagnosticData, IList<SuggestedAction>> map, IList<DiagnosticData> order)
{
var diag = fix.GetPrimaryDiagnosticData();
if (!map.ContainsKey(diag))
{
// Remember the order of the keys for the 'map' dictionary.
order.Add(diag);
map[diag] = ImmutableArray.CreateBuilder<SuggestedAction>();
}
map[diag].Add(suggestedAction);
}
/// <summary>
/// Return prioritized set of fix groups such that fix group for suppression always show up at the bottom of the list.
/// </summary>
/// <remarks>
/// Fix groups are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>.
/// Priority for all <see cref="SuggestedActionSet"/>s containing fixes is set to <see cref="SuggestedActionSetPriority.Medium"/> by default.
/// The only exception is the case where a <see cref="SuggestedActionSet"/> only contains suppression fixes -
/// the priority of such <see cref="SuggestedActionSet"/>s is set to <see cref="SuggestedActionSetPriority.None"/> so that suppression fixes
/// always show up last after all other fixes (and refactorings) for the selected line of code.
/// </remarks>
private static IEnumerable<SuggestedActionSet> PrioritizeFixGroups(IDictionary<DiagnosticData, IList<SuggestedAction>> map, IList<DiagnosticData> order)
{
var sets = ImmutableArray.CreateBuilder<SuggestedActionSet>();
foreach (var diag in order)
{
var fixes = map[diag];
var priority = fixes.All(s => s is SuppressionSuggestedAction) ? SuggestedActionSetPriority.None : SuggestedActionSetPriority.Medium;
// diagnostic from things like build shouldn't reach here since we don't support LB for those diagnostics
Contract.Requires(diag.HasTextSpan);
sets.Add(new SuggestedActionSet(fixes, priority, diag.TextSpan.ToSpan()));
}
return sets.ToImmutable();
}
private IEnumerable<SuggestedActionSet> GetRefactorings(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
Workspace workspace,
Document document,
SnapshotSpan range,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
var optionService = workspace.Services.GetService<IOptionService>();
if (optionService.GetOption(EditorComponentOnOffOptions.CodeRefactorings) &&
_owner._codeRefactoringService != null &&
supportsFeatureService.SupportsRefactorings(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring))
{
// Get the selection while on the UI thread.
var selection = TryGetCodeRefactoringSelection(_subjectBuffer, _textView, range);
if (!selection.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return null;
}
var refactorings = Task.Run(
async () =>
{
var stream = await _owner._codeRefactoringService.GetRefactoringsAsync(
document, selection.Value, cancellationToken).ConfigureAwait(false);
return stream.ToList();
},
cancellationToken).WaitAndGetResult(cancellationToken);
var filteredRefactorings = FilterOnUIThread(refactorings, workspace);
return filteredRefactorings.Select(r => OrganizeRefactorings(workspace, r));
}
return null;
}
/// <summary>
/// Arrange refactorings into groups.
/// </summary>
/// <remarks>
/// Refactorings are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>.
/// Priority for all <see cref="SuggestedActionSet"/>s containing refactorings is set to <see cref="SuggestedActionSetPriority.Low"/>
/// and should show up after fixes but before suppression fixes in the light bulb menu.
/// </remarks>
private SuggestedActionSet OrganizeRefactorings(Workspace workspace, CodeRefactoring refactoring)
{
var refactoringSuggestedActions = ImmutableArray.CreateBuilder<SuggestedAction>();
foreach (var a in refactoring.Actions)
{
refactoringSuggestedActions.Add(
new CodeRefactoringSuggestedAction(
workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator, a, refactoring.Provider));
}
return new SuggestedActionSet(refactoringSuggestedActions.ToImmutable(), SuggestedActionSetPriority.Low);
}
public async Task<bool> HasSuggestedActionsAsync(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken)
{
// Explicitly hold onto below fields in locals and use these locals throughout this code path to avoid crashes
// if these fields happen to be cleared by Dispose() below. This is required since this code path involves
// code that can run asynchronously from background thread.
var view = _textView;
var buffer = _subjectBuffer;
var provider = _owner;
if (view == null || buffer == null || provider == null)
{
return false;
}
using (var asyncToken = provider._listener.BeginAsyncOperation("HasSuggestedActionsAsync"))
{
var documentAndSnapshot = await GetMatchingDocumentAndSnapshotAsync(range.Snapshot, cancellationToken).ConfigureAwait(false);
if (!documentAndSnapshot.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return false;
}
var document = documentAndSnapshot.Value.Item1;
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>();
return
await HasFixesAsync(
supportsFeatureService, requestedActionCategories, provider, document, range,
cancellationToken).ConfigureAwait(false) ||
await HasRefactoringsAsync(
supportsFeatureService, requestedActionCategories, provider, document, buffer, view, range,
cancellationToken).ConfigureAwait(false);
}
}
private async Task<bool> HasFixesAsync(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
SuggestedActionsSourceProvider provider,
Document document, SnapshotSpan range,
CancellationToken cancellationToken)
{
if (provider._codeFixService != null && supportsFeatureService.SupportsCodeFixes(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix))
{
// We only consider suppressions if lightbulb is asking for everything.
// If the light bulb is only asking for code fixes, then we don't consider suppressions.
var considerSuppressionFixes = requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Any);
var result = await Task.Run(
async () => await provider._codeFixService.GetFirstDiagnosticWithFixAsync(
document, range.Span.ToTextSpan(), considerSuppressionFixes, cancellationToken).ConfigureAwait(false),
cancellationToken).ConfigureAwait(false);
if (result.HasFix)
{
Logger.Log(FunctionId.SuggestedActions_HasSuggestedActionsAsync);
return true;
}
if (result.PartialResult)
{
// reset solution version number so that we can raise suggested action changed event
Volatile.Write(ref _lastSolutionVersionReported, InvalidSolutionVersion);
return false;
}
}
return false;
}
private async Task<bool> HasRefactoringsAsync(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
SuggestedActionsSourceProvider provider,
Document document,
ITextBuffer buffer,
ITextView view,
SnapshotSpan range,
CancellationToken cancellationToken)
{
var optionService = document.Project.Solution.Workspace.Services.GetService<IOptionService>();
if (optionService.GetOption(EditorComponentOnOffOptions.CodeRefactorings) &&
provider._codeRefactoringService != null &&
supportsFeatureService.SupportsRefactorings(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring))
{
TextSpan? selection = null;
if (IsForeground())
{
// This operation needs to happen on UI thread because it needs to access textView.Selection.
selection = TryGetCodeRefactoringSelection(buffer, view, range);
}
else
{
await InvokeBelowInputPriority(() =>
{
// This operation needs to happen on UI thread because it needs to access textView.Selection.
selection = TryGetCodeRefactoringSelection(buffer, view, range);
}).ConfigureAwait(false);
}
if (!selection.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return false;
}
return await Task.Run(
async () => await provider._codeRefactoringService.HasRefactoringsAsync(
document, selection.Value, cancellationToken).ConfigureAwait(false),
cancellationToken).ConfigureAwait(false);
}
return false;
}
private static TextSpan? TryGetCodeRefactoringSelection(ITextBuffer buffer, ITextView view, SnapshotSpan range)
{
var selectedSpans = view.Selection.SelectedSpans
.SelectMany(ss => view.BufferGraph.MapDownToBuffer(ss, SpanTrackingMode.EdgeExclusive, buffer))
.Where(ss => !view.IsReadOnlyOnSurfaceBuffer(ss))
.ToList();
// We only support refactorings when there is a single selection in the document.
if (selectedSpans.Count != 1)
{
return null;
}
var translatedSpan = selectedSpans[0].TranslateTo(range.Snapshot, SpanTrackingMode.EdgeInclusive);
// We only support refactorings when selected span intersects with the span that the light bulb is asking for.
if (!translatedSpan.IntersectsWith(range))
{
return null;
}
return translatedSpan.Span.ToTextSpan();
}
private static async Task<ValueTuple<Document, ITextSnapshot>?> GetMatchingDocumentAndSnapshotAsync(ITextSnapshot givenSnapshot, CancellationToken cancellationToken)
{
var buffer = givenSnapshot.TextBuffer;
if (buffer == null)
{
return null;
}
var workspace = buffer.GetWorkspace();
if (workspace == null)
{
return null;
}
var documentId = workspace.GetDocumentIdInCurrentContext(buffer.AsTextContainer());
if (documentId == null)
{
return null;
}
var document = workspace.CurrentSolution.GetDocument(documentId);
if (document == null)
{
return null;
}
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
var snapshot = sourceText.FindCorrespondingEditorTextSnapshot();
if (snapshot == null || snapshot.Version.ReiteratedVersionNumber != givenSnapshot.Version.ReiteratedVersionNumber)
{
return null;
}
return ValueTuple.Create(document, snapshot);
}
private void OnTextViewClosed(object sender, EventArgs e)
{
Dispose();
}
private void OnWorkspaceChanged(object sender, EventArgs e)
{
// REVIEW: this event should give both old and new workspace as argument so that
// one doesn't need to hold onto workspace in field.
// remove existing event registration
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged -= OnActiveContextChanged;
}
// REVIEW: why one need to get new workspace from registration? why not just pass in the new workspace?
// add new event registration
_workspace = _registration.Workspace;
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged += OnActiveContextChanged;
}
}
private void OnActiveContextChanged(object sender, DocumentEventArgs e)
{
// REVIEW: it would be nice for changed event to pass in both old and new document.
OnSuggestedActionsChanged(e.Document.Project.Solution.Workspace, e.Document.Id, e.Document.Project.Solution.WorkspaceVersion);
}
private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e)
{
// document removed case. no reason to raise event
if (e.Solution == null)
{
return;
}
OnSuggestedActionsChanged(e.Workspace, e.DocumentId, e.Solution.WorkspaceVersion);
}
private void OnSuggestedActionsChanged(Workspace currentWorkspace, DocumentId currentDocumentId, int solutionVersion, DiagnosticsUpdatedArgs args = null)
{
// Explicitly hold onto the _subjectBuffer field in a local and use this local in this function to avoid crashes
// if this field happens to be cleared by Dispose() below. This is required since this code path involves code
// that can run on background thread.
var buffer = _subjectBuffer;
if (buffer == null)
{
return;
}
var workspace = buffer.GetWorkspace();
// workspace is not ready, nothing to do.
if (workspace == null || workspace != currentWorkspace)
{
return;
}
if (currentDocumentId != workspace.GetDocumentIdInCurrentContext(buffer.AsTextContainer()) ||
solutionVersion == Volatile.Read(ref _lastSolutionVersionReported))
{
return;
}
this.SuggestedActionsChanged?.Invoke(this, EventArgs.Empty);
Volatile.Write(ref _lastSolutionVersionReported, solutionVersion);
}
public void Dispose()
{
if (_owner != null)
{
var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService;
updateSource.DiagnosticsUpdated -= OnDiagnosticsUpdated;
_owner = null;
}
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged -= OnActiveContextChanged;
_workspace = null;
}
if (_registration != null)
{
_registration.WorkspaceChanged -= OnWorkspaceChanged;
_registration = null;
}
if (_textView != null)
{
_textView.Closed -= OnTextViewClosed;
_textView = null;
}
if (_subjectBuffer != null)
{
_subjectBuffer = null;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace HTLib2
{
public partial class HSerialize
{
[Serializable]
class Ver : ISerializable, IBinarySerializable
{
public int ver { get { return _ver; } } int _ver;
public Ver(int ver)
{
_ver = ver;
}
public Ver(SerializationInfo info, StreamingContext context)
{
_ver = (int)info.GetValue("ver", typeof(int));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ver", ver);
}
public static implicit operator int(Ver ver)
{
return ver.ver;
}
public void BinarySerialize(HBinaryWriter writer)
{
writer.Write("ver(");
writer.Write(ver);
writer.Write(")");
}
public void Deserialize(HBinaryReader reader)
{
string str1, str2;
str1 = reader.ReadString(); HDebug.Assert(str1 == "ver(");
_ver = reader.ReadInt32 ();
str2 = reader.ReadString(); HDebug.Assert(str2 == ")");
}
}
public class SerializedVersionException : Exception
{
public SerializedVersionException() { }
public SerializedVersionException(string message) : base(message) { }
public SerializedVersionException(string message, Exception innerException) : base (message,innerException) { }
}
public static void Serialize(string filename, int? ver, object obj0 ) { _Serialize(filename, ver, new object[] { obj0 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1 ) { _Serialize(filename, ver, new object[] { obj0, obj1 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3, object obj4 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3, obj4 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3, object obj4, object obj5 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3, obj4, obj5 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3, obj4, obj5, obj6 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3, obj4, obj5, obj6, obj7 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7, object obj8 ) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8 }); }
public static void Serialize(string filename, int? ver, object obj0, object obj1, object obj2, object obj3, object obj4, object obj5, object obj6, object obj7, object obj8, object obj9) { _Serialize(filename, ver, new object[] { obj0, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8, obj9 }); }
public static void SerializeDepreciated(string filename, int? ver, object obj1, params object[] obj234)
{
List<object> objs = new List<object>();
objs.Add(obj1);
foreach(object obj in obj234)
objs.Add(obj);
_Serialize(filename, ver, objs.ToArray());
}
public static void _Serialize(string filename, int? ver, object[] objs)
{
string lockname = "Serializer: "+filename.Replace("\\", "@");
using(new NamedLock(lockname))
{
Stream stream = HFile.Open(filename, FileMode.Create);
BinaryFormatter bFormatter = new BinaryFormatter();
{
if(ver != null)
bFormatter.Serialize(stream, new Ver(ver.Value));
}
{
System.Int32 count = objs.Length;
bFormatter.Serialize(stream, count);
for(int i = 0; i < count; i++)
{
bFormatter.Serialize(stream, objs[i]);
}
}
stream.Flush();
stream.Close();
}
}
public static bool _Deserialize(string filename, int? ver, out object[] objs)
{
string lockname = "Serializer: "+filename.Replace("\\", "@");
using(new NamedLock(lockname))
{
Stream stream = HFile.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryFormatter bFormatter = new BinaryFormatter();
{
if(ver != null)
{
try
{
Ver sver = (Ver)bFormatter.Deserialize(stream);
if(sver.ver != ver.Value)
{
stream.Close();
objs = null;
return false;
}
}
catch(Exception)
{
stream.Close();
objs = null;
return false;
}
}
}
{
System.Int32 count = (System.Int32)bFormatter.Deserialize(stream);
objs = new object[count];
for(int i = 0; i < count; i++)
{
objs[i] = bFormatter.Deserialize(stream);
}
}
stream.Close();
}
return true;
}
public static T Deserialize<T>(string filename, int? ver)
{
object[] objs;
HDebug.Verify(_Deserialize(filename, ver, out objs));
HDebug.Assert(objs.Length == 1);
return (T)objs[0];
}
//public static bool DeserializeIfExist<T>(string filename, int? ver, out T obj)
//{
// if(HFile.Exists(filename) == false)
// {
// obj = default(T);
// return false;
// }
// return Deserialize(filename, ver, out obj);
//}
//public static bool Deserialize<T>(string filename, int? ver, out T obj)
//{
// object[] objs;
// if(Deserialize(filename, ver, out objs) == false)
// {
// obj = default(T);
// return false;
// }
// HDebug.Assert(objs.Length == 1);
// obj = (T)objs[0];
// return true;
//}
//public static bool Deserialize<T1, T2>(string filename, int? ver, out T1 obj1, out T2 obj2)
//{
// object[] objs;
// if(Deserialize(filename, ver, out objs) == false)
// {
// obj1 = default(T1);
// obj2 = default(T2);
// return false;
// }
// HDebug.Assert(objs.Length == 2);
// obj1 = (T1)objs[0];
// obj2 = (T2)objs[1];
// return true;
//}
//public static bool Deserialize<T1, T2, T3>(string filename, int? ver, out T1 obj1, out T2 obj2, out T3 obj3)
//{
// object[] objs;
// if(Deserialize(filename, ver, out objs) == false)
// {
// obj1 = default(T1);
// obj2 = default(T2);
// obj3 = default(T3);
// return false;
// }
// HDebug.Assert(objs.Length == 3);
// obj1 = (T1)objs[0];
// obj2 = (T2)objs[1];
// obj3 = (T3)objs[2];
// return true;
//}
//public static bool Deserialize<T1, T2, T3, T4>(string filename, int? ver, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4)
//{
// object[] objs;
// if(Deserialize(filename, ver, out objs) == false)
// {
// obj1 = default(T1);
// obj2 = default(T2);
// obj3 = default(T3);
// obj4 = default(T4);
// return false;
// }
// HDebug.Assert(objs.Length == 4);
// obj1 = (T1)objs[0];
// obj2 = (T2)objs[1];
// obj3 = (T3)objs[2];
// obj4 = (T4)objs[3];
// return true;
//}
//public static bool Deserialize<T1, T2, T3, T4, T5>(string filename, int? ver, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4, out T5 obj5)
//{
// object[] objs;
// if(Deserialize(filename, ver, out objs) == false)
// {
// obj1 = default(T1);
// obj2 = default(T2);
// obj3 = default(T3);
// obj4 = default(T4);
// obj5 = default(T5);
// return false;
// }
// HDebug.Assert(objs.Length == 5);
// obj1 = (T1)objs[0];
// obj2 = (T2)objs[1];
// obj3 = (T3)objs[2];
// obj4 = (T4)objs[3];
// obj5 = (T5)objs[4];
// return true;
//}
public static bool Deserialize<T0 >(string filename, int? ver, out T0 obj0 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); return false; } HDebug.Assert(objs.Length == 1); obj0 = (T0)objs[0]; return true; }
public static bool Deserialize<T0, T1 >(string filename, int? ver, out T0 obj0, out T1 obj1 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); return false; } HDebug.Assert(objs.Length == 2); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; return true; }
public static bool Deserialize<T0, T1, T2 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); return false; } HDebug.Assert(objs.Length == 3); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; return true; }
public static bool Deserialize<T0, T1, T2, T3 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); return false; } HDebug.Assert(objs.Length == 4); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; return true; }
public static bool Deserialize<T0, T1, T2, T3, T4 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); obj4 = default(T4); return false; } HDebug.Assert(objs.Length == 5); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; obj4 = (T4)objs[4]; return true; }
public static bool Deserialize<T0, T1, T2, T3, T4, T5 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4, out T5 obj5 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); obj4 = default(T4); obj5 = default(T5); return false; } HDebug.Assert(objs.Length == 6); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; obj4 = (T4)objs[4]; obj5 = (T5)objs[5]; return true; }
public static bool Deserialize<T0, T1, T2, T3, T4, T5, T6 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4, out T5 obj5, out T6 obj6 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); obj4 = default(T4); obj5 = default(T5); obj6 = default(T6); return false; } HDebug.Assert(objs.Length == 7); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; obj4 = (T4)objs[4]; obj5 = (T5)objs[5]; obj6 = (T6)objs[6]; return true; }
public static bool Deserialize<T0, T1, T2, T3, T4, T5, T6, T7 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4, out T5 obj5, out T6 obj6, out T7 obj7 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); obj4 = default(T4); obj5 = default(T5); obj6 = default(T6); obj7 = default(T7); return false; } HDebug.Assert(objs.Length == 8); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; obj4 = (T4)objs[4]; obj5 = (T5)objs[5]; obj6 = (T6)objs[6]; obj7 = (T7)objs[7]; return true; }
public static bool Deserialize<T0, T1, T2, T3, T4, T5, T6, T7, T8 >(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4, out T5 obj5, out T6 obj6, out T7 obj7, out T8 obj8 ) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); obj4 = default(T4); obj5 = default(T5); obj6 = default(T6); obj7 = default(T7); obj8 = default(T8); return false; } HDebug.Assert(objs.Length == 9); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; obj4 = (T4)objs[4]; obj5 = (T5)objs[5]; obj6 = (T6)objs[6]; obj7 = (T7)objs[7]; obj8 = (T8)objs[8]; return true; }
public static bool Deserialize<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(string filename, int? ver, out T0 obj0, out T1 obj1, out T2 obj2, out T3 obj3, out T4 obj4, out T5 obj5, out T6 obj6, out T7 obj7, out T8 obj8, out T9 obj9) { object[] objs; if(_Deserialize(filename, ver, out objs) == false) { obj0 = default(T0); obj1 = default(T1); obj2 = default(T2); obj3 = default(T3); obj4 = default(T4); obj5 = default(T5); obj6 = default(T6); obj7 = default(T7); obj8 = default(T8); obj9 = default(T9); return false; } HDebug.Assert(objs.Length == 10); obj0 = (T0)objs[0]; obj1 = (T1)objs[1]; obj2 = (T2)objs[2]; obj3 = (T3)objs[3]; obj4 = (T4)objs[4]; obj5 = (T5)objs[5]; obj6 = (T6)objs[6]; obj7 = (T7)objs[7]; obj8 = (T8)objs[8]; obj9 = (T9)objs[9]; return true; }
}
}
| |
using System;
using Xunit;
using Medo.Math;
namespace Tests.Medo.Math {
public class ExponentialMovingAverageTests {
[Fact(DisplayName = "ExponentialMovingAverage: Example (1)")]
public void Example1() {
var stats = new ExponentialMovingAverage();
stats.Add(4);
stats.Add(7);
stats.Add(13);
stats.Add(16);
Assert.Equal(4, stats.Count);
Assert.Equal(7.885800150262959, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (2)")]
public void Example2() {
var stats = new ExponentialMovingAverage();
stats.Add(100000004);
stats.Add(100000007);
stats.Add(100000013);
stats.Add(100000016);
Assert.Equal(4, stats.Count);
Assert.Equal(100000007.88580015, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (3)")]
public void Example3() {
var stats = new ExponentialMovingAverage();
stats.Add(1000000004);
stats.Add(1000000007);
stats.Add(1000000013);
stats.Add(1000000016);
Assert.Equal(4, stats.Count);
Assert.Equal(1000000007.8858002, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (4)")]
public void Example4() {
var stats = new ExponentialMovingAverage();
stats.Add(6);
stats.Add(2);
stats.Add(3);
stats.Add(1);
Assert.Equal(4, stats.Count);
Assert.Equal(4.157776108189332, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (5)")]
public void Example5() {
var stats = new ExponentialMovingAverage(new double[] { 2, 2, 5, 7 });
Assert.Equal(4, stats.Count);
Assert.Equal(3.355371900826446, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (6)")]
public void Example6() {
var stats = new ExponentialMovingAverage();
stats.AddRange(new double[] { 2, 4, 4, 4, 5, 5, 7, 9 });
Assert.Equal(8, stats.Count);
Assert.Equal(5.085784386045568, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (7)")]
public void Example7() {
var stats = new ExponentialMovingAverage();
stats.AddRange(new double[] { 9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4 });
Assert.Equal(20, stats.Count);
Assert.Equal(6.929979179740536, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (8)")]
public void Example8() {
var stats = new ExponentialMovingAverage();
stats.AddRange(new double[] { 51.3, 55.6, 49.9, 52.0 });
Assert.Equal(4, stats.Count);
Assert.Equal(51.74237415477084, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (9)")]
public void Example9() {
var stats = new ExponentialMovingAverage();
stats.AddRange(new double[] { -5, -3, -1, 1, 3 });
Assert.Equal(5, stats.Count);
Assert.Equal(-1.966873847414794, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (10)")]
public void Example10() {
var stats = new ExponentialMovingAverage();
stats.AddRange(new double[] { -1, 0, 1 });
Assert.Equal(3, stats.Count);
Assert.Equal(-0.487603305785124, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (11)")]
public void Example11() {
var stats = new ExponentialMovingAverage(3);
stats.Add(4);
stats.Add(7);
stats.Add(13);
stats.Add(16);
Assert.Equal(4, stats.Count);
Assert.Equal(12.625, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (12)")]
public void Example12() {
var stats = new ExponentialMovingAverage(3);
stats.Add(100000004);
stats.Add(100000007);
stats.Add(100000013);
stats.Add(100000016);
Assert.Equal(4, stats.Count);
Assert.Equal(100000012.625, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (13)")]
public void Example13() {
var stats = new ExponentialMovingAverage(3);
stats.Add(1000000004);
stats.Add(1000000007);
stats.Add(1000000013);
stats.Add(1000000016);
Assert.Equal(4, stats.Count);
Assert.Equal(1000000012.625, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (14)")]
public void Example14() {
var stats = new ExponentialMovingAverage(3);
stats.Add(6);
stats.Add(2);
stats.Add(3);
stats.Add(1);
Assert.Equal(4, stats.Count);
Assert.Equal(2.25, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (15)")]
public void Example15() {
var stats = new ExponentialMovingAverage(3, new double[] { 2, 2, 5, 7 });
Assert.Equal(4, stats.Count);
Assert.Equal(5.25, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (16)")]
public void Example16() {
var stats = new ExponentialMovingAverage(3);
stats.AddRange(new double[] { 2, 4, 4, 4, 5, 5, 7, 9 });
Assert.Equal(8, stats.Count);
Assert.Equal(7.421875, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (17)")]
public void Example17() {
var stats = new ExponentialMovingAverage(3);
stats.AddRange(new double[] { 9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4 });
Assert.Equal(20, stats.Count);
Assert.Equal(6.044046401977539, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (18)")]
public void Example18() {
var stats = new ExponentialMovingAverage(3);
stats.AddRange(new double[] { 51.3, 55.6, 49.9, 52.0 });
Assert.Equal(4, stats.Count);
Assert.Equal(51.8375, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (19)")]
public void Example19() {
var stats = new ExponentialMovingAverage(3);
stats.AddRange(new double[] { -5, -3, -1, 1, 3 });
Assert.Equal(5, stats.Count);
Assert.Equal(1.125, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (20)")]
public void Example20() {
var stats = new ExponentialMovingAverage(3);
stats.AddRange(new double[] { -1, 0, 1 });
Assert.Equal(3, stats.Count);
Assert.Equal(0.25, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (21)")]
public void Example21() {
var stats = new ExponentialMovingAverage(0.1);
stats.Add(4);
stats.Add(7);
stats.Add(13);
stats.Add(16);
Assert.Equal(4, stats.Count);
Assert.Equal(6.253, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (22)")]
public void Example22() {
var stats = new ExponentialMovingAverage(0.1);
stats.Add(100000004);
stats.Add(100000007);
stats.Add(100000013);
stats.Add(100000016);
Assert.Equal(4, stats.Count);
Assert.Equal(100000006.253, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (23)")]
public void Example23() {
var stats = new ExponentialMovingAverage(0.1);
stats.Add(1000000004);
stats.Add(1000000007);
stats.Add(1000000013);
stats.Add(1000000016);
Assert.Equal(4, stats.Count);
Assert.Equal(1000000006.253, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (24)")]
public void Example24() {
var stats = new ExponentialMovingAverage(0.1);
stats.Add(6);
stats.Add(2);
stats.Add(3);
stats.Add(1);
Assert.Equal(4, stats.Count);
Assert.Equal(4.906, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (25)")]
public void Example25() {
var stats = new ExponentialMovingAverage(0.1, new double[] { 2, 2, 5, 7 });
Assert.Equal(4, stats.Count);
Assert.Equal(2.77, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (26)")]
public void Example26() {
var stats = new ExponentialMovingAverage(0.1);
stats.AddRange(new double[] { 2, 4, 4, 4, 5, 5, 7, 9 });
Assert.Equal(8, stats.Count);
Assert.Equal(3.9673062, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (27)")]
public void Example27() {
var stats = new ExponentialMovingAverage(0.1);
stats.AddRange(new double[] { 9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4 });
Assert.Equal(20, stats.Count);
Assert.Equal(7.239007925922224, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (28)")]
public void Example28() {
var stats = new ExponentialMovingAverage(0.1);
stats.AddRange(new double[] { 51.3, 55.6, 49.9, 52.0 });
Assert.Equal(4, stats.Count);
Assert.Equal(51.592299999999994, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (29)")]
public void Example29() {
var stats = new ExponentialMovingAverage(0.1);
stats.AddRange(new double[] { -5, -3, -1, 1, 3 });
Assert.Equal(5, stats.Count);
Assert.Equal(-3.1902, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (30)")]
public void Example30() {
var stats = new ExponentialMovingAverage(0.1);
stats.AddRange(new double[] { -1, 0, 1 });
Assert.Equal(3, stats.Count);
Assert.Equal(-0.71, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (31)")]
public void Example31() {
var stats = new ExponentialMovingAverage(0.9);
stats.Add(4);
stats.Add(7);
stats.Add(13);
stats.Add(16);
Assert.Equal(4, stats.Count);
Assert.Equal(15.637, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (32)")]
public void Example32() {
var stats = new ExponentialMovingAverage(0.9);
stats.Add(100000004);
stats.Add(100000007);
stats.Add(100000013);
stats.Add(100000016);
Assert.Equal(4, stats.Count);
Assert.Equal(100000015.63700001, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (33)")]
public void Example33() {
var stats = new ExponentialMovingAverage(0.9);
stats.Add(1000000004);
stats.Add(1000000007);
stats.Add(1000000013);
stats.Add(1000000016);
Assert.Equal(4, stats.Count);
Assert.Equal(1000000015.637, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (34)")]
public void Example34() {
var stats = new ExponentialMovingAverage(0.9);
stats.Add(6);
stats.Add(2);
stats.Add(3);
stats.Add(1);
Assert.Equal(4, stats.Count);
Assert.Equal(1.194, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (35)")]
public void Example35() {
var stats = new ExponentialMovingAverage(0.9, new double[] { 2, 2, 5, 7 });
Assert.Equal(4, stats.Count);
Assert.Equal(6.77, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (36)")]
public void Example36() {
var stats = new ExponentialMovingAverage(0.9);
stats.AddRange(new double[] { 2, 4, 4, 4, 5, 5, 7, 9 });
Assert.Equal(8, stats.Count);
Assert.Equal(8.7798998, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (37)")]
public void Example37() {
var stats = new ExponentialMovingAverage(0.9);
stats.AddRange(new double[] { 9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4 });
Assert.Equal(20, stats.Count);
Assert.Equal(4.473041622661694, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (38)")]
public void Example38() {
var stats = new ExponentialMovingAverage(0.9);
stats.AddRange(new double[] { 51.3, 55.6, 49.9, 52.0 });
Assert.Equal(4, stats.Count);
Assert.Equal(51.8427, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (39)")]
public void Example39() {
var stats = new ExponentialMovingAverage(0.9);
stats.AddRange(new double[] { -5, -3, -1, 1, 3 });
Assert.Equal(5, stats.Count);
Assert.Equal(2.7778, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: Example (40)")]
public void Example40() {
var stats = new ExponentialMovingAverage(0.9);
stats.AddRange(new double[] { -1, 0, 1 });
Assert.Equal(3, stats.Count);
Assert.Equal(0.89, stats.Average, 15);
}
[Fact(DisplayName = "ExponentialMovingAverage: No values")]
public void NoValue() {
var stats = new ExponentialMovingAverage();
Assert.Equal(0, stats.Count);
Assert.Equal(double.NaN, stats.Average);
}
[Fact(DisplayName = "ExponentialMovingAverage: One value")]
public void OneValue() {
var stats = new ExponentialMovingAverage();
stats.Add(1);
Assert.Equal(1, stats.Count);
Assert.Equal(1, stats.Average);
}
[Fact(DisplayName = "ExponentialMovingAverage: No infinities")]
public void NoInfinity() {
var stats = new ExponentialMovingAverage();
Assert.Throws<ArgumentOutOfRangeException>(delegate {
stats.Add(double.NegativeInfinity);
});
Assert.Throws<ArgumentOutOfRangeException>(delegate {
stats.Add(double.PositiveInfinity);
});
Assert.Throws<ArgumentOutOfRangeException>(delegate {
stats.Add(double.NaN);
});
}
[Fact(DisplayName = "ExponentialMovingAverage: No null collection")]
public void NoNullCollection() {
Assert.Throws<ArgumentNullException>(delegate {
var stats = new ExponentialMovingAverage(null);
});
Assert.Throws<ArgumentNullException>(delegate {
var stats = new ExponentialMovingAverage(10, null);
});
Assert.Throws<ArgumentNullException>(delegate {
var stats = new ExponentialMovingAverage(0.0, null);
});
Assert.Throws<ArgumentNullException>(delegate {
var stats = new ExponentialMovingAverage();
stats.AddRange(null);
});
}
[Fact(DisplayName = "ExponentialMovingAverage: No count out of range")]
public void NoCountOutOfRange() {
Assert.Throws<ArgumentOutOfRangeException>(delegate {
var stats = new ExponentialMovingAverage(0);
});
Assert.Throws<ArgumentOutOfRangeException>(delegate {
var stats = new ExponentialMovingAverage(0, new double[] { 0 });
});
}
[Fact(DisplayName = "ExponentialMovingAverage: No smoothing out of range")]
public void NoSmoothingOutOfRange() {
Assert.Throws<ArgumentOutOfRangeException>(delegate {
var stats = new ExponentialMovingAverage(0 - double.Epsilon);
});
Assert.Throws<ArgumentOutOfRangeException>(delegate {
var stats = new ExponentialMovingAverage(1.001);
});
Assert.Throws<ArgumentOutOfRangeException>(delegate {
var stats = new ExponentialMovingAverage(0 - double.Epsilon, new double[] { 0 });
});
Assert.Throws<ArgumentOutOfRangeException>(delegate {
var stats = new ExponentialMovingAverage(1.001, new double[] { 0 });
});
}
}
}
| |
/*
Copyright (c) 2010 - 2012 Jordan "Earlz/hckr83" Earls <http://lastyearswishes.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
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. 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 ``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.
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Earlz.LucidMVC.ViewEngine;
using System.Linq;
using Earlz.LucidMVC.Authentication;
using System.Collections.ObjectModel;
using Earlz.LucidMVC.Caching;
namespace Earlz.LucidMVC
{
public delegate ILucidView HandlerInvoker<T>(T httphandler) where T:HttpController;
public delegate T HandlerCreator<T>(Router r) where T:HttpController;
public delegate ICacheMechanism CacheMechanismRetriever();
/**The routing engine of EFramework.
* This is a simple, but powerful router utilizing simple route pattern matching and lambdas for initializing the HttpHandler for a request.**/
public class Router
{
static Router()
{
GetCacher=() => new ASPCacheMechanism(); //default to ASP.Net
}
/// <summary>
/// Gets a new or existing ICacheMechanism
/// Defaults to getting a new ASPCacheMechanism
/// </summary>
public static CacheMechanismRetriever GetCacher
{
get;
set;
}
protected IList<Route> Routes
{
get;
private set;
}
public Route[] GetRoutes()
{
return Routes.ToArray();
}
public Router()
{
Routes=new List<Route>();
}
public virtual void AddRoute(Route r)
{
Routes.Add(r);
}
public virtual ControllerBox<T, object> Controller<T>(ControllerCreator<T> creator) where T:HttpController
{
return new ControllerBox<T, object>(this, creator);
}
public virtual ControllerBox<T, object> Controller<T>(ControllerCreator<T> creator, string root) where T:HttpController
{
return new ControllerBox<T, object>(this, creator, root);
}
bool CheckValidators(IEnumerable<RouteParamsMustMatch> validators, ParameterDictionary d)
{
if (validators == null)
{
return true; //exit early if possible
}
foreach(var v in validators)
{
if(v(d) == false)
{
return false;
}
}
return true;
}
public virtual bool Execute(IServerContext context)
{
var defaultallowed=new string[]{"get"};
foreach(var route in Routes)
{
if(route.Pattern==null) continue;
var allowed=route.AllowedMethods ?? defaultallowed;
var match=route.Pattern.Match(context.RequestUrl.AbsolutePath);
if(match.IsMatch &&
allowed.Any(x=>x.ToLower()==context.HttpMethod.ToLower()) &&
CheckValidators(route.ParameterValidators, match.Params))
{
var request=new RequestContext(context, this, route, match.Params);
bool skip=false;
var view=route.Responder(request, ref skip);
if(view==null)
{
throw new NotSupportedException("The returned view from a controller must not be null!");
}
if(!skip)
{
view.RenderView(context.Writer);
return true;
}
}
}
return false;
}
/// <summary>
/// Adds a route to the router
/// </summary>
///
/*
public void AddRoute<T>(HttpMethod method, string pattern, HandlerCreator<T> creator, HandlerInvoker<T> invoker) where T:HttpHandl
{
//var r=new Route{Pattern=new SimplePattern(pattern), Invoker=handler, ID=id, Method=method};
//Routes.Add(r);
}*/
/*
public void AddRoute(string id,HttpMethod method, IPatternMatcher pattern, HandlerInvoker handler)
{
var r=new Route{Pattern=pattern, ID=id, Invoker=handler, Method=method};
Routes.Add(r);
}
/// <summary>
/// Adds a route to the router which requires authentication
/// </summary>
public void AddSecureRoute(string id, HttpMethod method, IPatternMatcher pattern, HandlerInvoker handler)
{
var r=new Route{Pattern=pattern, ID=id, Invoker=handler, Method=method, Secure=true};
Routes.Add(r);
}
public void AddSecureRoute(string id, HttpMethod method, string pattern, HandlerInvoker invoker)
{
var r=new Route{Pattern=new SimplePattern(pattern), Invoker=invoker, ID=id, Method=method, Secure=true};
Routes.Add(r);
}
*/
void DoHandler (Route r,IServerContext c,ParameterDictionary p)
{
/*
HttpHandler.RouteRequest=r;
HttpHandler.Method=c.SaneHttpMethod();
HttpHandler.RawRouteParams=p;
CallMethod(c, r.Invoker);
*/
}
/*
/// <summary>
/// Handles the current request
/// </summary>
public bool DoRoute(IServerContext c){
bool foundwrongmethod=false;
foreach(var r in Routes){
if(r.Pattern.IsMatch(c.RequestUrl.AbsolutePath))
{
var m=c.SaneHttpMethod();
if(r.Method == HttpMethod.Any || m==r.Method ||
(r.Method==HttpMethod.Get && m==HttpMethod.Head))
{
if(r.Secure)
{
FSCAuth.RequiresLogin();
}
DoHandler(r, c, r.Pattern.Params);
return true;
}else
{
foundwrongmethod=true;
}
}
}
if(foundwrongmethod)
{
throw new HttpException(405, "Method not allowed");;
}
return false;
}
void CallMethod<T>(IServerContext context, HandlerInvoker<T> invoker) where T:HttpController
{
ILucidView view=invoker(null);//HttpHandler.RawRouteParams, HttpHandler.Form.ToParameters());
int length=0;
var r=context.Writer;
if(view!=null){
//even if "directly-rendered", if ignoring the view, it won't really be rendered
var s=view.RenderView();
length+=s.Length;
if(!view.RenderedDirectly){
r.Write(s);
}
}
}
*/
}
/*example fluent API usage:
*
* Router.Route("/foo").
* IsHandledBy((r) => new MyHandler(r), (h) => h.Foo()).
* Accepts(HttpMethod.Get).
* AlsoIncludes("/foobar").
* AlsoIncludes("/{a}/{b}").
* RouteParam("a").MustBe(GroupMatchType.Integer).
* RouteParam("a").MustMatch("/someregex/").
* RedirectFrom("/foo/oldurl").
* IsProtected
*
*
* ORRRRR
* (if this is possible!)
* var blog=Router.Controller((r) => new BlogHandler(r));
* blog.Handles("/blog/view/{foo}").With((h) => h.Viewblog());
* blog.Handles("/blog/new").
* With((h) => h.New()).
* IsProtected().
* AlsoIncludes("/new").
* Accepts(HttpMethod.Get | HttpMethod.Post);
*
* */
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Storage.Queue;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Providers.Streams.AzureQueue;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Serialization;
using Orleans.Streams;
using TestExtensions;
using Xunit;
using Xunit.Abstractions;
using Orleans.Internal;
namespace Tester.AzureUtils.Streaming
{
[Collection(TestEnvironmentFixture.DefaultCollection)]
[TestCategory("Azure"), TestCategory("Streaming")]
public class AzureQueueAdapterTests : AzureStorageBasicTests, IDisposable
{
private readonly ITestOutputHelper output;
private readonly TestEnvironmentFixture fixture;
private const int NumBatches = 20;
private const int NumMessagesPerBatch = 20;
public static readonly string AZURE_QUEUE_STREAM_PROVIDER_NAME = "AQAdapterTests";
private readonly ILoggerFactory loggerFactory;
private static readonly SafeRandom Random = new SafeRandom();
private static List<string> azureQueueNames = AzureQueueUtilities.GenerateQueueNames($"AzureQueueAdapterTests-{Guid.NewGuid()}", 8);
public AzureQueueAdapterTests(ITestOutputHelper output, TestEnvironmentFixture fixture)
{
this.output = output;
this.fixture = fixture;
this.loggerFactory = this.fixture.Services.GetService<ILoggerFactory>();
BufferPool.InitGlobalBufferPool(new SiloMessagingOptions());
}
public void Dispose()
{
if (!string.IsNullOrWhiteSpace(TestDefaultConfiguration.DataConnectionString))
{
AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(this.loggerFactory, azureQueueNames, TestDefaultConfiguration.DataConnectionString).Wait();
}
}
[SkippableFact, TestCategory("Functional"), TestCategory("Halo")]
public async Task SendAndReceiveFromAzureQueue()
{
var options = new AzureQueueOptions
{
ConnectionString = TestDefaultConfiguration.DataConnectionString,
MessageVisibilityTimeout = TimeSpan.FromSeconds(30),
QueueNames = azureQueueNames
};
var serializationManager = this.fixture.Services.GetService<SerializationManager>();
var clusterOptions = this.fixture.Services.GetRequiredService<IOptions<ClusterOptions>>();
var queueCacheOptions = new SimpleQueueCacheOptions();
var queueDataAdapter = new AzureQueueDataAdapterV2(serializationManager);
var adapterFactory = new AzureQueueAdapterFactory(
AZURE_QUEUE_STREAM_PROVIDER_NAME,
options,
queueCacheOptions,
queueDataAdapter,
this.fixture.Services,
clusterOptions,
serializationManager,
loggerFactory);
adapterFactory.Init();
await SendAndReceiveFromQueueAdapter(adapterFactory);
}
private async Task SendAndReceiveFromQueueAdapter(IQueueAdapterFactory adapterFactory)
{
IQueueAdapter adapter = await adapterFactory.CreateAdapter();
IQueueAdapterCache cache = adapterFactory.GetQueueAdapterCache();
// Create receiver per queue
IStreamQueueMapper mapper = adapterFactory.GetStreamQueueMapper();
Dictionary<QueueId, IQueueAdapterReceiver> receivers = mapper.GetAllQueues().ToDictionary(queueId => queueId, adapter.CreateReceiver);
Dictionary<QueueId, IQueueCache> caches = mapper.GetAllQueues().ToDictionary(queueId => queueId, cache.CreateQueueCache);
await Task.WhenAll(receivers.Values.Select(receiver => receiver.Initialize(TimeSpan.FromSeconds(5))));
// test using 2 streams
Guid streamId1 = Guid.NewGuid();
Guid streamId2 = Guid.NewGuid();
int receivedBatches = 0;
var streamsPerQueue = new ConcurrentDictionary<QueueId, HashSet<IStreamIdentity>>();
// reader threads (at most 2 active queues because only two streams)
var work = new List<Task>();
foreach( KeyValuePair<QueueId, IQueueAdapterReceiver> receiverKvp in receivers)
{
QueueId queueId = receiverKvp.Key;
var receiver = receiverKvp.Value;
var qCache = caches[queueId];
Task task = Task.Factory.StartNew(() =>
{
while (receivedBatches < NumBatches)
{
var messages = receiver.GetQueueMessagesAsync(CloudQueueMessage.MaxNumberOfMessagesToPeek).Result.ToArray();
if (!messages.Any())
{
continue;
}
foreach (IBatchContainer message in messages)
{
streamsPerQueue.AddOrUpdate(queueId,
id => new HashSet<IStreamIdentity> { new StreamIdentity(message.StreamGuid, message.StreamGuid.ToString()) },
(id, set) =>
{
set.Add(new StreamIdentity(message.StreamGuid, message.StreamGuid.ToString()));
return set;
});
this.output.WriteLine("Queue {0} received message on stream {1}", queueId,
message.StreamGuid);
Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents<int>().Count()); // "Half the events were ints"
Assert.Equal(NumMessagesPerBatch / 2, message.GetEvents<string>().Count()); // "Half the events were strings"
}
Interlocked.Add(ref receivedBatches, messages.Length);
qCache.AddToCache(messages);
}
});
work.Add(task);
}
// send events
List<object> events = CreateEvents(NumMessagesPerBatch);
work.Add(Task.Factory.StartNew(() => Enumerable.Range(0, NumBatches)
.Select(i => i % 2 == 0 ? streamId1 : streamId2)
.ToList()
.ForEach(streamId =>
adapter.QueueMessageBatchAsync(streamId, streamId.ToString(),
events.Take(NumMessagesPerBatch).ToArray(), null, RequestContextExtensions.Export(this.fixture.SerializationManager)).Wait())));
await Task.WhenAll(work);
// Make sure we got back everything we sent
Assert.Equal(NumBatches, receivedBatches);
// check to see if all the events are in the cache and we can enumerate through them
StreamSequenceToken firstInCache = new EventSequenceTokenV2(0);
foreach (KeyValuePair<QueueId, HashSet<IStreamIdentity>> kvp in streamsPerQueue)
{
var receiver = receivers[kvp.Key];
var qCache = caches[kvp.Key];
foreach (IStreamIdentity streamGuid in kvp.Value)
{
// read all messages in cache for stream
IQueueCacheCursor cursor = qCache.GetCacheCursor(streamGuid, firstInCache);
int messageCount = 0;
StreamSequenceToken tenthInCache = null;
StreamSequenceToken lastToken = firstInCache;
while (cursor.MoveNext())
{
Exception ex;
messageCount++;
IBatchContainer batch = cursor.GetCurrent(out ex);
this.output.WriteLine("Token: {0}", batch.SequenceToken);
Assert.True(batch.SequenceToken.CompareTo(lastToken) >= 0, $"order check for event {messageCount}");
lastToken = batch.SequenceToken;
if (messageCount == 10)
{
tenthInCache = batch.SequenceToken;
}
}
this.output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid);
Assert.Equal(NumBatches / 2, messageCount);
Assert.NotNull(tenthInCache);
// read all messages from the 10th
cursor = qCache.GetCacheCursor(streamGuid, tenthInCache);
messageCount = 0;
while (cursor.MoveNext())
{
messageCount++;
}
this.output.WriteLine("On Queue {0} we received a total of {1} message on stream {2}", kvp.Key, messageCount, streamGuid);
const int expected = NumBatches / 2 - 10 + 1; // all except the first 10, including the 10th (10 + 1)
Assert.Equal(expected, messageCount);
}
}
}
private List<object> CreateEvents(int count)
{
return Enumerable.Range(0, count).Select(i =>
{
if (i % 2 == 0)
{
return Random.Next(int.MaxValue) as object;
}
return Random.Next(int.MaxValue).ToString(CultureInfo.InvariantCulture);
}).ToList();
}
internal static string MakeClusterId()
{
const string DeploymentIdFormat = "cluster-{0}";
string now = DateTime.UtcNow.ToString("yyyy-MM-dd-hh-mm-ss-ffff");
return string.Format(DeploymentIdFormat, now);
}
}
}
| |
#region License
/* The MIT License
*
* Copyright (c) 2011 Red Badger Consulting
*
* 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
namespace RedBadger.Xpf.Controls
{
using System;
using RedBadger.Xpf.Controls.Primitives;
using RedBadger.Xpf.Internal;
using RedBadger.Xpf.Internal.Controls;
public class ScrollContentPresenter : ContentControl, IScrollInfo
{
private bool isClippingRequired;
private ScrollData scrollData;
public ScrollContentPresenter()
{
this.scrollData.CanHorizontallyScroll = true;
this.scrollData.CanVerticallyScroll = true;
}
public bool CanHorizontallyScroll
{
get
{
return this.scrollData.CanHorizontallyScroll;
}
set
{
this.scrollData.CanHorizontallyScroll = value;
}
}
public bool CanVerticallyScroll
{
get
{
return this.scrollData.CanVerticallyScroll;
}
set
{
this.scrollData.CanVerticallyScroll = value;
}
}
public Size Extent
{
get
{
return this.scrollData.Extent;
}
}
public Vector Offset
{
get
{
return this.scrollData.Offset;
}
}
public Size Viewport
{
get
{
return this.scrollData.Viewport;
}
}
public void SetHorizontalOffset(double offset)
{
if (!this.CanHorizontallyScroll)
{
return;
}
if (double.IsNaN(offset))
{
throw new ArgumentOutOfRangeException("offset");
}
offset = Math.Max(0d, offset);
if (this.scrollData.Offset.X.IsDifferentFrom(offset))
{
this.scrollData.Offset.X = offset;
this.InvalidateArrange();
}
}
public void SetVerticalOffset(double offset)
{
if (!this.CanVerticallyScroll)
{
return;
}
if (double.IsNaN(offset))
{
throw new ArgumentOutOfRangeException("offset");
}
offset = Math.Max(0d, offset);
if (this.scrollData.Offset.Y.IsDifferentFrom(offset))
{
this.scrollData.Offset.Y = offset;
this.InvalidateArrange();
}
}
protected override Size ArrangeOverride(Size finalSize)
{
IElement content = this.Content;
this.UpdateScrollData(finalSize, this.scrollData.Extent);
if (content != null)
{
var finalRect = new Rect(
-this.scrollData.Offset.X,
-this.scrollData.Offset.Y,
content.DesiredSize.Width,
content.DesiredSize.Height);
this.isClippingRequired = finalSize.Width.IsLessThan(finalRect.Width) ||
finalSize.Height.IsLessThan(finalRect.Height);
finalRect.Width = Math.Max(finalRect.Width, finalSize.Width);
finalRect.Height = Math.Max(finalRect.Height, finalSize.Height);
content.Arrange(finalRect);
}
return finalSize;
}
protected override Rect GetClippingRect(Size finalSize)
{
return this.isClippingRequired ? new Rect(this.RenderSize) : Rect.Empty;
}
protected override Size MeasureOverride(Size availableSize)
{
IElement content = this.Content;
var desiredSize = new Size();
var extent = new Size();
if (content != null)
{
Size availableSizeForContent = availableSize;
if (this.scrollData.CanHorizontallyScroll)
{
availableSizeForContent.Width = double.PositiveInfinity;
}
if (this.scrollData.CanVerticallyScroll)
{
availableSizeForContent.Height = double.PositiveInfinity;
}
content.Measure(availableSizeForContent);
desiredSize = content.DesiredSize;
extent = content.DesiredSize;
}
this.UpdateScrollData(availableSize, extent);
desiredSize.Width = Math.Min(availableSize.Width, desiredSize.Width);
desiredSize.Height = Math.Min(availableSize.Height, desiredSize.Height);
return desiredSize;
}
private void UpdateScrollData(Size viewport, Size extent)
{
this.scrollData.Viewport = viewport;
this.scrollData.Extent = extent;
double x = this.scrollData.Offset.X.Coerce(
0d, this.scrollData.Extent.Width - this.scrollData.Viewport.Width);
double y = this.scrollData.Offset.Y.Coerce(
0d, this.scrollData.Extent.Height - this.scrollData.Viewport.Height);
this.scrollData.Offset = new Vector(x, y);
}
}
}
| |
// 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.
#if !ROTOR
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
#if CCINamespace
namespace Microsoft.Cci{
#else
namespace System.Compiler{
#endif
#if !FxCop
public
#endif
class GlobalAssemblyCache{
private GlobalAssemblyCache(){}
private static readonly object Lock = new object();
private static bool FusionLoaded;
#if CodeContracts
public static bool probeGAC = true;
#endif
/// <param name="codeBaseUri">Uri pointing to the assembly</param>
public static bool Contains(Uri codeBaseUri){
if (codeBaseUri == null) { Debug.Fail("codeBaseUri == null"); return false; }
lock(GlobalAssemblyCache.Lock){
if (!GlobalAssemblyCache.FusionLoaded){
GlobalAssemblyCache.FusionLoaded = true;
System.Reflection.Assembly systemAssembly = typeof(object).Assembly;
//^ assume systemAssembly != null && systemAssembly.Location != null;
string dir = Path.GetDirectoryName(systemAssembly.Location);
//^ assume dir != null;
GlobalAssemblyCache.LoadLibrary(Path.Combine(dir, "fusion.dll"));
}
IAssemblyEnum assemblyEnum;
int rc = GlobalAssemblyCache.CreateAssemblyEnum(out assemblyEnum, null, null, ASM_CACHE.GAC, 0);
if (rc < 0 || assemblyEnum == null) return false;
IApplicationContext applicationContext;
IAssemblyName currentName;
while (assemblyEnum.GetNextAssembly(out applicationContext, out currentName, 0) == 0){
//^ assume currentName != null;
AssemblyName assemblyName = new AssemblyName(currentName);
string scheme = codeBaseUri.Scheme;
if (scheme != null && assemblyName.CodeBase.StartsWith(scheme)){
try{
Uri foundUri = new Uri(assemblyName.CodeBase);
if (codeBaseUri.Equals(foundUri)) return true;
#if !FxCop
}catch(Exception){
#else
}finally{
#endif
}
}
}
return false;
}
}
/// <summary>
/// Returns the original location of the corresponding assembly if available, otherwise returns the location of the shadow copy.
/// If the corresponding assembly is not in the GAC, null is returned.
/// </summary>
public static string GetLocation(AssemblyReference assemblyReference){
#if CodeContracts
if (!probeGAC) return null;
#endif
if (assemblyReference == null) { Debug.Fail("assemblyReference == null"); return null; }
lock(GlobalAssemblyCache.Lock){
if (!GlobalAssemblyCache.FusionLoaded){
GlobalAssemblyCache.FusionLoaded = true;
System.Reflection.Assembly systemAssembly = typeof(object).Assembly;
//^ assume systemAssembly != null && systemAssembly.Location != null;
string dir = Path.GetDirectoryName(systemAssembly.Location);
//^ assume dir != null;
GlobalAssemblyCache.LoadLibrary(Path.Combine(dir, "fusion.dll"));
}
IAssemblyEnum assemblyEnum;
CreateAssemblyEnum(out assemblyEnum, null, null, ASM_CACHE.GAC, 0);
if (assemblyEnum == null) return null;
IApplicationContext applicationContext;
IAssemblyName currentName;
while (assemblyEnum.GetNextAssembly(out applicationContext, out currentName, 0) == 0){
//^ assume currentName != null;
AssemblyName aName = new AssemblyName(currentName);
if (assemblyReference.Matches(aName.Name, aName.Version, aName.Culture, aName.PublicKeyToken)){
string codeBase = aName.CodeBase;
if (codeBase != null && codeBase.StartsWith("file:///"))
return codeBase.Substring(8);
return aName.GetLocation();
}
}
return null;
}
}
[DllImport("kernel32.dll", CharSet=CharSet.Ansi)]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("fusion.dll", CharSet=CharSet.Auto)]
private static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, IApplicationContext pAppCtx, IAssemblyName pName, uint dwFlags, int pvReserved);
private class ASM_CACHE{
private ASM_CACHE(){}
public const uint ZAP = 1;
public const uint GAC = 2;
public const uint DOWNLOAD = 4;
}
}
internal class AssemblyName{
readonly IAssemblyName/*!*/ assemblyName;
internal AssemblyName(IAssemblyName/*!*/ assemblyName) {
this.assemblyName = assemblyName;
//^ base();
}
internal string/*!*/ Name {
//set {this.WriteString(ASM_NAME.NAME, value);}
get {return this.ReadString(ASM_NAME.NAME);}
}
internal Version Version{
//set{
// if (value == null) throw new ArgumentNullException();
// this.WriteUInt16(ASM_NAME.MAJOR_VERSION, (ushort)value.Major);
// this.WriteUInt16(ASM_NAME.MINOR_VERSION, (ushort)value.Minor);
// this.WriteUInt16(ASM_NAME.BUILD_NUMBER, (ushort)value.Build);
// this.WriteUInt16(ASM_NAME.REVISION_NUMBER, (ushort)value.Revision);
//}
get{
int major = this.ReadUInt16(ASM_NAME.MAJOR_VERSION);
int minor = this.ReadUInt16(ASM_NAME.MINOR_VERSION);
int build = this.ReadUInt16(ASM_NAME.BUILD_NUMBER);
int revision = this.ReadUInt16(ASM_NAME.REVISION_NUMBER);
return new Version(major, minor, build, revision);
}
}
internal string/*!*/ Culture {
//set {this.WriteString(ASM_NAME.CULTURE, value);}
get {return this.ReadString(ASM_NAME.CULTURE);}
}
internal byte[]/*!*/ PublicKeyToken {
//set {this.WriteBytes(ASM_NAME.PUBLIC_KEY_TOKEN, value); }
get {return this.ReadBytes(ASM_NAME.PUBLIC_KEY_TOKEN); }
}
internal string StrongName{
get{
uint size = 0;
this.assemblyName.GetDisplayName(null, ref size, (uint)AssemblyNameDisplayFlags.ALL);
if (size == 0) return "";
StringBuilder strongName = new StringBuilder((int)size);
this.assemblyName.GetDisplayName(strongName, ref size, (uint)AssemblyNameDisplayFlags.ALL);
return strongName.ToString();
}
}
internal string/*!*/ CodeBase {
//set {this.WriteString(ASM_NAME.CODEBASE_URL, value);}
get {return this.ReadString(ASM_NAME.CODEBASE_URL);}
}
public override string ToString(){
return this.StrongName;
}
internal string GetLocation(){
IAssemblyCache assemblyCache;
CreateAssemblyCache(out assemblyCache, 0);
if (assemblyCache == null) return null;
ASSEMBLY_INFO assemblyInfo = new ASSEMBLY_INFO();
assemblyInfo.cbAssemblyInfo = (uint)Marshal.SizeOf(typeof(ASSEMBLY_INFO));
assemblyCache.QueryAssemblyInfo(ASSEMBLYINFO_FLAG.VALIDATE | ASSEMBLYINFO_FLAG.GETSIZE, this.StrongName, ref assemblyInfo);
if (assemblyInfo.cbAssemblyInfo == 0) return null;
assemblyInfo.pszCurrentAssemblyPathBuf = new string(new char[assemblyInfo.cchBuf]);
assemblyCache.QueryAssemblyInfo(ASSEMBLYINFO_FLAG.VALIDATE | ASSEMBLYINFO_FLAG.GETSIZE, this.StrongName, ref assemblyInfo);
String value = assemblyInfo.pszCurrentAssemblyPathBuf;
return value;
}
private string/*!*/ ReadString(uint assemblyNameProperty) {
uint size = 0;
this.assemblyName.GetProperty(assemblyNameProperty, IntPtr.Zero, ref size);
if (size == 0 || size > Int16.MaxValue) return String.Empty;
IntPtr ptr = Marshal.AllocHGlobal((int) size);
this.assemblyName.GetProperty(assemblyNameProperty, ptr, ref size);
String str = Marshal.PtrToStringUni(ptr);
//^ assume str != null;
Marshal.FreeHGlobal(ptr);
return str;
}
private ushort ReadUInt16(uint assemblyNameProperty){
uint size = 0;
this.assemblyName.GetProperty(assemblyNameProperty, IntPtr.Zero, ref size);
IntPtr ptr = Marshal.AllocHGlobal((int) size);
this.assemblyName.GetProperty(assemblyNameProperty, ptr, ref size);
ushort value = (ushort)Marshal.ReadInt16(ptr);
Marshal.FreeHGlobal(ptr);
return value;
}
private byte[]/*!*/ ReadBytes(uint assemblyNameProperty) {
uint size = 0;
this.assemblyName.GetProperty(assemblyNameProperty, IntPtr.Zero, ref size);
IntPtr ptr = Marshal.AllocHGlobal((int) size);
this.assemblyName.GetProperty(assemblyNameProperty, ptr, ref size);
byte[] value = new byte[(int) size];
Marshal.Copy(ptr, value, 0, (int) size);
Marshal.FreeHGlobal(ptr);
return value;
}
//private void WriteString(uint assemblyNameProperty, string/*!*/ value){
// IntPtr ptr = Marshal.StringToHGlobalUni(value);
// this.assemblyName.SetProperty(assemblyNameProperty, ptr, (uint)((value.Length + 1) * 2));
// Marshal.FreeHGlobal(ptr);
//}
//private void WriteUInt16(uint assemblyNameProperty, ushort value){
// IntPtr ptr = Marshal.AllocHGlobal(2);
// Marshal.WriteInt16(ptr, (short)value);
// this.assemblyName.SetProperty(assemblyNameProperty, ptr, 2);
// Marshal.FreeHGlobal(ptr);
//}
//private void WriteBytes(uint assemblyNameProperty, Byte[]/*!*/ value) {
// int size = value.Length;
// IntPtr ptr = Marshal.AllocHGlobal(size);
// Marshal.Copy(value, 0, ptr, size);
// this.assemblyName.SetProperty(assemblyNameProperty, ptr, (uint)size);
// Marshal.FreeHGlobal(ptr);
//}
[DllImport("fusion.dll", CharSet=CharSet.Auto)]
private static extern int CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved);
private class CREATE_ASM_NAME_OBJ_FLAGS{
private CREATE_ASM_NAME_OBJ_FLAGS(){}
public const uint CANOF_PARSE_DISPLAY_NAME = 0x1;
public const uint CANOF_SET_DEFAULT_VALUES = 0x2;
}
private class ASM_NAME{
private ASM_NAME(){}
public const uint PUBLIC_KEY = 0;
public const uint PUBLIC_KEY_TOKEN = 1;
public const uint HASH_VALUE = 2;
public const uint NAME = 3;
public const uint MAJOR_VERSION = 4;
public const uint MINOR_VERSION = 5;
public const uint BUILD_NUMBER = 6;
public const uint REVISION_NUMBER = 7;
public const uint CULTURE = 8;
public const uint PROCESSOR_ID_ARRAY = 9;
public const uint OSINFO_ARRAY = 10;
public const uint HASH_ALGID = 11;
public const uint ALIAS = 12;
public const uint CODEBASE_URL = 13;
public const uint CODEBASE_LASTMOD = 14;
public const uint NULL_PUBLIC_KEY = 15;
public const uint NULL_PUBLIC_KEY_TOKEN = 16;
public const uint CUSTOM = 17;
public const uint NULL_CUSTOM = 18;
public const uint MVID = 19;
public const uint _32_BIT_ONLY = 20;
}
[Flags]
internal enum AssemblyNameDisplayFlags{
VERSION=0x01,
CULTURE=0x02,
PUBLIC_KEY_TOKEN=0x04,
PROCESSORARCHITECTURE=0x20,
RETARGETABLE=0x80,
ALL=VERSION | CULTURE | PUBLIC_KEY_TOKEN | PROCESSORARCHITECTURE | RETARGETABLE
}
private class ASSEMBLYINFO_FLAG {
private ASSEMBLYINFO_FLAG(){}
public const uint VALIDATE = 1;
public const uint GETSIZE = 2;
}
[StructLayout(LayoutKind.Sequential)]
private struct ASSEMBLY_INFO{
public uint cbAssemblyInfo;
public uint dwAssemblyFlags;
public ulong uliAssemblySizeInKB;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszCurrentAssemblyPathBuf;
public uint cchBuf;
}
[ComImport(), Guid("E707DCDE-D1CD-11D2-BAB9-00C04F8ECEAE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IAssemblyCache{
[PreserveSig()]
int UninstallAssembly(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, IntPtr pvReserved, int pulDisposition);
[PreserveSig()]
int QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref ASSEMBLY_INFO pAsmInfo);
[PreserveSig()]
int CreateAssemblyCacheItem(uint dwFlags, IntPtr pvReserved, out object ppAsmItem, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName);
[PreserveSig()]
int CreateAssemblyScavenger(out object ppAsmScavenger);
[PreserveSig()]
int InstallAssembly(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszManifestFilePath, IntPtr pvReserved);
}
}
[ComImport(), Guid("CD193BC0-B4BC-11D2-9833-00C04FC31D2E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAssemblyName{
[PreserveSig()]
int SetProperty(uint PropertyId, IntPtr pvProperty, uint cbProperty);
[PreserveSig()]
int GetProperty(uint PropertyId, IntPtr pvProperty, ref uint pcbProperty);
[PreserveSig()]
int Finalize();
[PreserveSig()]
int GetDisplayName(StringBuilder szDisplayName, ref uint pccDisplayName, uint dwDisplayFlags);
[PreserveSig()]
int BindToObject(object refIID, object pAsmBindSink, IApplicationContext pApplicationContext, [MarshalAs(UnmanagedType.LPWStr)] string szCodeBase, long llFlags, int pvReserved, uint cbReserved, out int ppv);
[PreserveSig()]
int GetName(out uint lpcwBuffer, out int pwzName);
[PreserveSig()]
int GetVersion(out uint pdwVersionHi, out uint pdwVersionLow);
[PreserveSig()]
int IsEqual(IAssemblyName pName, uint dwCmpFlags);
[PreserveSig()]
int Clone(out IAssemblyName pName);
}
[ComImport(), Guid("7C23FF90-33AF-11D3-95DA-00A024A85B51"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IApplicationContext{
void SetContextNameObject(IAssemblyName pName);
void GetContextNameObject(out IAssemblyName ppName);
void Set([MarshalAs(UnmanagedType.LPWStr)] string szName, int pvValue, uint cbValue, uint dwFlags);
void Get([MarshalAs(UnmanagedType.LPWStr)] string szName, out int pvValue, ref uint pcbValue, uint dwFlags);
void GetDynamicDirectory(out int wzDynamicDir, ref uint pdwSize);
}
[ComImport(), Guid("21B8916C-F28E-11D2-A473-00C04F8EF448"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAssemblyEnum{
[PreserveSig()]
int GetNextAssembly(out IApplicationContext ppAppCtx, out IAssemblyName ppName, uint dwFlags);
[PreserveSig()]
int Reset();
[PreserveSig()]
int Clone(out IAssemblyEnum ppEnum);
}
}
#else
//TODO: provide a way to query ROTOR GAC
#endif
| |
using System;
using System.Collections;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
namespace Org.BouncyCastle.Asn1.X509
{
public class X509Extensions
: Asn1Encodable
{
/**
* Subject Directory Attributes
*/
public static readonly DerObjectIdentifier SubjectDirectoryAttributes = new DerObjectIdentifier("2.5.29.9");
/**
* Subject Key Identifier
*/
public static readonly DerObjectIdentifier SubjectKeyIdentifier = new DerObjectIdentifier("2.5.29.14");
/**
* Key Usage
*/
public static readonly DerObjectIdentifier KeyUsage = new DerObjectIdentifier("2.5.29.15");
/**
* Private Key Usage Period
*/
public static readonly DerObjectIdentifier PrivateKeyUsagePeriod = new DerObjectIdentifier("2.5.29.16");
/**
* Subject Alternative Name
*/
public static readonly DerObjectIdentifier SubjectAlternativeName = new DerObjectIdentifier("2.5.29.17");
/**
* Issuer Alternative Name
*/
public static readonly DerObjectIdentifier IssuerAlternativeName = new DerObjectIdentifier("2.5.29.18");
/**
* Basic Constraints
*/
public static readonly DerObjectIdentifier BasicConstraints = new DerObjectIdentifier("2.5.29.19");
/**
* CRL Number
*/
public static readonly DerObjectIdentifier CrlNumber = new DerObjectIdentifier("2.5.29.20");
/**
* Reason code
*/
public static readonly DerObjectIdentifier ReasonCode = new DerObjectIdentifier("2.5.29.21");
/**
* Hold Instruction Code
*/
public static readonly DerObjectIdentifier InstructionCode = new DerObjectIdentifier("2.5.29.23");
/**
* Invalidity Date
*/
public static readonly DerObjectIdentifier InvalidityDate = new DerObjectIdentifier("2.5.29.24");
/**
* Delta CRL indicator
*/
public static readonly DerObjectIdentifier DeltaCrlIndicator = new DerObjectIdentifier("2.5.29.27");
/**
* Issuing Distribution Point
*/
public static readonly DerObjectIdentifier IssuingDistributionPoint = new DerObjectIdentifier("2.5.29.28");
/**
* Certificate Issuer
*/
public static readonly DerObjectIdentifier CertificateIssuer = new DerObjectIdentifier("2.5.29.29");
/**
* Name Constraints
*/
public static readonly DerObjectIdentifier NameConstraints = new DerObjectIdentifier("2.5.29.30");
/**
* CRL Distribution Points
*/
public static readonly DerObjectIdentifier CrlDistributionPoints = new DerObjectIdentifier("2.5.29.31");
/**
* Certificate Policies
*/
public static readonly DerObjectIdentifier CertificatePolicies = new DerObjectIdentifier("2.5.29.32");
/**
* Policy Mappings
*/
public static readonly DerObjectIdentifier PolicyMappings = new DerObjectIdentifier("2.5.29.33");
/**
* Authority Key Identifier
*/
public static readonly DerObjectIdentifier AuthorityKeyIdentifier = new DerObjectIdentifier("2.5.29.35");
/**
* Policy Constraints
*/
public static readonly DerObjectIdentifier PolicyConstraints = new DerObjectIdentifier("2.5.29.36");
/**
* Extended Key Usage
*/
public static readonly DerObjectIdentifier ExtendedKeyUsage = new DerObjectIdentifier("2.5.29.37");
/**
* Freshest CRL
*/
public static readonly DerObjectIdentifier FreshestCrl = new DerObjectIdentifier("2.5.29.46");
/**
* Inhibit Any Policy
*/
public static readonly DerObjectIdentifier InhibitAnyPolicy = new DerObjectIdentifier("2.5.29.54");
/**
* Authority Info Access
*/
public static readonly DerObjectIdentifier AuthorityInfoAccess = new DerObjectIdentifier("1.3.6.1.5.5.7.1.1");
/**
* Subject Info Access
*/
public static readonly DerObjectIdentifier SubjectInfoAccess = new DerObjectIdentifier("1.3.6.1.5.5.7.1.11");
/**
* Logo Type
*/
public static readonly DerObjectIdentifier LogoType = new DerObjectIdentifier("1.3.6.1.5.5.7.1.12");
/**
* BiometricInfo
*/
public static readonly DerObjectIdentifier BiometricInfo = new DerObjectIdentifier("1.3.6.1.5.5.7.1.2");
/**
* QCStatements
*/
public static readonly DerObjectIdentifier QCStatements = new DerObjectIdentifier("1.3.6.1.5.5.7.1.3");
/**
* Audit identity extension in attribute certificates.
*/
public static readonly DerObjectIdentifier AuditIdentity = new DerObjectIdentifier("1.3.6.1.5.5.7.1.4");
/**
* NoRevAvail extension in attribute certificates.
*/
public static readonly DerObjectIdentifier NoRevAvail = new DerObjectIdentifier("2.5.29.56");
/**
* TargetInformation extension in attribute certificates.
*/
public static readonly DerObjectIdentifier TargetInformation = new DerObjectIdentifier("2.5.29.55");
private readonly IDictionary extensions = Platform.CreateHashtable();
private readonly IList ordering;
public static X509Extensions GetInstance(
Asn1TaggedObject obj,
bool explicitly)
{
return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
}
public static X509Extensions GetInstance(
object obj)
{
if (obj == null || obj is X509Extensions)
{
return (X509Extensions) obj;
}
if (obj is Asn1Sequence)
{
return new X509Extensions((Asn1Sequence) obj);
}
if (obj is Asn1TaggedObject)
{
return GetInstance(((Asn1TaggedObject) obj).GetObject());
}
throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
}
/**
* Constructor from Asn1Sequence.
*
* the extensions are a list of constructed sequences, either with (Oid, OctetString) or (Oid, Boolean, OctetString)
*/
private X509Extensions(
Asn1Sequence seq)
{
this.ordering = Platform.CreateArrayList();
foreach (Asn1Encodable ae in seq)
{
Asn1Sequence s = Asn1Sequence.GetInstance(ae.ToAsn1Object());
if (s.Count < 2 || s.Count > 3)
throw new ArgumentException("Bad sequence size: " + s.Count);
DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(s[0].ToAsn1Object());
bool isCritical = s.Count == 3
&& DerBoolean.GetInstance(s[1].ToAsn1Object()).IsTrue;
Asn1OctetString octets = Asn1OctetString.GetInstance(s[s.Count - 1].ToAsn1Object());
extensions.Add(oid, new X509Extension(isCritical, octets));
ordering.Add(oid);
}
}
/**
* constructor from a table of extensions.
* <p>
* it's is assumed the table contains Oid/string pairs.</p>
*/
public X509Extensions(
IDictionary extensions)
: this(null, extensions)
{
}
/**
* Constructor from a table of extensions with ordering.
* <p>
* It's is assumed the table contains Oid/string pairs.</p>
*/
public X509Extensions(
IList ordering,
IDictionary extensions)
{
if (ordering == null)
{
this.ordering = Platform.CreateArrayList(extensions.Keys);
}
else
{
this.ordering = Platform.CreateArrayList(ordering);
}
foreach (DerObjectIdentifier oid in this.ordering)
{
this.extensions.Add(oid, (X509Extension)extensions[oid]);
}
}
/**
* Constructor from two vectors
*
* @param objectIDs an ArrayList of the object identifiers.
* @param values an ArrayList of the extension values.
*/
public X509Extensions(
IList oids,
IList values)
{
this.ordering = Platform.CreateArrayList(oids);
int count = 0;
foreach (DerObjectIdentifier oid in this.ordering)
{
this.extensions.Add(oid, (X509Extension)values[count++]);
}
}
#if !(SILVERLIGHT || NETFX_CORE)
/**
* constructor from a table of extensions.
* <p>
* it's is assumed the table contains Oid/string pairs.</p>
*/
[Obsolete]
public X509Extensions(
Hashtable extensions)
: this(null, extensions)
{
}
/**
* Constructor from a table of extensions with ordering.
* <p>
* It's is assumed the table contains Oid/string pairs.</p>
*/
[Obsolete]
public X509Extensions(
ArrayList ordering,
Hashtable extensions)
{
if (ordering == null)
{
this.ordering = Platform.CreateArrayList(extensions.Keys);
}
else
{
this.ordering = Platform.CreateArrayList(ordering);
}
foreach (DerObjectIdentifier oid in this.ordering)
{
this.extensions.Add(oid, (X509Extension) extensions[oid]);
}
}
/**
* Constructor from two vectors
*
* @param objectIDs an ArrayList of the object identifiers.
* @param values an ArrayList of the extension values.
*/
[Obsolete]
public X509Extensions(
ArrayList oids,
ArrayList values)
{
this.ordering = Platform.CreateArrayList(oids);
int count = 0;
foreach (DerObjectIdentifier oid in this.ordering)
{
this.extensions.Add(oid, (X509Extension) values[count++]);
}
}
#endif
[Obsolete("Use ExtensionOids IEnumerable property")]
public IEnumerator Oids()
{
return ExtensionOids.GetEnumerator();
}
/**
* return an Enumeration of the extension field's object ids.
*/
public IEnumerable ExtensionOids
{
get { return new EnumerableProxy(ordering); }
}
/**
* return the extension represented by the object identifier
* passed in.
*
* @return the extension if it's present, null otherwise.
*/
public X509Extension GetExtension(
DerObjectIdentifier oid)
{
return (X509Extension) extensions[oid];
}
/**
* <pre>
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*
* Extension ::= SEQUENCE {
* extnId EXTENSION.&id ({ExtensionSet}),
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING }
* </pre>
*/
public override Asn1Object ToAsn1Object()
{
Asn1EncodableVector vec = new Asn1EncodableVector();
foreach (DerObjectIdentifier oid in ordering)
{
X509Extension ext = (X509Extension) extensions[oid];
Asn1EncodableVector v = new Asn1EncodableVector(oid);
if (ext.IsCritical)
{
v.Add(DerBoolean.True);
}
v.Add(ext.Value);
vec.Add(new DerSequence(v));
}
return new DerSequence(vec);
}
public bool Equivalent(
X509Extensions other)
{
if (extensions.Count != other.extensions.Count)
return false;
foreach (DerObjectIdentifier oid in extensions.Keys)
{
if (!extensions[oid].Equals(other.extensions[oid]))
return false;
}
return true;
}
public DerObjectIdentifier[] GetExtensionOids()
{
return ToOidArray(ordering);
}
public DerObjectIdentifier[] GetNonCriticalExtensionOids()
{
return GetExtensionOids(false);
}
public DerObjectIdentifier[] GetCriticalExtensionOids()
{
return GetExtensionOids(true);
}
private DerObjectIdentifier[] GetExtensionOids(bool isCritical)
{
IList oids = Platform.CreateArrayList();
foreach (DerObjectIdentifier oid in this.ordering)
{
X509Extension ext = (X509Extension)extensions[oid];
if (ext.IsCritical == isCritical)
{
oids.Add(oid);
}
}
return ToOidArray(oids);
}
private static DerObjectIdentifier[] ToOidArray(IList oids)
{
DerObjectIdentifier[] oidArray = new DerObjectIdentifier[oids.Count];
oids.CopyTo(oidArray, 0);
return oidArray;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using Xunit;
using Xunit.Abstractions;
namespace System.Slices.Tests
{
public class UsageScenarioTests
{
private readonly ITestOutputHelper output;
public UsageScenarioTests(ITestOutputHelper output)
{
this.output = output;
}
private struct MyByte
{
public MyByte(byte value)
{
Value = value;
}
public byte Value { get; private set; }
}
[Theory]
[InlineData(new byte[] { })]
[InlineData(new byte[] { 0 })]
[InlineData(new byte[] { 0, 1 })]
[InlineData(new byte[] { 0, 1, 2 })]
[InlineData(new byte[] { 0, 1, 2, 3 })]
[InlineData(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 })]
public void CtorSpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array)
{
Span<byte> span = new Span<byte>(array);
Assert.Equal(array.Length, span.Length);
Assert.NotSame(array, span.ToArray());
Assert.True(span.Equals(array));
ReadOnlySpan<byte>.Enumerator it = span.GetEnumerator();
for (int i = 0; i < span.Length; i++)
{
Assert.True(it.MoveNext());
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
array[i] = unchecked((byte)(array[i] + 1));
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
span.Slice(i).Write<byte>(unchecked((byte)(array[i] + 1)));
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
span.Slice(i).Write<MyByte>(unchecked(new MyByte((byte)(array[i] + 1))));
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
}
Assert.False(it.MoveNext());
it.Reset();
for (int i = 0; i < span.Length; i++)
{
Assert.True(it.MoveNext());
Assert.Equal(array[i], it.Current);
}
Assert.False(it.MoveNext());
}
[Theory]
[InlineData(new byte[] { })]
[InlineData(new byte[] { 0 })]
[InlineData(new byte[] { 0, 1 })]
[InlineData(new byte[] { 0, 1, 2 })]
[InlineData(new byte[] { 0, 1, 2, 3 })]
[InlineData(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 })]
public void CtorReadOnlySpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array)
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(array);
Assert.Equal(array.Length, span.Length);
Assert.NotSame(array, span.ToArray());
Assert.True(span.Equals(array));
ReadOnlySpan<byte>.Enumerator it = span.GetEnumerator();
for (int i = 0; i < span.Length; i++)
{
Assert.True(it.MoveNext());
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
array[i] = unchecked((byte)(array[i] + 1));
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
}
Assert.False(it.MoveNext());
it.Reset();
for (int i = 0; i < span.Length; i++)
{
Assert.True(it.MoveNext());
Assert.Equal(array[i], it.Current);
}
Assert.False(it.MoveNext());
}
[Theory]
// copy whole buffer
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 6)]
// copy first half to first half (length match)
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 3)]
// copy second half to second half (length match)
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3,
new byte[] { 1, 2, 3, 7, 7, 7 }, 3, 3)]
// copy first half to first half
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)]
// copy no bytes starting from index 0
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0,
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)]
// copy no bytes starting from index 3
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0,
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)]
// copy no bytes starting at the end
[InlineData(
new byte[] { 7, 7, 7, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)]
// copy first byte of 1 element array to last position
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 6 }, 0, 1,
new byte[] { 1, 2, 3, 4, 5, 7 }, 5, 1)]
// copy first two bytes of 2 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 5, 6 }, 0, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy first two bytes of 3 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 5, 6, 7 }, 0, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy last two bytes of 3 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 5, 6 }, 1, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy first two bytes of 2 element array to the middle of other array
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 3, 4 }, 0, 2,
new byte[] { 1, 2, 7, 7, 5, 6 }, 2, 3)]
// copy one byte from the beginning at the end of other array
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 1,
new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)]
// copy two bytes from the beginning at 5th element
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 2,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)]
// copy one byte from the beginning at the end of other array
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1,
new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)]
// copy two bytes from the beginning at 5th element
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 4, 2,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)]
public void SpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount)
{
if (expected != null)
{
Span<byte> spanA = new Span<byte>(a, aidx, acount);
Span<byte> spanB = new Span<byte>(b, bidx, bcount);
spanA.CopyTo(spanB);
Assert.Equal(expected, b);
Span<byte> spanExpected = new Span<byte>(expected);
Span<byte> spanBAll = new Span<byte>(b);
Assert.True(spanExpected.SequenceEqual(spanBAll));
}
else
{
Span<byte> spanA = new Span<byte>(a, aidx, acount);
Span<byte> spanB = new Span<byte>(b, bidx, bcount);
Assert.ThrowsAny<Exception>(() => { spanA.CopyTo(spanB); });
}
}
[Theory]
// copy whole buffer
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 6)]
// copy first half to first half (length match)
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 3)]
// copy second half to second half (length match)
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3,
new byte[] { 1, 2, 3, 7, 7, 7 }, 3, 3)]
// copy first half to first half
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)]
// copy no bytes starting from index 0
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0,
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)]
// copy no bytes starting from index 3
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0,
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)]
// copy no bytes starting at the end
[InlineData(
new byte[] { 7, 7, 7, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)]
// copy first byte of 1 element array to last position
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 6 }, 0, 1,
new byte[] { 1, 2, 3, 4, 5, 7 }, 5, 1)]
// copy first two bytes of 2 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 5, 6 }, 0, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy first two bytes of 3 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 5, 6, 7 }, 0, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy last two bytes of 3 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 5, 6 }, 1, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy first two bytes of 2 element array to the middle of other array
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 3, 4 }, 0, 2,
new byte[] { 1, 2, 7, 7, 5, 6 }, 2, 3)]
// copy one byte from the beginning at the end of other array
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 1,
new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)]
// copy two bytes from the beginning at 5th element
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 2,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)]
// copy one byte from the beginning at the end of other array
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1,
new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)]
// copy two bytes from the beginning at 5th element
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 4, 2,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)]
public void ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount)
{
if (expected != null)
{
ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount);
Span<byte> spanB = new Span<byte>(b, bidx, bcount);
spanA.CopyTo(spanB);
Assert.Equal(expected, b);
ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected);
ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b);
Assert.True(spanExpected.SequenceEqual(spanBAll));
}
else
{
ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount);
Span<byte> spanB = new Span<byte>(b, bidx, bcount);
Assert.ThrowsAny<Exception>(() => { spanA.CopyTo(spanB); });
}
ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCasesNative(expected, a, aidx, acount, b, bidx, bcount);
}
public unsafe void ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCasesNative(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount)
{
IntPtr pa = Marshal.AllocHGlobal(a.Length);
Span<byte> na = new Span<byte>(pa.ToPointer(), a.Length);
na.Set(a);
IntPtr pb = Marshal.AllocHGlobal(b.Length);
Span<byte> nb = new Span<byte>(pb.ToPointer(), b.Length);
nb.Set(b);
ReadOnlySpan<byte> spanA = na.Slice(aidx, acount);
Span<byte> spanB = nb.Slice(bidx, bcount);
if (expected != null) {
spanA.CopyTo(spanB);
Assert.Equal(expected, b);
ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected);
ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b);
Assert.True(spanExpected.SequenceEqual(spanBAll));
}
else {
Assert.ThrowsAny<Exception>(() => { spanA.CopyTo(spanB); });
}
Marshal.FreeHGlobal(pa);
Marshal.FreeHGlobal(pb);
}
[Theory]
// copy whole buffer
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6,
new byte[] { 7, 7, 7, 7, 7, 7 })]
// copy first half
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 })]
// copy second half
[InlineData(
new byte[] { 4, 5, 6, 7, 7, 7 },
new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3,
new byte[] { 7, 7, 7, 7, 7, 7 })]
// copy no bytes starting from index 0
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0,
new byte[] { 1, 2, 3, 4, 5, 6 })]
// copy no bytes starting from index 3
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0,
new byte[] { 1, 2, 3, 4, 5, 6 })]
// copy no bytes starting at the end
[InlineData(
new byte[] { 7, 7, 7, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0,
new byte[] { 7, 7, 7, 4, 5, 6 })]
// copy first byte of 1 element array
[InlineData(
new byte[] { 6, 2, 3, 4, 5, 6 },
new byte[] { 6 }, 0, 1,
new byte[] { 1, 2, 3, 4, 5, 6 })]
public void SpanCopyToArrayTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b)
{
if (expected != null)
{
Span<byte> spanA = new Span<byte>(a, aidx, acount);
spanA.CopyTo(b);
Assert.Equal(expected, b);
Span<byte> spanExpected = new Span<byte>(expected);
Span<byte> spanBAll = new Span<byte>(b);
Assert.True(spanExpected.SequenceEqual(spanBAll));
}
else
{
Span<byte> spanA = new Span<byte>(a, aidx, acount);
Assert.ThrowsAny<Exception>(() => { spanA.CopyTo(b); });
}
}
[Theory]
// copy whole buffer
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6,
new byte[] { 7, 7, 7, 7, 7, 7 })]
// copy first half
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 })]
// copy second half
[InlineData(
new byte[] { 4, 5, 6, 7, 7, 7 },
new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3,
new byte[] { 7, 7, 7, 7, 7, 7 })]
// copy no bytes starting from index 0
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0,
new byte[] { 1, 2, 3, 4, 5, 6 })]
// copy no bytes starting from index 3
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0,
new byte[] { 1, 2, 3, 4, 5, 6 })]
// copy no bytes starting at the end
[InlineData(
new byte[] { 7, 7, 7, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0,
new byte[] { 7, 7, 7, 4, 5, 6 })]
// copy first byte of 1 element array
[InlineData(
new byte[] { 6, 2, 3, 4, 5, 6 },
new byte[] { 6 }, 0, 1,
new byte[] { 1, 2, 3, 4, 5, 6 })]
public void ROSpanCopyToArrayTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b)
{
if (expected != null)
{
ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount);
spanA.CopyTo(b);
Assert.Equal(expected, b);
ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected);
ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b);
Assert.True(spanExpected.SequenceEqual(spanBAll));
}
else
{
ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount);
Assert.ThrowsAny<Exception>(() => { spanA.CopyTo(b); });
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Diagnostics;
using System.Reflection;
namespace System.Xml.Serialization
{
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class CodeIdentifier
{
internal const int MaxIdentifierLength = 511;
[Obsolete("This class should never get constructed as it contains only static methods.")]
public CodeIdentifier()
{
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string MakePascal(string identifier)
{
identifier = MakeValid(identifier);
if (identifier.Length <= 2)
return CultureInfo.InvariantCulture.TextInfo.ToUpper(identifier);
else if (char.IsLower(identifier[0]))
return char.ToUpperInvariant(identifier[0]) + identifier.Substring(1);
else
return identifier;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string MakeCamel(string identifier)
{
identifier = MakeValid(identifier);
if (identifier.Length <= 2)
return CultureInfo.InvariantCulture.TextInfo.ToLower(identifier);
else if (char.IsUpper(identifier[0]))
return char.ToLower(identifier[0]) + identifier.Substring(1);
else
return identifier;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string MakeValid(string identifier)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < identifier.Length && builder.Length < MaxIdentifierLength; i++)
{
char c = identifier[i];
if (IsValid(c))
{
if (builder.Length == 0 && !IsValidStart(c))
{
builder.Append("Item");
}
builder.Append(c);
}
}
if (builder.Length == 0) return "Item";
return builder.ToString();
}
internal static string MakeValidInternal(string identifier)
{
if (identifier.Length > 30)
{
return "Item";
}
return MakeValid(identifier);
}
private static bool IsValidStart(char c)
{
// the given char is already a valid name character
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
if (!IsValid(c)) throw new ArgumentException(SR.Format(SR.XmlInternalErrorDetails, "Invalid identifier character " + ((Int16)c).ToString(CultureInfo.InvariantCulture)), "c");
#endif
// First char cannot be a number
if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber)
return false;
return true;
}
private static bool IsValid(char c)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(c);
// each char must be Lu, Ll, Lt, Lm, Lo, Nd, Mn, Mc, Pc
//
switch (uc)
{
case UnicodeCategory.UppercaseLetter: // Lu
case UnicodeCategory.LowercaseLetter: // Ll
case UnicodeCategory.TitlecaseLetter: // Lt
case UnicodeCategory.ModifierLetter: // Lm
case UnicodeCategory.OtherLetter: // Lo
case UnicodeCategory.DecimalDigitNumber: // Nd
case UnicodeCategory.NonSpacingMark: // Mn
case UnicodeCategory.SpacingCombiningMark: // Mc
case UnicodeCategory.ConnectorPunctuation: // Pc
break;
case UnicodeCategory.LetterNumber:
case UnicodeCategory.OtherNumber:
case UnicodeCategory.EnclosingMark:
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.LineSeparator:
case UnicodeCategory.ParagraphSeparator:
case UnicodeCategory.Control:
case UnicodeCategory.Format:
case UnicodeCategory.Surrogate:
case UnicodeCategory.PrivateUse:
case UnicodeCategory.DashPunctuation:
case UnicodeCategory.OpenPunctuation:
case UnicodeCategory.ClosePunctuation:
case UnicodeCategory.InitialQuotePunctuation:
case UnicodeCategory.FinalQuotePunctuation:
case UnicodeCategory.OtherPunctuation:
case UnicodeCategory.MathSymbol:
case UnicodeCategory.CurrencySymbol:
case UnicodeCategory.ModifierSymbol:
case UnicodeCategory.OtherSymbol:
case UnicodeCategory.OtherNotAssigned:
return false;
default:
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
throw new ArgumentException(SR.Format(SR.XmlInternalErrorDetails, "Unhandled category " + uc), "c");
#else
return false;
#endif
}
return true;
}
internal static void CheckValidIdentifier(string ident)
{
if (!CSharpHelpers.IsValidLanguageIndependentIdentifier(ident))
throw new ArgumentException(SR.Format(SR.XmlInvalidIdentifier, ident), nameof(ident));
}
internal static string GetCSharpName(string name)
{
return EscapeKeywords(name.Replace('+', '.'));
}
private static int GetCSharpName(Type t, Type[] parameters, int index, StringBuilder sb)
{
if (t.DeclaringType != null && t.DeclaringType != t)
{
index = GetCSharpName(t.DeclaringType, parameters, index, sb);
sb.Append(".");
}
string name = t.Name;
int nameEnd = name.IndexOf('`');
if (nameEnd < 0)
{
nameEnd = name.IndexOf('!');
}
if (nameEnd > 0)
{
EscapeKeywords(name.Substring(0, nameEnd), sb);
sb.Append("<");
int arguments = int.Parse(name.Substring(nameEnd + 1), CultureInfo.InvariantCulture) + index;
for (; index < arguments; index++)
{
sb.Append(GetCSharpName(parameters[index]));
if (index < arguments - 1)
{
sb.Append(",");
}
}
sb.Append(">");
}
else
{
EscapeKeywords(name, sb);
}
return index;
}
internal static string GetCSharpName(Type t)
{
int rank = 0;
while (t.IsArray)
{
t = t.GetElementType();
rank++;
}
StringBuilder sb = new StringBuilder();
sb.Append("global::");
string ns = t.Namespace;
if (ns != null && ns.Length > 0)
{
string[] parts = ns.Split(new char[] { '.' });
for (int i = 0; i < parts.Length; i++)
{
EscapeKeywords(parts[i], sb);
sb.Append(".");
}
}
Type[] arguments = t.IsGenericType || t.ContainsGenericParameters ? t.GetGenericArguments() : Array.Empty<Type>();
GetCSharpName(t, arguments, 0, sb);
for (int i = 0; i < rank; i++)
{
sb.Append("[]");
}
return sb.ToString();
}
/*
internal static string GetTypeName(string name, CodeDomProvider codeProvider) {
return codeProvider.GetTypeOutput(new CodeTypeReference(name));
}
*/
private static void EscapeKeywords(string identifier, StringBuilder sb)
{
if (identifier == null || identifier.Length == 0)
return;
int arrayCount = 0;
while (identifier.EndsWith("[]", StringComparison.Ordinal))
{
arrayCount++;
identifier = identifier.Substring(0, identifier.Length - 2);
}
if (identifier.Length > 0)
{
CheckValidIdentifier(identifier);
identifier = CSharpHelpers.CreateEscapedIdentifier(identifier);
sb.Append(identifier);
}
for (int i = 0; i < arrayCount; i++)
{
sb.Append("[]");
}
}
private static string EscapeKeywords(string identifier)
{
if (identifier == null || identifier.Length == 0) return identifier;
string originalIdentifier = identifier;
string[] names = identifier.Split(new char[] { '.', ',', '<', '>' });
StringBuilder sb = new StringBuilder();
int separator = -1;
for (int i = 0; i < names.Length; i++)
{
if (separator >= 0)
{
sb.Append(originalIdentifier.Substring(separator, 1));
}
separator++;
separator += names[i].Length;
string escapedName = names[i].Trim();
EscapeKeywords(escapedName, sb);
}
if (sb.Length != originalIdentifier.Length)
return sb.ToString();
return originalIdentifier;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="PagedDataSource.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.Collections;
using System.ComponentModel;
using System.Web.UI;
/// <devdoc>
/// <para>Provides a wrapper over an ICollection datasource to implement paging
/// semantics or 'paged views' on top of the underlying datasource.</para>
/// </devdoc>
public sealed class PagedDataSource : ICollection, ITypedList {
private IEnumerable dataSource;
private int currentPageIndex;
private int pageSize;
private bool allowPaging;
private bool allowCustomPaging;
private bool allowServerPaging;
private int virtualCount;
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.PagedDataSource'/> class.</para>
/// </devdoc>
public PagedDataSource() {
this.pageSize = 10;
this.allowPaging = false;
this.currentPageIndex = 0;
this.allowCustomPaging = false;
this.allowServerPaging = false;
this.virtualCount = 0;
}
/// <devdoc>
/// Indicates whether to assume the underlying datasource
/// contains data for just the current page.
/// </devdoc>
public bool AllowCustomPaging {
get {
return allowCustomPaging;
}
set {
allowCustomPaging = value;
}
}
/// <devdoc>
/// <para>Indicates whether to implement page semantics on top of the underlying datasource.</para>
/// </devdoc>
public bool AllowPaging {
get {
return allowPaging;
}
set {
allowPaging = value;
}
}
/// <devdoc>
/// <para>Indicates whether to implement page semantics on top of the underlying datasource.</para>
/// </devdoc>
public bool AllowServerPaging {
get {
return allowServerPaging;
}
set {
allowServerPaging = value;
}
}
/// <devdoc>
/// <para>
/// Specifies the number of items
/// to be used from the datasource.</para>
/// </devdoc>
public int Count {
get {
if (dataSource == null)
return 0;
if (IsPagingEnabled) {
if (IsCustomPagingEnabled || (IsLastPage == false)) {
// In custom paging the datasource can contain at most
// a single page's worth of data.
// In non-custom paging, all pages except last one have
// a full page worth of data.
return pageSize;
}
else {
// last page might have fewer items in datasource
return DataSourceCount - FirstIndexInPage;
}
}
else {
return DataSourceCount;
}
}
}
/// <devdoc>
/// <para>Indicates the index of the current page.</para>
/// </devdoc>
public int CurrentPageIndex {
get {
return currentPageIndex;
}
set {
currentPageIndex = value;
}
}
/// <devdoc>
/// <para> Indicates the data source.</para>
/// </devdoc>
public IEnumerable DataSource {
get {
return dataSource;
}
set {
dataSource = value;
}
}
/// <devdoc>
/// </devdoc>
public int DataSourceCount {
get {
if (dataSource == null)
return 0;
if (IsCustomPagingEnabled || IsServerPagingEnabled) {
return virtualCount;
}
else {
if (dataSource is ICollection) {
return ((ICollection)dataSource).Count;
}
else {
// The caller should not call this in the case of an IEnumerator datasource
// This is required for paging, but the assumption is that the user will set
// up custom paging.
throw new HttpException(SR.GetString(SR.PagedDataSource_Cannot_Get_Count));
}
}
}
}
/// <devdoc>
/// </devdoc>
public int FirstIndexInPage {
get {
if ((dataSource == null) || (IsPagingEnabled == false)) {
return 0;
}
else {
if (IsCustomPagingEnabled || IsServerPagingEnabled) {
// In this mode, all the data belongs to the current page.
return 0;
}
else {
return currentPageIndex * pageSize;
}
}
}
}
/// <devdoc>
/// </devdoc>
public bool IsCustomPagingEnabled {
get {
return IsPagingEnabled && allowCustomPaging;
}
}
/// <devdoc>
/// </devdoc>
public bool IsFirstPage {
get {
if (IsPagingEnabled)
return(CurrentPageIndex == 0);
else
return true;
}
}
/// <devdoc>
/// </devdoc>
public bool IsLastPage {
get {
if (IsPagingEnabled)
return(CurrentPageIndex == (PageCount - 1));
else
return true;
}
}
/// <devdoc>
/// </devdoc>
public bool IsPagingEnabled {
get {
return allowPaging && (pageSize != 0);
}
}
/// <devdoc>
/// </devdoc>
public bool IsReadOnly {
get {
return false;
}
}
/// <devdoc>
/// Indicates whether server-side paging is enabled
/// </devdoc>
public bool IsServerPagingEnabled {
get {
return IsPagingEnabled && allowServerPaging;
}
}
/// <devdoc>
/// </devdoc>
public bool IsSynchronized {
get {
return false;
}
}
/// <devdoc>
/// </devdoc>
public int PageCount {
get {
if (dataSource == null)
return 0;
int dataSourceItemCount = DataSourceCount;
if (IsPagingEnabled && (dataSourceItemCount > 0)) {
int pageCountNum = dataSourceItemCount + pageSize - 1;
if (pageCountNum < 0) {
return 1; // integer overflow
}
return (int)(pageCountNum/pageSize);
}
else {
return 1;
}
}
}
/// <devdoc>
/// </devdoc>
public int PageSize {
get {
return pageSize;
}
set {
pageSize = value;
}
}
/// <devdoc>
/// </devdoc>
public object SyncRoot {
get {
return this;
}
}
/// <devdoc>
/// </devdoc>
public int VirtualCount {
get {
return virtualCount;
}
set {
virtualCount = value;
}
}
/// <devdoc>
/// </devdoc>
public void CopyTo(Array array, int index) {
for (IEnumerator e = this.GetEnumerator(); e.MoveNext();)
array.SetValue(e.Current, index++);
}
/// <devdoc>
/// </devdoc>
public IEnumerator GetEnumerator() {
int startIndex = FirstIndexInPage;
int count = -1;
if (dataSource is ICollection) {
count = Count;
}
if (dataSource is IList) {
return new EnumeratorOnIList((IList)dataSource, startIndex, count);
}
else if (dataSource is Array) {
return new EnumeratorOnArray((object[])dataSource, startIndex, count);
}
else if (dataSource is ICollection) {
return new EnumeratorOnICollection((ICollection)dataSource, startIndex, count);
}
else {
if (allowCustomPaging || allowServerPaging) {
// startIndex does not matter
// however count does... even if the data source contains more than 1 page of data in
// it, we only want to enumerate over a single page of data
// note: we can call Count here, even though we're dealing with an IEnumerator
// because by now we have ensured that we're in custom paging mode
return new EnumeratorOnIEnumerator(dataSource.GetEnumerator(), Count);
}
else {
// startIndex and count don't matter since we're going to enumerate over all the
// data (either non-paged or custom paging scenario)
return dataSource.GetEnumerator();
}
}
}
/// <devdoc>
/// </devdoc>
public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) {
if (dataSource == null)
return null;
if (dataSource is ITypedList) {
return((ITypedList)dataSource).GetItemProperties(listAccessors);
}
return null;
}
/// <devdoc>
/// </devdoc>
public string GetListName(PropertyDescriptor[] listAccessors) {
return String.Empty;
}
/// <devdoc>
/// </devdoc>
private sealed class EnumeratorOnIEnumerator : IEnumerator {
private IEnumerator realEnum;
private int index;
private int indexBounds;
public EnumeratorOnIEnumerator(IEnumerator realEnum, int count) {
this.realEnum = realEnum;
this.index = -1;
this.indexBounds = count;
}
public object Current {
get {
return realEnum.Current;
}
}
public bool MoveNext() {
bool result = realEnum.MoveNext();
index++;
return result && (index < indexBounds);
}
public void Reset() {
realEnum.Reset();
index = -1;
}
}
/// <devdoc>
/// </devdoc>
private sealed class EnumeratorOnICollection : IEnumerator {
private ICollection collection;
private IEnumerator collectionEnum;
private int startIndex;
private int index;
private int indexBounds;
public EnumeratorOnICollection(ICollection collection, int startIndex, int count) {
this.collection = collection;
this.startIndex = startIndex;
this.index = -1;
this.indexBounds = startIndex + count;
if (indexBounds > collection.Count) {
indexBounds = collection.Count;
}
}
public object Current {
get {
return collectionEnum.Current;
}
}
public bool MoveNext() {
if (collectionEnum == null) {
collectionEnum = collection.GetEnumerator();
for (int i = 0; i < startIndex; i++)
collectionEnum.MoveNext();
}
collectionEnum.MoveNext();
index++;
return (startIndex + index) < indexBounds;
}
public void Reset() {
collectionEnum = null;
index = -1;
}
}
/// <devdoc>
/// </devdoc>
private sealed class EnumeratorOnIList : IEnumerator {
private IList collection;
private int startIndex;
private int index;
private int indexBounds;
public EnumeratorOnIList(IList collection, int startIndex, int count) {
this.collection = collection;
this.startIndex = startIndex;
this.index = -1;
this.indexBounds = startIndex + count;
if (indexBounds > collection.Count) {
indexBounds = collection.Count;
}
}
public object Current {
get {
if (index < 0) {
throw new InvalidOperationException(SR.GetString(SR.Enumerator_MoveNext_Not_Called));
}
return collection[startIndex + index];
}
}
public bool MoveNext() {
index++;
return (startIndex + index) < indexBounds;
}
public void Reset() {
index = -1;
}
}
/// <devdoc>
/// </devdoc>
private sealed class EnumeratorOnArray : IEnumerator {
private object[] array;
private int startIndex;
private int index;
private int indexBounds;
public EnumeratorOnArray(object[] array, int startIndex, int count) {
this.array = array;
this.startIndex = startIndex;
this.index = -1;
this.indexBounds = startIndex + count;
if (indexBounds > array.Length) {
indexBounds = array.Length;
}
}
public object Current {
get {
if (index < 0) {
throw new InvalidOperationException(SR.GetString(SR.Enumerator_MoveNext_Not_Called));
}
return array[startIndex + index];
}
}
public bool MoveNext() {
index++;
return (startIndex + index) < indexBounds;
}
public void Reset() {
index = -1;
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace Northwind{
/// <summary>
/// Strongly-typed collection for the OrderDetailsExtended class.
/// </summary>
[Serializable]
public partial class OrderDetailsExtendedCollection : ReadOnlyList<OrderDetailsExtended, OrderDetailsExtendedCollection>
{
public OrderDetailsExtendedCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the Order Details Extended view.
/// </summary>
[Serializable]
public partial class OrderDetailsExtended : ReadOnlyRecord<OrderDetailsExtended>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Order Details Extended", TableType.View, DataService.GetInstance("Northwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema);
colvarOrderID.ColumnName = "OrderID";
colvarOrderID.DataType = DbType.Int32;
colvarOrderID.MaxLength = 0;
colvarOrderID.AutoIncrement = false;
colvarOrderID.IsNullable = false;
colvarOrderID.IsPrimaryKey = false;
colvarOrderID.IsForeignKey = false;
colvarOrderID.IsReadOnly = false;
schema.Columns.Add(colvarOrderID);
TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema);
colvarProductID.ColumnName = "ProductID";
colvarProductID.DataType = DbType.Int32;
colvarProductID.MaxLength = 0;
colvarProductID.AutoIncrement = false;
colvarProductID.IsNullable = false;
colvarProductID.IsPrimaryKey = false;
colvarProductID.IsForeignKey = false;
colvarProductID.IsReadOnly = false;
schema.Columns.Add(colvarProductID);
TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema);
colvarProductName.ColumnName = "ProductName";
colvarProductName.DataType = DbType.String;
colvarProductName.MaxLength = 40;
colvarProductName.AutoIncrement = false;
colvarProductName.IsNullable = false;
colvarProductName.IsPrimaryKey = false;
colvarProductName.IsForeignKey = false;
colvarProductName.IsReadOnly = false;
schema.Columns.Add(colvarProductName);
TableSchema.TableColumn colvarUnitPrice = new TableSchema.TableColumn(schema);
colvarUnitPrice.ColumnName = "UnitPrice";
colvarUnitPrice.DataType = DbType.Currency;
colvarUnitPrice.MaxLength = 0;
colvarUnitPrice.AutoIncrement = false;
colvarUnitPrice.IsNullable = false;
colvarUnitPrice.IsPrimaryKey = false;
colvarUnitPrice.IsForeignKey = false;
colvarUnitPrice.IsReadOnly = false;
schema.Columns.Add(colvarUnitPrice);
TableSchema.TableColumn colvarQuantity = new TableSchema.TableColumn(schema);
colvarQuantity.ColumnName = "Quantity";
colvarQuantity.DataType = DbType.Int16;
colvarQuantity.MaxLength = 0;
colvarQuantity.AutoIncrement = false;
colvarQuantity.IsNullable = false;
colvarQuantity.IsPrimaryKey = false;
colvarQuantity.IsForeignKey = false;
colvarQuantity.IsReadOnly = false;
schema.Columns.Add(colvarQuantity);
TableSchema.TableColumn colvarDiscount = new TableSchema.TableColumn(schema);
colvarDiscount.ColumnName = "Discount";
colvarDiscount.DataType = DbType.Single;
colvarDiscount.MaxLength = 0;
colvarDiscount.AutoIncrement = false;
colvarDiscount.IsNullable = false;
colvarDiscount.IsPrimaryKey = false;
colvarDiscount.IsForeignKey = false;
colvarDiscount.IsReadOnly = false;
schema.Columns.Add(colvarDiscount);
TableSchema.TableColumn colvarExtendedPrice = new TableSchema.TableColumn(schema);
colvarExtendedPrice.ColumnName = "ExtendedPrice";
colvarExtendedPrice.DataType = DbType.Currency;
colvarExtendedPrice.MaxLength = 0;
colvarExtendedPrice.AutoIncrement = false;
colvarExtendedPrice.IsNullable = true;
colvarExtendedPrice.IsPrimaryKey = false;
colvarExtendedPrice.IsForeignKey = false;
colvarExtendedPrice.IsReadOnly = false;
schema.Columns.Add(colvarExtendedPrice);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Northwind"].AddSchema("Order Details Extended",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public OrderDetailsExtended()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public OrderDetailsExtended(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public OrderDetailsExtended(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public OrderDetailsExtended(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("OrderID")]
[Bindable(true)]
public int OrderID
{
get
{
return GetColumnValue<int>("OrderID");
}
set
{
SetColumnValue("OrderID", value);
}
}
[XmlAttribute("ProductID")]
[Bindable(true)]
public int ProductID
{
get
{
return GetColumnValue<int>("ProductID");
}
set
{
SetColumnValue("ProductID", value);
}
}
[XmlAttribute("ProductName")]
[Bindable(true)]
public string ProductName
{
get
{
return GetColumnValue<string>("ProductName");
}
set
{
SetColumnValue("ProductName", value);
}
}
[XmlAttribute("UnitPrice")]
[Bindable(true)]
public decimal UnitPrice
{
get
{
return GetColumnValue<decimal>("UnitPrice");
}
set
{
SetColumnValue("UnitPrice", value);
}
}
[XmlAttribute("Quantity")]
[Bindable(true)]
public short Quantity
{
get
{
return GetColumnValue<short>("Quantity");
}
set
{
SetColumnValue("Quantity", value);
}
}
[XmlAttribute("Discount")]
[Bindable(true)]
public float Discount
{
get
{
return GetColumnValue<float>("Discount");
}
set
{
SetColumnValue("Discount", value);
}
}
[XmlAttribute("ExtendedPrice")]
[Bindable(true)]
public decimal? ExtendedPrice
{
get
{
return GetColumnValue<decimal?>("ExtendedPrice");
}
set
{
SetColumnValue("ExtendedPrice", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string OrderID = @"OrderID";
public static string ProductID = @"ProductID";
public static string ProductName = @"ProductName";
public static string UnitPrice = @"UnitPrice";
public static string Quantity = @"Quantity";
public static string Discount = @"Discount";
public static string ExtendedPrice = @"ExtendedPrice";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace SafariPushNotifications.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// <copyright file="SafariDriverServer.cs" company="WebDriver Committers">
// Copyright 2007-2011 WebDriver committers
// Copyright 2007-2011 Google Inc.
// Portions copyright 2011 Software Freedom Conservancy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Safari.Internal;
namespace OpenQA.Selenium.Safari
{
/// <summary>
/// Provides the WebSockets server for communicating with the Safari extension.
/// </summary>
public class SafariDriverServer : ICommandServer
{
private WebSocketServer webSocketServer;
private Queue<SafariDriverConnection> connections = new Queue<SafariDriverConnection>();
private Uri serverUri;
private string temporaryDirectoryPath;
private string safariExecutableLocation;
private Process safariProcess;
private SafariDriverConnection connection;
/// <summary>
/// Initializes a new instance of the <see cref="SafariDriverServer"/> class using the specified options.
/// </summary>
/// <param name="options">The <see cref="SafariOptions"/> defining the browser settings.</param>
public SafariDriverServer(SafariOptions options)
{
int webSocketPort = options.Port;
if (webSocketPort == 0)
{
webSocketPort = PortUtilities.FindFreePort();
}
this.webSocketServer = new WebSocketServer(webSocketPort, "ws://localhost/wd");
this.webSocketServer.Opened += new EventHandler<ConnectionEventArgs>(this.ServerOpenedEventHandler);
this.webSocketServer.Closed += new EventHandler<ConnectionEventArgs>(this.ServerClosedEventHandler);
this.webSocketServer.StandardHttpRequestReceived += new EventHandler<StandardHttpRequestReceivedEventArgs>(this.ServerStandardHttpRequestReceivedEventHandler);
this.serverUri = new Uri(string.Format(CultureInfo.InvariantCulture, "http://localhost:{0}/", webSocketPort.ToString(CultureInfo.InvariantCulture)));
if (string.IsNullOrEmpty(options.SafariLocation))
{
this.safariExecutableLocation = GetDefaultSafariLocation();
}
else
{
this.safariExecutableLocation = options.SafariLocation;
}
}
/// <summary>
/// Starts the server.
/// </summary>
public void Start()
{
this.webSocketServer.Start();
string connectFileName = this.PrepareConnectFile();
this.LaunchSafariProcess(connectFileName);
this.connection = this.WaitForConnection(TimeSpan.FromSeconds(45));
this.DeleteConnectFile();
if (this.connection == null)
{
throw new WebDriverException("Did not receive a connection from the Safari extension. Please verify that it is properly installed and is the proper version.");
}
}
/// <summary>
/// Sends a command to the server.
/// </summary>
/// <param name="commandToSend">The <see cref="Command"/> to send.</param>
/// <returns>The command <see cref="Response"/>.</returns>
public Response SendCommand(Command commandToSend)
{
return this.connection.Send(commandToSend);
}
/// <summary>
/// Waits for a connection to be established with the server by the Safari browser extension.
/// </summary>
/// <param name="timeout">A <see cref="TimeSpan"/> containing the amount of time to wait for the connection.</param>
/// <returns>A <see cref="SafariDriverConnection"/> representing the connection to the browser.</returns>
public SafariDriverConnection WaitForConnection(TimeSpan timeout)
{
SafariDriverConnection foundConnection = null;
DateTime end = DateTime.Now.Add(timeout);
while (this.connections.Count == 0 && DateTime.Now < end)
{
Thread.Sleep(250);
}
if (this.connections.Count > 0)
{
foundConnection = this.connections.Dequeue();
}
return foundConnection;
}
/// <summary>
/// Releases all resources used by the <see cref="SafariDriverServer"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="SafariDriverServer"/> and optionally
/// releases the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release managed and resources;
/// <see langword="false"/> to only release unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.webSocketServer.Dispose();
if (this.safariProcess != null)
{
this.CloseSafariProcess();
this.safariProcess.Dispose();
}
}
}
private static string GetDefaultSafariLocation()
{
string safariPath = string.Empty;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
// Safari remains a 32-bit application. Use a hack to look for it
// in the 32-bit program files directory. If a 64-bit version of
// Safari for Windows is released, this needs to be revisited.
string programFilesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
if (Directory.Exists(programFilesDirectory + " (x86)"))
{
programFilesDirectory += " (x86)";
}
safariPath = Path.Combine(programFilesDirectory, Path.Combine("Safari", "safari.exe"));
}
else
{
safariPath = "/Applications/Safari.app/Contents/MacOS/Safari";
}
return safariPath;
}
[SecurityPermission(SecurityAction.Demand)]
private void LaunchSafariProcess(string initialPage)
{
this.safariProcess = new Process();
this.safariProcess.StartInfo.FileName = this.safariExecutableLocation;
this.safariProcess.StartInfo.Arguments = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", initialPage);
this.safariProcess.Start();
}
[SecurityPermission(SecurityAction.Demand)]
private void CloseSafariProcess()
{
if (this.safariProcess != null && !this.safariProcess.HasExited)
{
this.safariProcess.Kill();
while (!this.safariProcess.HasExited)
{
Thread.Sleep(250);
}
}
}
private string PrepareConnectFile()
{
string directoryName = FileUtilities.GenerateRandomTempDirectoryName("SafariDriverConnect.{0}");
this.temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), directoryName);
string tempFileName = Path.Combine(this.temporaryDirectoryPath, "connect.html");
string contents = string.Format(CultureInfo.InvariantCulture, "<!DOCTYPE html><script>window.location = '{0}';</script>", this.serverUri.ToString());
Directory.CreateDirectory(this.temporaryDirectoryPath);
using (FileStream stream = File.Create(tempFileName))
{
stream.Write(Encoding.UTF8.GetBytes(contents), 0, Encoding.UTF8.GetByteCount(contents));
}
return tempFileName;
}
private void DeleteConnectFile()
{
Directory.Delete(this.temporaryDirectoryPath, true);
}
private void ServerOpenedEventHandler(object sender, ConnectionEventArgs e)
{
this.connections.Enqueue(new SafariDriverConnection(e.Connection));
}
private void ServerClosedEventHandler(object sender, ConnectionEventArgs e)
{
}
private void ServerStandardHttpRequestReceivedEventHandler(object sender, StandardHttpRequestReceivedEventArgs e)
{
const string PageSource = @"<!DOCTYPE html>
<script>
window.onload = function() {{
window.postMessage({{
'type': 'connect',
'origin': 'webdriver',
'url': 'ws://localhost:{0}/wd'
}}, '*');
}};
</script>";
string redirectPage = string.Format(CultureInfo.InvariantCulture, PageSource, this.webSocketServer.Port.ToString(CultureInfo.InvariantCulture));
StringBuilder builder = new StringBuilder();
builder.AppendLine("HTTP/1.1 200");
builder.AppendLine("Content-Length: " + redirectPage.Length.ToString(CultureInfo.InvariantCulture));
builder.AppendLine("Connection:close");
builder.AppendLine();
builder.AppendLine(redirectPage);
e.Connection.SendRaw(builder.ToString());
}
}
}
| |
using System.Collections.Generic;
using InAudioSystem;
using InAudioSystem.ExtensionMethods;
using UnityEngine;
[AddComponentMenu("InAudio/Spline/Audio Spline")]
public class InSpline : MonoBehaviour
{
public InAudioEvent SplineAudioEvent;
public List<InSplineNode> Nodes = new List<InSplineNode>();
public List<InSplineConnection> Connections = new List<InSplineConnection>();
private GameObject movingObject;
private Transform movingTransform;
public Vector3 SoundPosition
{
get { return movingTransform.position; }
}
public Quaternion SoundRotation
{
get { return movingTransform.rotation; }
}
void Awake()
{
movingObject = new GameObject();
movingObject.transform.parent = transform;
movingObject.transform.localPosition = new Vector3();
movingObject.name = "Audio source";
movingTransform = movingObject.transform;
}
void OnEnable()
{
InAudio.PostEventAttachedTo(gameObject, SplineAudioEvent, movingObject);
}
void LateUpdate()
{
AudioListener listener = InAudio.ActiveListener;
if (Connections.Count >= 1)
{
PlaceSource(listener);
}
else if (Nodes.Count == 1)
{
movingTransform.position = Nodes[0].GetTransform.position;
}
}
private void PlaceSource(AudioListener listener)
{
if (listener != null)
{
Vector3 listenerPos = listener.transform.position;
float minDistance = float.MaxValue;
Vector3 closetsPoint = Vector3.zero;
int count = Connections.Count;
for (int i = 0; i < count; i++)
{
var connection = Connections[i];
Vector3 posA;
Vector3 posB;
if (connection.NodeA != null)
posA = connection.NodeA.transform.position;
else
continue;
if (connection.NodeB != null)
posB = connection.NodeB.transform.position;
else
continue;
Vector3 minPos;
float distance = PointToSegmentDistance(listenerPos, posA, posB, out minPos);
if (distance < minDistance)
{
minDistance = distance;
closetsPoint = minPos;
}
}
movingTransform.position = closetsPoint;
movingTransform.rotation = Quaternion.LookRotation((InAudio.ActiveListener.transform.position - closetsPoint).normalized);
}
}
public InSplineNode[] FindConnectedNodes(InSplineNode node)
{
List<InSplineNode> nodes = new List<InSplineNode>();
foreach (var connection in Connections)
{
if(connection.NodeA == node)
nodes.Add(connection.NodeB);
else if (connection.NodeB == node)
nodes.Add(connection.NodeA);
}
return nodes.ToArray();
}
private float PointToSegmentDistance(Vector3 P, Vector3 S0, Vector3 S1, out Vector3 point)
{
Vector3 v = S1 - S0;
Vector3 w = P - S0;
float c1 = Vector3.Dot(w, v);
if (c1 <= 0)
{
point = S0;
return Vector3.Distance(P, S0);
}
float c2 = Vector3.Dot(v, v);
if (c2 <= c1)
{
point = S1;
return Vector3.Distance(P, S1);
}
float b = c1 / c2;
point = S0 + b * v;
return Vector3.Distance(P, point);
}
void OnDrawGizmos()
{
if (movingTransform != null)
{
Gizmos.color = Color.blue;
Gizmos.DrawRay(movingTransform.position, movingTransform.forward);
if (InAudio.ActiveListener != null)
Gizmos.DrawCube(InAudio.ActiveListener.gameObject.transform.position, new Vector3(1, 1, 1) * 0.3f);
}
}
public void AddConnection(InSplineNode nodeA, InSplineNode nodeB)
{
bool contains = false;
for (int i = 0; i < Connections.Count; i++)
{
var connection = Connections[i];
if ((connection.NodeA == nodeA && connection.NodeB == nodeB) || (connection.NodeA == nodeB && connection.NodeB == nodeA))
{
contains = true;
break;
}
}
if(!contains)
Connections.Add(new InSplineConnection(nodeA, nodeB));
}
public bool ContainsConnection(InSplineNode a, InSplineNode b)
{
for (int i = 0; i < Connections.Count; i++)
{
var con = Connections[i];
if (con.NodeA == a && con.NodeB == b || con.NodeA == b && con.NodeB == a)
return true;
}
return false;
}
public void RemoveConnections(InSplineConnection connection)
{
for (int i = 0; i < Connections.Count; i++)
{
var curConnection = Connections[i];
if (connection == curConnection)
{
Connections.SafeRemoveAt(ref i);
}
}
}
public void RemoveConnections(InSplineNode node)
{
for (int i = 0; i < Connections.Count; i++)
{
var connection = Connections[i];
if (connection.NodeA == node || connection.NodeB == node)
{
Connections.SafeRemoveAt(ref i);
}
}
}
public void RemoveConnections(InSplineNode nodeA, InSplineNode nodeB)
{
for (int i = 0; i < Connections.Count; i++)
{
var connection = Connections[i];
if (connection.NodeA == nodeA && connection.NodeB == nodeB || connection.NodeA == nodeB && connection.NodeB == nodeA)
{
Connections.SafeRemoveAt(ref i);
}
}
}
}
| |
// 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 System.Numerics;
using Xunit;
namespace System.Tests
{
public partial class UInt64Tests
{
[Fact]
public static void Ctor_Empty()
{
var i = new ulong();
Assert.Equal((ulong)0, i);
}
[Fact]
public static void Ctor_Value()
{
ulong i = 41;
Assert.Equal((ulong)41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0xFFFFFFFFFFFFFFFF, ulong.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal((ulong)0, ulong.MinValue);
}
[Theory]
[InlineData((ulong)234, (ulong)234, 0)]
[InlineData((ulong)234, ulong.MinValue, 1)]
[InlineData((ulong)234, (ulong)0, 1)]
[InlineData((ulong)234, (ulong)123, 1)]
[InlineData((ulong)234, (ulong)456, -1)]
[InlineData((ulong)234, ulong.MaxValue, -1)]
[InlineData((ulong)234, null, 1)]
public void CompareTo_Other_ReturnsExpected(ulong i, object value, int expected)
{
if (value is ulong ulongValue)
{
Assert.Equal(expected, Math.Sign(i.CompareTo(ulongValue)));
}
Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
[Theory]
[InlineData("a")]
[InlineData(234)]
public void CompareTo_ObjectNotUlong_ThrowsArgumentException(object value)
{
AssertExtensions.Throws<ArgumentException>(null, () => ((ulong)123).CompareTo(value));
}
[Theory]
[InlineData((ulong)789, (ulong)789, true)]
[InlineData((ulong)788, (ulong)0, false)]
[InlineData((ulong)0, (ulong)0, true)]
[InlineData((ulong)789, null, false)]
[InlineData((ulong)789, "789", false)]
[InlineData((ulong)789, 789, false)]
public static void Equals(ulong i1, object obj, bool expected)
{
if (obj is ulong i2)
{
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
Assert.Equal((int)i1, i1.GetHashCode());
}
Assert.Equal(expected, i1.Equals(obj));
}
[Fact]
public void GetTypeCode_Invoke_ReturnsUInt64()
{
Assert.Equal(TypeCode.UInt64, ((ulong)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[] { (ulong)0, defaultSpecifier, defaultFormat, "0" };
yield return new object[] { (ulong)4567, defaultSpecifier, defaultFormat, "4567" };
yield return new object[] { ulong.MaxValue, defaultSpecifier, defaultFormat, "18446744073709551615" };
}
yield return new object[] { (ulong)4567, "D", defaultFormat, "4567" };
yield return new object[] { (ulong)4567, "D18", defaultFormat, "000000000000004567" };
yield return new object[] { (ulong)0x2468, "x", defaultFormat, "2468" };
yield return new object[] { (ulong)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[] { (ulong)2468, "N", customFormat, "2*468~00" };
yield return new object[] { (ulong)123, "E", customFormat, "1~230000E&002" };
yield return new object[] { (ulong)123, "F", customFormat, "123~00" };
yield return new object[] { (ulong)123, "P", customFormat, "12,300.00000 @" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(ulong 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()
{
ulong 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()
{
// Reuse all Int64 test data that's relevant
foreach (object[] objs in Int64Tests.Parse_Valid_TestData())
{
if ((long)objs[3] < 0) continue;
yield return new object[] { objs[0], objs[1], objs[2], (ulong)(long)objs[3] };
}
// All lengths decimal
{
string s = "";
ulong result = 0;
for (int i = 1; i <= 20; i++)
{
result = (result * 10) + (ulong)(i % 10);
s += (i % 10).ToString();
yield return new object[] { s, NumberStyles.Integer, null, result };
}
}
// All lengths hexadecimal
{
string s = "";
ulong result = 0;
for (int i = 1; i <= 16; i++)
{
result = (result * 16) + (ulong)(i % 16);
s += (i % 16).ToString("X");
yield return new object[] { s, NumberStyles.HexNumber, null, result };
}
}
// And test boundary conditions for UInt64
yield return new object[] { "18446744073709551615", NumberStyles.Integer, null, ulong.MaxValue };
yield return new object[] { "+18446744073709551615", NumberStyles.Integer, null, ulong.MaxValue };
yield return new object[] { " +18446744073709551615 ", NumberStyles.Integer, null, ulong.MaxValue };
yield return new object[] { "FFFFFFFFFFFFFFFF", NumberStyles.HexNumber, null, ulong.MaxValue };
yield return new object[] { " FFFFFFFFFFFFFFFF ", NumberStyles.HexNumber, null, ulong.MaxValue };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse_Valid(string value, NumberStyles style, IFormatProvider provider, ulong expected)
{
ulong result;
// Default style and provider
if (style == NumberStyles.Integer && provider == null)
{
Assert.True(ulong.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, ulong.Parse(value));
}
// Default provider
if (provider == null)
{
Assert.Equal(expected, ulong.Parse(value, style));
// Substitute default NumberFormatInfo
Assert.True(ulong.TryParse(value, style, new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
Assert.Equal(expected, ulong.Parse(value, style, new NumberFormatInfo()));
}
// Default style
if (style == NumberStyles.Integer)
{
Assert.Equal(expected, ulong.Parse(value, provider));
}
// Full overloads
Assert.True(ulong.TryParse(value, style, provider, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, ulong.Parse(value, style, provider));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
// Reuse all long test data, except for those that wouldn't overflow ulong.
foreach (object[] objs in Int64Tests.Parse_Invalid_TestData())
{
if ((Type)objs[3] == typeof(OverflowException) &&
(!BigInteger.TryParse((string)objs[0], out BigInteger bi) || bi <= ulong.MaxValue))
{
continue;
}
yield return objs;
}
// < min value
foreach (string ws in new[] { "", " " })
{
yield return new object[] { ws + "-1" + ws, NumberStyles.Integer, null, typeof(OverflowException) };
yield return new object[] { ws + "abc123" + ws, NumberStyles.Integer, new NumberFormatInfo { NegativeSign = "abc" }, typeof(OverflowException) };
}
// > max value
yield return new object[] { "18446744073709551616", NumberStyles.Integer, null, typeof(OverflowException) };
yield return new object[] { "10000000000000000", NumberStyles.HexNumber, null, typeof(OverflowException) };
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
ulong result;
// Default style and provider
if (style == NumberStyles.Integer && provider == null)
{
Assert.False(ulong.TryParse(value, out result));
Assert.Equal(default, result);
Assert.Throws(exceptionType, () => ulong.Parse(value));
}
// Default provider
if (provider == null)
{
Assert.Throws(exceptionType, () => ulong.Parse(value, style));
// Substitute default NumberFormatInfo
Assert.False(ulong.TryParse(value, style, new NumberFormatInfo(), out result));
Assert.Equal(default, result);
Assert.Throws(exceptionType, () => ulong.Parse(value, style, new NumberFormatInfo()));
}
// Default style
if (style == NumberStyles.Integer)
{
Assert.Throws(exceptionType, () => ulong.Parse(value, provider));
}
// Full overloads
Assert.False(ulong.TryParse(value, style, provider, out result));
Assert.Equal(default, result);
Assert.Throws(exceptionType, () => ulong.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)
{
ulong result = 0;
AssertExtensions.Throws<ArgumentException>(paramName, () => ulong.TryParse("1", style, null, out result));
Assert.Equal(default(ulong), result);
AssertExtensions.Throws<ArgumentException>(paramName, () => ulong.Parse("1", style));
AssertExtensions.Throws<ArgumentException>(paramName, () => ulong.Parse("1", style, null));
}
}
}
| |
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudioTools.Project {
internal class AssemblyReferenceNode : ReferenceNode {
#region fieds
/// <summary>
/// The name of the assembly this refernce represents
/// </summary>
private System.Reflection.AssemblyName assemblyName;
private AssemblyName resolvedAssemblyName;
private string assemblyPath = String.Empty;
/// <summary>
/// Defines the listener that would listen on file changes on the nested project node.
/// </summary>
private FileChangeManager fileChangeListener;
/// <summary>
/// A flag for specifying if the object was disposed.
/// </summary>
private bool isDisposed;
#endregion
#region properties
/// <summary>
/// The name of the assembly this reference represents.
/// </summary>
/// <value></value>
internal System.Reflection.AssemblyName AssemblyName {
get {
return this.assemblyName;
}
}
/// <summary>
/// Returns the name of the assembly this reference refers to on this specific
/// machine. It can be different from the AssemblyName property because it can
/// be more specific.
/// </summary>
internal System.Reflection.AssemblyName ResolvedAssembly {
get { return resolvedAssemblyName; }
}
public override string Url {
get {
return this.assemblyPath;
}
}
public override string Caption {
get {
return this.assemblyName.Name;
}
}
private Automation.OAAssemblyReference assemblyRef;
internal override object Object {
get {
if (null == assemblyRef) {
assemblyRef = new Automation.OAAssemblyReference(this);
}
return assemblyRef;
}
}
#endregion
#region ctors
/// <summary>
/// Constructor for the ReferenceNode
/// </summary>
public AssemblyReferenceNode(ProjectNode root, ProjectElement element)
: base(root, element) {
this.GetPathNameFromProjectFile();
this.InitializeFileChangeEvents();
if (File.Exists(assemblyPath)) {
this.fileChangeListener.ObserveItem(this.assemblyPath);
}
string include = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
this.CreateFromAssemblyName(new System.Reflection.AssemblyName(include));
}
/// <summary>
/// Constructor for the AssemblyReferenceNode
/// </summary>
public AssemblyReferenceNode(ProjectNode root, string assemblyPath)
: base(root) {
// Validate the input parameters.
if (null == root) {
throw new ArgumentNullException("root");
}
if (string.IsNullOrEmpty(assemblyPath)) {
throw new ArgumentNullException("assemblyPath");
}
this.InitializeFileChangeEvents();
// The assemblyPath variable can be an actual path on disk or a generic assembly name.
if (File.Exists(assemblyPath)) {
// The assemblyPath parameter is an actual file on disk; try to load it.
this.assemblyName = System.Reflection.AssemblyName.GetAssemblyName(assemblyPath);
this.assemblyPath = assemblyPath;
// We register with listeningto chnages onteh path here. The rest of teh cases will call into resolving the assembly and registration is done there.
this.fileChangeListener.ObserveItem(this.assemblyPath);
} else {
// The file does not exist on disk. This can be because the file / path is not
// correct or because this is not a path, but an assembly name.
// Try to resolve the reference as an assembly name.
this.CreateFromAssemblyName(new System.Reflection.AssemblyName(assemblyPath));
}
}
#endregion
#region methods
/// <summary>
/// Links a reference node to the project and hierarchy.
/// </summary>
protected override void BindReferenceData() {
UIThread.MustBeCalledFromUIThread();
Debug.Assert(this.assemblyName != null, "The AssemblyName field has not been initialized");
// If the item has not been set correctly like in case of a new reference added it now.
// The constructor for the AssemblyReference node will create a default project item. In that case the Item is null.
// We need to specify here the correct project element.
if (this.ItemNode == null || this.ItemNode is VirtualProjectElement) {
this.ItemNode = new MsBuildProjectElement(this.ProjectMgr, this.assemblyName.FullName, ProjectFileConstants.Reference);
}
// Set the basic information we know about
this.ItemNode.SetMetadata(ProjectFileConstants.Name, this.assemblyName.Name);
this.ItemNode.SetMetadata(ProjectFileConstants.AssemblyName, Path.GetFileName(this.assemblyPath));
this.SetReferenceProperties();
}
/// <summary>
/// Disposes the node
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing) {
if (this.isDisposed) {
return;
}
try {
this.UnregisterFromFileChangeService();
} finally {
base.Dispose(disposing);
this.isDisposed = true;
}
}
private void CreateFromAssemblyName(AssemblyName name) {
this.assemblyName = name;
// Use MsBuild to resolve the assemblyname
this.ResolveAssemblyReference();
if (String.IsNullOrEmpty(this.assemblyPath) && (this.ItemNode is MsBuildProjectElement)) {
// Try to get the assmbly name from the hintpath.
this.GetPathNameFromProjectFile();
if (this.assemblyPath == null) {
// Try to get the assembly name from the path
this.assemblyName = System.Reflection.AssemblyName.GetAssemblyName(this.assemblyPath);
}
}
if (null == resolvedAssemblyName) {
resolvedAssemblyName = assemblyName;
}
}
/// <summary>
/// Checks if an assembly is already added. The method parses all references and compares the full assemblynames, or the location of the assemblies to decide whether two assemblies are the same.
/// </summary>
/// <returns>true if the assembly has already been added.</returns>
protected override bool IsAlreadyAdded() {
ReferenceContainerNode referencesFolder = this.ProjectMgr.GetReferenceContainer() as ReferenceContainerNode;
Debug.Assert(referencesFolder != null, "Could not find the References node");
if (referencesFolder == null) {
// Return true so that our caller does not try and add us.
return true;
}
bool shouldCheckPath = !string.IsNullOrEmpty(this.Url);
for (HierarchyNode n = referencesFolder.FirstChild; n != null; n = n.NextSibling) {
AssemblyReferenceNode assemblyRefererenceNode = n as AssemblyReferenceNode;
if (null != assemblyRefererenceNode) {
// We will check if the full assemblynames are the same or if the Url of the assemblies is the same.
if (String.Compare(assemblyRefererenceNode.AssemblyName.FullName, this.assemblyName.FullName, StringComparison.OrdinalIgnoreCase) == 0 ||
(shouldCheckPath && CommonUtils.IsSamePath(assemblyRefererenceNode.Url, this.Url))) {
return true;
}
}
}
return false;
}
/// <summary>
/// Determines if this is node a valid node for painting the default reference icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon() {
return File.Exists(assemblyPath);
}
private void GetPathNameFromProjectFile() {
string result = this.ItemNode.GetMetadata(ProjectFileConstants.HintPath);
if (String.IsNullOrEmpty(result)) {
result = this.ItemNode.GetMetadata(ProjectFileConstants.AssemblyName);
if (String.IsNullOrEmpty(result)) {
this.assemblyPath = String.Empty;
} else if (!result.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) {
result += ".dll";
this.assemblyPath = result;
}
} else {
this.assemblyPath = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, result);
}
}
protected override void ResolveReference() {
this.ResolveAssemblyReference();
}
private void SetHintPathAndPrivateValue() {
// Private means local copy; we want to know if it is already set to not override the default
string privateValue = this.ItemNode.GetMetadata(ProjectFileConstants.Private);
// Get the list of items which require HintPath
var references = this.ProjectMgr.CurrentConfig.GetItems(MsBuildGeneratedItemType.ReferenceCopyLocalPaths);
// Now loop through the generated References to find the corresponding one
foreach (var reference in references) {
string fileName = Path.GetFileNameWithoutExtension(reference.EvaluatedInclude);
if (String.Compare(fileName, this.assemblyName.Name, StringComparison.OrdinalIgnoreCase) == 0) {
// We found it, now set some properties based on this.
// Remove the HintPath, we will re-add it below if it is needed
if (!String.IsNullOrEmpty(this.assemblyPath)) {
this.ItemNode.SetMetadata(ProjectFileConstants.HintPath, null);
}
string hintPath = reference.GetMetadataValue(ProjectFileConstants.HintPath);
if (!String.IsNullOrEmpty(hintPath)) {
hintPath = CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, hintPath);
this.ItemNode.SetMetadata(ProjectFileConstants.HintPath, hintPath);
// If this is not already set, we default to true
if (String.IsNullOrEmpty(privateValue)) {
this.ItemNode.SetMetadata(ProjectFileConstants.Private, true.ToString());
}
}
break;
}
}
}
/// <summary>
/// This function ensures that some properies of the reference are set.
/// </summary>
private void SetReferenceProperties() {
UIThread.MustBeCalledFromUIThread();
// Set a default HintPath for msbuild to be able to resolve the reference.
this.ItemNode.SetMetadata(ProjectFileConstants.HintPath, this.assemblyPath);
// Resolve assembly referernces. This is needed to make sure that properties like the full path
// to the assembly or the hint path are set.
if (!ProjectMgr.BuildProject.Targets.ContainsKey(MsBuildTarget.ResolveAssemblyReferences)) {
return;
}
if (this.ProjectMgr.Build(MsBuildTarget.ResolveAssemblyReferences) != MSBuildResult.Successful) {
return;
}
// Check if we have to resolve again the path to the assembly.
if (string.IsNullOrEmpty(this.assemblyPath)) {
ResolveReference();
}
// Make sure that the hint path if set (if needed).
SetHintPathAndPrivateValue();
}
/// <summary>
/// Does the actual job of resolving an assembly reference. We need a private method that does not violate
/// calling virtual method from the constructor.
/// </summary>
private void ResolveAssemblyReference() {
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) {
return;
}
var group = this.ProjectMgr.CurrentConfig.GetItems(ProjectFileConstants.ReferencePath);
foreach (var item in group) {
string fullPath = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, item.EvaluatedInclude);
System.Reflection.AssemblyName name = System.Reflection.AssemblyName.GetAssemblyName(fullPath);
// Try with full assembly name and then with weak assembly name.
if (String.Equals(name.FullName, this.assemblyName.FullName, StringComparison.OrdinalIgnoreCase) || String.Equals(name.Name, this.assemblyName.Name, StringComparison.OrdinalIgnoreCase)) {
if (!CommonUtils.IsSamePath(fullPath, this.assemblyPath)) {
// set the full path now.
this.assemblyPath = fullPath;
// We have a new item to listen too, since the assembly reference is resolved from a different place.
this.fileChangeListener.ObserveItem(this.assemblyPath);
}
this.resolvedAssemblyName = name;
// No hint path is needed since the assembly path will always be resolved.
return;
}
}
}
/// <summary>
/// Registers with File change events
/// </summary>
private void InitializeFileChangeEvents() {
this.fileChangeListener = new FileChangeManager(this.ProjectMgr.Site);
this.fileChangeListener.FileChangedOnDisk += this.OnAssemblyReferenceChangedOnDisk;
}
/// <summary>
/// Unregisters this node from file change notifications.
/// </summary>
private void UnregisterFromFileChangeService() {
this.fileChangeListener.FileChangedOnDisk -= this.OnAssemblyReferenceChangedOnDisk;
this.fileChangeListener.Dispose();
}
/// <summary>
/// Event callback. Called when one of the assembly file is changed.
/// </summary>
/// <param name="sender">The FileChangeManager object.</param>
/// <param name="e">Event args containing the file name that was updated.</param>
protected virtual void OnAssemblyReferenceChangedOnDisk(object sender, FileChangedOnDiskEventArgs e) {
Debug.Assert(e != null, "No event args specified for the FileChangedOnDisk event");
if (e == null) {
return;
}
// We only care about file deletes, so check for one before enumerating references.
if ((e.FileChangeFlag & _VSFILECHANGEFLAGS.VSFILECHG_Del) == 0) {
return;
}
if (CommonUtils.IsSamePath(e.FileName, this.assemblyPath)) {
ProjectMgr.OnInvalidateItems(this.Parent);
}
}
/// <summary>
/// Overridden method. The method updates the build dependency list before removing the node from the hierarchy.
/// </summary>
public override void Remove(bool removeFromStorage) {
if (this.ProjectMgr == null) {
return;
}
base.RemoveNonDocument(removeFromStorage);
this.ItemNode.RemoveFromProjectFile();
// Notify hierarchy event listeners that items have been invalidated
ProjectMgr.OnInvalidateItems(this);
// Dispose the node now that is deleted.
Dispose(true);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WebSocketHelpers.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net.WebSockets
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32;
internal static class WebSocketHelpers
{
internal const string SecWebSocketKeyGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
internal const string WebSocketUpgradeToken = "websocket";
internal const int DefaultReceiveBufferSize = 16 * 1024;
internal const int DefaultClientSendBufferSize = 16 * 1024;
internal const int MaxControlFramePayloadLength = 123;
// RFC 6455 requests WebSocket clients to let the server initiate the TCP close to avoid that client sockets
// end up in TIME_WAIT-state
//
// After both sending and receiving a Close message, an endpoint considers the WebSocket connection closed and
// MUST close the underlying TCP connection. The server MUST close the underlying TCP connection immediately;
// the client SHOULD wait for the server to close the connection but MAY close the connection at any time after
// sending and receiving a Close message, e.g., if it has not received a TCP Close from the server in a
// reasonable time period.
internal const int ClientTcpCloseTimeout = 1000; // 1s
private const int CloseStatusCodeAbort = 1006;
private const int CloseStatusCodeFailedTLSHandshake = 1015;
private const int InvalidCloseStatusCodesFrom = 0;
private const int InvalidCloseStatusCodesTo = 999;
private const string Separators = "()<>@,;:\\\"/[]?={} ";
private static readonly ArraySegment<byte> s_EmptyPayload = new ArraySegment<byte>(new byte[] { }, 0, 0);
private static readonly Random s_KeyGenerator = new Random();
private static volatile bool s_HttpSysSupportsWebSockets = ComNetOS.IsWin8orLater;
internal static ArraySegment<byte> EmptyPayload
{
get { return s_EmptyPayload; }
}
internal static Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(HttpListenerContext context,
string subProtocol,
int receiveBufferSize,
TimeSpan keepAliveInterval,
ArraySegment<byte> internalBuffer)
{
WebSocketHelpers.ValidateOptions(subProtocol, receiveBufferSize, WebSocketBuffer.MinSendBufferSize, keepAliveInterval);
WebSocketHelpers.ValidateArraySegment<byte>(internalBuffer, "internalBuffer");
WebSocketBuffer.Validate(internalBuffer.Count, receiveBufferSize, WebSocketBuffer.MinSendBufferSize, true);
return AcceptWebSocketAsyncCore(context, subProtocol, receiveBufferSize, keepAliveInterval, internalBuffer);
}
private static async Task<HttpListenerWebSocketContext> AcceptWebSocketAsyncCore(HttpListenerContext context,
string subProtocol,
int receiveBufferSize,
TimeSpan keepAliveInterval,
ArraySegment<byte> internalBuffer)
{
HttpListenerWebSocketContext webSocketContext = null;
if (Logging.On)
{
Logging.Enter(Logging.WebSockets, context, "AcceptWebSocketAsync", "");
}
try
{
// get property will create a new response if one doesn't exist.
HttpListenerResponse response = context.Response;
HttpListenerRequest request = context.Request;
ValidateWebSocketHeaders(context);
string secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion];
// Optional for non-browser client
string origin = request.Headers[HttpKnownHeaderNames.Origin];
List<string> secWebSocketProtocols = new List<string>();
string outgoingSecWebSocketProtocolString;
bool shouldSendSecWebSocketProtocolHeader =
WebSocketHelpers.ProcessWebSocketProtocolHeader(
request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol],
subProtocol,
out outgoingSecWebSocketProtocolString);
if (shouldSendSecWebSocketProtocolHeader)
{
secWebSocketProtocols.Add(outgoingSecWebSocketProtocolString);
response.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol,
outgoingSecWebSocketProtocolString);
}
// negotiate the websocket key return value
string secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey];
string secWebSocketAccept = WebSocketHelpers.GetSecWebSocketAcceptString(secWebSocketKey);
response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade);
response.Headers.Add(HttpKnownHeaderNames.Upgrade, WebSocketHelpers.WebSocketUpgradeToken);
response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept);
response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101
response.ComputeCoreHeaders();
ulong hresult = SendWebSocketHeaders(response);
if (hresult != 0)
{
throw new WebSocketException((int)hresult,
SR.GetString(SR.net_WebSockets_NativeSendResponseHeaders,
WebSocketHelpers.MethodNames.AcceptWebSocketAsync,
hresult));
}
if (Logging.On)
{
Logging.PrintInfo(Logging.WebSockets, string.Format("{0} = {1}",
HttpKnownHeaderNames.Origin, origin));
Logging.PrintInfo(Logging.WebSockets, string.Format("{0} = {1}",
HttpKnownHeaderNames.SecWebSocketVersion, secWebSocketVersion));
Logging.PrintInfo(Logging.WebSockets, string.Format("{0} = {1}",
HttpKnownHeaderNames.SecWebSocketKey, secWebSocketKey));
Logging.PrintInfo(Logging.WebSockets, string.Format("{0} = {1}",
HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept));
Logging.PrintInfo(Logging.WebSockets, string.Format("Request {0} = {1}",
HttpKnownHeaderNames.SecWebSocketProtocol,
request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol]));
Logging.PrintInfo(Logging.WebSockets, string.Format("Response {0} = {1}",
HttpKnownHeaderNames.SecWebSocketProtocol, outgoingSecWebSocketProtocolString));
}
await response.OutputStream.FlushAsync().SuppressContextFlow();
HttpResponseStream responseStream = response.OutputStream as HttpResponseStream;
Contract.Assert(responseStream != null, "'responseStream' MUST be castable to System.Net.HttpResponseStream.");
((HttpResponseStream)response.OutputStream).SwitchToOpaqueMode();
HttpRequestStream requestStream = new HttpRequestStream(context);
requestStream.SwitchToOpaqueMode();
WebSocketHttpListenerDuplexStream webSocketStream =
new WebSocketHttpListenerDuplexStream(requestStream, responseStream, context);
WebSocket webSocket = WebSocket.CreateServerWebSocket(webSocketStream,
subProtocol,
receiveBufferSize,
keepAliveInterval,
internalBuffer);
webSocketContext = new HttpListenerWebSocketContext(
request.Url,
request.Headers,
request.Cookies,
context.User,
request.IsAuthenticated,
request.IsLocal,
request.IsSecureConnection,
origin,
secWebSocketProtocols.AsReadOnly(),
secWebSocketVersion,
secWebSocketKey,
webSocket);
if (Logging.On)
{
Logging.Associate(Logging.WebSockets, context, webSocketContext);
Logging.Associate(Logging.WebSockets, webSocketContext, webSocket);
}
}
catch (Exception ex)
{
if (Logging.On)
{
Logging.Exception(Logging.WebSockets, context, "AcceptWebSocketAsync", ex);
}
throw;
}
finally
{
if (Logging.On)
{
Logging.Exit(Logging.WebSockets, context, "AcceptWebSocketAsync", "");
}
}
return webSocketContext;
}
[SuppressMessage("Microsoft.Cryptographic.Standard", "CA5354:SHA1CannotBeUsed",
Justification = "SHA1 used only for hashing purposes, not for crypto.")]
internal static string GetSecWebSocketAcceptString(string secWebSocketKey)
{
string retVal;
// SHA1 used only for hashing purposes, not for crypto. Check here for FIPS compat.
using (SHA1 sha1 = SHA1.Create())
{
string acceptString = string.Concat(secWebSocketKey, WebSocketHelpers.SecWebSocketKeyGuid);
byte[] toHash = Encoding.UTF8.GetBytes(acceptString);
retVal = Convert.ToBase64String(sha1.ComputeHash(toHash));
}
return retVal;
}
internal static string GetTraceMsgForParameters(int offset, int count, CancellationToken cancellationToken)
{
return string.Format(CultureInfo.InvariantCulture,
"offset: {0}, count: {1}, cancellationToken.CanBeCanceled: {2}",
offset,
count,
cancellationToken.CanBeCanceled);
}
// return value here signifies if a Sec-WebSocket-Protocol header should be returned by the server.
internal static bool ProcessWebSocketProtocolHeader(string clientSecWebSocketProtocol,
string subProtocol,
out string acceptProtocol)
{
acceptProtocol = string.Empty;
if (string.IsNullOrEmpty(clientSecWebSocketProtocol))
{
// client hasn't specified any Sec-WebSocket-Protocol header
if (subProtocol != null)
{
// If the server specified _anything_ this isn't valid.
throw new WebSocketException(WebSocketError.UnsupportedProtocol,
SR.GetString(SR.net_WebSockets_ClientAcceptingNoProtocols, subProtocol));
}
// Treat empty and null from the server as the same thing here, server should not send headers.
return false;
}
// here, we know the client specified something and it's non-empty.
if (subProtocol == null)
{
// client specified some protocols, server specified 'null'. So server should send headers.
return true;
}
// here, we know that the client has specified something, it's not empty
// and the server has specified exactly one protocol
string[] requestProtocols = clientSecWebSocketProtocol.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
acceptProtocol = subProtocol;
// client specified protocols, serverOptions has exactly 1 non-empty entry. Check that
// this exists in the list the client specified.
for (int i = 0; i < requestProtocols.Length; i++)
{
string currentRequestProtocol = requestProtocols[i].Trim();
if (string.Compare(acceptProtocol, currentRequestProtocol, StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
}
throw new WebSocketException(WebSocketError.UnsupportedProtocol,
SR.GetString(SR.net_WebSockets_AcceptUnsupportedProtocol,
clientSecWebSocketProtocol,
subProtocol));
}
internal static ConfiguredTaskAwaitable SuppressContextFlow(this Task task)
{
// We don't flow the synchronization context within WebSocket.xxxAsync - but the calling application
// can decide whether the completion callback for the task returned from WebSocket.xxxAsync runs
// under the caller's synchronization context.
return task.ConfigureAwait(false);
}
internal static ConfiguredTaskAwaitable<T> SuppressContextFlow<T>(this Task<T> task)
{
// We don't flow the synchronization context within WebSocket.xxxAsync - but the calling application
// can decide whether the completion callback for the task returned from WebSocket.xxxAsync runs
// under the caller's synchronization context.
return task.ConfigureAwait(false);
}
internal static void ValidateBuffer(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0 || count > (buffer.Length - offset))
{
throw new ArgumentOutOfRangeException("count");
}
}
private static unsafe ulong SendWebSocketHeaders(HttpListenerResponse response)
{
return response.SendHeaders(null, null,
UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_OPAQUE |
UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA |
UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA,
true);
}
private static void ValidateWebSocketHeaders(HttpListenerContext context)
{
EnsureHttpSysSupportsWebSockets();
if (!context.Request.IsWebSocketRequest)
{
throw new WebSocketException(WebSocketError.NotAWebSocket,
SR.GetString(SR.net_WebSockets_AcceptNotAWebSocket,
WebSocketHelpers.MethodNames.ValidateWebSocketHeaders,
HttpKnownHeaderNames.Connection,
HttpKnownHeaderNames.Upgrade,
WebSocketHelpers.WebSocketUpgradeToken,
context.Request.Headers[HttpKnownHeaderNames.Upgrade]));
}
string secWebSocketVersion = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketVersion];
if (string.IsNullOrEmpty(secWebSocketVersion))
{
throw new WebSocketException(WebSocketError.HeaderError,
SR.GetString(SR.net_WebSockets_AcceptHeaderNotFound,
WebSocketHelpers.MethodNames.ValidateWebSocketHeaders,
HttpKnownHeaderNames.SecWebSocketVersion));
}
if (string.Compare(secWebSocketVersion, WebSocketProtocolComponent.SupportedVersion, StringComparison.OrdinalIgnoreCase) != 0)
{
throw new WebSocketException(WebSocketError.UnsupportedVersion,
SR.GetString(SR.net_WebSockets_AcceptUnsupportedWebSocketVersion,
WebSocketHelpers.MethodNames.ValidateWebSocketHeaders,
secWebSocketVersion,
WebSocketProtocolComponent.SupportedVersion));
}
if (string.IsNullOrWhiteSpace(context.Request.Headers[HttpKnownHeaderNames.SecWebSocketKey]))
{
throw new WebSocketException(WebSocketError.HeaderError,
SR.GetString(SR.net_WebSockets_AcceptHeaderNotFound,
WebSocketHelpers.MethodNames.ValidateWebSocketHeaders,
HttpKnownHeaderNames.SecWebSocketKey));
}
}
internal static void PrepareWebRequest(ref HttpWebRequest request)
{
request.Connection = HttpKnownHeaderNames.Upgrade;
request.Headers[HttpKnownHeaderNames.Upgrade] = WebSocketUpgradeToken;
byte[] keyBlob = new byte[16];
lock (s_KeyGenerator)
{
s_KeyGenerator.NextBytes(keyBlob);
}
request.Headers[HttpKnownHeaderNames.SecWebSocketKey] = Convert.ToBase64String(keyBlob);
if (WebSocketProtocolComponent.IsSupported)
{
request.Headers[HttpKnownHeaderNames.SecWebSocketVersion] = WebSocketProtocolComponent.SupportedVersion;
}
}
internal static void ValidateSubprotocol(string subProtocol)
{
if (string.IsNullOrWhiteSpace(subProtocol))
{
throw new ArgumentException(SR.GetString(SR.net_WebSockets_InvalidEmptySubProtocol), "subProtocol");
}
char[] chars = subProtocol.ToCharArray();
string invalidChar = null;
int i = 0;
while (i < chars.Length)
{
char ch = chars[i];
if (ch < 0x21 || ch > 0x7e)
{
invalidChar = string.Format(CultureInfo.InvariantCulture, "[{0}]", (int)ch);
break;
}
if (!char.IsLetterOrDigit(ch) &&
Separators.IndexOf(ch) >= 0)
{
invalidChar = ch.ToString();
break;
}
i++;
}
if (invalidChar != null)
{
throw new ArgumentException(SR.GetString(SR.net_WebSockets_InvalidCharInProtocolString, subProtocol, invalidChar),
"subProtocol");
}
}
internal static void ValidateCloseStatus(WebSocketCloseStatus closeStatus, string statusDescription)
{
if (closeStatus == WebSocketCloseStatus.Empty && !string.IsNullOrEmpty(statusDescription))
{
throw new ArgumentException(SR.GetString(SR.net_WebSockets_ReasonNotNull,
statusDescription,
WebSocketCloseStatus.Empty),
"statusDescription");
}
int closeStatusCode = (int)closeStatus;
if ((closeStatusCode >= InvalidCloseStatusCodesFrom &&
closeStatusCode <= InvalidCloseStatusCodesTo) ||
closeStatusCode == CloseStatusCodeAbort ||
closeStatusCode == CloseStatusCodeFailedTLSHandshake)
{
// CloseStatus 1006 means Aborted - this will never appear on the wire and is reflected by calling WebSocket.Abort
throw new ArgumentException(SR.GetString(SR.net_WebSockets_InvalidCloseStatusCode,
closeStatusCode),
"closeStatus");
}
int length = 0;
if (!string.IsNullOrEmpty(statusDescription))
{
length = UTF8Encoding.UTF8.GetByteCount(statusDescription);
}
if (length > WebSocketHelpers.MaxControlFramePayloadLength)
{
throw new ArgumentException(SR.GetString(SR.net_WebSockets_InvalidCloseStatusDescription,
statusDescription,
WebSocketHelpers.MaxControlFramePayloadLength),
"statusDescription");
}
}
internal static void ValidateOptions(string subProtocol,
int receiveBufferSize,
int sendBufferSize,
TimeSpan keepAliveInterval)
{
// We allow the subProtocol to be null. Validate if it is not null.
if (subProtocol != null)
{
ValidateSubprotocol(subProtocol);
}
ValidateBufferSizes(receiveBufferSize, sendBufferSize);
if (keepAliveInterval < Timeout.InfiniteTimeSpan) // -1
{
throw new ArgumentOutOfRangeException("keepAliveInterval", keepAliveInterval,
SR.GetString(SR.net_WebSockets_ArgumentOutOfRange_TooSmall, Timeout.InfiniteTimeSpan.ToString()));
}
}
internal static void ValidateBufferSizes(int receiveBufferSize, int sendBufferSize)
{
if (receiveBufferSize < WebSocketBuffer.MinReceiveBufferSize)
{
throw new ArgumentOutOfRangeException("receiveBufferSize", receiveBufferSize,
SR.GetString(SR.net_WebSockets_ArgumentOutOfRange_TooSmall, WebSocketBuffer.MinReceiveBufferSize));
}
if (sendBufferSize < WebSocketBuffer.MinSendBufferSize)
{
throw new ArgumentOutOfRangeException("sendBufferSize", sendBufferSize,
SR.GetString(SR.net_WebSockets_ArgumentOutOfRange_TooSmall, WebSocketBuffer.MinSendBufferSize));
}
if (receiveBufferSize > WebSocketBuffer.MaxBufferSize)
{
throw new ArgumentOutOfRangeException("receiveBufferSize", receiveBufferSize,
SR.GetString(SR.net_WebSockets_ArgumentOutOfRange_TooBig,
"receiveBufferSize",
receiveBufferSize,
WebSocketBuffer.MaxBufferSize));
}
if (sendBufferSize > WebSocketBuffer.MaxBufferSize)
{
throw new ArgumentOutOfRangeException("sendBufferSize", sendBufferSize,
SR.GetString(SR.net_WebSockets_ArgumentOutOfRange_TooBig,
"sendBufferSize",
sendBufferSize,
WebSocketBuffer.MaxBufferSize));
}
}
internal static void ValidateInnerStream(Stream innerStream)
{
if (innerStream == null)
{
throw new ArgumentNullException("innerStream");
}
if (!innerStream.CanRead)
{
throw new ArgumentException(SR.GetString(SR.NotReadableStream), "innerStream");
}
if (!innerStream.CanWrite)
{
throw new ArgumentException(SR.GetString(SR.NotWriteableStream), "innerStream");
}
}
internal static void ThrowIfConnectionAborted(Stream connection, bool read)
{
if ((!read && !connection.CanWrite) ||
(read && !connection.CanRead))
{
throw new WebSocketException(WebSocketError.ConnectionClosedPrematurely);
}
}
internal static void ThrowPlatformNotSupportedException_WSPC()
{
throw new PlatformNotSupportedException(SR.GetString(SR.net_WebSockets_UnsupportedPlatform));
}
private static void ThrowPlatformNotSupportedException_HTTPSYS()
{
throw new PlatformNotSupportedException(SR.GetString(SR.net_WebSockets_UnsupportedPlatform));
}
internal static void ValidateArraySegment<T>(ArraySegment<T> arraySegment, string parameterName)
{
Contract.Requires(!string.IsNullOrEmpty(parameterName), "'parameterName' MUST NOT be NULL or string.Empty");
if (arraySegment.Array == null)
{
throw new ArgumentNullException(parameterName + ".Array");
}
if (arraySegment.Offset < 0 || arraySegment.Offset > arraySegment.Array.Length)
{
throw new ArgumentOutOfRangeException(parameterName + ".Offset");
}
if (arraySegment.Count < 0 || arraySegment.Count > (arraySegment.Array.Length - arraySegment.Offset))
{
throw new ArgumentOutOfRangeException(parameterName + ".Count");
}
}
private static void EnsureHttpSysSupportsWebSockets()
{
if (!s_HttpSysSupportsWebSockets)
{
ThrowPlatformNotSupportedException_HTTPSYS();
}
}
internal static class MethodNames
{
internal const string AcceptWebSocketAsync = "AcceptWebSocketAsync";
internal const string ValidateWebSocketHeaders = "ValidateWebSocketHeaders";
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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
//namespace Instinct.ApplicationUnit_.WebApplicationControl
//{
// //- GoogleMap -//
// //+ [GoogleApi]http://www.google.com/apis/maps/documentation/
// //+ [Geocoder]http://geocoder.us/help/
// public class GoogleMap : System.Web.UI.WebControls.WebControl
// {
// private static System.Type s_type = typeof(GoogleMap);
// private System.Collections.Generic.Dictionary<int, GoogleMapPoint> m_pointHash = new System.Collections.Generic.Dictionary<int, GoogleMapPoint>();
// private System.Collections.Generic.Dictionary<int, GoogleMapTextOverlay> m_textOverlayHash = new System.Collections.Generic.Dictionary<int, GoogleMapTextOverlay>();
// private string m_keyId = string.Empty;
// private int m_zoomOffset = 0;
// private GoogleMapControlType m_controlType = GoogleMapControlType.Small;
// private GoogleMapPointType m_pointType = GoogleMapPointType.Simple;
// private bool m_isAutoSelect = true;
// private string m_iconRootUri = "/";
// //- GoogleMapControlType -//
// public enum GoogleMapControlType
// {
// Large,
// LargePlus,
// Small,
// SmallPlus
// }
// //- GoogleMapPointType -//
// public enum GoogleMapPointType
// {
// Simple,
// Direction
// }
// //- Main -//
// public GoogleMap()
// {
// Width = new System.Web.UI.WebControls.Unit("560px");
// Height = new System.Web.UI.WebControls.Unit("400px");
// }
// public GoogleMap(string width, string height)
// {
// Width = new System.Web.UI.WebControls.Unit(width);
// Height = new System.Web.UI.WebControls.Unit(height);
// }
// //- AddPoint -//
// public void AddPoint(GoogleMapPoint point)
// {
// m_pointHash.Add(m_pointHash.Count, point);
// }
// //- AddTextOverlay -//
// public void AddTextOverlay(GoogleMapTextOverlay textOverlay)
// {
// m_textOverlayHash.Add(m_textOverlayHash.Count, textOverlay);
// }
// //- AppendMapToStream -//
// private void AppendMapToStream(System.Text.StringBuilder textStream)
// {
// textStream.AppendLine(" var map = new GMap2(document.getElementById(\"" + ClientID + "\"));");
// switch (m_controlType)
// {
// case GoogleMapControlType.Large:
// textStream.AppendLine(" map.addControl(new GLargeMapControl());");
// break;
// case GoogleMapControlType.LargePlus:
// textStream.AppendLine(" map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl());");
// break;
// case GoogleMapControlType.Small:
// textStream.AppendLine(" map.addControl(new GSmallMapControl());");
// break;
// case GoogleMapControlType.SmallPlus:
// textStream.AppendLine(" map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl());");
// break;
// }
// }
// //- ControlType -//
// public GoogleMapControlType ControlType
// {
// get
// {
// return m_controlType;
// }
// set
// {
// m_controlType = value;
// }
// }
// //- ZoomOffset -//
// public int ZoomOffset
// {
// get
// {
// return m_zoomOffset;
// }
// set
// {
// m_zoomOffset = value;
// }
// }
// //- KeyId -//
// public string KeyId
// {
// get
// {
// return m_keyId;
// }
// set
// {
// m_keyId = value;
// }
// }
// //- PointType -//
// public GoogleMapPointType PointType
// {
// get
// {
// return m_pointType;
// }
// set
// {
// m_pointType = value;
// }
// }
// //- IconRootUri -//
// public string IconRootUri
// {
// get
// {
// return m_iconRootUri;
// }
// set
// {
// m_iconRootUri = value;
// }
// }
// //- IsAutoSelect -//
// public bool IsAutoSelect
// {
// get
// {
// return m_isAutoSelect;
// }
// set
// {
// m_isAutoSelect = value;
// }
// }
// //- OnPreRender -//
// protected override void OnPreRender(System.EventArgs e)
// {
// base.OnPreRender(e);
// WebApplicationFactory.RegisterScript(Page, WebApplicationFactory.RegisterScriptFlag.Kernel);
// Page.ClientScript.RegisterClientScriptInclude(s_type, "Google", "http://maps.google.com/maps?file=api&v=2&key=" + m_keyId);
// if (m_textOverlayHash.Count > 0)
// {
// Page.ClientScript.RegisterClientScriptBlock(s_type, "GoogleMapTextOverlay", @"
//<script type=""text/javascript"">
////<![CDATA[
//function GoogleMapTextOverlay(html, point, width, height, borderStyle, moveByX, moveByY, textAlign, verticalAlign) {
// this.html_ = html;
// this.point_ = point;
// this.width_ = width;
// this.height_ = height;
// this.borderStyle_ = borderStyle;
// this.moveByX_ = moveByX;
// this.moveByY_ = moveByY;
// this.textAlign_ = textAlign;
// this.verticalAlign_ = verticalAlign;
//}
//GoogleMapTextOverlay.prototype = new GOverlay();
//
////+ creates the DIV representing this GoogleMapTextOverlay.
//GoogleMapTextOverlay.prototype.initialize = function(map) {
// // create the div representing our GoogleMapTextOverlay
// var div = document.createElement('div');
// div.style.border = this.borderStyle_;
// div.style.position = 'absolute';
// div.style.width = this.width_;
// div.style.height = this.height_;
// div.style.textAlign = this.textAlign_;
// div.style.verticalAlign = this.verticalAlign_;
// div.innerHTML = this.html_;
// //+ GoogleMapTextOverlay is flat against the map, so we add our selves to the MAP_PANE pane,
// //+ which is at the same z-index as the map itself (i.e., below the marker shadows)
// map.getPane(G_MAP_MAP_PANE).appendChild(div);
// //+
// this.map_ = map;
// this.div_ = div;
//}
//
////+ remove the main DIV from the map pane
//GoogleMapTextOverlay.prototype.remove = function() {
// this.div_.parentNode.removeChild(this.div_);
//}
//
////+ copy data to a new GoogleMapTextOverlay
//GoogleMapTextOverlay.prototype.copy = function() {
// return new GoogleMapTextOverlay(this.html_, this.point_, this.width_, this.height_, this.borderStyle_, this.moveByX_, this.moveByY_, this.textAlign_, this.verticalAlign_);
//}
//
////+ redraw the GoogleMapTextOverlay based on the current projection and zoom level
//GoogleMapTextOverlay.prototype.redraw = function(force) {
// // redraw only if the coordinate system has changed
// if (!force) return;
// //+ map point to location in div
// var c1 = this.map_.fromLatLngToDivPixel(this.point_);
// // position div
// this.div_.style.left = (c1.x + this.moveByX_) + 'px';
// this.div_.style.top = (c1.y + this.moveByY_) + 'px';
//}
////]]>
//</script>", false);
// }
// switch (m_pointType)
// {
// case GoogleMapPointType.Direction:
// if (Page.ClientScript.IsClientScriptBlockRegistered(s_type, "Direction") == false)
// {
// string clientId = ClientID;
// System.Text.StringBuilder textBuilder = new System.Text.StringBuilder();
// textBuilder.Append(@"<script type=""text/javascript"">
////<![CDATA[
//function GoogleMapTo(key) {
// var o = _gel('"); textBuilder.Append(clientId); textBuilder.Append(@"');
// if (o != null) {
// o.Marker[key].openInfoWindowHtml(o.ToText[key]);
// }
//}
//function GoogleMapFrom(key) {
// var o = _gel('"); textBuilder.Append(clientId); textBuilder.Append(@"');
// if (o != null) {
// o.Marker[key].openInfoWindowHtml(o.FromText[key]);
// }
//}
//var g_icon = new GIcon();
//g_icon.shadow = '"); textBuilder.Append(m_iconRootUri); textBuilder.Append(@"IconShadow.png';
//g_icon.iconSize = new GSize(20, 34);
//g_icon.shadowSize = new GSize(37, 34);
//g_icon.iconAnchor = new GPoint(9, 34);
//g_icon.infoWindowAnchor = new GPoint(9, 2);
//g_icon.infoShadowAnchor = new GPoint(18, 25);
//function CreatePoint(o, bound, key, icon, point, address, text) {
// bound.extend(point);
// o.ToText[key] = text
// + '<br />Directions: <b>To here</b> - <a href=""javascript:GoogleMapFrom(' + key + ')"">From here</a>'
// + '<br />Start address:<form action=""http://maps.google.com/maps"" method=""get"" target=""_blank"" style=""margin: 0;"">'
// + '<input id=""saddr"" name=""saddr"" type=""text"" size=""25"" maxlength=""60"" value="""" /><br />'
// + '<input value=""Get Directions"" type=""submit"">'
// + '<input type=""hidden"" name=""daddr"" value=""' + address + '""/></form>';
// o.FromText[key] = text
// + '<br />Directions: <a href=""javascript:GoogleMapTo(' + key + ')"">To here</a> - <b>From here</b>'
// + '<br />End address:<form action=""http://maps.google.com/maps"" method=""get"" target=""_blank"" style=""margin: 0;"">'
// + '<input id=""daddr"" name=""daddr"" type=""text"" size=""25"" maxlength=""60"" value="""" /><br />'
// + '<input value=""Get Directions"" type=""submit"">'
// + '<input type=""hidden"" name=""saddr"" value=""' + address + '""/></form>';
// text = text.replace(/\[\:Direction\:\]/, 'Directions: <a href=""javascript:GoogleMapTo(' + key + ')"">To here</a> - <a href=""javascript:GoogleMapFrom(' + key + ')"">From here</a>');
// if (icon != '') {
// var icon2 = new GIcon(g_icon);
// icon2.image = '"); textBuilder.Append(m_iconRootUri); textBuilder.Append(@"' + icon + '.png';
// var marker = new GMarker(point, icon2);
// } else {
// var marker = new GMarker(point);
// }
// GEvent.addListener(marker, 'click', function() {
// marker.openInfoWindowHtml(text);
// });
// o.Marker[key] = marker;
// o.Text[key] = text;
// return marker;
//}
////]]>
//</script>");
// Page.ClientScript.RegisterClientScriptBlock(s_type, "Direction", textBuilder.ToString(), false);
// }
// break;
// }
// }
// //- Render -//
// protected override void Render(System.Web.UI.HtmlTextWriter writer)
// {
// HtmlBuilder z = HtmlBuilder.GetBuilder(writer);
// //+
// string clientId = ClientID;
// System.Text.StringBuilder textBuilder;
// switch (m_pointType)
// {
// case GoogleMapPointType.Simple:
// if (m_pointHash.Count < 1)
// {
// return;
// }
// //+ startup script
// textBuilder = new System.Text.StringBuilder();
// textBuilder.AppendLine("if (GBrowserIsCompatible() != null) {");
// AppendMapToStream(textBuilder);
// GoogleMapPoint point = m_pointHash[0];
// //+ 37.4419, -122.1419, 13
// textBuilder.AppendFormat(" map.setCenter(new GLatLng({0}, {1}), {2});\r\n", point.Latitude, point.Longitude, point.Zoom); point = null;
// //+ text overlay
// foreach (GoogleMapTextOverlay textOverlay in m_textOverlayHash.Values)
// {
// textBuilder.AppendFormat(" map.addOverlay(new GoogleMapTextOverlay('{0}', new GLatLng({1}, {2}), '{3}', '{4}', '{5}', {6}, {7}, '{8}', '{9}'));\r\n", textOverlay.Html, textOverlay.Latitude, textOverlay.Longitude, textOverlay.Width, textOverlay.Height, textOverlay.BorderStyle, textOverlay.MoveByX, textOverlay.MoveByY, textOverlay.TextAlign, textOverlay.VerticalAlign);
// }
// textBuilder.AppendLine("}");
// Page.ClientScript.RegisterStartupScript(s_type, clientId, textBuilder.ToString(), true);
// break;
// case GoogleMapPointType.Direction:
// if (m_pointHash.Count < 1)
// {
// return;
// }
// //+ startup script
// textBuilder = new System.Text.StringBuilder();
// textBuilder.Append(@"<script type=""text/javascript"">
////<![CDATA[
//if (window.Kernel) {
// Kernel.AddEvent(window, 'load', function() {
//var o = _gel('"); textBuilder.Append(clientId); textBuilder.AppendLine(@"');
//if ((o != null) && (GBrowserIsCompatible() != null)) {
// var key = 0;
// o.Marker = [];
// o.Text = [];
// o.ToText = [];
// o.FromText = [];");
// AppendMapToStream(textBuilder);
// textBuilder.AppendLine(" var bound = new GLatLngBounds();");
// foreach (GoogleMapPoint point2 in m_pointHash.Values)
// {
// string address = KernelText.Axb(point2.Street, " ", point2.Street2) + ", " + KernelText.Axb(KernelText.Axb(point2.City, " ", point2.State), " ", point2.Zip);
// textBuilder.AppendFormat(" CreatePoint(o, bound, key++, '{0}', new GLatLng({1}, {2}), unescape('{3}'), unescape('{4}'));\r\n", point2.Icon, point2.Latitude, point2.Longitude, Http.Escape(address), Http.Escape(point2.Text));
// }
// textBuilder.Append(@"
// var centerLat = (bound.getNorthEast().lat() + bound.getSouthWest().lat()) / 2;
// var centerLng = (bound.getNorthEast().lng() + bound.getSouthWest().lng()) / 2;
// var zoomLevel = map.getBoundsZoomLevel(bound);
// map.setCenter(new GLatLng(centerLat, centerLng), zoomLevel - "); textBuilder.Append(m_zoomOffset); textBuilder.Append(@");
// while (key > 0) {
// map.addOverlay(o.Marker[--key]);
// };");
// if ((m_isAutoSelect == true) && (m_pointHash.Count == 1))
// {
// textBuilder.AppendLine(" o.Marker[0].openInfoWindowHtml(o.Text[0]);");
// }
// //+ text overlay
// foreach (GoogleMapTextOverlay textOverlay in m_textOverlayHash.Values)
// {
// textBuilder.AppendFormat(" map.addOverlay(new GoogleMapTextOverlay('{0}', new GLatLng({1}, {2}), '{3}', '{4}', '{5}', {6}, {7}, '{8}', '{9}'));\r\n", textOverlay.Html, textOverlay.Latitude, textOverlay.Longitude, textOverlay.Width, textOverlay.Height, textOverlay.BorderStyle, textOverlay.MoveByX, textOverlay.MoveByY, textOverlay.TextAlign, textOverlay.VerticalAlign);
// }
// textBuilder.Append(@"
//}
// });
//}
////]]>
//</script>");
// Page.ClientScript.RegisterStartupScript(s_type, clientId, textBuilder.ToString(), false);
// break;
// }
// //+ render
// z.AddHtmlAttrib(HtmlAttrib.Id, clientId);
// z.AddHtmlAttrib(HtmlAttrib.StyleWidth, Width.ToString());
// z.AddHtmlAttrib(HtmlAttrib.StyleHeight, Height.ToString());
// z.EmptyHtmlTag(HtmlTag.Div);
// }
// //- POINT -//
// #region POINT
// //- GoogleMapPoint -//
// public class GoogleMapPoint
// {
// private string m_icon = string.Empty;
// private string m_street = string.Empty;
// private string m_street2 = string.Empty;
// private string m_city = string.Empty;
// private string m_state = string.Empty;
// private string m_zip = string.Empty;
// private string m_text = string.Empty;
// private decimal m_latitude = -1;
// private decimal m_longitude = -1;
// private int m_zoom = -1;
// //- Main -//
// public GoogleMapPoint()
// {
// }
// public GoogleMapPoint(TableBase table, string fieldPrefix)
// {
// m_street = table.GetText(fieldPrefix + "Street");
// m_street2 = table.GetText(fieldPrefix + "Street2");
// m_city = table.GetText(fieldPrefix + "City");
// m_state = table.GetText(fieldPrefix + "State");
// m_zip = table.GetText(fieldPrefix + "Zip");
// SetCoordinate(table[fieldPrefix + "Latitude"], table[fieldPrefix + "Longitude"]);
// }
// //- Icon -//
// public string Icon
// {
// get
// {
// return m_icon;
// }
// set
// {
// m_icon = value;
// }
// }
// //- Street -//
// public string Street
// {
// get
// {
// return m_street;
// }
// set
// {
// m_street = value;
// }
// }
// //- Street2 -//
// public string Street2
// {
// get
// {
// return m_street2;
// }
// set
// {
// m_street2 = value;
// }
// }
// //- City -//
// public string City
// {
// get
// {
// return m_city;
// }
// set
// {
// m_city = value;
// }
// }
// //- State -//
// public string State
// {
// get
// {
// return m_state;
// }
// set
// {
// m_state = value;
// }
// }
// //- Zip -//
// public string Zip
// {
// get
// {
// return m_zip;
// }
// set
// {
// m_zip = value;
// }
// }
// //- Text -//
// public string Text
// {
// get
// {
// return m_text;
// }
// set
// {
// m_text = value;
// }
// }
// //- Latitude -//
// public decimal Latitude
// {
// get
// {
// return m_latitude;
// }
// set
// {
// m_latitude = value;
// }
// }
// //- Longitude -//
// public decimal Longitude
// {
// get
// {
// return m_longitude;
// }
// set
// {
// m_longitude = value;
// }
// }
// //- Zoom -//
// public int Zoom
// {
// get
// {
// return m_zoom;
// }
// set
// {
// m_zoom = value;
// }
// }
// //- SetCoordinate -//
// public void SetCoordinate(object latitude, object longitude)
// {
// string textLatitude;
// m_latitude = -1;
// if (latitude != null)
// {
// if (latitude is decimal)
// {
// m_latitude = (decimal)latitude;
// }
// else if ((textLatitude = (latitude as string)) != null)
// {
// decimal.TryParse(textLatitude, out m_latitude);
// }
// }
// string textLongitude;
// m_longitude = -1;
// if (longitude != null)
// {
// if (longitude is decimal)
// {
// m_longitude = (decimal)longitude;
// }
// else if ((textLongitude = (longitude as string)) != null)
// {
// decimal.TryParse(textLongitude, out m_longitude);
// }
// }
// }
// //- GeocodeAddress -//
// public bool GeocodeAddress(string googleMapApi)
// {
// string url = "http://maps.google.com/maps/geo?q=" + Http.UrlEncode(string.Concat(KernelText.Axb(Street, " ", Street2), ", ", KernelText.Axb(KernelText.Axb(City, " ", State), " ", Zip))) + "&output=csv&key=" + googleMapApi;
// System.Net.HttpWebRequest httpRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
// System.Net.HttpWebResponse httpResponse = null;
// try
// {
// httpResponse = (System.Net.HttpWebResponse)httpRequest.GetResponse();
// }
// catch (System.Exception)
// {
// return false;
// }
// string[] responseArray;
// try
// {
// responseArray = KernelIo.ReadTextStream(httpResponse.GetResponseStream()).Split(new string[] { "\r\n" }, System.StringSplitOptions.RemoveEmptyEntries);
// }
// catch (System.Exception e)
// {
// KernelEvent.LogEvent(LogEventType.Warning, "GoogleMap::GeocodeAddress", e);
// return false;
// }
// finally
// {
// httpResponse.Close();
// }
// responseArray = responseArray[responseArray.GetUpperBound(0)].Split(',');
// if (Kernel.ParseInt32(responseArray[0], 0) != 200)
// {
// return false;
// }
// if (responseArray.GetUpperBound(0) == 3)
// {
// SetCoordinate(responseArray[2], responseArray[3]);
// return true;
// }
// return false;
// }
// }
// #endregion POINT
// //- TEXTOVERLAY -//
// #region TEXTOVERLAY
// //- GoogleMapTextOverlay -//
// public class GoogleMapTextOverlay
// {
// private string m_borderStyle = string.Empty;
// private string m_html = string.Empty;
// private decimal m_latitude = -1;
// private decimal m_longitude = -1;
// private System.Web.UI.WebControls.Unit m_width = -1;
// private System.Web.UI.WebControls.Unit m_height = -1;
// private int m_moveByX;
// private int m_moveByY;
// private string m_textAlign = string.Empty;
// private string m_verticalAlign = string.Empty;
// //- Main -//
// public GoogleMapTextOverlay()
// {
// }
// public GoogleMapTextOverlay(string html, decimal latitude, decimal longitude, System.Web.UI.WebControls.Unit width, System.Web.UI.WebControls.Unit height)
// : this(html, latitude, longitude, width, height, 0, 0, "left", "top")
// {
// }
// public GoogleMapTextOverlay(string html, decimal latitude, decimal longitude, string width, string height)
// : this(html, latitude, longitude, new System.Web.UI.WebControls.Unit(width), new System.Web.UI.WebControls.Unit(height), 0, 0, "left", "top")
// {
// }
// public GoogleMapTextOverlay(string html, decimal latitude, decimal longitude, string width, string height, int moveByX, int moveByY, string textAlign, string verticalAlign)
// : this(html, latitude, longitude, new System.Web.UI.WebControls.Unit(width), new System.Web.UI.WebControls.Unit(height), moveByX, moveByY, textAlign, verticalAlign)
// {
// }
// public GoogleMapTextOverlay(string html, decimal latitude, decimal longitude, System.Web.UI.WebControls.Unit width, System.Web.UI.WebControls.Unit height, int moveByX, int moveByY, string textAlign, string verticalAlign)
// {
// m_html = html;
// m_latitude = latitude;
// m_longitude = longitude;
// m_width = width;
// m_height = height;
// m_moveByX = moveByX;
// m_moveByY = moveByY;
// m_textAlign = textAlign;
// m_verticalAlign = verticalAlign;
// }
// //- BorderStyle -//
// public string BorderStyle
// {
// get
// {
// return m_borderStyle;
// }
// set
// {
// m_borderStyle = value;
// }
// }
// //- Height -//
// public System.Web.UI.WebControls.Unit Height
// {
// get
// {
// return m_height;
// }
// set
// {
// m_height = value;
// }
// }
// //- Html -//
// public string Html
// {
// get
// {
// return m_html;
// }
// set
// {
// m_html = value;
// }
// }
// //- Latitude -//
// public decimal Latitude
// {
// get
// {
// return m_latitude;
// }
// set
// {
// m_latitude = value;
// }
// }
// //- Longitude -//
// public decimal Longitude
// {
// get
// {
// return m_longitude;
// }
// set
// {
// m_longitude = value;
// }
// }
// //- MoveByX -//
// public int MoveByX
// {
// get
// {
// return m_moveByX;
// }
// set
// {
// m_moveByX = value;
// }
// }
// //- MoveByY -//
// public int MoveByY
// {
// get
// {
// return m_moveByY;
// }
// set
// {
// m_moveByY = value;
// }
// }
// //- TextAlign -//
// public string TextAlign
// {
// get
// {
// return m_textAlign;
// }
// set
// {
// m_textAlign = value;
// }
// }
// //- VerticalAlign -//
// public string VerticalAlign
// {
// get
// {
// return m_verticalAlign;
// }
// set
// {
// m_verticalAlign = value;
// }
// }
// //- Width -//
// public System.Web.UI.WebControls.Unit Width
// {
// get
// {
// return m_width;
// }
// set
// {
// m_width = value;
// }
// }
// }
// #endregion TEXTOVERLAY
// }
//}
| |
#region license
// Sqloogle
// Copyright 2013-2017 Dale Newman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Text;
using System.Data.SqlClient;
using Sqloogle.Libs.DBDiff.Schema.Events;
using Sqloogle.Libs.DBDiff.Schema.Model;
using Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Generates.SQLCommands;
using Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Generates.Util;
using Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Model;
namespace Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Generates
{
public class GenerateConstraint
{
private Generate root;
public GenerateConstraint(Generate root)
{
this.root = root;
}
private static string AlternateName(string schema, string table)
{
//var columns = SqlStrings.RemoveBrackets(string.Join("_", this.Columns.Select(c => c.Name)));
//var name = string.Format("PK_{0}_{1}_{2}", schema, table, columns);
var name = string.Format("PK_{0}_{1}", schema.Replace(" ", "_").Replace("\\", "_"), table.Replace(" ", "_"));
var length = Math.Min(name.Length, 128);
return name.Substring(0, length);
}
#region Check Functions...
public void FillCheck(Database database, string connectionString)
{
int parentId = 0;
ISchemaBase table = null;
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(ConstraintSQLCommand.GetCheck(database.Info.Version), conn))
{
root.RaiseOnReading(new ProgressEventArgs("Reading constraint...", Constants.READING_CONSTRAINTS));
conn.Open();
command.CommandTimeout = 0;
using (SqlDataReader reader = command.ExecuteReader())
{
Constraint item = null;
while (reader.Read())
{
root.RaiseOnReadingOne(reader["Name"]);
if (parentId != (int)reader["parent_object_id"])
{
parentId = (int)reader["parent_object_id"];
if (reader["ObjectType"].ToString().Trim().Equals("U"))
table = database.Tables.Find(parentId);
else
table = database.TablesTypes.Find(parentId);
}
item = new Constraint(table);
item.Id = (int)reader["id"];
item.Name = reader["Name"].ToString();
item.Type = Constraint.ConstraintType.Check;
item.Definition = reader["Definition"].ToString();
item.WithNoCheck = (bool)reader["WithCheck"];
item.IsDisabled = (bool)reader["is_disabled"];
item.Owner = reader["Owner"].ToString();
if (database.Options.Ignore.FilterNotForReplication)
item.NotForReplication = (bool)reader["is_not_for_replication"];
if (reader["ObjectType"].ToString().Trim().Equals("U"))
((Table)table).Constraints.Add(item);
else
((TableType)table).Constraints.Add(item);
}
}
}
}
}
#endregion
#region ForeignKey Functions...
private static string GetSQLForeignKey()
{
StringBuilder sql = new StringBuilder();
sql.Append("SELECT FK.object_id, C.user_type_id ,FK.parent_object_id,S.Name AS Owner, S2.Name AS ReferenceOwner, C2.Name AS ColumnName, C2.column_id AS ColumnId, C.name AS ColumnRelationalName, C.column_id AS ColumnRelationalId, T.object_id AS TableRelationalId, FK.Parent_object_id AS TableId, T.Name AS TableRelationalName, FK.Name, FK.is_disabled, FK.is_not_for_replication, FK.is_not_trusted, FK.delete_referential_action, FK.update_referential_action ");
sql.Append("FROM sys.foreign_keys FK ");
sql.Append("INNER JOIN sys.tables T ON T.object_id = FK.referenced_object_id ");
sql.Append("INNER JOIN sys.schemas S2 ON S2.schema_id = T.schema_id ");
sql.Append("INNER JOIN sys.foreign_key_columns FKC ON FKC.constraint_object_id = FK.object_id ");
sql.Append("INNER JOIN sys.columns C ON C.object_id = FKC.referenced_object_id AND C.column_id = referenced_column_id ");
sql.Append("INNER JOIN sys.columns C2 ON C2.object_id = FKC.parent_object_id AND C2.column_id = parent_column_id ");
sql.Append("INNER JOIN sys.schemas S ON S.schema_id = FK.schema_id ");
sql.Append("ORDER BY FK.parent_object_id, FK.Name, ColumnId");
return sql.ToString();
}
private static void FillForeignKey(Database database, string connectionString)
{
int lastid = 0;
int parentId = 0;
Table table = null;
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(GetSQLForeignKey(), conn))
{
conn.Open();
command.CommandTimeout = 0;
using (SqlDataReader reader = command.ExecuteReader())
{
Constraint con = null;
while (reader.Read())
{
if (parentId != (int)reader["parent_object_id"])
{
parentId = (int)reader["parent_object_id"];
table = database.Tables.Find(parentId);
}
if (lastid != (int)reader["object_id"])
{
con = new Constraint(table);
con.Id = (int)reader["object_id"];
con.Name = reader["Name"].ToString();
con.Type = Constraint.ConstraintType.ForeignKey;
con.WithNoCheck = (bool)reader["is_not_trusted"];
con.RelationalTableFullName = "[" + reader["ReferenceOwner"].ToString() + "].[" + reader["TableRelationalName"].ToString() + "]";
con.RelationalTableId = (int)reader["TableRelationalId"];
con.Owner = reader["Owner"].ToString();
con.IsDisabled = (bool)reader["is_disabled"];
con.OnDeleteCascade = (byte)reader["delete_referential_action"];
con.OnUpdateCascade = (byte)reader["update_referential_action"];
if (database.Options.Ignore.FilterNotForReplication)
con.NotForReplication = (bool)reader["is_not_for_replication"];
lastid = (int)reader["object_id"];
table.Constraints.Add(con);
}
ConstraintColumn ccon = new ConstraintColumn(con);
ccon.Name = reader["ColumnName"].ToString();
ccon.ColumnRelationalName = reader["ColumnRelationalName"].ToString();
ccon.ColumnRelationalId = (int)reader["ColumnRelationalId"];
ccon.Id = (int)reader["ColumnId"];
ccon.KeyOrder = con.Columns.Count;
ccon.ColumnRelationalDataTypeId = (int)reader["user_type_id"];
//table.DependenciesCount++;
con.Columns.Add(ccon);
}
}
}
}
}
#endregion
#region UniqueKey Functions...
private static void FillUniqueKey(Database database, string connectionString)
{
int lastId = 0;
int parentId = 0;
bool change = false;
ISchemaBase table = null;
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(ConstraintSQLCommand.GetUniqueKey(database.Info.Version), conn))
{
conn.Open();
command.CommandTimeout = 0;
using (SqlDataReader reader = command.ExecuteReader())
{
Constraint con = null;
while (reader.Read())
{
if (parentId != (int)reader["ID"])
{
parentId = (int)reader["ID"];
if (reader["ObjectType"].ToString().Trim().Equals("U"))
table = database.Tables.Find(parentId);
else
table = database.TablesTypes.Find(parentId);
change = true;
}
else
change = false;
if ((lastId != (int)reader["Index_id"]) || (change))
{
con = new Constraint(table);
con.Name = reader["Name"].ToString();
con.Owner = (string)reader["Owner"];
con.Id = (int)reader["Index_id"];
con.Type = Constraint.ConstraintType.Unique;
con.Index.Id = (int)reader["Index_id"];
con.Index.AllowPageLocks = (bool)reader["allow_page_locks"];
con.Index.AllowRowLocks = (bool)reader["allow_row_locks"];
con.Index.FillFactor = (byte)reader["fill_factor"];
con.Index.IgnoreDupKey = (bool)reader["ignore_dup_key"];
con.Index.IsAutoStatistics = (bool)reader["ignore_dup_key"];
con.Index.IsDisabled = (bool)reader["is_disabled"];
con.Index.IsPadded = (bool)reader["is_padded"];
con.Index.IsPrimaryKey = false;
con.Index.IsUniqueKey = true;
con.Index.Type = (Index.IndexTypeEnum)(byte)reader["type"];
con.Index.Name = con.Name;
if (database.Options.Ignore.FilterTableFileGroup)
con.Index.FileGroup = reader["FileGroup"].ToString();
lastId = (int)reader["Index_id"];
if (reader["ObjectType"].ToString().Trim().Equals("U"))
((Table)table).Constraints.Add(con);
else
((TableType)table).Constraints.Add(con);
}
ConstraintColumn ccon = new ConstraintColumn(con);
ccon.Name = reader["ColumnName"].ToString();
ccon.IsIncluded = (bool)reader["is_included_column"];
ccon.Order = (bool)reader["is_descending_key"];
ccon.Id = (int)reader["column_id"];
ccon.DataTypeId = (int)reader["user_type_id"];
con.Columns.Add(ccon);
}
}
}
}
}
#endregion
#region PrimaryKey Functions...
private static void FillPrimaryKey(Database database, string connectionString)
{
int lastId = 0;
int parentId = 0;
bool change = false;
ISchemaBase table = null;
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(ConstraintSQLCommand.GetPrimaryKey(database.Info.Version, null), conn))
{
conn.Open();
command.CommandTimeout = 0;
using (SqlDataReader reader = command.ExecuteReader())
{
Constraint con = null;
while (reader.Read())
{
if (parentId != (int)reader["ID"])
{
parentId = (int)reader["ID"];
if (reader["ObjectType"].ToString().Trim().Equals("U"))
table = database.Tables.Find(parentId);
else
table = database.TablesTypes.Find(parentId);
change = true;
}
else
change = false;
if ((lastId != (int)reader["Index_id"]) || (change))
{
var name = (string) reader["Name"];
var owner = (string) reader["Owner"];
con = new Constraint(table);
con.Id = (int)reader["Index_id"];
con.Name = SqlStrings.HasHexEnding(name) ? AlternateName(owner, con.Parent.Name) : name;
con.Owner = owner;
con.Type = Constraint.ConstraintType.PrimaryKey;
con.Index.Id = (int)reader["Index_id"];
con.Index.AllowPageLocks = (bool)reader["allow_page_locks"];
con.Index.AllowRowLocks = (bool)reader["allow_row_locks"];
con.Index.FillFactor = (byte)reader["fill_factor"];
con.Index.IgnoreDupKey = (bool)reader["ignore_dup_key"];
con.Index.IsAutoStatistics = (bool)reader["ignore_dup_key"];
con.Index.IsDisabled = (bool)reader["is_disabled"];
con.Index.IsPadded = (bool)reader["is_padded"];
con.Index.IsPrimaryKey = true;
con.Index.IsUniqueKey = false;
con.Index.Type = (Index.IndexTypeEnum)(byte)reader["type"];
con.Index.Name = con.Name;
if (database.Options.Ignore.FilterTableFileGroup)
con.Index.FileGroup = reader["FileGroup"].ToString();
lastId = (int)reader["Index_id"];
if (reader["ObjectType"].ToString().Trim().Equals("U"))
((Table)table).Constraints.Add(con);
else
((TableType)table).Constraints.Add(con);
}
ConstraintColumn ccon = new ConstraintColumn(con);
ccon.Name = (string)reader["ColumnName"];
ccon.IsIncluded = (bool)reader["is_included_column"];
ccon.Order = (bool)reader["is_descending_key"];
ccon.KeyOrder = (byte)reader["key_ordinal"];
ccon.Id = (int)reader["column_id"];
ccon.DataTypeId = (int)reader["user_type_id"];
con.Columns.Add(ccon);
}
}
}
}
}
#endregion
public void Fill(Database database, string connectionString)
{
if (database.Options.Ignore.FilterConstraintPK)
FillPrimaryKey(database, connectionString);
if (database.Options.Ignore.FilterConstraintFK)
FillForeignKey(database, connectionString);
if (database.Options.Ignore.FilterConstraintUK)
FillUniqueKey(database, connectionString);
if (database.Options.Ignore.FilterConstraintCheck)
FillCheck(database, connectionString);
}
}
}
| |
/***************************************************************************
copyright : (C) 2005 by Brian Nickel
email : brian.nickel@gmail.com
based on : oggfile.cpp from TagLib
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
* USA *
***************************************************************************/
using System.Collections;
using System;
namespace TagLib.Ogg.Flac
{
public abstract class File : Ogg.File
{
//////////////////////////////////////////////////////////////////////////
// private properties
//////////////////////////////////////////////////////////////////////////
private Ogg.XiphComment comment;
private AudioProperties properties;
private ByteVector stream_info_data;
private ByteVector xiph_comment_data;
private long stream_start;
private long stream_length;
private bool scanned;
private bool has_xiph_comment;
private uint comment_packet;
//////////////////////////////////////////////////////////////////////////
// public methods
//////////////////////////////////////////////////////////////////////////
public File (string file, AudioProperties.ReadStyle properties_style) : base (file)
{
comment = null;
properties = null;
stream_info_data = null;
xiph_comment_data = null;
stream_start = 0;
stream_length = 0;
scanned = false;
has_xiph_comment = false;
comment_packet = 0;
Mode = AccessMode.Read;
Read (properties_style);
Mode = AccessMode.Closed;
}
public File (string file) : this (file, AudioProperties.ReadStyle.Average)
{
}
public override void Save ()
{
ClearPageData (); // Force re-reading of the file.
xiph_comment_data = comment.Render ();
// Create FLAC metadata-block:
// Put the size in the first 32 bit (I assume no more than 24 bit are used)
ByteVector v = ByteVector.FromUInt ((uint) xiph_comment_data.Count);
// Set the type of the metadata-block to be a Xiph / Vorbis comment
v [0] = 4;
// Append the comment-data after the 32 bit header
v.Add (xiph_comment_data);
// Save the packet at the old spot
// FIXME: Use padding if size is increasing
SetPacket (comment_packet, v);
base.Save ();
}
//////////////////////////////////////////////////////////////////////////
// public properties
//////////////////////////////////////////////////////////////////////////
public override TagLib.Tag Tag {get {return comment;}}
public override AudioProperties AudioProperties {get {return properties;}}
public long StreamLength {get {Scan (); return stream_length;}}
//////////////////////////////////////////////////////////////////////////
// private methods
//////////////////////////////////////////////////////////////////////////
private void Read (AudioProperties.ReadStyle properties_style)
{
// Look for FLAC metadata, including vorbis comments
Scan ();
comment = new Ogg.XiphComment (has_xiph_comment ? XiphCommentData : null);
if (properties_style != AudioProperties.ReadStyle.None)
properties = new TagLib.Flac.Properties(StreamInfoData, StreamLength, properties_style);
}
private void Scan ()
{
// Scan the metadata pages
if (scanned)
return;
uint ipacket = 0;
long overhead = 0;
ByteVector metadata_header = GetPacket (ipacket++);
ByteVector header;
if (!metadata_header.StartsWith ("fLaC"))
{
// FLAC 1.1.2+
if (metadata_header.Mid (1,4) != "FLAC")
throw new CorruptFileException ("FLAC header missing.");
if (metadata_header [5] != 1)
throw new CorruptFileException ("Unsupported FLAC version."); // not version 1
metadata_header = metadata_header.Mid (13);
}
else
{
// FLAC 1.1.0 & 1.1.1
metadata_header = GetPacket (ipacket++);
}
header = metadata_header.Mid (0,4);
// Header format (from spec):
// <1> Last-metadata-block flag
// <7> BLOCK_TYPE
// 0 : STREAMINFO
// 1 : PADDING
// ..
// 4 : VORBIS_COMMENT
// ..
// <24> Length of metadata to follow
byte block_type = (byte) (header [0] & 0x7f);
bool last_block = (header [0] & 0x80) != 0;
uint length = header.Mid (1, 3).ToUInt ();
overhead += length;
// Sanity: First block should be the stream_info metadata
if (block_type != 0)
throw new CorruptFileException ("Invalid Ogg/FLAC stream.");
stream_info_data = metadata_header.Mid (4, (int) length);
// Search through the remaining metadata
// FIXME: Support new code from TagLib.Flac.
while (!last_block)
{
metadata_header = GetPacket (ipacket++);
header = metadata_header.Mid (0, 4);
block_type = (byte) (header [0] & 0x7f);
last_block = (header [0] & 0x80) != 0;
length = header.Mid (1, 3).ToUInt ();
overhead += length;
if (block_type == 4)
{
xiph_comment_data = metadata_header.Mid (4, (int) length);
has_xiph_comment = true;
comment_packet = ipacket;
}
else if (block_type > 5)
Debugger.Debug ("Ogg.Flac.File.Scan() -- Unknown metadata block");
}
// End of metadata, now comes the datastream
stream_start = overhead;
stream_length = Length - stream_start;
scanned = true;
}
//////////////////////////////////////////////////////////////////////////
// private properties
//////////////////////////////////////////////////////////////////////////
private ByteVector StreamInfoData {get {Scan (); return stream_info_data;}}
private ByteVector XiphCommentData {get {Scan (); return xiph_comment_data;}}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// Renders the UI and handles update logic for HoloToolkit/Configure/Apply HoloLens Project Settings.
/// </summary>
public class ProjectSettingsWindow : AutoConfigureWindow<ProjectSettingsWindow.ProjectSetting>
{
#region Nested Types
public enum ProjectSetting
{
BuildWsaUwp,
WsaUwpBuildToD3D,
WsaFastestQuality,
WsaEnableVR
}
#endregion // Nested Types
#region Internal Methods
/// <summary>
/// Enables virtual reality for WSA and ensures HoloLens is in the supported SDKs.
/// </summary>
private void EnableVirtualReality()
{
try
{
// Grab the text from the project settings asset file
string settingsPath = "ProjectSettings/ProjectSettings.asset";
string settings = File.ReadAllText(settingsPath);
// We're looking for the list of VR devices for the current build target, then
// ensuring that the HoloLens is in that list
bool foundBuildTargetVRSettings = false;
bool foundBuildTargetMetro = false;
bool foundBuildTargetEnabled = false;
bool foundDevices = false;
bool foundHoloLens = false;
StringBuilder builder = new StringBuilder(); // Used to build the final output
string[] lines = settings.Split(new char[] { '\n' });
for (int i = 0; i < lines.Length; ++i)
{
string line = lines[i];
// Look for the build target VR settings
if (!foundBuildTargetVRSettings)
{
if (line.Contains("m_BuildTargetVRSettings:"))
{
// If no targets are enabled at all, just create the known entries and skip the rest of the tests
if (line.Contains("[]"))
{
// Remove the empty array symbols
line = line.Replace(" []", "\n");
// Generate the new lines
line += " - m_BuildTarget: Metro\n";
line += " m_Enabled: 1\n";
line += " m_Devices:\n";
line += " - HoloLens";
// Mark all fields as found so we don't search anymore
foundBuildTargetVRSettings = true;
foundBuildTargetMetro = true;
foundBuildTargetEnabled = true;
foundDevices = true;
foundHoloLens = true;
}
else
{
// The target VR settngs were found but the others
// still need to be searched for.
foundBuildTargetVRSettings = true;
}
}
}
// Look for the build target for Metro
else if (!foundBuildTargetMetro)
{
if (line.Contains("m_BuildTarget: Metro"))
{
foundBuildTargetMetro = true;
}
}
else if (!foundBuildTargetEnabled)
{
if (line.Contains("m_Enabled"))
{
line = " m_Enabled: 1";
foundBuildTargetEnabled = true;
}
}
// Look for the enabled Devices list
else if (!foundDevices)
{
if (line.Contains("m_Devices:"))
{
// Clear the empty array symbols if any
line = line.Replace(" []", "");
foundDevices = true;
}
}
// Once we've found the list look for HoloLens or the next non element
else if (!foundHoloLens)
{
// If this isn't an element in the device list
if (!line.Contains("-"))
{
// add the hololens element, and mark it found
builder.Append(" - HoloLens\n");
foundHoloLens = true;
}
// Otherwise test if this is the hololens device
else if (line.Contains("HoloLens"))
{
foundHoloLens = true;
}
}
builder.Append(line);
// Write out a \n for all but the last line
// NOTE: Specifically preserving unix line endings by avoiding StringBuilder.AppendLine
if (i != lines.Length - 1)
{
builder.Append('\n');
}
}
// Capture the final string
settings = builder.ToString();
File.WriteAllText(settingsPath, settings);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
/// <summary>
/// Modifies the WSA default quality setting to the fastest
/// </summary>
private void SetFastestDefaultQuality()
{
try
{
// Find the WSA element under the platform quality list and replace it's value with 0
string settingsPath = "ProjectSettings/QualitySettings.asset";
string matchPattern = @"(m_PerPlatformDefaultQuality.*Windows Store Apps:) (\d+)";
string replacePattern = @"$1 0";
string settings = File.ReadAllText(settingsPath);
settings = Regex.Replace(settings, matchPattern, replacePattern, RegexOptions.Singleline);
File.WriteAllText(settingsPath, settings);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
#endregion // Internal Methods
#region Overrides / Event Handlers
protected override void ApplySettings()
{
// See the blow notes for why text asset serialization is required
if (EditorSettings.serializationMode != SerializationMode.ForceText)
{
// NOTE: PlayerSettings.virtualRealitySupported would be ideal, except that it only reports/affects whatever platform tab
// is currently selected in the Player settings window. As we don't have code control over what view is selected there
// this property is fairly useless from script.
// NOTE: There is no current way to change the default quality setting from script
string title = "Updates require text serialization of assets";
string message = "Unity doesn't provide apis for updating the default quality or enabling VR support.\n\n" +
"Is it ok if we force text serialization of assets so that we can modify the properties directly?";
bool forceText = EditorUtility.DisplayDialog(title, message, "Yes", "No");
if (!forceText)
{
return;
}
EditorSettings.serializationMode = SerializationMode.ForceText;
}
// Apply individual settings
if (Values[ProjectSetting.BuildWsaUwp])
{
EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTarget.WSAPlayer);
EditorUserBuildSettings.wsaSDK = WSASDK.UWP;
}
if (Values[ProjectSetting.WsaUwpBuildToD3D])
{
EditorUserBuildSettings.wsaUWPBuildType = WSAUWPBuildType.D3D;
}
if (Values[ProjectSetting.WsaFastestQuality])
{
SetFastestDefaultQuality();
}
if (Values[ProjectSetting.WsaEnableVR])
{
EnableVirtualReality();
}
// Since we went behind Unity's back to tweak some settings we
// need to reload the project to have them take effect
bool canReload = EditorUtility.DisplayDialog(
"Project reload required!",
"Some changes require a project reload to take effect.\n\nReload now?",
"Yes", "No");
if (canReload)
{
string projectPath = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));
EditorApplication.OpenProject(projectPath);
}
}
protected override void LoadSettings()
{
for (int i = (int)ProjectSetting.BuildWsaUwp; i <= (int)ProjectSetting.WsaEnableVR; i++)
{
Values[(ProjectSetting)i] = true;
}
}
protected override void LoadStrings()
{
Names[ProjectSetting.BuildWsaUwp] = "Target Windows Store and UWP";
Descriptions[ProjectSetting.BuildWsaUwp] = "Required\n\nSwitches the currently active target to produce a Store app targeting the Universal Windows Platform.\n\nSince HoloLens only supports Windows Store apps, this option should remain checked unless you plan to manually switch the target later before you build.";
Names[ProjectSetting.WsaUwpBuildToD3D] = "Build for Direct3D";
Descriptions[ProjectSetting.WsaUwpBuildToD3D] = "Recommended\n\nProduces an app that targets Direct3D instead of Xaml.\n\nPure Direct3D apps run faster than applications that include Xaml. This option should remain checked unless you plan to overlay Unity content with Xaml content or you plan to switch between Unity views and Xaml views at runtime.";
Names[ProjectSetting.WsaFastestQuality] = "Set Quality to Fastest";
Descriptions[ProjectSetting.WsaFastestQuality] = "Recommended\n\nChanges the quality settings for Windows Store apps to the 'Fastest' setting.\n\n'Fastest' is the recommended quality setting for HoloLens apps, but this option can be unchecked if you have already optimized your project for the HoloLens.";
Names[ProjectSetting.WsaEnableVR] = "Enable VR";
Descriptions[ProjectSetting.WsaEnableVR] = "Required\n\nEnables VR for Windows Store apps and adds the HoloLens as a target VR device.\n\nThe application will not compile for HoloLens and tools like Holographic Remoting will not function without this enabled. Therefore this option should remain checked unless you plan to manually perform these steps later.";
}
protected override void OnEnable()
{
// Pass to base first
base.OnEnable();
// Set size
this.minSize = new Vector2(350, 260);
this.maxSize = this.minSize;
}
#endregion // Overrides / Event Handlers
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: CornerRadiusConverter.cs
//
// Description: Contains the CornerRadiusConverter: TypeConverter for the CornerRadiusclass.
//
// History:
// 07/19/2004 : t-jaredg - Created
//
//---------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Security;
using MS.Internal;
using MS.Utility;
#pragma warning disable 1634, 1691 // suppressing PreSharp warnings
namespace System.Windows
{
/// <summary>
/// CornerRadiusConverter - Converter class for converting instances of other types to and from CornerRadius instances.
/// </summary>
public class CornerRadiusConverter : TypeConverter
{
#region Public Methods
/// <summary>
/// CanConvertFrom - Returns whether or not this class can convert from a given type.
/// </summary>
/// <returns>
/// bool - True if thie converter can convert from the provided type, false if not.
/// </returns>
/// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call. </param>
/// <param name="sourceType"> The Type being queried for support. </param>
public override bool CanConvertFrom(ITypeDescriptorContext typeDescriptorContext, Type sourceType)
{
// We can only handle strings, integral and floating types
TypeCode tc = Type.GetTypeCode(sourceType);
switch (tc)
{
case TypeCode.String:
case TypeCode.Decimal:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
/// <summary>
/// CanConvertTo - Returns whether or not this class can convert to a given type.
/// </summary>
/// <returns>
/// bool - True if this converter can convert to the provided type, false if not.
/// </returns>
/// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call. </param>
/// <param name="destinationType"> The Type being queried for support. </param>
public override bool CanConvertTo(ITypeDescriptorContext typeDescriptorContext, Type destinationType)
{
// We can convert to an InstanceDescriptor or to a string.
if ( destinationType == typeof(InstanceDescriptor)
|| destinationType == typeof(string))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// ConvertFrom - Attempt to convert to a CornerRadius from the given object
/// </summary>
/// <returns>
/// The CornerRadius which was constructed.
/// </returns>
/// <exception cref="ArgumentNullException">
/// An ArgumentNullException is thrown if the example object is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An ArgumentException is thrown if the example object is not null and is not a valid type
/// which can be converted to a CornerRadius.
/// </exception>
/// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call. </param>
/// <param name="cultureInfo"> The CultureInfo which is respected when converting. </param>
/// <param name="source"> The object to convert to a CornerRadius. </param>
public override object ConvertFrom(ITypeDescriptorContext typeDescriptorContext, CultureInfo cultureInfo, object source)
{
if (source != null)
{
if (source is string) { return FromString((string)source, cultureInfo); }
else { return new CornerRadius(Convert.ToDouble(source, cultureInfo)); }
}
throw GetConvertFromException(source);
}
//Workaround for PreSharp bug - it complains about value being possibly null even though there is a check above
#pragma warning disable 56506
/// <summary>
/// ConvertTo - Attempt to convert a CornerRadius to the given type
/// </summary>
/// <returns>
/// The object which was constructoed.
/// </returns>
/// <exception cref="ArgumentNullException">
/// An ArgumentNullException is thrown if the example object is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An ArgumentException is thrown if the object is not null and is not a CornerRadius,
/// or if the destinationType isn't one of the valid destination types.
/// </exception>
/// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call. </param>
/// <param name="cultureInfo"> The CultureInfo which is respected when converting. </param>
/// <param name="value"> The CornerRadius to convert. </param>
/// <param name="destinationType">The type to which to convert the CornerRadius instance. </param>
///<SecurityNote>
/// Critical: calls InstanceDescriptor ctor which LinkDemands
/// PublicOK: can only make an InstanceDescriptor for CornerRadius, not an arbitrary class
///</SecurityNote>
[SecurityCritical]
public override object ConvertTo(ITypeDescriptorContext typeDescriptorContext, CultureInfo cultureInfo, object value, Type destinationType)
{
if (null == value)
{
throw new ArgumentNullException("value");
}
if (null == destinationType)
{
throw new ArgumentNullException("destinationType");
}
if (!(value is CornerRadius))
{
#pragma warning suppress 6506 // value is obviously not null
throw new ArgumentException(SR.Get(SRID.UnexpectedParameterType, value.GetType(), typeof(CornerRadius)), "value");
}
CornerRadius cr = (CornerRadius)value;
if (destinationType == typeof(string)) { return ToString(cr, cultureInfo); }
if (destinationType == typeof(InstanceDescriptor))
{
ConstructorInfo ci = typeof(CornerRadius).GetConstructor(new Type[] { typeof(double), typeof(double), typeof(double), typeof(double) });
return new InstanceDescriptor(ci, new object[] { cr.TopLeft, cr.TopRight, cr.BottomRight, cr.BottomLeft });
}
throw new ArgumentException(SR.Get(SRID.CannotConvertType, typeof(CornerRadius), destinationType.FullName));
}
//Workaround for PreSharp bug - it complains about value being possibly null even though there is a check above
#pragma warning restore 56506
#endregion Public Methods
//-------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------
#region Internal Methods
static internal string ToString(CornerRadius cr, CultureInfo cultureInfo)
{
char listSeparator = TokenizerHelper.GetNumericListSeparator(cultureInfo);
// Initial capacity [64] is an estimate based on a sum of:
// 48 = 4x double (twelve digits is generous for the range of values likely)
// 8 = 4x UnitType string (approx two characters)
// 4 = 4x separator characters
StringBuilder sb = new StringBuilder(64);
sb.Append(cr.TopLeft.ToString(cultureInfo));
sb.Append(listSeparator);
sb.Append(cr.TopRight.ToString(cultureInfo));
sb.Append(listSeparator);
sb.Append(cr.BottomRight.ToString(cultureInfo));
sb.Append(listSeparator);
sb.Append(cr.BottomLeft.ToString(cultureInfo));
return sb.ToString();
}
static internal CornerRadius FromString(string s, CultureInfo cultureInfo)
{
TokenizerHelper th = new TokenizerHelper(s, cultureInfo);
double[] radii = new double[4];
int i = 0;
// Peel off each Length in the delimited list.
while (th.NextToken())
{
if (i >= 4)
{
i = 5; // Set i to a bad value.
break;
}
radii[i] = double.Parse(th.GetCurrentToken(), cultureInfo);
i++;
}
// We have a reasonable interpreation for one value (all four edges)
// and four values (left, top, right, bottom).
switch (i)
{
case 1:
return (new CornerRadius(radii[0]));
case 4:
return (new CornerRadius(radii[0], radii[1], radii[2], radii[3]));
}
throw new FormatException(SR.Get(SRID.InvalidStringCornerRadius, s));
}
#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 IndexReader = Lucene.Net.Index.IndexReader;
namespace Lucene.Net.Search
{
/* Description from Doug Cutting (excerpted from
* LUCENE-1483):
*
* BooleanScorer uses a ~16k array to score windows of
* docs. So it scores docs 0-16k first, then docs 16-32k,
* etc. For each window it iterates through all query terms
* and accumulates a score in table[doc%16k]. It also stores
* in the table a bitmask representing which terms
* contributed to the score. Non-zero scores are chained in
* a linked list. At the end of scoring each window it then
* iterates through the linked list and, if the bitmask
* matches the boolean constraints, collects a hit. For
* boolean queries with lots of frequent terms this can be
* much faster, since it does not need to update a priority
* queue for each posting, instead performing constant-time
* operations per posting. The only downside is that it
* results in hits being delivered out-of-order within the
* window, which means it cannot be nested within other
* scorers. But it works well as a top-level scorer.
*
* The new BooleanScorer2 implementation instead works by
* merging priority queues of postings, albeit with some
* clever tricks. For example, a pure conjunction (all terms
* required) does not require a priority queue. Instead it
* sorts the posting streams at the start, then repeatedly
* skips the first to to the last. If the first ever equals
* the last, then there's a hit. When some terms are
* required and some terms are optional, the conjunction can
* be evaluated first, then the optional terms can all skip
* to the match and be added to the score. Thus the
* conjunction can reduce the number of priority queue
* updates for the optional terms. */
public sealed class BooleanScorer:Scorer
{
private void InitBlock()
{
bucketTable = new BucketTable();
}
private sealed class BooleanScorerCollector:Collector
{
private BucketTable bucketTable;
private int mask;
private Scorer scorer;
public BooleanScorerCollector(int mask, BucketTable bucketTable)
{
this.mask = mask;
this.bucketTable = bucketTable;
}
public override void Collect(int doc)
{
BucketTable table = bucketTable;
int i = doc & Lucene.Net.Search.BooleanScorer.BucketTable.MASK;
Bucket bucket = table.buckets[i];
if (bucket == null)
table.buckets[i] = bucket = new Bucket();
if (bucket.doc != doc)
{
// invalid bucket
bucket.doc = doc; // set doc
bucket.score = scorer.Score(); // initialize score
bucket.bits = mask; // initialize mask
bucket.coord = 1; // initialize coord
bucket.next = table.first; // push onto valid list
table.first = bucket;
}
else
{
// valid bucket
bucket.score += scorer.Score(); // increment score
bucket.bits |= mask; // add bits in mask
bucket.coord++; // increment coord
}
}
public override void SetNextReader(IndexReader reader, int docBase)
{
// not needed by this implementation
}
public override void SetScorer(Scorer scorer)
{
this.scorer = scorer;
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
// An internal class which is used in score(Collector, int) for setting the
// current score. This is required since Collector exposes a setScorer method
// and implementations that need the score will call scorer.score().
// Therefore the only methods that are implemented are score() and doc().
private sealed class BucketScorer:Scorer
{
internal float score;
internal int doc = NO_MORE_DOCS;
public BucketScorer():base(null)
{
}
public override int Advance(int target)
{
return NO_MORE_DOCS;
}
/// <deprecated> use {@link #DocID()} instead.
/// </deprecated>
[Obsolete("use DocID() instead.")]
public override int Doc()
{
return doc;
}
public override int DocID()
{
return doc;
}
public override Explanation Explain(int doc)
{
return null;
}
/// <deprecated> use {@link #NextDoc()} instead.
/// </deprecated>
[Obsolete("use NextDoc() instead. ")]
public override bool Next()
{
return false;
}
public override int NextDoc()
{
return NO_MORE_DOCS;
}
public override float Score()
{
return score;
}
/// <deprecated> use {@link #Advance(int)} instead.
/// </deprecated>
[Obsolete("use Advance(int) instead. ")]
public override bool SkipTo(int target)
{
return false;
}
}
internal sealed class Bucket
{
internal int doc = - 1; // tells if bucket is valid
internal float score; // incremental score
internal int bits; // used for bool constraints
internal int coord; // count of terms in score
internal Bucket next; // next valid bucket
}
/// <summary>A simple hash table of document scores within a range. </summary>
internal sealed class BucketTable
{
private void InitBlock()
{
buckets = new Bucket[SIZE];
}
public const int SIZE = 1 << 11;
public static readonly int MASK;
internal Bucket[] buckets;
internal Bucket first = null; // head of valid list
public BucketTable()
{
InitBlock();
}
public Collector NewCollector(int mask)
{
return new BooleanScorerCollector(mask, this);
}
public int Size()
{
return SIZE;
}
static BucketTable()
{
MASK = SIZE - 1;
}
}
internal sealed class SubScorer
{
public Scorer scorer;
public bool required = false;
public bool prohibited = false;
public Collector collector;
public SubScorer next;
public SubScorer(Scorer scorer, bool required, bool prohibited, Collector collector, SubScorer next)
{
this.scorer = scorer;
this.required = required;
this.prohibited = prohibited;
this.collector = collector;
this.next = next;
}
}
private SubScorer scorers = null;
private BucketTable bucketTable;
private int maxCoord = 1;
private float[] coordFactors;
private int requiredMask = 0;
private int prohibitedMask = 0;
private int nextMask = 1;
private int minNrShouldMatch;
private int end;
private Bucket current;
private int doc = - 1;
public /*internal*/ BooleanScorer(Similarity similarity, int minNrShouldMatch, System.Collections.IList optionalScorers, System.Collections.IList prohibitedScorers):base(similarity)
{
InitBlock();
this.minNrShouldMatch = minNrShouldMatch;
if (optionalScorers != null && optionalScorers.Count > 0)
{
for (System.Collections.IEnumerator si = optionalScorers.GetEnumerator(); si.MoveNext(); )
{
Scorer scorer = (Scorer) si.Current;
maxCoord++;
if (scorer.NextDoc() != NO_MORE_DOCS)
{
scorers = new SubScorer(scorer, false, false, bucketTable.NewCollector(0), scorers);
}
}
}
if (prohibitedScorers != null && prohibitedScorers.Count > 0)
{
for (System.Collections.IEnumerator si = prohibitedScorers.GetEnumerator(); si.MoveNext(); )
{
Scorer scorer = (Scorer) si.Current;
int mask = nextMask;
nextMask = nextMask << 1;
prohibitedMask |= mask; // update prohibited mask
if (scorer.NextDoc() != NO_MORE_DOCS)
{
scorers = new SubScorer(scorer, false, true, bucketTable.NewCollector(mask), scorers);
}
}
}
coordFactors = new float[maxCoord];
Similarity sim = GetSimilarity();
for (int i = 0; i < maxCoord; i++)
{
coordFactors[i] = sim.Coord(i, maxCoord - 1);
}
}
// firstDocID is ignored since nextDoc() initializes 'current'
public /*protected internal*/ override bool Score(Collector collector, int max, int firstDocID)
{
bool more;
Bucket tmp;
BucketScorer bs = new BucketScorer();
// The internal loop will set the score and doc before calling collect.
collector.SetScorer(bs);
do
{
bucketTable.first = null;
while (current != null)
{
// more queued
// check prohibited & required
if ((current.bits & prohibitedMask) == 0 && (current.bits & requiredMask) == requiredMask)
{
if (current.doc >= max)
{
tmp = current;
current = current.next;
tmp.next = bucketTable.first;
bucketTable.first = tmp;
continue;
}
if (current.coord >= minNrShouldMatch)
{
bs.score = current.score * coordFactors[current.coord];
bs.doc = current.doc;
collector.Collect(current.doc);
}
}
current = current.next; // pop the queue
}
if (bucketTable.first != null)
{
current = bucketTable.first;
bucketTable.first = current.next;
return true;
}
// refill the queue
more = false;
end += BucketTable.SIZE;
for (SubScorer sub = scorers; sub != null; sub = sub.next)
{
int subScorerDocID = sub.scorer.DocID();
if (subScorerDocID != NO_MORE_DOCS)
{
more |= sub.scorer.Score(sub.collector, end, subScorerDocID);
}
}
current = bucketTable.first;
}
while (current != null || more);
return false;
}
/// <deprecated> use {@link #Score(Collector, int, int)} instead.
/// </deprecated>
[Obsolete("use Score(Collector, int, int) instead.")]
protected internal override bool Score(HitCollector hc, int max)
{
return Score(new HitCollectorWrapper(hc), max, DocID());
}
public override int Advance(int target)
{
throw new System.NotSupportedException();
}
/// <deprecated> use {@link #DocID()} instead.
/// </deprecated>
[Obsolete("use DocID() instead. ")]
public override int Doc()
{
return current.doc;
}
public override int DocID()
{
return doc;
}
public override Explanation Explain(int doc)
{
throw new System.NotSupportedException();
}
/// <deprecated> use {@link #NextDoc()} instead.
/// </deprecated>
[Obsolete("use NextDoc() instead. ")]
public override bool Next()
{
return NextDoc() != NO_MORE_DOCS;
}
public override int NextDoc()
{
bool more;
do
{
while (bucketTable.first != null)
{
// more queued
current = bucketTable.first;
bucketTable.first = current.next; // pop the queue
// check prohibited & required, and minNrShouldMatch
if ((current.bits & prohibitedMask) == 0 && (current.bits & requiredMask) == requiredMask && current.coord >= minNrShouldMatch)
{
return doc = current.doc;
}
}
// refill the queue
more = false;
end += BucketTable.SIZE;
for (SubScorer sub = scorers; sub != null; sub = sub.next)
{
Scorer scorer = sub.scorer;
sub.collector.SetScorer(scorer);
int doc = scorer.DocID();
while (doc < end)
{
sub.collector.Collect(doc);
doc = scorer.NextDoc();
}
more |= (doc != NO_MORE_DOCS);
}
}
while (bucketTable.first != null || more);
return this.doc = NO_MORE_DOCS;
}
public override float Score()
{
return current.score * coordFactors[current.coord];
}
public override void Score(Collector collector)
{
Score(collector, System.Int32.MaxValue, NextDoc());
}
/// <deprecated> use {@link #Score(Collector)} instead.
/// </deprecated>
[Obsolete("use Score(Collector) instead. ")]
public override void Score(HitCollector hc)
{
Score(new HitCollectorWrapper(hc));
}
/// <deprecated> use {@link #Advance(int)} instead.
/// </deprecated>
[Obsolete("use Advance(int) instead. ")]
public override bool SkipTo(int target)
{
throw new System.NotSupportedException();
}
public override System.String ToString()
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
buffer.Append("boolean(");
for (SubScorer sub = scorers; sub != null; sub = sub.next)
{
buffer.Append(sub.scorer.ToString());
buffer.Append(" ");
}
buffer.Append(")");
return buffer.ToString();
}
}
}
| |
#region License
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Announcers;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using Mono.Options;
namespace FluentMigrator.Console
{
public class MigratorConsole
{
private readonly ConsoleAnnouncer consoleAnnouncer = new ConsoleAnnouncer();
public string ApplicationContext;
public string Connection;
public string ConnectionStringConfigPath;
public string Namespace;
public bool NestedNamespaces;
public bool Output;
public string OutputFilename;
public bool PreviewOnly;
public string ProcessorType;
public string Profile;
public bool ShowHelp;
public int Steps;
public List<string> Tags = new List<string>();
public string TargetAssembly;
public string Task;
public int Timeout;
public bool Verbose;
public long Version;
public long StartVersion;
public bool NoConnection;
public string WorkingDirectory;
public bool TransactionPerSession;
public string ProviderSwitches;
public RunnerContext RunnerContext { get; private set;}
public MigratorConsole(params string[] args)
{
consoleAnnouncer.Header();
try
{
var optionSet = new OptionSet
{
{
"assembly=|a=|target=",
"REQUIRED. The assembly containing the migrations you want to execute.",
v => { TargetAssembly = v; }
},
{
"provider=|dbType=|db=",
string.Format("REQUIRED. The kind of database you are migrating against. Available choices are: {0}.",
new MigrationProcessorFactoryProvider().ListAvailableProcessorTypes()),
v => { ProcessorType = v; }
},
{
"connectionString=|connection=|conn=|c=",
"The name of the connection string (falls back to machine name) or the connection string itself to the server and database you want to execute your migrations against."
,
v => { Connection = v; }
},
{
"connectionStringConfigPath=|configPath=",
string.Format("The path of the machine.config where the connection string named by connectionString" +
" is found. If not specified, it defaults to the machine.config used by the currently running CLR version")
,
v => { ConnectionStringConfigPath = v; }
},
{
"namespace=|ns=",
"The namespace contains the migrations you want to run. Default is all migrations found within the Target Assembly will be run."
,
v => { Namespace = v; }
},
{
"nested",
"Whether migrations in nested namespaces should be included. Used in conjunction with the namespace option."
,
v => { NestedNamespaces = true; }
},
{
"output|out|o",
"Output generated SQL to a file. Default is no output. Use outputFilename to control the filename, otherwise [assemblyname].sql is the default."
,
v => { Output = true; }
},
{
"outputFilename=|outfile=|of=",
"The name of the file to output the generated SQL to. The output option must be included for output to be saved to the file."
,
v => { OutputFilename = v; }
},
{
"preview|p",
"Only output the SQL generated by the migration - do not execute it. Default is false.",
v => { PreviewOnly = true; }
},
{
"steps=",
"The number of versions to rollback if the task is 'rollback'. Default is 1.",
v => { Steps = int.Parse(v); }
},
{
"task=|t=",
"The task you want FluentMigrator to perform. Available choices are: migrate:up, migrate (same as migrate:up), migrate:down, rollback, rollback:toversion, rollback:all, validateversionorder, listmigrations. Default is 'migrate'."
,
v => { Task = v; }
},
{
"version=",
"The specific version to migrate. Default is 0, which will run all migrations.",
v => { Version = long.Parse(v); }
},
{
"startVersion=",
"The specific version to start migrating from. Only used when NoConnection is true. Default is 0",
v => { StartVersion = long.Parse(v); }
},
{
"noConnection",
"Indicates that migrations will be generated without consulting a target database. Should only be used when generating an output file.",
v => { NoConnection = NoConnection = true; }
},
{
"verbose=",
"Show the SQL statements generated and execution time in the console. Default is false.",
v => { Verbose = true; }
},
{
"workingdirectory=|wd=",
"The directory to load SQL scripts specified by migrations from.",
v => { WorkingDirectory = v; }
},
{
"profile=",
"The profile to run after executing migrations.",
v => { Profile = v; }
},
{
"context=",
"Set ApplicationContext to the given string.",
v => { ApplicationContext = v; }
},
{
"timeout=",
"Overrides the default SqlCommand timeout of 30 seconds.",
v => { Timeout = int.Parse(v); }
},
{
"tag=",
"Filters the migrations to be run by tag.",
v => { Tags.Add(v); }
},
{
"providerswitches=",
"Provider specific switches",
v => { ProviderSwitches = v; }
},
{
"help|h|?",
"Displays this help menu.",
v => { ShowHelp = true; }
},
{
"transaction-per-session|tps",
"Overrides the transaction behavior of migrations, so that all migrations to be executed will run in one transaction.",
v => { TransactionPerSession = true; }
}
};
try
{
optionSet.Parse(args);
}
catch (OptionException e)
{
consoleAnnouncer.Error(e);
consoleAnnouncer.Say("Try 'migrate --help' for more information.");
return;
}
if (string.IsNullOrEmpty(Task))
Task = "migrate";
if (string.IsNullOrEmpty(ProcessorType) ||
string.IsNullOrEmpty(TargetAssembly))
{
DisplayHelp(optionSet);
Environment.ExitCode = 1;
return;
}
if (ShowHelp)
{
DisplayHelp(optionSet);
return;
}
if (Output)
{
if (string.IsNullOrEmpty(OutputFilename))
OutputFilename = TargetAssembly + ".sql";
ExecuteMigrations(OutputFilename);
}
else
ExecuteMigrations();
}
catch (Exception ex)
{
consoleAnnouncer.Error(ex);
Environment.ExitCode = 1;
}
System.Console.ResetColor();
}
private void DisplayHelp(OptionSet p)
{
consoleAnnouncer.Write("Usage:");
consoleAnnouncer.Write(" migrate [OPTIONS]");
consoleAnnouncer.Write("Example:");
consoleAnnouncer.Write(" migrate -a bin\\debug\\MyMigrations.dll -db SqlServer2008 -conn \"SEE_BELOW\" -profile \"Debug\"");
consoleAnnouncer.HorizontalRule();
consoleAnnouncer.Write("Example Connection Strings:");
consoleAnnouncer.Write(" MySql: Data Source=172.0.0.1;Database=Foo;User Id=USERNAME;Password=BLAH");
consoleAnnouncer.Write(" Oracle: Server=172.0.0.1;Database=Foo;Uid=USERNAME;Pwd=BLAH");
consoleAnnouncer.Write(" SqlLite: Data Source=:memory:;Version=3;New=True");
consoleAnnouncer.Write(" SqlServer: server=127.0.0.1;database=Foo;user id=USERNAME;password=BLAH");
consoleAnnouncer.Write(" server=.\\SQLExpress;database=Foo;trusted_connection=true");
consoleAnnouncer.Write(" ");
consoleAnnouncer.Write("OR use a named connection string from the machine.config:");
consoleAnnouncer.Write(" migrate -a bin\\debug\\MyMigrations.dll -db SqlServer2008 -conn \"namedConnection\" -profile \"Debug\"");
consoleAnnouncer.HorizontalRule();
consoleAnnouncer.Write("Options:");
p.WriteOptionDescriptions(System.Console.Out);
}
private void ExecuteMigrations()
{
consoleAnnouncer.ShowElapsedTime = Verbose;
consoleAnnouncer.ShowSql = Verbose;
ExecuteMigrations(consoleAnnouncer);
}
private void ExecuteMigrations(string outputTo)
{
using (var sw = new StreamWriter(outputTo))
{
var fileAnnouncer = this.ExecutingAgainstMsSql ?
new TextWriterWithGoAnnouncer(sw) :
new TextWriterAnnouncer(sw);
fileAnnouncer.ShowElapsedTime = false;
fileAnnouncer.ShowSql = true;
consoleAnnouncer.ShowElapsedTime = Verbose;
consoleAnnouncer.ShowSql = Verbose;
var announcer = new CompositeAnnouncer(consoleAnnouncer, fileAnnouncer);
ExecuteMigrations(announcer);
}
}
private bool ExecutingAgainstMsSql
{
get
{
return ProcessorType.StartsWith("SqlServer", StringComparison.InvariantCultureIgnoreCase);
}
}
private void ExecuteMigrations(IAnnouncer announcer)
{
RunnerContext = new RunnerContext(announcer)
{
Database = ProcessorType,
Connection = Connection,
Targets = new string[] {TargetAssembly},
PreviewOnly = PreviewOnly,
Namespace = Namespace,
NestedNamespaces = NestedNamespaces,
Task = Task,
Version = Version,
StartVersion = StartVersion,
NoConnection = NoConnection,
Steps = Steps,
WorkingDirectory = WorkingDirectory,
Profile = Profile,
Timeout = Timeout,
ConnectionStringConfigPath = ConnectionStringConfigPath,
ApplicationContext = ApplicationContext,
Tags = Tags,
TransactionPerSession = TransactionPerSession,
ProviderSwitches = ProviderSwitches
};
new TaskExecutor(RunnerContext).Execute();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.ComponentModel;
using Microsoft.Xml.Serialization;
namespace Microsoft.Xml.Schema
{
using System;
using Microsoft.Xml;
/// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlSchemaAttribute : XmlSchemaAnnotated
{
private string _defaultValue;
private string _fixedValue;
private string _name;
private XmlSchemaForm _form = XmlSchemaForm.None;
private XmlSchemaUse _use = XmlSchemaUse.None;
private XmlQualifiedName _refName = XmlQualifiedName.Empty;
private XmlQualifiedName _typeName = XmlQualifiedName.Empty;
private XmlQualifiedName _qualifiedName = XmlQualifiedName.Empty;
private XmlSchemaSimpleType _type;
private XmlSchemaSimpleType _attributeType;
private SchemaAttDef _attDef;
/// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.DefaultValue"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("default")]
[DefaultValue(null)]
public string DefaultValue
{
get { return _defaultValue; }
set { _defaultValue = value; }
}
/// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.FixedValue"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("fixed")]
[DefaultValue(null)]
public string FixedValue
{
get { return _fixedValue; }
set { _fixedValue = value; }
}
/// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.Form"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("form"), DefaultValue(XmlSchemaForm.None)]
public XmlSchemaForm Form
{
get { return _form; }
set { _form = value; }
}
/// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.Name"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("name")]
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.RefName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("ref")]
public XmlQualifiedName RefName
{
get { return _refName; }
set { _refName = (value == null ? XmlQualifiedName.Empty : value); }
}
/// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.SchemaTypeName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("type")]
public XmlQualifiedName SchemaTypeName
{
get { return _typeName; }
set { _typeName = (value == null ? XmlQualifiedName.Empty : value); }
}
/// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.SchemaType"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlElement("simpleType")]
public XmlSchemaSimpleType SchemaType
{
get { return _type; }
set { _type = value; }
}
/// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.Use"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("use"), DefaultValue(XmlSchemaUse.None)]
public XmlSchemaUse Use
{
get { return _use; }
set { _use = value; }
}
/// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.QualifiedName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlQualifiedName QualifiedName
{
get { return _qualifiedName; }
}
/// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.AttributeType"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
[Obsolete("This property has been deprecated. Please use AttributeSchemaType property that returns a strongly typed attribute type. http://go.microsoft.com/fwlink/?linkid=14202")]
public object AttributeType
{
get
{
if (_attributeType == null)
return null;
if (_attributeType.QualifiedName.Namespace == XmlReservedNs.NsXs)
{
return _attributeType.Datatype;
}
return _attributeType;
}
}
/// <include file='doc\XmlSchemaAttribute.uex' path='docs/doc[@for="XmlSchemaAttribute.AttributeSchemaType"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaSimpleType AttributeSchemaType
{
get { return _attributeType; }
}
internal XmlReader Validate(XmlReader reader, XmlResolver resolver, XmlSchemaSet schemaSet, ValidationEventHandler valEventHandler)
{
if (schemaSet != null)
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas = schemaSet;
readerSettings.ValidationEventHandler += valEventHandler;
return new XsdValidatingReader(reader, resolver, readerSettings, this);
}
return null;
}
[XmlIgnore]
internal XmlSchemaDatatype Datatype
{
get
{
if (_attributeType != null)
{
return _attributeType.Datatype;
}
return null;
}
}
internal void SetQualifiedName(XmlQualifiedName value)
{
_qualifiedName = value;
}
internal void SetAttributeType(XmlSchemaSimpleType value)
{
_attributeType = value;
}
internal SchemaAttDef AttDef
{
get { return _attDef; }
set { _attDef = value; }
}
internal bool HasDefault
{
get { return _defaultValue != null; }
}
[XmlIgnore]
internal override string NameAttribute
{
get { return Name; }
set { Name = value; }
}
internal override XmlSchemaObject Clone()
{
XmlSchemaAttribute newAtt = (XmlSchemaAttribute)MemberwiseClone();
//Deep clone the QNames as these will be updated on chameleon includes
newAtt._refName = _refName.Clone();
newAtt._typeName = _typeName.Clone();
newAtt._qualifiedName = _qualifiedName.Clone();
return newAtt;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ODataApplication.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Compute
{
using System;
using System.Diagnostics.CodeAnalysis;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Compute.Closure;
using Apache.Ignite.Core.Impl.Memory;
using Apache.Ignite.Core.Impl.Portable;
using Apache.Ignite.Core.Impl.Portable.IO;
using Apache.Ignite.Core.Impl.Resource;
using Apache.Ignite.Core.Portable;
/// <summary>
/// Holder for user-provided compute job.
/// </summary>
internal class ComputeJobHolder : IPortableWriteAware
{
/** Actual job. */
private readonly IComputeJob _job;
/** Owning grid. */
private readonly Ignite _ignite;
/** Result (set for local jobs only). */
private volatile ComputeJobResultImpl _jobRes;
/// <summary>
/// Default ctor for marshalling.
/// </summary>
/// <param name="reader"></param>
public ComputeJobHolder(IPortableReader reader)
{
var reader0 = (PortableReaderImpl) reader.RawReader();
_ignite = reader0.Marshaller.Ignite;
_job = PortableUtils.ReadPortableOrSerializable<IComputeJob>(reader0);
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="job">Job.</param>
public ComputeJobHolder(Ignite grid, IComputeJob job)
{
_ignite = grid;
_job = job;
}
/// <summary>
/// Executes local job.
/// </summary>
/// <param name="cancel">Cancel flag.</param>
public void ExecuteLocal(bool cancel)
{
object res;
bool success;
Execute0(cancel, out res, out success);
_jobRes = new ComputeJobResultImpl(
success ? res : null,
success ? null : res as Exception,
_job,
_ignite.LocalNode.Id,
cancel
);
}
/// <summary>
/// Execute job serializing result to the stream.
/// </summary>
/// <param name="cancel">Whether the job must be cancelled.</param>
/// <param name="stream">Stream.</param>
public void ExecuteRemote(PlatformMemoryStream stream, bool cancel)
{
// 1. Execute job.
object res;
bool success;
Execute0(cancel, out res, out success);
// 2. Try writing result to the stream.
ClusterGroupImpl prj = _ignite.ClusterGroup;
PortableWriterImpl writer = prj.Marshaller.StartMarshal(stream);
try
{
// 3. Marshal results.
PortableUtils.WriteWrappedInvocationResult(writer, success, res);
}
finally
{
// 4. Process metadata.
prj.FinishMarshal(writer);
}
}
/// <summary>
/// Cancel the job.
/// </summary>
public void Cancel()
{
_job.Cancel();
}
/// <summary>
/// Serialize the job to the stream.
/// </summary>
/// <param name="stream">Stream.</param>
/// <returns>True if successfull.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "User job can throw any exception")]
internal bool Serialize(IPortableStream stream)
{
ClusterGroupImpl prj = _ignite.ClusterGroup;
PortableWriterImpl writer = prj.Marshaller.StartMarshal(stream);
try
{
writer.Write(this);
return true;
}
catch (Exception e)
{
writer.WriteString("Failed to marshal job [job=" + _job + ", errType=" + e.GetType().Name +
", errMsg=" + e.Message + ']');
return false;
}
finally
{
// 4. Process metadata.
prj.FinishMarshal(writer);
}
}
/// <summary>
/// Job.
/// </summary>
internal IComputeJob Job
{
get { return _job; }
}
/// <summary>
/// Job result.
/// </summary>
internal ComputeJobResultImpl JobResult
{
get { return _jobRes; }
}
/// <summary>
/// Internal job execution routine.
/// </summary>
/// <param name="cancel">Cancel flag.</param>
/// <param name="res">Result.</param>
/// <param name="success">Success flag.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "User job can throw any exception")]
private void Execute0(bool cancel, out object res, out bool success)
{
// 1. Inject resources.
IComputeResourceInjector injector = _job as IComputeResourceInjector;
if (injector != null)
injector.Inject(_ignite);
else
ResourceProcessor.Inject(_job, _ignite);
// 2. Execute.
try
{
if (cancel)
_job.Cancel();
res = _job.Execute();
success = true;
}
catch (Exception e)
{
res = e;
success = false;
}
}
/** <inheritDoc /> */
public void WritePortable(IPortableWriter writer)
{
PortableWriterImpl writer0 = (PortableWriterImpl) writer.RawWriter();
writer0.DetachNext();
PortableUtils.WritePortableOrSerializable(writer0, _job);
}
/// <summary>
/// Create job instance.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="stream">Stream.</param>
/// <returns></returns>
internal static ComputeJobHolder CreateJob(Ignite grid, IPortableStream stream)
{
try
{
return grid.Marshaller.StartUnmarshal(stream).ReadObject<ComputeJobHolder>();
}
catch (Exception e)
{
throw new IgniteException("Failed to deserialize the job [errType=" + e.GetType().Name +
", errMsg=" + e.Message + ']');
}
}
}
}
| |
//
// Copyright 2011-2013, Xamarin 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.
//
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Database;
using Android.OS;
using Android.Provider;
using Environment = Android.OS.Environment;
using Path = System.IO.Path;
using Uri = Android.Net.Uri;
using Media.Plugin.Abstractions;
namespace Media.Plugin
{
/// <summary>
/// Picker
/// </summary>
[Activity]
[Android.Runtime.Preserve(AllMembers = true)]
public class MediaPickerActivity
: Activity
{
internal const string ExtraPath = "path";
internal const string ExtraLocation = "location";
internal const string ExtraType = "type";
internal const string ExtraId = "id";
internal const string ExtraAction = "action";
internal const string ExtraTasked = "tasked";
internal static event EventHandler<MediaPickedEventArgs> MediaPicked;
private int id;
private string title;
private string description;
private string type;
/// <summary>
/// The user's destination path.
/// </summary>
private Uri path;
private bool isPhoto;
private string action;
private int seconds;
private VideoQuality quality;
private bool tasked;
/// <summary>
/// OnSaved
/// </summary>
/// <param name="outState"></param>
protected override void OnSaveInstanceState(Bundle outState)
{
outState.PutBoolean("ran", true);
outState.PutString(MediaStore.MediaColumns.Title, this.title);
outState.PutString(MediaStore.Images.ImageColumns.Description, this.description);
outState.PutInt(ExtraId, this.id);
outState.PutString(ExtraType, this.type);
outState.PutString(ExtraAction, this.action);
outState.PutInt(MediaStore.ExtraDurationLimit, this.seconds);
outState.PutInt(MediaStore.ExtraVideoQuality, (int)this.quality);
outState.PutBoolean(ExtraTasked, this.tasked);
if (this.path != null)
outState.PutString(ExtraPath, this.path.Path);
base.OnSaveInstanceState(outState);
}
/// <summary>
/// OnCreate
/// </summary>
/// <param name="savedInstanceState"></param>
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Bundle b = (savedInstanceState ?? Intent.Extras);
bool ran = b.GetBoolean("ran", defaultValue: false);
this.title = b.GetString(MediaStore.MediaColumns.Title);
this.description = b.GetString(MediaStore.Images.ImageColumns.Description);
this.tasked = b.GetBoolean(ExtraTasked);
this.id = b.GetInt(ExtraId, 0);
this.type = b.GetString(ExtraType);
if (this.type == "image/*")
this.isPhoto = true;
this.action = b.GetString(ExtraAction);
Intent pickIntent = null;
try
{
pickIntent = new Intent(this.action);
if (this.action == Intent.ActionPick)
pickIntent.SetType(type);
else
{
if (!this.isPhoto)
{
this.seconds = b.GetInt(MediaStore.ExtraDurationLimit, 0);
if (this.seconds != 0)
pickIntent.PutExtra(MediaStore.ExtraDurationLimit, seconds);
}
this.quality = (VideoQuality)b.GetInt(MediaStore.ExtraVideoQuality, (int)VideoQuality.High);
pickIntent.PutExtra(MediaStore.ExtraVideoQuality, GetVideoQuality(this.quality));
if (!ran)
{
this.path = GetOutputMediaFile(this, b.GetString(ExtraPath), this.title, this.isPhoto);
Touch();
pickIntent.PutExtra(MediaStore.ExtraOutput, this.path);
}
else
this.path = Uri.Parse(b.GetString(ExtraPath));
}
if (!ran)
StartActivityForResult(pickIntent, this.id);
}
catch (Exception ex)
{
OnMediaPicked(new MediaPickedEventArgs(this.id, ex));
}
finally
{
if (pickIntent != null)
pickIntent.Dispose();
}
}
private void Touch()
{
if (this.path.Scheme != "file")
return;
File.Create(GetLocalPath(this.path)).Close();
}
internal static Task<MediaPickedEventArgs> GetMediaFileAsync(Context context, int requestCode, string action, bool isPhoto, ref Uri path, Uri data)
{
Task<Tuple<string, bool>> pathFuture;
string originalPath = null;
if (action != Intent.ActionPick)
{
originalPath = path.Path;
// Not all camera apps respect EXTRA_OUTPUT, some will instead
// return a content or file uri from data.
if (data != null && data.Path != originalPath)
{
originalPath = data.ToString();
string currentPath = path.Path;
pathFuture = TryMoveFileAsync(context, data, path, isPhoto).ContinueWith(t =>
new Tuple<string, bool>(t.Result ? currentPath : null, false));
}
else
pathFuture = TaskFromResult(new Tuple<string, bool>(path.Path, false));
}
else if (data != null)
{
originalPath = data.ToString();
path = data;
pathFuture = GetFileForUriAsync(context, path, isPhoto);
}
else
pathFuture = TaskFromResult<Tuple<string, bool>>(null);
return pathFuture.ContinueWith(t =>
{
string resultPath = t.Result.Item1;
if (resultPath != null && File.Exists(t.Result.Item1))
{
var mf = new MediaFile(resultPath, () =>
{
return File.OpenRead(resultPath);
}, deletePathOnDispose: t.Result.Item2, dispose: (dis) =>
{
if (t.Result.Item2)
{
try
{
File.Delete(t.Result.Item1);
// We don't really care if this explodes for a normal IO reason.
}
catch (UnauthorizedAccessException)
{
}
catch (DirectoryNotFoundException)
{
}
catch (IOException)
{
}
}
});
return new MediaPickedEventArgs(requestCode, false, mf);
}
else
return new MediaPickedEventArgs(requestCode, new MediaFileNotFoundException(originalPath));
});
}
/// <summary>
/// OnActivity Result
/// </summary>
/// <param name="requestCode"></param>
/// <param name="resultCode"></param>
/// <param name="data"></param>
protected override async void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (this.tasked)
{
Task<MediaPickedEventArgs> future;
if (resultCode == Result.Canceled)
{
future = TaskFromResult(new MediaPickedEventArgs(requestCode, isCanceled: true));
Finish();
future.ContinueWith(t => OnMediaPicked(t.Result));
}
else
{
if ((int)Build.VERSION.SdkInt >= 22)
{
var e = await GetMediaFileAsync(this, requestCode, this.action, this.isPhoto, ref this.path, (data != null) ? data.Data : null);
OnMediaPicked(e);
Finish();
}
else
{
future = GetMediaFileAsync(this, requestCode, this.action, this.isPhoto, ref this.path, (data != null) ? data.Data : null);
Finish();
future.ContinueWith(t => OnMediaPicked(t.Result));
}
}
}
else
{
if (resultCode == Result.Canceled)
SetResult(Result.Canceled);
else
{
Intent resultData = new Intent();
resultData.PutExtra("MediaFile", (data != null) ? data.Data : null);
resultData.PutExtra("path", this.path);
resultData.PutExtra("isPhoto", this.isPhoto);
resultData.PutExtra("action", this.action);
SetResult(Result.Ok, resultData);
}
Finish();
}
}
private static Task<bool> TryMoveFileAsync(Context context, Uri url, Uri path, bool isPhoto)
{
string moveTo = GetLocalPath(path);
return GetFileForUriAsync(context, url, isPhoto).ContinueWith(t =>
{
if (t.Result.Item1 == null)
return false;
File.Delete(moveTo);
File.Move(t.Result.Item1, moveTo);
if (url.Scheme == "content")
context.ContentResolver.Delete(url, null, null);
return true;
}, TaskScheduler.Default);
}
private static int GetVideoQuality(VideoQuality videoQuality)
{
switch (videoQuality)
{
case VideoQuality.Medium:
case VideoQuality.High:
return 1;
default:
return 0;
}
}
private static string GetUniquePath(string folder, string name, bool isPhoto)
{
string ext = Path.GetExtension(name);
if (ext == String.Empty)
ext = ((isPhoto) ? ".jpg" : ".mp4");
name = Path.GetFileNameWithoutExtension(name);
string nname = name + ext;
int i = 1;
while (File.Exists(Path.Combine(folder, nname)))
nname = name + "_" + (i++) + ext;
return Path.Combine(folder, nname);
}
private static Uri GetOutputMediaFile(Context context, string subdir, string name, bool isPhoto)
{
subdir = subdir ?? String.Empty;
if (String.IsNullOrWhiteSpace(name))
{
string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
if (isPhoto)
name = "IMG_" + timestamp + ".jpg";
else
name = "VID_" + timestamp + ".mp4";
}
string mediaType = (isPhoto) ? Environment.DirectoryPictures : Environment.DirectoryMovies;
using (Java.IO.File mediaStorageDir = new Java.IO.File(context.GetExternalFilesDir(mediaType), subdir))
{
if (!mediaStorageDir.Exists())
{
if (!mediaStorageDir.Mkdirs())
throw new IOException("Couldn't create directory, have you added the WRITE_EXTERNAL_STORAGE permission?");
// Ensure this media doesn't show up in gallery apps
using (Java.IO.File nomedia = new Java.IO.File(mediaStorageDir, ".nomedia"))
nomedia.CreateNewFile();
}
return Uri.FromFile(new Java.IO.File(GetUniquePath(mediaStorageDir.Path, name, isPhoto)));
}
}
internal static Task<Tuple<string, bool>> GetFileForUriAsync(Context context, Uri uri, bool isPhoto)
{
var tcs = new TaskCompletionSource<Tuple<string, bool>>();
if (uri.Scheme == "file")
tcs.SetResult(new Tuple<string, bool>(new System.Uri(uri.ToString()).LocalPath, false));
else if (uri.Scheme == "content")
{
Task.Factory.StartNew(() =>
{
ICursor cursor = null;
try
{
string[] proj = null;
if((int)Build.VERSION.SdkInt >= 22)
proj = new[] { MediaStore.MediaColumns.Data };
cursor = context.ContentResolver.Query(uri, proj, null, null, null);
if (cursor == null || !cursor.MoveToNext())
tcs.SetResult(new Tuple<string, bool>(null, false));
else
{
int column = cursor.GetColumnIndex(MediaStore.MediaColumns.Data);
string contentPath = null;
if (column != -1)
contentPath = cursor.GetString(column);
bool copied = false;
// If they don't follow the "rules", try to copy the file locally
if (contentPath == null || !contentPath.StartsWith("file"))
{
copied = true;
Uri outputPath = GetOutputMediaFile(context, "temp", null, isPhoto);
try
{
using (Stream input = context.ContentResolver.OpenInputStream(uri))
using (Stream output = File.Create(outputPath.Path))
input.CopyTo(output);
contentPath = outputPath.Path;
}
catch (Java.IO.FileNotFoundException)
{
// If there's no data associated with the uri, we don't know
// how to open this. contentPath will be null which will trigger
// MediaFileNotFoundException.
}
}
tcs.SetResult(new Tuple<string, bool>(contentPath, false));
}
}
finally
{
if (cursor != null)
{
cursor.Close();
cursor.Dispose();
}
}
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
else
tcs.SetResult(new Tuple<string, bool>(null, false));
return tcs.Task;
}
private static string GetLocalPath(Uri uri)
{
return new System.Uri(uri.ToString()).LocalPath;
}
private static Task<T> TaskFromResult<T>(T result)
{
var tcs = new TaskCompletionSource<T>();
tcs.SetResult(result);
return tcs.Task;
}
private static void OnMediaPicked(MediaPickedEventArgs e)
{
var picked = MediaPicked;
if (picked != null)
picked(null, e);
}
}
internal class MediaPickedEventArgs
: EventArgs
{
public MediaPickedEventArgs(int id, Exception error)
{
if (error == null)
throw new ArgumentNullException("error");
RequestId = id;
Error = error;
}
public MediaPickedEventArgs(int id, bool isCanceled, MediaFile media = null)
{
RequestId = id;
IsCanceled = isCanceled;
if (!IsCanceled && media == null)
throw new ArgumentNullException("media");
Media = media;
}
public int RequestId
{
get;
private set;
}
public bool IsCanceled
{
get;
private set;
}
public Exception Error
{
get;
private set;
}
public MediaFile Media
{
get;
private set;
}
public Task<MediaFile> ToTask()
{
var tcs = new TaskCompletionSource<MediaFile>();
if (IsCanceled)
tcs.SetResult(null);
else if (Error != null)
tcs.SetResult(null);
else
tcs.SetResult(Media);
return tcs.Task;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Globalization;
using System.Runtime;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
namespace System.IdentityModel.Claims
{
// Examples:
// ClaimType ResourceValue ResourceRight
// --------------- ---------------- ------------------
// "File" "boot.ini" "Read"
// "HairColor" "Brown" "PossessProperty"
// "UserName" "Mary" "PossessProperty"
// "Service" "MailService" "Access"
// "Operation" "ReadMail" "Invoke"
// ClaimType:
// DESC: The type of resource for which rights are granted
// XrML: ClaimSet/Resource
// SAML: SamlAttributeStatement/Attribute/@Name/..., SamlAuthorizationDecisionStatement/Action/@Namespace/...
// ResourceValue:
// DESC: Value identifying the resource for which rights are granted
// XrML: ClaimSet/Resource/...
// SAML: SamlAttributeStatement/Attribute/..., SamlAuthorizationDecisionStatement/@Resource/...
// Right:
// DESC: Rights expressed about a resource
// XRML: ClaimSet/Right
// SAML: SamlAttributeStatement (aka. "PossessProperty") or, SamlAuthorizationDecisionStatement/Action/...
[DataContract(Namespace = XsiConstants.Namespace)]
public class Claim
{
private static Claim s_system;
[DataMember(Name = "ClaimType")]
private string _claimType;
[DataMember(Name = "Resource")]
private object _resource;
[DataMember(Name = "Right")]
private string _right;
private IEqualityComparer<Claim> _comparer;
private Claim(string claimType, object resource, string right, IEqualityComparer<Claim> comparer)
{
if (claimType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claimType");
if (claimType.Length <= 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("claimType", SR.ArgumentCannotBeEmptyString);
if (right == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("right");
if (right.Length <= 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("right", SR.ArgumentCannotBeEmptyString);
_claimType = claimType;
_resource = resource;
_right = right;
_comparer = comparer;
}
public Claim(string claimType, object resource, string right) : this(claimType, resource, right, null)
{
}
public static IEqualityComparer<Claim> DefaultComparer
{
get
{
return EqualityComparer<Claim>.Default;
}
}
public static Claim System
{
get
{
if (s_system == null)
s_system = new Claim(ClaimTypes.System, XsiConstants.System, Rights.Identity);
return s_system;
}
}
public object Resource
{
get { return _resource; }
}
public string ClaimType
{
get { return _claimType; }
}
public string Right
{
get { return _right; }
}
// Turn key claims
public static Claim CreateDnsClaim(string dns)
{
if (dns == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dns");
return new Claim(ClaimTypes.Dns, dns, Rights.PossessProperty, ClaimComparer.Dns);
}
public static Claim CreateHashClaim(byte[] hash)
{
if (hash == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("hash");
return new Claim(ClaimTypes.Hash, SecurityUtils.CloneBuffer(hash), Rights.PossessProperty, ClaimComparer.Hash);
}
public static Claim CreateNameClaim(string name)
{
if (name == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");
return new Claim(ClaimTypes.Name, name, Rights.PossessProperty);
}
public static Claim CreateSpnClaim(string spn)
{
if (spn == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("spn");
return new Claim(ClaimTypes.Spn, spn, Rights.PossessProperty);
}
public static Claim CreateThumbprintClaim(byte[] thumbprint)
{
if (thumbprint == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("thumbprint");
return new Claim(ClaimTypes.Thumbprint, SecurityUtils.CloneBuffer(thumbprint), Rights.PossessProperty, ClaimComparer.Thumbprint);
}
#if SUPPORTS_WINDOWSIDENTITY
public static Claim CreateUpnClaim(string upn)
{
if (upn == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("upn");
return new Claim(ClaimTypes.Upn, upn, Rights.PossessProperty, ClaimComparer.Upn);
}
#endif // SUPPORTS_WINDOWSIDENTITY
public static Claim CreateUriClaim(Uri uri)
{
if (uri == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri");
return new Claim(ClaimTypes.Uri, uri, Rights.PossessProperty);
}
#if SUPPORTS_WINDOWSIDENTITY // NegotiateStream
public static Claim CreateWindowsSidClaim(SecurityIdentifier sid)
{
if (sid == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sid");
return new Claim(ClaimTypes.Sid, sid, Rights.PossessProperty);
}
#endif // SUPPORTS_WINDOWSIDENTITY
public static Claim CreateX500DistinguishedNameClaim(X500DistinguishedName x500DistinguishedName)
{
if (x500DistinguishedName == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("x500DistinguishedName");
return new Claim(ClaimTypes.X500DistinguishedName, x500DistinguishedName, Rights.PossessProperty, ClaimComparer.X500DistinguishedName);
}
public override bool Equals(object obj)
{
if (_comparer == null)
_comparer = ClaimComparer.GetComparer(_claimType);
return _comparer.Equals(this, obj as Claim);
}
public override int GetHashCode()
{
if (_comparer == null)
_comparer = ClaimComparer.GetComparer(_claimType);
return _comparer.GetHashCode(this);
}
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "{0}: {1}", _right, _claimType);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
#if !FEATURE_PORTABLE_SPAN
using Internal.Runtime.CompilerServices;
#endif // FEATURE_PORTABLE_SPAN
namespace System
{
/// <summary>
/// Memory represents a contiguous region of arbitrary memory similar to <see cref="Span{T}"/>.
/// Unlike <see cref="Span{T}"/>, it is not a byref-like type.
/// </summary>
[DebuggerTypeProxy(typeof(MemoryDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public readonly struct Memory<T>
{
// NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout,
// as code uses Unsafe.As to cast between them.
// The highest order bit of _index is used to discern whether _object is an array/string or an owned memory
// if (_index >> 31) == 1, object _object is an OwnedMemory<T>
// else, object _object is a T[] or a string. It can only be a string if the Memory<T> was created by
// using unsafe / marshaling code to reinterpret a ReadOnlyMemory<char> wrapped around a string as
// a Memory<T>.
private readonly object _object;
private readonly int _index;
private readonly int _length;
private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory(T[] array)
{
if (array == null)
{
this = default;
return; // returns default
}
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
_object = array;
_index = 0;
_length = array.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(T[] array, int start)
{
if (array == null)
{
if (start != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
this = default;
return; // returns default
}
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
_object = array;
_index = start;
_length = array.Length - start;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory(T[] array, int start, int length)
{
if (array == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
this = default;
return; // returns default
}
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
_object = array;
_index = start;
_length = length;
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(OwnedMemory<T> owner, int index, int length)
{
// No validation performed; caller must provide any necessary validation.
_object = owner;
_index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask
_length = length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Memory(object obj, int index, int length)
{
// No validation performed; caller must provide any necessary validation.
_object = obj;
_index = index;
_length = length;
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator Memory<T>(T[] array) => new Memory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator Memory<T>(ArraySegment<T> arraySegment) => new Memory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) =>
Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory);
/// <summary>
/// Returns an empty <see cref="Memory{T}"/>
/// </summary>
public static Memory<T> Empty => default;
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// For <see cref="Memory{Char}"/>, returns a new instance of string that represents the characters pointed to by the memory.
/// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements.
/// </summary>
public override string ToString()
{
if (typeof(T) == typeof(char))
{
return (_object is string str) ? str.Substring(_index, _length) : Span.ToString();
}
return string.Format("System.Memory<{0}>[{1}]", typeof(T).Name, _length);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
return new Memory<T>(_object, _index + start, _length - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
return new Memory<T>(_object, _index + start, length);
}
/// <summary>
/// Returns a span from the memory.
/// </summary>
public Span<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_index < 0)
{
return ((OwnedMemory<T>)_object).Span.Slice(_index & RemoveOwnedFlagBitMask, _length);
}
else if (typeof(T) == typeof(char) && _object is string s)
{
// This is dangerous, returning a writable span for a string that should be immutable.
// However, we need to handle the case where a ReadOnlyMemory<char> was created from a string
// and then cast to a Memory<T>. Such a cast can only be done with unsafe or marshaling code,
// in which case that's the dangerous operation performed by the dev, and we're just following
// suit here to make it work as best as possible.
#if FEATURE_PORTABLE_SPAN
return new Span<T>(Unsafe.As<Pinnable<T>>(s), MemoryExtensions.StringAdjustment, s.Length).Slice(_index, _length);
#else
return new Span<T>(ref Unsafe.As<char, T>(ref s.GetRawStringData()), s.Length).Slice(_index, _length);
#endif // FEATURE_PORTABLE_SPAN
}
else if (_object != null)
{
return new Span<T>((T[])_object, _index, _length);
}
else
{
return default;
}
}
}
/// <summary>
/// Copies the contents of the memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The Memory to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination is shorter than the source.
/// </exception>
/// </summary>
public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span);
/// <summary>
/// Copies the contents of the memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination is shorter than the source, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span);
/// <summary>
/// Returns a handle for the array.
/// <param name="pin">If pin is true, the GC will not move the array and hence its address can be taken</param>
/// </summary>
public unsafe MemoryHandle Retain(bool pin = false)
{
MemoryHandle memoryHandle = default;
if (pin)
{
if (_index < 0)
{
memoryHandle = ((OwnedMemory<T>)_object).Pin((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>());
}
else if (typeof(T) == typeof(char) && _object is string s)
{
// This case can only happen if a ReadOnlyMemory<char> was created around a string
// and then that was cast to a Memory<char> using unsafe / marshaling code. This needs
// to work, however, so that code that uses a single Memory<char> field to store either
// a readable ReadOnlyMemory<char> or a writable Memory<char> can still be pinned and
// used for interop purposes.
GCHandle handle = GCHandle.Alloc(s, GCHandleType.Pinned);
#if FEATURE_PORTABLE_SPAN
void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
#else
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref s.GetRawStringData()), _index);
#endif // FEATURE_PORTABLE_SPAN
memoryHandle = new MemoryHandle(null, pointer, handle);
}
else if (_object is T[] array)
{
var handle = GCHandle.Alloc(array, GCHandleType.Pinned);
#if FEATURE_PORTABLE_SPAN
void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
#else
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index);
#endif // FEATURE_PORTABLE_SPAN
memoryHandle = new MemoryHandle(null, pointer, handle);
}
}
else
{
if (_index < 0)
{
((OwnedMemory<T>)_object).Retain();
memoryHandle = new MemoryHandle((OwnedMemory<T>)_object);
}
}
return memoryHandle;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// Returns true if the object is Memory or ReadOnlyMemory and if both objects point to the same array and have the same length.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
if (obj is ReadOnlyMemory<T>)
{
return ((ReadOnlyMemory<T>)obj).Equals(this);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(Memory<T> other)
{
return
_object == other._object &&
_index == other._index &&
_length == other._length;
}
/// <summary>
/// Serves as the default hash function.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return _object != null ? CombineHashCodes(_object.GetHashCode(), _index.GetHashCode(), _length.GetHashCode()) : 0;
}
private static int CombineHashCodes(int left, int right)
{
return ((left << 5) + left) ^ right;
}
private static int CombineHashCodes(int h1, int h2, int h3)
{
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
}
}
| |
/*
* 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 Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Physics.POSPlugin
{
public class POSPrim : PhysicsActor
{
private Vector3 _position;
private Vector3 _velocity;
private Vector3 _acceleration;
private Vector3 _size;
private Vector3 m_rotationalVelocity = Vector3.Zero;
private Quaternion _orientation;
private bool iscolliding;
public POSPrim()
{
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Prim; }
set { return; }
}
public override Vector3 RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool IsColliding
{
get { return iscolliding; }
set { iscolliding = value; }
}
public override bool CollidingGround
{
get { return false; }
set { return; }
}
public override bool CollidingObj
{
get { return false; }
set { return; }
}
public override bool Stopped
{
get { return false; }
}
public override Vector3 Position
{
get { return _position; }
set { _position = value; }
}
public override Vector3 Size
{
get { return _size; }
set { _size = value; }
}
public override float Mass
{
get { return 0f; }
}
public override Vector3 Force
{
get { return Vector3.Zero; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, Vector3 value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void SetVolumeDetect(int param)
{
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 GeometricCenter
{
get { return Vector3.Zero; }
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override Vector3 Velocity
{
get { return _velocity; }
set { _velocity = value; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return _orientation; }
set { _orientation = value; }
}
public override Vector3 Acceleration
{
get { return _acceleration; }
}
public override bool Kinematic
{
get { return true; }
set { }
}
public void SetAcceleration(Vector3 accel)
{
_acceleration = accel;
}
public override void AddForce(Vector3 force, bool pushforce)
{
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override void SetMomentum(Vector3 momentum)
{
}
public override bool Flying
{
get { return false; }
set { }
}
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override uint LocalID
{
set { return; }
}
public override bool Grabbed
{
set { return; }
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(Vector3 axis)
{
}
public override bool Selected
{
set { return; }
}
public override void CrossingFailure()
{
}
public override Vector3 PIDTarget
{
set { return; }
}
public override bool PIDActive
{
set { return; }
}
public override float PIDTau
{
set { return; }
}
public override float PIDHoverHeight
{
set { return; }
}
public override bool PIDHoverActive
{
set { return; }
}
public override PIDHoverType PIDHoverType
{
set { return; }
}
public override float PIDHoverTau
{
set { return; }
}
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Backlog.Wiki.cs">
// bl4n - Backlog.jp API Client library
// this file is part of bl4n, license under MIT license. http://t-ashula.mit-license.org/2015
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using BL4N.Data;
using Newtonsoft.Json;
namespace BL4N
{
/// <summary> The backlog. for Wiki API </summary>
public partial class Backlog
{
/// <summary>
/// Get Wiki Page List
/// Returns list of Wiki pages.
/// </summary>
/// <param name="projectId">project id</param>
/// <returns>list of <see cref="IWikiPage"/></returns>
public IList<IWikiPage> GetWikiPages(long projectId)
{
return GetWikiPages(string.Format("{0}", projectId));
}
/// <summary>
/// Get Wiki Page List
/// Returns list of Wiki pages.
/// </summary>
/// <param name="projectKey">project key</param>
/// <returns>list of <see cref="IWikiPage"/></returns>
public IList<IWikiPage> GetWikiPages(string projectKey)
{
var query = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("projectIdOrKey", projectKey)
};
var api = GetApiUri(new[] { "wikis" }, query);
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var res = GetApiResult<List<WikiPage>>(api, jss);
return res.Result.ToList<IWikiPage>();
}
/// <summary>
/// Count Wiki Page
/// Returns number of Wiki pages.
/// </summary>
/// <param name="projectId">project id</param>
/// <returns>list of <see cref="IWikiPage"/></returns>
public ICounter GetWikiPagesCount(long projectId)
{
return GetWikiPagesCount(string.Format("{0}", projectId));
}
/// <summary>
/// Count Wiki Page
/// Returns number of Wiki pages.
/// </summary>
/// <param name="projectKey">project key</param>
/// <returns>list of <see cref="IWikiPage"/></returns>
public ICounter GetWikiPagesCount(string projectKey)
{
var query = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("projectIdOrKey", projectKey)
};
var api = GetApiUri(new[] { "wikis", "count" }, query);
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var res = GetApiResult<Counter>(api, jss);
return res.Result;
}
/// <summary>
/// Get Wiki Page Tag List
/// Returns list of tags that are used in the project.
/// </summary>
/// <param name="projectId">project id</param>
/// <returns>list of <see cref="ITag"/></returns>
public IList<ITag> GetWikiPageTags(long projectId)
{
return GetWikiPageTags(string.Format("{0}", projectId));
}
/// <summary>
/// Get Wiki Page Tag List
/// Returns list of tags that are used in the project.
/// </summary>
/// <param name="projectKey">project key</param>
/// <returns>list of <see cref="ITag"/></returns>
public IList<ITag> GetWikiPageTags(string projectKey)
{
var query = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("projectIdOrKey", projectKey)
};
var api = GetApiUri(new[] { "wikis", "tags" }, query);
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var res = GetApiResult<List<Tag>>(api, jss);
return res.Result.ToList<ITag>();
}
/// <summary>
/// Add Wiki Page
/// Adds new Wiki page.
/// </summary>
/// <param name="projectId">project id</param>
/// <param name="addWikiPageOptions">adding wikipage info</param>
/// <returns>created <see cref="IWikiPage"/></returns>
public IWikiPage AddWikiPage(long projectId, AddWikiPageOptions addWikiPageOptions)
{
var api = GetApiUri(new[] { "wikis" });
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var kvs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("projectId", string.Format("{0}", projectId))
};
kvs.AddRange(addWikiPageOptions.ToKeyValuePairs());
var hc = new FormUrlEncodedContent(kvs);
var res = PostApiResult<WikiPage>(api, hc, jss);
return res.Result;
}
/// <summary>
/// Get Wiki Page
/// Returns information about Wiki page.
/// </summary>
/// <param name="pageId">wiki page id</param>
/// <returns>wiki page</returns>
public IWikiPage GetWikiPage(long pageId)
{
var api = GetApiUri(new[] { "wikis", pageId.ToString() });
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var res = GetApiResult<WikiPage>(api, jss);
return res.Result;
}
/// <summary>
/// Update Wiki Page
/// Updates information about Wiki page.
/// </summary>
/// <param name="wikiId">wiki page id</param>
/// <param name="updateOptions">update option</param>
/// <returns>updated <see cref="IWikiPage"/></returns>
public IWikiPage UpdateWikiPage(long wikiId, UpdateWikiPageOptions updateOptions)
{
var api = GetApiUri(new[] { "wikis", wikiId.ToString() });
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var hc = new FormUrlEncodedContent(updateOptions.ToKeyValuePairs());
var res = PatchApiResult<WikiPage>(api, hc, jss);
return res.Result;
}
/// <summary>
/// Delete Wiki Page
/// Deletes Wiki page.
/// </summary>
/// <param name="wikiId">wiki page id</param>
/// <param name="doNotify">true: do mail notify</param>
/// <returns></returns>
public IWikiPage DeleteWikiPage(long wikiId, bool doNotify)
{
var api = GetApiUri(new[] { "wikis", wikiId.ToString() });
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var kvs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("mailNotify", doNotify ? "true" : "false")
};
var hc = new FormUrlEncodedContent(kvs);
var res = DeleteApiResult<WikiPage>(api, hc, jss);
return res.Result;
}
/// <summary>
/// Get List of Wiki attachments
/// Gets list of files attached to Wiki.
/// </summary>
/// <param name="wikiId">wiki page id</param>
/// <returns>list of <see cref="IAttachment"/>(created/createdUser is not set)</returns>
public IList<IAttachment> GetWikiPageAttachments(long wikiId)
{
var api = GetApiUri(new[] { "wikis", wikiId.ToString(), "attachments" });
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var res = GetApiResult<List<Attachment>>(api, jss);
return res.Result.ToList<IAttachment>();
}
/// <summary>
/// Attach File to Wiki
/// Attaches file to Wiki
/// </summary>
/// <param name="wikiId">wiki page id</param>
/// <param name="fileIds">attachment file ids</param>
/// <returns>list of <see cref="IAttachment"/></returns>
public IList<IAttachment> AddWikiPageAttachments(long wikiId, IEnumerable<long> fileIds)
{
var api = GetApiUri(new[] { "wikis", wikiId.ToString(), "attachments" });
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var kvs = fileIds.ToKeyValuePairs("attachmentId[]");
var hc = new FormUrlEncodedContent(kvs);
var res = PostApiResult<List<Attachment>>(api, hc, jss);
return res.Result.ToList<IAttachment>();
}
/// <summary>
/// Get Wiki Page Attachment
/// Downloads Wiki page's attachment file.
/// </summary>
/// <param name="wikiId">wiki page id</param>
/// <param name="fileId">attachment file id</param>
/// <returns>downloaded file content and name as <see cref="ISharedFileData"/></returns>
public ISharedFileData GetWikiPageAttachment(long wikiId, long fileId)
{
var api = GetApiUri(new[] { "wikis", wikiId.ToString(), "attachments", fileId.ToString() });
var res = GetApiResultAsFile(api);
var file = new SharedFileData(res.Result.Item1, res.Result.Item2);
return file;
}
/// <summary>
/// Remove Wiki Attachment
/// Removes files attached to Wiki.
/// </summary>
/// <param name="wikiId">wiki page id</param>
/// <param name="fileId">attachment file id</param>
/// <returns>removed file <see cref="IAttachment"/></returns>
public IAttachment RemoveWikiPageAttachment(long wikiId, long fileId)
{
var api = GetApiUri(new[] { "wikis", wikiId.ToString(), "attachments", fileId.ToString() });
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var res = DeleteApiResult<Attachment>(api, jss);
return res.Result;
}
/// <summary>
/// Get List of Shared Files on Wiki
/// Returns the list of Shared Files on Wiki.
/// </summary>
/// <param name="wikiId">wiki page id</param>
/// <returns>list of <see cref="ISharedFile"/></returns>
public IList<ISharedFile> GetWikiPageSharedFiles(long wikiId)
{
var api = GetApiUri(new[] { "wikis", wikiId.ToString(), "sharedFiles" });
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var res = GetApiResult<List<SharedFile>>(api, jss);
return res.Result.ToList<ISharedFile>();
}
/// <summary>
/// Link Shared Files to Wiki
/// Links Shared Files to Wiki.
/// </summary>
/// <param name="wikiId">wiki page id</param>
/// <param name="fileIds">shared file id</param>
/// <returns>list of linked <see cref="ISharedFile"/> </returns>
public IList<ISharedFile> AddWikiPageSharedFiles(long wikiId, IEnumerable<long> fileIds)
{
var api = GetApiUri(new[] { "wikis", wikiId.ToString(), "sharedFiles" });
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var kvs = fileIds.ToKeyValuePairs("fileId[]");
var hc = new FormUrlEncodedContent(kvs);
var res = PostApiResult<List<SharedFile>>(api, hc, jss);
return res.Result.ToList<ISharedFile>();
}
/// <summary>
/// Remove Link to Shared File from Wiki
/// Removes link to shared file from Wiki.
/// </summary>
/// <param name="wikiId">wiki page id</param>
/// <param name="fileId">shared file id</param>
/// <returns>deleted <see cref="ISharedFile"/></returns>
public ISharedFile RemoveWikiPageSharedFile(long wikiId, long fileId)
{
var api = GetApiUri(new[] { "wikis", wikiId.ToString(), "sharedFiles", fileId.ToString() });
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var res = DeleteApiResult<SharedFile>(api, jss);
return res.Result;
}
/// <summary>
/// Get Wiki Page History
/// Returns history of Wiki page.
/// </summary>
/// <param name="wikiId">wiki page id</param>
/// <param name="filter">result paging option</param>
/// <returns>list of <see cref="IWikiPageHistory"/></returns>
public IList<IWikiPageHistory> GetWikiPageHistory(long wikiId, ResultPagingOptions filter = null)
{
var query = filter == null ? null : filter.ToKeyValuePairs();
var api = GetApiUri(new[] { "wikis", wikiId.ToString(), "history" }, query);
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var res = GetApiResult<List<WikiPageHistory>>(api, jss);
return res.Result.ToList<IWikiPageHistory>();
}
/// <summary>
/// Get Wiki Page Star
/// Returns list of stars received on the Wiki page.
/// </summary>
/// <param name="wikiId">wiki page id</param>
/// <returns>list of <see cref="IStar"/></returns>
public IList<IStar> GetWikiPageStars(long wikiId)
{
var api = GetApiUri(new[] { "wikis", wikiId.ToString(), "stars" });
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore
};
var res = GetApiResult<List<Star>>(api, jss);
return res.Result.ToList<IStar>();
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Conditions
{
using NLog.Internal;
using NLog.Conditions;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using Xunit;
public class ConditionParserTests : NLogTestBase
{
[Fact]
public void ParseNullText()
{
Assert.Null(ConditionParser.ParseExpression(null));
}
[Fact]
public void ParseEmptyText()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression(""));
}
[Fact]
public void ImplicitOperatorTest()
{
ConditionExpression cond = "true and true";
Assert.IsType<ConditionAndExpression>(cond);
}
[Fact]
public void NullLiteralTest()
{
Assert.Equal("null", ConditionParser.ParseExpression("null").ToString());
}
[Fact]
public void BooleanLiteralTest()
{
Assert.Equal("True", ConditionParser.ParseExpression("true").ToString());
Assert.Equal("True", ConditionParser.ParseExpression("tRuE").ToString());
Assert.Equal("False", ConditionParser.ParseExpression("false").ToString());
Assert.Equal("False", ConditionParser.ParseExpression("fAlSe").ToString());
}
[Fact]
public void AndTest()
{
Assert.Equal("(True and True)", ConditionParser.ParseExpression("true and true").ToString());
Assert.Equal("(True and True)", ConditionParser.ParseExpression("tRuE AND true").ToString());
Assert.Equal("(True and True)", ConditionParser.ParseExpression("tRuE && true").ToString());
Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("true and true && true").ToString());
Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("tRuE AND true and true").ToString());
Assert.Equal("((True and True) and True)", ConditionParser.ParseExpression("tRuE && true AND true").ToString());
}
[Fact]
public void OrTest()
{
Assert.Equal("(True or True)", ConditionParser.ParseExpression("true or true").ToString());
Assert.Equal("(True or True)", ConditionParser.ParseExpression("tRuE OR true").ToString());
Assert.Equal("(True or True)", ConditionParser.ParseExpression("tRuE || true").ToString());
Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("true or true || true").ToString());
Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("tRuE OR true or true").ToString());
Assert.Equal("((True or True) or True)", ConditionParser.ParseExpression("tRuE || true OR true").ToString());
}
[Fact]
public void NotTest()
{
Assert.Equal("(not True)", ConditionParser.ParseExpression("not true").ToString());
Assert.Equal("(not (not True))", ConditionParser.ParseExpression("not not true").ToString());
Assert.Equal("(not (not (not True)))", ConditionParser.ParseExpression("not not not true").ToString());
}
[Fact]
public void StringTest()
{
Assert.Equal("''", ConditionParser.ParseExpression("''").ToString());
Assert.Equal("'Foo'", ConditionParser.ParseExpression("'Foo'").ToString());
Assert.Equal("'Bar'", ConditionParser.ParseExpression("'Bar'").ToString());
Assert.Equal("'d'Artagnan'", ConditionParser.ParseExpression("'d''Artagnan'").ToString());
var cle = ConditionParser.ParseExpression("'${message} ${level}'") as ConditionLayoutExpression;
Assert.NotNull(cle);
SimpleLayout sl = cle.Layout as SimpleLayout;
Assert.NotNull(sl);
Assert.Equal(3, sl.Renderers.Count);
Assert.IsType<MessageLayoutRenderer>(sl.Renderers[0]);
Assert.IsType<LiteralLayoutRenderer>(sl.Renderers[1]);
Assert.IsType<LevelLayoutRenderer>(sl.Renderers[2]);
}
[Fact]
public void LogLevelTest()
{
var result = ConditionParser.ParseExpression("LogLevel.Info") as ConditionLiteralExpression;
Assert.NotNull(result);
Assert.Same(LogLevel.Info, result.LiteralValue);
result = ConditionParser.ParseExpression("LogLevel.Trace") as ConditionLiteralExpression;
Assert.NotNull(result);
Assert.Same(LogLevel.Trace, result.LiteralValue);
}
[Fact]
public void RelationalOperatorTest()
{
RelationalOperatorTestInner("=", "==");
RelationalOperatorTestInner("==", "==");
RelationalOperatorTestInner("!=", "!=");
RelationalOperatorTestInner("<>", "!=");
RelationalOperatorTestInner("<", "<");
RelationalOperatorTestInner(">", ">");
RelationalOperatorTestInner("<=", "<=");
RelationalOperatorTestInner(">=", ">=");
}
[Fact]
public void NumberTest()
{
Assert.Equal("3.141592", ConditionParser.ParseExpression("3.141592").ToString());
Assert.Equal("42", ConditionParser.ParseExpression("42").ToString());
Assert.Equal("-42", ConditionParser.ParseExpression("-42").ToString());
Assert.Equal("-3.141592", ConditionParser.ParseExpression("-3.141592").ToString());
}
[Fact]
public void ExtraParenthesisTest()
{
Assert.Equal("3.141592", ConditionParser.ParseExpression("(((3.141592)))").ToString());
}
[Fact]
public void MessageTest()
{
var result = ConditionParser.ParseExpression("message");
Assert.IsType<ConditionMessageExpression>(result);
Assert.Equal("message", result.ToString());
}
[Fact]
public void LevelTest()
{
var result = ConditionParser.ParseExpression("level");
Assert.IsType<ConditionLevelExpression>(result);
Assert.Equal("level", result.ToString());
}
[Fact]
public void LoggerTest()
{
var result = ConditionParser.ParseExpression("logger");
Assert.IsType<ConditionLoggerNameExpression>(result);
Assert.Equal("logger", result.ToString());
}
[Fact]
public void ConditionFunctionTests()
{
var result = ConditionParser.ParseExpression("starts-with(logger, 'x${message}')") as ConditionMethodExpression;
Assert.NotNull(result);
Assert.Equal("starts-with(logger, 'x${message}')", result.ToString());
Assert.Equal("StartsWith", result.MethodInfo.Name);
Assert.Equal(typeof(ConditionMethods), result.MethodInfo.DeclaringType);
}
[Fact]
public void CustomNLogFactoriesTest()
{
var configurationItemFactory = new ConfigurationItemFactory();
configurationItemFactory.LayoutRenderers.RegisterDefinition("foo", typeof(FooLayoutRenderer));
configurationItemFactory.ConditionMethods.RegisterDefinition("check", typeof(MyConditionMethods).GetMethod("CheckIt"));
ConditionParser.ParseExpression("check('${foo}')", configurationItemFactory);
}
[Fact]
public void MethodNameWithUnderscores()
{
var configurationItemFactory = new ConfigurationItemFactory();
configurationItemFactory.LayoutRenderers.RegisterDefinition("foo", typeof(FooLayoutRenderer));
configurationItemFactory.ConditionMethods.RegisterDefinition("__check__", typeof(MyConditionMethods).GetMethod("CheckIt"));
ConditionParser.ParseExpression("__check__('${foo}')", configurationItemFactory);
}
[Fact]
public void UnbalancedParenthesis1Test()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("check("));
}
[Fact]
public void UnbalancedParenthesis2Test()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("((1)"));
}
[Fact]
public void UnbalancedParenthesis3Test()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("(1))"));
}
[Fact]
public void LogLevelWithoutAName()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("LogLevel.'somestring'"));
}
[Fact]
public void InvalidNumberWithUnaryMinusTest()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("-a31"));
}
[Fact]
public void InvalidNumberTest()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("-123.4a"));
}
[Fact]
public void UnclosedString()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("'Hello world"));
}
[Fact]
public void UnrecognizedToken()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("somecompletelyunrecognizedtoken"));
}
[Fact]
public void UnrecognizedPunctuation()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("#"));
}
[Fact]
public void UnrecognizedUnicodeChar()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("\u0090"));
}
[Fact]
public void UnrecognizedUnicodeChar2()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("\u0015"));
}
[Fact]
public void UnrecognizedMethod()
{
Assert.Throws<ConditionParseException>(() => ConditionParser.ParseExpression("unrecognized-method()"));
}
[Fact]
public void TokenizerEOFTest()
{
var tokenizer = new ConditionTokenizer(new SimpleStringReader(string.Empty));
Assert.Throws<ConditionParseException>(() => tokenizer.GetNextToken());
}
private void RelationalOperatorTestInner(string op, string result)
{
string operand1 = "3";
string operand2 = "7";
string input = operand1 + " " + op + " " + operand2;
string expectedOutput = "(" + operand1 + " " + result + " " + operand2 + ")";
var condition = ConditionParser.ParseExpression(input);
Assert.Equal(expectedOutput, condition.ToString());
}
public class FooLayoutRenderer : LayoutRenderer
{
protected override void Append(System.Text.StringBuilder builder, LogEventInfo logEvent)
{
throw new System.NotImplementedException();
}
}
public class MyConditionMethods
{
public static bool CheckIt(string s)
{
return s == "X";
}
}
}
}
| |
// <copyright file="Skeleton.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using OpenTelemetry.Metrics;
namespace OpenTelemetry.Tests.Stress;
public partial class Program
{
private static readonly Meter StressMeter = new Meter("OpenTelemetry.Tests.Stress");
private static volatile bool bContinue = true;
private static volatile string output = "Test results not available yet.";
static Program()
{
var process = Process.GetCurrentProcess();
StressMeter.CreateObservableGauge("Process.NonpagedSystemMemorySize64", () => process.NonpagedSystemMemorySize64);
StressMeter.CreateObservableGauge("Process.PagedSystemMemorySize64", () => process.PagedSystemMemorySize64);
StressMeter.CreateObservableGauge("Process.PagedMemorySize64", () => process.PagedMemorySize64);
StressMeter.CreateObservableGauge("Process.WorkingSet64", () => process.WorkingSet64);
StressMeter.CreateObservableGauge("Process.VirtualMemorySize64", () => process.VirtualMemorySize64);
}
public static void Stress(int concurrency = 0, int prometheusPort = 0)
{
#if DEBUG
Console.WriteLine("***WARNING*** The current build is DEBUG which may affect timing!");
Console.WriteLine();
#endif
if (concurrency < 0)
{
throw new ArgumentOutOfRangeException(nameof(concurrency), "concurrency level should be a non-negative number.");
}
if (concurrency == 0)
{
concurrency = Environment.ProcessorCount;
}
using var meter = new Meter("OpenTelemetry.Tests.Stress." + Guid.NewGuid().ToString("D"));
var cntLoopsTotal = 0UL;
meter.CreateObservableCounter(
"OpenTelemetry.Tests.Stress.Loops",
() => unchecked((long)cntLoopsTotal),
description: "The total number of `Run()` invocations that are completed.");
var dLoopsPerSecond = 0D;
meter.CreateObservableGauge(
"OpenTelemetry.Tests.Stress.LoopsPerSecond",
() => dLoopsPerSecond,
description: "The rate of `Run()` invocations based on a small sliding window of few hundreds of milliseconds.");
var dCpuCyclesPerLoop = 0D;
#if NET462
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
#else
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
#endif
{
meter.CreateObservableGauge(
"OpenTelemetry.Tests.Stress.CpuCyclesPerLoop",
() => dCpuCyclesPerLoop,
description: "The average CPU cycles for each `Run()` invocation, based on a small sliding window of few hundreds of milliseconds.");
}
using var meterProvider = prometheusPort != 0 ? Sdk.CreateMeterProviderBuilder()
.AddMeter(StressMeter.Name)
.AddMeter(meter.Name)
.AddPrometheusExporter(options =>
{
options.StartHttpListener = true;
options.HttpListenerPrefixes = new string[] { $"http://localhost:{prometheusPort}/" };
options.ScrapeResponseCacheDurationMilliseconds = 0;
})
.Build() : null;
var statistics = new long[concurrency];
var watchForTotal = Stopwatch.StartNew();
Parallel.Invoke(
() =>
{
Console.Write($"Running (concurrency = {concurrency}");
if (prometheusPort != 0)
{
Console.Write($", prometheusEndpoint = http://localhost:{prometheusPort}/metrics/");
}
Console.WriteLine("), press <Esc> to stop...");
var bOutput = false;
var watch = new Stopwatch();
while (true)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true).Key;
switch (key)
{
case ConsoleKey.Enter:
Console.WriteLine(string.Format("{0} {1}", DateTime.UtcNow.ToString("O"), output));
break;
case ConsoleKey.Escape:
bContinue = false;
return;
case ConsoleKey.Spacebar:
bOutput = !bOutput;
break;
}
continue;
}
if (bOutput)
{
Console.WriteLine(string.Format("{0} {1}", DateTime.UtcNow.ToString("O"), output));
}
var cntLoopsOld = (ulong)statistics.Sum();
var cntCpuCyclesOld = GetCpuCycles();
watch.Restart();
Thread.Sleep(200);
watch.Stop();
cntLoopsTotal = (ulong)statistics.Sum();
var cntCpuCyclesNew = GetCpuCycles();
var nLoops = cntLoopsTotal - cntLoopsOld;
var nCpuCycles = cntCpuCyclesNew - cntCpuCyclesOld;
dLoopsPerSecond = (double)nLoops / ((double)watch.ElapsedMilliseconds / 1000.0);
dCpuCyclesPerLoop = nLoops == 0 ? 0 : nCpuCycles / nLoops;
output = $"Loops: {cntLoopsTotal:n0}, Loops/Second: {dLoopsPerSecond:n0}, CPU Cycles/Loop: {dCpuCyclesPerLoop:n0}";
Console.Title = output;
}
},
() =>
{
Parallel.For(0, concurrency, (i) =>
{
statistics[i] = 0;
while (bContinue)
{
Run();
statistics[i]++;
}
});
});
watchForTotal.Stop();
cntLoopsTotal = (ulong)statistics.Sum();
var totalLoopsPerSecond = (double)cntLoopsTotal / ((double)watchForTotal.ElapsedMilliseconds / 1000.0);
var cntCpuCyclesTotal = GetCpuCycles();
var cpuCyclesPerLoopTotal = cntLoopsTotal == 0 ? 0 : cntCpuCyclesTotal / cntLoopsTotal;
Console.WriteLine("Stopping the stress test...");
Console.WriteLine($"* Total Loops: {cntLoopsTotal:n0}");
Console.WriteLine($"* Average Loops/Second: {totalLoopsPerSecond:n0}");
Console.WriteLine($"* Average CPU Cycles/Loop: {cpuCyclesPerLoopTotal:n0}");
}
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool QueryProcessCycleTime(IntPtr hProcess, out ulong cycles);
private static ulong GetCpuCycles()
{
#if NET462
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
#else
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
#endif
{
return 0;
}
if (!QueryProcessCycleTime((IntPtr)(-1), out var cycles))
{
return 0;
}
return cycles;
}
}
| |
// 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 AndUInt16()
{
var test = new SimpleBinaryOpTest__AndUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndUInt16
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[ElementCount];
private static UInt16[] _data2 = new UInt16[ElementCount];
private static Vector128<UInt16> _clsVar1;
private static Vector128<UInt16> _clsVar2;
private Vector128<UInt16> _fld1;
private Vector128<UInt16> _fld2;
private SimpleBinaryOpTest__DataTable<UInt16> _dataTable;
static SimpleBinaryOpTest__AndUInt16()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AndUInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt16>(_data1, _data2, new UInt16[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.And(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.And(
Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.And(
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.And(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr);
var result = Sse2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr));
var result = Sse2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr));
var result = Sse2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndUInt16();
var result = Sse2.And(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.And(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt16> left, Vector128<UInt16> right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[ElementCount];
UInt16[] inArray2 = new UInt16[ElementCount];
UInt16[] outArray = new UInt16[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[ElementCount];
UInt16[] inArray2 = new UInt16[ElementCount];
UInt16[] outArray = new UInt16[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
if ((ushort)(left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((ushort)(left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.And)}<UInt16>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
//set player transform
gameObject.transform.position = GameManager.instance.lastPosition;
gameObject.transform.rotation = GameManager.instance.lastRotation;
}
// Update is called once per frame
private void Update()
{
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
m_MouseLook.UpdateCursorLock();
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
| |
// Client-server helpers for TCP/IP
// ClientInfo: wrapper for a socket which throws
// Receive events, and allows for messaged communication (using
// a specified character as end-of-message)
// Server: simple TCP server that throws Connect events
// ByteBuilder: utility class to manage byte arrays built up
// in multiple transactions
// (C) Richard Smith 2005-9
// bobjanova@gmail.com
// You can use this for free and give it to people as much as you like
// as long as you leave a credit to me :).
// Code to connect to a SOCKS proxy modified from
// http://www.thecodeproject.com/csharp/ZaSocks5Proxy.asp
// changelog 1.6
// Option for thread synchronisation on a UI control
// Define this symbol to include console output in various places
//#define DEBUG
// Define this symbol to use the old host name resolution
//#define NET_1_1
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Collections;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Security.Cryptography;
using RedCorona.Cryptography;
[assembly:System.Reflection.AssemblyVersion("1.6.2010.1228")]
namespace RedCorona.Net {
public delegate void ConnectionRead(ClientInfo ci, String text);
public delegate void ConnectionClosed(ClientInfo ci);
public delegate void ConnectionReadBytes(ClientInfo ci, byte[] bytes, int len);
public delegate void ConnectionReadMessage(ClientInfo ci, uint code, byte[] bytes, int len);
public delegate void ConnectionReadPartialMessage(ClientInfo ci, uint code, byte[] bytes, int start, int read, int sofar, int totallength);
public delegate void ConnectionNotify(ClientInfo ci);
public enum ClientDirection {In, Out, Left, Right, Both};
public enum MessageType {Unmessaged, EndMarker, Length, CodeAndLength};
// ServerDES: The server sends an encryption key on connect
// ServerRSAClientDES: The server sends an RSA public key, the client sends back a key
public enum EncryptionType {None, ServerKey, ServerRSAClientKey};
public class EncryptionUtils {
static RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
public static byte[] GetRandomBytes(int length, bool addByte){
if(addByte && (length > 255)) throw new ArgumentException("Length must be 1 byte <256");
byte[] random = new byte[length + (addByte ? 1 : 0)];
rng.GetBytes(random);
if(addByte) random[0] = (byte)length;
return random;
}
}
// OnReadBytes: catch the raw bytes as they arrive
// OnRead: for text ended with a marker character
// OnReadMessage: for binary info on a messaged client
public class ClientInfo {
internal Server server = null;
private Socket sock;
private String buffer;
public event ConnectionRead OnRead;
public event ConnectionClosed OnClose;
public event ConnectionReadBytes OnReadBytes;
public event ConnectionReadMessage OnReadMessage;
public event ConnectionReadPartialMessage OnPartialMessage;
public event ConnectionNotify OnReady;
public MessageType MessageType;
private ClientDirection dir;
int id;
bool alreadyclosed = false;
public static int NextID = 100;
private Exception closeException;
private string closeReason = null;
//private ClientThread t;
public object Data = null;
private Control threadSyncControl;
// Encryption info
EncryptionType encType;
int encRead = 0, encStage, encExpected;
internal bool encComplete;
internal byte[] encKey;
internal RSAParameters encParams;
public EncryptionType EncryptionType {
get { return encType; }
set {
if(encStage != 0) throw new ArgumentException("Key exchange has already begun");
encType = value;
encComplete = encType == EncryptionType.None;
encExpected = -1;
}
}
public bool EncryptionReady { get { return encComplete; } }
internal ICryptoTransform encryptor, decryptor;
public ICryptoTransform Encryptor { get { return encryptor; } }
public ICryptoTransform Decryptor { get { return decryptor; } }
public Control ThreadSyncControl { get { return threadSyncControl; } set { threadSyncControl = value; } }
private string delim;
public const int BUFSIZE = 1024;
byte[] buf = new byte[BUFSIZE];
ByteBuilder bytes = new ByteBuilder(10);
byte[] msgheader = new byte[8];
byte headerread = 0;
bool wantingChecksum = true;
bool sentReady = false;
public string Delimiter {
get { return delim; }
set { delim = value; }
}
public ClientDirection Direction { get { return dir; } }
public Socket Socket { get { return sock; } }
public Server Server { get { return server; } }
public int ID { get { return id; } }
public bool Closed {
get { return !sock.Connected; }
}
public string CloseReason { get { return closeReason; } }
public Exception CloseException { get { return closeException; } }
public ClientInfo(Socket cl, bool StartNow) : this(cl, null, null, ClientDirection.Both, StartNow, EncryptionType.None) {}
//public ClientInfo(Socket cl, ConnectionRead read, ConnectionReadBytes readevt, ClientDirection d) : this(cl, read, readevt, d, true, EncryptionType.None) {}
public ClientInfo(Socket cl, ConnectionRead read, ConnectionReadBytes readevt, ClientDirection d, bool StartNow) : this(cl, read, readevt, d, StartNow, EncryptionType.None) {}
public ClientInfo(Socket cl, ConnectionRead read, ConnectionReadBytes readevt, ClientDirection d, bool StartNow, EncryptionType encryptionType){
sock = cl; buffer = ""; OnReadBytes = readevt; encType = encryptionType;
encStage = 0; encComplete = encType == EncryptionType.None;
OnRead = read;
MessageType = MessageType.EndMarker;
dir = d; delim = "\n";
id = NextID; // Assign each client an application-unique ID
unchecked{NextID++;}
//t = new ClientThread(this);
if(StartNow) BeginReceive();
}
public void BeginReceive(){
// t.t.Start();
if((encType == EncryptionType.None) && (!sentReady)) {
sentReady = true;
if(OnReady != null) OnReady(this);
}
sock.BeginReceive(buf, 0, BUFSIZE, 0, new AsyncCallback(ReadCallback), this);
}
public String Send(String text){
byte[] ba = Encoding.UTF8.GetBytes(text);
String s = "";
for(int i = 0; i < ba.Length; i++) s += ba[i] + " ";
Send(ba);
return s;
}
public void SendMessage(uint code, byte[] bytes){ SendMessage(code, bytes, 0, bytes.Length); }
public void SendMessage(uint code, byte[] bytes, byte paramType){ SendMessage(code, bytes, paramType, bytes.Length); }
public void SendMessage(uint code, byte[] bytes, byte paramType, int len){
if(paramType > 0){
ByteBuilder b = new ByteBuilder(3);
b.AddParameter(bytes, paramType);
bytes = b.Read(0, b.Length);
len = bytes.Length;
}
lock(sock){
byte checksum = 0; byte[] ba;
switch(MessageType){
case MessageType.CodeAndLength:
Send(ba = UintToBytes(code));
for(int i = 0; i < 4; i++) checksum += ba[i];
Send(ba = IntToBytes(len));
for(int i = 0; i < 4; i++) checksum += ba[i];
if(encType != EncryptionType.None) Send(new byte[]{checksum});
break;
case MessageType.Length:
Send(ba = IntToBytes(len));
for(int i = 0; i < 4; i++) checksum += ba[i];
if(encType != EncryptionType.None) Send(new byte[]{checksum});
break;
}
Send(bytes, len);
if(encType != EncryptionType.None){
checksum = 0;
for(int i = 0; i < len; i++) checksum += bytes[i];
Send(new byte[]{checksum});
}
}
}
public void Send(byte[] bytes){ Send(bytes, bytes.Length); }
public void Send(byte[] bytes, int len){
if(!encComplete) throw new IOException("Key exchange is not yet completed");
if(encType != EncryptionType.None){
byte[] outbytes = new byte[len];
Encryptor.TransformBlock(bytes, 0, len, outbytes, 0);
bytes = outbytes;
//Console.Write("Encryptor IV: "); LogBytes(encryptor.Key, encryptor.IV.length);
}
#if DEBUG
Console.Write(ID + " Sent: "); LogBytes(bytes, len);
#endif
try {
sock.Send(bytes, len, SocketFlags.None);
} catch(Exception e){
closeException = e;
closeReason = "Exception in send: "+e.Message;
Close();
}
}
public bool MessageWaiting(){
FillBuffer(sock);
return buffer.IndexOf(delim) >= 0;
}
public String Read(){
//FillBuffer(sock);
int p = buffer.IndexOf(delim);
if(p >= 0){
String res = buffer.Substring(0, p);
buffer = buffer.Substring(p + delim.Length);
return res;
} else return "";
}
private void FillBuffer(Socket sock){
byte[] buf = new byte[256];
int read;
while(sock.Available != 0){
read = sock.Receive(buf);
if(OnReadBytes != null) OnReadBytes(this, buf, read);
buffer += Encoding.UTF8.GetString(buf, 0, read);
}
}
void ReadCallback(IAsyncResult ar){
try {
int read = sock.EndReceive(ar);
//Console.WriteLine("Socket "+ID+" read "+read+" bytes");
if(read > 0){
DoRead(buf, read);
BeginReceive();
} else {
#if DEBUG
Console.WriteLine(ID + " zero byte read closure");
#endif
closeReason = "Zero byte read (no data available)";
closeException = null;
Close();
}
} catch(SocketException e){
#if DEBUG
Console.WriteLine(ID + " socket exception closure: "+e);
#endif
closeReason = "Socket exception (" + e.Message + ")";
closeException = e;
Close();
} catch(ObjectDisposedException e){
#if DEBUG
Console.WriteLine(ID + " disposed exception closure");
#endif
closeReason = "Disposed exception (socket object was disposed by the subsystem)";
closeException = e;
Close();
}
}
internal void DoRead(byte[] buf, int read){
if(read > 0){
if(OnRead != null){ // Simple text mode
buffer += Encoding.UTF8.GetString(buf, 0, read);
while(buffer.IndexOf(delim) >= 0){
if(threadSyncControl != null) threadSyncControl.BeginInvoke(OnRead, new object[]{this, Read()});
else OnRead(this, Read());
}
}
}
Console.WriteLine(ID + " read "+read+" bytes for event handler");
ReadInternal(buf, read, false);
}
public static void LogBytes(byte[] buf, int len){
byte[] ba = new byte[len];
Array.Copy(buf, ba, len);
Console.WriteLine(ByteBuilder.FormatParameter(new Parameter(ba, ParameterType.Byte)));
}
void ReadInternal(byte[] buf, int read, bool alreadyEncrypted){
Console.WriteLine(ID + " read "+read+" bytes for event handler");
if((!alreadyEncrypted) && (encType != EncryptionType.None)){
if(encComplete){
#if DEBUG
Console.Write(ID + " Received: "); LogBytes(buf, read);
#endif
buf = decryptor.TransformFinalBlock(buf, 0, read);
#if DEBUG
Console.Write(ID + " Decrypted: "); LogBytes(buf, read);
#endif
} else {
// Client side key exchange
int ofs = 0;
if(encExpected < 0){
encStage++;
ofs++; read--; encExpected = buf[0]; // length of key to come
encKey = new byte[encExpected];
encRead = 0;
}
if(read >= encExpected){
Array.Copy(buf, ofs, encKey, encRead, encExpected);
int togo = read - encExpected;
encExpected = -1;
#if DEBUG
Console.WriteLine(ID + " Read encryption key: "+ByteBuilder.FormatParameter(new Parameter(encKey, ParameterType.Byte)));
#endif
if(server == null) ClientEncryptionTransferComplete();
else ServerEncryptionTransferComplete();
if(togo > 0){
byte[] newbuf = new byte[togo];
Array.Copy(buf, read + ofs - togo, newbuf, 0, togo);
ReadInternal(newbuf, togo, false);
}
} else {
Array.Copy(buf, ofs, encKey, encRead, read);
encExpected -= read; encRead += read;
}
return;
}
}
if((!alreadyEncrypted) && (OnReadBytes != null)){
if(threadSyncControl != null) threadSyncControl.BeginInvoke(OnReadBytes, new object[]{this, buf, read});
else OnReadBytes(this, buf, read);
}
if((OnReadMessage != null) && (MessageType != MessageType.Unmessaged)){
// Messaged mode
int copied;
uint code = 0;
switch(MessageType){
case MessageType.CodeAndLength:
case MessageType.Length:
int length;
if(MessageType == MessageType.Length){
copied = FillHeader(ref buf, 4, read);
if(headerread < 4) break;
length = GetInt(msgheader, 0, 4);
} else{
copied = FillHeader(ref buf, 8, read);
if(headerread < 8) break;
code = (uint)GetInt(msgheader, 0, 4);
length = GetInt(msgheader, 4, 4);
}
if(read == copied) break;
// If encryption is on, the next byte is a checksum of the header
int ofs = 0;
if(wantingChecksum && (encType != EncryptionType.None)){
byte checksum = buf[0];
ofs++;
wantingChecksum = false;
byte headersum = 0;
for(int i = 0; i < 8; i++) headersum += msgheader[i];
if(checksum != headersum){
Close();
throw new IOException("Header checksum failed! (was "+checksum+", calculated "+headersum+")");
}
}
bytes.Add(buf, ofs, read - ofs - copied);
if(encType != EncryptionType.None) length++; // checksum byte
// Now we know we are reading into the body of the message
#if DEBUG
Console.WriteLine(ID + " Added "+(read - ofs - copied)+" bytes, have "+bytes.Length+" of "+length);
#endif
if(OnPartialMessage != null) {
if(threadSyncControl != null) threadSyncControl.BeginInvoke(OnPartialMessage, new object[]{this, code, buf, ofs, read - ofs - copied, bytes.Length, length});
else OnPartialMessage(this, code, buf, ofs, read - ofs - copied, bytes.Length, length);
}
if(bytes.Length >= length){
// A message was received!
headerread = 0; wantingChecksum = true;
byte[] msg = bytes.Read(0, length);
if(encType != EncryptionType.None){
byte checksum = msg[length - 1], msgsum = 0;
for(int i = 0; i < length - 1; i++) msgsum += msg[i];
if(checksum != msgsum){
Close();
throw new IOException("Content checksum failed! (was "+checksum+", calculated "+msgsum+")");
}
if(threadSyncControl != null) threadSyncControl.BeginInvoke(OnReadMessage, new object[]{this, code, msg, length - 1});
else OnReadMessage(this, code, msg, length - 1);
} else {
if(threadSyncControl != null) threadSyncControl.BeginInvoke(OnReadMessage, new object[]{this, code, msg, length });
else OnReadMessage(this, code, msg, length);
}
// Don't forget to put the rest through the mill
int togo = bytes.Length - length;
if(togo > 0){
byte[] whatsleft = bytes.Read(length, togo);
bytes.Clear();
ReadInternalSecondPass(whatsleft);
} else bytes.Clear();
}
//if(OnStatus != null) OnStatus(this, bytes.Length, length);
break;
}
}
}
void ReadInternalSecondPass(byte[] newbytes){
ReadInternal(newbytes, newbytes.Length, true);
}
int FillHeader(ref byte[] buf, int to, int read) {
int copied = 0;
if(headerread < to){
// First copy the header into the header variable.
for(int i = 0; (i < read) && (headerread < to); i++, headerread++, copied++){
msgheader[headerread] = buf[i];
}
}
if(copied > 0){
// Take the header bytes off the 'message' section
byte[] newbuf = new byte[read - copied];
for(int i = 0; i < newbuf.Length; i++) newbuf[i] = buf[i + copied];
buf = newbuf;
}
return copied;
}
internal ICryptoTransform MakeEncryptor(){ return MakeCrypto(true); }
internal ICryptoTransform MakeDecryptor(){ return MakeCrypto(false); }
internal ICryptoTransform MakeCrypto(bool encrypt){
if(encrypt) return new SimpleEncryptor(encKey);
else return new SimpleDecryptor(encKey);
}
void ServerEncryptionTransferComplete(){
switch(encType){
case EncryptionType.None:
throw new ArgumentException("Should not have key exchange for unencrypted connection!");
case EncryptionType.ServerKey:
throw new ArgumentException("Should not have server-side key exchange for server keyed connection!");
case EncryptionType.ServerRSAClientKey:
// Symmetric key is in RSA-encoded encKey
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(encParams);
encKey = rsa.Decrypt(encKey, false);
#if DEBUG
Console.WriteLine("Symmetric key is: "); LogBytes(encKey, encKey.Length);
#endif
MakeEncoders();
server.KeyExchangeComplete(this);
break;
}
}
void ClientEncryptionTransferComplete(){
// A part of the key exchange process has been completed, and the key is
// in encKey
switch(encType){
case EncryptionType.None:
throw new ArgumentException("Should not have key exchange for unencrypted connection!");
case EncryptionType.ServerKey:
// key for transfer is now in encKey, so all is good
MakeEncoders();
break;
case EncryptionType.ServerRSAClientKey:
// Stage 1: modulus; Stage 2: exponent
// When the exponent arrives, create a random DES key
// and send it
switch(encStage){
case 1: encParams.Modulus = encKey; break;
case 2:
encParams.Exponent = encKey;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(encParams);
encKey = EncryptionUtils.GetRandomBytes(24, false);
byte[] send = GetLengthEncodedVector(rsa.Encrypt(encKey, false));
sock.Send(send);
#if DEBUG
Console.WriteLine("Sent symmetric key: "+ByteBuilder.FormatParameter(new Parameter(send, ParameterType.Byte)));
#endif
MakeEncoders();
break;
}
break;
}
}
internal void MakeEncoders(){
encryptor = MakeEncryptor();
decryptor = MakeDecryptor();
encComplete = true;
if(OnReady != null) OnReady(this);
}
public static byte[] GetLengthEncodedVector(byte[] from){
int l = from.Length;
if(l > 255) throw new ArgumentException("Cannot length encode more than 255");
byte[] to = new byte[l + 1];
to[0] = (byte)l;
Array.Copy(from, 0, to, 1, l);
return to;
}
public static int GetInt(byte[] ba, int from, int len){
int r = 0;
for(int i = 0; i < len; i++)
r += ba[from + i] << ((len - i - 1) * 8);
return r;
}
public static int[] GetIntArray(byte[] ba){ return GetIntArray(ba, 0, ba.Length, 4); }
public static int[] GetIntArray(byte[] ba, int from, int len){ return GetIntArray(ba, from, len, 4); }
public static int[] GetIntArray(byte[] ba, int from, int len, int stride){
int[] res = new int[len / stride];
for(int i = 0; i < res.Length; i++){
res[i] = GetInt(ba, from + (i * stride), stride);
}
return res;
}
public static uint[] GetUintArray(byte[] ba){
uint[] res = new uint[ba.Length / 4];
for(int i = 0; i < res.Length; i++){
res[i] = (uint)GetInt(ba, i * 4, 4);
}
return res;
}
public static double[] GetDoubleArray(byte[] ba){
double[] res = new double[ba.Length / 8];
for(int i = 0; i < res.Length; i++){
res[i] = BitConverter.ToDouble(ba, i * 8);
}
return res;
}
public static byte[] IntToBytes(int val){ return UintToBytes((uint)val); }
public static byte[] UintToBytes(uint val){
byte[] res = new byte[4];
for(int i = 3; i >= 0; i--){
res[i] = (byte)val; val >>= 8;
}
return res;
}
public static byte[] IntArrayToBytes(int[] val){
byte[] res = new byte[val.Length * 4];
for(int i = 0; i < val.Length; i++){
byte[] vb = IntToBytes(val[i]);
res[(i * 4)] = vb[0];
res[(i * 4) + 1] = vb[1];
res[(i * 4) + 2] = vb[2];
res[(i * 4) + 3] = vb[3];
}
return res;
}
public static byte[] UintArrayToBytes(uint[] val){
byte[] res = new byte[val.Length * 4];
for(uint i = 0; i < val.Length; i++){
byte[] vb = IntToBytes((int)val[i]);
res[(i * 4)] = vb[0];
res[(i * 4) + 1] = vb[1];
res[(i * 4) + 2] = vb[2];
res[(i * 4) + 3] = vb[3];
}
return res;
}
public static byte[] DoubleArrayToBytes(double[] val){
byte[] res = new byte[val.Length * 8];
for(int i = 0; i < val.Length; i++){
byte[] vb = BitConverter.GetBytes(val[i]);
for(int ii = 0; ii < 8; ii++) res[(i*8)+ii] = vb[ii];
}
return res;
}
public static byte[] StringArrayToBytes(string[] val, Encoding e){
byte[][] baa = new byte[val.Length][];
int l = 0;
for(int i = 0; i < val.Length; i++){ baa[i] = e.GetBytes(val[i]); l += 4 + baa[i].Length; }
byte[] r = new byte[l + 4];
IntToBytes(val.Length).CopyTo(r, 0);
int ofs = 4;
for(int i = 0; i < baa.Length; i++){
IntToBytes(baa[i].Length).CopyTo(r, ofs); ofs += 4;
baa[i].CopyTo(r, ofs); ofs += baa[i].Length;
}
return r;
}
public static string[] GetStringArray(byte[] ba, Encoding e){
int l = GetInt(ba, 0, 4), ofs = 4;
string[] r = new string[l];
for(int i = 0; i < l; i++){
int thislen = GetInt(ba, ofs, 4); ofs += 4;
r[i] = e.GetString(ba, ofs, thislen); ofs += thislen;
}
return r;
}
public void Close(string reason){ if(!alreadyclosed){ closeReason = reason; Close(); } }
public void Close(){
if(!alreadyclosed){
if(server != null) server.ClientClosed(this);
if(OnClose != null) {
if((threadSyncControl != null) && (threadSyncControl.InvokeRequired))
threadSyncControl.Invoke(OnClose, new object[]{this});
else OnClose(this);
}
alreadyclosed = true;
#if DEBUG
Console.WriteLine("**closed client** at "+DateTime.Now.Ticks);
#endif
}
sock.Close();
}
}
public class Sockets {
// Socks proxy inspired by http://www.thecodeproject.com/csharp/ZaSocks5Proxy.asp
public static SocksProxy SocksProxy;
public static bool UseSocks = false;
public static Socket CreateTCPSocket(String address, int port){return CreateTCPSocket(address, port, UseSocks, SocksProxy);}
public static Socket CreateTCPSocket(String address, int port, bool useSocks, SocksProxy proxy){
Socket sock;
if(useSocks) sock = ConnectToSocksProxy(proxy.host, proxy.port, address, port, proxy.username, proxy.password);
else {
#if NET_1_1
IPAddress host = Dns.GetHostByName(address).AddressList[0];
#else
IPAddress host = Dns.GetHostEntry(address).AddressList[0];
#endif
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(new IPEndPoint(host, port));
}
return sock;
}
private static string[] errorMsgs= {
"Operation completed successfully.",
"General SOCKS server failure.",
"Connection not allowed by ruleset.",
"Network unreachable.",
"Host unreachable.",
"Connection refused.",
"TTL expired.",
"Command not supported.",
"Address type not supported.",
"Unknown error."
};
public static Socket ConnectToSocksProxy(IPAddress proxyIP, int proxyPort, String destAddress, int destPort, string userName, string password){
byte[] request = new byte[257];
byte[] response = new byte[257];
ushort nIndex;
IPAddress destIP = null;
try{ destIP = IPAddress.Parse(destAddress); }
catch { }
IPEndPoint proxyEndPoint = new IPEndPoint(proxyIP, proxyPort);
// open a TCP connection to SOCKS server...
Socket s;
s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
s.Connect(proxyEndPoint);
/* } catch(SocketException){
throw new SocketException(0, "Could not connect to proxy server.");
}*/
nIndex = 0;
request[nIndex++]=0x05; // Version 5.
request[nIndex++]=0x02; // 2 Authentication methods are in packet...
request[nIndex++]=0x00; // NO AUTHENTICATION REQUIRED
request[nIndex++]=0x02; // USERNAME/PASSWORD
// Send the authentication negotiation request...
s.Send(request,nIndex,SocketFlags.None);
// Receive 2 byte response...
int nGot = s.Receive(response,2,SocketFlags.None);
if (nGot!=2)
throw new ConnectionException("Bad response received from proxy server.");
if (response[1]==0xFF)
{ // No authentication method was accepted close the socket.
s.Close();
throw new ConnectionException("None of the authentication method was accepted by proxy server.");
}
byte[] rawBytes;
if (/*response[1]==0x02*/true)
{//Username/Password Authentication protocol
nIndex = 0;
request[nIndex++]=0x05; // Version 5.
// add user name
request[nIndex++]=(byte)userName.Length;
rawBytes = Encoding.Default.GetBytes(userName);
rawBytes.CopyTo(request,nIndex);
nIndex+=(ushort)rawBytes.Length;
// add password
request[nIndex++]=(byte)password.Length;
rawBytes = Encoding.Default.GetBytes(password);
rawBytes.CopyTo(request,nIndex);
nIndex+=(ushort)rawBytes.Length;
// Send the Username/Password request
s.Send(request,nIndex,SocketFlags.None);
// Receive 2 byte response...
nGot = s.Receive(response,2,SocketFlags.None);
if (nGot!=2)
throw new ConnectionException("Bad response received from proxy server.");
if (response[1] != 0x00)
throw new ConnectionException("Bad Usernaem/Password.");
}
// This version only supports connect command.
// UDP and Bind are not supported.
// Send connect request now...
nIndex = 0;
request[nIndex++]=0x05; // version 5.
request[nIndex++]=0x01; // command = connect.
request[nIndex++]=0x00; // Reserve = must be 0x00
if (destIP != null)
{// Destination adress in an IP.
switch(destIP.AddressFamily)
{
case AddressFamily.InterNetwork:
// Address is IPV4 format
request[nIndex++]=0x01;
rawBytes = destIP.GetAddressBytes();
rawBytes.CopyTo(request,nIndex);
nIndex+=(ushort)rawBytes.Length;
break;
case AddressFamily.InterNetworkV6:
// Address is IPV6 format
request[nIndex++]=0x04;
rawBytes = destIP.GetAddressBytes();
rawBytes.CopyTo(request,nIndex);
nIndex+=(ushort)rawBytes.Length;
break;
}
}
else
{// Dest. address is domain name.
request[nIndex++]=0x03; // Address is full-qualified domain name.
request[nIndex++]=Convert.ToByte(destAddress.Length); // length of address.
rawBytes = Encoding.Default.GetBytes(destAddress);
rawBytes.CopyTo(request,nIndex);
nIndex+=(ushort)rawBytes.Length;
}
// using big-edian byte order
byte[] portBytes = BitConverter.GetBytes((ushort)destPort);
for (int i=portBytes.Length-1;i>=0;i--)
request[nIndex++]=portBytes[i];
// send connect request.
s.Send(request,nIndex,SocketFlags.None);
s.Receive(response); // Get variable length response...
if (response[1]!=0x00)
throw new ConnectionException(errorMsgs[response[1]]);
// Success Connected...
return s;
}
}
public struct SocksProxy {
public IPAddress host;
public ushort port;
public string username, password;
public SocksProxy(String hostname, ushort port, String username, String password){
this.port = port;
#if NET_1_1
host = Dns.GetHostByName(hostname).AddressList[0];
#else
host = Dns.GetHostEntry(hostname).AddressList[0];
#endif
this.username = username; this.password = password;
}
}
public class ConnectionException: Exception {
public ConnectionException(string message) : base(message) {}
}
// Server code cribbed from Framework Help
public delegate bool ClientEvent(Server serv, ClientInfo new_client); // whether to accept the client
public class Server {
class ClientState {
// To hold the state information about a client between transactions
internal Socket Socket = null;
internal const int BufferSize = 1024;
internal byte[] buffer = new byte[BufferSize];
internal StringBuilder sofar = new StringBuilder();
internal ClientState(Socket sock){
Socket = sock;
}
}
Hashtable clients = new Hashtable();
Socket ss;
public event ClientEvent Connect, ClientReady;
public IEnumerable Clients {
get { return clients.Values; }
}
public Socket ServerSocket {
get { return ss; }
}
public ClientInfo this[int id]{
get { return (ClientInfo)clients[id]; }
/* foreach(ClientInfo ci in Clients)
if(ci.ID == id) return ci;
return null;
}*/
}
public object SyncRoot { get { return this; } }
private EncryptionType encType;
public EncryptionType DefaultEncryptionType {
get { return encType; }
set { encType = value; }
}
public int Port {
get { return ((IPEndPoint)ss.LocalEndPoint).Port; }
}
public Server(int port) : this(port, null) {}
public Server(int port, ClientEvent connDel) {
Connect = connDel;
ss = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
ss.Bind(new IPEndPoint(IPAddress.Any, port));
ss.Listen(100);
// Start the accept process. When a connection is accepted, the callback
// must do this again to accept another connection
ss.BeginAccept(new AsyncCallback(AcceptCallback), ss);
}
internal void ClientClosed(ClientInfo ci){
lock(SyncRoot) clients.Remove(ci.ID);
}
public void Broadcast(byte[] bytes){
lock(SyncRoot) foreach(ClientInfo ci in Clients) ci.Send(bytes);
}
public void BroadcastMessage(uint code, byte[] bytes){BroadcastMessage(code, bytes, 0); }
public void BroadcastMessage(uint code, byte[] bytes, byte paramType){
lock(SyncRoot) foreach(ClientInfo ci in Clients) ci.SendMessage(code, bytes, paramType);
}
// ASYNC CALLBACK CODE
void AcceptCallback(IAsyncResult ar) {
try{
Socket server = (Socket) ar.AsyncState;
Socket cs = server.EndAccept(ar);
// Start the thing listening again
server.BeginAccept(new AsyncCallback(AcceptCallback), server);
ClientInfo c = new ClientInfo(cs, null, null, ClientDirection.Both, false);
c.server = this;
// Allow the new client to be rejected by the application
if(Connect != null){
if(!Connect(this, c)){
// Rejected
cs.Close();
return;
}
}
// Initiate key exchange
c.EncryptionType = encType;
switch(encType){
case EncryptionType.None: KeyExchangeComplete(c); break;
case EncryptionType.ServerKey:
c.encKey = GetSymmetricKey();
byte[] key = ClientInfo.GetLengthEncodedVector(c.encKey);
cs.Send(key);
#if DEBUG
Console.Write(c.ID + " Sent key: "); ClientInfo.LogBytes(key, key.Length);
#endif
c.MakeEncoders();
KeyExchangeComplete(c);
break;
case EncryptionType.ServerRSAClientKey:
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters p = rsa.ExportParameters(true);
cs.Send(ClientInfo.GetLengthEncodedVector(p.Modulus));
cs.Send(ClientInfo.GetLengthEncodedVector(p.Exponent));
c.encParams = p;
break;
default: throw new ArgumentException("Unknown or unsupported encryption type "+encType);
}
lock(SyncRoot) clients[c.ID] = c;
c.BeginReceive();
} catch(ObjectDisposedException) { }
catch(SocketException) { }
catch(Exception e) { Console.WriteLine(e); }
}
protected virtual byte[] GetSymmetricKey(){
return EncryptionUtils.GetRandomBytes(24, false);
}
internal void KeyExchangeComplete(ClientInfo ci){
// Key exchange is complete on this client. Client ready
// handlers may still force a close of the connection
if(ClientReady != null)
if(!ClientReady(this, ci)) ci.Close("ClientReady callback rejected connection");
}
~Server() { Close(); }
public void Close(){
ArrayList cl2 = new ArrayList();
foreach(ClientInfo c in Clients) cl2.Add(c);
foreach(ClientInfo c in cl2) c.Close("Server shutdown");
ss.Close();
}
}
public class ByteBuilder : MarshalByRefObject {
byte[][] data;
int packsize, used, paraminx = 0;
public int Length {
get {
int len = 0;
for(int i = 0; i < used; i++) len += data[i].Length;
return len;
}
}
public byte this[int i]{
get { return Read(i, 1)[0]; }
}
public ByteBuilder() : this(10) {}
public ByteBuilder(int packsize){
this.packsize = packsize; used = 0;
data = new byte[packsize][];
}
public ByteBuilder(byte[] data) {
packsize = 1;
used = 1;
this.data = new byte[][] { data };
}
public ByteBuilder(byte[] data, int len) : this(data, 0, len) {}
public ByteBuilder(byte[] data, int from, int len) : this(1) {
Add(data, from, len);
}
public void Add(byte[] moredata){ Add(moredata, 0, moredata.Length); }
public void Add(byte[] moredata, int from, int len){
//Console.WriteLine("Getting "+from+" to "+(from+len-1)+" of "+moredata.Length);
if(used < packsize){
data[used] = new byte[len];
for(int j = from; j < from + len; j++)
data[used][j - from] = moredata[j];
used++;
} else {
// Compress the existing items into the first array
byte[] newdata = new byte[Length + len];
int np = 0;
for(int i = 0; i < used; i++)
for(int j = 0; j < data[i].Length; j++)
newdata[np++] = data[i][j];
for(int j = from; j < from + len; j++)
newdata[np++] = moredata[j];
data[0] = newdata;
for(int i = 1; i < used; i++) data[i] = null;
used = 1;
}
}
public byte[] Read(int from, int len){
if(len == 0) return new byte[0];
byte[] res = new byte[len];
int done = 0, start = 0;
for(int i = 0; i < used; i++){
if((start + data[i].Length) <= from){
start += data[i].Length; continue;
}
// Now we're in the data block
for(int j = 0; j < data[i].Length; j++){
if((j + start) < from) continue;
res[done++] = data[i][j];
if(done == len) return res;
}
}
throw new ArgumentException("Datapoints "+from+" and "+(from+len)+" must be less than "+Length);
}
public void Clear(){
used = 0;
for(int i = 0; i < used; i++) data[i] = null;
}
public Parameter GetNextParameter(){ return GetParameter(ref paraminx); }
public void ResetParameterPointer(){ paraminx = 0; }
public Parameter GetParameter(ref int index){
paraminx = index;
Parameter res = new Parameter();
res.Type = Read(index++, 1)[0];
byte[] lenba = Read(index, 4);
index += 4;
int len = ClientInfo.GetInt(lenba, 0, 4);
res.content = Read(index, len);
index += len;
return res;
}
public void AddParameter(Parameter param){ AddParameter(param.content, param.Type); }
public void AddParameter(byte[] content, byte Type){
Add(new byte[]{Type});
Add(ClientInfo.IntToBytes(content.Length));
Add(content);
}
public void AddInt(int i){ AddParameter(ClientInfo.IntToBytes(i), ParameterType.Int); }
public void AddIntArray(int[] ia){ AddParameter(ClientInfo.IntArrayToBytes(ia), ParameterType.Int); }
public void AddString(string s){ AddParameter(Encoding.UTF8.GetBytes(s), ParameterType.String); }
public void AddStringArray(string[] sa){ AddParameter(ClientInfo.StringArrayToBytes(sa, Encoding.UTF8), ParameterType.StringArray); }
public void AddDouble(double i){ AddParameter(BitConverter.GetBytes(i), ParameterType.Double); }
public void AddLong(long i){ AddParameter(BitConverter.GetBytes(i), ParameterType.Long); }
public void AddDoubleArray(double[] ia){ AddParameter(ClientInfo.DoubleArrayToBytes(ia), ParameterType.Double); }
public int GetInt(){ return ClientInfo.GetInt(GetNextParameter().content, 0, 4);}
public int[] GetIntArray(){ return ClientInfo.GetIntArray(GetNextParameter().content);}
public double GetDouble(){ return BitConverter.ToDouble(GetNextParameter().content, 0);}
public double[] GetDoubleArray(){ return ClientInfo.GetDoubleArray(GetNextParameter().content);}
public long GetLong(){ return BitConverter.ToInt64(GetNextParameter().content, 0);}
public string GetString(){ return Encoding.UTF8.GetString(GetNextParameter().content);}
public string[] GetStringArray(){ return ClientInfo.GetStringArray(GetNextParameter().content, Encoding.UTF8);}
public static String FormatParameter(Parameter p){
switch(p.Type){
case ParameterType.Int:
int[] ia = ClientInfo.GetIntArray(p.content);
StringBuilder sb = new StringBuilder();
foreach(int i in ia) sb.Append(i + " ");
return sb.ToString();
case ParameterType.Uint:
ia = ClientInfo.GetIntArray(p.content);
sb = new StringBuilder();
foreach(int i in ia) sb.Append(i.ToString("X8") + " ");
return sb.ToString();
case ParameterType.Double:
double[] da = ClientInfo.GetDoubleArray(p.content);
sb = new StringBuilder();
foreach(double d in da) sb.Append(d + " ");
return sb.ToString();
case ParameterType.String:
return Encoding.UTF8.GetString(p.content);
case ParameterType.StringArray:
string[] sa = ClientInfo.GetStringArray(p.content, Encoding.UTF8);
sb = new StringBuilder();
foreach(string s in sa) sb.Append(s + "; ");
return sb.ToString();
case ParameterType.Byte:
sb = new StringBuilder();
foreach(int b in p.content) sb.Append(b.ToString("X2") + " ");
return sb.ToString();
default: return "??";
}
}
}
[Serializable]
public struct Parameter {
public byte Type;
public byte[] content;
public Parameter(byte[] content, byte type){
this.content = content; Type = type;
}
}
public struct ParameterType {
public const byte Unparameterised = 0;
public const byte Int = 1;
public const byte Uint = 2;
public const byte String = 3;
public const byte Byte = 4;
public const byte StringArray = 5;
public const byte Double = 6;
public const byte Long = 7;
}
}
namespace RedCorona.Cryptography {
// Cryptographic classes
public abstract class BaseCrypto : ICryptoTransform {
public int InputBlockSize { get { return 1; } }
public int OutputBlockSize { get { return 1; } }
public bool CanTransformMultipleBlocks { get { return true; } }
public bool CanReuseTransform { get { return true; } }
protected byte[] key;
protected byte currentKey;
protected int done = 0, keyinx = 0;
protected BaseCrypto(byte[] key){
if(key.Length == 0) throw new ArgumentException("Must provide a key");
this.key = key;
currentKey = 0;
for(int i = 0; i < key.Length; i++) currentKey += key[i];
}
protected abstract byte DoByte(byte b);
public int TransformBlock(byte[] from, int frominx, int len, byte[] to, int toinx){
#if DEBUG
Console.WriteLine("Starting transform, key is "+currentKey);
#endif
for(int i = 0; i < len; i++){
byte oldkey = currentKey;
to[toinx + i] = DoByte(from[frominx + i]);
#if DEBUG
Console.WriteLine(" encrypting "+from[frominx + i]+" to "+to[toinx + i]+", key is "+oldkey);
#endif
BumpKey();
}
return len;
}
public byte[] TransformFinalBlock(byte[] from, int frominx, int len){
byte[] to = new byte[len];
TransformBlock(from, frominx, len, to, 0);
return to;
}
protected void BumpKey(){
keyinx = (keyinx + 1) % key.Length;
currentKey = Multiply257(key[keyinx], currentKey);
}
protected static byte Multiply257(byte a, byte b){
return (byte)((((a + 1) * (b + 1)) % 257) - 1);
}
protected static byte[] complements = {0,128,85,192,102,42,146,224,199,179,186,149,177,201,119,240,120,99,229,89,48,221,189,74,71,88,237,100,194,59,198,248,147,188,234,49,131,114,144,44,162,152,5,110,39,94,174,165,20,35,125,172,96,118,242,178,247,225,60,29,58,227,101,252,86,73,233,222,148,245,180,24,168,65,23,185,246,200,243,150,164,209,95,204,126,2,64,183,25,19,208,175,151,215,45,82,52,138,134,17,27,62,4,214,163,176,244,187,223,249,43,217,115,123,37,112,133,158,53,14,16,157,139,113,219,50,84,254,1,171,205,36,142,116,98,239,241,202,97,122,143,218,132,140,38,212,6,32,68,11,79,92,41,251,193,228,238,121,117,203,173,210,40,104,80,47,236,230,72,191,253,129,51,160,46,91,105,12,55,9,70,232,190,87,231,75,10,107,33,22,182,169,3,154,28,197,226,195,30,8,77,13,137,159,83,130,220,235,90,81,161,216,145,250,103,93,211,111,141,124,206,21,67,108,7,57,196,61,155,18,167,184,181,66,34,207,166,26,156,135,15,136,54,78,106,69,76,56,31,109,213,153,63,170,127,255};
protected static byte Complement257(byte b){ return complements[b]; }
public void Dispose(){} // for IDisposable
}
public class SimpleEncryptor : BaseCrypto {
public SimpleEncryptor(byte[] key) : base(key) {}
protected override byte DoByte(byte b){
byte b2 = Multiply257((byte)(b+currentKey), currentKey);
currentKey = Multiply257((byte)(b+b2), currentKey);
return b2;
}
}
public class SimpleDecryptor : BaseCrypto {
public SimpleDecryptor(byte[] key) : base(key) {}
protected override byte DoByte(byte b){
byte b2 = (byte)(Multiply257(b, Complement257(currentKey)) - currentKey);
currentKey = Multiply257((byte)(b+b2), currentKey);
return b2;
}
}
}
| |
//
// SourceRowRenderer.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2005-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Gdk;
using Pango;
using Hyena.Gui;
using Hyena.Gui.Theming;
using Hyena.Gui.Theatrics;
using Banshee.ServiceStack;
namespace Banshee.Sources.Gui
{
public class SourceRowRenderer : CellRendererText
{
protected SourceRowRenderer (IntPtr raw) : base (raw)
{
}
public static void CellDataHandler (ICellLayout layout, CellRenderer cell, ITreeModel model, TreeIter iter)
{
SourceRowRenderer renderer = cell as SourceRowRenderer;
if (renderer == null) {
return;
}
var type = model.GetValue (iter, (int)SourceModel.Columns.Type);
if (type == null || (SourceModel.EntryType) type != SourceModel.EntryType.Source) {
renderer.Visible = false;
return;
}
Source source = model.GetValue (iter, 0) as Source;
renderer.Source = source;
renderer.Iter = iter;
if (source == null) {
return;
}
renderer.Visible = true;
renderer.Text = source.Name;
renderer.Sensitive = source.CanActivate;
}
private Source source;
public Source Source {
get { return source; }
set { source = value; }
}
private SourceView view;
private Widget parent_widget;
public Widget ParentWidget {
get { return parent_widget; }
set { parent_widget = value; }
}
private TreeIter iter = TreeIter.Zero;
public TreeIter Iter {
get { return iter; }
set { iter = value; }
}
private int row_height = 22;
public int RowHeight {
get { return row_height; }
set { row_height = value; }
}
public SourceRowRenderer ()
{
}
private StateFlags RendererStateToWidgetState (Widget widget, CellRendererState flags)
{
if (!Sensitive) {
return StateFlags.Insensitive;
} else if ((flags & CellRendererState.Selected) == CellRendererState.Selected) {
return widget.HasFocus ? StateFlags.Selected : StateFlags.Active;
} else if ((flags & CellRendererState.Prelit) == CellRendererState.Prelit) {
ComboBox box = parent_widget as ComboBox;
return box != null && box.PopupShown ? StateFlags.Prelight : StateFlags.Normal;
} else if (widget.StateFlags == StateFlags.Insensitive) {
return StateFlags.Insensitive;
} else {
return StateFlags.Normal;
}
}
private int Depth {
get {
return Source.Parent != null ? 1 : 0;
}
}
protected override void OnGetPreferredWidth (Widget widget, out int minimum_width, out int natural_width)
{
if (!(widget is TreeView)) {
minimum_width = natural_width = 200;
} else {
minimum_width = natural_width = 0;
}
}
protected override void OnGetPreferredHeight (Widget widget, out int minimum_height, out int natural_height)
{
int minimum_text_h, natural_text_h;
base.GetPreferredHeight (widget, out minimum_text_h, out natural_text_h);
minimum_height = (int)Math.Max (RowHeight, minimum_text_h);
natural_height = (int)Math.Max (RowHeight, natural_text_h);
}
private int expander_right_x;
public bool InExpander (int x)
{
return x < expander_right_x;
}
protected override void OnRender (Cairo.Context cr, Widget widget, Gdk.Rectangle background_area,
Gdk.Rectangle cell_area, CellRendererState flags)
{
if (source == null || source is SourceManager.GroupSource) {
return;
}
view = widget as SourceView;
bool selected = view != null && view.Selection.IterIsSelected (iter);
StateFlags state = RendererStateToWidgetState (widget, flags);
RenderBackground (cr, background_area, selected, state);
int title_layout_width = 0, title_layout_height = 0;
int count_layout_width = 0, count_layout_height = 0;
int max_title_layout_width;
int img_padding = 6;
int expander_icon_spacing = 3;
int x = cell_area.X;
bool np_etc = (source.Order + Depth * 100) < 40;
if (!np_etc) {
x += Depth * img_padding + (int)Xpad;
} else {
// Don't indent NowPlaying and Play Queue as much
x += Math.Max (0, (int)Xpad - 2);
}
// Draw the expander if the source has children
double exp_h = (cell_area.Height - 2.0*Ypad) / 2.0;
double exp_w = exp_h * 1.6;
int y = Middle (cell_area, (int)exp_h);
if (view != null && source.Children != null && source.Children.Count > 0) {
var r = new Gdk.Rectangle (x, y, (int)exp_w, (int)exp_h);
view.Theme.DrawArrow (cr, r, source.Expanded ? Math.PI/2.0 : 0.0);
}
if (!np_etc) {
x += (int) exp_w;
x += 2; // a little spacing after the expander
expander_right_x = x;
}
// Draw icon
Pixbuf icon = SourceIconResolver.ResolveIcon (source, RowHeight);
bool dispose_icon = false;
if (state == StateFlags.Insensitive) {
// Code ported from gtk_cell_renderer_pixbuf_render()
var icon_source = new IconSource () {
Pixbuf = icon,
Size = IconSize.SmallToolbar,
SizeWildcarded = false
};
icon = widget.StyleContext.RenderIconPixbuf (icon_source, (IconSize)(-1));
dispose_icon = true;
icon_source.Dispose ();
}
if (icon != null) {
x += expander_icon_spacing;
cr.Save ();
Gdk.CairoHelper.SetSourcePixbuf (cr, icon, x, Middle (cell_area, icon.Height));
cr.Paint ();
cr.Restore ();
x += icon.Width;
if (dispose_icon) {
icon.Dispose ();
}
}
// Setup font info for the title/count, and see if we should show the count
bool hide_count = source.EnabledCount <= 0 || source.Properties.Get<bool> ("SourceView.HideCount");
FontDescription fd = widget.PangoContext.FontDescription.Copy ();
fd.Weight = (ISource)ServiceManager.PlaybackController.NextSource == (ISource)source
? Pango.Weight.Bold
: Pango.Weight.Normal;
if (view != null && source == view.NewPlaylistSource) {
fd.Style = Pango.Style.Italic;
hide_count = true;
}
Pango.Layout title_layout = new Pango.Layout (widget.PangoContext);
Pango.Layout count_layout = null;
// If we have a count to draw, setup its fonts and see how wide it is to see if we have room
if (!hide_count) {
count_layout = new Pango.Layout (widget.PangoContext);
count_layout.FontDescription = fd;
count_layout.SetMarkup (String.Format ("<span size=\"small\">{0}</span>", source.EnabledCount));
count_layout.GetPixelSize (out count_layout_width, out count_layout_height);
}
// Hide the count if the title has no space
max_title_layout_width = cell_area.Width - x - count_layout_width;//(icon == null ? 0 : icon.Width) - count_layout_width - 10;
if (!hide_count && max_title_layout_width <= 0) {
hide_count = true;
}
// Draw the source Name
title_layout.FontDescription = fd;
title_layout.Width = (int)(max_title_layout_width * Pango.Scale.PangoScale);
title_layout.Ellipsize = EllipsizeMode.End;
title_layout.SetText (source.Name);
title_layout.GetPixelSize (out title_layout_width, out title_layout_height);
x += img_padding;
widget.StyleContext.RenderLayout (cr, x, Middle (cell_area, title_layout_height), title_layout);
title_layout.Dispose ();
// Draw the count
if (!hide_count) {
if (view != null) {
cr.SetSourceColor (state == StateFlags.Normal || (view != null && state == StateFlags.Prelight)
? view.Theme.TextMidColor
: CairoExtensions.GdkRGBAToCairoColor (view.Theme.Widget.StyleContext.GetColor (state)));
cr.MoveTo (
cell_area.X + cell_area.Width - count_layout_width - 2,
cell_area.Y + 0.5 + (double)(cell_area.Height - count_layout_height) / 2.0);
Pango.CairoHelper.ShowLayout (cr, count_layout);
}
count_layout.Dispose ();
}
fd.Dispose ();
}
private void RenderBackground (Cairo.Context cr, Gdk.Rectangle background_area,
bool selected, StateFlags state)
{
if (view == null) {
return;
}
if (selected) {
// Just leave the standard GTK selection and focus
return;
}
if (!TreeIter.Zero.Equals (iter) && iter.Equals (view.HighlightedIter)) {
// Item is highlighted but not selected
view.Theme.DrawHighlightFrame (cr, background_area.X + 1, background_area.Y + 1,
background_area.Width - 2, background_area.Height - 2);
} else if (view.NotifyStage.ActorCount > 0) {
if (!TreeIter.Zero.Equals (iter) && view.NotifyStage.Contains (iter)) {
// Render the current step of the notification animation
Actor<TreeIter> actor = view.NotifyStage[iter];
Cairo.Color normal_color = CairoExtensions.GdkRGBAToCairoColor (view.StyleContext.GetBackgroundColor (StateFlags.Normal));
Cairo.Color selected_color = CairoExtensions.GdkRGBAToCairoColor (view.StyleContext.GetBackgroundColor (StateFlags.Selected));
Cairo.Color notify_bg_color = CairoExtensions.AlphaBlend (normal_color, selected_color, 0.5);
notify_bg_color.A = Math.Sin (actor.Percent * Math.PI);
cr.SetSourceColor (notify_bg_color);
CairoExtensions.RoundedRectangle (cr, background_area.X, background_area.Y, background_area.Width, background_area.Height, view.Theme.Context.Radius);
cr.Fill ();
}
}
}
private int Middle (Gdk.Rectangle area, int height)
{
return area.Y + (int)Math.Round ((double)(area.Height - height) / 2.0, MidpointRounding.AwayFromZero);
}
protected override ICellEditable OnStartEditing (Gdk.Event evnt, Widget widget, string path,
Gdk.Rectangle background_area, Gdk.Rectangle cell_area, CellRendererState flags)
{
CellEditEntry text = new CellEditEntry ();
text.EditingDone += OnEditDone;
text.Text = source.Name;
text.path = path;
text.Show ();
view.EditingRow = true;
return text;
}
private void OnEditDone (object o, EventArgs args)
{
CellEditEntry edit = (CellEditEntry)o;
if (view == null) {
return;
}
view.EditingRow = false;
using (var tree_path = new TreePath (edit.path)) {
view.UpdateRow (tree_path, edit.Text);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Redis.Fluent
{
using Microsoft.Azure.Management.Redis.Fluent.Models;
using Microsoft.Azure.Management.Redis.Fluent.RedisCache.Definition;
using Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
internal partial class RedisCacheImpl
{
/// <summary>
/// Gets Firewall Rules in the Redis Cache, indexed by name.
/// </summary>
System.Collections.Generic.IReadOnlyDictionary<string,Models.IRedisFirewallRule> Microsoft.Azure.Management.Redis.Fluent.IRedisCacheBeta.FirewallRules
{
get
{
return this.FirewallRules();
}
}
/// <summary>
/// Gets the hostName value.
/// </summary>
string Microsoft.Azure.Management.Redis.Fluent.IRedisCache.HostName
{
get
{
return this.HostName();
}
}
/// <summary>
/// Gets returns true if current Redis Cache instance has Premium Sku.
/// </summary>
bool Microsoft.Azure.Management.Redis.Fluent.IRedisCache.IsPremium
{
get
{
return this.IsPremium();
}
}
/// <summary>
/// Gets a Redis Cache's access keys. This operation requires write permission to the Cache resource.
/// </summary>
Microsoft.Azure.Management.Redis.Fluent.IRedisAccessKeys Microsoft.Azure.Management.Redis.Fluent.IRedisCache.Keys
{
get
{
return this.Keys();
}
}
/// <summary>
/// Gets the minimum TLS version (or higher) that clients require to use.
/// </summary>
Models.TlsVersion Microsoft.Azure.Management.Redis.Fluent.IRedisCacheBeta.MinimumTlsVersion
{
get
{
return this.MinimumTlsVersion();
}
}
/// <summary>
/// Gets true if non SSL port is enabled, false otherwise.
/// </summary>
bool Microsoft.Azure.Management.Redis.Fluent.IRedisCache.NonSslPort
{
get
{
return this.NonSslPort();
}
}
/// <summary>
/// Gets List of patch schedules for current Redis Cache.
/// </summary>
System.Collections.Generic.IReadOnlyList<Models.ScheduleEntry> Microsoft.Azure.Management.Redis.Fluent.IRedisCacheBeta.PatchSchedules
{
get
{
return this.PatchSchedules();
}
}
/// <summary>
/// Gets the port value.
/// </summary>
int Microsoft.Azure.Management.Redis.Fluent.IRedisCache.Port
{
get
{
return this.Port();
}
}
/// <summary>
/// Gets the provisioningState value.
/// </summary>
string Microsoft.Azure.Management.Redis.Fluent.IRedisCache.ProvisioningState
{
get
{
return this.ProvisioningState();
}
}
/// <summary>
/// Gets the Redis configuration value.
/// </summary>
System.Collections.Generic.IReadOnlyDictionary<string,string> Microsoft.Azure.Management.Redis.Fluent.IRedisCache.RedisConfiguration
{
get
{
return this.RedisConfiguration();
}
}
/// <summary>
/// Gets the Redis version value.
/// </summary>
string Microsoft.Azure.Management.Redis.Fluent.IRedisCache.RedisVersion
{
get
{
return this.RedisVersion();
}
}
/// <summary>
/// Gets the shardCount value.
/// </summary>
int Microsoft.Azure.Management.Redis.Fluent.IRedisCache.ShardCount
{
get
{
return this.ShardCount();
}
}
/// <summary>
/// Gets the sku value.
/// </summary>
Models.Sku Microsoft.Azure.Management.Redis.Fluent.IRedisCache.Sku
{
get
{
return this.Sku();
}
}
/// <summary>
/// Gets the sslPort value.
/// </summary>
int Microsoft.Azure.Management.Redis.Fluent.IRedisCache.SslPort
{
get
{
return this.SslPort();
}
}
/// <summary>
/// Gets the staticIP value.
/// </summary>
string Microsoft.Azure.Management.Redis.Fluent.IRedisCache.StaticIP
{
get
{
return this.StaticIP();
}
}
/// <summary>
/// Gets the subnetId value.
/// </summary>
string Microsoft.Azure.Management.Redis.Fluent.IRedisCache.SubnetId
{
get
{
return this.SubnetId();
}
}
/// <summary>
/// Adds a linked server to the current Redis cache instance.
/// </summary>
/// <param name="linkedRedisCacheId">The resource Id of the Redis instance to link with.</param>
/// <param name="linkedServerLocation">The location of the linked Redis instance.</param>
/// <param name="role">The role of the linked server.</param>
/// <return>Name of the linked server.</return>
string Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremiumBeta.AddLinkedServer(string linkedRedisCacheId, string linkedServerLocation, ReplicationRole role)
{
return this.AddLinkedServer(linkedRedisCacheId, linkedServerLocation, role);
}
/// <summary>
/// Adds a linked server to the current Redis cache instance.
/// </summary>
/// <param name="linkedRedisCacheId">The resource Id of the Redis instance to link with.</param>
/// <param name="linkedServerLocation">The location of the linked Redis instance.</param>
/// <param name="role">The role of the linked server.</param>
/// <return>Name of the linked server.</return>
async Task<string> Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremiumBeta.AddLinkedServerAsync(string linkedRedisCacheId, string linkedServerLocation, ReplicationRole role, CancellationToken cancellationToken)
{
return await this.AddLinkedServerAsync(linkedRedisCacheId, linkedServerLocation, role, cancellationToken);
}
/// <return>Exposes features available only to Premium Sku Redis Cache instances.</return>
Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremium Microsoft.Azure.Management.Redis.Fluent.IRedisCache.AsPremium()
{
return this.AsPremium();
}
/// <summary>
/// Deletes the patching schedule for Redis Cache.
/// </summary>
void Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremium.DeletePatchSchedule()
{
this.DeletePatchSchedule();
}
/// <summary>
/// Export data from Redis Cache.
/// </summary>
/// <param name="containerSASUrl">Container name to export to.</param>
/// <param name="prefix">Prefix to use for exported files.</param>
void Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremium.ExportData(string containerSASUrl, string prefix)
{
this.ExportData(containerSASUrl, prefix);
}
/// <summary>
/// Export data from Redis Cache.
/// </summary>
/// <param name="containerSASUrl">Container name to export to.</param>
/// <param name="prefix">Prefix to use for exported files.</param>
/// <param name="fileFormat">Specifies file format.</param>
void Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremium.ExportData(string containerSASUrl, string prefix, string fileFormat)
{
this.ExportData(containerSASUrl, prefix, fileFormat);
}
/// <summary>
/// Reboot specified Redis node(s). This operation requires write permission to the cache resource. There can be potential data loss.
/// </summary>
/// <param name="rebootType">
/// Specifies which Redis node(s) to reboot. Depending on this value data loss is
/// possible. Possible values include: 'PrimaryNode', 'SecondaryNode', 'AllNodes'.
/// </param>
void Microsoft.Azure.Management.Redis.Fluent.IRedisCache.ForceReboot(string rebootType)
{
this.ForceReboot(rebootType);
}
/// <summary>
/// Reboot specified Redis node(s). This operation requires write permission to the cache resource. There can be potential data loss.
/// </summary>
/// <param name="rebootType">
/// Specifies which Redis node(s) to reboot. Depending on this value data loss is
/// possible. Possible values include: 'PrimaryNode', 'SecondaryNode', 'AllNodes'.
/// </param>
/// <param name="shardId">In case of cluster cache, this specifies shard id which should be rebooted.</param>
void Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremium.ForceReboot(string rebootType, int shardId)
{
this.ForceReboot(rebootType, shardId);
}
/// <return>A Redis Cache's access keys. This operation requires write permission to the Cache resource.</return>
Microsoft.Azure.Management.Redis.Fluent.IRedisAccessKeys Microsoft.Azure.Management.Redis.Fluent.IRedisCache.GetKeys()
{
return this.GetKeys();
}
/// <summary>
/// Gets the role for the linked server of the current Redis cache instance.
/// </summary>
/// <param name="linkedServerName">The name of the linked server.</param>
/// <return>The role of the linked server.</return>
Models.ReplicationRole Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremiumBeta.GetLinkedServerRole(string linkedServerName)
{
return this.GetLinkedServerRole(linkedServerName);
}
/// <summary>
/// Gets the role for the linked server of the current Redis cache instance.
/// </summary>
/// <param name="linkedServerName">The name of the linked server.</param>
/// <return>The role of the linked server.</return>
async Task<Models.ReplicationRole> Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremiumBeta.GetLinkedServerRoleAsync(string linkedServerName, CancellationToken cancellationToken)
{
return await this.GetLinkedServerRoleAsync(linkedServerName, cancellationToken);
}
/// <summary>
/// Import data into Redis Cache.
/// </summary>
/// <param name="files">Files to import.</param>
void Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremium.ImportData(IList<string> files)
{
this.ImportData(files);
}
/// <summary>
/// Import data into Redis Cache.
/// </summary>
/// <param name="files">Files to import.</param>
/// <param name="fileFormat">Specifies file format.</param>
void Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremium.ImportData(IList<string> files, string fileFormat)
{
this.ImportData(files, fileFormat);
}
/// <summary>
/// Gets the list of linked servers associated with this redis cache.
/// </summary>
/// <return>The Roles of the linked servers, indexed by name.</return>
System.Collections.Generic.IReadOnlyDictionary<string,Models.ReplicationRole> Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremiumBeta.ListLinkedServers()
{
return this.ListLinkedServers();
}
/// <summary>
/// Gets the list of linked servers associated with this redis cache.
/// </summary>
/// <return>The Roles of the linked servers, indexed by name.</return>
async Task<System.Collections.Generic.IReadOnlyDictionary<string, Models.ReplicationRole>> Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremiumBeta.ListLinkedServersAsync(CancellationToken cancellationToken)
{
return await this.ListLinkedServersAsync(cancellationToken);
}
/// <summary>
/// Gets the patching schedule for Redis Cache.
/// </summary>
/// <return>List of patch schedules for current Redis Cache.</return>
System.Collections.Generic.IReadOnlyList<Models.ScheduleEntry> Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremium.ListPatchSchedules()
{
return this.ListPatchSchedules();
}
/// <summary>
/// Refreshes the resource to sync with Azure.
/// </summary>
/// <return>The Observable to refreshed resource.</return>
async Task<Microsoft.Azure.Management.Redis.Fluent.IRedisCache> Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IRefreshable<Microsoft.Azure.Management.Redis.Fluent.IRedisCache>.RefreshAsync(CancellationToken cancellationToken)
{
return await this.RefreshAsync(cancellationToken);
}
/// <summary>
/// Fetch the up-to-date access keys from Azure for this Redis Cache.
/// </summary>
/// <return>The access keys for this Redis Cache.</return>
Microsoft.Azure.Management.Redis.Fluent.IRedisAccessKeys Microsoft.Azure.Management.Redis.Fluent.IRedisCache.RefreshKeys()
{
return this.RefreshKeys();
}
/// <summary>
/// Regenerates the access keys for this Redis Cache.
/// </summary>
/// <param name="keyType">Key type to regenerate.</param>
/// <return>The generated access keys for this Redis Cache.</return>
Microsoft.Azure.Management.Redis.Fluent.IRedisAccessKeys Microsoft.Azure.Management.Redis.Fluent.IRedisCache.RegenerateKey(RedisKeyType keyType)
{
return this.RegenerateKey(keyType);
}
/// <summary>
/// Removes the linked server from the current Redis cache instance.
/// </summary>
/// <param name="linkedServerName">The name of the linked server.</param>
void Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremiumBeta.RemoveLinkedServer(string linkedServerName)
{
this.RemoveLinkedServer(linkedServerName);
}
/// <summary>
/// Removes the linked server from the current Redis cache instance.
/// </summary>
/// <param name="linkedServerName">The name of the linked server.</param>
async Task Microsoft.Azure.Management.Redis.Fluent.IRedisCachePremiumBeta.RemoveLinkedServerAsync(string linkedServerName, CancellationToken cancellationToken)
{
await this.RemoveLinkedServerAsync(linkedServerName, cancellationToken);
}
/// <summary>
/// Begins an update for a new resource.
/// This is the beginning of the builder pattern used to update top level resources
/// in Azure. The final method completing the definition and starting the actual resource creation
/// process in Azure is Appliable.apply().
/// </summary>
/// <return>The stage of new resource update.</return>
RedisCache.Update.IUpdate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IUpdatable<RedisCache.Update.IUpdate>.Update()
{
return this.Update();
}
/// <summary>
/// Updates Redis Cache to Basic sku with new capacity.
/// </summary>
/// <param name="capacity">Specifies what size of Redis Cache to update to for Basic sku with C family (0, 1, 2, 3, 4, 5, 6).</param>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IWithSku.WithBasicSku(int capacity)
{
return this.WithBasicSku(capacity);
}
/// <summary>
/// Specifies the Basic sku of the Redis Cache.
/// </summary>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithSku.WithBasicSku()
{
return this.WithBasicSku();
}
/// <summary>
/// Specifies the Basic sku of the Redis Cache.
/// </summary>
/// <param name="capacity">Specifies what size of Redis Cache to deploy for Basic sku with C family (0, 1, 2, 3, 4, 5, 6).</param>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithSku.WithBasicSku(int capacity)
{
return this.WithBasicSku(capacity);
}
/// <summary>
/// Creates Redis cache firewall rule with range of IP addresses permitted to connect to the cache.
/// </summary>
/// <param name="name">Name of the rule.</param>
/// <param name="lowestIp">Lowest IP address included in the range.</param>
/// <param name="highestIp">Highest IP address included in the range.</param>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithCreateBeta.WithFirewallRule(string name, string lowestIp, string highestIp)
{
return this.WithFirewallRule(name, lowestIp, highestIp);
}
/// <summary>
/// Creates Redis cache firewall rule with range of IP addresses permitted to connect to the cache.
/// </summary>
/// <param name="rule">Firewall rule that specifies name, lowest and highest IP address included in the range of permitted IP addresses.</param>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithCreateBeta.WithFirewallRule(IRedisFirewallRule rule)
{
return this.WithFirewallRule(rule);
}
/// <summary>
/// Creates or updates Redis cache firewall rule with range of IP addresses permitted to connect to the cache.
/// </summary>
/// <param name="name">Name of the rule.</param>
/// <param name="lowestIp">Lowest IP address included in the range.</param>
/// <param name="highestIp">Highest IP address included in the range.</param>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IUpdateBeta.WithFirewallRule(string name, string lowestIp, string highestIp)
{
return this.WithFirewallRule(name, lowestIp, highestIp);
}
/// <summary>
/// Creates or updates Redis cache firewall rule with range of IP addresses permitted to connect to the cache.
/// </summary>
/// <param name="rule">Firewall rule that specifies name, lowest and highest IP address included in the range of permitted IP addresses.</param>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IUpdateBeta.WithFirewallRule(IRedisFirewallRule rule)
{
return this.WithFirewallRule(rule);
}
/// <summary>
/// Requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0', '1.1', '1.2').
/// </summary>
/// <param name="tlsVersion">Minimum TLS version.</param>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithCreateBeta.WithMinimumTlsVersion(TlsVersion tlsVersion)
{
return this.WithMinimumTlsVersion(tlsVersion);
}
/// <summary>
/// Requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0', '1.1', '1.2').
/// </summary>
/// <param name="tlsVersion">Minimum TLS version.</param>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Update.IUpdate RedisCache.Update.IUpdateBeta.WithMinimumTlsVersion(TlsVersion tlsVersion)
{
return this.WithMinimumTlsVersion(tlsVersion);
}
/// <summary>
/// Enables non-ssl Redis server port (6379).
/// </summary>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithCreate.WithNonSslPort()
{
return this.WithNonSslPort();
}
/// <summary>
/// Enables non-ssl Redis server port (6379).
/// </summary>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IWithNonSslPort.WithNonSslPort()
{
return this.WithNonSslPort();
}
/// <summary>
/// Deletes a single firewall rule in the current Redis cache instance.
/// </summary>
/// <param name="name">Name of the rule.</param>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IUpdateBeta.WithoutFirewallRule(string name)
{
return this.WithoutFirewallRule(name);
}
/// <summary>
/// Removes the requirement for clients minimum TLS version.
/// </summary>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Update.IUpdate RedisCache.Update.IUpdateBeta.WithoutMinimumTlsVersion()
{
return this.WithoutMinimumTlsVersion();
}
/// <summary>
/// Disables non-ssl Redis server port (6379).
/// </summary>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IWithNonSslPort.WithoutNonSslPort()
{
return this.WithoutNonSslPort();
}
/// <summary>
/// Removes all Patch schedules from the current Premium Cluster Cache.
/// </summary>
/// <return>The next stage of Redis Cache with Premium SKU definition.</return>
RedisCache.Update.IUpdate RedisCache.Update.IUpdateBeta.WithoutPatchSchedule()
{
return this.WithoutPatchSchedule();
}
/// <summary>
/// Cleans all the configuration settings being set on Redis Cache.
/// </summary>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IWithRedisConfiguration.WithoutRedisConfiguration()
{
return this.WithoutRedisConfiguration();
}
/// <summary>
/// Removes specified Redis Cache configuration setting.
/// </summary>
/// <param name="key">Redis configuration name.</param>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IWithRedisConfiguration.WithoutRedisConfiguration(string key)
{
return this.WithoutRedisConfiguration(key);
}
/// <summary>
/// Patch schedule on a Premium Cluster Cache.
/// </summary>
/// <param name="dayOfWeek">Day of week when cache can be patched.</param>
/// <param name="startHourUtc">Start hour after which cache patching can start.</param>
/// <return>The next stage of Redis Cache with Premium SKU definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithCreate.WithPatchSchedule(Models.DayOfWeek dayOfWeek, int startHourUtc)
{
return this.WithPatchSchedule(dayOfWeek, startHourUtc);
}
/// <summary>
/// Patch schedule on a Premium Cluster Cache.
/// </summary>
/// <param name="dayOfWeek">Day of week when cache can be patched.</param>
/// <param name="startHourUtc">Start hour after which cache patching can start.</param>
/// <param name="maintenanceWindow">ISO8601 timespan specifying how much time cache patching can take.</param>
/// <return>The next stage of Redis Cache with Premium SKU definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithCreate.WithPatchSchedule(Models.DayOfWeek dayOfWeek, int startHourUtc, TimeSpan maintenanceWindow)
{
return this.WithPatchSchedule(dayOfWeek, startHourUtc, maintenanceWindow);
}
/// <summary>
/// Patch schedule on a Premium Cluster Cache.
/// </summary>
/// <param name="scheduleEntry">List of patch schedule entries for Premium Redis Cache.</param>
/// <return>The next stage of Redis Cache with Premium SKU definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithCreate.WithPatchSchedule(IList<Models.ScheduleEntry> scheduleEntry)
{
return this.WithPatchSchedule(scheduleEntry);
}
/// <summary>
/// Patch schedule on a Premium Cluster Cache.
/// </summary>
/// <param name="scheduleEntry">Patch schedule entry for Premium Redis Cache.</param>
/// <return>The next stage of Redis Cache with Premium SKU definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithCreate.WithPatchSchedule(ScheduleEntry scheduleEntry)
{
return this.WithPatchSchedule(scheduleEntry);
}
/// <summary>
/// Adds Patch schedule to the current Premium Cluster Cache.
/// </summary>
/// <param name="dayOfWeek">Day of week when cache can be patched.</param>
/// <param name="startHourUtc">Start hour after which cache patching can start.</param>
/// <return>The next stage of Redis Cache with Premium SKU definition.</return>
RedisCache.Update.IUpdate RedisCache.Update.IUpdate.WithPatchSchedule(Models.DayOfWeek dayOfWeek, int startHourUtc)
{
return this.WithPatchSchedule(dayOfWeek, startHourUtc);
}
/// <summary>
/// Adds Patch schedule to the current Premium Cluster Cache.
/// </summary>
/// <param name="dayOfWeek">Day of week when cache can be patched.</param>
/// <param name="startHourUtc">Start hour after which cache patching can start.</param>
/// <param name="maintenanceWindow">ISO8601 timespan specifying how much time cache patching can take.</param>
/// <return>The next stage of Redis Cache with Premium SKU definition.</return>
RedisCache.Update.IUpdate RedisCache.Update.IUpdate.WithPatchSchedule(Models.DayOfWeek dayOfWeek, int startHourUtc, TimeSpan maintenanceWindow)
{
return this.WithPatchSchedule(dayOfWeek, startHourUtc, maintenanceWindow);
}
/// <summary>
/// Adds Patch schedule to the current Premium Cluster Cache.
/// </summary>
/// <param name="scheduleEntry">List of patch schedule entries for Premium Redis Cache.</param>
/// <return>The next stage of Redis Cache with Premium SKU definition.</return>
RedisCache.Update.IUpdate RedisCache.Update.IUpdate.WithPatchSchedule(IList<Models.ScheduleEntry> scheduleEntry)
{
return this.WithPatchSchedule(scheduleEntry);
}
/// <summary>
/// Adds Patch schedule to the current Premium Cluster Cache.
/// </summary>
/// <param name="scheduleEntry">Patch schedule entry for Premium Redis Cache.</param>
/// <return>The next stage of Redis Cache with Premium SKU definition.</return>
RedisCache.Update.IUpdate RedisCache.Update.IUpdate.WithPatchSchedule(ScheduleEntry scheduleEntry)
{
return this.WithPatchSchedule(scheduleEntry);
}
/// <summary>
/// Updates Redis Cache to Premium sku.
/// </summary>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IWithSku.WithPremiumSku()
{
return this.WithPremiumSku();
}
/// <summary>
/// Updates Redis Cache to Premium sku with new capacity.
/// </summary>
/// <param name="capacity">Specifies what size of Redis Cache to update to for Premium sku with P family (1, 2, 3, 4).</param>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IWithSku.WithPremiumSku(int capacity)
{
return this.WithPremiumSku(capacity);
}
/// <summary>
/// Specifies the Premium sku of the Redis Cache.
/// </summary>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithPremiumSkuCreate RedisCache.Definition.IWithSku.WithPremiumSku()
{
return this.WithPremiumSku();
}
/// <summary>
/// Specifies the Premium sku of the Redis Cache.
/// </summary>
/// <param name="capacity">Specifies what size of Redis Cache to deploy for Standard sku with P family (1, 2, 3, 4).</param>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithPremiumSkuCreate RedisCache.Definition.IWithSku.WithPremiumSku(int capacity)
{
return this.WithPremiumSku(capacity);
}
/// <summary>
/// All Redis Settings. Few possible keys:
/// rdb-backup-enabled, rdb-storage-connection-string, rdb-backup-frequency, maxmemory-delta, maxmemory-policy,
/// notify-keyspace-events, maxmemory-samples, slowlog-log-slower-than, slowlog-max-len, list-max-ziplist-entries,
/// list-max-ziplist-value, hash-max-ziplist-entries, hash-max-ziplist-value, set -max-intset-entries,
/// zset-max-ziplist-entries, zset-max-ziplist-value etc.
/// </summary>
/// <param name="redisConfiguration">Configuration of Redis Cache as a map indexed by configuration name.</param>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithCreate.WithRedisConfiguration(IDictionary<string,string> redisConfiguration)
{
return this.WithRedisConfiguration(redisConfiguration);
}
/// <summary>
/// Specifies Redis Setting.
/// rdb-backup-enabled, rdb-storage-connection-string, rdb-backup-frequency, maxmemory-delta, maxmemory-policy,
/// notify-keyspace-events, maxmemory-samples, slowlog-log-slower-than, slowlog-max-len, list-max-ziplist-entries,
/// list-max-ziplist-value, hash-max-ziplist-entries, hash-max-ziplist-value, set -max-intset-entries,
/// zset-max-ziplist-entries, zset-max-ziplist-value etc.
/// </summary>
/// <param name="key">Redis configuration name.</param>
/// <param name="value">Redis configuration value.</param>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithCreate.WithRedisConfiguration(string key, string value)
{
return this.WithRedisConfiguration(key, value);
}
/// <summary>
/// All Redis Settings. Few possible keys:
/// rdb-backup-enabled, rdb-storage-connection-string, rdb-backup-frequency, maxmemory-delta, maxmemory-policy,
/// notify-keyspace-events, maxmemory-samples, slowlog-log-slower-than, slowlog-max-len, list-max-ziplist-entries,
/// list-max-ziplist-value, hash-max-ziplist-entries, hash-max-ziplist-value, set -max-intset-entries,
/// zset-max-ziplist-entries, zset-max-ziplist-value etc.
/// </summary>
/// <param name="redisConfiguration">Configuration of Redis Cache as a map indexed by configuration name.</param>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IWithRedisConfiguration.WithRedisConfiguration(IDictionary<string,string> redisConfiguration)
{
return this.WithRedisConfiguration(redisConfiguration);
}
/// <summary>
/// Specifies Redis Setting.
/// rdb-backup-enabled, rdb-storage-connection-string, rdb-backup-frequency, maxmemory-delta, maxmemory-policy,
/// notify-keyspace-events, maxmemory-samples, slowlog-log-slower-than, slowlog-max-len, list-max-ziplist-entries,
/// list-max-ziplist-value, hash-max-ziplist-entries, hash-max-ziplist-value, set -max-intset-entries,
/// zset-max-ziplist-entries, zset-max-ziplist-value etc.
/// </summary>
/// <param name="key">Redis configuration name.</param>
/// <param name="value">Redis configuration value.</param>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IWithRedisConfiguration.WithRedisConfiguration(string key, string value)
{
return this.WithRedisConfiguration(key, value);
}
/// <summary>
/// The number of shards to be created on a Premium Cluster Cache.
/// </summary>
/// <param name="shardCount">The shard count value to set.</param>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IUpdate.WithShardCount(int shardCount)
{
return this.WithShardCount(shardCount);
}
/// <summary>
/// The number of shards to be created on a Premium Cluster Cache.
/// </summary>
/// <param name="shardCount">The shard count value to set.</param>
/// <return>The next stage of Redis Cache with Premium SKU definition.</return>
RedisCache.Definition.IWithPremiumSkuCreate RedisCache.Definition.IWithPremiumSkuCreate.WithShardCount(int shardCount)
{
return this.WithShardCount(shardCount);
}
/// <summary>
/// Updates Redis Cache to Standard sku.
/// </summary>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IWithSku.WithStandardSku()
{
return this.WithStandardSku();
}
/// <summary>
/// Updates Redis Cache to Standard sku with new capacity.
/// </summary>
/// <param name="capacity">Specifies what size of Redis Cache to update to for Standard sku with C family (0, 1, 2, 3, 4, 5, 6).</param>
/// <return>The next stage of Redis Cache update.</return>
RedisCache.Update.IUpdate RedisCache.Update.IWithSku.WithStandardSku(int capacity)
{
return this.WithStandardSku(capacity);
}
/// <summary>
/// Specifies the Standard Sku of the Redis Cache.
/// </summary>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithSku.WithStandardSku()
{
return this.WithStandardSku();
}
/// <summary>
/// Specifies the Standard sku of the Redis Cache.
/// </summary>
/// <param name="capacity">Specifies what size of Redis Cache to deploy for Standard sku with C family (0, 1, 2, 3, 4, 5, 6).</param>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithSku.WithStandardSku(int capacity)
{
return this.WithStandardSku(capacity);
}
/// <summary>
/// Sets Redis Cache static IP. Required when deploying a Redis Cache inside an existing Azure Virtual Network.
/// </summary>
/// <param name="staticIP">The static IP value to set.</param>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithPremiumSkuCreateBeta.WithStaticIP(string staticIP)
{
return this.WithStaticIP(staticIP);
}
/// <summary>
/// Assigns the specified subnet to this instance of Redis Cache.
/// </summary>
/// <param name="network">Instance of Network object.</param>
/// <param name="subnetName">The name of the subnet.</param>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithPremiumSkuCreateBeta.WithSubnet(IHasId network, string subnetName)
{
return this.WithSubnet(network, subnetName);
}
/// <summary>
/// Assigns the specified subnet to this instance of Redis Cache.
/// </summary>
/// <param name="subnetId">Resource id of subnet.</param>
/// <return>The next stage of Redis Cache definition.</return>
RedisCache.Definition.IWithCreate RedisCache.Definition.IWithPremiumSkuCreateBeta.WithSubnet(string subnetId)
{
return this.WithSubnet(subnetId);
}
}
}
| |
/* ====================================================================
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 TestCases.SS.Formula
{
using System;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.PTG;
using NPOI.SS.UserModel;
using NUnit.Framework;
using TestCases.HSSF;
/**
* Tests {@link WorkbookEvaluator}.
*
* @author Josh Micich
*/
[TestFixture]
public class TestWorkbookEvaluator
{
private static readonly double EPSILON = 0.0000001;
private static ValueEval EvaluateFormula(Ptg[] ptgs)
{
OperationEvaluationContext ec = new OperationEvaluationContext(null, null, 0, 0, 0, null);
return new WorkbookEvaluator(null, null, null).EvaluateFormula(ec, ptgs);
}
/**
* Make sure that the Evaluator can directly handle tAttrSum (instead of relying on re-parsing
* the whole formula which Converts tAttrSum to tFuncVar("SUM") )
*/
[Test]
public void TestAttrSum()
{
Ptg[] ptgs = { new IntPtg(42), AttrPtg.SUM, };
ValueEval result = EvaluateFormula(ptgs);
Assert.AreEqual(42, ((NumberEval)result).NumberValue, 0.0);
}
/**
* Make sure that the Evaluator can directly handle (deleted) ref error tokens
* (instead of relying on re-parsing the whole formula which Converts these
* to the error constant #REF! )
*/
[Test]
public void TestRefErr()
{
ConfirmRefErr(new RefErrorPtg());
ConfirmRefErr(new AreaErrPtg());
ConfirmRefErr(new DeletedRef3DPtg(0));
ConfirmRefErr(new DeletedArea3DPtg(0));
}
private static void ConfirmRefErr(Ptg ptg)
{
Ptg[] ptgs = { ptg };
ValueEval result = EvaluateFormula(ptgs);
Assert.AreEqual(ErrorEval.REF_INVALID, result);
}
/**
* Make sure that the Evaluator can directly handle tAttrSum (instead of relying on re-parsing
* the whole formula which Converts tAttrSum to tFuncVar("SUM") )
*/
[Test]
public void TestMemFunc()
{
Ptg[] ptgs = { new IntPtg(42), AttrPtg.SUM, };
ValueEval result = EvaluateFormula(ptgs);
Assert.AreEqual(42, ((NumberEval)result).NumberValue, 0.0);
}
[Test]
public void TestEvaluateMultipleWorkbooks()
{
HSSFWorkbook wbA = HSSFTestDataSamples.OpenSampleWorkbook("multibookFormulaA.xls");
HSSFWorkbook wbB = HSSFTestDataSamples.OpenSampleWorkbook("multibookFormulaB.xls");
HSSFFormulaEvaluator EvaluatorA = new HSSFFormulaEvaluator(wbA);
HSSFFormulaEvaluator EvaluatorB = new HSSFFormulaEvaluator(wbB);
// Hook up the IWorkbook Evaluators to enable Evaluation of formulas across books
String[] bookNames = { "multibookFormulaA.xls", "multibookFormulaB.xls", };
HSSFFormulaEvaluator[] Evaluators = { EvaluatorA, EvaluatorB, };
HSSFFormulaEvaluator.SetupEnvironment(bookNames, Evaluators);
ISheet aSheet1 = wbA.GetSheetAt(0);
ISheet bSheet1 = wbB.GetSheetAt(0);
// Simple case - single link from wbA to wbB
ConfirmFormula(wbA, 0, 0, 0, "[multibookFormulaB.xls]BSheet1!B1");
ICell cell = aSheet1.GetRow(0).GetCell(0);
ConfirmEvaluation(35, EvaluatorA, cell);
// more complex case - back link into wbA
// [wbA]ASheet1!A2 references (among other things) [wbB]BSheet1!B2
ConfirmFormula(wbA, 0, 1, 0, "[multibookFormulaB.xls]BSheet1!$B$2+2*A3");
// [wbB]BSheet1!B2 references (among other things) [wbA]AnotherSheet!A1:B2
ConfirmFormula(wbB, 0, 1, 1, "SUM([multibookFormulaA.xls]AnotherSheet!$A$1:$B$2)+B3");
cell = aSheet1.GetRow(1).GetCell(0);
ConfirmEvaluation(264, EvaluatorA, cell);
// change [wbB]BSheet1!B3 (from 50 to 60)
ICell cellB3 = bSheet1.GetRow(2).GetCell(1);
cellB3.SetCellValue(60);
EvaluatorB.NotifyUpdateCell(cellB3);
ConfirmEvaluation(274, EvaluatorA, cell);
// change [wbA]ASheet1!A3 (from 100 to 80)
ICell cellA3 = aSheet1.GetRow(2).GetCell(0);
cellA3.SetCellValue(80);
EvaluatorA.NotifyUpdateCell(cellA3);
ConfirmEvaluation(234, EvaluatorA, cell);
// change [wbA]AnotherSheet!A1 (from 2 to 3)
ICell cellA1 = wbA.GetSheetAt(1).GetRow(0).GetCell(0);
cellA1.SetCellValue(3);
EvaluatorA.NotifyUpdateCell(cellA1);
ConfirmEvaluation(235, EvaluatorA, cell);
}
private static void ConfirmEvaluation(double expectedValue, HSSFFormulaEvaluator fe, ICell cell)
{
Assert.AreEqual(expectedValue, fe.Evaluate(cell).NumberValue, 0.0);
}
private static void ConfirmFormula(HSSFWorkbook wb, int sheetIndex, int rowIndex, int columnIndex,
String expectedFormula)
{
ICell cell = wb.GetSheetAt(sheetIndex).GetRow(rowIndex).GetCell(columnIndex);
Assert.AreEqual(expectedFormula, cell.CellFormula);
}
/**
* This Test Makes sure that any {@link MissingArgEval} that propagates to
* the result of a function Gets translated to {@link BlankEval}.
*/
[Test]
public void TestMissingArg()
{
HSSFWorkbook wb = new HSSFWorkbook();
ISheet sheet = wb.CreateSheet("Sheet1");
IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(0);
cell.CellFormula = "1+IF(1,,)";
HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
CellValue cv = null;
try
{
cv = fe.Evaluate(cell);
}
catch (Exception)
{
Assert.Fail("Missing arg result not being handled correctly.");
}
Assert.AreEqual(CellType.Numeric, cv.CellType);
// Adding blank to 1.0 gives 1.0
Assert.AreEqual(1.0, cv.NumberValue, 0.0);
// check with string operand
cell.CellFormula = "\"abc\"&IF(1,,)";
fe.NotifySetFormula(cell);
cv = fe.Evaluate(cell);
Assert.AreEqual(CellType.String, cv.CellType);
// Adding blank to "abc" gives "abc"
Assert.AreEqual("abc", cv.StringValue);
// check CHOOSE()
cell.CellFormula = "\"abc\"&CHOOSE(2,5,,9)";
fe.NotifySetFormula(cell);
cv = fe.Evaluate(cell);
Assert.AreEqual(CellType.String, cv.CellType);
// Adding blank to "abc" gives "abc"
Assert.AreEqual("abc", cv.StringValue);
}
/**
* Functions like IF, INDIRECT, INDEX, OFFSET etc can return AreaEvals which
* should be dereferenced by the Evaluator
*/
[Test]
public void TestResultOutsideRange()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
HSSFWorkbook wb = new HSSFWorkbook();
ICell cell = wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0);
cell.CellFormula = "D2:D5"; // IF(TRUE,D2:D5,D2) or OFFSET(D2:D5,0,0) would work too
IFormulaEvaluator fe = wb.GetCreationHelper().CreateFormulaEvaluator();
CellValue cv;
try
{
cv = fe.Evaluate(cell);
}
catch (ArgumentException e)
{
if ("Specified row index (0) is outside the allowed range (1..4)".Equals(e.Message))
{
Assert.Fail("Identified bug in result dereferencing");
}
throw;
}
Assert.AreEqual(CellType.Error, cv.CellType);
Assert.AreEqual(ErrorEval.VALUE_INVALID.ErrorCode, cv.ErrorValue);
// verify circular refs are still detected properly
fe.ClearAllCachedResultValues();
cell.CellFormula = "OFFSET(A1,0,0)";
cv = fe.Evaluate(cell);
Assert.AreEqual(CellType.Error, cv.CellType);
Assert.AreEqual(ErrorEval.CIRCULAR_REF_ERROR.ErrorCode, cv.ErrorValue);
}
/**
* formulas with defined names.
*/
[Test]
public void TestNamesInFormulas()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
IWorkbook wb = new HSSFWorkbook();
ISheet sheet = wb.CreateSheet("Sheet1");
IName name1 = wb.CreateName();
name1.NameName = "aConstant";
name1.RefersToFormula = "3.14";
IName name2 = wb.CreateName();
name2.NameName = "aFormula";
name2.RefersToFormula = "SUM(Sheet1!$A$1:$A$3)";
IName name3 = wb.CreateName();
name3.NameName = "aSet";
name3.RefersToFormula = "Sheet1!$A$2:$A$4";
IRow row0 = sheet.CreateRow(0);
IRow row1 = sheet.CreateRow(1);
IRow row2 = sheet.CreateRow(2);
IRow row3 = sheet.CreateRow(3);
row0.CreateCell(0).SetCellValue(2);
row1.CreateCell(0).SetCellValue(5);
row2.CreateCell(0).SetCellValue(3);
row3.CreateCell(0).SetCellValue(7);
row0.CreateCell(2).SetCellFormula("aConstant");
row1.CreateCell(2).SetCellFormula("aFormula");
row2.CreateCell(2).SetCellFormula("SUM(aSet)");
row3.CreateCell(2).SetCellFormula("aConstant+aFormula+SUM(aSet)");
IFormulaEvaluator fe = wb.GetCreationHelper().CreateFormulaEvaluator();
Assert.AreEqual(3.14, fe.Evaluate(row0.GetCell(2)).NumberValue);
Assert.AreEqual(10.0, fe.Evaluate(row1.GetCell(2)).NumberValue);
Assert.AreEqual(15.0, fe.Evaluate(row2.GetCell(2)).NumberValue);
Assert.AreEqual(28.14, fe.Evaluate(row3.GetCell(2)).NumberValue);
}
// Test IF-Equals Formula Evaluation (bug 58591)
private IWorkbook TestIFEqualsFormulaEvaluation_setup(String formula, CellType a1CellType)
{
IWorkbook wb = new HSSFWorkbook();
ISheet sheet = wb.CreateSheet("IFEquals");
IRow row = sheet.CreateRow(0);
ICell A1 = row.CreateCell(0);
ICell B1 = row.CreateCell(1);
ICell C1 = row.CreateCell(2);
ICell D1 = row.CreateCell(3);
switch (a1CellType)
{
case CellType.Numeric:
A1.SetCellValue(1.0);
// "A1=1" should return true
break;
case CellType.String:
A1.SetCellValue("1");
// "A1=1" should return false
// "A1=\"1\"" should return true
break;
case CellType.Boolean:
A1.SetCellValue(true);
// "A1=1" should return true
break;
case CellType.Formula:
A1.SetCellFormula("1");
// "A1=1" should return true
break;
case CellType.Blank:
A1.SetCellValue((String)null);
// "A1=1" should return false
break;
}
B1.SetCellValue(2.0);
C1.SetCellValue(3.0);
D1.CellFormula = (formula);
return wb;
}
private void TestIFEqualsFormulaEvaluation_teardown(IWorkbook wb)
{
try
{
wb.Close();
}
catch (IOException)
{
Assert.Fail("Unable to close workbook");
}
}
private void TestIFEqualsFormulaEvaluation_evaluate(
String formula, CellType cellType, String expectedFormula, double expectedResult)
{
IWorkbook wb = TestIFEqualsFormulaEvaluation_setup(formula, cellType);
ICell D1 = wb.GetSheet("IFEquals").GetRow(0).GetCell(3);
IFormulaEvaluator eval = wb.GetCreationHelper().CreateFormulaEvaluator();
CellValue result = eval.Evaluate(D1);
// Call should not modify the contents
Assert.AreEqual(CellType.Formula, D1.CellType);
Assert.AreEqual(expectedFormula, D1.CellFormula);
Assert.AreEqual(CellType.Numeric, result.CellType);
Assert.AreEqual(expectedResult, result.NumberValue, EPSILON);
TestIFEqualsFormulaEvaluation_teardown(wb);
}
private void TestIFEqualsFormulaEvaluation_eval(
String formula, CellType cellType, String expectedFormula, double expectedValue)
{
TestIFEqualsFormulaEvaluation_evaluate(formula, cellType, expectedFormula, expectedValue);
TestIFEqualsFormulaEvaluation_evaluateFormulaCell(formula, cellType, expectedFormula, expectedValue);
TestIFEqualsFormulaEvaluation_evaluateInCell(formula, cellType, expectedFormula, expectedValue);
TestIFEqualsFormulaEvaluation_evaluateAll(formula, cellType, expectedFormula, expectedValue);
TestIFEqualsFormulaEvaluation_evaluateAllFormulaCells(formula, cellType, expectedFormula, expectedValue);
}
[Test]
public void TestIFEqualsFormulaEvaluation_NumericLiteral()
{
String formula = "IF(A1=1, 2, 3)";
CellType cellType = CellType.Numeric;
String expectedFormula = "IF(A1=1,2,3)";
double expectedValue = 2.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
[Test]
public void TestIFEqualsFormulaEvaluation_Numeric()
{
String formula = "IF(A1=1, B1, C1)";
CellType cellType = CellType.Numeric;
String expectedFormula = "IF(A1=1,B1,C1)";
double expectedValue = 2.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
[Test]
public void TestIFEqualsFormulaEvaluation_NumericCoerceToString()
{
String formula = "IF(A1&\"\"=\"1\", B1, C1)";
CellType cellType = CellType.Numeric;
String expectedFormula = "IF(A1&\"\"=\"1\",B1,C1)";
double expectedValue = 2.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
[Test]
public void TestIFEqualsFormulaEvaluation_String()
{
String formula = "IF(A1=1, B1, C1)";
CellType cellType = CellType.String;
String expectedFormula = "IF(A1=1,B1,C1)";
double expectedValue = 3.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
[Test]
public void TestIFEqualsFormulaEvaluation_StringCompareToString()
{
String formula = "IF(A1=\"1\", B1, C1)";
CellType cellType = CellType.String;
String expectedFormula = "IF(A1=\"1\",B1,C1)";
double expectedValue = 2.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
[Test]
public void TestIFEqualsFormulaEvaluation_StringCoerceToNumeric()
{
String formula = "IF(A1+0=1, B1, C1)";
CellType cellType = CellType.String;
String expectedFormula = "IF(A1+0=1,B1,C1)";
double expectedValue = 2.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
[Ignore("Bug 58591: this test currently Assert.Fails")]
[Test]
public void TestIFEqualsFormulaEvaluation_Boolean()
{
String formula = "IF(A1=1, B1, C1)";
CellType cellType = CellType.Boolean;
String expectedFormula = "IF(A1=1,B1,C1)";
double expectedValue = 2.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
[Ignore("Bug 58591: this test currently Assert.Fails")]
[Test]
public void TestIFEqualsFormulaEvaluation_BooleanSimple()
{
String formula = "3-(A1=1)";
CellType cellType = CellType.Boolean;
String expectedFormula = "3-(A1=1)";
double expectedValue = 2.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
[Test]
public void TestIFEqualsFormulaEvaluation_Formula()
{
String formula = "IF(A1=1, B1, C1)";
CellType cellType = CellType.Formula;
String expectedFormula = "IF(A1=1,B1,C1)";
double expectedValue = 2.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
[Test]
public void TestIFEqualsFormulaEvaluation_Blank()
{
String formula = "IF(A1=1, B1, C1)";
CellType cellType = CellType.Blank;
String expectedFormula = "IF(A1=1,B1,C1)";
double expectedValue = 3.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
[Test]
public void TestIFEqualsFormulaEvaluation_BlankCompareToZero()
{
String formula = "IF(A1=0, B1, C1)";
CellType cellType = CellType.Blank;
String expectedFormula = "IF(A1=0,B1,C1)";
double expectedValue = 2.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
[Ignore("Bug 58591: this test currently Assert.Fails")]
[Test]
public void TestIFEqualsFormulaEvaluation_BlankInverted()
{
String formula = "IF(NOT(A1)=1, B1, C1)";
CellType cellType = CellType.Blank;
String expectedFormula = "IF(NOT(A1)=1,B1,C1)";
double expectedValue = 2.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
[Ignore("Bug 58591: this test currently Assert.Fails")]
[Test]
public void TestIFEqualsFormulaEvaluation_BlankInvertedSimple()
{
String formula = "3-(NOT(A1)=1)";
CellType cellType = CellType.Blank;
String expectedFormula = "3-(NOT(A1)=1)";
double expectedValue = 2.0;
TestIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue);
}
private void TestIFEqualsFormulaEvaluation_evaluateFormulaCell(
String formula, CellType cellType, String expectedFormula, double expectedResult)
{
IWorkbook wb = TestIFEqualsFormulaEvaluation_setup(formula, cellType);
ICell D1 = wb.GetSheet("IFEquals").GetRow(0).GetCell(3);
IFormulaEvaluator eval = wb.GetCreationHelper().CreateFormulaEvaluator();
CellType resultCellType = eval.EvaluateFormulaCell(D1);
// Call should modify the contents, but leave the formula intact
Assert.AreEqual(CellType.Formula, D1.CellType);
Assert.AreEqual(expectedFormula, D1.CellFormula);
Assert.AreEqual(CellType.Numeric, resultCellType);
Assert.AreEqual(CellType.Numeric, D1.CachedFormulaResultType);
Assert.AreEqual(expectedResult, D1.NumericCellValue, EPSILON);
TestIFEqualsFormulaEvaluation_teardown(wb);
}
private void TestIFEqualsFormulaEvaluation_evaluateInCell(
String formula, CellType cellType, String expectedFormula, double expectedResult)
{
IWorkbook wb = TestIFEqualsFormulaEvaluation_setup(formula, cellType);
ICell D1 = wb.GetSheet("IFEquals").GetRow(0).GetCell(3);
IFormulaEvaluator eval = wb.GetCreationHelper().CreateFormulaEvaluator();
ICell result = eval.EvaluateInCell(D1);
// Call should modify the contents and replace the formula with the result
Assert.AreSame(D1, result); // returns the same cell that was provided as an argument so that calls can be chained.
try
{
string tmp = D1.CellFormula;
Assert.Fail("cell formula should be overwritten with formula result");
}
catch (InvalidOperationException)
{
}
Assert.AreEqual(CellType.Numeric, D1.CellType);
Assert.AreEqual(expectedResult, D1.NumericCellValue, EPSILON);
TestIFEqualsFormulaEvaluation_teardown(wb);
}
private void TestIFEqualsFormulaEvaluation_evaluateAll(
String formula, CellType cellType, String expectedFormula, double expectedResult)
{
IWorkbook wb = TestIFEqualsFormulaEvaluation_setup(formula, cellType);
ICell D1 = wb.GetSheet("IFEquals").GetRow(0).GetCell(3);
IFormulaEvaluator eval = wb.GetCreationHelper().CreateFormulaEvaluator();
eval.EvaluateAll();
// Call should modify the contents
Assert.AreEqual(CellType.Formula, D1.CellType);
Assert.AreEqual(expectedFormula, D1.CellFormula);
Assert.AreEqual(CellType.Numeric, D1.CachedFormulaResultType);
Assert.AreEqual(expectedResult, D1.NumericCellValue, EPSILON);
TestIFEqualsFormulaEvaluation_teardown(wb);
}
private void TestIFEqualsFormulaEvaluation_evaluateAllFormulaCells(
String formula, CellType cellType, String expectedFormula, double expectedResult)
{
IWorkbook wb = TestIFEqualsFormulaEvaluation_setup(formula, cellType);
ICell D1 = wb.GetSheet("IFEquals").GetRow(0).GetCell(3);
HSSFFormulaEvaluator.EvaluateAllFormulaCells(wb);
// Call should modify the contents
Assert.AreEqual(CellType.Formula, D1.CellType);
// whitespace gets deleted because formula is parsed and re-rendered
Assert.AreEqual(expectedFormula, D1.CellFormula);
Assert.AreEqual(CellType.Numeric, D1.CachedFormulaResultType);
Assert.AreEqual(expectedResult, D1.NumericCellValue, EPSILON);
TestIFEqualsFormulaEvaluation_teardown(wb);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using Sodium;
namespace Tests.sodium
{
[TestFixture]
public class EventTester
{
[TearDown]
public void TearDown()
{
GC.Collect();
Thread.Sleep(100);
}
[Test]
public void TestSendEvent()
{
var e = new EventSink<int>();
var @out = new List<int>();
Listener l = e.Listen(x => { @out.Add(x); });
e.Send(5);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 5 }, @out);
e.Send(6);
CollectionAssert.AreEqual(new[] { 5 }, @out);
}
[Test]
public void TestMap()
{
var e = new EventSink<int>();
Event<String> m = e.Map(x => x.ToString());
var @out = new List<string>();
Listener l = m.Listen(x => { @out.Add(x); });
e.Send(5);
l.Unlisten();
CollectionAssert.AreEqual(new[] { "5" }, @out);
}
[Test]
public void TestMergeNonSimultaneous()
{
var e1 = new EventSink<int>();
var e2 = new EventSink<int>();
var @out = new List<int>();
Listener l = Event<int>.Merge(e1, e2).Listen(x => { @out.Add(x); });
e1.Send(7);
e2.Send(9);
e1.Send(8);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 7, 9, 8 }, @out);
}
[Test]
public void TestMergeSimultaneous()
{
var e = new EventSink<int>();
var @out = new List<int>();
Listener l = Event<int>.Merge(e, e).Listen(x => { @out.Add(x); });
e.Send(7);
e.Send(9);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 7, 7, 9, 9 }, @out);
}
[Test]
public void TestMergeLeftBias()
{
var e1 = new EventSink<string>();
var e2 = new EventSink<string>();
var @out = new List<string>();
Listener l = Event<string>.Merge(e1, e2).Listen(x => { @out.Add(x); });
Transaction.RunVoid(() =>
{
e1.Send("left1a");
e1.Send("left1b");
e2.Send("right1a");
e2.Send("right1b");
});
Transaction.RunVoid(() =>
{
e2.Send("right2a");
e2.Send("right2b");
e1.Send("left2a");
e1.Send("left2b");
});
l.Unlisten();
CollectionAssert.AreEqual(new[]{
"left1a", "left1b",
"right1a", "right1b",
"left2a", "left2b",
"right2a", "right2b"
}, @out);
}
[Test]
public void TestCoalesce()
{
var e1 = new EventSink<int>();
var e2 = new EventSink<int>();
var @out = new List<int>();
Listener l =
Event<int>.Merge<int>(e1, Event<int>.Merge<int>(e1.Map<int>(x => x * 100), e2))
.Coalesce((a, b) => a + b)
.Listen(x => { @out.Add(x); });
e1.Send(2);
e1.Send(8);
e2.Send(40);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 202, 808, 40 }, @out.ToArray());
}
[Test]
public void TestFilter()
{
var e = new EventSink<char>();
var @out = new List<char>();
Listener l = e.Filter(c => Char.IsUpper((char)c)).Listen(c => { @out.Add(c); });
e.Send('H');
e.Send('o');
e.Send('I');
l.Unlisten();
CollectionAssert.AreEqual(new[] { 'H', 'I' }, @out);
}
[Test]
public void TestFilterNotNull()
{
var e = new EventSink<string>();
var @out = new List<string>();
Listener l = e.FilterNotNull().Listen(s => { @out.Add(s); });
e.Send("tomato");
e.Send(null);
e.Send("peach");
l.Unlisten();
CollectionAssert.AreEqual(new[] { "tomato", "peach" }, @out);
}
[Test]
public void testFilterOptional()
{
EventSink<Optional<String>> e = new EventSink<Optional<String>>();
List<String> @out = new List<string>();
Listener l = Event<Optional<String>>.FilterOptional(e).Listen(s => { @out.Add(s); });
e.Send(new Optional<string> ("tomato"));
e.Send(Optional<string>.Empty());
e.Send(new Optional<string>("peach"));
l.Unlisten();
CollectionAssert.AreEqual(new[] { "tomato", "peach" }, @out);
}
[Test]
public void TestLoopEvent()
{
var ea = new EventSink<int>();
Event<int> ec = Transaction.Run(() =>
{
var eb = new EventLoop<int>();
Event<int> ec_ = Event<int>.MergeWith<int>((x, y) => x + y, ea.Map<int>(x => x % 10), eb);
Event<int> ebOut = ea.Map<int>(x => x / 10).Filter(x => x != 0);
eb.Loop(ebOut);
return ec_;
});
var @out = new List<int>();
Listener l = ec.Listen(x => { @out.Add(x); });
ea.Send(2);
ea.Send(52);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 2, 7 }, @out.ToArray());
}
[Test]
public void TestGate()
{
var ec = new EventSink<char?>();
var epred = new BehaviorSink<Boolean>(true);
var @out = new List<char?>();
Listener l = ec.Gate(epred).Listen(x => { @out.Add(x); });
ec.Send('H');
epred.Send(false);
ec.Send('O');
epred.Send(true);
ec.Send('I');
l.Unlisten();
CollectionAssert.AreEqual(new[] { 'H', 'I' }, @out);
}
[Test]
public void TestCollect()
{
var ea = new EventSink<int>();
var @out = new List<int>();
Event<int> sum = ea.Collect(
(int)100,
//(a,s) => new Tuple2(a+s, a+s)
(a, s) => new Tuple<int, int>(a + s, a + s));
Listener l = sum.Listen(x => { @out.Add(x); });
ea.Send(5);
ea.Send(7);
ea.Send(1);
ea.Send(2);
ea.Send(3);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 105, 112, 113, 115, 118 }, @out);
}
[Test]
public void TestAccum()
{
var ea = new EventSink<int>();
var @out = new List<int>();
Behavior<int> sum = ea.Accum((int)100, (a, s) => a + s);
Listener l = sum.Updates().Listen(x => { @out.Add(x); });
ea.Send(5);
ea.Send(7);
ea.Send(1);
ea.Send(2);
ea.Send(3);
l.Unlisten();
CollectionAssert.AreEqual(new[] { 105, 112, 113, 115, 118 }, @out);
}
[Test]
public void TestOnce()
{
var e = new EventSink<char>();
var @out = new List<char>();
Listener l = e.Once().Listen(x => { @out.Add(x); });
e.Send('A');
e.Send('B');
e.Send('C');
l.Unlisten();
CollectionAssert.AreEqual(new[] { 'A' }, @out);
}
[Test]
public void TestDelay()
{
var e = new EventSink<char>();
Behavior<char> b = e.Hold(' ');
var @out = new List<char>();
Listener l = e.Delay().Snapshot(b).Listen(x => { @out.Add(x); });
e.Send('C');
e.Send('B');
e.Send('A');
l.Unlisten();
CollectionAssert.AreEqual(new[] { 'C', 'B', 'A' }, @out);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Runtime.CompilerServices
{
public class UnsafeTests
{
[Fact]
public static unsafe void ReadInt32()
{
int expected = 10;
void* address = Unsafe.AsPointer(ref expected);
int ret = Unsafe.Read<int>(address);
Assert.Equal(expected, ret);
}
[Fact]
public static unsafe void WriteInt32()
{
int value = 10;
int* address = (int*)Unsafe.AsPointer(ref value);
int expected = 20;
Unsafe.Write(address, expected);
Assert.Equal(expected, value);
Assert.Equal(expected, *address);
Assert.Equal(expected, Unsafe.Read<int>(address));
}
[Fact]
public static unsafe void WriteBytesIntoInt32()
{
int value = 20;
int* intAddress = (int*)Unsafe.AsPointer(ref value);
byte* byteAddress = (byte*)intAddress;
for (int i = 0; i < 4; i++)
{
Unsafe.Write(byteAddress + i, (byte)i);
}
Assert.Equal(0, Unsafe.Read<byte>(byteAddress));
Assert.Equal(1, Unsafe.Read<byte>(byteAddress + 1));
Assert.Equal(2, Unsafe.Read<byte>(byteAddress + 2));
Assert.Equal(3, Unsafe.Read<byte>(byteAddress + 3));
Byte4 b4 = Unsafe.Read<Byte4>(byteAddress);
Assert.Equal(0, b4.B0);
Assert.Equal(1, b4.B1);
Assert.Equal(2, b4.B2);
Assert.Equal(3, b4.B3);
int expected = (b4.B3 << 24) + (b4.B2 << 16) + (b4.B1 << 8) + (b4.B0);
Assert.Equal(expected, value);
}
[Fact]
public static unsafe void LongIntoCompoundStruct()
{
long value = 1234567891011121314L;
long* longAddress = (long*)Unsafe.AsPointer(ref value);
Byte4Short2 b4s2 = Unsafe.Read<Byte4Short2>(longAddress);
Assert.Equal(162, b4s2.B0);
Assert.Equal(48, b4s2.B1);
Assert.Equal(210, b4s2.B2);
Assert.Equal(178, b4s2.B3);
Assert.Equal(4340, b4s2.S4);
Assert.Equal(4386, b4s2.S6);
b4s2.B0 = 1;
b4s2.B1 = 1;
b4s2.B2 = 1;
b4s2.B3 = 1;
b4s2.S4 = 1;
b4s2.S6 = 1;
Unsafe.Write(longAddress, b4s2);
long expected = 281479288520961;
Assert.Equal(expected, value);
Assert.Equal(expected, Unsafe.Read<long>(longAddress));
}
[Fact]
public static unsafe void ReadWriteDoublePointer()
{
int value1 = 10;
int value2 = 20;
int* valueAddress = (int*)Unsafe.AsPointer(ref value1);
int** valueAddressPtr = &valueAddress;
Unsafe.Write(valueAddressPtr, new IntPtr(&value2));
Assert.Equal(20, *(*valueAddressPtr));
Assert.Equal(20, Unsafe.Read<int>(valueAddress));
Assert.Equal(new IntPtr(valueAddress), Unsafe.Read<IntPtr>(valueAddressPtr));
Assert.Equal(20, Unsafe.Read<int>(Unsafe.Read<IntPtr>(valueAddressPtr).ToPointer()));
}
[Fact]
public static unsafe void CopyToRef()
{
int value = 10;
int destination = -1;
Unsafe.Copy(ref destination, Unsafe.AsPointer(ref value));
Assert.Equal(10, destination);
Assert.Equal(10, value);
int destination2 = -1;
Unsafe.Copy(ref destination2, &value);
Assert.Equal(10, destination2);
Assert.Equal(10, value);
}
[Fact]
public static unsafe void CopyToVoidPtr()
{
int value = 10;
int destination = -1;
Unsafe.Copy(Unsafe.AsPointer(ref destination), ref value);
Assert.Equal(10, destination);
Assert.Equal(10, value);
int destination2 = -1;
Unsafe.Copy(&destination2, ref value);
Assert.Equal(10, destination2);
Assert.Equal(10, value);
}
[Theory]
[MemberData(nameof(SizeOfData))]
public static unsafe void SizeOf<T>(int expected, T valueUnused)
{
// valueUnused is only present to enable Xunit to call the correct generic overload.
Assert.Equal(expected, Unsafe.SizeOf<T>());
}
public static IEnumerable<object[]> SizeOfData()
{
yield return new object[] { 1, new sbyte() };
yield return new object[] { 1, new byte() };
yield return new object[] { 2, new short() };
yield return new object[] { 2, new ushort() };
yield return new object[] { 4, new int() };
yield return new object[] { 4, new uint() };
yield return new object[] { 8, new long() };
yield return new object[] { 8, new ulong() };
yield return new object[] { 4, new float() };
yield return new object[] { 8, new double() };
yield return new object[] { 4, new Byte4() };
yield return new object[] { 8, new Byte4Short2() };
yield return new object[] { 512, new Byte512() };
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockStack(int numBytes, byte value)
{
byte* stackPtr = stackalloc byte[numBytes];
Unsafe.InitBlock(stackPtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(stackPtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockUnmanaged(int numBytes, byte value)
{
IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes);
byte* bytePtr = (byte*)allocatedMemory.ToPointer();
Unsafe.InitBlock(bytePtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(bytePtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockRefStack(int numBytes, byte value)
{
byte* stackPtr = stackalloc byte[numBytes];
Unsafe.InitBlock(ref *stackPtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(stackPtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockRefUnmanaged(int numBytes, byte value)
{
IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes);
byte* bytePtr = (byte*)allocatedMemory.ToPointer();
Unsafe.InitBlock(ref *bytePtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(bytePtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockUnalignedStack(int numBytes, byte value)
{
byte* stackPtr = stackalloc byte[numBytes + 1];
stackPtr += 1; // +1 = make unaligned
Unsafe.InitBlockUnaligned(stackPtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(stackPtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockUnalignedUnmanaged(int numBytes, byte value)
{
IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes + 1);
byte* bytePtr = (byte*)allocatedMemory.ToPointer() + 1; // +1 = make unaligned
Unsafe.InitBlockUnaligned(bytePtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(bytePtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockUnalignedRefStack(int numBytes, byte value)
{
byte* stackPtr = stackalloc byte[numBytes + 1];
stackPtr += 1; // +1 = make unaligned
Unsafe.InitBlockUnaligned(ref *stackPtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(stackPtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockUnalignedRefUnmanaged(int numBytes, byte value)
{
IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes + 1);
byte* bytePtr = (byte*)allocatedMemory.ToPointer() + 1; // +1 = make unaligned
Unsafe.InitBlockUnaligned(ref *bytePtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(bytePtr[i], value);
}
}
public static IEnumerable<object[]> InitBlockData()
{
yield return new object[] { 0, 1 };
yield return new object[] { 1, 1 };
yield return new object[] { 10, 0 };
yield return new object[] { 10, 2 };
yield return new object[] { 10, 255 };
yield return new object[] { 10000, 255 };
}
[Theory]
[MemberData(nameof(CopyBlockData))]
public static unsafe void CopyBlock(int numBytes)
{
byte* source = stackalloc byte[numBytes];
byte* destination = stackalloc byte[numBytes];
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
source[i] = value;
}
Unsafe.CopyBlock(destination, source, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
Assert.Equal(value, destination[i]);
Assert.Equal(source[i], destination[i]);
}
}
[Theory]
[MemberData(nameof(CopyBlockData))]
public static unsafe void CopyBlockRef(int numBytes)
{
byte* source = stackalloc byte[numBytes];
byte* destination = stackalloc byte[numBytes];
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
source[i] = value;
}
Unsafe.CopyBlock(ref destination[0], ref source[0], (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
Assert.Equal(value, destination[i]);
Assert.Equal(source[i], destination[i]);
}
}
[Theory]
[MemberData(nameof(CopyBlockData))]
public static unsafe void CopyBlockUnaligned(int numBytes)
{
byte* source = stackalloc byte[numBytes + 1];
byte* destination = stackalloc byte[numBytes + 1];
source += 1; // +1 = make unaligned
destination += 1; // +1 = make unaligned
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
source[i] = value;
}
Unsafe.CopyBlockUnaligned(destination, source, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
Assert.Equal(value, destination[i]);
Assert.Equal(source[i], destination[i]);
}
}
[Theory]
[MemberData(nameof(CopyBlockData))]
public static unsafe void CopyBlockUnalignedRef(int numBytes)
{
byte* source = stackalloc byte[numBytes + 1];
byte* destination = stackalloc byte[numBytes + 1];
source += 1; // +1 = make unaligned
destination += 1; // +1 = make unaligned
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
source[i] = value;
}
Unsafe.CopyBlockUnaligned(ref destination[0], ref source[0], (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
Assert.Equal(value, destination[i]);
Assert.Equal(source[i], destination[i]);
}
}
public static IEnumerable<object[]> CopyBlockData()
{
yield return new object[] { 0 };
yield return new object[] { 1 };
yield return new object[] { 10 };
yield return new object[] { 100 };
yield return new object[] { 100000 };
}
[Fact]
public static void As()
{
object o = "Hello";
Assert.Equal("Hello", Unsafe.As<string>(o));
}
[Fact]
public static void DangerousAs()
{
// Verify that As does not perform type checks
object o = new Object();
Assert.IsType(typeof(Object), Unsafe.As<string>(o));
}
[Fact]
public static void ByteOffsetArray()
{
var a = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };
Assert.Equal(new IntPtr(0), Unsafe.ByteOffset(ref a[0], ref a[0]));
Assert.Equal(new IntPtr(1), Unsafe.ByteOffset(ref a[0], ref a[1]));
Assert.Equal(new IntPtr(-1), Unsafe.ByteOffset(ref a[1], ref a[0]));
Assert.Equal(new IntPtr(2), Unsafe.ByteOffset(ref a[0], ref a[2]));
Assert.Equal(new IntPtr(-2), Unsafe.ByteOffset(ref a[2], ref a[0]));
Assert.Equal(new IntPtr(3), Unsafe.ByteOffset(ref a[0], ref a[3]));
Assert.Equal(new IntPtr(4), Unsafe.ByteOffset(ref a[0], ref a[4]));
Assert.Equal(new IntPtr(5), Unsafe.ByteOffset(ref a[0], ref a[5]));
Assert.Equal(new IntPtr(6), Unsafe.ByteOffset(ref a[0], ref a[6]));
Assert.Equal(new IntPtr(7), Unsafe.ByteOffset(ref a[0], ref a[7]));
}
[Fact]
public static void ByteOffsetStackByte4()
{
var byte4 = new Byte4();
Assert.Equal(new IntPtr(0), Unsafe.ByteOffset(ref byte4.B0, ref byte4.B0));
Assert.Equal(new IntPtr(1), Unsafe.ByteOffset(ref byte4.B0, ref byte4.B1));
Assert.Equal(new IntPtr(-1), Unsafe.ByteOffset(ref byte4.B1, ref byte4.B0));
Assert.Equal(new IntPtr(2), Unsafe.ByteOffset(ref byte4.B0, ref byte4.B2));
Assert.Equal(new IntPtr(-2), Unsafe.ByteOffset(ref byte4.B2, ref byte4.B0));
Assert.Equal(new IntPtr(3), Unsafe.ByteOffset(ref byte4.B0, ref byte4.B3));
Assert.Equal(new IntPtr(-3), Unsafe.ByteOffset(ref byte4.B3, ref byte4.B0));
}
[Fact]
public static unsafe void AsRef()
{
byte[] b = new byte[4] { 0x42, 0x42, 0x42, 0x42 };
fixed (byte * p = b)
{
ref int r = ref Unsafe.AsRef<int>(p);
Assert.Equal(0x42424242, r);
r = 0x0EF00EF0;
Assert.Equal(0xFE, b[0] | b[1] | b[2] | b[3]);
}
}
[Fact]
public static void InAsRef()
{
int[] a = new int[] { 0x123, 0x234, 0x345, 0x456 };
ref int r = ref Unsafe.AsRef<int>(a[0]);
Assert.Equal(0x123, r);
r = 0x42;
Assert.Equal(0x42, a[0]);
}
[Fact]
public static void RefAs()
{
byte[] b = new byte[4] { 0x42, 0x42, 0x42, 0x42 };
ref int r = ref Unsafe.As<byte, int>(ref b[0]);
Assert.Equal(0x42424242, r);
r = 0x0EF00EF0;
Assert.Equal(0xFE, b[0] | b[1] | b[2] | b[3]);
}
[Fact]
public static void RefAdd()
{
int[] a = new int[] { 0x123, 0x234, 0x345, 0x456 };
ref int r1 = ref Unsafe.Add(ref a[0], 1);
Assert.Equal(0x234, r1);
ref int r2 = ref Unsafe.Add(ref r1, 2);
Assert.Equal(0x456, r2);
ref int r3 = ref Unsafe.Add(ref r2, -3);
Assert.Equal(0x123, r3);
}
[Fact]
public static unsafe void VoidPointerAdd()
{
int[] a = new int[] { 0x123, 0x234, 0x345, 0x456 };
fixed (void* ptr = a)
{
void* r1 = Unsafe.Add<int>(ptr, 1);
Assert.Equal(0x234, *(int*)r1);
void* r2 = Unsafe.Add<int>(r1, 2);
Assert.Equal(0x456, *(int*)r2);
void* r3 = Unsafe.Add<int>(r2, -3);
Assert.Equal(0x123, *(int*)r3);
}
fixed (void* ptr = &a[1])
{
void* r0 = Unsafe.Add<int>(ptr, -1);
Assert.Equal(0x123, *(int*)r0);
void* r3 = Unsafe.Add<int>(ptr, 2);
Assert.Equal(0x456, *(int*)r3);
}
}
[Fact]
public static void RefAddIntPtr()
{
int[] a = new int[] { 0x123, 0x234, 0x345, 0x456 };
ref int r1 = ref Unsafe.Add(ref a[0], (IntPtr)1);
Assert.Equal(0x234, r1);
ref int r2 = ref Unsafe.Add(ref r1, (IntPtr)2);
Assert.Equal(0x456, r2);
ref int r3 = ref Unsafe.Add(ref r2, (IntPtr)(-3));
Assert.Equal(0x123, r3);
}
[Fact]
public static void RefAddByteOffset()
{
byte[] a = new byte[] { 0x12, 0x34, 0x56, 0x78 };
ref byte r1 = ref Unsafe.AddByteOffset(ref a[0], (IntPtr)1);
Assert.Equal(0x34, r1);
ref byte r2 = ref Unsafe.AddByteOffset(ref r1, (IntPtr)2);
Assert.Equal(0x78, r2);
ref byte r3 = ref Unsafe.AddByteOffset(ref r2, (IntPtr)(-3));
Assert.Equal(0x12, r3);
}
[Fact]
public static void RefSubtract()
{
string[] a = new string[] { "abc", "def", "ghi", "jkl" };
ref string r1 = ref Unsafe.Subtract(ref a[0], -2);
Assert.Equal("ghi", r1);
ref string r2 = ref Unsafe.Subtract(ref r1, -1);
Assert.Equal("jkl", r2);
ref string r3 = ref Unsafe.Subtract(ref r2, 3);
Assert.Equal("abc", r3);
}
[Fact]
public static unsafe void VoidPointerSubtract()
{
int[] a = new int[] { 0x123, 0x234, 0x345, 0x456 };
fixed (void* ptr = a)
{
void* r1 = Unsafe.Subtract<int>(ptr, -2);
Assert.Equal(0x345, *(int*)r1);
void* r2 = Unsafe.Subtract<int>(r1, -1);
Assert.Equal(0x456, *(int*)r2);
void* r3 = Unsafe.Subtract<int>(r2, 3);
Assert.Equal(0x123, *(int*)r3);
}
fixed (void* ptr = &a[1])
{
void* r0 = Unsafe.Subtract<int>(ptr, 1);
Assert.Equal(0x123, *(int*)r0);
void* r3 = Unsafe.Subtract<int>(ptr, -2);
Assert.Equal(0x456, *(int*)r3);
}
}
[Fact]
public static void RefSubtractIntPtr()
{
string[] a = new string[] { "abc", "def", "ghi", "jkl" };
ref string r1 = ref Unsafe.Subtract(ref a[0], (IntPtr)(-2));
Assert.Equal("ghi", r1);
ref string r2 = ref Unsafe.Subtract(ref r1, (IntPtr)(-1));
Assert.Equal("jkl", r2);
ref string r3 = ref Unsafe.Subtract(ref r2, (IntPtr)3);
Assert.Equal("abc", r3);
}
[Fact]
public static void RefSubtractByteOffset()
{
byte[] a = new byte[] { 0x12, 0x34, 0x56, 0x78 };
ref byte r1 = ref Unsafe.SubtractByteOffset(ref a[0], (IntPtr)(-1));
Assert.Equal(0x34, r1);
ref byte r2 = ref Unsafe.SubtractByteOffset(ref r1, (IntPtr)(-2));
Assert.Equal(0x78, r2);
ref byte r3 = ref Unsafe.SubtractByteOffset(ref r2, (IntPtr)3);
Assert.Equal(0x12, r3);
}
[Fact]
public static void RefAreSame()
{
long[] a = new long[2];
Assert.True(Unsafe.AreSame(ref a[0], ref a[0]));
Assert.False(Unsafe.AreSame(ref a[0], ref a[1]));
}
[Fact]
public static unsafe void RefIsAddressGreaterThan()
{
int[] a = new int[2];
Assert.False(Unsafe.IsAddressGreaterThan(ref a[0], ref a[0]));
Assert.False(Unsafe.IsAddressGreaterThan(ref a[0], ref a[1]));
Assert.True(Unsafe.IsAddressGreaterThan(ref a[1], ref a[0]));
Assert.False(Unsafe.IsAddressGreaterThan(ref a[1], ref a[1]));
// The following tests ensure that we're using unsigned comparison logic
Assert.False(Unsafe.IsAddressGreaterThan(ref Unsafe.AsRef<byte>((void*)(1)), ref Unsafe.AsRef<byte>((void*)(-1))));
Assert.True(Unsafe.IsAddressGreaterThan(ref Unsafe.AsRef<byte>((void*)(-1)), ref Unsafe.AsRef<byte>((void*)(1))));
Assert.True(Unsafe.IsAddressGreaterThan(ref Unsafe.AsRef<byte>((void*)(Int32.MinValue)), ref Unsafe.AsRef<byte>((void*)(Int32.MaxValue))));
Assert.False(Unsafe.IsAddressGreaterThan(ref Unsafe.AsRef<byte>((void*)(Int32.MaxValue)), ref Unsafe.AsRef<byte>((void*)(Int32.MinValue))));
Assert.False(Unsafe.IsAddressGreaterThan(ref Unsafe.AsRef<byte>(null), ref Unsafe.AsRef<byte>(null)));
}
[Fact]
public static unsafe void RefIsAddressLessThan()
{
int[] a = new int[2];
Assert.False(Unsafe.IsAddressLessThan(ref a[0], ref a[0]));
Assert.True(Unsafe.IsAddressLessThan(ref a[0], ref a[1]));
Assert.False(Unsafe.IsAddressLessThan(ref a[1], ref a[0]));
Assert.False(Unsafe.IsAddressLessThan(ref a[1], ref a[1]));
// The following tests ensure that we're using unsigned comparison logic
Assert.True(Unsafe.IsAddressLessThan(ref Unsafe.AsRef<byte>((void*)(1)), ref Unsafe.AsRef<byte>((void*)(-1))));
Assert.False(Unsafe.IsAddressLessThan(ref Unsafe.AsRef<byte>((void*)(-1)), ref Unsafe.AsRef<byte>((void*)(1))));
Assert.False(Unsafe.IsAddressLessThan(ref Unsafe.AsRef<byte>((void*)(Int32.MinValue)), ref Unsafe.AsRef<byte>((void*)(Int32.MaxValue))));
Assert.True(Unsafe.IsAddressLessThan(ref Unsafe.AsRef<byte>((void*)(Int32.MaxValue)), ref Unsafe.AsRef<byte>((void*)(Int32.MinValue))));
Assert.False(Unsafe.IsAddressLessThan(ref Unsafe.AsRef<byte>(null), ref Unsafe.AsRef<byte>(null)));
}
[Fact]
public static unsafe void ReadUnaligned_ByRef_Int32()
{
byte[] unaligned = Int32Double.Unaligned(123456789, 3.42);
int actual = Unsafe.ReadUnaligned<int>(ref unaligned[1]);
Assert.Equal(123456789, actual);
}
[Fact]
public static unsafe void ReadUnaligned_ByRef_Double()
{
byte[] unaligned = Int32Double.Unaligned(123456789, 3.42);
double actual = Unsafe.ReadUnaligned<double>(ref unaligned[9]);
Assert.Equal(3.42, actual);
}
[Fact]
public static unsafe void ReadUnaligned_ByRef_Struct()
{
byte[] unaligned = Int32Double.Unaligned(123456789, 3.42);
Int32Double actual = Unsafe.ReadUnaligned<Int32Double>(ref unaligned[1]);
Assert.Equal(123456789, actual.Int32);
Assert.Equal(3.42, actual.Double);
}
[Fact]
public static unsafe void ReadUnaligned_Ptr_Int32()
{
byte[] unaligned = Int32Double.Unaligned(123456789, 3.42);
fixed (byte* p = unaligned)
{
int actual = Unsafe.ReadUnaligned<int>(p + 1);
Assert.Equal(123456789, actual);
}
}
[Fact]
public static unsafe void ReadUnaligned_Ptr_Double()
{
byte[] unaligned = Int32Double.Unaligned(123456789, 3.42);
fixed (byte* p = unaligned)
{
double actual = Unsafe.ReadUnaligned<double>(p + 9);
Assert.Equal(3.42, actual);
}
}
[Fact]
public static unsafe void ReadUnaligned_Ptr_Struct()
{
byte[] unaligned = Int32Double.Unaligned(123456789, 3.42);
fixed (byte* p = unaligned)
{
Int32Double actual = Unsafe.ReadUnaligned<Int32Double>(p + 1);
Assert.Equal(123456789, actual.Int32);
Assert.Equal(3.42, actual.Double);
}
}
[Fact]
public static unsafe void WriteUnaligned_ByRef_Int32()
{
byte[] unaligned = new byte[sizeof(Int32Double) + 1];
Unsafe.WriteUnaligned(ref unaligned[1], 123456789);
int actual = Int32Double.Aligned(unaligned).Int32;
Assert.Equal(123456789, actual);
}
[Fact]
public static unsafe void WriteUnaligned_ByRef_Double()
{
byte[] unaligned = new byte[sizeof(Int32Double) + 1];
Unsafe.WriteUnaligned(ref unaligned[9], 3.42);
double actual = Int32Double.Aligned(unaligned).Double;
Assert.Equal(3.42, actual);
}
[Fact]
public static unsafe void WriteUnaligned_ByRef_Struct()
{
byte[] unaligned = new byte[sizeof(Int32Double) + 1];
Unsafe.WriteUnaligned(ref unaligned[1], new Int32Double { Int32 = 123456789, Double = 3.42 });
Int32Double actual = Int32Double.Aligned(unaligned);
Assert.Equal(123456789, actual.Int32);
Assert.Equal(3.42, actual.Double);
}
[Fact]
public static unsafe void WriteUnaligned_Ptr_Int32()
{
byte[] unaligned = new byte[sizeof(Int32Double) + 1];
fixed (byte* p = unaligned)
{
Unsafe.WriteUnaligned(p + 1, 123456789);
}
int actual = Int32Double.Aligned(unaligned).Int32;
Assert.Equal(123456789, actual);
}
[Fact]
public static unsafe void WriteUnaligned_Ptr_Double()
{
byte[] unaligned = new byte[sizeof(Int32Double) + 1];
fixed (byte* p = unaligned)
{
Unsafe.WriteUnaligned(p + 9, 3.42);
}
double actual = Int32Double.Aligned(unaligned).Double;
Assert.Equal(3.42, actual);
}
[Fact]
public static unsafe void WriteUnaligned_Ptr_Struct()
{
byte[] unaligned = new byte[sizeof(Int32Double) + 1];
fixed (byte* p = unaligned)
{
Unsafe.WriteUnaligned(p + 1, new Int32Double { Int32 = 123456789, Double = 3.42 });
}
Int32Double actual = Int32Double.Aligned(unaligned);
Assert.Equal(123456789, actual.Int32);
Assert.Equal(3.42, actual.Double);
}
}
[StructLayout(LayoutKind.Explicit)]
public struct Byte4
{
[FieldOffset(0)]
public byte B0;
[FieldOffset(1)]
public byte B1;
[FieldOffset(2)]
public byte B2;
[FieldOffset(3)]
public byte B3;
}
[StructLayout(LayoutKind.Explicit)]
public struct Byte4Short2
{
[FieldOffset(0)]
public byte B0;
[FieldOffset(1)]
public byte B1;
[FieldOffset(2)]
public byte B2;
[FieldOffset(3)]
public byte B3;
[FieldOffset(4)]
public short S4;
[FieldOffset(6)]
public short S6;
}
public unsafe struct Byte512
{
public fixed byte Bytes[512];
}
[StructLayout(LayoutKind.Explicit, Size=16)]
public unsafe struct Int32Double
{
[FieldOffset(0)]
public int Int32;
[FieldOffset(8)]
public double Double;
public static unsafe byte[] Unaligned(int i, double d)
{
var aligned = new Int32Double { Int32 = i, Double = d };
var unaligned = new byte[sizeof(Int32Double) + 1];
fixed (byte* p = unaligned)
{
Buffer.MemoryCopy(&aligned, p + 1, sizeof(Int32Double), sizeof(Int32Double));
}
return unaligned;
}
public static unsafe Int32Double Aligned(byte[] unaligned)
{
var aligned = new Int32Double();
fixed (byte* p = unaligned)
{
Buffer.MemoryCopy(p + 1, &aligned, sizeof(Int32Double), sizeof(Int32Double));
}
return aligned;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: TypeHelper.cs
//
// 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.Diagnostics;
using System.Reflection;
using Dot42.Internal.Generics;
using Java.Lang.Reflect;
namespace Dot42.Internal
{
[DebuggerStepThrough]
internal static class TypeHelper
{
/// <summary>
/// Type of java.lang.Boolean
/// </summary>
[DexNative]
internal static extern Type BooleanType();
/// <summary>
/// Type of java.lang.Byte
/// </summary>
[DexNative]
internal static extern Type ByteType();
/// <summary>
/// Type of java.lang.Character
/// </summary>
[DexNative]
internal static extern Type CharacterType();
/// <summary>
/// Type of java.lang.Short
/// </summary>
[DexNative]
internal static extern Type ShortType();
/// <summary>
/// Type of java.lang.Integer
/// </summary>
[DexNative]
internal static extern Type IntegerType();
/// <summary>
/// Type of java.lang.Long
/// </summary>
[DexNative]
internal static extern Type LongType();
/// <summary>
/// Type of java.lang.Float
/// </summary>
[DexNative]
internal static extern Type FloatType();
/// <summary>
/// Type of java.lang.Double
/// </summary>
[DexNative]
internal static extern Type DoubleType();
private static bool? DefaultBool = false;
private static char? DefaultChar = (char)0;
private static byte? DefaultByte = (byte)0;
private static short? DefaultShort = (short)0;
private static int? DefaultInt = (int)0;
private static long? DefaultLong = (long)0;
private static float? DefaultFloat = (float)0;
private static double? DefaultDouble= (double)0;
/// <summary>
/// Create an array type with the given component type with dimension 1.
/// </summary>
[Include]
public static Type Array(Type componentType)
{
return Java.Lang.Reflect.Array.NewInstance(componentType, 0).GetType();
}
/// <summary>
/// Create an array type with the given component type with multiple dimensions.
/// </summary>
[Include]
public static Type Array(Type componentType, int dimensions)
{
while (true)
{
var type = Java.Lang.Reflect.Array.NewInstance(componentType, 0).GetType();
if (dimensions == 1)
return type;
dimensions--;
componentType = type;
}
}
/// <summary>
/// this is used by the compiler, to find out in a generic class to which
/// runtime class to map a primitive, a nullable marker type or a generic proxy.
/// </summary>
[Include][DebuggerHidden]
internal static Type EnsureGenericRuntimeType(Type p)
{
Type t = EnsureBoxedType(p);
if (t != p) return t;
return NullableReflection.GetUnderlyingTypeForMarked(p)
?? GenericInstanceFactory.GetGenericTypeDefinition(p)
?? p;
}
/// <summary>
/// this is used by the compiler, to find out in a generic class to which
/// runtime class to map a primitive, a nullable marker type or a generic proxy.
/// </summary>
[Include][DebuggerHidden]
internal static Type GetGenericInstanceType(Type baseType, Type[] genericParameters)
{
return GenericInstanceFactory.GetOrMakeGenericInstanceType(baseType, genericParameters);
}
[Include][DebuggerHidden]
internal static Type GetGenericInstanceType(Type baseType, Type gp1)
{
return GenericInstanceFactory.GetOrMakeGenericInstanceType(baseType, gp1, null, null, null);
}
[Include][DebuggerHidden]
internal static Type GetGenericInstanceType(Type baseType, Type gp1, Type gp2)
{
return GenericInstanceFactory.GetOrMakeGenericInstanceType(baseType, gp1, gp2, null, null);
}
[Include][DebuggerHidden]
internal static Type GetGenericInstanceType(Type baseType, Type gp1, Type gp2, Type gp3)
{
return GenericInstanceFactory.GetOrMakeGenericInstanceType(baseType, gp1, gp2, gp3, null);
}
[Include][DebuggerHidden]
internal static Type GetGenericInstanceType(Type baseType, Type gp1, Type gp2, Type gp3, Type gp4)
{
return GenericInstanceFactory.GetOrMakeGenericInstanceType(baseType, gp1, gp2, gp3, gp4);
}
/// <summary>
/// Construct a MethodInfo for the given method.
/// </summary>
/// <param name="declaringType">The declaring type. For generic classes, this is not the proxy type.</param>
/// <param name="methodName"></param>
/// <param name="parameters">this includes all generic parameters.</param>
/// <param name="genericInstanceTypeParameters"></param>
/// <param name="genericMethodParameters"></param>
/// <returns></returns>
[Include(TypeCondition = typeof(MulticastDelegate))]
internal static MethodInfo GetMethodInfo(Type declaringType, string methodName, Type[] parameters, Type[] genericInstanceTypeParameters, Type[] genericMethodParameters)
{
// TODO: make this correctly work with methods taking generic parameters as well.
var javaMethod = declaringType.JavaGetDeclaredMethod(methodName, parameters);
string possibleExplicitInterfacePrefix = declaringType.JavaIsInterface() ? declaringType.GetSimpleName() + "_" : null;
return new MethodInfo(javaMethod, declaringType, possibleExplicitInterfacePrefix);
}
public static Type EnsurePrimitiveType(Type p)
{
return p == BooleanType() ? typeof(bool)
: p == CharacterType() ? typeof(char)
: p == ByteType() ? typeof(byte)
: p == ShortType() ? typeof(short)
: p == IntegerType() ? typeof(int)
: p == LongType() ? typeof(long)
: p == FloatType() ? typeof(float)
: p == DoubleType() ? typeof(double)
: p;
}
public static Type EnsureBoxedType(Type p)
{
return p == typeof(bool) ? BooleanType()
: p == typeof(char) ? CharacterType()
: p == typeof(byte) ? ByteType()
: p == typeof(short) ? ShortType()
: p == typeof(int) ? IntegerType()
: p == typeof(long) ? LongType()
: p == typeof(float) ? FloatType()
: p == typeof(double)? DoubleType()
: p;
}
internal static object GetPrimitiveDefault(Type p)
{
return p == typeof(bool) ? DefaultBool
: p == typeof(char) ? DefaultChar
: p == typeof(byte) ? DefaultByte
: p == typeof(short) ? DefaultShort
: p == typeof(int) ? DefaultInt
: p == typeof(long) ? DefaultLong
: p == typeof(float) ? DefaultFloat
: p == typeof(double) ? DefaultDouble
: (object) null;
}
public static bool IsBoxedType(Type type)
{
return type == BooleanType()
|| type == ByteType()
|| type == ShortType()
|| type == IntegerType()
|| type == LongType()
|| type == FloatType()
|| type == DoubleType()
|| type == CharacterType();
}
//internal static JavaField[] GetFields(Type type, BindingFlags flags)
//{
// if (((flags & BindingFlags.DeclaredOnly) != 0))
// return type.JavaGetDeclaredFields().Where(x => Matches(x.GetModifiers(), flags));
// if (((flags & BindingFlags.NonPublic) == 0))
// return type.JavaGetFields().Where(x => Matches(x.GetModifiers(), flags));
// ArrayList<JavaField> ret = new ArrayList<JavaField>();
// while (type != null)
// {
// var fields = type.JavaGetDeclaredFields();
// for (int i = 0; i < fields.Length; ++i)
// {
// var javaField = fields[i];
// if (Matches(javaField.GetModifiers(), flags))
// ret.Add(javaField);
// }
// type = type.GetSuperclass();
// }
// return ret.ToArray((JavaField[])Java.Lang.Reflect.Array.NewInstance(typeof(JavaField), ret.Size()));
//}
//internal static JavaMethod[] GetMethods(Type type, BindingFlags flags)
//{
// if (((flags & BindingFlags.DeclaredOnly) != 0))
// return type.JavaGetDeclaredMethods().Where(x => Matches(x.GetModifiers(), flags));
// if (((flags & BindingFlags.NonPublic) == 0))
// return type.JavaGetMethods().Where(x => Matches(x.GetModifiers(), flags));
// ArrayList<JavaMethod> ret = new ArrayList<JavaMethod>();
// while (type != null)
// {
// var methods = type.JavaGetDeclaredMethods();
// for (int i = 0; i < methods.Length; ++i)
// {
// var javaMethod = methods[i];
// if (Matches(javaMethod.GetModifiers(), flags))
// ret.Add(javaMethod);
// }
// type = type.GetSuperclass();
// }
// return ret.ToArray((JavaMethod[])Java.Lang.Reflect.Array.NewInstance(typeof(JavaMethod), ret.Size()));
//}
/// <summary>
/// Do the given modifiers of a member match the given binding flags?
/// </summary>
internal static bool Matches(int modifiers, BindingFlags flags)
{
// Exclude instance members?
if (((flags & BindingFlags.Instance) == 0) && !Modifier.IsStatic(modifiers)) return false;
// Exclude static members?
if (((flags & BindingFlags.Static) == 0) && Modifier.IsStatic(modifiers)) return false;
// Exclude public members?
if (((flags & BindingFlags.Public) == 0) && Modifier.IsPublic(modifiers)) return false;
// Exclude nonpublic members?
if (((flags & BindingFlags.NonPublic)== 0) && !Modifier.IsPublic(modifiers)) return false;
return true;
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* 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 CS0420: 'MindTouch.Dream.TaskTimer._status': a reference to a volatile field will not be treated as volatile
#pragma warning disable 420
using System;
using System.Threading;
using MindTouch.Tasking;
// TODO (steveb): change namespace to MindTouch.Tasking
namespace MindTouch.Dream {
/// <summary>
/// Possible <see cref="TaskTimer"/> states
/// </summary>
public enum TaskTimerStatus {
/// <summary>
/// The timer has completed.
/// </summary>
Done,
/// <summary>
/// The timer is pending execution.
/// </summary>
Pending,
/// <summary>
/// The timer is queued for later execution.
/// </summary>
Queued,
/// <summary>
/// The timer is locked.
/// </summary>
Locked
}
/// <summary>
/// Provides a mechanism for invoking an action at future time.
/// </summary>
public class TaskTimer {
//--- Constants ---
internal const double QUEUE_CUTOFF = 30;
internal const double QUEUE_RESCAN = 25;
//--- Class Fields ---
private static int _retries;
//--- Class Properties ---
/// <summary>
/// Number of times the timer has retried a state change.
/// </summary>
public static int Retries { get { return _retries; } }
//--- Class Methods ---
/// <summary>
/// This method is obsolete. Use <see cref="TaskTimerFactory.New(System.DateTime,System.Action{MindTouch.Dream.TaskTimer},object,MindTouch.Tasking.TaskEnv)"/> instead.
/// </summary>
/// <param name="when"></param>
/// <param name="handler"></param>
/// <param name="state"></param>
/// <param name="env"></param>
/// <returns></returns>
[Obsolete("New(DateTime, Action<TaskTimer>, object, TaskEnv) is obsolete. Use TaskTimerFactory instead.")]
public static TaskTimer New(DateTime when, Action<TaskTimer> handler, object state, TaskEnv env) {
return TaskTimerFactory.Current.New(when, handler, state, env);
}
/// <summary>
/// This methods is obsolete. Use <see cref="TaskTimerFactory.New(System.TimeSpan,System.Action{MindTouch.Dream.TaskTimer},object,MindTouch.Tasking.TaskEnv)"/> instead.
/// </summary>
/// <param name="when"></param>
/// <param name="handler"></param>
/// <param name="state"></param>
/// <param name="env"></param>
/// <returns></returns>
[Obsolete("New(TimeSpan, Action<TaskTimer>, object, TaskEnv) is obsolete. Use TaskTimerFactory instead.")]
public static TaskTimer New(TimeSpan when, Action<TaskTimer> handler, object state, TaskEnv env) {
return TaskTimerFactory.Current.New(when, handler, state, env);
}
/// <summary>
/// This method is obsolete. Use <see cref="TaskTimerFactory.Shutdown()"/> instead.
/// </summary>
[Obsolete("Shutdown() is obsolete. Use TaskTimerFactory instead.")]
public static void Shutdown() {
TaskTimerFactory.Current.Shutdown();
}
//--- Fields ---
/// <summary>
/// State object.
/// </summary>
public readonly object State;
internal TaskEnv Env = null;
private readonly ITaskTimerOwner _owner;
private volatile int _status = (int)TaskTimerStatus.Done;
private readonly Action<TaskTimer> _handler;
private DateTime _when;
//--- Constructors ---
internal TaskTimer(ITaskTimerOwner owner, Action<TaskTimer> handler, object state) {
if(handler == null) {
throw new ArgumentNullException("handler");
}
_owner = owner;
this.State = state;
_handler = handler;
}
/// <summary>
/// This constructor is obsolete. Use <see cref="TaskTimerFactory.New(System.Action{MindTouch.Dream.TaskTimer},object)"/> instead.
/// </summary>
/// <param name="handler"></param>
/// <param name="state"></param>
[Obsolete("TaskTimer(Action<TaskTimer>, object) is obsolete. Use TaskTimerFactory instead.")]
public TaskTimer(Action<TaskTimer> handler, object state) : this(TaskTimerFactory.Current, handler, state) { }
//--- Properties ---
/// <summary>
/// The time when the timer is scheduled to fire.
/// </summary>
public DateTime When { get { return _when; } }
/// <summary>
/// Timer status.
/// </summary>
public TaskTimerStatus Status { get { return (TaskTimerStatus)_status; } }
/// <summary>
/// The action that will be invoked at fire time.
/// </summary>
public Action<TaskTimer> Handler { get { return _handler; } }
//--- Methods ---
/// <summary>
/// Change when the timer will execute.
/// </summary>
/// <param name="timespan">The relative time.</param>
/// <param name="env">The environment to use for invocation.</param>
public void Change(TimeSpan timespan, TaskEnv env) {
if(timespan != TimeSpan.MaxValue) {
Change(GlobalClock.UtcNow.Add(timespan), env);
} else {
Change(DateTime.MaxValue, env);
}
}
/// <summary>
/// Change when the timer will execute.
/// </summary>
/// <param name="when">The absolute time.</param>
/// <param name="env">The environment to use for invocation.</param>
public void Change(DateTime when, TaskEnv env) {
DateTime now = GlobalClock.UtcNow;
// determine new status
int next;
if(when <= now.AddSeconds(QUEUE_CUTOFF)) {
next = (int)TaskTimerStatus.Queued;
} else if(when < DateTime.MaxValue) {
next = (int)TaskTimerStatus.Pending;
} else {
next = (int)TaskTimerStatus.Done;
}
// ensure we have a behavior if we need one and we don't if we do not
if(next != (int)TaskTimerStatus.Done) {
if(env == null) {
throw new ArgumentNullException("env");
}
} else {
env = null;
}
// attempt to change current status
retry:
int current;
switch(_status) {
case (int)TaskTimerStatus.Done:
// nothing to do
break;
case (int)TaskTimerStatus.Pending:
// attempt to remove timer from pending list
current = Interlocked.CompareExchange(ref _status, (int)TaskTimerStatus.Done, (int)TaskTimerStatus.Pending);
switch(current) {
case (int)TaskTimerStatus.Done:
// nothing to do
break;
case (int)TaskTimerStatus.Pending:
// remove timer from pending list
_owner.RemoveFromPending(this);
break;
case (int)TaskTimerStatus.Queued:
// we changed states; retry
Interlocked.Increment(ref _retries);
goto retry;
case (int)TaskTimerStatus.Locked:
// somebody else is already changing the timer; no need to compete
return;
}
break;
case (int)TaskTimerStatus.Queued:
// attempto remove timer from queue
current = Interlocked.CompareExchange(ref _status, (int)TaskTimerStatus.Done, (int)TaskTimerStatus.Queued);
switch(current) {
case (int)TaskTimerStatus.Done:
// nothing to do
break;
case (int)TaskTimerStatus.Pending:
// we changed states; retry
Interlocked.Increment(ref _retries);
goto retry;
case (int)TaskTimerStatus.Queued:
// remove timer from queue
_owner.RemoveFromQueue(this);
break;
case (int)TaskTimerStatus.Locked:
// somebody else is already changing the timer; no need to compete
return;
}
break;
case (int)TaskTimerStatus.Locked:
// somebody else is already changing the timer; no need to compete
return;
}
// register timer according to new status
if(Interlocked.CompareExchange(ref _status, (int)TaskTimerStatus.Locked, (int)TaskTimerStatus.Done) == (int)TaskTimerStatus.Done) {
_when = when;
switch(next) {
case (int)TaskTimerStatus.Done:
// release Task Environment
if(Env != null) {
Env.Release();
}
Env = null;
Interlocked.Exchange(ref _status, next);
return;
case (int)TaskTimerStatus.Pending:
// add timer to pending list
_owner.AddToPending(this, env, (TaskTimerStatus)next);
break;
case (int)TaskTimerStatus.Queued:
// add timer to active queue
_owner.AddToQueue(this, env, (TaskTimerStatus)next);
break;
case (int)TaskTimerStatus.Locked:
Interlocked.Exchange(ref _status, (int)TaskTimerStatus.Done);
throw new InvalidOperationException("should never happen");
}
}
}
/// <summary>
/// Cancel the scheduled invocation.
/// </summary>
public void Cancel() {
Change(DateTime.MaxValue, (TaskEnv)null);
}
internal bool TryLockPending() {
return (Interlocked.CompareExchange(ref _status, (int)TaskTimerStatus.Locked, (int)TaskTimerStatus.Pending) == (int)TaskTimerStatus.Pending);
}
internal bool TryLockQueued() {
return (Interlocked.CompareExchange(ref _status, (int)TaskTimerStatus.Locked, (int)TaskTimerStatus.Queued) == (int)TaskTimerStatus.Queued);
}
internal bool TryQueuePending() {
return (Interlocked.CompareExchange(ref _status, (int)TaskTimerStatus.Queued, (int)TaskTimerStatus.Pending) == (int)TaskTimerStatus.Pending);
}
internal void Execute(TaskEnv env) {
env.Invoke(_handler, this);
}
internal void ExecuteNow(TaskEnv env) {
env.InvokeNow(() => _handler(this));
}
internal void SetStatus(TaskTimerStatus status) {
Interlocked.Exchange(ref _status, (int)status);
}
}
}
| |
using J2N.Runtime.CompilerServices;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// A <see cref="CompositeReader"/> which reads multiple, parallel indexes. Each index added
/// must have the same number of documents, and exactly the same hierarchical subreader structure,
/// but typically each contains different fields. Deletions are taken from the first reader.
/// Each document contains the union of the fields of all
/// documents with the same document number. When searching, matches for a
/// query term are from the first index added that has the field.
///
/// <para/>This is useful, e.g., with collections that have large fields which
/// change rarely and small fields that change more frequently. The smaller
/// fields may be re-indexed in a new index and both indexes may be searched
/// together.
///
/// <para/><strong>Warning:</strong> It is up to you to make sure all indexes
/// are created and modified the same way. For example, if you add
/// documents to one index, you need to add the same documents in the
/// same order to the other indexes. <em>Failure to do so will result in
/// undefined behavior</em>.
/// A good strategy to create suitable indexes with <see cref="IndexWriter"/> is to use
/// <see cref="LogDocMergePolicy"/>, as this one does not reorder documents
/// during merging (like <see cref="TieredMergePolicy"/>) and triggers merges
/// by number of documents per segment. If you use different <see cref="MergePolicy"/>s
/// it might happen that the segment structure of your index is no longer predictable.
/// </summary>
public class ParallelCompositeReader : BaseCompositeReader<IndexReader>
{
private readonly bool closeSubReaders;
private readonly ISet<IndexReader> completeReaderSet = new JCG.HashSet<IndexReader>(IdentityEqualityComparer<IndexReader>.Default);
// LUCENENET specific - optimized empty array creation
private static readonly IndexReader[] EMPTY_INDEXREADERS =
#if FEATURE_ARRAYEMPTY
Array.Empty<IndexReader>();
#else
new IndexReader[0];
#endif
/// <summary>
/// Create a <see cref="ParallelCompositeReader"/> based on the provided
/// readers; auto-disposes the given <paramref name="readers"/> on <see cref="IndexReader.Dispose()"/>.
/// </summary>
public ParallelCompositeReader(params CompositeReader[] readers)
: this(true, readers)
{
}
/// <summary>
/// Create a <see cref="ParallelCompositeReader"/> based on the provided
/// <paramref name="readers"/>.
/// </summary>
public ParallelCompositeReader(bool closeSubReaders, params CompositeReader[] readers)
: this(closeSubReaders, readers, readers)
{
}
/// <summary>
/// Expert: create a <see cref="ParallelCompositeReader"/> based on the provided
/// <paramref name="readers"/> and <paramref name="storedFieldReaders"/>; when a document is
/// loaded, only <paramref name="storedFieldReaders"/> will be used.
/// </summary>
public ParallelCompositeReader(bool closeSubReaders, CompositeReader[] readers, CompositeReader[] storedFieldReaders)
: base(PrepareSubReaders(readers, storedFieldReaders))
{
this.closeSubReaders = closeSubReaders;
completeReaderSet.UnionWith(readers);
completeReaderSet.UnionWith(storedFieldReaders);
// update ref-counts (like MultiReader):
if (!closeSubReaders)
{
foreach (IndexReader reader in completeReaderSet)
{
reader.IncRef();
}
}
// finally add our own synthetic readers, so we close or decRef them, too (it does not matter what we do)
completeReaderSet.UnionWith(GetSequentialSubReaders());
}
private static IndexReader[] PrepareSubReaders(CompositeReader[] readers, CompositeReader[] storedFieldsReaders)
{
if (readers.Length == 0)
{
if (storedFieldsReaders.Length > 0)
{
throw new ArgumentException("There must be at least one main reader if storedFieldsReaders are used.");
}
// LUCENENET: Optimized empty string array creation
return EMPTY_INDEXREADERS;
}
else
{
IList<IndexReader> firstSubReaders = readers[0].GetSequentialSubReaders();
// check compatibility:
int maxDoc = readers[0].MaxDoc, noSubs = firstSubReaders.Count;
int[] childMaxDoc = new int[noSubs];
bool[] childAtomic = new bool[noSubs];
for (int i = 0; i < noSubs; i++)
{
IndexReader r = firstSubReaders[i];
childMaxDoc[i] = r.MaxDoc;
childAtomic[i] = r is AtomicReader;
}
Validate(readers, maxDoc, childMaxDoc, childAtomic);
Validate(storedFieldsReaders, maxDoc, childMaxDoc, childAtomic);
// hierarchically build the same subreader structure as the first CompositeReader with Parallel*Readers:
IndexReader[] subReaders = new IndexReader[noSubs];
for (int i = 0; i < subReaders.Length; i++)
{
if (firstSubReaders[i] is AtomicReader)
{
AtomicReader[] atomicSubs = new AtomicReader[readers.Length];
for (int j = 0; j < readers.Length; j++)
{
atomicSubs[j] = (AtomicReader)readers[j].GetSequentialSubReaders()[i];
}
AtomicReader[] storedSubs = new AtomicReader[storedFieldsReaders.Length];
for (int j = 0; j < storedFieldsReaders.Length; j++)
{
storedSubs[j] = (AtomicReader)storedFieldsReaders[j].GetSequentialSubReaders()[i];
}
// We pass true for closeSubs and we prevent closing of subreaders in doClose():
// By this the synthetic throw-away readers used here are completely invisible to ref-counting
subReaders[i] = new ParallelAtomicReaderAnonymousInnerClassHelper(atomicSubs, storedSubs);
}
else
{
Debug.Assert(firstSubReaders[i] is CompositeReader);
CompositeReader[] compositeSubs = new CompositeReader[readers.Length];
for (int j = 0; j < readers.Length; j++)
{
compositeSubs[j] = (CompositeReader)readers[j].GetSequentialSubReaders()[i];
}
CompositeReader[] storedSubs = new CompositeReader[storedFieldsReaders.Length];
for (int j = 0; j < storedFieldsReaders.Length; j++)
{
storedSubs[j] = (CompositeReader)storedFieldsReaders[j].GetSequentialSubReaders()[i];
}
// We pass true for closeSubs and we prevent closing of subreaders in doClose():
// By this the synthetic throw-away readers used here are completely invisible to ref-counting
subReaders[i] = new ParallelCompositeReaderAnonymousInnerClassHelper(compositeSubs, storedSubs);
}
}
return subReaders;
}
}
private class ParallelAtomicReaderAnonymousInnerClassHelper : ParallelAtomicReader
{
public ParallelAtomicReaderAnonymousInnerClassHelper(Lucene.Net.Index.AtomicReader[] atomicSubs, Lucene.Net.Index.AtomicReader[] storedSubs)
: base(true, atomicSubs, storedSubs)
{
}
protected internal override void DoClose()
{
}
}
private class ParallelCompositeReaderAnonymousInnerClassHelper : ParallelCompositeReader
{
public ParallelCompositeReaderAnonymousInnerClassHelper(Lucene.Net.Index.CompositeReader[] compositeSubs, Lucene.Net.Index.CompositeReader[] storedSubs)
: base(true, compositeSubs, storedSubs)
{
}
protected internal override void DoClose()
{
}
}
private static void Validate(CompositeReader[] readers, int maxDoc, int[] childMaxDoc, bool[] childAtomic)
{
for (int i = 0; i < readers.Length; i++)
{
CompositeReader reader = readers[i];
IList<IndexReader> subs = reader.GetSequentialSubReaders();
if (reader.MaxDoc != maxDoc)
{
throw new ArgumentException("All readers must have same MaxDoc: " + maxDoc + "!=" + reader.MaxDoc);
}
int noSubs = subs.Count;
if (noSubs != childMaxDoc.Length)
{
throw new ArgumentException("All readers must have same number of subReaders");
}
for (int subIDX = 0; subIDX < noSubs; subIDX++)
{
IndexReader r = subs[subIDX];
if (r.MaxDoc != childMaxDoc[subIDX])
{
throw new ArgumentException("All readers must have same corresponding subReader maxDoc");
}
if (!(childAtomic[subIDX] ? (r is AtomicReader) : (r is CompositeReader)))
{
throw new ArgumentException("All readers must have same corresponding subReader types (atomic or composite)");
}
}
}
}
protected internal override void DoClose()
{
lock (this)
{
IOException ioe = null;
foreach (IndexReader reader in completeReaderSet)
{
try
{
if (closeSubReaders)
{
reader.Dispose();
}
else
{
reader.DecRef();
}
}
catch (IOException e)
{
if (ioe == null)
{
ioe = e;
}
}
}
// throw the first exception
if (ioe != null)
{
throw ioe;
}
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Globalization;
using System.Reflection;
using System.Windows.Forms;
using Skybound.ComponentModel;
namespace Skybound.VisualTips
{
[System.ComponentModel.TypeConverter(typeof(Skybound.VisualTips.VisualTipConverter))]
[System.ComponentModel.Editor(typeof(Skybound.VisualTips.VisualTipEditor), typeof(System.Drawing.Design.UITypeEditor))]
public class VisualTip : Skybound.ComponentModel.IPropertyListContainer, System.ComponentModel.ICustomTypeDescriptor
{
private bool _DefaultLanguageShouldSerialize;
private Skybound.VisualTips.VisualTipProvider _Provider;
private System.Drawing.Rectangle _RelativeToolArea;
private object CurrentComponent;
private System.Windows.Forms.Control CurrentControl;
private bool IsHelpRequestedHandled;
private Skybound.ComponentModel.PropertyList Properties;
[System.ComponentModel.AmbientValue(System.Windows.Forms.Shortcut.CtrlShiftX)]
[System.ComponentModel.Description("The keyboard shortcut that may be pressed to raise the AccessKeyPressed event when the tip is displayed.")]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.Localizable(true)]
[Skybound.ComponentModel.PropertyListValue]
public System.Windows.Forms.Shortcut AccessKey
{
get
{
return (System.Windows.Forms.Shortcut)Properties.GetValue("AccessKey", Provider == null ? 112 : (int)Provider.AccessKey);
}
set
{
Properties.SetValue("AccessKey", value, Provider == null ? 112 : (int)Provider.AccessKey);
}
}
[System.ComponentModel.Localizable(true)]
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.Description("Specifies whether the tip will be displayed.")]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
public bool Active
{
get
{
return (bool)Properties.GetValue("Active", true);
}
set
{
Properties.SetValue("Active", value, true);
}
}
[System.ComponentModel.Browsable(false)]
[System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
private bool DefaultLanguageShouldSerialize
{
get
{
return _DefaultLanguageShouldSerialize;
}
set
{
_DefaultLanguageShouldSerialize = value;
}
}
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.Description("The message displayed above the text when the tool is disabled.")]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.AmbientValue(null)]
public string DisabledMessage
{
get
{
return (string)Properties.GetValue("DisabledMessage", Provider == null ? "" : Provider.DisabledMessage);
}
set
{
Properties.SetValue("DisabledMessage", value == null ? "" : value, Provider == null ? "" : Provider.DisabledMessage);
}
}
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.AmbientValue(null)]
[System.ComponentModel.Description("The alternate text displayed when the tool is disabled. When this property is blank, the regular text is always used.")]
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.Localizable(true)]
public string DisabledText
{
get
{
return (string)Properties.GetValue("DisabledText", "");
}
set
{
Properties.SetValue("DisabledText", value == null ? "" : value, "");
}
}
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.Description("Determines where a visual tip is displayed in relation to the tool area.")]
[System.ComponentModel.AmbientValue(Skybound.VisualTips.VisualTipDisplayPosition.Bottom)]
public Skybound.VisualTips.VisualTipDisplayPosition DisplayPosition
{
get
{
return (Skybound.VisualTips.VisualTipDisplayPosition)Properties.GetValue("DisplayPosition", VisualTipDisplayPosition.Bottom); //(Provider != null) && Provider.DisplayPosition != null);
}
set
{
Properties.SetValue("DisplayPosition", value, (VisualTipDisplayPosition) (-1));
}
}
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.Description("When this property is false, the disabled message and text and displayed on the tip.")]
public bool Enabled
{
get
{
return (bool)Properties.GetValue("Enabled", EnabledDefaultValue);
}
set
{
Properties.SetValue("Enabled", value, EnabledDefaultValue);
}
}
private bool EnabledDefaultValue
{
get
{
object obj;
if (TryGetValue("Enabled", typeof(bool), out obj))
return (bool)obj;
if (CurrentControl == null)
return true;
return CurrentControl.Enabled;
}
}
[System.ComponentModel.Description("The font used to display the tip text.")]
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.AmbientValue(null)]
public System.Drawing.Font Font
{
get
{
return (System.Drawing.Font)Properties.GetValue("Font", FontDefaultValue);
}
set
{
Properties.SetValue("Font", value == null ? FontDefaultValue : value, FontDefaultValue);
}
}
private System.Drawing.Font FontDefaultValue
{
get
{
object obj;
if (TryGetValue("Font", typeof(System.Drawing.Font), out obj))
return (System.Drawing.Font)obj;
if (CurrentControl == null)
return System.Windows.Forms.Control.DefaultFont;
return CurrentControl.Font;
}
}
[System.ComponentModel.Editor(typeof(Skybound.Drawing.Design.IconImageEditor), typeof(System.Drawing.Design.UITypeEditor))]
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.Description("The image displayed in the footer.")]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.AmbientValue(null)]
public System.Drawing.Image FooterImage
{
get
{
return (System.Drawing.Image)Properties.GetValue("FooterImage", Provider == null ? null : Provider.FooterImage);
}
set
{
Properties.SetValue("FooterImage", value, Provider == null ? null : Provider.FooterImage);
}
}
[System.ComponentModel.AmbientValue(null)]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.Localizable(true)]
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.Description("The text displayed in the footer.")]
public string FooterText
{
get
{
return (string)Properties.GetValue("FooterText", Provider == null ? "" : Provider.FooterText);
}
set
{
Properties.SetValue("FooterText", value == null ? "" : value, Provider == null ? "" : Provider.FooterText);
}
}
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.Description("Specifies whether the footer text and image are hidden on this tip.")]
public bool HideFooter
{
get
{
return (bool)Properties.GetValue("HideFooter", false);
}
set
{
Properties.SetValue("HideFooter", value, false);
}
}
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.Description("The image displayed beside the text.")]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.Editor(typeof(Skybound.Drawing.Design.IconImageEditor), typeof(System.Drawing.Design.UITypeEditor))]
[System.ComponentModel.Localizable(true)]
public System.Drawing.Image Image
{
get
{
return (System.Drawing.Image)Properties.GetValue("Image", null);
}
set
{
if ((value != null) && ((value.Width > 128) || (value.Height > 128)))
throw new System.InvalidOperationException("The maximum image size is 128x128.");
Properties.SetValue("Image", value, null);
}
}
private bool IsDefaultLanguage
{
get
{
return Skybound.VisualTips.VisualTip.GetDesignModeCulture(Provider) == System.Globalization.CultureInfo.InvariantCulture;
}
}
[System.ComponentModel.Description("The maximum width of the tip.")]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.AmbientValue(256)]
[Skybound.ComponentModel.PropertyListValue]
public int MaximumWidth
{
get
{
return (int)Properties.GetValue("MaximumWidth", Provider == null ? 256 : Provider.MaximumWidth);
}
set
{
Properties.SetValue("MaximumWidth", System.Math.Max(value, 192), Provider == null ? 256 : Provider.MaximumWidth);
}
}
[System.ComponentModel.Browsable(false)]
public Skybound.VisualTips.VisualTipProvider Provider
{
get
{
return _Provider;
}
}
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.Description("Whether the tip text is displayed using a right-to-left reading order.")]
[System.ComponentModel.Localizable(true)]
public System.Windows.Forms.RightToLeft RightToLeft
{
get
{
return (System.Windows.Forms.RightToLeft)Properties.GetValue("RightToLeft", RightToLeftDefaultValue);
}
set
{
Properties.SetValue("RightToLeft", value, RightToLeftDefaultValue);
}
}
private System.Windows.Forms.RightToLeft RightToLeftDefaultValue
{
get
{
object obj;
if (TryGetValue("RightToLeft", typeof(System.Windows.Forms.RightToLeft), out obj))
return (System.Windows.Forms.RightToLeft)obj;
if (CurrentControl == null)
return System.Windows.Forms.RightToLeft.No;
return CurrentControl.RightToLeft;
}
}
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.Description("The shortcut key displayed beside the title, if it is not Shortcut.None.")]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
public System.Windows.Forms.Shortcut Shortcut
{
get
{
return (System.Windows.Forms.Shortcut)Properties.GetValue("Shortcut", 0);
}
set
{
Properties.SetValue("Shortcut", value, 0);
}
}
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.Description("The text displayed on the tooltip.")]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.Localizable(true)]
public string Text
{
get
{
return (string)Properties.GetValue("Text", "");
}
set
{
Properties.SetValue("Text", value == null ? "" : value, "");
}
}
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.Description("The title displayed in bold at the top of the tip.")]
public string Title
{
get
{
return (string)Properties.GetValue("Title", "");
}
set
{
Properties.SetValue("Title", value == null ? "" : value, "");
}
}
[System.ComponentModel.Localizable(true)]
[System.ComponentModel.RefreshProperties(System.ComponentModel.RefreshProperties.Repaint)]
[System.ComponentModel.AmbientValue(null)]
[Skybound.ComponentModel.PropertyListValue]
[System.ComponentModel.Description("The image displayed beside the title.")]
[System.ComponentModel.Editor(typeof(Skybound.Drawing.Design.IconImageEditor), typeof(System.Drawing.Design.UITypeEditor))]
public System.Drawing.Image TitleImage
{
get
{
return (System.Drawing.Image)Properties.GetValue("TitleImage", Provider == null ? null : Provider.TitleImage);
}
set
{
if ((value != null) && ((value.Width > 128) || (value.Height > 128)))
throw new System.InvalidOperationException("The maximum image size is 128x128.");
Properties.SetValue("TitleImage", value, Provider == null ? null : Provider.TitleImage);
}
}
public VisualTip()
{
Properties = new Skybound.ComponentModel.PropertyList();
Properties.PropertyChanging += new System.ComponentModel.PropertyChangedEventHandler(Properties_PropertyChanging);
Properties.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Properties_PropertyChanged);
}
public VisualTip(string text) : this(text, null, null, null, System.Windows.Forms.Shortcut.None, false)
{
}
public VisualTip(string text, string title) : this(text, title, null, null, System.Windows.Forms.Shortcut.None, false)
{
}
public VisualTip(string text, string title, System.Drawing.Image image) : this(text, title, image, null, System.Windows.Forms.Shortcut.None, false)
{
}
public VisualTip(string text, string title, System.Drawing.Image image, string disabledText, System.Windows.Forms.Shortcut shortcut, bool hideFooter)
{
Properties = new Skybound.ComponentModel.PropertyList();
Properties.PropertyChanging += new System.ComponentModel.PropertyChangedEventHandler(Properties_PropertyChanging);
Properties.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Properties_PropertyChanged);
Text = text;
Title = title;
Image = image;
DisabledText = disabledText;
Shortcut = shortcut;
HideFooter = hideFooter;
}
private void AddEventHandlers()
{
if ((Provider != null) && (CurrentControl != null) && (CurrentComponent == null) && (Provider.DisplayMode == Skybound.VisualTips.VisualTipDisplayMode.HelpRequested))
{
CurrentControl.KeyDown += new System.Windows.Forms.KeyEventHandler(CurrentControl_KeyDown);
CurrentControl.HelpRequested += new System.Windows.Forms.HelpEventHandler(CurrentControl_HelpRequested);
IsHelpRequestedHandled = true;
}
}
private void CurrentControl_HelpRequested(object sender, System.Windows.Forms.HelpEventArgs e)
{
if (System.Windows.Forms.Control.MouseButtons == System.Windows.Forms.MouseButtons.Left)
Provider.ShowTip(CurrentControl, Skybound.VisualTips.VisualTipDisplayOptions.HideOnMouseLeave | Skybound.VisualTips.VisualTipDisplayOptions.HideOnLostFocus);
e.Handled = true;
}
private void CurrentControl_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyData == System.Windows.Forms.Keys.F1)
{
Provider.ShowTip(CurrentControl, Skybound.VisualTips.VisualTipDisplayOptions.HideOnLostFocus);
e.Handled = true;
}
}
System.ComponentModel.AttributeCollection System.ComponentModel.ICustomTypeDescriptor.GetAttributes()
{
return System.ComponentModel.TypeDescriptor.GetAttributes(this, true);
}
string System.ComponentModel.ICustomTypeDescriptor.GetClassName()
{
return System.ComponentModel.TypeDescriptor.GetClassName(this, true);
}
string System.ComponentModel.ICustomTypeDescriptor.GetComponentName()
{
return System.ComponentModel.TypeDescriptor.GetComponentName(this, true);
}
System.ComponentModel.TypeConverter System.ComponentModel.ICustomTypeDescriptor.GetConverter()
{
return System.ComponentModel.TypeDescriptor.GetConverter(this, true);
}
System.ComponentModel.EventDescriptor System.ComponentModel.ICustomTypeDescriptor.GetDefaultEvent()
{
return System.ComponentModel.TypeDescriptor.GetDefaultEvent(this, true);
}
System.ComponentModel.PropertyDescriptor System.ComponentModel.ICustomTypeDescriptor.GetDefaultProperty()
{
return System.ComponentModel.TypeDescriptor.GetDefaultProperty(this, true);
}
object System.ComponentModel.ICustomTypeDescriptor.GetEditor(System.Type editorBaseType)
{
return System.ComponentModel.TypeDescriptor.GetEditor(this, editorBaseType, true);
}
System.ComponentModel.EventDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetEvents()
{
return System.ComponentModel.TypeDescriptor.GetEvents(this, true);
}
System.ComponentModel.EventDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetEvents(System.Attribute[] attributes)
{
return System.ComponentModel.TypeDescriptor.GetEvents(this, attributes, true);
}
System.ComponentModel.PropertyDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetProperties()
{
return null;// GetProperties(null);
}
System.ComponentModel.PropertyDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetProperties(System.Attribute[] attributes)
{
return Skybound.ComponentModel.PropertyList.GetProperties(this, attributes);
}
Skybound.ComponentModel.PropertyList Skybound.ComponentModel.IPropertyListContainer.GetPropertyList()
{
return Properties;
}
object System.ComponentModel.ICustomTypeDescriptor.GetPropertyOwner(System.ComponentModel.PropertyDescriptor pd)
{
return this;
}
internal System.Drawing.Rectangle GetRelativeToolArea()
{
return _RelativeToolArea;
}
internal void OnProviderDisplayModeChanged(System.EventArgs e)
{
RemoveEventHandlers();
AddEventHandlers();
}
private void Properties_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (IsDefaultLanguage)
DefaultLanguageShouldSerialize = Properties.ShouldSerialize();
}
private void Properties_PropertyChanging(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (!IsDefaultLanguage && !DefaultLanguageShouldSerialize)
throw new System.InvalidOperationException("New visual tips may not be created while the form is being localized. Set the Language property of the Form or UserControl to (Default) and create a tip in the default language before localizing it.");
}
private void RemoveEventHandlers()
{
if (IsHelpRequestedHandled)
{
CurrentControl.KeyDown -= new System.Windows.Forms.KeyEventHandler(CurrentControl_KeyDown);
CurrentControl.HelpRequested -= new System.Windows.Forms.HelpEventHandler(CurrentControl_HelpRequested);
IsHelpRequestedHandled = false;
}
}
internal void Reset()
{
Properties.Reset();
}
internal void SetProvider(Skybound.VisualTips.VisualTipProvider value)
{
RemoveEventHandlers();
_Provider = value;
CurrentControl = null;
CurrentComponent = null;
}
internal void SetRelativeToolArea(System.Drawing.Rectangle toolArea)
{
_RelativeToolArea = toolArea;
}
internal void SetTarget(System.Windows.Forms.Control control, object component)
{
CurrentControl = control;
CurrentComponent = component;
AddEventHandlers();
}
internal bool ShouldSerialize()
{
if (!DefaultLanguageShouldSerialize)
return Properties.ShouldSerialize();
return true;
}
private bool TryGetValue(string propertyName, System.Type propertyType, out object value)
{
if (CurrentComponent != null)
{
System.Reflection.PropertyInfo propertyInfo = CurrentComponent.GetType().GetProperty(propertyName);
if ((propertyInfo != null) && (propertyInfo.PropertyType == propertyType))
{
value = propertyInfo.GetValue(CurrentComponent, null);
return true;
}
}
value = null;
return false;
}
internal static System.Globalization.CultureInfo GetDesignModeCulture(System.ComponentModel.IComponent component)
{
if ((component != null) && (component.Site != null) && component.Site.DesignMode)
{
System.ComponentModel.Design.IDesignerHost idesignerHost = (System.ComponentModel.Design.IDesignerHost)component.Site.GetService(typeof(System.ComponentModel.Design.IDesignerHost));
System.ComponentModel.PropertyDescriptor propertyDescriptor = System.ComponentModel.TypeDescriptor.GetProperties(idesignerHost.RootComponent)["Language"];
if ((propertyDescriptor != null) && (propertyDescriptor.PropertyType == typeof(System.Globalization.CultureInfo)))
return propertyDescriptor.GetValue(idesignerHost.RootComponent) as System.Globalization.CultureInfo;
}
return System.Globalization.CultureInfo.InvariantCulture;
}
} // class VisualTip
}
| |
// 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;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Globalization.Tests
{
public class CompareInfoCompare
{
private static bool s_isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
// on windows hiragana characters sort after katakana. on ICU, it is the opposite
private static int s_expectedHiraganaToKatakanaCompare = s_isWindows ? 1 : -1;
// on windows, all halfwidth characters sort before fullwidth characters.
// on ICU, half and fullwidth characters that aren't in the "Halfwidth and fullwidth forms" block U+FF00-U+FFEF
// sort before the corresponding characters that are in the block U+FF00-U+FFEF
private static int s_expectedHalfToFullFormsComparison = s_isWindows ? -1 : 1;
private const string c_SoftHyphen = "\u00AD";
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test1() { TestOrd(CultureInfo.InvariantCulture, "\u3042", "\u30A1", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test2() { TestOrd(CultureInfo.InvariantCulture, "\u3042", "\u30A2", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test3() { TestOrd(CultureInfo.InvariantCulture, "\u3042", "\uFF71", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test4() { TestOrd(CultureInfo.InvariantCulture, "\u304D\u3083", "\u30AD\u30E3", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test5() { TestOrd(CultureInfo.InvariantCulture, "\u304D\u3083", "\u30AD\u3083", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test6() { TestOrd(CultureInfo.InvariantCulture, "\u304D \u3083", "\u30AD\u3083", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test7() { TestOrd(CultureInfo.InvariantCulture, "\u3044", "I", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test8() { TestOrd(CultureInfo.InvariantCulture, "a", "A", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test9() { TestOrd(CultureInfo.InvariantCulture, "a", "\uFF41", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test10() { TestOrd(CultureInfo.InvariantCulture, "ABCDE", "\uFF21\uFF22\uFF23\uFF24\uFF25", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test11() { TestOrd(CultureInfo.InvariantCulture, "ABCDE", "\uFF21\uFF22\uFF23D\uFF25", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test12() { TestOrd(CultureInfo.InvariantCulture, "ABCDE", "a\uFF22\uFF23D\uFF25", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test13() { TestOrd(CultureInfo.InvariantCulture, "ABCDE", "\uFF41\uFF42\uFF23D\uFF25", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test14() { TestOrd(CultureInfo.InvariantCulture, "\u6FA4", "\u6CA2", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test15() { TestOrd(CultureInfo.InvariantCulture, "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u30D6\u30D9\u30DC", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test16() { TestOrd(CultureInfo.InvariantCulture, "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u3076\u30D9\u30DC", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test17() { TestOrd(CultureInfo.InvariantCulture, "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u3076\u30D9\uFF8E\uFF9E", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test18() { TestOrd(CultureInfo.InvariantCulture, "\u3070\u3073\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u30D0\u30D3\u3076\u30D9\uFF8E\uFF9E", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test19() { TestOrd(CultureInfo.InvariantCulture, "\u3070\u3073\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\uFF8E\uFF9E", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test20() { TestOrd(CultureInfo.InvariantCulture, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\uFF8E\uFF9E", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test21() { TestOrd(CultureInfo.InvariantCulture, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u3079\uFF8E\uFF9E", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test22() { TestOrd(CultureInfo.InvariantCulture, "\u3070\u3073\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u30D6", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test23() { TestOrd(CultureInfo.InvariantCulture, "\u3071\u3074\u30D7\u307A", "\uFF8B\uFF9F\uFF8C\uFF9F", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test24() { TestOrd(CultureInfo.InvariantCulture, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u3070\uFF8E\uFF9E\u30D6", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test25() { TestOrd(CultureInfo.InvariantCulture, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C\u3079\u307C", "\u3079\uFF8E\uFF9E", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test26() { TestOrd(CultureInfo.InvariantCulture, "\u3070\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u30D6", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test27() { TestOrd(CultureInfo.InvariantCulture, "ABDDE", "D", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test28() { TestOrd(CultureInfo.InvariantCulture, "ABCDE", "\uFF43D\uFF25", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test29() { TestOrd(CultureInfo.InvariantCulture, "ABCDE", "\uFF43D", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test30() { TestOrd(CultureInfo.InvariantCulture, "ABCDE", "c", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test31() { TestOrd(CultureInfo.InvariantCulture, "\u3060", "\u305F", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test32() { TestOrd(CultureInfo.InvariantCulture, "\u3060", "\uFF80\uFF9E", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test33() { TestOrd(CultureInfo.InvariantCulture, "\u3060", "\u30C0", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test34() { TestOrd(CultureInfo.InvariantCulture, "\u30C7\u30BF\u30D9\u30B9", "\uFF83\uFF9E\uFF80\uFF8D\uFF9E\uFF7D", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test35() { TestOrd(CultureInfo.InvariantCulture, "\u30C7", "\uFF83\uFF9E", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test36() { TestOrd(CultureInfo.InvariantCulture, "\u30C7\u30BF", "\uFF83\uFF9E\uFF80", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test37() { TestOrd(CultureInfo.InvariantCulture, "\u30C7\u30BF\u30D9", "\uFF83\uFF9E\uFF80\uFF8D\uFF9E", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test38() { TestOrd(CultureInfo.InvariantCulture, "\u30BF", "\uFF80", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test39() { TestOrd(CultureInfo.InvariantCulture, "\uFF83\uFF9E\uFF70\uFF80\uFF8D\uFF9E\uFF70\uFF7D", "\u3067\u30FC\u305F\u3079\u30FC\u3059", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test40() { TestOrd(CultureInfo.InvariantCulture, "\u68EE\u9D0E\u5916", "\u68EE\u9DD7\u5916", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test41() { TestOrd(CultureInfo.InvariantCulture, "\u68EE\u9DD7\u5916", "\u68EE\u9DD7\u5916", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test42() { TestOrd(CultureInfo.InvariantCulture, "\u2019\u2019\u2019\u2019", "''''", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test43() { TestOrd(CultureInfo.InvariantCulture, "\u2019", "'", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test44() { TestOrd(CultureInfo.InvariantCulture, "", "'", -1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test45() { TestOrd(CultureInfo.InvariantCulture, "\u4E00", "\uFF11", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test46() { TestOrd(CultureInfo.InvariantCulture, "\u2160", "\uFF11", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test47() { TestOrd(CultureInfo.InvariantCulture, "0", "\uFF10", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test48() { TestOrd(CultureInfo.InvariantCulture, "10", "1\uFF10", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test49() { TestOrd(CultureInfo.InvariantCulture, "1\uFF10", "1\uFF10", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test50() { TestOrd(CultureInfo.InvariantCulture, "9999\uFF1910", "1\uFF10", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test51() { TestOrd(CultureInfo.InvariantCulture, "9999\uFF191010", "1\uFF10", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test52() { TestOrd(CultureInfo.InvariantCulture, "'\u3000'", "' '", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test53() { TestOrd(CultureInfo.InvariantCulture, "'\u3000'", "''", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test54() { TestOrd(CultureInfo.InvariantCulture, "\uFF1B", ";", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test55() { TestOrd(CultureInfo.InvariantCulture, "\uFF08", "(", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test56() { TestOrd(CultureInfo.InvariantCulture, "\u30FC", "\uFF70", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test57() { TestOrd(CultureInfo.InvariantCulture, "\u30FC", "\uFF0D", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test58() { TestOrd(CultureInfo.InvariantCulture, "\u30FC", "\u30FC", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test59() { TestOrd(CultureInfo.InvariantCulture, "\u30FC", "\u2015", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test60() { TestOrd(CultureInfo.InvariantCulture, "\u30FC", "\u2010", 1, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test61() { TestOrd(CultureInfo.InvariantCulture, "/", "\uFF0F", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test62() { TestOrd(CultureInfo.InvariantCulture, "'", "\uFF07", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test63() { TestOrd(CultureInfo.InvariantCulture, "\"", "\uFF02", 0, CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase); }
[Fact]
public void Test64() { Test(CultureInfo.InvariantCulture, "\u3042", "\u30A1", s_expectedHiraganaToKatakanaCompare, CompareOptions.None); }
[Fact]
public void Test65() { Test(CultureInfo.InvariantCulture, "\u3042", "\u30A2", s_expectedHiraganaToKatakanaCompare, CompareOptions.None); }
[Fact]
public void Test66() { Test(CultureInfo.InvariantCulture, "\u3042", "\uFF71", s_expectedHiraganaToKatakanaCompare, CompareOptions.None); }
[Fact]
public void Test67() { Test(CultureInfo.InvariantCulture, "\u304D\u3083", "\u30AD\u30E3", s_expectedHiraganaToKatakanaCompare, CompareOptions.None); }
[Fact]
public void Test68() { Test(CultureInfo.InvariantCulture, "\u304D\u3083", "\u30AD\u3083", s_expectedHiraganaToKatakanaCompare, CompareOptions.None); }
[Fact]
public void Test69() { Test(CultureInfo.InvariantCulture, "\u304D \u3083", "\u30AD\u3083", -1, CompareOptions.None); }
[Fact]
public void Test70() { Test(CultureInfo.InvariantCulture, "\u3044", "I", 1, CompareOptions.None); }
[Fact]
public void Test71() { Test(CultureInfo.InvariantCulture, "a", "A", -1, CompareOptions.None); }
[Fact]
public void Test72() { Test(CultureInfo.InvariantCulture, "a", "\uFF41", -1, CompareOptions.None); }
[Fact]
public void Test73() { Test(CultureInfo.InvariantCulture, "ABCDE", "\uFF21\uFF22\uFF23\uFF24\uFF25", -1, CompareOptions.None); }
[Fact]
public void Test74() { Test(CultureInfo.InvariantCulture, "ABCDE", "\uFF21\uFF22\uFF23D\uFF25", -1, CompareOptions.None); }
[Fact]
public void Test75() { Test(CultureInfo.InvariantCulture, new string('a', 5555), new string('a', 5554) + "b", -1, CompareOptions.None); }
[Fact]
public void Test76() { Test(CultureInfo.InvariantCulture, "ABCDE", "\uFF41\uFF42\uFF23D\uFF25", 1, CompareOptions.None); }
[Fact]
public void Test77() { Test(CultureInfo.InvariantCulture, "\u6FA4", "\u6CA2", 1, CompareOptions.None); }
[Fact]
public void Test78() { Test(CultureInfo.InvariantCulture, "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u30D6\u30D9\u30DC", s_expectedHiraganaToKatakanaCompare, CompareOptions.None); }
[Fact]
public void Test79() { Test(CultureInfo.InvariantCulture, "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u3076\u30D9\u30DC", s_expectedHiraganaToKatakanaCompare, CompareOptions.None); }
[Fact]
public void Test80() { Test(CultureInfo.InvariantCulture, "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u3076\u30D9\uFF8E\uFF9E", s_expectedHiraganaToKatakanaCompare, CompareOptions.None); }
[Fact]
public void Test81() { Test(CultureInfo.InvariantCulture, "\u3070\u3073\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u30D0\u30D3\u3076\u30D9\uFF8E\uFF9E", s_expectedHiraganaToKatakanaCompare, CompareOptions.None); }
[Fact]
public void Test82() { Test(CultureInfo.InvariantCulture, "\u3070\u3073\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\uFF8E\uFF9E", -1, CompareOptions.None); }
[Fact]
public void Test83() { Test(CultureInfo.InvariantCulture, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\uFF8E\uFF9E", -1, CompareOptions.None); }
[Fact]
public void Test84() { Test(CultureInfo.InvariantCulture, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u3079\uFF8E\uFF9E", -1, CompareOptions.None); }
[Fact]
public void Test85() { Test(CultureInfo.InvariantCulture, "\u3070\u3073\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u30D6", -1, CompareOptions.None); }
[Fact]
public void Test86() { Test(CultureInfo.InvariantCulture, "\u3071\u3074\u30D7\u307A", "\uFF8B\uFF9F\uFF8C\uFF9F", -1, CompareOptions.None); }
[Fact]
public void Test87() { Test(CultureInfo.InvariantCulture, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u3070\uFF8E\uFF9E\u30D6", 1, CompareOptions.None); }
[Fact]
public void Test88() { Test(CultureInfo.InvariantCulture, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C\u3079\u307C", "\u3079\uFF8E\uFF9E", -1, CompareOptions.None); }
[Fact]
public void Test89() { Test(CultureInfo.InvariantCulture, "\u3070\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u30D6", -1, CompareOptions.None); }
[Fact]
public void Test90() { Test(CultureInfo.InvariantCulture, "ABDDE", "D", -1, CompareOptions.None); }
[Fact]
public void Test91() { Test(CultureInfo.InvariantCulture, "ABCDE", "\uFF43D\uFF25", -1, CompareOptions.None); }
[Fact]
public void Test92() { Test(CultureInfo.InvariantCulture, "ABCDE", "\uFF43D", -1, CompareOptions.None); }
[Fact]
public void Test93() { Test(CultureInfo.InvariantCulture, "ABCDE", "c", -1, CompareOptions.None); }
[Fact]
public void Test94() { Test(CultureInfo.InvariantCulture, "\u3060", "\u305F", 1, CompareOptions.None); }
[Fact]
public void Test95() { Test(CultureInfo.InvariantCulture, "\u3060", "\uFF80\uFF9E", s_expectedHiraganaToKatakanaCompare, CompareOptions.None); }
[Fact]
public void Test96() { Test(CultureInfo.InvariantCulture, "\u3060", "\u30C0", s_expectedHiraganaToKatakanaCompare, CompareOptions.None); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test97() { Test(CultureInfo.InvariantCulture, "\u30C7\u30BF\u30D9\u30B9", "\uFF83\uFF9E\uFF80\uFF8D\uFF9E\uFF7D", 1, CompareOptions.None); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test98() { Test(CultureInfo.InvariantCulture, "\u30C7", "\uFF83\uFF9E", 1, CompareOptions.None); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test99() { Test(CultureInfo.InvariantCulture, "\u30C7\u30BF", "\uFF83\uFF9E\uFF80", 1, CompareOptions.None); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test100() { Test(CultureInfo.InvariantCulture, "\u30C7\u30BF\u30D9", "\uFF83\uFF9E\uFF80\uFF8D\uFF9E", 1, CompareOptions.None); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test101() { Test(CultureInfo.InvariantCulture, "\u30BF", "\uFF80", 1, CompareOptions.None); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test102() { Test(CultureInfo.InvariantCulture, "\uFF83\uFF9E\uFF70\uFF80\uFF8D\uFF9E\uFF70\uFF7D", "\u3067\u30FC\u305F\u3079\u30FC\u3059", -1, CompareOptions.None); }
[Fact]
public void Test103() { Test(CultureInfo.InvariantCulture, "\u68EE\u9D0E\u5916", "\u68EE\u9DD7\u5916", -1, CompareOptions.None); }
[Fact]
public void Test104() { Test(CultureInfo.InvariantCulture, "\u68EE\u9DD7\u5916", "\u68EE\u9DD7\u5916", 0, CompareOptions.None); }
[Fact]
public void Test105() { Test(CultureInfo.InvariantCulture, "\u2019\u2019\u2019\u2019", "''''", 1, CompareOptions.None); }
[Fact]
public void Test106() { Test(CultureInfo.InvariantCulture, "\u2019", "'", 1, CompareOptions.None); }
[Fact]
public void Test107() { Test(CultureInfo.InvariantCulture, "", "'", -1, CompareOptions.None); }
[Fact]
public void Test108() { Test(CultureInfo.InvariantCulture, "\u4E00", "\uFF11", 1, CompareOptions.None); }
[Fact]
public void Test109() { Test(CultureInfo.InvariantCulture, "\u2160", "\uFF11", 1, CompareOptions.None); }
[Fact]
public void Test110() { Test(CultureInfo.InvariantCulture, "0", "\uFF10", -1, CompareOptions.None); }
[Fact]
public void Test111() { Test(CultureInfo.InvariantCulture, "10", "1\uFF10", -1, CompareOptions.None); }
[Fact]
public void Test112() { Test(CultureInfo.InvariantCulture, "1\uFF10", "1\uFF10", 0, CompareOptions.None); }
[Fact]
public void Test113() { Test(CultureInfo.InvariantCulture, "9999\uFF1910", "1\uFF10", 1, CompareOptions.None); }
[Fact]
public void Test114() { Test(CultureInfo.InvariantCulture, "9999\uFF191010", "1\uFF10", 1, CompareOptions.None); }
[Fact]
public void Test115() { Test(CultureInfo.InvariantCulture, "'\u3000'", "' '", 1, CompareOptions.None); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test116() { Test(CultureInfo.InvariantCulture, "'\u3000'", "''", 1, CompareOptions.None); }
[Fact]
public void Test117() { Test(CultureInfo.InvariantCulture, "\uFF1B", ";", 1, CompareOptions.None); }
[Fact]
public void Test118() { Test(CultureInfo.InvariantCulture, "\uFF08", "(", 1, CompareOptions.None); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test119() { Test(CultureInfo.InvariantCulture, "\u30FC", "\uFF70", 0, CompareOptions.None); }
[Fact]
public void Test120() { Test(CultureInfo.InvariantCulture, "\u30FC", "\uFF0D", 1, CompareOptions.None); }
[Fact]
public void Test121() { Test(CultureInfo.InvariantCulture, "\u30FC", "\u30FC", 0, CompareOptions.None); }
[Fact]
public void Test122() { Test(CultureInfo.InvariantCulture, "\u30FC", "\u2015", 1, CompareOptions.None); }
[Fact]
public void Test123() { Test(CultureInfo.InvariantCulture, "\u30FC", "\u2010", 1, CompareOptions.None); }
[Fact]
public void Test124() { Test(CultureInfo.InvariantCulture, "/", "\uFF0F", -1, CompareOptions.None); }
[Fact]
public void Test125() { Test(CultureInfo.InvariantCulture, "'", "\uFF07", -1, CompareOptions.None); }
[Fact]
public void Test126() { Test(CultureInfo.InvariantCulture, "\"", "\uFF02", -1, CompareOptions.None); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test127() { Test(new CultureInfo("hu-HU"), "dzsdzs", "ddzs", 0, CompareOptions.None); }
[Fact]
public void Test128() { TestOrd(new CultureInfo("hu-HU"), "dzsdzs", "ddzs", 1, CompareOptions.Ordinal); }
[Fact]
public void Test129() { Test(CultureInfo.InvariantCulture, "dzsdzs", "ddzs", 1, CompareOptions.None); }
[Fact]
public void Test130() { TestOrd(CultureInfo.InvariantCulture, "dzsdzs", "ddzs", 1, CompareOptions.Ordinal); }
[Fact]
public void Test131() { Test(new CultureInfo("tr-TR"), "i", "I", 1, CompareOptions.IgnoreCase); }
[Fact]
public void Test132() { Test(CultureInfo.InvariantCulture, "i", "I", 0, CompareOptions.IgnoreCase); }
[Fact]
public void Test133() { Test(new CultureInfo("tr-TR"), "i", "\u0130", 0, CompareOptions.IgnoreCase); }
[Fact]
public void Test134() { Test(CultureInfo.InvariantCulture, "i", "\u0130", -1, CompareOptions.IgnoreCase); }
[Fact]
public void Test135() { Test(new CultureInfo("tr-TR"), "i", "I", 1, CompareOptions.None); }
[Fact]
public void Test136() { Test(CultureInfo.InvariantCulture, "i", "I", -1, CompareOptions.None); }
[Fact]
public void Test137() { Test(new CultureInfo("tr-TR"), "i", "\u0130", -1, CompareOptions.None); }
[Fact]
public void Test138() { Test(CultureInfo.InvariantCulture, "i", "\u0130", -1, CompareOptions.None); }
[Fact]
public void Test139() { Test(CultureInfo.InvariantCulture, "\u00C0", "A\u0300", 0, CompareOptions.None); }
[Fact]
public void Test140() { TestOrd(CultureInfo.InvariantCulture, "\u00C0", "A\u0300", 1, CompareOptions.Ordinal); }
[Fact]
public void Test141() { Test(CultureInfo.InvariantCulture, "\u00C0", "a\u0300", 0, CompareOptions.IgnoreCase); }
[Fact]
public void Test142() { TestOrd(CultureInfo.InvariantCulture, "\u00C0", "a\u0300", 1, CompareOptions.OrdinalIgnoreCase); }
[Fact]
public void Test143() { Test(CultureInfo.InvariantCulture, "\u00C0", "a\u0300", 1, CompareOptions.None); }
[Fact]
public void Test144() { TestOrd(CultureInfo.InvariantCulture, "\u00C0", "a\u0300", 1, CompareOptions.Ordinal); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test145()
{
char unassignedUnicode = GetNextUnassignedUnicode();
Test(CultureInfo.InvariantCulture, "FooBar", "Foo" + unassignedUnicode + "Bar", 0, CompareOptions.None);
}
[Fact]
public void Test146() { TestOrd(CultureInfo.InvariantCulture, "FooBar", "Foo\u0400Bar", -1, CompareOptions.Ordinal); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test147()
{
char unassignedUnicode = GetNextUnassignedUnicode();
Test(CultureInfo.InvariantCulture, "FooBar", "Foo" + unassignedUnicode + "Bar", 0, CompareOptions.IgnoreNonSpace);
}
[Fact]
public void Test148()
{
Test(CultureInfo.InvariantCulture, "FooBA\u0300R", "FooB\u00C0R", 0, CompareOptions.IgnoreNonSpace);
}
[Fact]
public void Test149() { Test(CultureInfo.InvariantCulture, "Test's", "Tests", 0, CompareOptions.IgnoreSymbols); }
[Fact]
[ActiveIssue(5463, PlatformID.AnyUnix)]
public void Test150() { Test(CultureInfo.InvariantCulture, "Test's", "Tests", 1, CompareOptions.None); }
[Fact]
public void Test151() { Test(CultureInfo.InvariantCulture, "Test's", "Tests", -1, CompareOptions.StringSort); }
[Fact]
public void Test152() { Assert.Throws<ArgumentException>(() => { int i = CultureInfo.InvariantCulture.CompareInfo.Compare("Test's", "Tests", (CompareOptions)(-1)); }); }
[Fact]
public void Test153() { TestOrd(CultureInfo.InvariantCulture, null, "Tests", -1, CompareOptions.None); }
[Fact]
public void Test154() { TestOrd(CultureInfo.InvariantCulture, "Test's", null, 1, CompareOptions.None); }
[Fact]
public void Test155() { TestOrd(CultureInfo.InvariantCulture, null, null, 0, CompareOptions.None); }
[Fact]
public void Test156() { Test(CultureInfo.InvariantCulture, new string('a', 5555), new string('a', 5555), 0, CompareOptions.None); }
[Fact]
public void Test157() { Test(CultureInfo.InvariantCulture, "foobar", "FooB\u00C0R", 0, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase); }
[Fact]
public void Test158() { Test(CultureInfo.InvariantCulture, "foobar", "FooB\u00C0R", -1, CompareOptions.IgnoreNonSpace); }
[Fact]
public void Test159() { Test(CultureInfo.InvariantCulture, "\uFF9E", "\u3099", 0, CompareOptions.IgnoreCase); }
[Fact]
public void Test160() { Test(CultureInfo.InvariantCulture, "\uFF9E", "\u3099", 0, CompareOptions.IgnoreNonSpace); }
[Fact]
public void Test161() { Test(CultureInfo.InvariantCulture, "\u20A9", "\uFFE6", 0, CompareOptions.IgnoreWidth); }
[Fact]
public void Test162() { Test(CultureInfo.InvariantCulture, "\u20A9", "\uFFE6", -1, CompareOptions.IgnoreCase); }
[Fact]
public void Test163() { Test(CultureInfo.InvariantCulture, "\u20A9", "\uFFE6", -1, CompareOptions.None); }
[Fact]
public void Test164() { Test(CultureInfo.InvariantCulture, "\u0021", "\uFF01", 0, CompareOptions.IgnoreSymbols); }
[Fact]
public void Test165() { Test(CultureInfo.InvariantCulture, "\u00A2", "\uFFE0", 0, CompareOptions.IgnoreSymbols); }
[Fact]
public void Test166() { Test(CultureInfo.InvariantCulture, "$", "&", 0, CompareOptions.IgnoreSymbols); }
[Fact]
public void Test167() { Test(CultureInfo.InvariantCulture, "\uFF65", "\u30FB", 0, CompareOptions.IgnoreSymbols); }
[Fact]
public void Test168() { Test(CultureInfo.InvariantCulture, "\u0021", "\uFF01", 0, CompareOptions.IgnoreWidth); }
[Fact]
public void Test169() { Test(CultureInfo.InvariantCulture, "\u0021", "\uFF01", -1, CompareOptions.None); }
[Fact]
public void Test170() { Test(CultureInfo.InvariantCulture, "\uFF66", "\u30F2", 0, CompareOptions.IgnoreWidth); }
[Fact]
public void Test171() { Test(CultureInfo.InvariantCulture, "\uFF66", "\u30F2", s_expectedHalfToFullFormsComparison, CompareOptions.IgnoreSymbols); }
[Fact]
public void Test172() { Test(CultureInfo.InvariantCulture, "\uFF66", "\u30F2", s_expectedHalfToFullFormsComparison, CompareOptions.IgnoreCase); }
[Fact]
public void Test173() { Test(CultureInfo.InvariantCulture, "\uFF66", "\u30F2", s_expectedHalfToFullFormsComparison, CompareOptions.IgnoreNonSpace); }
[Fact]
public void Test174() { Test(CultureInfo.InvariantCulture, "\uFF66", "\u30F2", s_expectedHalfToFullFormsComparison, CompareOptions.None); }
[Fact]
public void Test175() { Test(CultureInfo.InvariantCulture, "\u3060", "\u30C0", 0, CompareOptions.IgnoreKanaType); }
[Fact]
public void Test176() { Test(CultureInfo.InvariantCulture, "\u3060", "\u30C0", s_expectedHiraganaToKatakanaCompare, CompareOptions.IgnoreCase); }
[Fact]
public void Test177() { Test(CultureInfo.InvariantCulture, "c", "C", -1, CompareOptions.IgnoreKanaType); }
[Theory]
[InlineData(null, 0, 0, null, 0, 0, 0)]
[InlineData("Hello", 0, 5, null, 0, 0, 1)]
[InlineData(null, 0, 0, "Hello", 0, 5, -1)]
[InlineData("Hello", 0, 0, "Hello", 0, 0, 0)]
[InlineData("Hello", 0, 5, "Hello", 0, 5, 0)]
[InlineData("Hello", 0, 3, "Hello", 0, 3, 0)]
[InlineData("Hello", 2, 3, "Hello", 2, 3, 0)]
[InlineData("Hello", 0, 5, "He" + c_SoftHyphen + "llo", 0, 5, -1)]
[InlineData("Hello", 0, 5, "-=<Hello>=-", 3, 5, 0)]
[InlineData("\uD83D\uDD53Hello\uD83D\uDD50", 1, 7, "\uD83D\uDD53Hello\uD83D\uDD54", 1, 7, 0)] // Surrogate split
[InlineData("Hello", 0, 5, "Hello123", 0, 8, -1)]
[InlineData("Hello123", 0, 8, "Hello", 0, 5, 1)]
[InlineData("---aaaaaaaaaaa", 3, 11, "+++aaaaaaaaaaa", 3, 11, 0)] // Equal long alignment 2, equal compare
[InlineData("aaaaaaaaaaaaaa", 3, 11, "aaaxaaaaaaaaaa", 3, 11, -1)] // Equal long alignment 2, different compare at n=1
[InlineData("-aaaaaaaaaaaaa", 1, 13, "+aaaaaaaaaaaaa", 1, 13, 0)] // Equal long alignment 6, equal compare
[InlineData("aaaaaaaaaaaaaa", 1, 13, "axaaaaaaaaaaaa", 1, 13, -1)] // Equal long alignment 6, different compare at n=1
[InlineData("aaaaaaaaaaaaaa", 0, 14, "aaaaaaaaaaaaaa", 0, 14, 0)] // Equal long alignment 4, equal compare
[InlineData("aaaaaaaaaaaaaa", 0, 14, "xaaaaaaaaaaaaa", 0, 14, -1)] // Equal long alignment 4, different compare at n=1
[InlineData("aaaaaaaaaaaaaa", 0, 14, "axaaaaaaaaaaaa", 0, 14, -1)] // Equal long alignment 4, different compare at n=2
[InlineData("--aaaaaaaaaaaa", 2, 12, "++aaaaaaaaaaaa", 2, 12, 0)] // Equal long alignment 0, equal compare
[InlineData("aaaaaaaaaaaaaa", 2, 12, "aaxaaaaaaaaaaa", 2, 12, -1)] // Equal long alignment 0, different compare at n=1
[InlineData("aaaaaaaaaaaaaa", 2, 12, "aaaxaaaaaaaaaa", 2, 12, -1)] // Equal long alignment 0, different compare at n=2
[InlineData("aaaaaaaaaaaaaa", 2, 12, "aaaaxaaaaaaaaa", 2, 12, -1)] // Equal long alignment 0, different compare at n=3
[InlineData("aaaaaaaaaaaaaa", 2, 12, "aaaaaxaaaaaaaa", 2, 12, -1)] // Equal long alignment 0, different compare at n=4
[InlineData("aaaaaaaaaaaaaa", 2, 12, "aaaaaaxaaaaaaa", 2, 12, -1)] // Equal long alignment 0, different compare at n=5
[InlineData("aaaaaaaaaaaaaa", 0, 13, "+aaaaaaaaaaaaa", 1, 13, 0)] // Different int alignment, equal compare
[InlineData("aaaaaaaaaaaaaa", 0, 13, "aaaaaaaaaaaaax", 1, 13, -1)] // Different int alignment
[InlineData("aaaaaaaaaaaaaa", 1, 13, "aaaxaaaaaaaaaa", 3, 11, -1)] // Different long alignment, abs of 4, one of them is 2, different at n=1
[InlineData("-aaaaaaaaaaaaa", 1, 10, "++++aaaaaaaaaa", 4, 10, 0)] // Different long alignment, equal compare
[InlineData("aaaaaaaaaaaaaa", 1, 10, "aaaaaaaaaaaaax", 4, 10, -1)] // Different long alignment
public static void TestCompareOrdinalIndexed(string str1, int offset1, int length1, string str2, int offset2, int length2, int expectedResult)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
int i = NormalizeCompare(ci.Compare(str1, offset1, length1, str2, offset2, length2, CompareOptions.Ordinal));
Assert.Equal(expectedResult, i);
if ((str1 == null || offset1 + length1 == str1.Length) &&
(str2 == null || offset2 + length2 == str2.Length))
{
i = NormalizeCompare(ci.Compare(str1, offset1, str2, offset2, CompareOptions.Ordinal));
Assert.Equal(expectedResult, i);
}
}
public void Test(CultureInfo culture, string str1, string str2, int expected, CompareOptions options)
{
CompareInfo ci = culture.CompareInfo;
int i = ci.Compare(str1, str2, options);
i = Math.Sign(i);
Assert.Equal(expected, i);
i = ci.Compare(str2, str1, options);
i = Math.Sign(i);
Assert.Equal((0 - expected), i);
}
public void TestOrd(CultureInfo culture, string str1, string str2, int expected, CompareOptions options)
{
CompareInfo ci = culture.CompareInfo;
int i = ci.Compare(str1, str2, options);
i = Math.Sign(i);
Assert.Equal(expected, i);
i = ci.Compare(str2, str1, options);
i = Math.Sign(i);
Assert.Equal((0 - expected), i);
}
private char GetNextUnassignedUnicode()
{
for (char ch = '\uFFFF'; ch > '\u0000'; ch++)
{
if (CharUnicodeInfo.GetUnicodeCategory(ch) == UnicodeCategory.OtherNotAssigned)
{
return ch;
}
}
return Char.MinValue; // there are no unassigned unicode characters from \u0000 - \uFFFF
}
private static int NormalizeCompare(int i)
{
return
i == 0 ? 0 :
i > 0 ? 1 :
-1;
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Reflection;
namespace SpyUO.Packets
{
public abstract class BaseGump : Packet
{
private uint m_X;
private uint m_Y;
private uint m_Serial;
private uint m_GumpId;
private GumpEntry[] m_Layout;
private string[] m_Text;
[PacketProp( 0 )]
public uint X { get { return m_X; } }
[PacketProp( 1 )]
public uint Y { get { return m_Y; } }
[PacketProp( 2, "0x{0:X}" )]
public uint Serial { get { return m_Serial; } }
[PacketProp( 3, "0x{0:X}" )]
public uint GumpId { get { return m_GumpId; } }
public GumpEntry[] Layout { get { return m_Layout; } }
[PacketProp( 4 )]
public string LayoutString
{
get
{
if ( m_Layout.Length == 0 )
return "Empty";
StringBuilder sb = new StringBuilder();
int i = 0;
while ( true )
{
sb.AppendFormat( "{0}", m_Layout[i] );
if ( ++i < m_Layout.Length )
sb.Append( " - " );
else
break;
}
return sb.ToString();
}
}
public string[] Text { get { return m_Text; } }
[PacketProp( 5 )]
public string TextString
{
get
{
if ( m_Text.Length == 0 )
return "Empty";
StringBuilder sb = new StringBuilder();
int i = 0;
while ( true )
{
sb.AppendFormat( "{0}. \"{1}\"", i, m_Text[i] );
if ( ++i < m_Text.Length )
sb.Append( " - " );
else
break;
}
return sb.ToString();
}
}
public BaseGump( PacketReader reader, bool send ) : base( reader, send )
{
}
protected void Init( uint serial, uint gumpId, uint x, uint y, string layout, string[] text )
{
m_Serial = serial;
m_GumpId = gumpId;
m_X = x;
m_Y = y;
m_Text = text;
layout = layout.Replace( "}", "" );
string[] splt = layout.Substring( 1 ).Split( '{' );
ArrayList layoutList = new ArrayList();
foreach ( string s in splt )
{
try
{
string[] commands = SplitCommands( s );
ArrayList cmdList = new ArrayList();
foreach ( string cmd in commands )
{
if ( cmd != "" )
cmdList.Add( cmd );
}
GumpEntry entry = GumpEntry.Create( (string[])cmdList.ToArray( typeof( string ) ), this );
if ( entry != null )
layoutList.Add( entry );
}
catch { }
}
m_Layout = (GumpEntry[])layoutList.ToArray( typeof( GumpEntry ) );
}
private static string[] SplitCommands( string s )
{
s = s.Trim();
ArrayList ret = new ArrayList();
bool stringCmd = false;
int start = 0;
for ( int i = 0; i < s.Length; i++ )
{
char ch = s[i];
if ( ch == ' ' || ch == '\t' )
{
if ( !stringCmd )
{
ret.Add( s.Substring( start, i - start ) );
start = i + 1;
}
}
else if ( ch == '@' )
{
stringCmd = !stringCmd;
}
}
ret.Add( s.Substring( start, s.Length - start ) );
return (string[]) ret.ToArray( typeof( string ) );
}
public void WriteRunUOClass( StreamWriter writer )
{
writer.WriteLine( "using System;" );
writer.WriteLine( "using Server;" );
writer.WriteLine( "using Server.Gumps;" );
writer.WriteLine( "using Server.Network;" );
writer.WriteLine();
writer.WriteLine( "namespace Server.SpyUO" );
writer.WriteLine( "{" );
writer.WriteLine( "\tpublic class SpyUOGump : Gump" );
writer.WriteLine( "\t{" );
writer.WriteLine( "\t\tpublic SpyUOGump() : base( {0}, {1} )", m_X, m_Y );
writer.WriteLine( "\t\t{" );
for ( int i = 0; i < m_Layout.Length; i++ )
{
GumpEntry entry = m_Layout[i];
bool space = entry is GumpPage;
if ( space && i != 0 )
writer.WriteLine();
writer.Write( "\t\t\t{0}", entry.GetRunUOLine() );
if ( entry is GumpHtmlLocalized )
writer.WriteLine( " // " + LocalizedList.GetString( ((GumpHtmlLocalized)entry).Number ) as string );
else if ( entry is GumpHtmlLocalizedColor )
writer.WriteLine( " // " + LocalizedList.GetString( ((GumpHtmlLocalizedColor)entry).Number ) as string );
else if ( entry is GumpHtmlLocalizedArgs )
writer.WriteLine( " // " + LocalizedList.GetString( ((GumpHtmlLocalizedArgs)entry).Number ) as string );
else
writer.WriteLine();
if ( space && i < m_Layout.Length )
writer.WriteLine();
}
writer.WriteLine( "\t\t}" );
writer.WriteLine();
writer.WriteLine( "\t\tpublic override void OnResponse( NetState sender, RelayInfo info )" );
writer.WriteLine( "\t\t{" );
writer.WriteLine( "\t\t}" );
writer.WriteLine( "\t}" );
writer.Write( "}" );
}
public void WriteSphereGump( StreamWriter writer )
{
writer.WriteLine( "[DIALOG d_SpyUO]" );
writer.WriteLine( "SetLocation={0},{1}", m_X, m_Y );
foreach ( GumpEntry entry in m_Layout )
{
if ( entry is GumpPage )
writer.WriteLine();
int i = 0;
while ( true )
{
writer.Write( entry.Commands[i] );
if ( ++i < entry.Commands.Length )
writer.Write( " " );
else
break;
}
if ( entry is GumpHtmlLocalized )
writer.WriteLine( " // " + LocalizedList.GetString( ((GumpHtmlLocalized)entry).Number ) as string );
else if ( entry is GumpHtmlLocalizedColor )
writer.WriteLine( " // " + LocalizedList.GetString( ((GumpHtmlLocalizedColor)entry).Number ) as string );
else if ( entry is GumpHtmlLocalizedArgs )
writer.WriteLine( " // " + LocalizedList.GetString( ((GumpHtmlLocalizedArgs)entry).Number ) as string );
else
writer.WriteLine();
}
writer.WriteLine();
writer.WriteLine( "[DIALOG d_SpyUO TEXT]" );
foreach ( string txt in Text )
{
writer.WriteLine( txt );
}
writer.WriteLine();
writer.WriteLine( "[DIALOG d_SpyUO BUTTON]" );
ArrayList list = new ArrayList();
list.Add( 0 );
foreach ( GumpEntry entry in m_Layout )
{
GumpButton button = entry as GumpButton;
if ( button != null && button.Type != 0 && !list.Contains( button.ButtonId ) )
{
list.Add( button.ButtonId );
}
}
list.Sort();
foreach ( int b in list )
{
writer.WriteLine( "ON={0}", b );
}
writer.WriteLine();
writer.Write( "[EOF]" );
}
}
public abstract class GumpEntry
{
public static GumpEntry Create( string[] commands, BaseGump parent )
{
string command = commands[0].ToLower();
switch ( command )
{
case "nomove":
return new GumpNotDragable( commands, parent );
case "noclose":
return new GumpNotClosable( commands, parent );
case "nodispose":
return new GumpNotDisposable( commands, parent );
case "noresize":
return new GumpNotResizable( commands, parent );
case "checkertrans":
return new GumpAlphaRegion( commands, parent );
case "resizepic":
return new GumpBackground( commands, parent );
case "button":
return new GumpButton( commands, parent );
case "checkbox":
return new GumpCheck( commands, parent );
case "group":
return new GumpGroup( commands, parent );
case "htmlgump":
return new GumpHtml( commands, parent );
case "xmfhtmlgump":
return new GumpHtmlLocalized( commands, parent );
case "xmfhtmlgumpcolor":
return new GumpHtmlLocalizedColor( commands, parent );
case "xmfhtmltok":
return new GumpHtmlLocalizedArgs( commands, parent );
case "gumppic":
return new GumpImage( commands, parent );
case "gumppictiled":
return new GumpImageTiled( commands, parent );
case "buttontileart":
return new GumpImageTiledButton( commands, parent );
case "tilepic":
return new GumpItem( commands, parent );
case "tilepichue":
return new GumpItemColor( commands, parent );
case "text":
return new GumpLabel( commands, parent );
case "croppedtext":
return new GumpLabelCropped( commands, parent );
case "page":
return new GumpPage( commands, parent );
case "radio":
return new GumpRadio( commands, parent );
case "textentry":
return new GumpTextEntry( commands, parent );
case "tooltip":
return new GumpTooltip( commands, parent );
case "mastergump":
return null;
default:
throw new ArgumentException();
}
}
private string[] m_Commands;
private BaseGump m_Parent;
public string[] Commands { get { return m_Commands; } }
public BaseGump Parent { get { return m_Parent; } }
public GumpEntry( string[] commands, BaseGump parent )
{
m_Commands = commands;
m_Parent = parent;
}
public abstract string GetRunUOLine();
public int GetInt32( int n )
{
return Int32.Parse( m_Commands[n] );
}
public uint GetUInt32( int n )
{
return UInt32.Parse( m_Commands[ n ] );
}
public bool GetBoolean( int n )
{
return GetInt32( n ) != 0;
}
public string GetString( int n )
{
string cmd = m_Commands[n];
return cmd.Substring( 1, cmd.Length - 2 );
}
public string GetText( int n )
{
return m_Parent.Text[n];
}
public static string Format( bool b )
{
return b ? "true" : "false";
}
public static string Format( string s )
{
return s.Replace( "\t", "\\t" );
}
}
public class GumpNotDragable : GumpEntry
{
public GumpNotDragable( string[] commands, BaseGump parent ) : base( commands, parent )
{
}
public override string GetRunUOLine()
{
return "Dragable = false;";
}
public override string ToString()
{
return "Not Dragable";
}
}
public class GumpNotClosable : GumpEntry
{
public GumpNotClosable( string[] commands, BaseGump parent ) : base( commands, parent )
{
}
public override string GetRunUOLine()
{
return "Closable = false;";
}
public override string ToString()
{
return "Not Closable";
}
}
public class GumpNotDisposable : GumpEntry
{
public GumpNotDisposable( string[] commands, BaseGump parent ) : base( commands, parent )
{
}
public override string GetRunUOLine()
{
return "Disposable = false;";
}
public override string ToString()
{
return "Not Disposable";
}
}
public class GumpNotResizable : GumpEntry
{
public GumpNotResizable( string[] commands, BaseGump parent ) : base( commands, parent )
{
}
public override string GetRunUOLine()
{
return "Resizable = false;";
}
public override string ToString()
{
return "Not Resizable";
}
}
public class GumpAlphaRegion : GumpEntry
{
private int m_X;
private int m_Y;
private int m_Width;
private int m_Height;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int Width { get { return m_Width; } }
public int Height { get { return m_Height; } }
public GumpAlphaRegion( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_Width = GetInt32( 3 );
m_Height = GetInt32( 4 );
}
public override string GetRunUOLine()
{
return string.Format( "AddAlphaRegion( {0}, {1}, {2}, {3} );", m_X, m_Y, m_Width, m_Height );
}
public override string ToString()
{
return string.Format( "Alpha Region: \"X: \"{0}\", Y: \"{1}\", Width: \"{2}\", Height: \"{3}\"",
m_X, m_Y, m_Width, m_Height );
}
}
public class GumpBackground : GumpEntry
{
private int m_X;
private int m_Y;
private int m_Width;
private int m_Height;
private int m_GumpId;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int Width { get { return m_Width; } }
public int Height { get { return m_Height; } }
public int GumpId { get { return m_GumpId; } }
public GumpBackground( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_GumpId = GetInt32( 3 );
m_Width = GetInt32( 4 );
m_Height = GetInt32( 5 );
}
public override string GetRunUOLine()
{
return string.Format( "AddBackground( {0}, {1}, {2}, {3}, 0x{4:X} );", m_X, m_Y, m_Width, m_Height, m_GumpId );
}
public override string ToString()
{
return string.Format( "Background: \"X: \"{0}\", Y: \"{1}\", Width: \"{2}\", Height: \"{3}\", GumpId: \"0x{4:X}\"",
m_X, m_Y, m_Width, m_Height, m_GumpId );
}
}
public class GumpButton : GumpEntry
{
private int m_X;
private int m_Y;
private int m_NormalId;
private int m_PressedId;
private int m_ButtonId;
private int m_Type;
private int m_Param;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int NormalId { get { return m_NormalId; } }
public int PressedId { get { return m_PressedId; } }
public int ButtonId { get { return m_ButtonId; } }
public int Type { get { return m_Type; } }
public int Param { get { return m_Param; } }
public GumpButton( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_NormalId = GetInt32( 3 );
m_PressedId = GetInt32( 4 );
m_Type = GetInt32( 5 );
m_Param = GetInt32( 6 );
m_ButtonId = GetInt32( 7 );
}
public override string GetRunUOLine()
{
string type = m_Type == 0 ? "GumpButtonType.Page" : "GumpButtonType.Reply";
return string.Format( "AddButton( {0}, {1}, 0x{2:X}, 0x{3:X}, {4}, {5}, {6} );",
m_X, m_Y, m_NormalId, m_PressedId, m_ButtonId, type, m_Param );
}
public override string ToString()
{
return string.Format( "Button: \"X: \"{0}\", Y: \"{1}\", NormalId: \"0x{2:X}\", PressedId: \"0x{3:X}\", ButtonId: \"{4}\", Type: \"{5}\", Param: \"{6}\"",
m_X, m_Y, m_NormalId, m_PressedId, m_ButtonId, m_Type, m_Param );
}
}
public class GumpCheck : GumpEntry
{
private int m_X;
private int m_Y;
private int m_InactiveId;
private int m_ActiveId;
private bool m_InitialState;
private int m_SwitchId;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int InactiveId { get { return m_InactiveId; } }
public int ActiveId { get { return m_ActiveId; } }
public bool InitialState { get { return m_InitialState; } }
public int SwitchId { get { return m_SwitchId; } }
public GumpCheck( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_InactiveId = GetInt32( 3 );
m_ActiveId = GetInt32( 4 );
m_InitialState = GetBoolean( 5 );
m_SwitchId = GetInt32( 6 );
}
public override string GetRunUOLine()
{
return string.Format( "AddCheck( {0}, {1}, 0x{2:X}, 0x{3:X}, {4}, {5} );",
m_X, m_Y, m_InactiveId, m_ActiveId, Format( m_InitialState ), m_SwitchId );
}
public override string ToString()
{
return string.Format( "Check: X: \"{0}\", Y: \"{1}\", InactiveId: \"0x{2:X}\", ActiveId: \"0x{3:X}\", InitialState: \"{4}\", SwitchId: \"{5}\"",
m_X, m_Y, m_InactiveId, m_ActiveId, m_InitialState, m_SwitchId );
}
}
public class GumpGroup : GumpEntry
{
private int m_Group;
public int Group { get { return m_Group; } }
public GumpGroup( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_Group = GetInt32( 1 );
}
public override string GetRunUOLine()
{
return string.Format( "AddGroup( {0} );", m_Group );
}
public override string ToString()
{
return string.Format( "Group: \"{0}\"", m_Group );
}
}
public class GumpHtml : GumpEntry
{
private int m_X;
private int m_Y;
private int m_Width;
private int m_Height;
private string m_Text;
private bool m_Background;
private bool m_Scrollbar;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int Width { get { return m_Width; } }
public int Height { get { return m_Height; } }
public string Text { get { return m_Text; } }
public bool Background { get { return m_Background; } }
public bool Scrollbar { get { return m_Scrollbar; } }
public GumpHtml( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_Width = GetInt32( 3 );
m_Height = GetInt32( 4 );
m_Text = GetText( GetInt32( 5 ) );
m_Background = GetBoolean( 6 );
m_Scrollbar = GetBoolean( 7 );
}
public override string GetRunUOLine()
{
return string.Format( "AddHtml( {0}, {1}, {2}, {3}, \"{4}\", {5}, {6} );",
m_X, m_Y, m_Width, m_Height, Format( m_Text ), Format( m_Background ), Format( m_Scrollbar ) );
}
public override string ToString()
{
return string.Format( "Html: \"X: \"{0}\", Y: \"{1}\", Width: \"{2}\", Height: \"{3}\", Text: \"{4}\", Background: \"{5}\", Scrollbar: \"{6}\"",
m_X, m_Y, m_Width, m_Height, m_Text, m_Background, m_Scrollbar );
}
}
public class GumpHtmlLocalized : GumpEntry
{
private int m_X;
private int m_Y;
private int m_Width;
private int m_Height;
private uint m_Number;
private bool m_Background;
private bool m_Scrollbar;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int Width { get { return m_Width; } }
public int Height { get { return m_Height; } }
public uint Number { get { return m_Number; } }
public bool Background { get { return m_Background; } }
public bool Scrollbar { get { return m_Scrollbar; } }
public GumpHtmlLocalized( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_Width = GetInt32( 3 );
m_Height = GetInt32( 4 );
m_Number = GetUInt32( 5 );
if ( commands.Length < 8 )
{
m_Background = false;
m_Scrollbar = false;
}
else
{
m_Background = GetBoolean( 6 );
m_Scrollbar = GetBoolean( 7 );
}
}
public override string GetRunUOLine()
{
return string.Format( "AddHtmlLocalized( {0}, {1}, {2}, {3}, {4}, {5}, {6} );",
m_X, m_Y, m_Width, m_Height, m_Number, Format( m_Background ), Format( m_Scrollbar ) );
}
public override string ToString()
{
return string.Format( "HtmlLocalized: \"X: \"{0}\", Y: \"{1}\", Width: \"{2}\", Height: \"{3}\", Number: \"{4}\", Background: \"{5}\", Scrollbar: \"{6}\"",
m_X, m_Y, m_Width, m_Height, m_Number, m_Background, m_Scrollbar );
}
}
public class GumpHtmlLocalizedColor : GumpEntry
{
private int m_X;
private int m_Y;
private int m_Width;
private int m_Height;
private uint m_Number;
private int m_Color;
private bool m_Background;
private bool m_Scrollbar;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int Width { get { return m_Width; } }
public int Height { get { return m_Height; } }
public uint Number { get { return m_Number; } }
public int Color { get { return m_Color; } }
public bool Background { get { return m_Background; } }
public bool Scrollbar { get { return m_Scrollbar; } }
public GumpHtmlLocalizedColor( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_Width = GetInt32( 3 );
m_Height = GetInt32( 4 );
m_Number = GetUInt32( 5 );
m_Background = GetBoolean( 6 );
m_Scrollbar = GetBoolean( 7 );
m_Color = GetInt32( 8 );
}
public override string GetRunUOLine()
{
return string.Format( "AddHtmlLocalized( {0}, {1}, {2}, {3}, {4}, 0x{5:X}, {6}, {7} );",
m_X, m_Y, m_Width, m_Height, m_Number, m_Color, Format( m_Background ), Format( m_Scrollbar ) );
}
public override string ToString()
{
return string.Format( "HtmlLocalizedColor: \"X: \"{0}\", Y: \"{1}\", Width: \"{2}\", Height: \"{3}\", Number: \"{4}\", Color: \"0x{5:X}\", \"Background: \"{6}\", Scrollbar: \"{7}\"",
m_X, m_Y, m_Width, m_Height, m_Number, m_Color, m_Background, m_Scrollbar );
}
}
public class GumpHtmlLocalizedArgs : GumpEntry
{
private int m_X;
private int m_Y;
private int m_Width;
private int m_Height;
private uint m_Number;
private string m_Args;
private int m_Color;
private bool m_Background;
private bool m_Scrollbar;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int Width { get { return m_Width; } }
public int Height { get { return m_Height; } }
public uint Number { get { return m_Number; } }
public string Args{ get{ return m_Args; } }
public int Color { get { return m_Color; } }
public bool Background { get { return m_Background; } }
public bool Scrollbar { get { return m_Scrollbar; } }
public GumpHtmlLocalizedArgs( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_Width = GetInt32( 3 );
m_Height = GetInt32( 4 );
m_Background = GetBoolean( 5 );
m_Scrollbar = GetBoolean( 6 );
m_Color = GetInt32( 7 );
m_Number = GetUInt32( 8 );
m_Args = GetString( 9 );
}
public override string GetRunUOLine()
{
return string.Format( "AddHtmlLocalized( {0}, {1}, {2}, {3}, {4}, \"{5}\", 0x{6:X}, {7}, {8} );",
m_X, m_Y, m_Width, m_Height, m_Number, Format( m_Args ), m_Color, Format( m_Background ), Format( m_Scrollbar ) );
}
public override string ToString()
{
return string.Format( "HtmlLocalizedArgs: \"X: \"{0}\", Y: \"{1}\", Width: \"{2}\", Height: \"{3}\", Number: \"{4}\", Args: \"{5}\", Color: \"0x{6:X}\", \"Background: \"{7}\", Scrollbar: \"{8}\"",
m_X, m_Y, m_Width, m_Height, m_Number, m_Args, m_Color, m_Background, m_Scrollbar );
}
}
public class GumpImage : GumpEntry
{
private int m_X;
private int m_Y;
private int m_GumpId;
private int m_Color;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int GumpId { get { return m_GumpId; } }
public int Color { get { return m_Color; } }
public GumpImage( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_GumpId = GetInt32( 3 );
if ( commands.Length > 4 )
m_Color = Int32.Parse( commands[4].Substring( 4 ) );
else
m_Color = 0;
}
public override string GetRunUOLine()
{
return string.Format( "AddImage( {0}, {1}, 0x{2:X}{3} );",
m_X, m_Y, m_GumpId, m_Color != 0 ? ", 0x" + m_Color.ToString( "X" ) : "" );
}
public override string ToString()
{
return string.Format( "Image: \"X: \"{0}\", Y: \"{1}\", GumpId: \"0x{2:X}\", Color: \"0x{3:X}\"",
m_X, m_Y, m_GumpId, m_Color );
}
}
public class GumpImageTiled : GumpEntry
{
private int m_X;
private int m_Y;
private int m_Width;
private int m_Height;
private int m_GumpId;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int Width { get { return m_Width; } }
public int Height { get { return m_Height; } }
public int GumpId { get { return m_GumpId; } }
public GumpImageTiled( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_Width = GetInt32( 3 );
m_Height = GetInt32( 4 );
m_GumpId = GetInt32( 5 );
}
public override string GetRunUOLine()
{
return string.Format( "AddImageTiled( {0}, {1}, {2}, {3}, 0x{4:X} );",
m_X, m_Y, m_Width, m_Height, m_GumpId );
}
public override string ToString()
{
return string.Format( "ImageTiled: \"X: \"{0}\", Y: \"{1}\", Width: \"{2}\", Height: \"{3}\", GumpId: \"0x{4:X}\"",
m_X, m_Y, m_Width, m_Height, m_GumpId );
}
}
public class GumpImageTiledButton : GumpEntry
{
private int m_X;
private int m_Y;
private int m_NormalID;
private int m_PressedID;
private int m_ButtonID;
private int m_Type;
private int m_Param;
private int m_ItemID;
private int m_Hue;
private int m_Width;
private int m_Height;
public int X { get { return m_X; } }
public int Y { get { return m_Y; } }
public int NormalID { get { return m_NormalID; } }
public int PressedID { get { return m_PressedID; } }
public int ButtonID { get { return m_ButtonID; } }
public int Type { get { return m_Type; } }
public int Param { get { return m_Param; } }
public int ItemID { get { return m_ItemID; } }
public int Hue { get { return m_Hue; } }
public int Width { get { return m_Width; } }
public int Height { get { return m_Height; } }
public GumpImageTiledButton( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_NormalID = GetInt32( 3 );
m_PressedID = GetInt32( 4 );
m_Type = GetInt32( 5 );
m_Param = GetInt32( 6 );
m_ButtonID = GetInt32( 7 );
m_ItemID = GetInt32( 8 );
m_Hue = GetInt32( 9 );
m_Width = GetInt32( 10 );
m_Height = GetInt32( 11 );
}
public override string GetRunUOLine()
{
string type = ( m_Type == 0 ? "GumpButtonType.Page" : "GumpButtonType.Reply" );
return String.Format( "AddImageTiledButton( {0}, {1}, 0x{2:X}, 0x{3:X}, 0x{4:X}, {5}, {6}, 0x{7:X}, 0x{8:X}, {9}, {10} );",
m_X, m_Y, m_NormalID, m_PressedID, m_ButtonID, type, m_Param, m_ItemID, m_Hue, m_Width, m_Height );
}
public override string ToString()
{
return string.Format( "ImageTiledButton: \"X: \"{0}\", Y: \"{1}\", Id1: \"0x{2:X}\", Id2: \"0x{3:X}\", ButtonId: \"0x{4:X}\", Type: \"{5}\", Param: \"{6}\", ItemId: \"0x{7:X}\", Hue: \"0x{8:X}\", Width: \"{9}\", Height: \"{10}\"",
m_X, m_Y, m_NormalID, m_PressedID, m_ButtonID, m_Type, m_Param, m_ItemID, m_Hue, m_Width, m_Height );
}
}
public class GumpItem : GumpEntry
{
private int m_X;
private int m_Y;
private int m_GumpId;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int GumpId { get { return m_GumpId; } }
public GumpItem( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_GumpId = GetInt32( 3 );
}
public override string GetRunUOLine()
{
return string.Format( "AddItem( {0}, {1}, 0x{2:X} );", m_X, m_Y, m_GumpId );
}
public override string ToString()
{
return string.Format( "Item: \"X: \"{0}\", Y: \"{1}\", GumpId: \"0x{2:X}\"",
m_X, m_Y, m_GumpId );
}
}
public class GumpItemColor : GumpEntry
{
private int m_X;
private int m_Y;
private int m_GumpId;
private int m_Color;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int GumpId { get { return m_GumpId; } }
public int Color { get { return m_Color; } }
public GumpItemColor( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_GumpId = GetInt32( 3 );
m_Color = GetInt32( 4 );
}
public override string GetRunUOLine()
{
return string.Format( "AddItem( {0}, {1}, 0x{2:X}, 0x{3:X} );",
m_X, m_Y, m_GumpId, m_Color );
}
public override string ToString()
{
return string.Format( "ItemColor: \"X: \"{0}\", Y: \"{1}\", GumpId: \"0x{2:X}\", Color: \"0x{3:X}\"",
m_X, m_Y, m_GumpId, m_Color );
}
}
public class GumpLabel : GumpEntry
{
private int m_X;
private int m_Y;
private int m_Color;
private string m_Text;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int Color { get { return m_Color; } }
public string Text { get { return m_Text; } }
public GumpLabel( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_Color = GetInt32( 3 );
m_Text = GetText( GetInt32( 4 ) );
}
public override string GetRunUOLine()
{
return string.Format( "AddLabel( {0}, {1}, 0x{2:X}, \"{3}\" );",
m_X, m_Y, m_Color, Format( m_Text ) );
}
public override string ToString()
{
return string.Format( "Label: \"X: \"{0}\", Y: \"{1}\", Color: \"0x{2:X}\", Text: \"{3}\"",
m_X, m_Y, m_Color, m_Text );
}
}
public class GumpLabelCropped : GumpEntry
{
private int m_X;
private int m_Y;
private int m_Width;
private int m_Height;
private int m_Color;
private string m_Text;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int Color { get { return m_Color; } }
public string Text { get { return m_Text; } }
public GumpLabelCropped( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_Width = GetInt32( 3 );
m_Height = GetInt32( 4 );
m_Color = GetInt32( 5 );
m_Text = GetText( GetInt32( 6 ) );
}
public override string GetRunUOLine()
{
return string.Format( "AddLabelCropped( {0}, {1}, {2}, {3}, 0x{4:X}, \"{5}\" );",
m_X, m_Y, m_Width, m_Height, m_Color, Format( m_Text ) );
}
public override string ToString()
{
return string.Format( "LabelCropped: \"X: \"{0}\", Y: \"{1}\", Width: \"{2}\", Height: \"{3}\", Color: \"0x{4:X}\", Text: \"{5}\"",
m_X, m_Y, m_Width, m_Height, m_Color, m_Text );
}
}
public class GumpPage : GumpEntry
{
private int m_Page;
public int Page { get { return m_Page; } }
public GumpPage( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_Page = GetInt32( 1 );
}
public override string GetRunUOLine()
{
return string.Format( "AddPage( {0} );", m_Page );
}
public override string ToString()
{
return string.Format( "Page: \"{0}\"", m_Page );
}
}
public class GumpRadio : GumpEntry
{
private int m_X;
private int m_Y;
private int m_InactiveId;
private int m_ActiveId;
private bool m_InitialState;
private int m_SwitchId;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int InactiveId { get { return m_InactiveId; } }
public int ActiveId { get { return m_ActiveId; } }
public bool InitialState { get { return m_InitialState; } }
public int SwitchId { get { return m_SwitchId; } }
public GumpRadio( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_InactiveId = GetInt32( 3 );
m_ActiveId = GetInt32( 4 );
m_InitialState = GetBoolean( 5 );
m_SwitchId = GetInt32( 6 );
}
public override string GetRunUOLine()
{
return string.Format( "AddRadio( {0}, {1}, 0x{2:X}, 0x{3:X}, {4}, {5} );",
m_X, m_Y, m_InactiveId, m_ActiveId, Format( m_InitialState ), m_SwitchId );
}
public override string ToString()
{
return string.Format( "Radio: X: \"{0}\", Y: \"{1}\", InactiveId: \"0x{2:X}\", ActiveId: \"0x{3:X}\", InitialState: \"{4}\", SwitchId: \"{5}\"",
m_X, m_Y, m_InactiveId, m_ActiveId, m_InitialState, m_SwitchId );
}
}
public class GumpTextEntry : GumpEntry
{
private int m_X;
private int m_Y;
private int m_Width;
private int m_Height;
private int m_Color;
private int m_EntryId;
private string m_InitialText;
public int X { get { return m_X; } }
public int Y { get { return m_X; } }
public int Width { get { return m_Width; } }
public int Height { get { return m_Height; } }
public int Color { get { return m_Color; } }
public int EntryId { get { return m_EntryId; } }
public string InitialText { get { return m_InitialText; } }
public GumpTextEntry( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_X = GetInt32( 1 );
m_Y = GetInt32( 2 );
m_Width = GetInt32( 3 );
m_Height = GetInt32( 4 );
m_Color = GetInt32( 5 );
m_EntryId = GetInt32( 6 );
m_InitialText = GetText( GetInt32( 7 ) );
}
public override string GetRunUOLine()
{
return string.Format( "AddTextEntry( {0}, {1}, {2}, {3}, 0x{4:X}, {5}, \"{6}\" );",
m_X, m_Y, m_Width, m_Height, m_Color, m_EntryId, Format( m_InitialText ) );
}
public override string ToString()
{
return string.Format( "TextEntry: X: \"{0}\", Y: \"{1}\", Width: \"{2}\", Height: \"{3}\", Color: \"0x{4:X}\", EntryId: \"{5}\", Text: \"{6}\"",
m_X, m_Y, m_Width, m_Height, m_Color, m_EntryId, m_InitialText );
}
}
public class GumpTooltip : GumpEntry
{
private int m_Number;
public int Number { get { return m_Number; } }
public GumpTooltip( string[] commands, BaseGump parent ) : base( commands, parent )
{
m_Number = GetInt32( 1 );
}
public override string GetRunUOLine()
{
return string.Format( "AddTooltip( {0} );", m_Number );
}
public override string ToString()
{
return string.Format( "Tooltip: Number: \"{0}\"", m_Number );
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace PTWin
{
public partial class ResourceEdit : WinPart
{
private ProjectTracker.Library.ResourceEdit _resource;
public ProjectTracker.Library.ResourceEdit Resource
{
get { return _resource; }
}
public ResourceEdit(ProjectTracker.Library.ResourceEdit resource)
{
InitializeComponent();
// store object reference
_resource = resource;
}
private void ResourceEdit_Load(object sender, EventArgs e)
{
this.CurrentPrincipalChanged += new EventHandler(ResourceEdit_CurrentPrincipalChanged);
_resource.PropertyChanged += new PropertyChangedEventHandler(mResource_PropertyChanged);
this.RoleListBindingSource.DataSource = ProjectTracker.Library.RoleList.GetCachedList();
BindUI();
ApplyAuthorizationRules();
}
#region WinPart Code
protected internal override object GetIdValue()
{
return _resource;
}
public override string ToString()
{
return _resource.FullName;
}
private void ResourceEdit_CurrentPrincipalChanged(object sender, EventArgs e)
{
ApplyAuthorizationRules();
}
#endregion
private void ApplyAuthorizationRules()
{
bool canEdit = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectTracker.Library.ResourceEdit));
if (!canEdit)
RebindUI(false, true);
// have the controls enable/disable/etc
this.ReadWriteAuthorization1.ResetControlAuthorization();
// enable/disable appropriate buttons
this.OKButton.Enabled = canEdit;
this.ApplyButton.Enabled = canEdit;
this.Cancel_Button.Enabled = canEdit;
// enable/disable role column in grid
this.AssignmentsDataGridView.Columns[3].ReadOnly = !canEdit;
}
private void OKButton_Click(object sender, EventArgs e)
{
using (StatusBusy busy = new StatusBusy("Saving..."))
{
RebindUI(true, false);
}
this.Close();
}
private void ApplyButton_Click(object sender, EventArgs e)
{
using (StatusBusy busy = new StatusBusy("Saving..."))
{
RebindUI(true, true);
}
}
private void Cancel_Button_Click(object sender, EventArgs e)
{
RebindUI(false, true);
}
private void CloseButton_Click(object sender, EventArgs e)
{
RebindUI(false, false);
this.Close();
}
private void BindUI()
{
_resource.BeginEdit();
this.ResourceBindingSource.DataSource = _resource;
}
private void RebindUI(bool saveObject, bool rebind)
{
// disable events
this.ResourceBindingSource.RaiseListChangedEvents = false;
this.AssignmentsBindingSource.RaiseListChangedEvents = false;
try
{
// unbind the UI
UnbindBindingSource(this.AssignmentsBindingSource, saveObject, false);
UnbindBindingSource(this.ResourceBindingSource, saveObject, true);
this.AssignmentsBindingSource.DataSource = this.ResourceBindingSource;
// save or cancel changes
if (saveObject)
{
_resource.ApplyEdit();
try
{
_resource = _resource.Save();
}
catch (Csla.DataPortalException ex)
{
MessageBox.Show(ex.BusinessException.ToString(),
"Error saving", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(),
"Error Saving", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
else
_resource.CancelEdit();
}
finally
{
// rebind UI if requested
if (rebind)
BindUI();
// restore events
this.ResourceBindingSource.RaiseListChangedEvents = true;
this.AssignmentsBindingSource.RaiseListChangedEvents = true;
if (rebind)
{
// refresh the UI if rebinding
this.ResourceBindingSource.ResetBindings(false);
this.AssignmentsBindingSource.ResetBindings(false);
}
}
}
private void AssignButton_Click(object sender, EventArgs e)
{
ProjectSelect dlg = new ProjectSelect();
if (dlg.ShowDialog() == DialogResult.OK)
try
{
_resource.Assignments.AssignTo(dlg.ProjectId);
}
catch (InvalidOperationException ex)
{
MessageBox.Show(ex.ToString(),
"Error Assigning", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(),
"Error Assigning", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
private void UnassignButton_Click(object sender, EventArgs e)
{
if (this.AssignmentsDataGridView.SelectedRows.Count > 0)
{
var projectId = (int)this.AssignmentsDataGridView.SelectedRows[0].Cells[0].Value;
_resource.Assignments.Remove(projectId);
}
}
private void mResource_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsDirty")
{
this.ResourceBindingSource.ResetBindings(true);
this.AssignmentsBindingSource.ResetBindings(true);
}
}
private void AssignmentsDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1 && e.RowIndex > -1)
{
var projectId = (int)this.AssignmentsDataGridView.Rows[e.RowIndex].Cells[0].Value;
MainForm.Instance.ShowEditProject(projectId);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using NetGore.IO;
namespace NetGore.Audio
{
/// <summary>
/// Represents the unique ID of a music track.
/// </summary>
[Serializable]
[TypeConverter(typeof(MusicIDTypeConverter))]
public struct MusicID : IComparable<MusicID>, IConvertible, IFormattable, IComparable<int>, IEquatable<int>
{
/// <summary>
/// Represents the largest possible value of MusicID. This field is constant.
/// </summary>
public const int MaxValue = ushort.MaxValue;
/// <summary>
/// Represents the smallest possible value of MusicID. This field is constant.
/// </summary>
public const int MinValue = ushort.MinValue;
/// <summary>
/// The underlying value. This contains the actual value of the struct instance.
/// </summary>
readonly ushort _value;
/// <summary>
/// Initializes a new instance of the <see cref="MusicID"/> struct.
/// </summary>
/// <param name="value">Value to assign to the new MusicID.</param>
/// <exception cref="ArgumentOutOfRangeException"><c>value</c> is out of range.</exception>
public MusicID(int value)
{
if (value < MinValue || value > MaxValue)
throw new ArgumentOutOfRangeException("value");
_value = (ushort)value;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="other">Another object to compare to.</param>
/// <returns>
/// True if <paramref name="other"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
public bool Equals(MusicID other)
{
return other._value == _value;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns>
/// True if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
public override bool Equals(object obj)
{
return obj is MusicID && this == (MusicID)obj;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>
/// A 32-bit signed integer that is the hash code for this instance.
/// </returns>
public override int GetHashCode()
{
return _value.GetHashCode();
}
/// <summary>
/// Gets the raw internal value of this MusicID.
/// </summary>
/// <returns>The raw internal value.</returns>
public ushort GetRawValue()
{
return _value;
}
/// <summary>
/// Reads an MusicID from an IValueReader.
/// </summary>
/// <param name="reader">IValueReader to read from.</param>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>The MusicID read from the IValueReader.</returns>
public static MusicID Read(IValueReader reader, string name)
{
var value = reader.ReadUShort(name);
return new MusicID(value);
}
/// <summary>
/// Reads an MusicID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param>
/// <param name="i">The index of the field to find.</param>
/// <returns>The MusicID read from the <see cref="IDataRecord"/>.</returns>
public static MusicID Read(IDataRecord reader, int i)
{
var value = reader.GetValue(i);
if (value is ushort)
return new MusicID((ushort)value);
var convertedValue = Convert.ToUInt16(value);
return new MusicID(convertedValue);
}
/// <summary>
/// Reads an MusicID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param>
/// <param name="name">The name of the field to find.</param>
/// <returns>The MusicID read from the <see cref="IDataRecord"/>.</returns>
public static MusicID Read(IDataRecord reader, string name)
{
return Read(reader, reader.GetOrdinal(name));
}
/// <summary>
/// Reads an MusicID from an IValueReader.
/// </summary>
/// <param name="bitStream">BitStream to read from.</param>
/// <returns>The MusicID read from the BitStream.</returns>
public static MusicID Read(BitStream bitStream)
{
var value = bitStream.ReadUShort();
return new MusicID(value);
}
/// <summary>
/// Converts the numeric value of this instance to its equivalent string representation.
/// </summary>
/// <returns>The string representation of the value of this instance, consisting of a sequence
/// of digits ranging from 0 to 9, without leading zeroes.</returns>
public override string ToString()
{
return _value.ToString();
}
/// <summary>
/// Writes the MusicID to an IValueWriter.
/// </summary>
/// <param name="writer">IValueWriter to write to.</param>
/// <param name="name">Unique name of the MusicID that will be used to distinguish it
/// from other values when reading.</param>
public void Write(IValueWriter writer, string name)
{
writer.Write(name, _value);
}
/// <summary>
/// Writes the MusicID to an IValueWriter.
/// </summary>
/// <param name="bitStream">BitStream to write to.</param>
public void Write(BitStream bitStream)
{
bitStream.Write(_value);
}
#region IComparable<int> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(int other)
{
return _value.CompareTo(other);
}
#endregion
#region IComparable<MusicID> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared.
/// The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(MusicID other)
{
return _value.CompareTo(other._value);
}
#endregion
#region IConvertible Members
/// <summary>
/// Returns the <see cref="T:System.TypeCode"/> for this instance.
/// </summary>
/// <returns>
/// The enumerated constant that is the <see cref="T:System.TypeCode"/> of the class or value type that implements this interface.
/// </returns>
public TypeCode GetTypeCode()
{
return _value.GetTypeCode();
}
/// <summary>
/// Converts the value of this instance to an equivalent Boolean value using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation
/// that supplies culture-specific formatting information.</param>
/// <returns>
/// A Boolean value equivalent to the value of this instance.
/// </returns>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return ((IConvertible)_value).ToBoolean(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 8-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 8-bit unsigned integer equivalent to the value of this instance.
/// </returns>
byte IConvertible.ToByte(IFormatProvider provider)
{
return ((IConvertible)_value).ToByte(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent Unicode character using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A Unicode character equivalent to the value of this instance.
/// </returns>
char IConvertible.ToChar(IFormatProvider provider)
{
return ((IConvertible)_value).ToChar(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.DateTime"/> using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A <see cref="T:System.DateTime"/> instance equivalent to the value of this instance.
/// </returns>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return ((IConvertible)_value).ToDateTime(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.Decimal"/> number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information. </param>
/// <returns>
/// A <see cref="T:System.Decimal"/> number equivalent to the value of this instance.
/// </returns>
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return ((IConvertible)_value).ToDecimal(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent double-precision floating-point number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A double-precision floating-point number equivalent to the value of this instance.
/// </returns>
double IConvertible.ToDouble(IFormatProvider provider)
{
return ((IConvertible)_value).ToDouble(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 16-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 16-bit signed integer equivalent to the value of this instance.
/// </returns>
short IConvertible.ToInt16(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt16(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 32-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 32-bit signed integer equivalent to the value of this instance.
/// </returns>
int IConvertible.ToInt32(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt32(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 64-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 64-bit signed integer equivalent to the value of this instance.
/// </returns>
long IConvertible.ToInt64(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt64(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 8-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 8-bit signed integer equivalent to the value of this instance.
/// </returns>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return ((IConvertible)_value).ToSByte(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent single-precision floating-point number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information. </param>
/// <returns>
/// A single-precision floating-point number equivalent to the value of this instance.
/// </returns>
float IConvertible.ToSingle(IFormatProvider provider)
{
return ((IConvertible)_value).ToSingle(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.String"/> using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A <see cref="T:System.String"/> instance equivalent to the value of this instance.
/// </returns>
public string ToString(IFormatProvider provider)
{
return ((IConvertible)_value).ToString(provider);
}
/// <summary>
/// Converts the value of this instance to an <see cref="T:System.Object"/> of the specified <see cref="T:System.Type"/> that has an equivalent value, using the specified culture-specific formatting information.
/// </summary>
/// <param name="conversionType">The <see cref="T:System.Type"/> to which the value of this instance is converted.</param>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An <see cref="T:System.Object"/> instance of type <paramref name="conversionType"/> whose value is equivalent to the value of this instance.
/// </returns>
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return ((IConvertible)_value).ToType(conversionType, provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 16-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 16-bit unsigned integer equivalent to the value of this instance.
/// </returns>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt16(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 32-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 32-bit unsigned integer equivalent to the value of this instance.
/// </returns>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt32(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 64-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 64-bit unsigned integer equivalent to the value of this instance.
/// </returns>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt64(provider);
}
#endregion
#region IEquatable<int> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(int other)
{
return _value.Equals(other);
}
#endregion
#region IFormattable Members
/// <summary>
/// Formats the value of the current instance using the specified format.
/// </summary>
/// <param name="format">The <see cref="T:System.String"/> specifying the format to use.
/// -or-
/// null to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.
/// </param>
/// <param name="formatProvider">The <see cref="T:System.IFormatProvider"/> to use to format the value.
/// -or-
/// null to obtain the numeric format information from the current locale setting of the operating system.
/// </param>
/// <returns>
/// A <see cref="T:System.String"/> containing the value of the current instance in the specified format.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return _value.ToString(format, formatProvider);
}
#endregion
/// <summary>
/// Implements operator ++.
/// </summary>
/// <param name="l">The MusicID to increment.</param>
/// <returns>The incremented MusicID.</returns>
public static MusicID operator ++(MusicID l)
{
return new MusicID(l._value + 1);
}
/// <summary>
/// Implements operator --.
/// </summary>
/// <param name="l">The MusicID to decrement.</param>
/// <returns>The decremented MusicID.</returns>
public static MusicID operator --(MusicID l)
{
return new MusicID(l._value - 1);
}
/// <summary>
/// Implements operator +.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>Result of the left side plus the right side.</returns>
public static MusicID operator +(MusicID left, MusicID right)
{
return new MusicID(left._value + right._value);
}
/// <summary>
/// Implements operator -.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>Result of the left side minus the right side.</returns>
public static MusicID operator -(MusicID left, MusicID right)
{
return new MusicID(left._value - right._value);
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(MusicID left, int right)
{
return left._value == right;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(MusicID left, int right)
{
return left._value != right;
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(int left, MusicID right)
{
return left == right._value;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(int left, MusicID right)
{
return left != right._value;
}
/// <summary>
/// Casts a MusicID to an Int32.
/// </summary>
/// <param name="MusicID">MusicID to cast.</param>
/// <returns>The Int32.</returns>
public static explicit operator int(MusicID MusicID)
{
return MusicID._value;
}
/// <summary>
/// Casts an Int32 to a MusicID.
/// </summary>
/// <param name="value">Int32 to cast.</param>
/// <returns>The MusicID.</returns>
public static explicit operator MusicID(int value)
{
return new MusicID(value);
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(int left, MusicID right)
{
return left > right._value;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(int left, MusicID right)
{
return left < right._value;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(MusicID left, MusicID right)
{
return left._value > right._value;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(MusicID left, MusicID right)
{
return left._value < right._value;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(MusicID left, int right)
{
return left._value > right;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(MusicID left, int right)
{
return left._value < right;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(int left, MusicID right)
{
return left >= right._value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(int left, MusicID right)
{
return left <= right._value;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(MusicID left, int right)
{
return left._value >= right;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(MusicID left, int right)
{
return left._value <= right;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(MusicID left, MusicID right)
{
return left._value >= right._value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(MusicID left, MusicID right)
{
return left._value <= right._value;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(MusicID left, MusicID right)
{
return left._value != right._value;
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(MusicID left, MusicID right)
{
return left._value == right._value;
}
}
/// <summary>
/// Adds extensions to some data I/O objects for performing Read and Write operations for the MusicID.
/// All of the operations are implemented in the MusicID struct. These extensions are provided
/// purely for the convenience of accessing all the I/O operations from the same place.
/// </summary>
public static class MusicIDReadWriteExtensions
{
/// <summary>
/// Gets the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type MusicID.
/// </summary>
/// <typeparam name="T">The key Type.</typeparam>
/// <param name="dict">The IDictionary.</param>
/// <param name="key">The key for the value to get.</param>
/// <returns>The value at the given <paramref name="key"/> parsed as a MusicID.</returns>
public static MusicID AsMusicID<T>(this IDictionary<T, string> dict, T key)
{
return Parser.Invariant.ParseMusicID(dict[key]);
}
/// <summary>
/// Tries to get the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type MusicID.
/// </summary>
/// <typeparam name="T">The key Type.</typeparam>
/// <param name="dict">The IDictionary.</param>
/// <param name="key">The key for the value to get.</param>
/// <param name="defaultValue">The value to use if the value at the <paramref name="key"/> could not be parsed.</param>
/// <returns>The value at the given <paramref name="key"/> parsed as an int, or the
/// <paramref name="defaultValue"/> if the <paramref name="key"/> did not exist in the <paramref name="dict"/>
/// or the value at the given <paramref name="key"/> could not be parsed.</returns>
public static MusicID AsMusicID<T>(this IDictionary<T, string> dict, T key, MusicID defaultValue)
{
string value;
if (!dict.TryGetValue(key, out value))
return defaultValue;
MusicID parsed;
if (!Parser.Invariant.TryParse(value, out parsed))
return defaultValue;
return parsed;
}
/// <summary>
/// Reads the MusicID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="r"><see cref="IDataRecord"/> to read the MusicID from.</param>
/// <param name="i">The field index to read.</param>
/// <returns>The MusicID read from the <see cref="IDataRecord"/>.</returns>
public static MusicID GetMusicID(this IDataRecord r, int i)
{
return MusicID.Read(r, i);
}
/// <summary>
/// Reads the MusicID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="r"><see cref="IDataRecord"/> to read the MusicID from.</param>
/// <param name="name">The name of the field to read the value from.</param>
/// <returns>The MusicID read from the <see cref="IDataRecord"/>.</returns>
public static MusicID GetMusicID(this IDataRecord r, string name)
{
return MusicID.Read(r, name);
}
/// <summary>
/// Parses the MusicID from a string.
/// </summary>
/// <param name="parser">The Parser to use.</param>
/// <param name="value">The string to parse.</param>
/// <returns>The MusicID parsed from the string.</returns>
public static MusicID ParseMusicID(this Parser parser, string value)
{
return new MusicID(parser.ParseUShort(value));
}
/// <summary>
/// Reads the MusicID from a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to read the MusicID from.</param>
/// <returns>The MusicID read from the BitStream.</returns>
public static MusicID ReadMusicID(this BitStream bitStream)
{
return MusicID.Read(bitStream);
}
/// <summary>
/// Reads the MusicID from an IValueReader.
/// </summary>
/// <param name="valueReader">IValueReader to read the MusicID from.</param>
/// <param name="name">The unique name of the value to read.</param>
/// <returns>The MusicID read from the IValueReader.</returns>
public static MusicID ReadMusicID(this IValueReader valueReader, string name)
{
return MusicID.Read(valueReader, name);
}
/// <summary>
/// Tries to parse the MusicID from a string.
/// </summary>
/// <param name="parser">The Parser to use.</param>
/// <param name="value">The string to parse.</param>
/// <param name="outValue">If this method returns true, contains the parsed MusicID.</param>
/// <returns>True if the parsing was successfully; otherwise false.</returns>
public static bool TryParse(this Parser parser, string value, out MusicID outValue)
{
ushort tmp;
var ret = parser.TryParse(value, out tmp);
outValue = new MusicID(tmp);
return ret;
}
/// <summary>
/// Writes a MusicID to a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to write to.</param>
/// <param name="value">MusicID to write.</param>
public static void Write(this BitStream bitStream, MusicID value)
{
value.Write(bitStream);
}
/// <summary>
/// Writes a MusicID to a IValueWriter.
/// </summary>
/// <param name="valueWriter">IValueWriter to write to.</param>
/// <param name="name">Unique name of the MusicID that will be used to distinguish it
/// from other values when reading.</param>
/// <param name="value">MusicID to write.</param>
public static void Write(this IValueWriter valueWriter, string name, MusicID value)
{
value.Write(valueWriter, name);
}
}
}
| |
// _________________________________________________________________________________________
// Name: BaseWPHHelpers
// Purpose: Common helpers for tree walking etc
// Author: Andrew Whiddett
// (c) Copyright 2006 REZN8 Productions Inc
// _________________________________________________________________________________________
#region Using
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Configuration;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
#endregion
namespace BaseWPFHelpers
{
public class Helpers
{
/// <summary>
/// Helper method to create a snapshot of a visual item as a bitmap image. Typically used for things like drag and drop
/// or any time we want to do something where we don't want the hit of a video running in an animating object
/// </summary>
/// <param name="element">Element to take a snapshot of</param>
/// <returns>Bitmap image of the element</returns>
public static RenderTargetBitmap CreateImageBrushFromVisual(FrameworkElement element)
{
RenderTargetBitmap bitmapImage =
new RenderTargetBitmap((int)element.ActualWidth,
(int)element.ActualHeight,
96, 96,
PixelFormats.Pbgra32);
bitmapImage.Render(element);
return bitmapImage;
}
/// <summary>
/// Base Interface that describes the visual match pattern
/// Part of the Visual tree walkers
/// </summary>
public interface IFinderMatchVisualHelper
{
/// <summary>
/// Does this item match the input visual item
/// </summary>
/// <param name="item">Item to check </param>
/// <returns>True if matched, else false</returns>
bool DoesMatch(DependencyObject item);
/// <summary>
/// Property that defines if we should stop walking the tree after the first match is found
/// </summary>
bool StopAfterFirst
{
get;
set;
}
}
/// <summary>
/// Visual tree walker class that matches based on Type
/// </summary>
public class FinderMatchType : IFinderMatchVisualHelper
{
private Type _ty = null;
private bool _stopafterfirst = false;
public FinderMatchType(Type ty)
{
_ty = ty;
}
public FinderMatchType(Type ty, bool StopAfterFirst)
{
_ty = ty;
_stopafterfirst = StopAfterFirst;
}
public bool DoesMatch(DependencyObject item)
{
return _ty.IsInstanceOfType(item);
}
public bool StopAfterFirst
{
get
{
return _stopafterfirst;
}
set
{
_stopafterfirst = value;
}
}
}
/// <summary>
/// Visual tree walker function that matches on name of an element
/// </summary>
public class FinderMatchName : IFinderMatchVisualHelper
{
private String _name = "";
public FinderMatchName(String name)
{
_name = name;
}
public bool DoesMatch(DependencyObject item)
{
bool bMatch = false;
if (item is FrameworkElement)
{
if ((item as FrameworkElement).Name == _name) bMatch = true;
}
return bMatch;
}
/// <summary>
/// StopAfterFirst Property.. always true, you can't have more than one of the same name..
/// </summary>
public bool StopAfterFirst
{
get
{
return true;
}
set
{
}
}
}
/// <summary>
/// Visual tree helper that matches if the item is focused
/// </summary>
public class FinderMatchFocused : IFinderMatchVisualHelper
{
public bool DoesMatch(DependencyObject item)
{
bool bMatch = false;
if (item is FrameworkElement)
{
if ((item as FrameworkElement).IsFocused) bMatch = true;
}
return bMatch;
}
/// <summary>
/// StopAfterFirst Property.. always true, you can't have more than one item in focus..
/// </summary>
public bool StopAfterFirst
{
get
{
return true;
}
set
{
}
}
}
/// <summary>
/// Visual tree helper that matches is the item is an itemshost. Typically used in ItemControls
/// </summary>
public class FinderMatchItemHost : IFinderMatchVisualHelper
{
public bool DoesMatch(DependencyObject item)
{
bool bMatch = false;
if (item is Panel)
{
if ((item as Panel).IsItemsHost) bMatch = true;
}
return bMatch;
}
/// <summary>
/// StopAfterFirst Property.. always true, you can't have more than one item host in an item control..
/// </summary>
public bool StopAfterFirst
{
get
{
return true;
}
set
{
}
}
}
/// <summary>
/// Typically used method that walks down the visual tree from a given point to locate a given match only
/// once. Typically used with Name/ItemHost etc type matching.
///
/// Only returns one element
/// </summary>
/// <param name="parent">Start point in the tree to search</param>
/// <param name="helper">Match Helper to use</param>
/// <returns>Null if no match, else returns the first element that matches</returns>
public static FrameworkElement SingleFindDownInTree(Visual parent, IFinderMatchVisualHelper helper)
{
helper.StopAfterFirst = true;
List<FrameworkElement> lst = FindDownInTree(parent, helper);
FrameworkElement feRet = null;
if (lst.Count > 0) feRet = lst[0];
return feRet;
}
/// <summary>
/// All way visual tree helper that searches UP and DOWN in a tree for the matching pattern.
///
/// This is used to walk for name matches or type matches typically.
///
/// Returns only the first matching element
/// </summary>
/// <param name="parent">Start point in the tree to search</param>
/// <param name="helper">Match Helper to use</param>
/// <returns>Null if no match, else returns the first element that matches</returns>
public static FrameworkElement SingleFindInTree(Visual parent, IFinderMatchVisualHelper helper)
{
helper.StopAfterFirst = true;
List<FrameworkElement> lst = FindInTree(parent, helper);
FrameworkElement feRet = null;
if (lst.Count > 0) feRet = lst[0];
return feRet;
}
/// <summary>
/// Walker that looks down in the visual tree for any matching elements, typically used with Type
/// </summary>
/// <param name="parent">Start point in the tree to search</param>
/// <param name="helper">Match Helper to use</param>
/// <returns>List of matching FrameworkElements</returns>
public static List<FrameworkElement> FindDownInTree(Visual parent, IFinderMatchVisualHelper helper)
{
List<FrameworkElement> lst = new List<FrameworkElement>();
FindDownInTree(lst, parent, null, helper);
return lst;
}
/// <summary>
/// Walker that looks both UP and down in the visual tree for any matching elements, typically used with Type
/// </summary>
/// <param name="parent">Start point in the tree to search</param>
/// <param name="helper">Match Helper to use</param>
/// <returns>List of matching FrameworkElements</returns>
public static List<FrameworkElement> FindInTree(Visual parent, IFinderMatchVisualHelper helper)
{
List<FrameworkElement> lst = new List<FrameworkElement>();
FindUpInTree(lst, parent, null, helper);
return lst;
}
/// <summary>
/// Really a helper for FindDownInTree, typically not called directly.
/// </summary>
/// <param name="lst"></param>
/// <param name="parent"></param>
/// <param name="ignore"></param>
/// <param name="helper"></param>
public static void FindDownInTree(List<FrameworkElement> lst, DependencyObject parent, DependencyObject ignore, IFinderMatchVisualHelper helper)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
if (lst.Count > 0 && helper.StopAfterFirst) break;
DependencyObject visual = VisualTreeHelper.GetChild(parent, i);
if (visual is FrameworkElement)
{
(visual as FrameworkElement).ApplyTemplate();
}
if (helper.DoesMatch(visual))
{
lst.Add(visual as FrameworkElement);
}
if (lst.Count > 0 && helper.StopAfterFirst) break;
if (visual != ignore)
{
FindDownInTree(lst, visual, ignore, helper);
}
}
}
/// <summary>
/// Really a helper to look Up in a tree, typically not called directly.
/// </summary>
/// <param name="lst"></param>
/// <param name="parent"></param>
/// <param name="ignore"></param>
/// <param name="helper"></param>
public static void FindUpInTree(List<FrameworkElement> lst, Visual parent, Visual ignore, IFinderMatchVisualHelper helper)
{
// First thing to do is find Down in the existing node...
//FindDownInTree(lst, parent, ignore, helper);
if (helper.DoesMatch(parent))
{
lst.Add(parent as FrameworkElement);
}
// Ok, now check to see we are not at a stop.. i.e. got it.
if (lst.Count > 0 && helper.StopAfterFirst)
{
// Hum, don't think we need to do anything here: yet.
}
else
{
// Ok, now try to get a new parent...
FrameworkElement feCast = parent as FrameworkElement;
if (feCast != null)
{
FrameworkElement feNewParent = feCast.Parent as FrameworkElement;
if (feNewParent == null || feNewParent == feCast)
{
// Try to get the templated parent
feNewParent = feCast.TemplatedParent as FrameworkElement;
}
// Now check to see that we have a valid parent
if (feNewParent != null && feNewParent != feCast)
{
// Pass up
FindUpInTree(lst, feNewParent, feCast, helper);
}
}
}
}
/// <summary>
/// Simple form call that returns all elements of a given type down in the visual tree
/// </summary>
/// <param name="parent"></param>
/// <param name="ty"></param>
/// <returns></returns>
public static List<FrameworkElement> FindElementsOfType(Visual parent, Type ty)
{
return FindDownInTree(parent, new FinderMatchType(ty));
}
/// <summary>
/// Simple form call that returns the first element of a given type down in the visual tree
/// </summary>
/// <param name="parent"></param>
/// <param name="ty"></param>
/// <returns></returns>
public static FrameworkElement FindElementOfType(Visual parent, Type ty)
{
return SingleFindDownInTree(parent, new FinderMatchType(ty));
}
/// <summary>
/// Simple form call that returns the first element of a given type up in the visual tree
/// </summary>
/// <param name="parent"></param>
/// <param name="ty"></param>
/// <returns></returns>
public static FrameworkElement FindElementOfTypeUp(Visual parent, Type ty)
{
return SingleFindInTree(parent, new FinderMatchType(ty));
}
/// <summary>
/// Helper to pause any media elements down in the visual tree
/// </summary>
/// <param name="parent"></param>
public static void TurnOffMediaElements(Visual parent)
{
List<FrameworkElement> lst = FindElementsOfType(parent,typeof(MediaElement));
foreach (FrameworkElement me in lst)
{
MediaElement meCast = me as MediaElement;
if (meCast != null)
{
if (meCast.CanPause)
{
try
{
meCast.Pause();
}
catch (Exception )
{
}
}
}
}
}
/// <summary>
/// Helper to resume playing any media elements down in the visual tree
/// </summary>
/// <param name="parent"></param>
public static void TurnOnMediaElements(Visual parent)
{
List<FrameworkElement> lst = FindElementsOfType(parent, typeof(MediaElement));
foreach (FrameworkElement me in lst)
{
MediaElement meCast = me as MediaElement;
if (meCast != null)
{
try
{
meCast.Play();
}
catch (Exception )
{
}
}
}
}
/// <summary>
/// Helper to find the currently focused element
/// </summary>
/// <param name="parent"></param>
/// <returns></returns>
public static FrameworkElement FindFocusedElement(Visual parent)
{
return SingleFindInTree(parent, new FinderMatchFocused());
}
/// <summary>
/// Helper to find a items host (e.g. in a listbox etc) down in the tree
/// </summary>
/// <param name="parent"></param>
/// <returns></returns>
public static FrameworkElement FindItemsHost(Visual parent)
{
return SingleFindDownInTree(parent, new FinderMatchItemHost());
}
/// <summary>
/// Helper to find the given named element down in the visual tree
/// </summary>
/// <param name="parent"></param>
/// <param name="ElementName"></param>
/// <returns></returns>
public static FrameworkElement FindVisualElement(Visual parent, String ElementName)
{
return SingleFindDownInTree(parent, new FinderMatchName(ElementName));
}
/// <summary>
/// Helper to find the given named element up in the visual tree
/// </summary>
/// <param name="parent"></param>
/// <param name="ElementName"></param>
/// <returns></returns>
public static FrameworkElement FindVisualElementUp(Visual parent, String ElementName)
{
return SingleFindInTree(parent, new FinderMatchName(ElementName));
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq.Expressions;
using System.Text;
using Irony.Ast;
namespace Irony.Parsing {
public class Grammar {
#region properties
/// <summary>
/// Gets case sensitivity of the grammar. Read-only, true by default.
/// Can be set to false only through a parameter to grammar constructor.
/// </summary>
public readonly bool CaseSensitive;
//List of chars that unambigously identify the start of new token.
//used in scanner error recovery, and in quick parse path in NumberLiterals, Identifiers
[Obsolete("Use IsWhitespaceOrDelimiter() method instead.")]
public string Delimiters = null;
[Obsolete("Override Grammar.SkipWhitespace method instead.")]
// Not used anymore
public string WhitespaceChars = " \t\r\n\v";
public LanguageFlags LanguageFlags = LanguageFlags.Default;
public TermReportGroupList TermReportGroups = new TermReportGroupList();
//Terminals not present in grammar expressions and not reachable from the Root
// (Comment terminal is usually one of them)
// Tokens produced by these terminals will be ignored by parser input.
public readonly TerminalSet NonGrammarTerminals = new TerminalSet();
/// <summary>
/// The main root entry for the grammar.
/// </summary>
public NonTerminal Root;
/// <summary>
/// Alternative roots for parsing code snippets.
/// </summary>
public NonTerminalSet SnippetRoots = new NonTerminalSet();
public string GrammarComments; //shown in Grammar info tab
public CultureInfo DefaultCulture = CultureInfo.InvariantCulture;
//Console-related properties, initialized in grammar constructor
public string ConsoleTitle;
public string ConsoleGreeting;
public string ConsolePrompt; //default prompt
public string ConsolePromptMoreInput; //prompt to show when more input is expected
#endregion
#region constructors
public Grammar() : this(true) { } //case sensitive by default
public Grammar(bool caseSensitive) {
_currentGrammar = this;
this.CaseSensitive = caseSensitive;
var stringComparer = caseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
KeyTerms = new KeyTermTable(stringComparer);
//Initialize console attributes
ConsoleTitle = Resources.MsgDefaultConsoleTitle;
ConsoleGreeting = string.Format(Resources.MsgDefaultConsoleGreeting, this.GetType().Name);
ConsolePrompt = ">";
ConsolePromptMoreInput = ".";
}
#endregion
#region Reserved words handling
//Reserved words handling
public void MarkReservedWords(params string[] reservedWords) {
foreach (var word in reservedWords) {
var wdTerm = ToTerm(word);
wdTerm.SetFlag(TermFlags.IsReservedWord);
}
}
#endregion
#region Register/Mark methods
public void RegisterOperators(int precedence, params string[] opSymbols) {
RegisterOperators(precedence, Associativity.Left, opSymbols);
}
public void RegisterOperators(int precedence, Associativity associativity, params string[] opSymbols) {
foreach (string op in opSymbols) {
KeyTerm opSymbol = ToTerm(op);
opSymbol.SetFlag(TermFlags.IsOperator);
opSymbol.Precedence = precedence;
opSymbol.Associativity = associativity;
}
}//method
public void RegisterOperators(int precedence, params BnfTerm[] opTerms) {
RegisterOperators(precedence, Associativity.Left, opTerms);
}
public void RegisterOperators(int precedence, Associativity associativity, params BnfTerm[] opTerms) {
foreach (var term in opTerms) {
term.SetFlag(TermFlags.IsOperator);
term.Precedence = precedence;
term.Associativity = associativity;
}
}
public void RegisterBracePair(string openBrace, string closeBrace) {
KeyTerm openS = ToTerm(openBrace);
KeyTerm closeS = ToTerm(closeBrace);
openS.SetFlag(TermFlags.IsOpenBrace);
openS.IsPairFor = closeS;
closeS.SetFlag(TermFlags.IsCloseBrace);
closeS.IsPairFor = openS;
}
public void MarkPunctuation(params string[] symbols) {
foreach (string symbol in symbols) {
KeyTerm term = ToTerm(symbol);
term.SetFlag(TermFlags.IsPunctuation|TermFlags.NoAstNode);
}
}
public void MarkPunctuation(params BnfTerm[] terms) {
foreach (BnfTerm term in terms)
term.SetFlag(TermFlags.IsPunctuation|TermFlags.NoAstNode);
}
public void MarkTransient(params NonTerminal[] nonTerminals) {
foreach (NonTerminal nt in nonTerminals)
nt.Flags |= TermFlags.IsTransient | TermFlags.NoAstNode;
}
//MemberSelect are symbols invoking member list dropdowns in editor; for ex: . (dot), ::
public void MarkMemberSelect(params string[] symbols) {
foreach (var symbol in symbols)
ToTerm(symbol).SetFlag(TermFlags.IsMemberSelect);
}
//Sets IsNotReported flag on terminals. As a result the terminal wouldn't appear in expected terminal list
// in syntax error messages
public void MarkNotReported(params BnfTerm[] terms) {
foreach (var term in terms)
term.SetFlag(TermFlags.IsNotReported);
}
public void MarkNotReported(params string[] symbols) {
foreach (var symbol in symbols)
ToTerm(symbol).SetFlag(TermFlags.IsNotReported);
}
#endregion
#region virtual methods: CreateTokenFilters, TryMatch
public virtual void CreateTokenFilters(LanguageData language, TokenFilterList filters) {
}
//This method is called if Scanner fails to produce a token; it offers custom method a chance to produce the token
public virtual Token TryMatch(ParsingContext context, ISourceStream source) {
return null;
}
//Gives a way to customize parse tree nodes captions in the tree view.
public virtual string GetParseNodeCaption(ParseTreeNode node) {
if (node.IsError)
return node.Term.Name + " (Syntax error)";
if (node.Token != null)
return node.Token.ToString();
if(node.Term == null) //special case for initial node pushed into the stack at parser start
return (node.State != null ? string.Empty : "(State " + node.State.Name + ")"); // Resources.LabelInitialState;
var ntTerm = node.Term as NonTerminal;
if(ntTerm != null && !string.IsNullOrEmpty(ntTerm.NodeCaptionTemplate))
return ntTerm.GetNodeCaption(node);
return node.Term.Name;
}
/// <summary>
/// Override this method to help scanner select a terminal to create token when there are more than one candidates
/// for an input char. context.CurrentTerminals contains candidate terminals; leave a single terminal in this list
/// as the one to use.
/// </summary>
public virtual void OnScannerSelectTerminal(ParsingContext context) { }
/// <summary>Skips whitespace characters in the input stream. </summary>
/// <remarks>Override this method if your language has non-standard whitespace characters.</remarks>
/// <param name="source">Source stream.</param>
public virtual void SkipWhitespace(ISourceStream source) {
while (!source.EOF()) {
switch (source.PreviewChar) {
case ' ': case '\t':
break;
case '\r': case '\n': case '\v':
if (UsesNewLine) return; //do not treat as whitespace if language is line-based
break;
default:
return;
}//switch
source.PreviewPosition++;
}//while
}//method
/// <summary>Returns true if a character is whitespace or delimiter. Used in quick-scanning versions of some terminals. </summary>
/// <param name="ch">The character to check.</param>
/// <returns>True if a character is whitespace or delimiter; otherwise, false.</returns>
/// <remarks>Does not have to be completely accurate, should recognize most common characters that are special chars by themselves
/// and may never be part of other multi-character tokens. </remarks>
public virtual bool IsWhitespaceOrDelimiter(char ch) {
switch (ch) {
case ' ': case '\t': case '\r': case '\n': case '\v': //whitespaces
case '(': case ')': case ',': case ';': case '[': case ']': case '{': case '}':
case (char)0: //EOF
return true;
default:
return false;
}//switch
}//method
//The method is called after GrammarData is constructed
public virtual void OnGrammarDataConstructed(LanguageData language) {
}
public virtual void OnLanguageDataConstructed(LanguageData language) {
}
//Constructs the error message in situation when parser has no available action for current input.
// override this method if you want to change this message
public virtual string ConstructParserErrorMessage(ParsingContext context, StringSet expectedTerms) {
if(expectedTerms.Count > 0)
return string.Format(Resources.ErrSyntaxErrorExpected, expectedTerms.ToString(", "));
else
return Resources.ErrParserUnexpectedInput;
}
// Override this method to perform custom error processing
public virtual void ReportParseError(ParsingContext context) {
string error = null;
if (context.CurrentParserInput.Term == this.SyntaxError)
error = context.CurrentParserInput.Token.Value as string; //scanner error
else if (context.CurrentParserInput.Term == this.Indent)
error = Resources.ErrUnexpIndent;
else if (context.CurrentParserInput.Term == this.Eof && context.OpenBraces.Count > 0) {
if (context.OpenBraces.Count > 0) {
//report unclosed braces/parenthesis
var openBrace = context.OpenBraces.Peek();
error = string.Format(Resources.ErrNoClosingBrace, openBrace.Text);
} else
error = Resources.ErrUnexpEof;
}else {
var expectedTerms = context.GetExpectedTermSet();
error = ConstructParserErrorMessage(context, expectedTerms);
}
context.AddParserError(error);
}//method
#endregion
#region MakePlusRule, MakeStarRule methods
public BnfExpression MakePlusRule(NonTerminal listNonTerminal, BnfTerm listMember) {
return MakeListRule(listNonTerminal, null, listMember);
}
public BnfExpression MakePlusRule(NonTerminal listNonTerminal, BnfTerm delimiter, BnfTerm listMember) {
return MakeListRule(listNonTerminal, delimiter, listMember);
}
public BnfExpression MakeStarRule(NonTerminal listNonTerminal, BnfTerm listMember) {
return MakeListRule(listNonTerminal, null, listMember, TermListOptions.StarList);
}
public BnfExpression MakeStarRule(NonTerminal listNonTerminal, BnfTerm delimiter, BnfTerm listMember) {
return MakeListRule(listNonTerminal, delimiter, listMember, TermListOptions.StarList);
}
protected BnfExpression MakeListRule(NonTerminal list, BnfTerm delimiter, BnfTerm listMember, TermListOptions options = TermListOptions.PlusList) {
//If it is a star-list (allows empty), then we first build plus-list
var isPlusList = !options.IsSet(TermListOptions.AllowEmpty);
var allowTrailingDelim = options.IsSet(TermListOptions.AllowTrailingDelimiter) && delimiter != null;
//"plusList" is the list for which we will construct expression - it is either extra plus-list or original list.
// In the former case (extra plus-list) we will use it later to construct expression for list
NonTerminal plusList = isPlusList ? list : new NonTerminal(listMember.Name + "+");
plusList.SetFlag(TermFlags.IsList);
plusList.Rule = plusList; // rule => list
if (delimiter != null)
plusList.Rule += delimiter; // rule => list + delim
if (options.IsSet(TermListOptions.AddPreferShiftHint))
plusList.Rule += PreferShiftHere(); // rule => list + delim + PreferShiftHere()
plusList.Rule += listMember; // rule => list + delim + PreferShiftHere() + elem
plusList.Rule |= listMember; // rule => list + delim + PreferShiftHere() + elem | elem
if (isPlusList) {
// if we build plus list - we're almost done; plusList == list
// add trailing delimiter if necessary; for star list we'll add it to final expression
if (allowTrailingDelim)
plusList.Rule |= list + delimiter; // rule => list + delim + PreferShiftHere() + elem | elem | list + delim
} else {
// Setup list.Rule using plus-list we just created
list.Rule = Empty | plusList;
if (allowTrailingDelim)
list.Rule |= plusList + delimiter | delimiter;
plusList.SetFlag(TermFlags.NoAstNode);
list.SetFlag(TermFlags.IsListContainer); //indicates that real list is one level lower
}
return list.Rule;
}//method
#endregion
#region Hint utilities
protected GrammarHint PreferShiftHere() {
return new PreferredActionHint(PreferredActionType.Shift);
}
protected GrammarHint ReduceHere() {
return new PreferredActionHint(PreferredActionType.Reduce);
}
protected TokenPreviewHint ReduceIf(string thisSymbol, params string[] comesBefore) {
return new TokenPreviewHint(PreferredActionType.Reduce, thisSymbol, comesBefore);
}
protected TokenPreviewHint ReduceIf(Terminal thisSymbol, params Terminal[] comesBefore) {
return new TokenPreviewHint(PreferredActionType.Reduce, thisSymbol, comesBefore);
}
protected TokenPreviewHint ShiftIf(string thisSymbol, params string[] comesBefore) {
return new TokenPreviewHint(PreferredActionType.Shift, thisSymbol, comesBefore);
}
protected TokenPreviewHint ShiftIf(Terminal thisSymbol, params Terminal[] comesBefore) {
return new TokenPreviewHint(PreferredActionType.Shift, thisSymbol, comesBefore);
}
protected GrammarHint ImplyPrecedenceHere(int precedence) {
return ImplyPrecedenceHere(precedence, Associativity.Left);
}
protected GrammarHint ImplyPrecedenceHere(int precedence, Associativity associativity) {
return new ImpliedPrecedenceHint(precedence, associativity);
}
protected CustomActionHint CustomActionHere(ExecuteActionMethod executeMethod, PreviewActionMethod previewMethod = null) {
return new CustomActionHint(executeMethod, previewMethod);
}
#endregion
#region Term report group methods
/// <summary>
/// Creates a terminal reporting group, so all terminals in the group will be reported as a single "alias" in syntex error messages like
/// "Syntax error, expected: [list of terms]"
/// </summary>
/// <param name="alias">An alias for all terminals in the group.</param>
/// <param name="symbols">Symbols to be included into the group.</param>
protected void AddTermsReportGroup(string alias, params string[] symbols) {
TermReportGroups.Add(new TermReportGroup(alias, TermReportGroupType.Normal, SymbolsToTerms(symbols)));
}
/// <summary>
/// Creates a terminal reporting group, so all terminals in the group will be reported as a single "alias" in syntex error messages like
/// "Syntax error, expected: [list of terms]"
/// </summary>
/// <param name="alias">An alias for all terminals in the group.</param>
/// <param name="terminals">Terminals to be included into the group.</param>
protected void AddTermsReportGroup(string alias, params Terminal[] terminals) {
TermReportGroups.Add(new TermReportGroup(alias, TermReportGroupType.Normal, terminals));
}
/// <summary>
/// Adds symbols to a group with no-report type, so symbols will not be shown in expected lists in syntax error messages.
/// </summary>
/// <param name="symbols">Symbols to exclude.</param>
protected void AddToNoReportGroup(params string[] symbols) {
TermReportGroups.Add(new TermReportGroup(string.Empty, TermReportGroupType.DoNotReport, SymbolsToTerms(symbols)));
}
/// <summary>
/// Adds symbols to a group with no-report type, so symbols will not be shown in expected lists in syntax error messages.
/// </summary>
/// <param name="symbols">Symbols to exclude.</param>
protected void AddToNoReportGroup(params Terminal[] terminals) {
TermReportGroups.Add(new TermReportGroup(string.Empty, TermReportGroupType.DoNotReport, terminals));
}
/// <summary>
/// Adds a group and an alias for all operator symbols used in the grammar.
/// </summary>
/// <param name="alias">An alias for operator symbols.</param>
protected void AddOperatorReportGroup(string alias) {
TermReportGroups.Add(new TermReportGroup(alias, TermReportGroupType.Operator, null)); //operators will be filled later
}
private IEnumerable<Terminal> SymbolsToTerms(IEnumerable<string> symbols) {
var termList = new TerminalList();
foreach(var symbol in symbols)
termList.Add(ToTerm(symbol));
return termList;
}
#endregion
#region Standard terminals: EOF, Empty, NewLine, Indent, Dedent
// Empty object is used to identify optional element:
// term.Rule = term1 | Empty;
public readonly Terminal Empty = new Terminal("EMPTY");
public readonly NewLineTerminal NewLine = new NewLineTerminal("LF");
//set to true automatically by NewLine terminal; prevents treating new-line characters as whitespaces
public bool UsesNewLine;
// The following terminals are used in indent-sensitive languages like Python;
// they are not produced by scanner but are produced by CodeOutlineFilter after scanning
public readonly Terminal Indent = new Terminal("INDENT", TokenCategory.Outline, TermFlags.IsNonScanner);
public readonly Terminal Dedent = new Terminal("DEDENT", TokenCategory.Outline, TermFlags.IsNonScanner);
//End-of-Statement terminal - used in indentation-sensitive language to signal end-of-statement;
// it is not always synced with CRLF chars, and CodeOutlineFilter carefully produces Eos tokens
// (as well as Indent and Dedent) based on line/col information in incoming content tokens.
public readonly Terminal Eos = new Terminal("EOS", Resources.LabelEosLabel, TokenCategory.Outline, TermFlags.IsNonScanner);
// Identifies end of file
// Note: using Eof in grammar rules is optional. Parser automatically adds this symbol
// as a lookahead to Root non-terminal
public readonly Terminal Eof = new Terminal("EOF", TokenCategory.Outline);
//Artificial terminal to use for injected/replaced tokens that must be ignored by parser.
public readonly Terminal Skip = new Terminal("(SKIP)", TokenCategory.Outline, TermFlags.IsNonGrammar);
//Used as a "line-start" indicator
public readonly Terminal LineStartTerminal = new Terminal("LINE_START", TokenCategory.Outline);
//Used for error tokens
public readonly Terminal SyntaxError = new Terminal("SYNTAX_ERROR", TokenCategory.Error, TermFlags.IsNonScanner);
public NonTerminal NewLinePlus {
get {
if(_newLinePlus == null) {
_newLinePlus = new NonTerminal("LF+");
//We do no use MakePlusRule method; we specify the rule explicitly to add PrefereShiftHere call - this solves some unintended shift-reduce conflicts
// when using NewLinePlus
_newLinePlus.Rule = NewLine | _newLinePlus + PreferShiftHere() + NewLine;
MarkPunctuation(_newLinePlus);
_newLinePlus.SetFlag(TermFlags.IsList);
}
return _newLinePlus;
}
} NonTerminal _newLinePlus;
public NonTerminal NewLineStar {
get {
if(_newLineStar == null) {
_newLineStar = new NonTerminal("LF*");
MarkPunctuation(_newLineStar);
_newLineStar.Rule = MakeStarRule(_newLineStar, NewLine);
}
return _newLineStar;
}
} NonTerminal _newLineStar;
#endregion
#region KeyTerms (keywords + special symbols)
public KeyTermTable KeyTerms;
public KeyTerm ToTerm(string text) {
return ToTerm(text, text);
}
public KeyTerm ToTerm(string text, string name) {
KeyTerm term;
if (KeyTerms.TryGetValue(text, out term)) {
//update name if it was specified now and not before
if (string.IsNullOrEmpty(term.Name) && !string.IsNullOrEmpty(name))
term.Name = name;
return term;
}
//create new term
if (!CaseSensitive)
text = text.ToLowerInvariant();
//string.Intern(text);
term = new KeyTerm(text, name);
KeyTerms[text] = term;
return term;
}
#endregion
#region CurrentGrammar static field
//Static per-thread instance; Grammar constructor sets it to self (this).
// This field/property is used by operator overloads (which are static) to access Grammar's predefined terminals like Empty,
// and SymbolTerms dictionary to convert string literals to symbol terminals and add them to the SymbolTerms dictionary
[ThreadStatic]
private static Grammar _currentGrammar;
public static Grammar CurrentGrammar {
get { return _currentGrammar; }
}
internal static void ClearCurrentGrammar() {
_currentGrammar = null;
}
#endregion
#region AST construction
public virtual void BuildAst(LanguageData language, ParseTree parseTree) {
if (!LanguageFlags.IsSet(LanguageFlags.CreateAst))
return;
var astContext = new AstContext(language);
var astBuilder = new AstBuilder(astContext);
astBuilder.BuildAst(parseTree);
}
#endregion
}//class
}//namespace
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Data/PlayerBadge.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Data {
/// <summary>Holder for reflection information generated from POGOProtos/Data/PlayerBadge.proto</summary>
public static partial class PlayerBadgeReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Data/PlayerBadge.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PlayerBadgeReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiFQT0dPUHJvdG9zL0RhdGEvUGxheWVyQmFkZ2UucHJvdG8SD1BPR09Qcm90",
"b3MuRGF0YRogUE9HT1Byb3Rvcy9FbnVtcy9CYWRnZVR5cGUucHJvdG8iiwEK",
"C1BsYXllckJhZGdlEi8KCmJhZGdlX3R5cGUYASABKA4yGy5QT0dPUHJvdG9z",
"LkVudW1zLkJhZGdlVHlwZRIMCgRyYW5rGAIgASgFEhMKC3N0YXJ0X3ZhbHVl",
"GAMgASgFEhEKCWVuZF92YWx1ZRgEIAEoBRIVCg1jdXJyZW50X3ZhbHVlGAUg",
"ASgBYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Enums.BadgeTypeReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Data.PlayerBadge), global::POGOProtos.Data.PlayerBadge.Parser, new[]{ "BadgeType", "Rank", "StartValue", "EndValue", "CurrentValue" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class PlayerBadge : pb::IMessage<PlayerBadge> {
private static readonly pb::MessageParser<PlayerBadge> _parser = new pb::MessageParser<PlayerBadge>(() => new PlayerBadge());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PlayerBadge> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Data.PlayerBadgeReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlayerBadge() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlayerBadge(PlayerBadge other) : this() {
badgeType_ = other.badgeType_;
rank_ = other.rank_;
startValue_ = other.startValue_;
endValue_ = other.endValue_;
currentValue_ = other.currentValue_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlayerBadge Clone() {
return new PlayerBadge(this);
}
/// <summary>Field number for the "badge_type" field.</summary>
public const int BadgeTypeFieldNumber = 1;
private global::POGOProtos.Enums.BadgeType badgeType_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.BadgeType BadgeType {
get { return badgeType_; }
set {
badgeType_ = value;
}
}
/// <summary>Field number for the "rank" field.</summary>
public const int RankFieldNumber = 2;
private int rank_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Rank {
get { return rank_; }
set {
rank_ = value;
}
}
/// <summary>Field number for the "start_value" field.</summary>
public const int StartValueFieldNumber = 3;
private int startValue_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int StartValue {
get { return startValue_; }
set {
startValue_ = value;
}
}
/// <summary>Field number for the "end_value" field.</summary>
public const int EndValueFieldNumber = 4;
private int endValue_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int EndValue {
get { return endValue_; }
set {
endValue_ = value;
}
}
/// <summary>Field number for the "current_value" field.</summary>
public const int CurrentValueFieldNumber = 5;
private double currentValue_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double CurrentValue {
get { return currentValue_; }
set {
currentValue_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PlayerBadge);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PlayerBadge other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (BadgeType != other.BadgeType) return false;
if (Rank != other.Rank) return false;
if (StartValue != other.StartValue) return false;
if (EndValue != other.EndValue) return false;
if (CurrentValue != other.CurrentValue) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (BadgeType != 0) hash ^= BadgeType.GetHashCode();
if (Rank != 0) hash ^= Rank.GetHashCode();
if (StartValue != 0) hash ^= StartValue.GetHashCode();
if (EndValue != 0) hash ^= EndValue.GetHashCode();
if (CurrentValue != 0D) hash ^= CurrentValue.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (BadgeType != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) BadgeType);
}
if (Rank != 0) {
output.WriteRawTag(16);
output.WriteInt32(Rank);
}
if (StartValue != 0) {
output.WriteRawTag(24);
output.WriteInt32(StartValue);
}
if (EndValue != 0) {
output.WriteRawTag(32);
output.WriteInt32(EndValue);
}
if (CurrentValue != 0D) {
output.WriteRawTag(41);
output.WriteDouble(CurrentValue);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (BadgeType != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) BadgeType);
}
if (Rank != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Rank);
}
if (StartValue != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(StartValue);
}
if (EndValue != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(EndValue);
}
if (CurrentValue != 0D) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PlayerBadge other) {
if (other == null) {
return;
}
if (other.BadgeType != 0) {
BadgeType = other.BadgeType;
}
if (other.Rank != 0) {
Rank = other.Rank;
}
if (other.StartValue != 0) {
StartValue = other.StartValue;
}
if (other.EndValue != 0) {
EndValue = other.EndValue;
}
if (other.CurrentValue != 0D) {
CurrentValue = other.CurrentValue;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
badgeType_ = (global::POGOProtos.Enums.BadgeType) input.ReadEnum();
break;
}
case 16: {
Rank = input.ReadInt32();
break;
}
case 24: {
StartValue = input.ReadInt32();
break;
}
case 32: {
EndValue = input.ReadInt32();
break;
}
case 41: {
CurrentValue = input.ReadDouble();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Grpc.Core;
using Grpc.Core.Utils;
using Grpc.Core.Profiling;
using System.Buffers;
namespace Grpc.Core.Internal
{
/// <summary>
/// grpc_call from <c>grpc/grpc.h</c>
/// </summary>
internal class CallSafeHandle : SafeHandleZeroIsInvalid, INativeCall
{
public static readonly CallSafeHandle NullInstance = new CallSafeHandle();
static readonly NativeMethods Native = NativeMethods.Get();
// Completion handlers are pre-allocated to avoid unneccessary delegate allocations.
// The "state" field is used to store the actual callback to invoke.
static readonly BatchCompletionDelegate CompletionHandler_IUnaryResponseClientCallback =
(success, context, state) => ((IUnaryResponseClientCallback)state).OnUnaryResponseClient(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessageReader(), context.GetReceivedInitialMetadata());
static readonly BatchCompletionDelegate CompletionHandler_IReceivedStatusOnClientCallback =
(success, context, state) => ((IReceivedStatusOnClientCallback)state).OnReceivedStatusOnClient(success, context.GetReceivedStatusOnClient());
static readonly BatchCompletionDelegate CompletionHandler_IReceivedMessageCallback =
(success, context, state) => ((IReceivedMessageCallback)state).OnReceivedMessage(success, context.GetReceivedMessageReader());
static readonly BatchCompletionDelegate CompletionHandler_IReceivedResponseHeadersCallback =
(success, context, state) => ((IReceivedResponseHeadersCallback)state).OnReceivedResponseHeaders(success, context.GetReceivedInitialMetadata());
static readonly BatchCompletionDelegate CompletionHandler_ISendCompletionCallback =
(success, context, state) => ((ISendCompletionCallback)state).OnSendCompletion(success);
static readonly BatchCompletionDelegate CompletionHandler_ISendStatusFromServerCompletionCallback =
(success, context, state) => ((ISendStatusFromServerCompletionCallback)state).OnSendStatusFromServerCompletion(success);
static readonly BatchCompletionDelegate CompletionHandler_IReceivedCloseOnServerCallback =
(success, context, state) => ((IReceivedCloseOnServerCallback)state).OnReceivedCloseOnServer(success, context.GetReceivedCloseOnServerCancelled());
const uint GRPC_WRITE_BUFFER_HINT = 1;
CompletionQueueSafeHandle completionQueue;
private CallSafeHandle()
{
}
public void Initialize(CompletionQueueSafeHandle completionQueue)
{
this.completionQueue = completionQueue;
}
public void SetCredentials(CallCredentialsSafeHandle credentials)
{
Native.grpcsharp_call_set_credentials(this, credentials).CheckOk();
}
public void StartUnary(IUnaryResponseClientCallback callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
{
using (completionQueue.NewScope())
{
var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IUnaryResponseClientCallback, callback);
Native.grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, metadataArray, callFlags)
.CheckOk();
}
}
public void StartUnary(BatchContextSafeHandle ctx, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
{
Native.grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, metadataArray, callFlags)
.CheckOk();
}
public void StartClientStreaming(IUnaryResponseClientCallback callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
{
using (completionQueue.NewScope())
{
var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IUnaryResponseClientCallback, callback);
Native.grpcsharp_call_start_client_streaming(this, ctx, metadataArray, callFlags).CheckOk();
}
}
public void StartServerStreaming(IReceivedStatusOnClientCallback callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
{
using (completionQueue.NewScope())
{
var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedStatusOnClientCallback, callback);
Native.grpcsharp_call_start_server_streaming(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, metadataArray, callFlags).CheckOk();
}
}
public void StartDuplexStreaming(IReceivedStatusOnClientCallback callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
{
using (completionQueue.NewScope())
{
var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedStatusOnClientCallback, callback);
Native.grpcsharp_call_start_duplex_streaming(this, ctx, metadataArray, callFlags).CheckOk();
}
}
public void StartSendMessage(ISendCompletionCallback callback, byte[] payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata)
{
using (completionQueue.NewScope())
{
var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_ISendCompletionCallback, callback);
Native.grpcsharp_call_send_message(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, sendEmptyInitialMetadata ? 1 : 0).CheckOk();
}
}
public void StartSendCloseFromClient(ISendCompletionCallback callback)
{
using (completionQueue.NewScope())
{
var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_ISendCompletionCallback, callback);
Native.grpcsharp_call_send_close_from_client(this, ctx).CheckOk();
}
}
public void StartSendStatusFromServer(ISendStatusFromServerCompletionCallback callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata,
byte[] optionalPayload, WriteFlags writeFlags)
{
using (completionQueue.NewScope())
{
var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_ISendStatusFromServerCompletionCallback, callback);
var optionalPayloadLength = optionalPayload != null ? new UIntPtr((ulong)optionalPayload.Length) : UIntPtr.Zero;
const int MaxStackAllocBytes = 256;
int maxBytes = MarshalUtils.GetMaxByteCountUTF8(status.Detail);
if (maxBytes > MaxStackAllocBytes)
{
// pay the extra to get the *actual* size; this could mean that
// it ends up fitting on the stack after all, but even if not
// it will mean that we ask for a *much* smaller buffer
maxBytes = MarshalUtils.GetByteCountUTF8(status.Detail);
}
unsafe
{
if (maxBytes <= MaxStackAllocBytes)
{ // for small status, we can encode on the stack without touching arrays
// note: if init-locals is disabled, it would be more efficient
// to just stackalloc[MaxStackAllocBytes]; but by default, since we
// expect this to be small and it needs to wipe, just use maxBytes
byte* ptr = stackalloc byte[maxBytes];
int statusBytes = MarshalUtils.GetBytesUTF8(status.Detail, ptr, maxBytes);
Native.grpcsharp_call_send_status_from_server(this, ctx, status.StatusCode, new IntPtr(ptr), new UIntPtr((ulong)statusBytes), metadataArray, sendEmptyInitialMetadata ? 1 : 0,
optionalPayload, optionalPayloadLength, writeFlags).CheckOk();
}
else
{ // for larger status (rare), rent a buffer from the pool and
// use that for encoding
var statusBuffer = ArrayPool<byte>.Shared.Rent(maxBytes);
try
{
fixed (byte* ptr = statusBuffer)
{
int statusBytes = MarshalUtils.GetBytesUTF8(status.Detail, ptr, maxBytes);
Native.grpcsharp_call_send_status_from_server(this, ctx, status.StatusCode, new IntPtr(ptr), new UIntPtr((ulong)statusBytes), metadataArray, sendEmptyInitialMetadata ? 1 : 0,
optionalPayload, optionalPayloadLength, writeFlags).CheckOk();
}
}
finally
{
ArrayPool<byte>.Shared.Return(statusBuffer);
}
}
}
}
}
public void StartReceiveMessage(IReceivedMessageCallback callback)
{
using (completionQueue.NewScope())
{
var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedMessageCallback, callback);
Native.grpcsharp_call_recv_message(this, ctx).CheckOk();
}
}
public void StartReceiveInitialMetadata(IReceivedResponseHeadersCallback callback)
{
using (completionQueue.NewScope())
{
var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedResponseHeadersCallback, callback);
Native.grpcsharp_call_recv_initial_metadata(this, ctx).CheckOk();
}
}
public void StartServerSide(IReceivedCloseOnServerCallback callback)
{
using (completionQueue.NewScope())
{
var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedCloseOnServerCallback, callback);
Native.grpcsharp_call_start_serverside(this, ctx).CheckOk();
}
}
public void StartSendInitialMetadata(ISendCompletionCallback callback, MetadataArraySafeHandle metadataArray)
{
using (completionQueue.NewScope())
{
var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_ISendCompletionCallback, callback);
Native.grpcsharp_call_send_initial_metadata(this, ctx, metadataArray).CheckOk();
}
}
public void Cancel()
{
Native.grpcsharp_call_cancel(this).CheckOk();
}
public void CancelWithStatus(Status status)
{
Native.grpcsharp_call_cancel_with_status(this, status.StatusCode, status.Detail).CheckOk();
}
public string GetPeer()
{
using (var cstring = Native.grpcsharp_call_get_peer(this))
{
return cstring.GetValue();
}
}
public AuthContextSafeHandle GetAuthContext()
{
return Native.grpcsharp_call_auth_context(this);
}
protected override bool ReleaseHandle()
{
Native.grpcsharp_call_destroy(handle);
return true;
}
private static uint GetFlags(bool buffered)
{
return buffered ? 0 : GRPC_WRITE_BUFFER_HINT;
}
/// <summary>
/// Only for testing.
/// </summary>
public static CallSafeHandle CreateFake(IntPtr ptr, CompletionQueueSafeHandle cq)
{
var call = new CallSafeHandle();
call.SetHandle(ptr);
call.Initialize(cq);
return call;
}
}
}
| |
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 MyStik.TimeTable.Web.Areas.HelpPage.ModelDescriptions;
using MyStik.TimeTable.Web.Areas.HelpPage.Models;
namespace MyStik.TimeTable.Web.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);
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.IO;
using System.Globalization;
using Newtonsoft.Json.Utilities;
using System.Xml;
using Newtonsoft.Json.Converters;
using System.Text;
#if !NET20 && (!SILVERLIGHT || WINDOWS_PHONE)
using System.Xml.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Provides methods for converting between common language runtime types and JSON types.
/// </summary>
public static class JsonConvert
{
/// <summary>
/// Represents JavaScript's boolean value true as a string. This field is read-only.
/// </summary>
public static readonly string True = "true";
/// <summary>
/// Represents JavaScript's boolean value false as a string. This field is read-only.
/// </summary>
public static readonly string False = "false";
/// <summary>
/// Represents JavaScript's null as a string. This field is read-only.
/// </summary>
public static readonly string Null = "null";
/// <summary>
/// Represents JavaScript's undefined as a string. This field is read-only.
/// </summary>
public static readonly string Undefined = "undefined";
/// <summary>
/// Represents JavaScript's positive infinity as a string. This field is read-only.
/// </summary>
public static readonly string PositiveInfinity = "Infinity";
/// <summary>
/// Represents JavaScript's negative infinity as a string. This field is read-only.
/// </summary>
public static readonly string NegativeInfinity = "-Infinity";
/// <summary>
/// Represents JavaScript's NaN as a string. This field is read-only.
/// </summary>
public static readonly string NaN = "NaN";
internal static readonly long InitialJavaScriptDateTicks = 621355968000000000;
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
WriteDateTimeString(writer, value, GetUtcOffset(value), value.Kind);
return writer.ToString();
}
}
#if !PocketPC && !NET20
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
WriteDateTimeString(writer, value.UtcDateTime, value.Offset, DateTimeKind.Local);
return writer.ToString();
}
}
#endif
private static TimeSpan GetUtcOffset(DateTime dateTime)
{
#if SILVERLIGHT
return TimeZoneInfo.Local.GetUtcOffset(dateTime);
#else
return TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
#endif
}
internal static void WriteDateTimeString(TextWriter writer, DateTime value)
{
WriteDateTimeString(writer, value, GetUtcOffset(value), value.Kind);
}
internal static void WriteDateTimeString(TextWriter writer, DateTime value, TimeSpan offset, DateTimeKind kind)
{
long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value, offset);
writer.Write(@"""\/Date(");
writer.Write(javaScriptTicks);
switch (kind)
{
case DateTimeKind.Local:
case DateTimeKind.Unspecified:
writer.Write((offset.Ticks >= 0L) ? "+" : "-");
int absHours = Math.Abs(offset.Hours);
if (absHours < 10)
writer.Write(0);
writer.Write(absHours);
int absMinutes = Math.Abs(offset.Minutes);
if (absMinutes < 10)
writer.Write(0);
writer.Write(absMinutes);
break;
}
writer.Write(@")\/""");
}
private static long ToUniversalTicks(DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Utc)
return dateTime.Ticks;
return ToUniversalTicks(dateTime, GetUtcOffset(dateTime));
}
private static long ToUniversalTicks(DateTime dateTime, TimeSpan offset)
{
if (dateTime.Kind == DateTimeKind.Utc)
return dateTime.Ticks;
long ticks = dateTime.Ticks - offset.Ticks;
if (ticks > 3155378975999999999L)
return 3155378975999999999L;
if (ticks < 0L)
return 0L;
return ticks;
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, TimeSpan offset)
{
long universialTicks = ToUniversalTicks(dateTime, offset);
return UniversialTicksToJavaScriptTicks(universialTicks);
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime)
{
return ConvertDateTimeToJavaScriptTicks(dateTime, true);
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, bool convertToUtc)
{
long ticks = (convertToUtc) ? ToUniversalTicks(dateTime) : dateTime.Ticks;
return UniversialTicksToJavaScriptTicks(ticks);
}
private static long UniversialTicksToJavaScriptTicks(long universialTicks)
{
long javaScriptTicks = (universialTicks - InitialJavaScriptDateTicks) / 10000;
return javaScriptTicks;
}
internal static DateTime ConvertJavaScriptTicksToDateTime(long javaScriptTicks)
{
DateTime dateTime = new DateTime((javaScriptTicks * 10000) + InitialJavaScriptDateTicks, DateTimeKind.Utc);
return dateTime;
}
/// <summary>
/// Converts the <see cref="Boolean"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Boolean"/>.</returns>
public static string ToString(bool value)
{
return (value) ? True : False;
}
/// <summary>
/// Converts the <see cref="Char"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Char"/>.</returns>
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
/// <summary>
/// Converts the <see cref="Enum"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString("D");
}
/// <summary>
/// Converts the <see cref="Int32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int32"/>.</returns>
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int16"/>.</returns>
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt16"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt32"/>.</returns>
[CLSCompliant(false)]
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int64"/>.</returns>
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt64"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Single"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Single"/>.</returns>
public static string ToString(float value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Double"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
private static string EnsureDecimalPlace(double value, string text)
{
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1)
return text;
return text + ".0";
}
private static string EnsureDecimalPlace(string text)
{
if (text.IndexOf('.') != -1)
return text;
return text + ".0";
}
/// <summary>
/// Converts the <see cref="Byte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Byte"/>.</returns>
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="SByte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
[CLSCompliant(false)]
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Decimal"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
public static string ToString(decimal value)
{
return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Guid"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
public static string ToString(Guid value)
{
return '"' + value.ToString("D", CultureInfo.InvariantCulture) + '"';
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value)
{
return ToString(value, '"');
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimter">The string delimiter character.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimter)
{
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimter, true);
}
/// <summary>
/// Converts the <see cref="Object"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Object"/>.</returns>
public static string ToString(object value)
{
if (value == null)
return Null;
IConvertible convertible = value as IConvertible;
if (convertible != null)
{
switch (convertible.GetTypeCode())
{
case TypeCode.String:
return ToString(convertible.ToString(CultureInfo.InvariantCulture));
case TypeCode.Char:
return ToString(convertible.ToChar(CultureInfo.InvariantCulture));
case TypeCode.Boolean:
return ToString(convertible.ToBoolean(CultureInfo.InvariantCulture));
case TypeCode.SByte:
return ToString(convertible.ToSByte(CultureInfo.InvariantCulture));
case TypeCode.Int16:
return ToString(convertible.ToInt16(CultureInfo.InvariantCulture));
case TypeCode.UInt16:
return ToString(convertible.ToUInt16(CultureInfo.InvariantCulture));
case TypeCode.Int32:
return ToString(convertible.ToInt32(CultureInfo.InvariantCulture));
case TypeCode.Byte:
return ToString(convertible.ToByte(CultureInfo.InvariantCulture));
case TypeCode.UInt32:
return ToString(convertible.ToUInt32(CultureInfo.InvariantCulture));
case TypeCode.Int64:
return ToString(convertible.ToInt64(CultureInfo.InvariantCulture));
case TypeCode.UInt64:
return ToString(convertible.ToUInt64(CultureInfo.InvariantCulture));
case TypeCode.Single:
return ToString(convertible.ToSingle(CultureInfo.InvariantCulture));
case TypeCode.Double:
return ToString(convertible.ToDouble(CultureInfo.InvariantCulture));
case TypeCode.DateTime:
return ToString(convertible.ToDateTime(CultureInfo.InvariantCulture));
case TypeCode.Decimal:
return ToString(convertible.ToDecimal(CultureInfo.InvariantCulture));
case TypeCode.DBNull:
return Null;
}
}
#if !PocketPC && !NET20
else if (value is DateTimeOffset)
{
return ToString((DateTimeOffset)value);
}
#endif
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
private static bool IsJsonPrimitiveTypeCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.String:
case TypeCode.Char:
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.Byte:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.DateTime:
case TypeCode.Decimal:
case TypeCode.DBNull:
return true;
default:
return false;
}
}
internal static bool IsJsonPrimitiveType(Type type)
{
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
#if !PocketPC && !NET20
if (type == typeof(DateTimeOffset))
return true;
#endif
if (type == typeof(byte[]))
return true;
return IsJsonPrimitiveTypeCode(Type.GetTypeCode(type));
}
internal static bool IsJsonPrimitive(object value)
{
if (value == null)
return true;
IConvertible convertible = value as IConvertible;
if (convertible != null)
return IsJsonPrimitiveTypeCode(convertible.GetTypeCode());
#if !PocketPC && !NET20
if (value is DateTimeOffset)
return true;
#endif
if (value is byte[])
return true;
return false;
}
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value)
{
return SerializeObject(value, Formatting.None, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, params JsonConverter[] converters)
{
return SerializeObject(value, Formatting.None, converters);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
StringBuilder sb = new StringBuilder(128);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = formatting;
jsonSerializer.Serialize(jsonWriter, value);
}
return sw.ToString();
}
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, JsonSerializerSettings settings)
{
return DeserializeObject(value, null, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be infered from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
{
return DeserializeObject<T>(value);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
{
return (T)DeserializeObject(value, typeof(T), converters);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
{
return (T)DeserializeObject(value, typeof(T), settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return DeserializeObject(value, type, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
{
StringReader sr = new StringReader(value);
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
object deserializedValue;
using (JsonReader jsonReader = new JsonTextReader(sr))
{
deserializedValue = jsonSerializer.Deserialize(jsonReader, type);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
}
return deserializedValue;
}
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public static void PopulateObject(string value, object target)
{
PopulateObject(value, target, null);
}
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
{
StringReader sr = new StringReader(value);
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
using (JsonReader jsonReader = new JsonTextReader(sr))
{
jsonSerializer.Populate(jsonReader, target);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
}
}
#if !SILVERLIGHT
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node)
{
return SerializeXmlNode(node, Formatting.None);
}
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting)
{
XmlNodeConverter converter = new XmlNodeConverter();
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value)
{
return DeserializeXmlNode(value, null);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName)
{
return DeserializeXmlNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), converter);
}
#endif
#if !NET20 && (!SILVERLIGHT || WINDOWS_PHONE)
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node)
{
return SerializeXNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node, Formatting formatting)
{
return SerializeXNode(node, formatting, false);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value)
{
return DeserializeXNode(value, null);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName)
{
return DeserializeXNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
return (XDocument)DeserializeObject(value, typeof(XDocument), converter);
}
#endif
}
}
| |
/**
* Couchbase Lite for .NET
*
* Original iOS version by Jens Alfke
* Android Port by Marty Schoch, Traun Leyden
* C# Port by Zack Gramana
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
* Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Couchbase.Lite;
using Couchbase.Lite.Internal;
using Couchbase.Lite.Support;
using Couchbase.Lite.Util;
using NUnit.Framework;
using Org.Apache.Commons.IO;
using Sharpen;
namespace Couchbase.Lite
{
public class AttachmentsTest : LiteTestCase
{
public const string Tag = "Attachments";
/// <exception cref="System.Exception"></exception>
public virtual void TestAttachments()
{
string testAttachmentName = "test_attachment";
BlobStore attachments = database.GetAttachments();
NUnit.Framework.Assert.AreEqual(0, attachments.Count());
NUnit.Framework.Assert.AreEqual(new HashSet<object>(), attachments.AllKeys());
Status status = new Status();
IDictionary<string, object> rev1Properties = new Dictionary<string, object>();
rev1Properties.Put("foo", 1);
rev1Properties.Put("bar", false);
RevisionInternal rev1 = database.PutRevision(new RevisionInternal(rev1Properties,
database), null, false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
byte[] attach1 = Sharpen.Runtime.GetBytesForString("This is the body of attach1");
database.InsertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach1
), rev1.GetSequence(), testAttachmentName, "text/plain", rev1.GetGeneration());
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
Attachment attachment = database.GetAttachmentForSequence(rev1.GetSequence(), testAttachmentName
);
NUnit.Framework.Assert.AreEqual("text/plain", attachment.GetContentType());
byte[] data = IOUtils.ToByteArray(attachment.GetContent());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(attach1, data));
IDictionary<string, object> innerDict = new Dictionary<string, object>();
innerDict.Put("content_type", "text/plain");
innerDict.Put("digest", "sha1-gOHUOBmIMoDCrMuGyaLWzf1hQTE=");
innerDict.Put("length", 27);
innerDict.Put("stub", true);
innerDict.Put("revpos", 1);
IDictionary<string, object> attachmentDict = new Dictionary<string, object>();
attachmentDict.Put(testAttachmentName, innerDict);
IDictionary<string, object> attachmentDictForSequence = database.GetAttachmentsDictForSequenceWithContent
(rev1.GetSequence(), EnumSet.NoneOf<Database.TDContentOptions>());
NUnit.Framework.Assert.AreEqual(attachmentDict, attachmentDictForSequence);
RevisionInternal gotRev1 = database.GetDocumentWithIDAndRev(rev1.GetDocId(), rev1
.GetRevId(), EnumSet.NoneOf<Database.TDContentOptions>());
IDictionary<string, object> gotAttachmentDict = (IDictionary<string, object>)gotRev1
.GetProperties().Get("_attachments");
NUnit.Framework.Assert.AreEqual(attachmentDict, gotAttachmentDict);
// Check the attachment dict, with attachments included:
Sharpen.Collections.Remove(innerDict, "stub");
innerDict.Put("data", Base64.EncodeBytes(attach1));
attachmentDictForSequence = database.GetAttachmentsDictForSequenceWithContent(rev1
.GetSequence(), EnumSet.Of(Database.TDContentOptions.TDIncludeAttachments));
NUnit.Framework.Assert.AreEqual(attachmentDict, attachmentDictForSequence);
gotRev1 = database.GetDocumentWithIDAndRev(rev1.GetDocId(), rev1.GetRevId(), EnumSet
.Of(Database.TDContentOptions.TDIncludeAttachments));
gotAttachmentDict = (IDictionary<string, object>)gotRev1.GetProperties().Get("_attachments"
);
NUnit.Framework.Assert.AreEqual(attachmentDict, gotAttachmentDict);
// Add a second revision that doesn't update the attachment:
IDictionary<string, object> rev2Properties = new Dictionary<string, object>();
rev2Properties.Put("_id", rev1.GetDocId());
rev2Properties.Put("foo", 2);
rev2Properties.Put("bazz", false);
RevisionInternal rev2 = database.PutRevision(new RevisionInternal(rev2Properties,
database), rev1.GetRevId(), false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
database.CopyAttachmentNamedFromSequenceToSequence(testAttachmentName, rev1.GetSequence
(), rev2.GetSequence());
// Add a third revision of the same document:
IDictionary<string, object> rev3Properties = new Dictionary<string, object>();
rev3Properties.Put("_id", rev2.GetDocId());
rev3Properties.Put("foo", 2);
rev3Properties.Put("bazz", false);
RevisionInternal rev3 = database.PutRevision(new RevisionInternal(rev3Properties,
database), rev2.GetRevId(), false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
byte[] attach2 = Sharpen.Runtime.GetBytesForString("<html>And this is attach2</html>"
);
database.InsertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach2
), rev3.GetSequence(), testAttachmentName, "text/html", rev2.GetGeneration());
// Check the 2nd revision's attachment:
Attachment attachment2 = database.GetAttachmentForSequence(rev2.GetSequence(), testAttachmentName
);
NUnit.Framework.Assert.AreEqual("text/plain", attachment2.GetContentType());
data = IOUtils.ToByteArray(attachment2.GetContent());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(attach1, data));
// Check the 3rd revision's attachment:
Attachment attachment3 = database.GetAttachmentForSequence(rev3.GetSequence(), testAttachmentName
);
NUnit.Framework.Assert.AreEqual("text/html", attachment3.GetContentType());
data = IOUtils.ToByteArray(attachment3.GetContent());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(attach2, data));
// Examine the attachment store:
NUnit.Framework.Assert.AreEqual(2, attachments.Count());
ICollection<BlobKey> expected = new HashSet<BlobKey>();
expected.AddItem(BlobStore.KeyForBlob(attach1));
expected.AddItem(BlobStore.KeyForBlob(attach2));
NUnit.Framework.Assert.AreEqual(expected, attachments.AllKeys());
database.Compact();
// This clears the body of the first revision
NUnit.Framework.Assert.AreEqual(1, attachments.Count());
ICollection<BlobKey> expected2 = new HashSet<BlobKey>();
expected2.AddItem(BlobStore.KeyForBlob(attach2));
NUnit.Framework.Assert.AreEqual(expected2, attachments.AllKeys());
}
/// <exception cref="System.Exception"></exception>
public virtual void TestPutLargeAttachment()
{
string testAttachmentName = "test_attachment";
BlobStore attachments = database.GetAttachments();
attachments.DeleteBlobs();
NUnit.Framework.Assert.AreEqual(0, attachments.Count());
Status status = new Status();
IDictionary<string, object> rev1Properties = new Dictionary<string, object>();
rev1Properties.Put("foo", 1);
rev1Properties.Put("bar", false);
RevisionInternal rev1 = database.PutRevision(new RevisionInternal(rev1Properties,
database), null, false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
StringBuilder largeAttachment = new StringBuilder();
for (int i = 0; i < Database.kBigAttachmentLength; i++)
{
largeAttachment.Append("big attachment!");
}
byte[] attach1 = Sharpen.Runtime.GetBytesForString(largeAttachment.ToString());
database.InsertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach1
), rev1.GetSequence(), testAttachmentName, "text/plain", rev1.GetGeneration());
Attachment attachment = database.GetAttachmentForSequence(rev1.GetSequence(), testAttachmentName
);
NUnit.Framework.Assert.AreEqual("text/plain", attachment.GetContentType());
byte[] data = IOUtils.ToByteArray(attachment.GetContent());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(attach1, data));
EnumSet<Database.TDContentOptions> contentOptions = EnumSet.Of(Database.TDContentOptions
.TDIncludeAttachments, Database.TDContentOptions.TDBigAttachmentsFollow);
IDictionary<string, object> attachmentDictForSequence = database.GetAttachmentsDictForSequenceWithContent
(rev1.GetSequence(), contentOptions);
IDictionary<string, object> innerDict = (IDictionary<string, object>)attachmentDictForSequence
.Get(testAttachmentName);
if (!innerDict.ContainsKey("stub"))
{
throw new RuntimeException("Expected attachment dict to have 'stub' key");
}
if (((bool)innerDict.Get("stub")) == false)
{
throw new RuntimeException("Expected attachment dict 'stub' key to be true");
}
if (!innerDict.ContainsKey("follows"))
{
throw new RuntimeException("Expected attachment dict to have 'follows' key");
}
RevisionInternal rev1WithAttachments = database.GetDocumentWithIDAndRev(rev1.GetDocId
(), rev1.GetRevId(), contentOptions);
// Map<String,Object> rev1PropertiesPrime = rev1WithAttachments.getProperties();
// rev1PropertiesPrime.put("foo", 2);
IDictionary<string, object> rev1WithAttachmentsProperties = rev1WithAttachments.GetProperties
();
IDictionary<string, object> rev2Properties = new Dictionary<string, object>();
rev2Properties.Put("_id", rev1WithAttachmentsProperties.Get("_id"));
rev2Properties.Put("foo", 2);
RevisionInternal newRev = new RevisionInternal(rev2Properties, database);
RevisionInternal rev2 = database.PutRevision(newRev, rev1WithAttachments.GetRevId
(), false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
database.CopyAttachmentNamedFromSequenceToSequence(testAttachmentName, rev1WithAttachments
.GetSequence(), rev2.GetSequence());
// Check the 2nd revision's attachment:
Attachment rev2FetchedAttachment = database.GetAttachmentForSequence(rev2.GetSequence
(), testAttachmentName);
NUnit.Framework.Assert.AreEqual(attachment.GetLength(), rev2FetchedAttachment.GetLength
());
NUnit.Framework.Assert.AreEqual(attachment.GetMetadata(), rev2FetchedAttachment.GetMetadata
());
NUnit.Framework.Assert.AreEqual(attachment.GetContentType(), rev2FetchedAttachment
.GetContentType());
// Add a third revision of the same document:
IDictionary<string, object> rev3Properties = new Dictionary<string, object>();
rev3Properties.Put("_id", rev2.GetProperties().Get("_id"));
rev3Properties.Put("foo", 3);
rev3Properties.Put("baz", false);
RevisionInternal rev3 = new RevisionInternal(rev3Properties, database);
rev3 = database.PutRevision(rev3, rev2.GetRevId(), false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
byte[] attach3 = Sharpen.Runtime.GetBytesForString("<html><blink>attach3</blink></html>"
);
database.InsertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach3
), rev3.GetSequence(), testAttachmentName, "text/html", rev3.GetGeneration());
// Check the 3rd revision's attachment:
Attachment rev3FetchedAttachment = database.GetAttachmentForSequence(rev3.GetSequence
(), testAttachmentName);
data = IOUtils.ToByteArray(rev3FetchedAttachment.GetContent());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(attach3, data));
NUnit.Framework.Assert.AreEqual("text/html", rev3FetchedAttachment.GetContentType
());
// TODO: why doesn't this work?
// Assert.assertEquals(attach3.length, rev3FetchedAttachment.getLength());
ICollection<BlobKey> blobKeys = database.GetAttachments().AllKeys();
NUnit.Framework.Assert.AreEqual(2, blobKeys.Count);
database.Compact();
blobKeys = database.GetAttachments().AllKeys();
NUnit.Framework.Assert.AreEqual(1, blobKeys.Count);
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
public virtual void TestPutAttachment()
{
string testAttachmentName = "test_attachment";
BlobStore attachments = database.GetAttachments();
attachments.DeleteBlobs();
NUnit.Framework.Assert.AreEqual(0, attachments.Count());
// Put a revision that includes an _attachments dict:
byte[] attach1 = Sharpen.Runtime.GetBytesForString("This is the body of attach1");
string base64 = Base64.EncodeBytes(attach1);
IDictionary<string, object> attachment = new Dictionary<string, object>();
attachment.Put("content_type", "text/plain");
attachment.Put("data", base64);
IDictionary<string, object> attachmentDict = new Dictionary<string, object>();
attachmentDict.Put(testAttachmentName, attachment);
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("foo", 1);
properties.Put("bar", false);
properties.Put("_attachments", attachmentDict);
RevisionInternal rev1 = database.PutRevision(new RevisionInternal(properties, database
), null, false);
// Examine the attachment store:
NUnit.Framework.Assert.AreEqual(1, attachments.Count());
// Get the revision:
RevisionInternal gotRev1 = database.GetDocumentWithIDAndRev(rev1.GetDocId(), rev1
.GetRevId(), EnumSet.NoneOf<Database.TDContentOptions>());
IDictionary<string, object> gotAttachmentDict = (IDictionary<string, object>)gotRev1
.GetProperties().Get("_attachments");
IDictionary<string, object> innerDict = new Dictionary<string, object>();
innerDict.Put("content_type", "text/plain");
innerDict.Put("digest", "sha1-gOHUOBmIMoDCrMuGyaLWzf1hQTE=");
innerDict.Put("length", 27);
innerDict.Put("stub", true);
innerDict.Put("revpos", 1);
IDictionary<string, object> expectAttachmentDict = new Dictionary<string, object>
();
expectAttachmentDict.Put(testAttachmentName, innerDict);
NUnit.Framework.Assert.AreEqual(expectAttachmentDict, gotAttachmentDict);
// Update the attachment directly:
byte[] attachv2 = Sharpen.Runtime.GetBytesForString("Replaced body of attach");
bool gotExpectedErrorCode = false;
try
{
database.UpdateAttachment(testAttachmentName, new ByteArrayInputStream(attachv2),
"application/foo", rev1.GetDocId(), null);
}
catch (CouchbaseLiteException e)
{
gotExpectedErrorCode = (e.GetCBLStatus().GetCode() == Status.Conflict);
}
NUnit.Framework.Assert.IsTrue(gotExpectedErrorCode);
gotExpectedErrorCode = false;
try
{
database.UpdateAttachment(testAttachmentName, new ByteArrayInputStream(attachv2),
"application/foo", rev1.GetDocId(), "1-bogus");
}
catch (CouchbaseLiteException e)
{
gotExpectedErrorCode = (e.GetCBLStatus().GetCode() == Status.Conflict);
}
NUnit.Framework.Assert.IsTrue(gotExpectedErrorCode);
gotExpectedErrorCode = false;
RevisionInternal rev2 = null;
try
{
rev2 = database.UpdateAttachment(testAttachmentName, new ByteArrayInputStream(attachv2
), "application/foo", rev1.GetDocId(), rev1.GetRevId());
}
catch (CouchbaseLiteException)
{
gotExpectedErrorCode = true;
}
NUnit.Framework.Assert.IsFalse(gotExpectedErrorCode);
NUnit.Framework.Assert.AreEqual(rev1.GetDocId(), rev2.GetDocId());
NUnit.Framework.Assert.AreEqual(2, rev2.GetGeneration());
// Get the updated revision:
RevisionInternal gotRev2 = database.GetDocumentWithIDAndRev(rev2.GetDocId(), rev2
.GetRevId(), EnumSet.NoneOf<Database.TDContentOptions>());
attachmentDict = (IDictionary<string, object>)gotRev2.GetProperties().Get("_attachments"
);
innerDict = new Dictionary<string, object>();
innerDict.Put("content_type", "application/foo");
innerDict.Put("digest", "sha1-mbT3208HI3PZgbG4zYWbDW2HsPk=");
innerDict.Put("length", 23);
innerDict.Put("stub", true);
innerDict.Put("revpos", 2);
expectAttachmentDict.Put(testAttachmentName, innerDict);
NUnit.Framework.Assert.AreEqual(expectAttachmentDict, attachmentDict);
// Delete the attachment:
gotExpectedErrorCode = false;
try
{
database.UpdateAttachment("nosuchattach", null, null, rev2.GetDocId(), rev2.GetRevId
());
}
catch (CouchbaseLiteException e)
{
gotExpectedErrorCode = (e.GetCBLStatus().GetCode() == Status.NotFound);
}
NUnit.Framework.Assert.IsTrue(gotExpectedErrorCode);
gotExpectedErrorCode = false;
try
{
database.UpdateAttachment("nosuchattach", null, null, "nosuchdoc", "nosuchrev");
}
catch (CouchbaseLiteException e)
{
gotExpectedErrorCode = (e.GetCBLStatus().GetCode() == Status.NotFound);
}
NUnit.Framework.Assert.IsTrue(gotExpectedErrorCode);
RevisionInternal rev3 = database.UpdateAttachment(testAttachmentName, null, null,
rev2.GetDocId(), rev2.GetRevId());
NUnit.Framework.Assert.AreEqual(rev2.GetDocId(), rev3.GetDocId());
NUnit.Framework.Assert.AreEqual(3, rev3.GetGeneration());
// Get the updated revision:
RevisionInternal gotRev3 = database.GetDocumentWithIDAndRev(rev3.GetDocId(), rev3
.GetRevId(), EnumSet.NoneOf<Database.TDContentOptions>());
attachmentDict = (IDictionary<string, object>)gotRev3.GetProperties().Get("_attachments"
);
NUnit.Framework.Assert.IsNull(attachmentDict);
database.Close();
}
public virtual void TestStreamAttachmentBlobStoreWriter()
{
BlobStore attachments = database.GetAttachments();
BlobStoreWriter blobWriter = new BlobStoreWriter(attachments);
string testBlob = "foo";
blobWriter.AppendData(Sharpen.Runtime.GetBytesForString(new string(testBlob)));
blobWriter.Finish();
string sha1Base64Digest = "sha1-C+7Hteo/D9vJXQ3UfzxbwnXaijM=";
NUnit.Framework.Assert.AreEqual(blobWriter.SHA1DigestString(), sha1Base64Digest);
NUnit.Framework.Assert.AreEqual(blobWriter.MD5DigestString(), "md5-rL0Y20zC+Fzt72VPzMSk2A=="
);
// install it
blobWriter.Install();
// look it up in blob store and make sure it's there
BlobKey blobKey = new BlobKey(sha1Base64Digest);
byte[] blob = attachments.BlobForKey(blobKey);
NUnit.Framework.Assert.IsTrue(Arrays.Equals(Sharpen.Runtime.GetBytesForString(testBlob
, Sharpen.Extensions.GetEncoding("UTF-8")), blob));
}
/// <summary>https://github.com/couchbase/couchbase-lite-android/issues/134</summary>
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
/// <exception cref="System.IO.IOException"></exception>
public virtual void TestGetAttachmentBodyUsingPrefetch()
{
// add a doc with an attachment
Document doc = database.CreateDocument();
UnsavedRevision rev = doc.CreateRevision();
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("foo", "bar");
rev.SetUserProperties(properties);
byte[] attachBodyBytes = Sharpen.Runtime.GetBytesForString("attach body");
Attachment attachment = new Attachment(new ByteArrayInputStream(attachBodyBytes),
"text/plain");
string attachmentName = "test_attachment.txt";
rev.AddAttachment(attachment, attachmentName);
rev.Save();
// do query that finds that doc with prefetch
View view = database.GetView("aview");
view.SetMapReduce(new _Mapper_432(), null, "1");
// try to get the attachment
Query query = view.CreateQuery();
query.SetPrefetch(true);
QueryEnumerator results = query.Run();
while (results.HasNext())
{
QueryRow row = results.Next();
// This returns the revision just fine, but the sequence number
// is set to 0.
SavedRevision revision = row.GetDocument().GetCurrentRevision();
IList<string> attachments = revision.GetAttachmentNames();
// This returns an Attachment object which looks ok, except again
// its sequence number is 0. The metadata property knows about
// the length and mime type of the attachment. It also says
// "stub" -> "true".
Attachment attachmentRetrieved = revision.GetAttachment(attachmentName);
// This throws a CouchbaseLiteException with Status.NOT_FOUND.
InputStream @is = attachmentRetrieved.GetContent();
NUnit.Framework.Assert.IsNotNull(@is);
byte[] attachmentDataRetrieved = TextUtils.Read(@is);
string attachmentDataRetrievedString = Sharpen.Runtime.GetStringForBytes(attachmentDataRetrieved
);
string attachBodyString = Sharpen.Runtime.GetStringForBytes(attachBodyBytes);
NUnit.Framework.Assert.AreEqual(attachBodyString, attachmentDataRetrievedString);
}
}
private sealed class _Mapper_432 : Mapper
{
public _Mapper_432()
{
}
public void Map(IDictionary<string, object> document, Emitter emitter)
{
string id = (string)document.Get("_id");
emitter.Emit(id, null);
}
}
/// <summary>Regression test for https://github.com/couchbase/couchbase-lite-android-core/issues/70
/// </summary>
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
/// <exception cref="System.IO.IOException"></exception>
public virtual void TestAttachmentDisappearsAfterSave()
{
// create a doc with an attachment
Document doc = database.CreateDocument();
string content = "This is a test attachment!";
ByteArrayInputStream body = new ByteArrayInputStream(Sharpen.Runtime.GetBytesForString
(content));
UnsavedRevision rev = doc.CreateRevision();
rev.SetAttachment("index.html", "text/plain; charset=utf-8", body);
rev.Save();
// make sure the doc's latest revision has the attachment
IDictionary<string, object> attachments = (IDictionary)doc.GetCurrentRevision().GetProperty
("_attachments");
NUnit.Framework.Assert.IsNotNull(attachments);
NUnit.Framework.Assert.AreEqual(1, attachments.Count);
// make sure the rev has the attachment
attachments = (IDictionary)rev.GetProperty("_attachments");
NUnit.Framework.Assert.IsNotNull(attachments);
NUnit.Framework.Assert.AreEqual(1, attachments.Count);
// create new properties to add
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("foo", "bar");
// make sure the new rev still has the attachment
UnsavedRevision rev2 = doc.CreateRevision();
rev2.GetProperties().PutAll(properties);
rev2.Save();
attachments = (IDictionary)rev2.GetProperty("_attachments");
NUnit.Framework.Assert.IsNotNull(attachments);
NUnit.Framework.Assert.AreEqual(1, attachments.Count);
}
/// <summary>Regression test for https://github.com/couchbase/couchbase-lite-android-core/issues/70
/// </summary>
/// <exception cref="System.Exception"></exception>
public virtual void TestAttachmentInstallBodies()
{
IDictionary<string, object> attachmentsMap = new Dictionary<string, object>();
IDictionary<string, object> attachmentMap = new Dictionary<string, object>();
attachmentMap.Put("length", 25);
string attachmentName = "index.html";
attachmentsMap.Put(attachmentName, attachmentMap);
IDictionary<string, object> updatedAttachments = Attachment.InstallAttachmentBodies
(attachmentsMap, database);
NUnit.Framework.Assert.IsTrue(updatedAttachments.Count > 0);
NUnit.Framework.Assert.IsTrue(updatedAttachments.ContainsKey(attachmentName));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Python.Runtime
{
/// <summary>
/// Implements a Python type that provides access to CLR namespaces. The
/// type behaves like a Python module, and can contain other sub-modules.
/// </summary>
internal class ModuleObject : ExtensionType
{
private Dictionary<string, ManagedType> cache;
internal string moduleName;
internal IntPtr dict;
protected string _namespace;
public ModuleObject(string name)
{
if (name == string.Empty)
{
throw new ArgumentException("Name must not be empty!");
}
moduleName = name;
cache = new Dictionary<string, ManagedType>();
_namespace = name;
// Use the filename from any of the assemblies just so there's something for
// anything that expects __file__ to be set.
var filename = "unknown";
var docstring = "Namespace containing types from the following assemblies:\n\n";
foreach (Assembly a in AssemblyManager.GetAssemblies(name))
{
if (!a.IsDynamic && a.Location != null)
{
filename = a.Location;
}
docstring += "- " + a.FullName + "\n";
}
dict = Runtime.PyDict_New();
IntPtr pyname = Runtime.PyString_FromString(moduleName);
IntPtr pyfilename = Runtime.PyString_FromString(filename);
IntPtr pydocstring = Runtime.PyString_FromString(docstring);
IntPtr pycls = TypeManager.GetTypeHandle(GetType());
Runtime.PyDict_SetItemString(dict, "__name__", pyname);
Runtime.PyDict_SetItemString(dict, "__file__", pyfilename);
Runtime.PyDict_SetItemString(dict, "__doc__", pydocstring);
Runtime.PyDict_SetItemString(dict, "__class__", pycls);
Runtime.XDecref(pyname);
Runtime.XDecref(pyfilename);
Runtime.XDecref(pydocstring);
Marshal.WriteIntPtr(pyHandle, ObjectOffset.DictOffset(pyHandle), dict);
InitializeModuleMembers();
}
/// <summary>
/// Returns a ClassBase object representing a type that appears in
/// this module's namespace or a ModuleObject representing a child
/// namespace (or null if the name is not found). This method does
/// not increment the Python refcount of the returned object.
/// </summary>
public ManagedType GetAttribute(string name, bool guess)
{
ManagedType cached = null;
cache.TryGetValue(name, out cached);
if (cached != null)
{
return cached;
}
ModuleObject m;
ClassBase c;
Type type;
//if (AssemblyManager.IsValidNamespace(name))
//{
// IntPtr py_mod_name = Runtime.PyString_FromString(name);
// IntPtr modules = Runtime.PyImport_GetModuleDict();
// IntPtr module = Runtime.PyDict_GetItem(modules, py_mod_name);
// if (module != IntPtr.Zero)
// return (ManagedType)this;
// return null;
//}
string qname = _namespace == string.Empty
? name
: _namespace + "." + name;
// If the fully-qualified name of the requested attribute is
// a namespace exported by a currently loaded assembly, return
// a new ModuleObject representing that namespace.
if (AssemblyManager.IsValidNamespace(qname))
{
m = new ModuleObject(qname);
StoreAttribute(name, m);
return m;
}
// Look for a type in the current namespace. Note that this
// includes types, delegates, enums, interfaces and structs.
// Only public namespace members are exposed to Python.
type = AssemblyManager.LookupType(qname);
if (type != null)
{
if (!type.IsPublic)
{
return null;
}
c = ClassManager.GetClass(type);
StoreAttribute(name, c);
return c;
}
// This is a little repetitive, but it ensures that the right
// thing happens with implicit assembly loading at a reasonable
// cost. Ask the AssemblyManager to do implicit loading for each
// of the steps in the qualified name, then try it again.
bool ignore = name.StartsWith("__");
if (AssemblyManager.LoadImplicit(qname, !ignore))
{
if (AssemblyManager.IsValidNamespace(qname))
{
m = new ModuleObject(qname);
StoreAttribute(name, m);
return m;
}
type = AssemblyManager.LookupType(qname);
if (type != null)
{
if (!type.IsPublic)
{
return null;
}
c = ClassManager.GetClass(type);
StoreAttribute(name, c);
return c;
}
}
// We didn't find the name, so we may need to see if there is a
// generic type with this base name. If so, we'll go ahead and
// return it. Note that we store the mapping of the unmangled
// name to generic type - it is technically possible that some
// future assembly load could contribute a non-generic type to
// the current namespace with the given basename, but unlikely
// enough to complicate the implementation for now.
if (guess)
{
string gname = GenericUtil.GenericNameForBaseName(_namespace, name);
if (gname != null)
{
ManagedType o = GetAttribute(gname, false);
if (o != null)
{
StoreAttribute(name, o);
return o;
}
}
}
return null;
}
/// <summary>
/// Stores an attribute in the instance dict for future lookups.
/// </summary>
private void StoreAttribute(string name, ManagedType ob)
{
Runtime.PyDict_SetItemString(dict, name, ob.pyHandle);
cache[name] = ob;
}
/// <summary>
/// Preloads all currently-known names for the module namespace. This
/// can be called multiple times, to add names from assemblies that
/// may have been loaded since the last call to the method.
/// </summary>
public void LoadNames()
{
ManagedType m = null;
foreach (string name in AssemblyManager.GetNames(_namespace))
{
cache.TryGetValue(name, out m);
if (m != null)
{
continue;
}
IntPtr attr = Runtime.PyDict_GetItemString(dict, name);
// If __dict__ has already set a custom property, skip it.
if (attr != IntPtr.Zero)
{
continue;
}
GetAttribute(name, true);
}
}
/// <summary>
/// Initialize module level functions and attributes
/// </summary>
internal void InitializeModuleMembers()
{
Type funcmarker = typeof(ModuleFunctionAttribute);
Type propmarker = typeof(ModulePropertyAttribute);
Type ftmarker = typeof(ForbidPythonThreadsAttribute);
Type type = GetType();
BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
while (type != null)
{
MethodInfo[] methods = type.GetMethods(flags);
foreach (MethodInfo method in methods)
{
object[] attrs = method.GetCustomAttributes(funcmarker, false);
object[] forbid = method.GetCustomAttributes(ftmarker, false);
bool allow_threads = forbid.Length == 0;
if (attrs.Length > 0)
{
string name = method.Name;
var mi = new MethodInfo[1];
mi[0] = method;
var m = new ModuleFunctionObject(type, name, mi, allow_threads);
StoreAttribute(name, m);
}
}
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
object[] attrs = property.GetCustomAttributes(propmarker, false);
if (attrs.Length > 0)
{
string name = property.Name;
var p = new ModulePropertyObject(property);
StoreAttribute(name, p);
}
}
type = type.BaseType;
}
}
/// <summary>
/// ModuleObject __getattribute__ implementation. Module attributes
/// are always either classes or sub-modules representing subordinate
/// namespaces. CLR modules implement a lazy pattern - the sub-modules
/// and classes are created when accessed and cached for future use.
/// </summary>
public static IntPtr tp_getattro(IntPtr ob, IntPtr key)
{
var self = (ModuleObject)GetManagedObject(ob);
if (!Runtime.PyString_Check(key))
{
Exceptions.SetError(Exceptions.TypeError, "string expected");
return IntPtr.Zero;
}
IntPtr op = Runtime.PyDict_GetItem(self.dict, key);
if (op != IntPtr.Zero)
{
Runtime.XIncref(op);
return op;
}
string name = Runtime.GetManagedString(key);
if (name == "__dict__")
{
Runtime.XIncref(self.dict);
return self.dict;
}
ManagedType attr = self.GetAttribute(name, true);
if (attr == null)
{
Exceptions.SetError(Exceptions.AttributeError, name);
return IntPtr.Zero;
}
Runtime.XIncref(attr.pyHandle);
return attr.pyHandle;
}
/// <summary>
/// ModuleObject __repr__ implementation.
/// </summary>
public static IntPtr tp_repr(IntPtr ob)
{
var self = (ModuleObject)GetManagedObject(ob);
return Runtime.PyString_FromString($"<module '{self.moduleName}'>");
}
}
/// <summary>
/// The CLR module is the root handler used by the magic import hook
/// to import assemblies. It has a fixed module name "clr" and doesn't
/// provide a namespace.
/// </summary>
internal class CLRModule : ModuleObject
{
protected static bool hacked = false;
protected static bool interactive_preload = true;
internal static bool preload;
// XXX Test performance of new features //
internal static bool _SuppressDocs = false;
internal static bool _SuppressOverloads = false;
public CLRModule() : base("clr")
{
_namespace = string.Empty;
// This hackery is required in order to allow a plain Python to
// import the managed runtime via the CLR bootstrapper module.
// The standard Python machinery in control at the time of the
// import requires the module to pass PyModule_Check. :(
if (!hacked)
{
IntPtr type = tpHandle;
IntPtr mro = Marshal.ReadIntPtr(type, TypeOffset.tp_mro);
IntPtr ext = Runtime.ExtendTuple(mro, Runtime.PyModuleType);
Marshal.WriteIntPtr(type, TypeOffset.tp_mro, ext);
Runtime.XDecref(mro);
hacked = true;
}
}
public static void Reset()
{
hacked = false;
interactive_preload = true;
preload = false;
// XXX Test performance of new features //
_SuppressDocs = false;
_SuppressOverloads = false;
}
/// <summary>
/// The initializing of the preload hook has to happen as late as
/// possible since sys.ps1 is created after the CLR module is
/// created.
/// </summary>
internal void InitializePreload()
{
if (interactive_preload)
{
interactive_preload = false;
if (Runtime.PySys_GetObject("ps1") != IntPtr.Zero)
{
preload = true;
}
else
{
Exceptions.Clear();
preload = false;
}
}
}
[ModuleFunction]
public static bool getPreload()
{
return preload;
}
[ModuleFunction]
public static void setPreload(bool preloadFlag)
{
preload = preloadFlag;
}
//[ModuleProperty]
public static bool SuppressDocs
{
get { return _SuppressDocs; }
set { _SuppressDocs = value; }
}
//[ModuleProperty]
public static bool SuppressOverloads
{
get { return _SuppressOverloads; }
set { _SuppressOverloads = value; }
}
[ModuleFunction]
[ForbidPythonThreads]
public static Assembly AddReference(string name)
{
AssemblyManager.UpdatePath();
Assembly assembly = null;
assembly = AssemblyManager.FindLoadedAssembly(name);
if (assembly == null)
{
assembly = AssemblyManager.LoadAssemblyPath(name);
}
if (assembly == null)
{
assembly = AssemblyManager.LoadAssembly(name);
}
if (assembly == null)
{
assembly = AssemblyManager.LoadAssemblyFullPath(name);
}
if (assembly == null)
{
throw new FileNotFoundException($"Unable to find assembly '{name}'.");
}
return assembly;
}
/// <summary>
/// Get a Type instance for a class object.
/// clr.GetClrType(IComparable) gives you the Type for IComparable,
/// that you can e.g. perform reflection on. Similar to typeof(IComparable) in C#
/// or clr.GetClrType(IComparable) in IronPython.
///
/// </summary>
/// <param name="type"></param>
/// <returns>The Type object</returns>
[ModuleFunction]
[ForbidPythonThreads]
public static Type GetClrType(Type type)
{
return type;
}
[ModuleFunction]
[ForbidPythonThreads]
public static string FindAssembly(string name)
{
AssemblyManager.UpdatePath();
return AssemblyManager.FindAssembly(name);
}
[ModuleFunction]
public static string[] ListAssemblies(bool verbose)
{
AssemblyName[] assnames = AssemblyManager.ListAssemblies();
var names = new string[assnames.Length];
for (var i = 0; i < assnames.Length; i++)
{
if (verbose)
{
names[i] = assnames[i].FullName;
}
else
{
names[i] = assnames[i].Name;
}
}
return names;
}
[ModuleFunction]
public static int _AtExit()
{
return Runtime.AtExit();
}
}
}
| |
// 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.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyNumber
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// Number operations.
/// </summary>
public partial interface INumber
{
/// <summary>
/// Get null Number value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<double?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get invalid float Number value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<double?>> GetInvalidFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get invalid double Number value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<double?>> GetInvalidDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get invalid decimal Number value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<decimal?>> GetInvalidDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put big float value 3.402823e+20
/// </summary>
/// <param name='numberBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutBigFloatWithHttpMessagesAsync(double? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get big float value 3.402823e+20
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<double?>> GetBigFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put big double value 2.5976931e+101
/// </summary>
/// <param name='numberBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutBigDoubleWithHttpMessagesAsync(double? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get big double value 2.5976931e+101
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<double?>> GetBigDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put big double value 99999999.99
/// </summary>
/// <param name='numberBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutBigDoublePositiveDecimalWithHttpMessagesAsync(double? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get big double value 99999999.99
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<double?>> GetBigDoublePositiveDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put big double value -99999999.99
/// </summary>
/// <param name='numberBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutBigDoubleNegativeDecimalWithHttpMessagesAsync(double? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get big double value -99999999.99
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<double?>> GetBigDoubleNegativeDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put big decimal value 2.5976931e+101
/// </summary>
/// <param name='numberBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutBigDecimalWithHttpMessagesAsync(decimal? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get big decimal value 2.5976931e+101
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<decimal?>> GetBigDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put big decimal value 99999999.99
/// </summary>
/// <param name='numberBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutBigDecimalPositiveDecimalWithHttpMessagesAsync(decimal? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get big decimal value 99999999.99
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<decimal?>> GetBigDecimalPositiveDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put big decimal value -99999999.99
/// </summary>
/// <param name='numberBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutBigDecimalNegativeDecimalWithHttpMessagesAsync(decimal? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get big decimal value -99999999.99
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<decimal?>> GetBigDecimalNegativeDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put small float value 3.402823e-20
/// </summary>
/// <param name='numberBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutSmallFloatWithHttpMessagesAsync(double? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get big double value 3.402823e-20
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<double?>> GetSmallFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put small double value 2.5976931e-101
/// </summary>
/// <param name='numberBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutSmallDoubleWithHttpMessagesAsync(double? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get big double value 2.5976931e-101
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<double?>> GetSmallDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put small decimal value 2.5976931e-101
/// </summary>
/// <param name='numberBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> PutSmallDecimalWithHttpMessagesAsync(decimal? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get small decimal value 2.5976931e-101
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<decimal?>> GetSmallDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
//This namespace holds Indicators in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Indicators
{
public class TrueRange : Indicator
{
private ATR tr, atr, trOpc, atrOpc;
private StdDev stdDev;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"";
Name = "TrueRange";
Calculate = Calculate.OnBarClose;
IsOverlay = false;
DisplayInDataBox = true;
DrawOnPricePanel = true;
DrawHorizontalGridLines = true;
DrawVerticalGridLines = true;
PaintPriceMarkers = true;
ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
//Disable this property if your indicator requires custom values that cumulate with each new market data event.
//See Help Guide for additional information.
IsSuspendedWhileInactive = true;
TRPeriod = 1;
ATRPeriod = 14;
StdDevPeriod = 14;
Multiplier = 1.0;
AddPlot(new Stroke(Brushes.DarkGreen, 8), PlotStyle.Bar, "TRBar");
AddPlot(new Stroke(Brushes.LimeGreen, 4), PlotStyle.Bar, "ATRBar");
AddPlot(Brushes.Red, "AtrStd1");
AddPlot(Brushes.Red, "AtrStd2");
AddPlot(Brushes.Transparent, "MarketAnalyzerPlot");
}
else if (State == State.Configure)
{
this.AddDataSeries(BarsPeriods[0].BarsPeriodType, BarsPeriods[0].Value);
tr = ATR(Values[1], TRPeriod);
atr = ATR(ATRPeriod);
stdDev = StdDev(tr, StdDevPeriod);
trOpc = ATR(TRPeriod);
atrOpc = ATR(ATRPeriod);
}
}
protected override void OnBarUpdate()
{
if (CurrentBar <= ATRPeriod + StdDevPeriod)
{
return;
}
TRBar[0] = tr[0];
ATRBar[0] = atr[0];
AtrStd1[0] = atr[0] + stdDev[0];
AtrStd2[0] = atr[0] + stdDev[0] * 2;
MarketAnalyzerPlot[0] = trOpc[0] * Multiplier > atrOpc[0] ? 1 : 0;
}
#region Properties
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="TRPeriod", Order=1, GroupName="Parameters")]
public int TRPeriod
{ get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="ATRPeriod", Order=2, GroupName="Parameters")]
public int ATRPeriod
{ get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="StdDevPeriod", Order=3, GroupName="Parameters")]
public int StdDevPeriod
{ get; set; }
[NinjaScriptProperty]
[Range(0, double.MaxValue)]
[Display(Name="Multiplier", Order=4, GroupName="Parameters")]
public double Multiplier
{ get; set; }
[Browsable(false)]
[XmlIgnore]
public Series<double> TRBar
{
get { return Values[1]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> ATRBar
{
get { return Values[0]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> AtrStd1
{
get { return Values[2]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> AtrStd2
{
get { return Values[3]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> MarketAnalyzerPlot
{
get { return Values[4]; }
}
#endregion
}
}
#region NinjaScript generated code. Neither change nor remove.
namespace NinjaTrader.NinjaScript.Indicators
{
public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
{
private TrueRange[] cacheTrueRange;
public TrueRange TrueRange(int tRPeriod, int aTRPeriod, int stdDevPeriod, double multiplier)
{
return TrueRange(Input, tRPeriod, aTRPeriod, stdDevPeriod, multiplier);
}
public TrueRange TrueRange(ISeries<double> input, int tRPeriod, int aTRPeriod, int stdDevPeriod, double multiplier)
{
if (cacheTrueRange != null)
for (int idx = 0; idx < cacheTrueRange.Length; idx++)
if (cacheTrueRange[idx] != null && cacheTrueRange[idx].TRPeriod == tRPeriod && cacheTrueRange[idx].ATRPeriod == aTRPeriod && cacheTrueRange[idx].StdDevPeriod == stdDevPeriod && cacheTrueRange[idx].Multiplier == multiplier && cacheTrueRange[idx].EqualsInput(input))
return cacheTrueRange[idx];
return CacheIndicator<TrueRange>(new TrueRange(){ TRPeriod = tRPeriod, ATRPeriod = aTRPeriod, StdDevPeriod = stdDevPeriod, Multiplier = multiplier }, input, ref cacheTrueRange);
}
}
}
namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
{
public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
{
public Indicators.TrueRange TrueRange(int tRPeriod, int aTRPeriod, int stdDevPeriod, double multiplier)
{
return indicator.TrueRange(Input, tRPeriod, aTRPeriod, stdDevPeriod, multiplier);
}
public Indicators.TrueRange TrueRange(ISeries<double> input , int tRPeriod, int aTRPeriod, int stdDevPeriod, double multiplier)
{
return indicator.TrueRange(input, tRPeriod, aTRPeriod, stdDevPeriod, multiplier);
}
}
}
namespace NinjaTrader.NinjaScript.Strategies
{
public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
{
public Indicators.TrueRange TrueRange(int tRPeriod, int aTRPeriod, int stdDevPeriod, double multiplier)
{
return indicator.TrueRange(Input, tRPeriod, aTRPeriod, stdDevPeriod, multiplier);
}
public Indicators.TrueRange TrueRange(ISeries<double> input , int tRPeriod, int aTRPeriod, int stdDevPeriod, double multiplier)
{
return indicator.TrueRange(input, tRPeriod, aTRPeriod, stdDevPeriod, multiplier);
}
}
}
#endregion
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AllReady.Configuration;
using AllReady.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
namespace AllReady.DataAccess
{
public class SampleDataGenerator
{
private readonly AllReadyContext _context;
private readonly SampleDataSettings _settings;
private readonly GeneralSettings _generalSettings;
private readonly UserManager<ApplicationUser> _userManager;
private readonly TimeZoneInfo _timeZone = TimeZoneInfo.Local;
public SampleDataGenerator(AllReadyContext context, IOptions<SampleDataSettings> options, IOptions<GeneralSettings> generalSettings, UserManager<ApplicationUser> userManager)
{
_context = context;
_settings = options.Value;
_generalSettings = generalSettings.Value;
_userManager = userManager;
}
public async Task InsertTestData()
{
// Avoid polluting the database if there's already something in there.
if (_context.Locations.Any() ||
_context.Organizations.Any() ||
_context.VolunteerTasks.Any() ||
_context.Campaigns.Any() ||
_context.Events.Any() ||
_context.EventSkills.Any() ||
_context.Skills.Any() ||
_context.Resources.Any())
{
return;
}
#region postalCodes
var existingPostalCode = _context.PostalCodes.ToList();
_context.PostalCodes.AddRange(GetPostalCodes(existingPostalCode));
#endregion
var organizations = new List<Organization>();
var organizationSkills = new List<Skill>();
var locations = GetLocations();
var users = new List<ApplicationUser>();
var volunteerTaskSignups = new List<VolunteerTaskSignup>();
var events = new List<Event>();
var eventSkills = new List<EventSkill>();
var campaigns = new List<Campaign>();
var volunteerTasks = new List<VolunteerTask>();
var resources = new List<Resource>();
var contacts = GetContacts();
var skills = new List<Skill>();
var eventManagers = new List<EventManager>();
var campaignManagers = new List<CampaignManager>();
#region Skills
var medical = new Skill { Name = "Medical", Description = "specific enough, right?" };
var cprCertified = new Skill { Name = "CPR Certified", ParentSkill = medical, Description = "ha ha ha ha, stayin alive" };
var md = new Skill { Name = "MD", ParentSkill = medical, Description = "Trust me, I'm a doctor" };
var surgeon = new Skill { Name = "Surgeon", ParentSkill = md, Description = "cut open; sew shut; play 18 holes" };
skills.AddRange(new[] { medical, cprCertified, md, surgeon });
#endregion
#region Organization
var organization = new Organization
{
Name = "Humanitarian Toolbox",
LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png",
WebUrl = "http://www.htbox.org",
Location = locations.FirstOrDefault(),
Campaigns = new List<Campaign>(),
OrganizationContacts = new List<OrganizationContact>(),
};
#endregion
#region Organization Skills
organizationSkills.Add(new Skill
{
Name = "Code Ninja",
Description = "Ability to commit flawless code without review or testing",
OwningOrganization = organization
});
#endregion
#region Campaign
//TODO: Campaign/Event/Task dates need to be set as a DateTimeOffset, offset to the correct timezone instead of UtcNow or DateTime.Today.
var firePreventionCampaign = new Campaign
{
Name = "Neighborhood Fire Prevention Days",
ManagingOrganization = organization,
Resources = resources,
TimeZoneId = _timeZone.Id,
StartDateTime = AdjustToTimezone(DateTimeOffset.Now.AddMonths(-1), _timeZone),
EndDateTime = AdjustToTimezone(DateTimeOffset.Now.AddMonths(3), _timeZone),
Location = GetRandom(locations),
Published = true
};
organization.Campaigns.Add(firePreventionCampaign);
var smokeDetectorCampaignGoal = new CampaignGoal
{
GoalType = GoalType.Numeric,
NumericGoal = 10000,
CurrentGoalLevel = 6722,
Display = true,
TextualGoal = "Total number of smoke detectors installed."
};
_context.CampaignGoals.Add(smokeDetectorCampaignGoal);
var smokeDetectorCampaign = new Campaign
{
Name = "Working Smoke Detectors Save Lives",
ManagingOrganization = organization,
StartDateTime = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone),
EndDateTime = AdjustToTimezone(DateTime.Today.AddMonths(1), _timeZone),
CampaignGoals = new List<CampaignGoal> { smokeDetectorCampaignGoal },
TimeZoneId = _timeZone.Id,
Location = GetRandom(locations),
Published = true
};
organization.Campaigns.Add(smokeDetectorCampaign);
var financialCampaign = new Campaign
{
Name = "Everyday Financial Safety",
ManagingOrganization = organization,
TimeZoneId = _timeZone.Id,
StartDateTime = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone),
EndDateTime = AdjustToTimezone(DateTime.Today.AddMonths(1), _timeZone),
Location = GetRandom(locations),
Published = true
};
organization.Campaigns.Add(financialCampaign);
var safetyKitCampaign = new Campaign
{
Name = "Simple Safety Kit Building",
ManagingOrganization = organization,
TimeZoneId = _timeZone.Id,
StartDateTime = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone),
EndDateTime = AdjustToTimezone(DateTime.Today.AddMonths(2), _timeZone),
Location = GetRandom(locations),
Published = true
};
organization.Campaigns.Add(safetyKitCampaign);
var carSafeCampaign = new Campaign
{
Name = "Family Safety In the Car",
ManagingOrganization = organization,
TimeZoneId = _timeZone.Id,
StartDateTime = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone),
EndDateTime = AdjustToTimezone(DateTime.Today.AddMonths(2), _timeZone),
Location = GetRandom(locations),
Published = true
};
organization.Campaigns.Add(carSafeCampaign);
var escapePlanCampaign = new Campaign
{
Name = "Be Ready to Get Out: Have a Home Escape Plan",
ManagingOrganization = organization,
TimeZoneId = _timeZone.Id,
StartDateTime = AdjustToTimezone(DateTime.Today.AddMonths(-6), _timeZone),
EndDateTime = AdjustToTimezone(DateTime.Today.AddMonths(6), _timeZone),
Location = GetRandom(locations),
Published = true
};
organization.Campaigns.Add(escapePlanCampaign);
#endregion
#region Event
var queenAnne = new Event
{
Name = "Queen Anne Fire Prevention Day",
Campaign = firePreventionCampaign,
StartDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddDays(1), _timeZone),
EndDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddMonths(2), _timeZone),
TimeZoneId = firePreventionCampaign.TimeZoneId,
Location = GetRandom(locations),
RequiredSkills = new List<EventSkill>(),
EventType = EventType.Itinerary,
};
queenAnne.VolunteerTasks = GetSomeVolunteerTasks(queenAnne, organization);
var ask = new EventSkill { Skill = surgeon, Event = queenAnne };
queenAnne.RequiredSkills.Add(ask);
eventSkills.Add(ask);
ask = new EventSkill { Skill = cprCertified, Event = queenAnne };
queenAnne.RequiredSkills.Add(ask);
eventSkills.Add(ask);
volunteerTasks.AddRange(queenAnne.VolunteerTasks);
var ballard = new Event
{
Name = "Ballard Fire Prevention Day",
Campaign = firePreventionCampaign,
StartDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddDays(1), _timeZone),
EndDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddMonths(2), _timeZone),
TimeZoneId = firePreventionCampaign.TimeZoneId,
Location = GetRandom(locations),
EventType = EventType.Itinerary,
};
ballard.VolunteerTasks = GetSomeVolunteerTasks(ballard, organization);
volunteerTasks.AddRange(ballard.VolunteerTasks);
var madrona = new Event
{
Name = "Madrona Fire Prevention Day",
Campaign = firePreventionCampaign,
StartDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddDays(1), _timeZone),
EndDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddMonths(2), _timeZone),
TimeZoneId = firePreventionCampaign.TimeZoneId,
Location = GetRandom(locations),
EventType = EventType.Itinerary,
};
madrona.VolunteerTasks = GetSomeVolunteerTasks(madrona, organization);
volunteerTasks.AddRange(madrona.VolunteerTasks);
var southLoopSmoke = new Event
{
Name = "Smoke Detector Installation and Testing-South Loop",
Campaign = smokeDetectorCampaign,
StartDateTime = AdjustToTimezone(smokeDetectorCampaign.StartDateTime.AddDays(1), _timeZone),
EndDateTime = AdjustToTimezone(smokeDetectorCampaign.EndDateTime, _timeZone),
TimeZoneId = smokeDetectorCampaign.TimeZoneId,
Location = GetRandom(locations),
EventType = EventType.Itinerary,
};
southLoopSmoke.VolunteerTasks = GetSomeVolunteerTasks(southLoopSmoke, organization);
volunteerTasks.AddRange(southLoopSmoke.VolunteerTasks);
var northLoopSmoke = new Event
{
Name = "Smoke Detector Installation and Testing-Near North Side",
Campaign = smokeDetectorCampaign,
StartDateTime = AdjustToTimezone(smokeDetectorCampaign.StartDateTime.AddDays(1), _timeZone),
EndDateTime = AdjustToTimezone(smokeDetectorCampaign.EndDateTime, _timeZone),
TimeZoneId = smokeDetectorCampaign.TimeZoneId,
Location = GetRandom(locations),
EventType = EventType.Itinerary,
};
northLoopSmoke.VolunteerTasks = GetSomeVolunteerTasks(northLoopSmoke, organization);
volunteerTasks.AddRange(northLoopSmoke.VolunteerTasks);
var dateTimeToday = DateTime.Today;
var rentersInsurance = new Event
{
Name = "Renters Insurance Education Door to Door and a bag of chips",
Description = "description for the win",
Campaign = financialCampaign,
StartDateTime = AdjustToTimezone(new DateTime(dateTimeToday.Year, dateTimeToday.Month, dateTimeToday.Day, 8, 0, 0), _timeZone),
EndDateTime = AdjustToTimezone(new DateTime(dateTimeToday.Year, dateTimeToday.Month, dateTimeToday.Day, 16, 0, 0), _timeZone),
TimeZoneId = financialCampaign.TimeZoneId,
Location = GetRandom(locations),
EventType = EventType.Rally,
};
rentersInsurance.VolunteerTasks = GetSomeVolunteerTasks(rentersInsurance, organization);
volunteerTasks.AddRange(rentersInsurance.VolunteerTasks);
var rentersInsuranceEd = new Event
{
Name = "Renters Insurance Education Door to Door (woop woop)",
Description = "another great description",
Campaign = financialCampaign,
StartDateTime = AdjustToTimezone(financialCampaign.StartDateTime.AddMonths(1).AddDays(1), _timeZone),
EndDateTime = AdjustToTimezone(financialCampaign.EndDateTime, _timeZone),
TimeZoneId = financialCampaign.TimeZoneId,
Location = GetRandom(locations),
EventType = EventType.Itinerary,
};
rentersInsuranceEd.VolunteerTasks = GetSomeVolunteerTasks(rentersInsuranceEd, organization);
volunteerTasks.AddRange(rentersInsuranceEd.VolunteerTasks);
var safetyKitBuild = new Event
{
Name = "Safety Kit Assembly Volunteer Day",
Description = "Full day of volunteers building kits",
Campaign = safetyKitCampaign,
StartDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddDays(1), _timeZone),
EndDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone),
TimeZoneId = safetyKitCampaign.TimeZoneId,
Location = GetRandom(locations),
EventType = EventType.Itinerary,
};
safetyKitBuild.VolunteerTasks = GetSomeVolunteerTasks(safetyKitBuild, organization);
volunteerTasks.AddRange(safetyKitBuild.VolunteerTasks);
var safetyKitHandout = new Event
{
Name = "Safety Kit Distribution Weekend",
Description = "Handing out kits at local fire stations",
Campaign = safetyKitCampaign,
StartDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddDays(1), _timeZone),
EndDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone),
TimeZoneId = safetyKitCampaign.TimeZoneId,
Location = GetRandom(locations),
EventType = EventType.Itinerary,
};
safetyKitHandout.VolunteerTasks = GetSomeVolunteerTasks(safetyKitHandout, organization);
volunteerTasks.AddRange(safetyKitHandout.VolunteerTasks);
var carSeatTest1 = new Event
{
Name = "Car Seat Testing-Naperville",
Description = "Checking car seats at local fire stations after last day of school year",
Campaign = carSafeCampaign,
StartDateTime = AdjustToTimezone(carSafeCampaign.StartDateTime.AddDays(1), _timeZone),
EndDateTime = AdjustToTimezone(carSafeCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone),
TimeZoneId = carSafeCampaign.TimeZoneId,
Location = GetRandom(locations),
EventType = EventType.Itinerary,
};
carSeatTest1.VolunteerTasks = GetSomeVolunteerTasks(carSeatTest1, organization);
volunteerTasks.AddRange(carSeatTest1.VolunteerTasks);
var carSeatTest2 = new Event
{
Name = "Car Seat and Tire Pressure Checking Volunteer Day",
Description = "Checking those things all day at downtown train station parking",
Campaign = carSafeCampaign,
StartDateTime = AdjustToTimezone(carSafeCampaign.StartDateTime.AddDays(1), _timeZone),
EndDateTime = AdjustToTimezone(carSafeCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone),
TimeZoneId = carSafeCampaign.TimeZoneId,
Location = GetRandom(locations),
EventType = EventType.Itinerary,
};
carSeatTest2.VolunteerTasks = GetSomeVolunteerTasks(carSeatTest2, organization);
volunteerTasks.AddRange(carSeatTest2.VolunteerTasks);
var homeFestival = new Event
{
Name = "Park District Home Safety Festival",
Description = "At downtown park district(adjacent to pool)",
Campaign = safetyKitCampaign,
StartDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddDays(1), _timeZone),
EndDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddMonths(1), _timeZone),
TimeZoneId = safetyKitCampaign.TimeZoneId,
Location = GetRandom(locations),
EventType = EventType.Itinerary,
};
homeFestival.VolunteerTasks = GetSomeVolunteerTasks(homeFestival, organization);
volunteerTasks.AddRange(homeFestival.VolunteerTasks);
var homeEscape = new Event
{
Name = "Home Escape Plan Flyer Distribution",
Description = "Handing out flyers door to door in several areas of town after school/ work hours.Streets / blocks will vary but number of volunteers.",
Campaign = escapePlanCampaign,
StartDateTime = AdjustToTimezone(escapePlanCampaign.StartDateTime.AddDays(1), _timeZone),
EndDateTime = AdjustToTimezone(escapePlanCampaign.StartDateTime.AddMonths(7), _timeZone),
TimeZoneId = escapePlanCampaign.TimeZoneId,
Location = GetRandom(locations),
EventType = EventType.Itinerary,
};
homeEscape.VolunteerTasks = GetSomeVolunteerTasks(homeEscape, organization);
volunteerTasks.AddRange(homeEscape.VolunteerTasks);
#endregion
#region Link campaign and event
firePreventionCampaign.Events = new List<Event> { queenAnne, ballard, madrona };
smokeDetectorCampaign.Events = new List<Event> { southLoopSmoke, northLoopSmoke };
financialCampaign.Events = new List<Event> { rentersInsurance, rentersInsuranceEd };
safetyKitCampaign.Events = new List<Event> { safetyKitBuild, safetyKitHandout };
carSafeCampaign.Events = new List<Event> { carSeatTest1, carSeatTest2 };
escapePlanCampaign.Events = new List<Event> { homeFestival, homeEscape };
#endregion
#region Add Campaigns and Events
organizations.Add(organization);
campaigns.Add(firePreventionCampaign);
campaigns.Add(smokeDetectorCampaign);
campaigns.Add(financialCampaign);
campaigns.Add(escapePlanCampaign);
campaigns.Add(safetyKitCampaign);
campaigns.Add(carSafeCampaign);
events.AddRange(firePreventionCampaign.Events);
events.AddRange(smokeDetectorCampaign.Events);
events.AddRange(financialCampaign.Events);
events.AddRange(escapePlanCampaign.Events);
events.AddRange(safetyKitCampaign.Events);
events.AddRange(carSafeCampaign.Events);
#endregion
#region Insert Resource items into Resources
resources.Add(new Resource
{
Name = "allReady Partner Name",
Description = "allready Partner Description",
PublishDateBegin = DateTime.Today,
PublishDateEnd = DateTime.Today.AddDays(14),
MediaUrl = "",
ResourceUrl = "",
CategoryTag = "Partners",
CampaignId = 1
});
resources.Add(new Resource
{
Name = "allReady Partner Name 2",
Description = "allready Partner Description 2",
PublishDateBegin = DateTime.Today.AddDays(-3),
PublishDateEnd = DateTime.Today.AddDays(-1),
MediaUrl = "",
ResourceUrl = "",
CategoryTag = "Partners",
CampaignId = 1,
});
#endregion
#region Insert into DB
_context.Skills.AddRange(skills);
_context.Contacts.AddRange(contacts);
_context.EventSkills.AddRange(eventSkills);
_context.Locations.AddRange(locations);
_context.Organizations.AddRange(organizations);
_context.VolunteerTasks.AddRange(volunteerTasks);
_context.Campaigns.AddRange(campaigns);
_context.Events.AddRange(events);
_context.Resources.AddRange(resources);
//_context.SaveChanges();
#endregion
#region Users for Events
var username1 = $"{_settings.DefaultUsername}1.com";
var username2 = $"{_settings.DefaultUsername}2.com";
var username3 = $"{_settings.DefaultUsername}3.com";
var user1 = new ApplicationUser
{
FirstName = "FirstName1",
LastName = "LastName1",
UserName = username1,
Email = username1,
EmailConfirmed = true,
TimeZoneId = _timeZone.Id,
PhoneNumber = "111-111-1111"
};
await _userManager.CreateAsync(user1, _settings.DefaultAdminPassword);
users.Add(user1);
var user2 = new ApplicationUser
{
FirstName = "FirstName2",
LastName = "LastName2",
UserName = username2,
Email = username2,
EmailConfirmed = true,
TimeZoneId = _timeZone.Id,
PhoneNumber = "222-222-2222"
};
await _userManager.CreateAsync(user2, _settings.DefaultAdminPassword);
users.Add(user2);
var user3 = new ApplicationUser
{
FirstName = "FirstName3",
LastName = "LastName3",
UserName = username3,
Email = username3,
EmailConfirmed = true,
TimeZoneId = _timeZone.Id,
PhoneNumber = "333-333-3333"
};
await _userManager.CreateAsync(user3, _settings.DefaultAdminPassword);
users.Add(user3);
#endregion
#region Event Managers
var eventManagerUser = new ApplicationUser
{
FirstName = "Event",
LastName = "Manager",
UserName = _settings.DefaultEventManagerUsername,
Email = _settings.DefaultEventManagerUsername,
EmailConfirmed = true,
TimeZoneId = _timeZone.Id,
PhoneNumber = "333-333-3333"
};
await _userManager.CreateAsync(eventManagerUser, _settings.DefaultAdminPassword);
users.Add(eventManagerUser);
var eventManager = new EventManager
{
Event = queenAnne,
User = eventManagerUser
};
eventManagers.Add(eventManager);
_context.EventManagers.AddRange(eventManagers);
#endregion
#region Campaign Managers
var campaignManagerUser = new ApplicationUser
{
FirstName = "Campaign",
LastName = "Manager",
UserName = _settings.DefaultCampaignManagerUsername,
Email = _settings.DefaultCampaignManagerUsername,
EmailConfirmed = true,
TimeZoneId = _timeZone.Id,
PhoneNumber = "333-333-3333"
};
await _userManager.CreateAsync(campaignManagerUser, _settings.DefaultAdminPassword);
users.Add(campaignManagerUser);
var campaignManager = new CampaignManager
{
Campaign = firePreventionCampaign,
User = campaignManagerUser
};
campaignManagers.Add(campaignManager);
_context.CampaignManagers.AddRange(campaignManagers);
#endregion
#region TaskSignups
var i = 0;
foreach (var volunteerTask in volunteerTasks.Where(t => t.Event == madrona))
{
for (var j = 0; j < i; j++)
{
volunteerTaskSignups.Add(new VolunteerTaskSignup { VolunteerTask = volunteerTask, User = users[j], Status = VolunteerTaskStatus.Assigned });
}
i = (i + 1) % users.Count;
}
_context.VolunteerTaskSignups.AddRange(volunteerTaskSignups);
#endregion
#region OrganizationContacts
organization.OrganizationContacts.Add(new OrganizationContact { Contact = contacts.First(), Organization = organization, ContactType = 1 /*Primary*/ });
#endregion
#region Wrap Up DB
_context.SaveChanges();
#endregion
}
private DateTimeOffset AdjustToTimezone(DateTimeOffset dateTimeOffset, TimeZoneInfo timeZone)
{
return new DateTimeOffset(dateTimeOffset.DateTime, timeZone.GetUtcOffset(dateTimeOffset.DateTime));
}
private List<Contact> GetContacts()
{
var list = new List<Contact>();
list.Add(new Contact { FirstName = "Bob", LastName = "Smith", Email = "BobSmith@mailinator.com", PhoneNumber = "999-888-7777" });
list.Add(new Contact { FirstName = "George", LastName = "Leone", Email = "GeorgeLeone@mailinator.com", PhoneNumber = "999-888-7777" });
return list;
}
#region Sample Data Helper methods
private static T GetRandom<T>(List<T> list)
{
var rand = new Random();
return list[rand.Next(list.Count)];
}
private List<VolunteerTask> GetSomeVolunteerTasks(Event campaignEvent, Organization organization)
{
var volunteerTasks = new List<VolunteerTask>();
for (var i = 0; i < 5; i++)
{
volunteerTasks.Add(new VolunteerTask
{
Event = campaignEvent,
Description = "Description of a very important volunteerTask # " + i,
Name = "Task # " + i,
EndDateTime = AdjustToTimezone(DateTime.Today.AddHours(17).AddDays(i), _timeZone),
StartDateTime = AdjustToTimezone(DateTime.Today.AddHours(9).AddDays(campaignEvent.EventType == EventType.Itinerary ? i : i - 1), _timeZone),
Organization = organization,
NumberOfVolunteersRequired = 5
});
}
return volunteerTasks;
}
private static Location CreateLocation(string address1, string city, string state, string postalCode)
{
var ret = new Location
{
Address1 = address1,
City = city,
State = state,
Country = "US",
PostalCode = postalCode,
Name = "Humanitarian Toolbox location",
PhoneNumber = "1-425-555-1212"
};
return ret;
}
private List<PostalCodeGeo> GetPostalCodes(IList<PostalCodeGeo> existingPostalCode)
{
var postalCodes = new List<PostalCodeGeo>();
if (!existingPostalCode.Any(item => item.PostalCode == "98052")) postalCodes.Add(new PostalCodeGeo { City = "Redmond", State = "WA", PostalCode = "98052" });
if (!existingPostalCode.Any(item => item.PostalCode == "98004")) postalCodes.Add(new PostalCodeGeo { City = "Bellevue", State = "WA", PostalCode = "98004" });
if (!existingPostalCode.Any(item => item.PostalCode == "98116")) postalCodes.Add(new PostalCodeGeo { City = "Seattle", State = "WA", PostalCode = "98116" });
if (!existingPostalCode.Any(item => item.PostalCode == "98117")) postalCodes.Add(new PostalCodeGeo { City = "Seattle", State = "WA", PostalCode = "98117" });
if (!existingPostalCode.Any(item => item.PostalCode == "98007")) postalCodes.Add(new PostalCodeGeo { City = "Bellevue", State = "WA", PostalCode = "98007" });
if (!existingPostalCode.Any(item => item.PostalCode == "98027")) postalCodes.Add(new PostalCodeGeo { City = "Issaquah", State = "WA", PostalCode = "98027" });
if (!existingPostalCode.Any(item => item.PostalCode == "98034")) postalCodes.Add(new PostalCodeGeo { City = "Kirkland", State = "WA", PostalCode = "98034" });
if (!existingPostalCode.Any(item => item.PostalCode == "98033")) postalCodes.Add(new PostalCodeGeo { City = "Kirkland", State = "WA", PostalCode = "98033" });
if (!existingPostalCode.Any(item => item.PostalCode == "60505")) postalCodes.Add(new PostalCodeGeo { City = "Aurora", State = "IL", PostalCode = "60505" });
if (!existingPostalCode.Any(item => item.PostalCode == "60506")) postalCodes.Add(new PostalCodeGeo { City = "Aurora", State = "IL", PostalCode = "60506" });
if (!existingPostalCode.Any(item => item.PostalCode == "45231")) postalCodes.Add(new PostalCodeGeo { City = "Cincinnati", State = "OH", PostalCode = "45231" });
if (!existingPostalCode.Any(item => item.PostalCode == "45240")) postalCodes.Add(new PostalCodeGeo { City = "Cincinnati", State = "OH", PostalCode = "45240" });
return postalCodes;
}
private List<Location> GetLocations()
{
var ret = new List<Location>
{
CreateLocation("1 Microsoft Way", "Redmond", "WA", "98052"),
CreateLocation("15563 Ne 31st St", "Redmond", "WA", "98052"),
CreateLocation("700 Bellevue Way Ne", "Bellevue", "WA", "98004"),
CreateLocation("1702 Alki Ave SW", "Seattle", "WA", "98116"),
CreateLocation("8498 Seaview Pl NW", "Seattle", "WA", "98117"),
CreateLocation("6046 W Lake Sammamish Pkwy Ne", "Redmond", "WA", "98052"),
CreateLocation("7031 148th Ave Ne", "Redmond", "WA", "98052"),
CreateLocation("2430 148th Ave SE", "Bellevue", "WA", "98007"),
CreateLocation("2000 NW Sammamish Rd", "Issaquah", "WA", "98027"),
CreateLocation("9703 Ne Juanita Dr", "Kirkland", "WA", "98034"),
CreateLocation("25 Lakeshore Plaza Dr", "Kirkland", "Washington", "98033"),
CreateLocation("633 Waverly Way", "Kirkland", "WA", "98033")
};
return ret;
}
#endregion
/// <summary>
/// Creates a administrative user who can manage the inventory.
/// </summary>
public async Task CreateAdminUser()
{
var user = await _userManager.FindByNameAsync(_settings.DefaultAdminUsername);
if (user == null)
{
user = new ApplicationUser
{
FirstName = "FirstName4",
LastName = "LastName4",
UserName = _settings.DefaultAdminUsername,
Email = _settings.DefaultAdminUsername,
TimeZoneId = _timeZone.Id,
EmailConfirmed = true,
PhoneNumber = "444-444-4444"
};
await _userManager.CreateAsync(user, _settings.DefaultAdminPassword);
await _userManager.AddClaimAsync(user, new Claim(Security.ClaimTypes.UserType, nameof(UserType.SiteAdmin)));
var user2 = new ApplicationUser
{
FirstName = "FirstName5",
LastName = "LastName5",
UserName = _settings.DefaultOrganizationUsername,
Email = _settings.DefaultOrganizationUsername,
TimeZoneId = _timeZone.Id,
EmailConfirmed = true,
PhoneNumber = "555-555-5555"
};
// For the sake of being able to exercise Organization-specific stuff, we need to associate a organization.
await _userManager.CreateAsync(user2, _settings.DefaultAdminPassword);
await _userManager.AddClaimAsync(user2, new Claim(Security.ClaimTypes.UserType, nameof(UserType.OrgAdmin)));
await _userManager.AddClaimAsync(user2, new Claim(Security.ClaimTypes.Organization, _context.Organizations.First().Id.ToString()));
var user3 = new ApplicationUser
{
FirstName = "FirstName6",
LastName = "LastName6",
UserName = _settings.DefaultUsername,
Email = _settings.DefaultUsername,
TimeZoneId = _timeZone.Id,
EmailConfirmed = true,
PhoneNumber = "666-666-6666"
};
await _userManager.CreateAsync(user3, _settings.DefaultAdminPassword);
}
}
}
}
| |
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.IO;
using System.Net;
using System.Text;
using System.Security;
using System.Collections.Generic;
using System.Reflection;
using Hydra.Framework.XmlSerialization.Common;
using Hydra.Framework.XmlSerialization.Common.XPath;
using Hydra.Framework.XmlSerialization.XPointer;
namespace Hydra.Framework.XmlSerialization.XInclude
{
//
//**********************************************************************
/// <summary>
/// <c>XIncludingReader</c> class implements streamable subset of the
/// XInclude 1.0 in a fast, non-caching, forward-only fashion.
/// To put it another way <c>XIncludingReader</c> is XML Base and XInclude 1.0 aware
/// <see cref="XmlReader"/>.
//**********************************************************************
//
public class XIncludingReader : XmlReader
{
#region Private fields
//XInclude keywords
private XIncludeKeywords _keywords;
//Current reader
private XmlReader _reader;
//Stack of readers
private Stack<XmlReader> _readers;
//Top base URI
private Uri _topBaseUri;
//Top-level included item flag
private bool _topLevel;
//A top-level included element has been included already
private bool _gotTopIncludedElem;
//At least one element has been returned by the reader
private bool _gotElement;
//Internal state
private XIncludingReaderState _state;
//StateName table
private XmlNameTable _nameTable;
//Normalization
private bool _normalization;
//Whitespace handling
private WhitespaceHandling _whiteSpaceHandling;
//Emit relative xml:base URIs
private bool _relativeBaseUri = true;
//Current fallback state
private FallbackState _fallbackState;
//Previous fallback state (imagine enclosed deep xi:fallback/xi:include tree)
private FallbackState _prevFallbackState;
//XmlResolver to resolve URIs
XmlResolver _xmlResolver;
//Expose text inclusions as CDATA
private bool _exposeTextAsCDATA;
//Top-level included item has different xml:lang
private bool _differentLang = false;
//Acquired infosets cache
private static IDictionary<string, WeakReference> _cache;
#endregion
#region Constructors
//
//**********************************************************************
/// <summary>
/// Creates new instance of <c>XIncludingReader</c> class with
/// specified underlying <c>XmlReader</c> reader.
/// </summary>
/// <param name="reader">Underlying reader to read from</param>
//**********************************************************************
//
public XIncludingReader(XmlReader reader)
{
XmlTextReader xtr = reader as XmlTextReader;
if (xtr != null)
{
XmlValidatingReader vr = new XmlValidatingReader(reader);
vr.ValidationType = ValidationType.None;
vr.EntityHandling = EntityHandling.ExpandEntities;
vr.ValidationEventHandler += new ValidationEventHandler(
ValidationCallback);
_normalization = xtr.Normalization;
_whiteSpaceHandling = xtr.WhitespaceHandling;
_reader = vr;
}
else
{
_reader = reader;
}
_nameTable = reader.NameTable;
_keywords = new XIncludeKeywords(NameTable);
if (_reader.BaseURI != "")
_topBaseUri = new Uri(_reader.BaseURI);
else
{
_relativeBaseUri = false;
_topBaseUri = new Uri(Assembly.GetExecutingAssembly().Location);
}
_readers = new Stack<XmlReader>();
_state = XIncludingReaderState.Default;
}
//
//**********************************************************************
/// <summary>
/// Creates new instance of <c>XIncludingReader</c> class with
/// specified URL.
/// </summary>
/// <param name="url">Document location.</param>
//**********************************************************************
//
public XIncludingReader(string url)
: this(new XmlBaseAwareXmlTextReader(url)) { }
//
//**********************************************************************
/// <summary>
/// Creates new instance of <c>XIncludingReader</c> class with
/// specified URL and nametable.
/// </summary>
/// <param name="url">Document location.</param>
/// <param name="nt">StateName table.</param>
//**********************************************************************
//
public XIncludingReader(string url, XmlNameTable nt) :
this(new XmlBaseAwareXmlTextReader(url, nt)) { }
//
//**********************************************************************
/// <summary>
/// Creates new instance of <c>XIncludingReader</c> class with
/// specified <c>TextReader</c> reader.
/// </summary>
/// <param name="reader"><c>TextReader</c>.</param>
//**********************************************************************
//
public XIncludingReader(TextReader reader)
: this(new XmlBaseAwareXmlTextReader(reader)) { }
//
//**********************************************************************
/// <summary>
/// Creates new instance of <c>XIncludingReader</c> class with
/// specified URL and <c>TextReader</c> reader.
/// </summary>
/// <param name="reader"><c>TextReader</c>.</param>
/// <param name="url">Source document's URL</param>
//**********************************************************************
//
public XIncludingReader(string url, TextReader reader)
: this(new XmlBaseAwareXmlTextReader(url, reader)) { }
//
//**********************************************************************
/// <summary>
/// Creates new instance of <c>XIncludingReader</c> class with
/// specified <c>TextReader</c> reader and nametable.
/// </summary>
/// <param name="reader"><c>TextReader</c>.</param>
/// <param name="nt">Nametable.</param>
//**********************************************************************
//
public XIncludingReader(TextReader reader, XmlNameTable nt) :
this(new XmlBaseAwareXmlTextReader(reader, nt)) { }
//
//**********************************************************************
/// <summary>
/// Creates new instance of <c>XIncludingReader</c> class with
/// specified URL, <c>TextReader</c> reader and nametable.
/// </summary>
/// <param name="reader"><c>TextReader</c>.</param>
/// <param name="nt">Nametable.</param>
/// <param name="url">Source document's URI</param>
//**********************************************************************
//
public XIncludingReader(string url, TextReader reader, XmlNameTable nt) :
this(new XmlBaseAwareXmlTextReader(url, reader, nt)) { }
//
//**********************************************************************
/// <summary>
/// Creates new instance of <c>XIncludingReader</c> class with
/// specified <c>Stream</c>.
/// </summary>
/// <param name="input"><c>Stream</c>.</param>
//**********************************************************************
//
public XIncludingReader(Stream input)
: this(new XmlBaseAwareXmlTextReader(input)) { }
//
//**********************************************************************
/// <summary>
/// Creates new instance of <c>XIncludingReader</c> class with
/// specified URL and <c>Stream</c>.
/// </summary>
/// <param name="input"><c>Stream</c>.</param>
/// <param name="url">Source document's URL</param>
//**********************************************************************
//
public XIncludingReader(string url, Stream input)
: this(new XmlBaseAwareXmlTextReader(url, input)) { }
//
//**********************************************************************
/// <summary>
/// Creates new instance of <c>XIncludingReader</c> class with
/// specified <c>Stream</c> and nametable.
/// </summary>
/// <param name="input"><c>Stream</c>.</param>
/// <param name="nt">Nametable</param>
//**********************************************************************
//
public XIncludingReader(Stream input, XmlNameTable nt) :
this(new XmlBaseAwareXmlTextReader(input, nt)) { }
//
//**********************************************************************
/// <summary>
/// Creates new instance of <c>XIncludingReader</c> class with
/// specified URL, <c>Stream</c> and nametable.
/// </summary>
/// <param name="input"><c>Stream</c>.</param>
/// <param name="nt">Nametable</param>
/// <param name="url">Source document's URL</param>
//**********************************************************************
//
public XIncludingReader(string url, Stream input, XmlNameTable nt) :
this(new XmlBaseAwareXmlTextReader(url, input, nt)) { }
#endregion
#region XmlReader's overriden members
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.AttributeCount"/></summary>
//**********************************************************************
//
public override int AttributeCount
{
get
{
if (_topLevel)
{
int ac = _reader.AttributeCount;
if (_reader.GetAttribute(_keywords.XmlBase) == null)
ac++;
if (_differentLang)
ac++;
return ac;
}
else
return _reader.AttributeCount;
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.BaseURI"/></summary>
//**********************************************************************
//
public override string BaseURI
{
get { return _reader.BaseURI; }
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.HasValue"/></summary>
//**********************************************************************
//
public override bool HasValue
{
get
{
if (_state == XIncludingReaderState.Default)
return _reader.HasValue;
else
return true;
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.IsDefault"/></summary>
//**********************************************************************
//
public override bool IsDefault
{
get
{
if (_state == XIncludingReaderState.Default)
return _reader.IsDefault;
else
return false;
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.StateName"/></summary>
//**********************************************************************
//
public override string Name
{
get
{
switch (_state)
{
case XIncludingReaderState.ExposingXmlBaseAttr:
return _keywords.XmlBase;
case XIncludingReaderState.ExposingXmlBaseAttrValue:
case XIncludingReaderState.ExposingXmlLangAttrValue:
return String.Empty;
case XIncludingReaderState.ExposingXmlLangAttr:
return _keywords.XmlLang;
default:
return _reader.Name;
}
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.LocalName"/></summary>
//**********************************************************************
//
public override string LocalName
{
get
{
switch (_state)
{
case XIncludingReaderState.ExposingXmlBaseAttr:
return _keywords.Base;
case XIncludingReaderState.ExposingXmlBaseAttrValue:
case XIncludingReaderState.ExposingXmlLangAttrValue:
return String.Empty;
case XIncludingReaderState.ExposingXmlLangAttr:
return _keywords.Lang;
default:
return _reader.LocalName;
}
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.NamespaceURI"/></summary>
//**********************************************************************
//
public override string NamespaceURI
{
get
{
switch (_state)
{
case XIncludingReaderState.ExposingXmlBaseAttr:
case XIncludingReaderState.ExposingXmlLangAttr:
return _keywords.XmlNamespace;
case XIncludingReaderState.ExposingXmlBaseAttrValue:
case XIncludingReaderState.ExposingXmlLangAttrValue:
return String.Empty;
default:
return _reader.NamespaceURI;
}
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.NameTable"/></summary>
//**********************************************************************
//
public override XmlNameTable NameTable
{
get { return _nameTable; }
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.NodeType"/></summary>
//**********************************************************************
//
public override XmlNodeType NodeType
{
get
{
switch (_state)
{
case XIncludingReaderState.ExposingXmlBaseAttr:
case XIncludingReaderState.ExposingXmlLangAttr:
return XmlNodeType.Attribute;
case XIncludingReaderState.ExposingXmlBaseAttrValue:
case XIncludingReaderState.ExposingXmlLangAttrValue:
return XmlNodeType.Text;
default:
return _reader.NodeType;
}
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.Prefix"/></summary>
//**********************************************************************
//
public override string Prefix
{
get
{
switch (_state)
{
case XIncludingReaderState.ExposingXmlBaseAttr:
case XIncludingReaderState.ExposingXmlLangAttr:
return _keywords.Xml;
case XIncludingReaderState.ExposingXmlBaseAttrValue:
case XIncludingReaderState.ExposingXmlLangAttrValue:
return String.Empty;
default:
return _reader.Prefix;
}
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.QuoteChar"/></summary>
//**********************************************************************
//
public override char QuoteChar
{
get
{
switch (_state)
{
case XIncludingReaderState.ExposingXmlBaseAttr:
case XIncludingReaderState.ExposingXmlLangAttr:
return '"';
default:
return _reader.QuoteChar;
}
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.Close"/></summary>
//**********************************************************************
//
public override void Close()
{
if (_reader != null)
_reader.Close();
//Close all readers in the stack
while (_readers.Count > 0)
{
_reader = (XmlReader)_readers.Pop();
if (_reader != null)
_reader.Close();
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.Depth"/></summary>
//**********************************************************************
//
public override int Depth
{
get
{
if (_readers.Count == 0)
return _reader.Depth;
else
//TODO: that might be way ineffective
return ((XmlReader)_readers.Peek()).Depth + _reader.Depth;
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.EOF"/></summary>
//**********************************************************************
//
public override bool EOF
{
get { return _reader.EOF; }
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.GetAttribute(int)"/></summary>
//**********************************************************************
//
public override string GetAttribute(int i)
{
return _reader.GetAttribute(i);
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.GetAttribute(string)"/></summary>
//**********************************************************************
//
public override string GetAttribute(string name)
{
if (_topLevel)
{
if (XIncludeKeywords.Equals(name, _keywords.XmlBase))
return _reader.BaseURI;
else if (XIncludeKeywords.Equals(name, _keywords.XmlLang))
return _reader.XmlLang;
}
return _reader.GetAttribute(name);
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.GetAttribute(string, string)"/></summary>
//**********************************************************************
//
public override string GetAttribute(string name, string namespaceURI)
{
if (_topLevel)
{
if (XIncludeKeywords.Equals(name, _keywords.Base) &&
XIncludeKeywords.Equals(namespaceURI, _keywords.XmlNamespace))
return _reader.BaseURI;
else if (XIncludeKeywords.Equals(name, _keywords.Lang) &&
XIncludeKeywords.Equals(namespaceURI, _keywords.XmlNamespace))
return _reader.XmlLang;
}
return _reader.GetAttribute(name, namespaceURI);
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.IsEmptyElement"/></summary>
//**********************************************************************
//
public override bool IsEmptyElement
{
get { return _reader.IsEmptyElement; }
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.LookupNamespace"/></summary>
//**********************************************************************
//
public override String LookupNamespace(String prefix)
{
return _reader.LookupNamespace(prefix);
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.MoveToAttribute(int)"/></summary>
//**********************************************************************
//
public override void MoveToAttribute(int i)
{
_reader.MoveToAttribute(i);
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.MoveToAttribute(string)"/></summary>
//**********************************************************************
//
public override bool MoveToAttribute(string name)
{
if (_topLevel)
{
if (XIncludeKeywords.Equals(name, _keywords.XmlBase))
{
_state = XIncludingReaderState.ExposingXmlBaseAttr;
return true;
}
else if (XIncludeKeywords.Equals(name, _keywords.XmlLang))
{
_state = XIncludingReaderState.ExposingXmlLangAttr;
return true;
}
}
return _reader.MoveToAttribute(name);
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.MoveToAttribute(string, string)"/></summary>
//**********************************************************************
//
public override bool MoveToAttribute(string name, string ns)
{
if (_topLevel)
{
if (XIncludeKeywords.Equals(name, _keywords.Base) &&
XIncludeKeywords.Equals(ns, _keywords.XmlNamespace))
{
_state = XIncludingReaderState.ExposingXmlBaseAttr;
return true;
}
else if (XIncludeKeywords.Equals(name, _keywords.Lang) &&
XIncludeKeywords.Equals(ns, _keywords.XmlNamespace))
{
_state = XIncludingReaderState.ExposingXmlLangAttr;
return true;
}
}
return _reader.MoveToAttribute(name, ns);
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.MoveToElement"/></summary>
//**********************************************************************
//
public override bool MoveToElement()
{
return _reader.MoveToElement();
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.MoveToFirstAttribute"/></summary>
//**********************************************************************
//
public override bool MoveToFirstAttribute()
{
if (_topLevel)
{
bool res = _reader.MoveToFirstAttribute();
if (res)
{
//it might be xml:base or xml:lang
if (_reader.Name == _keywords.XmlBase ||
_reader.Name == _keywords.XmlLang)
//omit them - we expose virtual ones at the end
return MoveToNextAttribute();
else
return res;
}
else
{
//No attrs? Expose xml:base
_state = XIncludingReaderState.ExposingXmlBaseAttr;
return true;
}
}
else
return _reader.MoveToFirstAttribute();
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.MoveToNextAttribute"/></summary>
//**********************************************************************
//
public override bool MoveToNextAttribute()
{
if (_topLevel)
{
switch (_state)
{
case XIncludingReaderState.ExposingXmlBaseAttr:
case XIncludingReaderState.ExposingXmlBaseAttrValue:
//Exposing xml:base already - switch to xml:lang
if (_differentLang)
{
_state = XIncludingReaderState.ExposingXmlLangAttr;
return true;
}
else
{
//No need for xml:lang, stop
_state = XIncludingReaderState.Default;
return false;
}
case XIncludingReaderState.ExposingXmlLangAttr:
case XIncludingReaderState.ExposingXmlLangAttrValue:
//Exposing xml:lang already - that's a last one
_state = XIncludingReaderState.Default;
return false;
default:
//1+ attrs, default mode
bool res = _reader.MoveToNextAttribute();
if (res)
{
//Still real attributes - it might be xml:base or xml:lang
if (_reader.Name == _keywords.XmlBase ||
_reader.Name == _keywords.XmlLang)
//omit them - we expose virtual ones at the end
return MoveToNextAttribute();
else
return res;
}
else
{
//No more attrs - expose virtual xml:base
_state = XIncludingReaderState.ExposingXmlBaseAttr;
return true;
}
}
}
else
return _reader.MoveToNextAttribute();
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.ReadAttributeValue"/></summary>
//**********************************************************************
//
public override bool ReadAttributeValue()
{
switch (_state)
{
case XIncludingReaderState.ExposingXmlBaseAttr:
_state = XIncludingReaderState.ExposingXmlBaseAttrValue;
return true;
case XIncludingReaderState.ExposingXmlBaseAttrValue:
return false;
case XIncludingReaderState.ExposingXmlLangAttr:
_state = XIncludingReaderState.ExposingXmlLangAttrValue;
return true;
case XIncludingReaderState.ExposingXmlLangAttrValue:
return false;
default:
return _reader.ReadAttributeValue();
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.ReadState"/></summary>
//**********************************************************************
//
public override ReadState ReadState
{
get { return _reader.ReadState; }
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.this[int]"/></summary>
//**********************************************************************
//
public override String this[int i]
{
get { return GetAttribute(i); }
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.this[string]"/></summary>
//**********************************************************************
//
public override string this[string name]
{
get { return GetAttribute(name); }
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.this[string, string]"/></summary>
//**********************************************************************
//
public override string this[string name, string namespaceURI]
{
get { return GetAttribute(name, namespaceURI); }
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.ResolveEntity"/></summary>
//**********************************************************************
//
public override void ResolveEntity()
{
_reader.ResolveEntity();
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.XmlLang"/></summary>
//**********************************************************************
//
public override string XmlLang
{
get { return _reader.XmlLang; }
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.XmlSpace"/></summary>
//**********************************************************************
//
public override XmlSpace XmlSpace
{
get { return _reader.XmlSpace; }
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.Value"/></summary>
//**********************************************************************
//
public override string Value
{
get
{
switch (_state)
{
case XIncludingReaderState.ExposingXmlBaseAttr:
case XIncludingReaderState.ExposingXmlBaseAttrValue:
if (_reader.BaseURI == String.Empty)
{
return String.Empty;
}
if (_relativeBaseUri)
{
Uri baseUri = new Uri(_reader.BaseURI);
return _topBaseUri.MakeRelativeUri(baseUri).ToString();
}
else
return _reader.BaseURI;
case XIncludingReaderState.ExposingXmlLangAttr:
case XIncludingReaderState.ExposingXmlLangAttrValue:
return _reader.XmlLang;
default:
return _reader.Value;
}
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.ReadInnerXml"/></summary>
//**********************************************************************
//
public override string ReadInnerXml()
{
switch (_state)
{
case XIncludingReaderState.ExposingXmlBaseAttr:
return _reader.BaseURI;
case XIncludingReaderState.ExposingXmlBaseAttrValue:
return String.Empty;
case XIncludingReaderState.ExposingXmlLangAttr:
return _reader.XmlLang;
case XIncludingReaderState.ExposingXmlLangAttrValue:
return String.Empty;
default:
if (NodeType == XmlNodeType.Element)
{
int depth = Depth;
if (Read())
{
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
while (Depth > depth)
xw.WriteNode(this, false);
xw.Close();
return sw.ToString();
}
else
return String.Empty;
}
else if (NodeType == XmlNodeType.Attribute)
{
return Value;
}
else
return String.Empty;
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.ReadOuterXml"/></summary>
//**********************************************************************
//
public override string ReadOuterXml()
{
switch (_state)
{
case XIncludingReaderState.ExposingXmlBaseAttr:
return @"xml:base="" + _reader.BaseURI + @""";
case XIncludingReaderState.ExposingXmlBaseAttrValue:
return String.Empty;
case XIncludingReaderState.ExposingXmlLangAttr:
return @"xml:lang="" + _reader.XmlLang + @""";
case XIncludingReaderState.ExposingXmlLangAttrValue:
return String.Empty;
default:
if (NodeType == XmlNodeType.Element)
{
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xw.WriteNode(this, false);
xw.Close();
return sw.ToString();
}
else if (NodeType == XmlNodeType.Attribute)
{
return String.Format("{0=\"{1}\"}", Name, Value);
}
else
return String.Empty;
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.ReadString"/></summary>
//**********************************************************************
//
public override string ReadString()
{
switch (_state)
{
case XIncludingReaderState.ExposingXmlBaseAttr:
return String.Empty;
case XIncludingReaderState.ExposingXmlBaseAttrValue:
return _reader.BaseURI;
case XIncludingReaderState.ExposingXmlLangAttr:
return String.Empty;
case XIncludingReaderState.ExposingXmlLangAttrValue:
return _reader.XmlLang;
default:
return _reader.ReadString();
}
}
//
//**********************************************************************
/// <summary>See <see cref="XmlReader.Read"/></summary>
//**********************************************************************
//
public override bool Read()
{
//Read internal reader
bool baseRead = _reader.Read();
if (baseRead)
{
//If we are including and including reader is at 0 depth -
//we are at a top level included item
_topLevel = (_readers.Count > 0 && _reader.Depth == 0) ? true : false;
//Check if included item has different language
if (_topLevel)
_differentLang = AreDifferentLangs(_reader.XmlLang, ((XmlReader)_readers.Peek()).XmlLang);
if (_topLevel && _reader.NodeType == XmlNodeType.Attribute)
//Attempt to include an attribute or namespace node
throw new AttributeOrNamespaceInIncludeLocationError(SR.AttributeOrNamespaceInIncludeLocationError);
if (_topLevel && ((XmlReader)_readers.Peek()).Depth == 0 &&
_reader.NodeType == XmlNodeType.Element)
{
if (_gotTopIncludedElem)
//Attempt to include more than one element at the top level
throw new MalformedXInclusionResultError(SR.MalformedXInclusionResult);
else
_gotTopIncludedElem = true;
}
switch (_reader.NodeType)
{
case XmlNodeType.XmlDeclaration:
case XmlNodeType.Document:
case XmlNodeType.DocumentType:
case XmlNodeType.DocumentFragment:
//This stuff should not be included into resulting infoset,
//but should be inclused into acquired infoset
return _readers.Count > 0 ? Read() : baseRead;
case XmlNodeType.Element:
//Check for xi:include
if (IsIncludeElement(_reader))
{
//xi:include element found
//Save current reader to possible fallback processing
XmlReader current = _reader;
try
{
return ProcessIncludeElement();
}
catch (FatalException fe)
{
throw fe;
}
catch (Exception e)
{
//Let's be liberal - any exceptions other than fatal one
//should be treated as resource error
//Console.WriteLine("Resource error has been detected: " + e.Message);
//Start fallback processing
if (!current.Equals(_reader))
{
_reader.Close();
_reader = current;
}
_prevFallbackState = _fallbackState;
return ProcessFallback(_reader.Depth, e);
}
//No, it's not xi:include, check it for xi:fallback
}
else if (IsFallbackElement(_reader))
{
//Found xi:fallback not child of xi:include
IXmlLineInfo li = _reader as IXmlLineInfo;
if (li != null && li.HasLineInfo())
{
throw new XIncludeSyntaxError(
SR.GetString("FallbackNotChildOfIncludeLong",
_reader.BaseURI.ToString(), li.LineNumber,
li.LinePosition));
}
else
throw new XIncludeSyntaxError(
SR.GetString("FallbackNotChildOfInclude",
_reader.BaseURI.ToString()));
}
else
{
_gotElement = true;
goto default;
}
case XmlNodeType.EndElement:
//Looking for end of xi:fallback
if (_fallbackState.Fallbacking &&
_reader.Depth == _fallbackState.FallbackDepth &&
IsFallbackElement(_reader))
{
//End of fallback processing
_fallbackState.FallbackProcessed = true;
//Now read other ignored content till </xi:fallback>
return ProcessFallback(_reader.Depth - 1, null);
}
else
goto default;
default:
return baseRead;
}
}
else
{
//No more input - finish possible xi:include processing
if (_topLevel)
_topLevel = false;
if (_readers.Count > 0)
{
_reader.Close();
//Pop previous reader
_reader = (XmlReader)_readers.Pop();
//Successful include - skip xi:include content
if (!_reader.IsEmptyElement)
CheckAndSkipContent();
return Read();
}
else
{
if (!_gotElement)
throw new MalformedXInclusionResultError(SR.MalformedXInclusionResult);
//That's all, folks
return false;
}
}
} // Read()
#endregion
#region Public members
//
//**********************************************************************
/// <summary>
/// See <see cref="XmlTextReader.Normalization"/>.
/// </summary>
//**********************************************************************
//
public bool Normalization
{
get { return _normalization; }
set { _normalization = value; }
}
//
//**********************************************************************
/// <summary>
/// See <see cref="XmlTextReader.WhitespaceHandling"/>.
/// </summary>
//**********************************************************************
//
public WhitespaceHandling WhitespaceHandling
{
get { return _whiteSpaceHandling; }
set { _whiteSpaceHandling = value; }
}
//
//**********************************************************************
/// <summary>
/// XmlResolver to resolve external URI references
/// </summary>
//**********************************************************************
//
public XmlResolver XmlResolver
{
set { _xmlResolver = value; }
}
//
//**********************************************************************
/// <summary>
/// Flag indicating whether to emit <c>xml:base</c> as relative URI.
/// True by default.
/// </summary>
//**********************************************************************
//
public bool MakeRelativeBaseUri
{
get { return _relativeBaseUri; }
set { _relativeBaseUri = value; }
}
//
//**********************************************************************
/// <summary>
/// Flag indicating whether expose text inclusions
/// as CDATA or as Text. By default it's Text.
/// </summary>
//**********************************************************************
//
public bool ExposeTextInclusionsAsCDATA
{
get { return _exposeTextAsCDATA; }
set { _exposeTextAsCDATA = value; }
}
#endregion
#region Private methods
//Dummy validation even handler
private static void ValidationCallback(object sender, ValidationEventArgs args)
{
//do nothing
}
//
//**********************************************************************
/// <summary>
/// Checks if given reader is positioned on a xi:include element.
/// </summary>
//**********************************************************************
//
private bool IsIncludeElement(XmlReader r)
{
if (
(
XIncludeKeywords.Equals(_reader.NamespaceURI, _keywords.XIncludeNamespace) ||
XIncludeKeywords.Equals(_reader.NamespaceURI, _keywords.OldXIncludeNamespace)
) &&
XIncludeKeywords.Equals(_reader.LocalName, _keywords.Include))
return true;
else
return false;
}
//
//**********************************************************************
/// <summary>
/// /// Checks if given reader is positioned on a xi:fallback element.
/// </summary>
/// <param name="r"></param>
/// <returns></returns>
//**********************************************************************
//
private bool IsFallbackElement(XmlReader r)
{
if (
(
XIncludeKeywords.Equals(_reader.NamespaceURI, _keywords.XIncludeNamespace) ||
XIncludeKeywords.Equals(_reader.NamespaceURI, _keywords.OldXIncludeNamespace)
) &&
XIncludeKeywords.Equals(_reader.LocalName, _keywords.Fallback))
return true;
else
return false;
}
//
//**********************************************************************
/// <summary>
/// Fetches resource by URI.
/// </summary>
//**********************************************************************
//
internal static Stream GetResource(string includeLocation,
string accept, string acceptLanguage, out WebResponse response)
{
WebRequest wReq;
try
{
wReq = WebRequest.Create(includeLocation);
}
catch (NotSupportedException nse)
{
throw new ResourceException(SR.GetString("URISchemaNotSupported", includeLocation), nse);
}
catch (SecurityException se)
{
throw new ResourceException(SR.GetString("SecurityException", includeLocation), se);
}
//Add accept headers if this is HTTP request
HttpWebRequest httpReq = wReq as HttpWebRequest;
if (httpReq != null)
{
if (accept != null)
{
TextUtils.CheckAcceptValue(accept);
if (httpReq.Accept == null || httpReq.Accept == String.Empty)
httpReq.Accept = accept;
else
httpReq.Accept += "," + accept;
}
if (acceptLanguage != null)
{
if (httpReq.Headers["Accept-Language"] == null)
httpReq.Headers.Add("Accept-Language", acceptLanguage);
else
httpReq.Headers["Accept-Language"] += "," + acceptLanguage;
}
}
try
{
response = wReq.GetResponse();
}
catch (WebException we)
{
throw new ResourceException(SR.GetString("ResourceError", includeLocation), we);
}
return response.GetResponseStream();
}
//
//**********************************************************************
/// <summary>
/// Processes xi:include element.
/// </summary>
//**********************************************************************
//
private bool ProcessIncludeElement()
{
string href = _reader.GetAttribute(_keywords.Href);
string xpointer = _reader.GetAttribute(_keywords.Xpointer);
string parse = _reader.GetAttribute(_keywords.Parse);
if (href == null || href == String.Empty)
{
//Intra-document inclusion
if (parse == null || parse.Equals(_keywords.Xml))
{
if (xpointer == null)
{
//Both href and xpointer attributes are absent in xml mode,
// => critical error
IXmlLineInfo li = _reader as IXmlLineInfo;
if (li != null && li.HasLineInfo())
{
throw new XIncludeSyntaxError(
SR.GetString("MissingHrefAndXpointerExceptionLong",
_reader.BaseURI.ToString(),
li.LineNumber, li.LinePosition));
}
else
throw new XIncludeSyntaxError(
SR.GetString("MissingHrefAndXpointerException",
_reader.BaseURI.ToString()));
}
//No support for intra-document refs
throw new InvalidOperationException(SR.IntradocumentReferencesNotSupported);
}
else if (parse.Equals(_keywords.Text))
{
//No support for intra-document refs
throw new InvalidOperationException(SR.IntradocumentReferencesNotSupported);
}
}
else
{
//Inter-document inclusion
if (parse == null || parse.Equals(_keywords.Xml))
return ProcessInterDocXMLInclusion(href, xpointer);
else if (parse.Equals(_keywords.Text))
return ProcessInterDocTextInclusion(href);
}
//Unknown "parse" attribute value, critical error
IXmlLineInfo li2 = _reader as IXmlLineInfo;
if (li2 != null && li2.HasLineInfo())
{
throw new XIncludeSyntaxError(
SR.GetString("UnknownParseAttrValueLong",
parse,
_reader.BaseURI.ToString(),
li2.LineNumber, li2.LinePosition));
}
else
throw new XIncludeSyntaxError(
SR.GetString("UnknownParseAttrValue", parse));
}
//
//**********************************************************************
/// <summary>
/// Resolves include location.
/// </summary>
/// <param name="href">href value</param>
/// <returns>Include location.</returns>
//**********************************************************************
//
private Uri ResolveHref(string href)
{
Uri includeLocation;
try
{
Uri baseURI = _reader.BaseURI == "" ? _topBaseUri : new Uri(_reader.BaseURI);
if (_xmlResolver == null)
includeLocation = new Uri(baseURI, href);
else
includeLocation = _xmlResolver.ResolveUri(baseURI, href);
}
catch (UriFormatException ufe)
{
throw new ResourceException(SR.GetString("InvalidURI", href), ufe);
}
catch (Exception e)
{
throw new ResourceException(SR.GetString("UnresolvableURI", href), e);
}
return includeLocation;
}
//
//**********************************************************************
/// <summary>
/// Skips content of an element using directly current reader's methods.
/// </summary>
//**********************************************************************
//
private void SkipContent()
{
if (!_reader.IsEmptyElement)
{
int depth = _reader.Depth;
while (_reader.Read() && depth < _reader.Depth) ;
}
}
//
//**********************************************************************
/// <summary>
/// Fallback processing.
/// </summary>
/// <param name="depth"><c>xi:include</c> depth level.</param>
/// <param name="e">Resource error, which caused this processing.</param>
/// <remarks>When inluding fails due to any resource error, <c>xi:inlcude</c>
/// element content is processed as follows: each child <c>xi:include</c> -
/// fatal error, more than one child <c>xi:fallback</c> - fatal error. No
/// <c>xi:fallback</c> - the resource error results in a fatal error.
/// Content of first <c>xi:fallback</c> element is included in a usual way.</remarks>
//**********************************************************************
//
private bool ProcessFallback(int depth, Exception e)
{
//Read to the xi:include end tag
while (_reader.Read() && depth < _reader.Depth)
{
switch (_reader.NodeType)
{
case XmlNodeType.Element:
if (IsIncludeElement(_reader))
{
//xi:include child of xi:include - fatal error
IXmlLineInfo li = _reader as IXmlLineInfo;
if (li != null && li.HasLineInfo())
{
throw new XIncludeSyntaxError(SR.GetString("IncludeChildOfIncludeLong",
BaseURI.ToString(),
li.LineNumber, li.LinePosition));
}
else
throw new XIncludeSyntaxError(SR.GetString("IncludeChildOfInclude",
BaseURI.ToString()));
}
if (IsFallbackElement(_reader))
{
//Found xi:fallback
if (_fallbackState.FallbackProcessed)
{
IXmlLineInfo li = _reader as IXmlLineInfo;
if (li != null && li.HasLineInfo())
{
//Two xi:fallback
throw new XIncludeSyntaxError(SR.GetString("TwoFallbacksLong",
BaseURI.ToString(),
li.LineNumber, li.LinePosition));
}
else
throw new XIncludeSyntaxError(SR.GetString("TwoFallbacks", BaseURI.ToString()));
}
if (_reader.IsEmptyElement)
{
//Empty xi:fallback - nothing to include
_fallbackState.FallbackProcessed = true;
break;
}
_fallbackState.Fallbacking = true;
_fallbackState.FallbackDepth = _reader.Depth;
return Read();
}
else
//Ignore anything else along with its content
SkipContent();
break;
default:
break;
}
}
//xi:include content is read
if (!_fallbackState.FallbackProcessed)
//No xi:fallback, fatal error
throw new FatalResourceException(e);
else
{
//End of xi:include content processing, reset and go forth
_fallbackState = _prevFallbackState;
return Read();
}
}
//
//**********************************************************************
/// <summary>
/// Skips xi:include element's content, while checking XInclude syntax (no
/// xi:include, no more than one xi:fallback).
/// </summary>
//**********************************************************************
//
private void CheckAndSkipContent()
{
int depth = _reader.Depth;
bool fallbackElem = false;
while (_reader.Read() && depth < _reader.Depth)
{
switch (_reader.NodeType)
{
case XmlNodeType.Element:
if (IsIncludeElement(_reader))
{
//xi:include child of xi:include - fatal error
IXmlLineInfo li = _reader as IXmlLineInfo;
if (li != null && li.HasLineInfo())
{
throw new XIncludeSyntaxError(SR.GetString("IncludeChildOfIncludeLong",
_reader.BaseURI.ToString(),
li.LineNumber, li.LinePosition));
}
else
throw new XIncludeSyntaxError(SR.GetString("IncludeChildOfInclude",
_reader.BaseURI.ToString()));
}
else if (IsFallbackElement(_reader))
{
//Found xi:fallback
if (fallbackElem)
{
//More than one xi:fallback
IXmlLineInfo li = _reader as IXmlLineInfo;
if (li != null && li.HasLineInfo())
{
throw new XIncludeSyntaxError(SR.GetString("TwoFallbacksLong",
_reader.BaseURI.ToString(),
li.LineNumber, li.LinePosition));
}
else
throw new XIncludeSyntaxError(SR.GetString("TwoFallbacks", _reader.BaseURI.ToString()));
}
else
{
fallbackElem = true;
SkipContent();
}
}
//Check anything else in XInclude namespace
else if (XIncludeKeywords.Equals(_reader.NamespaceURI, _keywords.XIncludeNamespace))
{
throw new XIncludeSyntaxError(SR.GetString("UnknownXIncludeElement", _reader.Name));
}
else
//Ignore everything else
SkipContent();
break;
default:
break;
}
}
} // CheckAndSkipContent()
//
//**********************************************************************
/// <summary>
/// Throws CircularInclusionException.
/// </summary>
//**********************************************************************
//
private void ThrowCircularInclusionError(XmlReader reader, Uri url)
{
IXmlLineInfo li = reader as IXmlLineInfo;
if (li != null && li.HasLineInfo())
{
throw new CircularInclusionException(url,
BaseURI.ToString(),
li.LineNumber, li.LinePosition);
}
else
throw new CircularInclusionException(url);
}
//
//**********************************************************************
/// <summary>
/// Compares two languages as per IETF RFC 3066.
/// </summary>
//**********************************************************************
//
private bool AreDifferentLangs(string lang1, string lang2)
{
return lang1.ToLower() != lang2.ToLower();
}
//
//**********************************************************************
/// <summary>
/// Creates acquired infoset.
/// </summary>
//**********************************************************************
//
private string CreateAcquiredInfoset(Uri includeLocation)
{
if (_cache == null)
_cache = new Dictionary<string, WeakReference>();
WeakReference wr;
if (_cache.TryGetValue(includeLocation.AbsoluteUri, out wr) && wr.IsAlive)
{
return (string)wr.Target;
}
else
{
//Not cached or GCollected
WebResponse wRes;
Stream stream = GetResource(includeLocation.AbsoluteUri,
_reader.GetAttribute(_keywords.Accept),
_reader.GetAttribute(_keywords.AcceptLanguage), out wRes);
XIncludingReader xir = new XIncludingReader(wRes.ResponseUri.AbsoluteUri, stream, _nameTable);
xir.Normalization = _normalization;
xir.WhitespaceHandling = _whiteSpaceHandling;
StringWriter sw = new StringWriter();
XmlTextWriter w = new XmlTextWriter(sw);
try
{
while (xir.Read())
w.WriteNode(xir, false);
}
finally
{
if (xir != null)
xir.Close();
if (w != null)
w.Close();
}
string content = sw.ToString();
lock (_cache)
{
if (!_cache.ContainsKey(includeLocation.AbsoluteUri))
_cache.Add(includeLocation.AbsoluteUri, new WeakReference(content));
}
return content;
}
}
//
//**********************************************************************
/// <summary>
/// Creates acquired infoset.
/// </summary>
/// <param name="reader">Source reader</param>
/// <param name="includeLocation">Base URI</param>
//**********************************************************************
//
private string CreateAcquiredInfoset(Uri includeLocation, TextReader reader)
{
return CreateAcquiredInfoset(
new XmlBaseAwareXmlTextReader(includeLocation.AbsoluteUri, reader, _nameTable));
}
//
//**********************************************************************
/// <summary>
/// Creates acquired infoset.
/// </summary>
/// <param name="reader">Source reader</param>
//**********************************************************************
//
private string CreateAcquiredInfoset(XmlReader reader)
{
//TODO: Try to stream out this stuff
XIncludingReader xir = new XIncludingReader(reader);
xir.XmlResolver = this._xmlResolver;
StringWriter sw = new StringWriter();
XmlTextWriter w = new XmlTextWriter(sw);
try
{
while (xir.Read())
w.WriteNode(xir, false);
}
finally
{
if (xir != null)
xir.Close();
if (w != null)
w.Close();
}
return sw.ToString();
}
//
//**********************************************************************
/// <summary>
/// Processes inter-document inclusion (xml mode).
/// </summary>
/// <param name="href">'href' attr value</param>
/// <param name="xpointer">'xpointer attr value'</param>
//**********************************************************************
//
private bool ProcessInterDocXMLInclusion(string href, string xpointer)
{
//Include document as XML
Uri includeLocation = ResolveHref(href);
if (includeLocation.Fragment != String.Empty)
throw new XIncludeSyntaxError(SR.FragmentIDInHref);
CheckLoops(includeLocation, xpointer);
if (_xmlResolver == null)
{
//No custom resolver
if (xpointer != null)
{
//Push current reader to the stack
_readers.Push(_reader);
//XPointers should be resolved against the acquired infoset,
//not the source infoset
_reader = new XPointerReader(includeLocation.AbsoluteUri,
CreateAcquiredInfoset(includeLocation),
xpointer);
}
else
{
WebResponse wRes;
Stream stream = GetResource(includeLocation.AbsoluteUri,
_reader.GetAttribute(_keywords.Accept),
_reader.GetAttribute(_keywords.AcceptLanguage), out wRes);
//Push current reader to the stack
_readers.Push(_reader);
XmlTextReader r = new XmlBaseAwareXmlTextReader(wRes.ResponseUri.AbsoluteUri, stream, _nameTable);
r.Normalization = _normalization;
r.WhitespaceHandling = _whiteSpaceHandling;
_reader = r;
}
return Read();
}
else
{
//Custom resolver provided, let's ask him
object resource;
try
{
resource = _xmlResolver.GetEntity(includeLocation, null, null);
}
catch (Exception e)
{
throw new ResourceException(SR.CustomXmlResolverError, e);
}
if (resource == null)
throw new ResourceException(SR.CustomXmlResolverReturnedNull);
//Push current reader to the stack
_readers.Push(_reader);
//Ok, we accept Stream, TextReader and XmlReader only
if (resource is Stream)
resource = new StreamReader((Stream)resource);
if (xpointer != null)
{
if (resource is TextReader)
{
//XPointers should be resolved against the acquired infoset,
//not the source infoset
_reader = new XPointerReader(includeLocation.AbsoluteUri,
CreateAcquiredInfoset(includeLocation, (TextReader)resource),
xpointer);
}
else if (resource is XmlReader)
{
XmlReader r = (XmlReader)resource;
_reader = new XPointerReader(r.BaseURI,
CreateAcquiredInfoset(r), xpointer);
}
else
{
//Unsupported type
throw new ResourceException(SR.GetString(
"CustomXmlResolverReturnedUnsupportedType",
resource.GetType().ToString()));
}
}
else
{
//No XPointer
if (resource is TextReader)
_reader = new XmlBaseAwareXmlTextReader(includeLocation.AbsoluteUri, (TextReader)resource, _nameTable);
else if (resource is XmlReader)
_reader = (XmlReader)resource;
else
{
//Unsupported type
throw new ResourceException(SR.GetString(
"CustomXmlResolverReturnedUnsupportedType",
resource.GetType().ToString()));
}
}
return Read();
}
}
//
//**********************************************************************
/// <summary>
/// Process inter-document inclusion as text.
/// </summary>
/// <param name="href">'href' attr value</param>
//**********************************************************************
//
private bool ProcessInterDocTextInclusion(string href)
{
//Include document as text
string encoding = GetAttribute(_keywords.Encoding);
Uri includeLocation = ResolveHref(href);
//No need to check loops when including as text
//Push current reader to the stack
_readers.Push(_reader);
_reader = new TextIncludingReader(includeLocation, encoding,
_reader.GetAttribute(_keywords.Accept),
_reader.GetAttribute(_keywords.AcceptLanguage),
_exposeTextAsCDATA);
return Read();
}
//
//**********************************************************************
/// <summary>
/// Checks for inclusion loops.
/// </summary>
//**********************************************************************
//
private void CheckLoops(Uri url, string xpointer)
{
//Check circular inclusion
Uri baseUri = _reader.BaseURI == "" ? _topBaseUri : new Uri(_reader.BaseURI);
if (baseUri.Equals(url))
ThrowCircularInclusionError(_reader, url);
foreach (XmlReader r in _readers)
{
baseUri = r.BaseURI == "" ? _topBaseUri : new Uri(r.BaseURI);
if (baseUri.Equals(url))
ThrowCircularInclusionError(_reader, url);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ICSharpCode.WpfDesign.XamlDom
{
public static class XamlFormatter
{
public static char IndentChar = ' ';
public static int Indenation = 2;
public static int LengthBeforeNewLine = 60;
static StringBuilder sb;
static int currentColumn;
static int nextColumn;
static int lineNumber;
public static string Format(string xaml)
{
Dictionary<XamlElementLineInfo, XamlElementLineInfo> dict;
return Format(xaml, out dict);
}
public static string Format(string xaml, out Dictionary<XamlElementLineInfo, XamlElementLineInfo> mappingOldNewLineInfo)
{
sb = new StringBuilder();
lineNumber = 1;
mappingOldNewLineInfo = new Dictionary<XamlElementLineInfo, XamlElementLineInfo>();
currentColumn = 0;
nextColumn = 0;
try {
var doc = XDocument.Parse(xaml, LoadOptions.SetLineInfo);
WalkContainer(doc, mappingOldNewLineInfo);
return sb.ToString();
}
catch {
return xaml;
}
}
static void WalkContainer(XContainer node, Dictionary<XamlElementLineInfo, XamlElementLineInfo> mappingOldNewLineInfo)
{
foreach (var c in node.Nodes()) {
if (c is XElement) {
WalkElement(c as XElement, mappingOldNewLineInfo);
} else {
NewLine();
Append(c.ToString().Trim());
}
}
}
static void WalkElement(XElement e, Dictionary<XamlElementLineInfo, XamlElementLineInfo> mappingOldNewLineInfo)
{
var info = (IXmlLineInfo)e;
var newLineInfo = new XamlElementLineInfo(lineNumber, currentColumn);
mappingOldNewLineInfo.Add(new XamlElementLineInfo(info.LineNumber, info.LinePosition), newLineInfo);
Console.WriteLine(info.LinePosition);
NewLine();
string prefix1 = e.GetPrefixOfNamespace(e.Name.Namespace);
string name1 = prefix1 == null ? e.Name.LocalName : prefix1 + ":" + e.Name.LocalName;
newLineInfo.Position = sb.Length;
Append("<" + name1);
List<AttributeString> list = new List<AttributeString>();
int length = name1.Length;
foreach (var a in e.Attributes()) {
string prefix2 = e.GetPrefixOfNamespace(a.Name.Namespace);
var g = new AttributeString() { Name = a.Name, Prefix = prefix2, Value = a.Value };
list.Add(g);
length += g.FinalString.Length;
}
list.Sort(AttributeComparrer.Instance);
if (length > LengthBeforeNewLine) {
nextColumn = currentColumn + 1;
for (int i = 0; i < list.Count; i++) {
if (i > 0) {
NewLine();
}
else {
Append(" ");
}
Append(list[i].FinalString);
}
nextColumn -= name1.Length + 2;
}
else {
foreach (var a in list) {
Append(" " + a.FinalString);
}
}
if (e.Nodes().Count() > 0) {
Append(">");
nextColumn += Indenation;
WalkContainer(e, mappingOldNewLineInfo);
nextColumn -= Indenation;
NewLine();
Append("</" + name1 + ">");
}
else {
Append(" />");
}
newLineInfo.Length = sb.Length - newLineInfo.Position;
}
static void NewLine()
{
if (sb.Length > 0)
{
lineNumber++;
sb.AppendLine();
sb.Append(new string(' ', nextColumn));
currentColumn = nextColumn;
}
}
static void Append(string s)
{
sb.Append(s);
currentColumn += s.Length;
}
enum AttributeLayout
{
X,
XmlnsMicrosoft,
Xmlns,
XmlnsWithClr,
SpecialOrder,
ByName,
Attached,
WithPrefix
}
class AttributeString
{
public XName Name;
public string Prefix;
public string Value;
public string LocalName {
get { return Name.LocalName; }
}
public string FinalName {
get {
return Prefix == null ? Name.LocalName : Prefix + ":" + Name.LocalName;
}
}
public string FinalString {
get {
return FinalName + "=\"" + Value + "\"";
}
}
public AttributeLayout GetAttributeLayout()
{
if (Prefix == "xmlns" || LocalName == "xmlns") {
if (Value.StartsWith("http://schemas.microsoft.com")) return AttributeLayout.XmlnsMicrosoft;
if (Value.StartsWith("clr")) return AttributeLayout.XmlnsWithClr;
return AttributeLayout.Xmlns;
}
if (Prefix == "x") return AttributeLayout.X;
if (Prefix != null) return AttributeLayout.WithPrefix;
if (LocalName.Contains(".")) return AttributeLayout.Attached;
if (AttributeComparrer.SpecialOrder.Contains(LocalName)) return AttributeLayout.SpecialOrder;
return AttributeLayout.ByName;
}
}
class AttributeComparrer : IComparer<AttributeString>
{
public static AttributeComparrer Instance = new AttributeComparrer();
public int Compare(AttributeString a1, AttributeString a2)
{
var y1 = a1.GetAttributeLayout();
var y2 = a2.GetAttributeLayout();
if (y1 == y2) {
if (y1 == AttributeLayout.SpecialOrder) {
return
Array.IndexOf(SpecialOrder, a1.LocalName).CompareTo(
Array.IndexOf(SpecialOrder, a2.LocalName));
}
return a1.FinalName.CompareTo(a2.FinalName);
}
return y1.CompareTo(y2);
}
public static string[] SpecialOrder = new string[] {
"Name",
"Content",
"Command",
"Executed",
"CanExecute",
"Width",
"Height",
"Margin",
"HorizontalAlignment",
"VerticalAlignment",
"HorizontalContentAlignment",
"VerticalContentAlignment",
"StartPoint",
"EndPoint",
"Offset",
"Color"
};
}
}
}
| |
using System.Collections.Concurrent;
using Exceptionless.Core.Extensions;
using Exceptionless.Core.Plugins.Formatting;
using Exceptionless.Core.Queues.Models;
using Exceptionless.Core.Models;
using Exceptionless.DateTimeExtensions;
using Foundatio.Metrics;
using Foundatio.Queues;
using Foundatio.Utility;
using HandlebarsDotNet;
using Microsoft.Extensions.Logging;
namespace Exceptionless.Core.Mail;
public class Mailer : IMailer {
private readonly ConcurrentDictionary<string, HandlebarsTemplate<object, object>> _cachedTemplates = new ConcurrentDictionary<string, HandlebarsTemplate<object, object>>();
private readonly IQueue<MailMessage> _queue;
private readonly FormattingPluginManager _pluginManager;
private readonly AppOptions _appOptions;
private readonly IMetricsClient _metrics;
private readonly ILogger _logger;
public Mailer(IQueue<MailMessage> queue, FormattingPluginManager pluginManager, AppOptions appOptions, IMetricsClient metrics, ILogger<Mailer> logger) {
_queue = queue;
_pluginManager = pluginManager;
_appOptions = appOptions;
_metrics = metrics;
_logger = logger;
}
public async Task<bool> SendEventNoticeAsync(User user, PersistentEvent ev, Project project, bool isNew, bool isRegression, int totalOccurrences) {
bool isCritical = ev.IsCritical();
var result = _pluginManager.GetEventNotificationMailMessageData(ev, isCritical, isNew, isRegression);
if (result == null || result.Data.Count == 0) {
_logger.LogWarning("Unable to create event notification mail message for event \"{user}\". User: \"{EmailAddress}\"", ev.Id, user.EmailAddress);
return false;
}
if (String.IsNullOrEmpty(result.Subject))
result.Subject = ev.Message ?? ev.Source ?? "(Global)";
var messageData = new Dictionary<string, object> {
{ "Subject", result.Subject },
{ "BaseUrl", _appOptions.BaseURL },
{ "ProjectName", project.Name },
{ "ProjectId", project.Id },
{ "StackId", ev.StackId },
{ "EventId", ev.Id },
{ "IsCritical", isCritical },
{ "IsNew", isNew },
{ "IsRegression", isRegression },
{ "TotalOccurrences", totalOccurrences },
{ "Fields", result.Data }
};
AddDefaultFields(ev, result.Data);
AddUserInfo(ev, messageData);
const string template = "event-notice";
await QueueMessageAsync(new MailMessage {
To = user.EmailAddress,
Subject = $"[{project.Name}] {result.Subject}",
Body = RenderTemplate(template, messageData)
}, template).AnyContext();
return true;
}
private void AddUserInfo(PersistentEvent ev, Dictionary<string, object> data) {
var ud = ev.GetUserDescription();
var ui = ev.GetUserIdentity();
if (!String.IsNullOrEmpty(ud?.Description))
data["UserDescription"] = ud.Description;
if (!String.IsNullOrEmpty(ud?.EmailAddress))
data["UserEmail"] = ud.EmailAddress;
string displayName = null;
if (!String.IsNullOrEmpty(ui?.Identity))
data["UserIdentity"] = displayName = ui.Identity;
if (!String.IsNullOrEmpty(ui?.Name))
data["UserName"] = displayName = ui.Name;
if (!String.IsNullOrEmpty(displayName) && !String.IsNullOrEmpty(ud?.EmailAddress))
displayName = $"{displayName} ({ud.EmailAddress})";
else if (!String.IsNullOrEmpty(ui?.Identity) && !String.IsNullOrEmpty(ui.Name))
displayName = $"{ui.Name} ({ui.Identity})";
if (!String.IsNullOrEmpty(displayName))
data["UserDisplayName"] = displayName;
data["HasUserInfo"] = ud != null || ui != null;
}
private void AddDefaultFields(PersistentEvent ev, Dictionary<string, object> data) {
if (ev.Tags.Count > 0)
data["Tags"] = String.Join(", ", ev.Tags);
if (ev.Value.GetValueOrDefault() != 0)
data["Value"] = ev.Value;
string version = ev.GetVersion();
if (!String.IsNullOrEmpty(version))
data["Version"] = version;
}
public Task SendOrganizationAddedAsync(User sender, Organization organization, User user) {
const string template = "organization-added";
string subject = $"{sender.FullName} added you to the organization \"{organization.Name}\" on Exceptionless";
var data = new Dictionary<string, object> {
{ "Subject", subject },
{ "BaseUrl", _appOptions.BaseURL },
{ "OrganizationId", organization.Id },
{ "OrganizationName", organization.Name }
};
return QueueMessageAsync(new MailMessage {
To = user.EmailAddress,
Subject = subject,
Body = RenderTemplate(template, data)
}, template);
}
public Task SendOrganizationInviteAsync(User sender, Organization organization, Invite invite) {
const string template = "organization-invited";
string subject = $"{sender.FullName} invited you to join the organization \"{organization.Name}\" on Exceptionless";
var data = new Dictionary<string, object> {
{ "Subject", subject },
{ "BaseUrl", _appOptions.BaseURL },
{ "InviteToken", invite.Token }
};
var body = RenderTemplate(template, data);
return QueueMessageAsync(new MailMessage {
To = invite.EmailAddress,
Subject = subject,
Body = body
}, template);
}
public Task SendOrganizationNoticeAsync(User user, Organization organization, bool isOverMonthlyLimit, bool isOverHourlyLimit) {
const string template = "organization-notice";
string subject = isOverMonthlyLimit
? $"[{organization.Name}] Monthly plan limit exceeded."
: $"[{organization.Name}] Events are currently being throttled.";
var data = new Dictionary<string, object> {
{ "Subject", subject },
{ "BaseUrl", _appOptions.BaseURL },
{ "OrganizationId", organization.Id },
{ "OrganizationName", organization.Name },
{ "IsOverMonthlyLimit", isOverMonthlyLimit },
{ "IsOverHourlyLimit", isOverHourlyLimit },
{ "ThrottledUntil", SystemClock.UtcNow.StartOfHour().AddHours(1).ToShortTimeString() }
};
return QueueMessageAsync(new MailMessage {
To = user.EmailAddress,
Subject = subject,
Body = RenderTemplate(template, data)
}, template);
}
public Task SendOrganizationPaymentFailedAsync(User owner, Organization organization) {
const string template = "organization-payment-failed";
string subject = $"[{organization.Name}] Payment failed! Update billing information to avoid service interruption!";
var data = new Dictionary<string, object> {
{ "Subject", subject },
{ "BaseUrl", _appOptions.BaseURL },
{ "OrganizationId", organization.Id },
{ "OrganizationName", organization.Name }
};
return QueueMessageAsync(new MailMessage {
To = owner.EmailAddress,
Subject = subject,
Body = RenderTemplate(template, data)
}, template);
}
public Task SendProjectDailySummaryAsync(User user, Project project, IEnumerable<Stack> mostFrequent, IEnumerable<Stack> newest, DateTime startDate, bool hasSubmittedEvents, double count, double uniqueCount, double newCount, double fixedCount, int blockedCount, int tooBigCount, bool isFreePlan) {
const string template = "project-daily-summary";
string subject = $"[{project.Name}] Summary for {startDate.ToLongDateString()}";
var data = new Dictionary<string, object> {
{ "Subject", subject },
{ "BaseUrl", _appOptions.BaseURL },
{ "OrganizationId", project.OrganizationId },
{ "ProjectId", project.Id },
{ "ProjectName", project.Name },
{ "MostFrequent", GetStackTemplateData(mostFrequent) },
{ "Newest", GetStackTemplateData(newest) },
{ "StartDate", startDate.ToLongDateString() },
{ "HasSubmittedEvents", hasSubmittedEvents },
{ "Count", count },
{ "Unique", uniqueCount },
{ "New", newCount },
{ "Fixed", fixedCount },
{ "Blocked", blockedCount },
{ "TooBig", tooBigCount },
{ "IsFreePlan", isFreePlan }
};
return QueueMessageAsync(new MailMessage {
To = user.EmailAddress,
Subject = subject,
Body = RenderTemplate(template, data)
}, template);
}
private static IEnumerable<object> GetStackTemplateData(IEnumerable<Stack> stacks) {
return stacks?.Select(s => new {
StackId = s.Id,
Title = s.Title.Truncate(50),
TypeName = s.GetTypeName().Truncate(50),
s.Status,
});
}
public Task SendUserEmailVerifyAsync(User user) {
if (String.IsNullOrEmpty(user?.VerifyEmailAddressToken))
return Task.CompletedTask;
const string template = "user-email-verify";
const string subject = "Exceptionless Account Confirmation";
var data = new Dictionary<string, object> {
{ "Subject", subject },
{ "BaseUrl", _appOptions.BaseURL },
{ "UserFullName", user.FullName },
{ "UserVerifyEmailAddressToken", user.VerifyEmailAddressToken }
};
return QueueMessageAsync(new MailMessage {
To = user.EmailAddress,
Subject = subject,
Body = RenderTemplate(template, data)
}, template);
}
public Task SendUserPasswordResetAsync(User user) {
if (String.IsNullOrEmpty(user?.PasswordResetToken))
return Task.CompletedTask;
const string template = "user-password-reset";
const string subject = "Exceptionless Password Reset";
var data = new Dictionary<string, object> {
{ "Subject", subject },
{ "BaseUrl", _appOptions.BaseURL },
{ "UserFullName", user.FullName },
{ "UserPasswordResetToken", user.PasswordResetToken }
};
return QueueMessageAsync(new MailMessage {
To = user.EmailAddress,
Subject = subject,
Body = RenderTemplate(template, data)
}, template);
}
private string RenderTemplate(string name, IDictionary<string, object> data) {
var template = GetCompiledTemplate(name);
var result = template(data);
return result?.ToString();
}
private HandlebarsTemplate<object, object> GetCompiledTemplate(string name) {
return _cachedTemplates.GetOrAdd(name, templateName => {
var assembly = typeof(Mailer).Assembly;
string resourceName = $"Exceptionless.Core.Mail.Templates.{templateName}.html";
using (var stream = assembly.GetManifestResourceStream(resourceName)) {
using (var reader = new StreamReader(stream)) {
string template = reader.ReadToEnd();
var compiledTemplateFunc = Handlebars.Compile(template);
return compiledTemplateFunc;
}
}
});
}
private Task QueueMessageAsync(MailMessage message, string metricsName) {
CleanAddresses(message);
_metrics.Counter($"mailer.{metricsName}");
return _queue.EnqueueAsync(message);
}
private void CleanAddresses(MailMessage message) {
if (_appOptions.AppMode == AppMode.Production)
return;
string address = message.To.ToLowerInvariant();
if (_appOptions.EmailOptions.AllowedOutboundAddresses.Any(address.Contains))
return;
message.Subject = $"[{message.To}] {message.Subject}".StripInvisible();
message.To = _appOptions.EmailOptions.TestEmailAddress;
}
}
| |
namespace Ioke.Math {
public class MPN {
/** Add x[0:size-1] and y, and write the size least
* significant words of the result to dest.
* Return carry, either 0 or 1.
* All values are unsigned.
* This is basically the same as gmp's mpn_add_1. */
public static int add_1 (int[] dest, int[] x, int size, int y)
{
long carry = (long) y & 0xffffffffL;
for (int i = 0; i < size; i++)
{
carry += ((long) x[i] & 0xffffffffL);
dest[i] = (int) carry;
carry >>= 32;
}
return (int) carry;
}
/** Add x[0:len-1] and y[0:len-1] and write the len least
* significant words of the result to dest[0:len-1].
* All words are treated as unsigned.
* @return the carry, either 0 or 1
* This function is basically the same as gmp's mpn_add_n.
*/
public static int add_n (int[] dest, int[] x, int[] y, int len)
{
long carry = 0;
for (int i = 0; i < len; i++)
{
carry += ((long) x[i] & 0xffffffffL)
+ ((long) y[i] & 0xffffffffL);
dest[i] = (int) carry;
carry = (long)(((ulong)carry) >> 32);
}
return (int) carry;
}
/** Subtract Y[0:size-1] from X[0:size-1], and write
* the size least significant words of the result to dest[0:size-1].
* Return borrow, either 0 or 1.
* This is basically the same as gmp's mpn_sub_n function.
*/
public static int sub_n (int[] dest, int[] X, int[] Y, int size)
{
int cy = 0;
for (int i = 0; i < size; i++)
{
int y = Y[i];
int x = X[i];
y += cy; /* add previous carry to subtrahend */
// Invert the high-order bit, because: (unsigned) X > (unsigned) Y
// iff: (int) (X^0x80000000) > (int) (Y^0x80000000).
cy = (y^0x80000000) < (cy^0x80000000) ? 1 : 0;
y = x - y;
cy += (y^0x80000000) > (x ^ 0x80000000) ? 1 : 0;
dest[i] = y;
}
return cy;
}
/** Multiply x[0:len-1] by y, and write the len least
* significant words of the product to dest[0:len-1].
* Return the most significant word of the product.
* All values are treated as if they were unsigned
* (i.e. masked with 0xffffffffL).
* OK if dest==x (not sure if this is guaranteed for mpn_mul_1).
* This function is basically the same as gmp's mpn_mul_1.
*/
public static int mul_1 (int[] dest, int[] x, int len, int y)
{
long yword = (long) y & 0xffffffffL;
long carry = 0;
for (int j = 0; j < len; j++)
{
carry += ((long) x[j] & 0xffffffffL) * yword;
dest[j] = (int) carry;
carry = (long)(((ulong)carry) >> 32);
}
return (int) carry;
}
/**
* Multiply x[0:xlen-1] and y[0:ylen-1], and
* write the result to dest[0:xlen+ylen-1].
* The destination has to have space for xlen+ylen words,
* even if the result might be one limb smaller.
* This function requires that xlen >= ylen.
* The destination must be distinct from either input operands.
* All operands are unsigned.
* This function is basically the same gmp's mpn_mul. */
public static void mul (int[] dest,
int[] x, int xlen,
int[] y, int ylen)
{
dest[xlen] = MPN.mul_1 (dest, x, xlen, y[0]);
for (int i = 1; i < ylen; i++)
{
long yword = (long) y[i] & 0xffffffffL;
long carry = 0;
for (int j = 0; j < xlen; j++)
{
carry += ((long) x[j] & 0xffffffffL) * yword
+ ((long) dest[i+j] & 0xffffffffL);
dest[i+j] = (int) carry;
carry = (long)(((ulong)carry) >> 32);
}
dest[i+xlen] = (int) carry;
}
}
/* Divide (unsigned long) N by (unsigned int) D.
* Returns (remainder << 32)+(unsigned int)(quotient).
* Assumes (unsigned int)(N>>32) < (unsigned int)D.
* Code transcribed from gmp-2.0's mpn_udiv_w_sdiv function.
*/
public static long udiv_qrnnd (long N, int D)
{
long q, r;
long a1 = (long)(((ulong)N) >> 32);
long a0 = N & 0xffffffffL;
if (D >= 0)
{
if (a1 < ((D - a1 - ((long)(((ulong)a0) >> 31))) & 0xffffffffL))
{
/* dividend, divisor, and quotient are nonnegative */
q = N / D;
r = N % D;
}
else
{
/* Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d */
long c = N - ((long) D << 31);
/* Divide (c1*2^32 + c0) by d */
q = c / D;
r = c % D;
/* Add 2^31 to quotient */
q += 1 << 31;
}
}
else
{
long b1 = (int)((uint)D >> 1); /* d/2, between 2^30 and 2^31 - 1 */
//long c1 = (a1 >> 1); /* A/2 */
//int c0 = (a1 << 31) + (a0 >> 1);
long c = (long)((ulong)N >> 1);
if (a1 < b1 || (a1 >> 1) < b1)
{
if (a1 < b1)
{
q = c / b1;
r = c % b1;
}
else /* c1 < b1, so 2^31 <= (A/2)/b1 < 2^32 */
{
c = ~(c - (b1 << 32));
q = c / b1; /* (A/2) / (d/2) */
r = c % b1;
q = (~q) & 0xffffffffL; /* (A/2)/b1 */
r = (b1 - 1) - r; /* r < b1 => new r >= 0 */
}
r = 2 * r + (a0 & 1);
if ((D & 1) != 0)
{
if (r >= q) {
r = r - q;
} else if (q - r <= ((long) D & 0xffffffffL)) {
r = r - q + D;
q -= 1;
} else {
r = r - q + D + D;
q -= 2;
}
}
}
else /* Implies c1 = b1 */
{ /* Hence a1 = d - 1 = 2*b1 - 1 */
if (a0 >= ((long)(-D) & 0xffffffffL))
{
q = -1;
r = a0 + D;
}
else
{
q = -2;
r = a0 + D + D;
}
}
}
return (r << 32) | (q & 0xFFFFFFFFL);
}
/** Divide divident[0:len-1] by (unsigned int)divisor.
* Write result into quotient[0:len-1].
* Return the one-word (unsigned) remainder.
* OK for quotient==dividend.
*/
public static int divmod_1 (int[] quotient, int[] dividend,
int len, int divisor)
{
int i = len - 1;
long r = dividend[i];
if ((r & 0xffffffffL) >= ((long)divisor & 0xffffffffL))
r = 0;
else
{
quotient[i--] = 0;
r <<= 32;
}
for (; i >= 0; i--)
{
int n0 = dividend[i];
r = (r & ~0xffffffffL) | (n0 & 0xffffffffL);
r = udiv_qrnnd (r, divisor);
quotient[i] = (int) r;
}
return (int)(r >> 32);
}
/* Subtract x[0:len-1]*y from dest[offset:offset+len-1].
* All values are treated as if unsigned.
* @return the most significant word of
* the product, minus borrow-out from the subtraction.
*/
public static int submul_1 (int[] dest, int offset, int[] x, int len, int y)
{
long yl = (long) y & 0xffffffffL;
int carry = 0;
int j = 0;
do
{
long prod = ((long) x[j] & 0xffffffffL) * yl;
int prod_low = (int) prod;
int prod_high = (int) (prod >> 32);
prod_low += carry;
// Invert the high-order bit, because: (unsigned) X > (unsigned) Y
// iff: (int) (X^0x80000000) > (int) (Y^0x80000000).
carry = ((prod_low ^ 0x80000000) < (carry ^ 0x80000000) ? 1 : 0)
+ prod_high;
int x_j = dest[offset+j];
prod_low = x_j - prod_low;
if ((prod_low ^ 0x80000000) > (x_j ^ 0x80000000))
carry++;
dest[offset+j] = prod_low;
}
while (++j < len);
return carry;
}
/** Divide zds[0:nx] by y[0:ny-1].
* The remainder ends up in zds[0:ny-1].
* The quotient ends up in zds[ny:nx].
* Assumes: nx>ny.
* (int)y[ny-1] < 0 (i.e. most significant bit set)
*/
public static void divide (int[] zds, int nx, int[] y, int ny)
{
// This is basically Knuth's formulation of the classical algorithm,
// but translated from in scm_divbigbig in Jaffar's SCM implementation.
// Correspondance with Knuth's notation:
// Knuth's u[0:m+n] == zds[nx:0].
// Knuth's v[1:n] == y[ny-1:0]
// Knuth's n == ny.
// Knuth's m == nx-ny.
// Our nx == Knuth's m+n.
// Could be re-implemented using gmp's mpn_divrem:
// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
int j = nx;
do
{ // loop over digits of quotient
// Knuth's j == our nx-j.
// Knuth's u[j:j+n] == our zds[j:j-ny].
int qhat; // treated as unsigned
if (zds[j]==y[ny-1])
qhat = -1; // 0xffffffff
else
{
long w = (((long)(zds[j])) << 32) + ((long)zds[j-1] & 0xffffffffL);
qhat = (int) udiv_qrnnd (w, y[ny-1]);
}
if (qhat != 0)
{
int borrow = submul_1 (zds, j - ny, y, ny, qhat);
int save = zds[j];
long num = ((long)save&0xffffffffL) - ((long)borrow&0xffffffffL);
while (num != 0)
{
qhat--;
long carry = 0;
for (int i = 0; i < ny; i++)
{
carry += ((long) zds[j-ny+i] & 0xffffffffL)
+ ((long) y[i] & 0xffffffffL);
zds[j-ny+i] = (int) carry;
carry = (long)((ulong)carry >> 32);
}
zds[j] += (int)carry;
num = carry - 1;
}
}
zds[j] = qhat;
} while (--j >= ny);
}
/** Number of digits in the conversion base that always fits in a word.
* For example, for base 10 this is 9, since 10**9 is the
* largest number that fits into a words (assuming 32-bit words).
* This is the same as gmp's __mp_bases[radix].chars_per_limb.
* @param radix the base
* @return number of digits */
public static int chars_per_word (int radix)
{
if (radix < 10)
{
if (radix < 8)
{
if (radix <= 2)
return 32;
else if (radix == 3)
return 20;
else if (radix == 4)
return 16;
else
return 18 - radix;
}
else
return 10;
}
else if (radix < 12)
return 9;
else if (radix <= 16)
return 8;
else if (radix <= 23)
return 7;
else if (radix <= 40)
return 6;
// The following are conservative, but we don't care.
else if (radix <= 256)
return 4;
else
return 1;
}
/** Count the number of leading zero bits in an int. */
public static int count_leading_zeros (int i)
{
if (i == 0)
return 32;
int count = 0;
for (int k = 16; k > 0; k = k >> 1) {
int j = (int)((uint)i >> k);
if (j == 0)
count += k;
else
i = j;
}
return count;
}
public static int set_str (int[] dest, byte[] str, int str_len, int _base)
{
int size = 0;
if ((_base & (_base - 1)) == 0)
{
// The base is a power of 2. Read the input string from
// least to most significant character/digit. */
int next_bitpos = 0;
int bits_per_indigit = 0;
for (int i = _base; (i >>= 1) != 0; ) bits_per_indigit++;
int res_digit = 0;
for (int i = str_len; --i >= 0; )
{
int inp_digit = str[i];
res_digit |= inp_digit << next_bitpos;
next_bitpos += bits_per_indigit;
if (next_bitpos >= 32)
{
dest[size++] = res_digit;
next_bitpos -= 32;
res_digit = inp_digit >> (bits_per_indigit - next_bitpos);
}
}
if (res_digit != 0)
dest[size++] = res_digit;
}
else
{
// General case. The base is not a power of 2.
int indigits_per_limb = MPN.chars_per_word (_base);
int str_pos = 0;
while (str_pos < str_len)
{
int chunk = str_len - str_pos;
if (chunk > indigits_per_limb)
chunk = indigits_per_limb;
int res_digit = str[str_pos++];
int big_base = _base;
while (--chunk > 0)
{
res_digit = res_digit * _base + str[str_pos++];
big_base *= _base;
}
int cy_limb;
if (size == 0)
cy_limb = res_digit;
else
{
cy_limb = MPN.mul_1 (dest, dest, size, big_base);
cy_limb += MPN.add_1 (dest, dest, size, res_digit);
}
if (cy_limb != 0)
dest[size++] = cy_limb;
}
}
return size;
}
/** Compare {@code x[0:size-1]} with {@code y[0:size-1]}, treating them as unsigned integers.
* @return -1, 0, or 1 depending on if {@code x<y}, {@code x==y}, or {@code x>y}.
* This is basically the same as gmp's {@code mpn_cmp} function.
*/
public static int cmp (int[] x, int[] y, int size)
{
while (--size >= 0)
{
int x_word = x[size];
int y_word = y[size];
if (x_word != y_word)
{
// Invert the high-order bit, because:
// (unsigned) X > (unsigned) Y iff
// (int) (X^0x80000000) > (int) (Y^0x80000000).
return ((int)((uint)x_word ^ 0x80000000)) > ((int)((uint)y_word ^ 0x80000000)) ? 1 : -1;
}
}
return 0;
}
/** Compare {@code x[0:xlen-1]} with {@code y[0:ylen-1]}, treating them as unsigned integers.
* @return -1, 0, or 1 depending on
* whether {@code x<y}, {@code x==y}, or {@code x>y}.
*/
public static int cmp (int[] x, int xlen, int[] y, int ylen)
{
return xlen > ylen ? 1 : xlen < ylen ? -1 : cmp (x, y, xlen);
}
/* Shift x[x_start:x_start+len-1] count bits to the "right"
* (i.e. divide by 2**count).
* Store the len least significant words of the result at dest.
* The bits shifted out to the right are returned.
* OK if dest==x.
* Assumes: 0 < count < 32
*/
public static int rshift (int[] dest, int[] x, int x_start,
int len, int count)
{
int count_2 = 32 - count;
int low_word = x[x_start];
int retval = low_word << count_2;
int i = 1;
for (; i < len; i++)
{
int high_word = x[x_start+i];
dest[i-1] = ((int)((uint)low_word >> count)) | (high_word << count_2);
low_word = high_word;
}
dest[i-1] = (int)((uint)low_word >> count);
return retval;
}
/* Shift x[x_start:x_start+len-1] count bits to the "right"
* (i.e. divide by 2**count).
* Store the len least significant words of the result at dest.
* OK if dest==x.
* Assumes: 0 <= count < 32
* Same as rshift, but handles count==0 (and has no return value).
*/
public static void rshift0 (int[] dest, int[] x, int x_start,
int len, int count)
{
if (count > 0)
rshift(dest, x, x_start, len, count);
else
for (int i = 0; i < len; i++)
dest[i] = x[i + x_start];
}
/** Return the long-truncated value of right shifting.
* @param x a two's-complement "bignum"
* @param len the number of significant words in x
* @param count the shift count
* @return (long)(x[0..len-1] >> count).
*/
public static long rshift_long (int[] x, int len, int count)
{
int wordno = count >> 5;
count &= 31;
int sign = x[len-1] < 0 ? -1 : 0;
int w0 = wordno >= len ? sign : x[wordno];
wordno++;
int w1 = wordno >= len ? sign : x[wordno];
if (count != 0)
{
wordno++;
int w2 = wordno >= len ? sign : x[wordno];
w0 = ((int)((uint)w0 >> count)) | (w1 << (32-count));
w1 = ((int)((uint)w1 >> count)) | (w2 << (32-count));
}
return ((long)w1 << 32) | ((long)w0 & 0xffffffffL);
}
/* Shift x[0:len-1] left by count bits, and store the len least
* significant words of the result in dest[d_offset:d_offset+len-1].
* Return the bits shifted out from the most significant digit.
* Assumes 0 < count < 32.
* OK if dest==x.
*/
public static int lshift (int[] dest, int d_offset,
int[] x, int len, int count)
{
int count_2 = 32 - count;
int i = len - 1;
int high_word = x[i];
int retval = (int)((uint)high_word >> count_2);
d_offset++;
while (--i >= 0)
{
int low_word = x[i];
dest[d_offset+i] = (high_word << count) | ((int)((uint)low_word >> count_2));
high_word = low_word;
}
dest[d_offset+i] = high_word << count;
return retval;
}
/** Return least i such that word&(1<<i). Assumes word!=0. */
static int findLowestBit (int word)
{
int i = 0;
while ((word & 0xF) == 0)
{
word >>= 4;
i += 4;
}
if ((word & 3) == 0)
{
word >>= 2;
i += 2;
}
if ((word & 1) == 0)
i += 1;
return i;
}
/** Calculate Greatest Common Divisior of x[0:len-1] and y[0:len-1].
* Assumes both arguments are non-zero.
* Leaves result in x, and returns len of result.
* Also destroys y (actually sets it to a copy of the result). */
public static int gcd (int[] x, int[] y, int len)
{
int i, word;
// Find sh such that both x and y are divisible by 2**sh.
for (i = 0; ; i++)
{
word = x[i] | y[i];
if (word != 0)
{
// Must terminate, since x and y are non-zero.
break;
}
}
int initShiftWords = i;
int initShiftBits = findLowestBit (word);
// Logically: sh = initShiftWords * 32 + initShiftBits
// Temporarily devide both x and y by 2**sh.
len -= initShiftWords;
MPN.rshift0 (x, x, initShiftWords, len, initShiftBits);
MPN.rshift0 (y, y, initShiftWords, len, initShiftBits);
int[] odd_arg; /* One of x or y which is odd. */
int[] other_arg; /* The other one can be even or odd. */
if ((x[0] & 1) != 0)
{
odd_arg = x;
other_arg = y;
}
else
{
odd_arg = y;
other_arg = x;
}
for (;;)
{
// Shift other_arg until it is odd; this doesn't
// affect the gcd, since we divide by 2**k, which does not
// divide odd_arg.
for (i = 0; other_arg[i] == 0; ) i++;
if (i > 0)
{
int j;
for (j = 0; j < len-i; j++)
other_arg[j] = other_arg[j+i];
for ( ; j < len; j++)
other_arg[j] = 0;
}
i = findLowestBit(other_arg[0]);
if (i > 0)
MPN.rshift (other_arg, other_arg, 0, len, i);
// Now both odd_arg and other_arg are odd.
// Subtract the smaller from the larger.
// This does not change the result, since gcd(a-b,b)==gcd(a,b).
i = MPN.cmp(odd_arg, other_arg, len);
if (i == 0)
break;
if (i > 0)
{ // odd_arg > other_arg
MPN.sub_n (odd_arg, odd_arg, other_arg, len);
// Now odd_arg is even, so swap with other_arg;
int[] tmp = odd_arg; odd_arg = other_arg; other_arg = tmp;
}
else
{ // other_arg > odd_arg
MPN.sub_n (other_arg, other_arg, odd_arg, len);
}
while (odd_arg[len-1] == 0 && other_arg[len-1] == 0)
len--;
}
if (initShiftWords + initShiftBits > 0)
{
if (initShiftBits > 0)
{
int sh_out = MPN.lshift (x, initShiftWords, x, len, initShiftBits);
if (sh_out != 0)
x[(len++)+initShiftWords] = sh_out;
}
else
{
for (i = len; --i >= 0;)
x[i+initShiftWords] = x[i];
}
for (i = initShiftWords; --i >= 0; )
x[i] = 0;
len += initShiftWords;
}
return len;
}
public static int intLength (int i)
{
return 32 - count_leading_zeros (i < 0 ? ~i : i);
}
/** Calcaulte the Common Lisp "integer-length" function.
* Assumes input is canonicalized: len==IntNum.wordsNeeded(words,len) */
public static int intLength (int[] words, int len)
{
len--;
return intLength (words[len]) + 32 * len;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using log4net;
using OpenMetaverse;
namespace OpenSim.Framework.Console
{
public class ConsoleUtil
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const int LocalIdNotFound = 0;
/// <summary>
/// Used by modules to display stock co-ordinate help, though possibly this should be under some general section
/// rather than in each help summary.
/// </summary>
public const string CoordHelp
= @"Each component of the coord is comma separated. There must be no spaces between the commas.
If you don't care about the z component you can simply omit it.
If you don't care about the x or y components then you can leave them blank (though a comma is still required)
If you want to specify the maximum value of a component then you can use ~ instead of a number
If you want to specify the minimum value of a component then you can use -~ instead of a number
e.g.
show object pos 20,20,20 to 40,40,40
delete object pos 20,20 to 40,40
show object pos ,20,20 to ,40,40
delete object pos ,,30 to ,,~
show object pos ,,-~ to ,,30";
public const string MinRawConsoleVectorValue = "-~";
public const string MaxRawConsoleVectorValue = "~";
public const string VectorSeparator = ",";
public static char[] VectorSeparatorChars = VectorSeparator.ToCharArray();
/// <summary>
/// Check if the given file path exists.
/// </summary>
/// <remarks>If not, warning is printed to the given console.</remarks>
/// <returns>true if the file does not exist, false otherwise.</returns>
/// <param name='console'></param>
/// <param name='path'></param>
public static bool CheckFileDoesNotExist(ICommandConsole console, string path)
{
if (File.Exists(path))
{
console.OutputFormat("File {0} already exists. Please move or remove it.", path);
return false;
}
return true;
}
/// <summary>
/// Try to parse a console UUID from the console.
/// </summary>
/// <remarks>
/// Will complain to the console if parsing fails.
/// </remarks>
/// <returns></returns>
/// <param name='console'>If null then no complaint is printed.</param>
/// <param name='rawUuid'></param>
/// <param name='uuid'></param>
public static bool TryParseConsoleUuid(ICommandConsole console, string rawUuid, out UUID uuid)
{
if (!UUID.TryParse(rawUuid, out uuid))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid uuid", rawUuid);
return false;
}
return true;
}
public static bool TryParseConsoleLocalId(ICommandConsole console, string rawLocalId, out uint localId)
{
if (!uint.TryParse(rawLocalId, out localId))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid local id", localId);
return false;
}
if (localId == 0)
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid local id - it must be greater than 0", localId);
return false;
}
return true;
}
/// <summary>
/// Tries to parse the input as either a UUID or a local ID.
/// </summary>
/// <returns>true if parsing succeeded, false otherwise.</returns>
/// <param name='console'></param>
/// <param name='rawId'></param>
/// <param name='uuid'></param>
/// <param name='localId'>
/// Will be set to ConsoleUtil.LocalIdNotFound if parsing result was a UUID or no parse succeeded.
/// </param>
public static bool TryParseConsoleId(ICommandConsole console, string rawId, out UUID uuid, out uint localId)
{
if (TryParseConsoleUuid(null, rawId, out uuid))
{
localId = LocalIdNotFound;
return true;
}
if (TryParseConsoleLocalId(null, rawId, out localId))
{
return true;
}
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid UUID or local id", rawId);
return false;
}
/// <summary>
/// Convert a console input to a bool, automatically complaining if a console is given.
/// </summary>
/// <param name='console'>Can be null if no console is available.</param>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleBool(ICommandConsole console, string rawConsoleString, out bool b)
{
if (!bool.TryParse(rawConsoleString, out b))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a true or false value", rawConsoleString);
return false;
}
return true;
}
/// <summary>
/// Convert a console input to an int, automatically complaining if a console is given.
/// </summary>
/// <param name='console'>Can be null if no console is available.</param>
/// <param name='rawConsoleInt'>/param>
/// <param name='i'></param>
/// <returns></returns>
public static bool TryParseConsoleInt(ICommandConsole console, string rawConsoleInt, out int i)
{
if (!int.TryParse(rawConsoleInt, out i))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid integer", rawConsoleInt);
return false;
}
return true;
}
/// <summary>
/// Convert a console input to a float, automatically complaining if a console is given.
/// </summary>
/// <param name='console'>Can be null if no console is available.</param>
/// <param name='rawConsoleInput'>/param>
/// <param name='i'></param>
/// <returns></returns>
public static bool TryParseConsoleFloat(ICommandConsole console, string rawConsoleInput, out float i)
{
if (!float.TryParse(rawConsoleInput, out i))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid float", rawConsoleInput);
return false;
}
return true;
}
/// <summary>
/// Convert a console input to a double, automatically complaining if a console is given.
/// </summary>
/// <param name='console'>Can be null if no console is available.</param>
/// <param name='rawConsoleInput'>/param>
/// <param name='i'></param>
/// <returns></returns>
public static bool TryParseConsoleDouble(ICommandConsole console, string rawConsoleInput, out double i)
{
if (!double.TryParse(rawConsoleInput, out i))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid double", rawConsoleInput);
return false;
}
return true;
}
/// <summary>
/// Convert a console integer to a natural int, automatically complaining if a console is given.
/// </summary>
/// <param name='console'>Can be null if no console is available.</param>
/// <param name='rawConsoleInt'>/param>
/// <param name='i'></param>
/// <returns></returns>
public static bool TryParseConsoleNaturalInt(ICommandConsole console, string rawConsoleInt, out int i)
{
if (TryParseConsoleInt(console, rawConsoleInt, out i))
{
if (i < 0)
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a positive integer", rawConsoleInt);
return false;
}
return true;
}
return false;
}
/// <summary>
/// Convert a minimum vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleMinVector(string rawConsoleVector, out Vector3 vector)
{
return TryParseConsoleVector(rawConsoleVector, c => float.MinValue.ToString(), out vector);
}
/// <summary>
/// Convert a maximum vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleMaxVector(string rawConsoleVector, out Vector3 vector)
{
return TryParseConsoleVector(rawConsoleVector, c => float.MaxValue.ToString(), out vector);
}
/// <summary>
/// Convert a vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>
/// A string in the form <x>,<y>,<z> where there is no space between values.
/// Any component can be missing (e.g. ,,40). blankComponentFunc is invoked to replace the blank with a suitable value
/// Also, if the blank component is at the end, then the comma can be missed off entirely (e.g. 40,30 or 40)
/// The strings "~" and "-~" are valid in components. The first substitutes float.MaxValue whilst the second is float.MinValue
/// Other than that, component values must be numeric.
/// </param>
/// <param name='blankComponentFunc'>
/// Behaviour if component is blank. If null then conversion fails on a blank component.
/// </param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleVector(
string rawConsoleVector, Func<string, string> blankComponentFunc, out Vector3 vector)
{
return Vector3.TryParse(CookVector(rawConsoleVector, 3, blankComponentFunc), out vector);
}
/// <summary>
/// Convert a vector input from the console to an OpenMetaverse.Vector2
/// </summary>
/// <param name='rawConsoleVector'>
/// A string in the form <x>,<y> where there is no space between values.
/// Any component can be missing (e.g. ,40). blankComponentFunc is invoked to replace the blank with a suitable value
/// Also, if the blank component is at the end, then the comma can be missed off entirely (e.g. 40)
/// The strings "~" and "-~" are valid in components. The first substitutes float.MaxValue whilst the second is float.MinValue
/// Other than that, component values must be numeric.
/// </param>
/// <param name='blankComponentFunc'>
/// Behaviour if component is blank. If null then conversion fails on a blank component.
/// </param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsole2DVector(
string rawConsoleVector, Func<string, string> blankComponentFunc, out Vector2 vector)
{
// We don't use Vector2.TryParse() for now because for some reason it expects an input with 3 components
// rather than 2.
string cookedVector = CookVector(rawConsoleVector, 2, blankComponentFunc);
if (cookedVector == null)
{
vector = Vector2.Zero;
return false;
}
else
{
string[] cookedComponents = cookedVector.Split(VectorSeparatorChars);
vector = new Vector2(float.Parse(cookedComponents[0]), float.Parse(cookedComponents[1]));
return true;
}
//return Vector2.TryParse(CookVector(rawConsoleVector, 2, blankComponentFunc), out vector);
}
/// <summary>
/// Convert a raw console vector into a vector that can be be parsed by the relevant OpenMetaverse.TryParse()
/// </summary>
/// <param name='rawConsoleVector'></param>
/// <param name='dimensions'></param>
/// <param name='blankComponentFunc'></param>
/// <returns>null if conversion was not possible</returns>
private static string CookVector(
string rawConsoleVector, int dimensions, Func<string, string> blankComponentFunc)
{
List<string> components = rawConsoleVector.Split(VectorSeparatorChars).ToList();
if (components.Count < 1 || components.Count > dimensions)
return null;
if (components.Count < dimensions)
{
if (blankComponentFunc == null)
return null;
else
for (int i = components.Count; i < dimensions; i++)
components.Add("");
}
List<string> cookedComponents
= components.ConvertAll<string>(
c =>
{
if (c == "")
return blankComponentFunc.Invoke(c);
else if (c == MaxRawConsoleVectorValue)
return float.MaxValue.ToString();
else if (c == MinRawConsoleVectorValue)
return float.MinValue.ToString();
else
return c;
});
return string.Join(VectorSeparator, cookedComponents.ToArray());
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ProperBitConverter.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
// Tested and verified to work
#pragma warning disable 0675
using System.Globalization;
namespace Stratus.OdinSerializer
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// Corresponds to the .NET <see cref="BitConverter"/> class, but works only with buffers and so never allocates garbage.
/// <para />
/// This class always writes and reads bytes in a little endian format, regardless of system architecture.
/// </summary>
public static class ProperBitConverter
{
private static readonly uint[] ByteToHexCharLookupLowerCase = CreateByteToHexLookup(false);
private static readonly uint[] ByteToHexCharLookupUpperCase = CreateByteToHexLookup(true);
// 16x16 table, set up for direct visual correlation to Unicode table with hex coords
private static readonly byte[] HexToByteLookup = new byte[] {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
private static uint[] CreateByteToHexLookup(bool upperCase)
{
var result = new uint[256];
if (upperCase)
{
for (int i = 0; i < 256; i++)
{
string s = i.ToString("X2", CultureInfo.InvariantCulture);
result[i] = ((uint)s[0]) + ((uint)s[1] << 16);
}
}
else
{
for (int i = 0; i < 256; i++)
{
string s = i.ToString("x2", CultureInfo.InvariantCulture);
result[i] = ((uint)s[0]) + ((uint)s[1] << 16);
}
}
return result;
}
/// <summary>
/// Converts a byte array into a hexadecimal string.
/// </summary>
public static string BytesToHexString(byte[] bytes, bool lowerCaseHexChars = true)
{
var lookup = lowerCaseHexChars ? ByteToHexCharLookupLowerCase : ByteToHexCharLookupUpperCase;
var result = new char[bytes.Length * 2];
for (int i = 0; i < bytes.Length; i++)
{
int offset = i * 2;
var val = lookup[bytes[i]];
result[offset] = (char)val;
result[offset + 1] = (char)(val >> 16);
}
return new string(result);
}
/// <summary>
/// Converts a hexadecimal string into a byte array.
/// </summary>
public static byte[] HexStringToBytes(string hex)
{
int length = hex.Length;
int rLength = length / 2;
if (length % 2 != 0)
{
throw new ArgumentException("Hex string must have an even length.");
}
byte[] result = new byte[rLength];
for (int i = 0; i < rLength; i++)
{
int offset = i * 2;
byte b1;
byte b2;
try
{
b1 = HexToByteLookup[hex[offset]];
if (b1 == 0xff)
{
throw new ArgumentException("Expected a hex character, got '" + hex[offset] + "' at string index '" + offset + "'.");
}
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("Expected a hex character, got '" + hex[offset] + "' at string index '" + offset + "'.");
}
try
{
b2 = HexToByteLookup[hex[offset + 1]];
if (b2 == 0xff)
{
throw new ArgumentException("Expected a hex character, got '" + hex[offset + 1] + "' at string index '" + (offset + 1) + "'.");
}
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("Expected a hex character, got '" + hex[offset + 1] + "' at string index '" + (offset + 1) + "'.");
}
result[i] = (byte)(b1 << 4 | b2);
}
return result;
}
/// <summary>
/// Reads two bytes from a buffer and converts them into a <see cref="short"/> value.
/// </summary>
/// <param name="buffer">The buffer to read from.</param>
/// <param name="index">The index to start reading at.</param>
/// <returns>The converted value.</returns>
public static short ToInt16(byte[] buffer, int index)
{
short value = default(short);
value |= buffer[index + 1];
value <<= 8;
value |= buffer[index];
return value;
}
/// <summary>
/// Reads two bytes from a buffer and converts them into a <see cref="ushort"/> value.
/// </summary>
/// <param name="buffer">The buffer to read from.</param>
/// <param name="index">The index to start reading at.</param>
/// <returns>The converted value.</returns>
public static ushort ToUInt16(byte[] buffer, int index)
{
ushort value = default(ushort);
value |= buffer[index + 1];
value <<= 8;
value |= buffer[index];
return value;
}
/// <summary>
/// Reads four bytes from a buffer and converts them into an <see cref="int"/> value.
/// </summary>
/// <param name="buffer">The buffer to read from.</param>
/// <param name="index">The index to start reading at.</param>
/// <returns>The converted value.</returns>
public static int ToInt32(byte[] buffer, int index)
{
int value = default(int);
value |= buffer[index + 3];
value <<= 8;
value |= buffer[index + 2];
value <<= 8;
value |= buffer[index + 1];
value <<= 8;
value |= buffer[index];
return value;
}
/// <summary>
/// Reads four bytes from a buffer and converts them into an <see cref="uint"/> value.
/// </summary>
/// <param name="buffer">The buffer to read from.</param>
/// <param name="index">The index to start reading at.</param>
/// <returns>The converted value.</returns>
public static uint ToUInt32(byte[] buffer, int index)
{
uint value = default(uint);
value |= buffer[index + 3];
value <<= 8;
value |= buffer[index + 2];
value <<= 8;
value |= buffer[index + 1];
value <<= 8;
value |= buffer[index];
return value;
}
/// <summary>
/// Reads eight bytes from a buffer and converts them into a <see cref="long"/> value.
/// </summary>
/// <param name="buffer">The buffer to read from.</param>
/// <param name="index">The index to start reading at.</param>
/// <returns>The converted value.</returns>
public static long ToInt64(byte[] buffer, int index)
{
long value = default(long);
value |= buffer[index + 7];
value <<= 8;
value |= buffer[index + 6];
value <<= 8;
value |= buffer[index + 5];
value <<= 8;
value |= buffer[index + 4];
value <<= 8;
value |= buffer[index + 3];
value <<= 8;
value |= buffer[index + 2];
value <<= 8;
value |= buffer[index + 1];
value <<= 8;
value |= buffer[index];
return value;
}
/// <summary>
/// Reads eight bytes from a buffer and converts them into an <see cref="ulong"/> value.
/// </summary>
/// <param name="buffer">The buffer to read from.</param>
/// <param name="index">The index to start reading at.</param>
/// <returns>The converted value.</returns>
public static ulong ToUInt64(byte[] buffer, int index)
{
ulong value = default(ulong);
value |= buffer[index + 7];
value <<= 8;
value |= buffer[index + 6];
value <<= 8;
value |= buffer[index + 5];
value <<= 8;
value |= buffer[index + 4];
value <<= 8;
value |= buffer[index + 3];
value <<= 8;
value |= buffer[index + 2];
value <<= 8;
value |= buffer[index + 1];
value <<= 8;
value |= buffer[index];
return value;
}
/// <summary>
/// Reads four bytes from a buffer and converts them into an <see cref="float"/> value.
/// </summary>
/// <param name="buffer">The buffer to read from.</param>
/// <param name="index">The index to start reading at.</param>
/// <returns>The converted value.</returns>
public static float ToSingle(byte[] buffer, int index)
{
var union = default(SingleByteUnion);
if (BitConverter.IsLittleEndian)
{
union.Byte0 = buffer[index];
union.Byte1 = buffer[index + 1];
union.Byte2 = buffer[index + 2];
union.Byte3 = buffer[index + 3];
}
else
{
union.Byte3 = buffer[index];
union.Byte2 = buffer[index + 1];
union.Byte1 = buffer[index + 2];
union.Byte0 = buffer[index + 3];
}
return union.Value;
}
/// <summary>
/// Reads eight bytes from a buffer and converts them into an <see cref="double"/> value.
/// </summary>
/// <param name="buffer">The buffer to read from.</param>
/// <param name="index">The index to start reading at.</param>
/// <returns>The converted value.</returns>
public static double ToDouble(byte[] buffer, int index)
{
var union = default(DoubleByteUnion);
if (BitConverter.IsLittleEndian)
{
union.Byte0 = buffer[index];
union.Byte1 = buffer[index + 1];
union.Byte2 = buffer[index + 2];
union.Byte3 = buffer[index + 3];
union.Byte4 = buffer[index + 4];
union.Byte5 = buffer[index + 5];
union.Byte6 = buffer[index + 6];
union.Byte7 = buffer[index + 7];
}
else
{
union.Byte7 = buffer[index];
union.Byte6 = buffer[index + 1];
union.Byte5 = buffer[index + 2];
union.Byte4 = buffer[index + 3];
union.Byte3 = buffer[index + 4];
union.Byte2 = buffer[index + 5];
union.Byte1 = buffer[index + 6];
union.Byte0 = buffer[index + 7];
}
return union.Value;
}
/// <summary>
/// Reads sixteen bytes from a buffer and converts them into a <see cref="decimal"/> value.
/// </summary>
/// <param name="buffer">The buffer to read from.</param>
/// <param name="index">The index to start reading at.</param>
/// <returns>The converted value.</returns>
public static decimal ToDecimal(byte[] buffer, int index)
{
var union = default(DecimalByteUnion);
if (BitConverter.IsLittleEndian)
{
union.Byte0 = buffer[index];
union.Byte1 = buffer[index + 1];
union.Byte2 = buffer[index + 2];
union.Byte3 = buffer[index + 3];
union.Byte4 = buffer[index + 4];
union.Byte5 = buffer[index + 5];
union.Byte6 = buffer[index + 6];
union.Byte7 = buffer[index + 7];
union.Byte8 = buffer[index + 8];
union.Byte9 = buffer[index + 9];
union.Byte10 = buffer[index + 10];
union.Byte11 = buffer[index + 11];
union.Byte12 = buffer[index + 12];
union.Byte13 = buffer[index + 13];
union.Byte14 = buffer[index + 14];
union.Byte15 = buffer[index + 15];
}
else
{
union.Byte15 = buffer[index];
union.Byte14 = buffer[index + 1];
union.Byte13 = buffer[index + 2];
union.Byte12 = buffer[index + 3];
union.Byte11 = buffer[index + 4];
union.Byte10 = buffer[index + 5];
union.Byte9 = buffer[index + 6];
union.Byte8 = buffer[index + 7];
union.Byte7 = buffer[index + 8];
union.Byte6 = buffer[index + 9];
union.Byte5 = buffer[index + 10];
union.Byte4 = buffer[index + 11];
union.Byte3 = buffer[index + 12];
union.Byte2 = buffer[index + 13];
union.Byte1 = buffer[index + 14];
union.Byte0 = buffer[index + 15];
}
return union.Value;
}
/// <summary>
/// Reads sixteen bytes from a buffer and converts them into a <see cref="Guid"/> value.
/// </summary>
/// <param name="buffer">The buffer to read from.</param>
/// <param name="index">The index to start reading at.</param>
/// <returns>The converted value.</returns>
public static Guid ToGuid(byte[] buffer, int index)
{
var union = default(GuidByteUnion);
// First 10 bytes of a guid are always little endian
// Last 6 bytes depend on architecture endianness
// See http://stackoverflow.com/questions/10190817/guid-byte-order-in-
union.Byte0 = buffer[index];
union.Byte1 = buffer[index + 1];
union.Byte2 = buffer[index + 2];
union.Byte3 = buffer[index + 3];
union.Byte4 = buffer[index + 4];
union.Byte5 = buffer[index + 5];
union.Byte6 = buffer[index + 6];
union.Byte7 = buffer[index + 7];
union.Byte8 = buffer[index + 8];
union.Byte9 = buffer[index + 9];
if (BitConverter.IsLittleEndian)
{
union.Byte10 = buffer[index + 10];
union.Byte11 = buffer[index + 11];
union.Byte12 = buffer[index + 12];
union.Byte13 = buffer[index + 13];
union.Byte14 = buffer[index + 14];
union.Byte15 = buffer[index + 15];
}
else
{
union.Byte15 = buffer[index + 10];
union.Byte14 = buffer[index + 11];
union.Byte13 = buffer[index + 12];
union.Byte12 = buffer[index + 13];
union.Byte11 = buffer[index + 14];
union.Byte10 = buffer[index + 15];
}
return union.Value;
}
/// <summary>
/// Turns a <see cref="short"/> value into two bytes and writes those bytes to a given buffer.
/// </summary>
/// <param name="buffer">The buffer to write to.</param>
/// <param name="index">The index to start writing at.</param>
/// <param name="value">The value to write.</param>
public static void GetBytes(byte[] buffer, int index, short value)
{
if (BitConverter.IsLittleEndian)
{
buffer[index] = (byte)value;
buffer[index + 1] = (byte)(value >> 8);
}
else
{
buffer[index] = (byte)(value >> 8);
buffer[index + 1] = (byte)value;
}
}
/// <summary>
/// Turns an <see cref="ushort"/> value into two bytes and writes those bytes to a given buffer.
/// </summary>
/// <param name="buffer">The buffer to write to.</param>
/// <param name="index">The index to start writing at.</param>
/// <param name="value">The value to write.</param>
public static void GetBytes(byte[] buffer, int index, ushort value)
{
if (BitConverter.IsLittleEndian)
{
buffer[index] = (byte)value;
buffer[index + 1] = (byte)(value >> 8);
}
else
{
buffer[index] = (byte)(value >> 8);
buffer[index + 1] = (byte)value;
}
}
/// <summary>
/// Turns an <see cref="int"/> value into four bytes and writes those bytes to a given buffer.
/// </summary>
/// <param name="buffer">The buffer to write to.</param>
/// <param name="index">The index to start writing at.</param>
/// <param name="value">The value to write.</param>
public static void GetBytes(byte[] buffer, int index, int value)
{
if (BitConverter.IsLittleEndian)
{
buffer[index] = (byte)value;
buffer[index + 1] = (byte)(value >> 8);
buffer[index + 2] = (byte)(value >> 16);
buffer[index + 3] = (byte)(value >> 24);
}
else
{
buffer[index] = (byte)(value >> 24);
buffer[index + 1] = (byte)(value >> 16);
buffer[index + 2] = (byte)(value >> 8);
buffer[index + 3] = (byte)value;
}
}
/// <summary>
/// Turns an <see cref="uint"/> value into four bytes and writes those bytes to a given buffer.
/// </summary>
/// <param name="buffer">The buffer to write to.</param>
/// <param name="index">The index to start writing at.</param>
/// <param name="value">The value to write.</param>
public static void GetBytes(byte[] buffer, int index, uint value)
{
if (BitConverter.IsLittleEndian)
{
buffer[index] = (byte)value;
buffer[index + 1] = (byte)(value >> 8);
buffer[index + 2] = (byte)(value >> 16);
buffer[index + 3] = (byte)(value >> 24);
}
else
{
buffer[index] = (byte)(value >> 24);
buffer[index + 1] = (byte)(value >> 16);
buffer[index + 2] = (byte)(value >> 8);
buffer[index + 3] = (byte)value;
}
}
/// <summary>
/// Turns a <see cref="long"/> value into eight bytes and writes those bytes to a given buffer.
/// </summary>
/// <param name="buffer">The buffer to write to.</param>
/// <param name="index">The index to start writing at.</param>
/// <param name="value">The value to write.</param>
public static void GetBytes(byte[] buffer, int index, long value)
{
if (BitConverter.IsLittleEndian)
{
buffer[index] = (byte)value;
buffer[index + 1] = (byte)(value >> 8);
buffer[index + 2] = (byte)(value >> 16);
buffer[index + 3] = (byte)(value >> 24);
buffer[index + 4] = (byte)(value >> 32);
buffer[index + 5] = (byte)(value >> 40);
buffer[index + 6] = (byte)(value >> 48);
buffer[index + 7] = (byte)(value >> 56);
}
else
{
buffer[index] = (byte)(value >> 56);
buffer[index + 1] = (byte)(value >> 48);
buffer[index + 2] = (byte)(value >> 40);
buffer[index + 3] = (byte)(value >> 32);
buffer[index + 4] = (byte)(value >> 24);
buffer[index + 5] = (byte)(value >> 16);
buffer[index + 6] = (byte)(value >> 8);
buffer[index + 7] = (byte)value;
}
}
/// <summary>
/// Turns an <see cref="ulong"/> value into eight bytes and writes those bytes to a given buffer.
/// </summary>
/// <param name="buffer">The buffer to write to.</param>
/// <param name="index">The index to start writing at.</param>
/// <param name="value">The value to write.</param>
public static void GetBytes(byte[] buffer, int index, ulong value)
{
if (BitConverter.IsLittleEndian)
{
buffer[index] = (byte)value;
buffer[index + 1] = (byte)(value >> 8);
buffer[index + 2] = (byte)(value >> 16);
buffer[index + 3] = (byte)(value >> 24);
buffer[index + 4] = (byte)(value >> 32);
buffer[index + 5] = (byte)(value >> 40);
buffer[index + 6] = (byte)(value >> 48);
buffer[index + 7] = (byte)(value >> 56);
}
else
{
buffer[index] = (byte)(value >> 56);
buffer[index + 1] = (byte)(value >> 48);
buffer[index + 2] = (byte)(value >> 40);
buffer[index + 3] = (byte)(value >> 32);
buffer[index + 4] = (byte)(value >> 24);
buffer[index + 5] = (byte)(value >> 16);
buffer[index + 6] = (byte)(value >> 8);
buffer[index + 7] = (byte)value;
}
}
/// <summary>
/// Turns a <see cref="float"/> value into four bytes and writes those bytes to a given buffer.
/// </summary>
/// <param name="buffer">The buffer to write to.</param>
/// <param name="index">The index to start writing at.</param>
/// <param name="value">The value to write.</param>
public static void GetBytes(byte[] buffer, int index, float value)
{
var union = default(SingleByteUnion);
union.Value = value;
if (BitConverter.IsLittleEndian)
{
buffer[index] = union.Byte0;
buffer[index + 1] = union.Byte1;
buffer[index + 2] = union.Byte2;
buffer[index + 3] = union.Byte3;
}
else
{
buffer[index] = union.Byte3;
buffer[index + 1] = union.Byte2;
buffer[index + 2] = union.Byte1;
buffer[index + 3] = union.Byte0;
}
}
/// <summary>
/// Turns a <see cref="double"/> value into eight bytes and writes those bytes to a given buffer.
/// </summary>
/// <param name="buffer">The buffer to write to.</param>
/// <param name="index">The index to start writing at.</param>
/// <param name="value">The value to write.</param>
public static void GetBytes(byte[] buffer, int index, double value)
{
var union = default(DoubleByteUnion);
union.Value = value;
if (BitConverter.IsLittleEndian)
{
buffer[index] = union.Byte0;
buffer[index + 1] = union.Byte1;
buffer[index + 2] = union.Byte2;
buffer[index + 3] = union.Byte3;
buffer[index + 4] = union.Byte4;
buffer[index + 5] = union.Byte5;
buffer[index + 6] = union.Byte6;
buffer[index + 7] = union.Byte7;
}
else
{
buffer[index] = union.Byte7;
buffer[index + 1] = union.Byte6;
buffer[index + 2] = union.Byte5;
buffer[index + 3] = union.Byte4;
buffer[index + 4] = union.Byte3;
buffer[index + 5] = union.Byte2;
buffer[index + 6] = union.Byte1;
buffer[index + 7] = union.Byte0;
}
}
/// <summary>
/// Turns a <see cref="decimal"/> value into sixteen bytes and writes those bytes to a given buffer.
/// </summary>
/// <param name="buffer">The buffer to write to.</param>
/// <param name="index">The index to start writing at.</param>
/// <param name="value">The value to write.</param>
public static void GetBytes(byte[] buffer, int index, decimal value)
{
var union = default(DecimalByteUnion);
union.Value = value;
if (BitConverter.IsLittleEndian)
{
buffer[index] = union.Byte0;
buffer[index + 1] = union.Byte1;
buffer[index + 2] = union.Byte2;
buffer[index + 3] = union.Byte3;
buffer[index + 4] = union.Byte4;
buffer[index + 5] = union.Byte5;
buffer[index + 6] = union.Byte6;
buffer[index + 7] = union.Byte7;
buffer[index + 8] = union.Byte8;
buffer[index + 9] = union.Byte9;
buffer[index + 10] = union.Byte10;
buffer[index + 11] = union.Byte11;
buffer[index + 12] = union.Byte12;
buffer[index + 13] = union.Byte13;
buffer[index + 14] = union.Byte14;
buffer[index + 15] = union.Byte15;
}
else
{
buffer[index] = union.Byte15;
buffer[index + 1] = union.Byte14;
buffer[index + 2] = union.Byte13;
buffer[index + 3] = union.Byte12;
buffer[index + 4] = union.Byte11;
buffer[index + 5] = union.Byte10;
buffer[index + 6] = union.Byte9;
buffer[index + 7] = union.Byte8;
buffer[index + 8] = union.Byte7;
buffer[index + 9] = union.Byte6;
buffer[index + 10] = union.Byte5;
buffer[index + 11] = union.Byte4;
buffer[index + 12] = union.Byte3;
buffer[index + 13] = union.Byte2;
buffer[index + 14] = union.Byte1;
buffer[index + 15] = union.Byte0;
}
}
/// <summary>
/// Turns a <see cref="Guid"/> value into sixteen bytes and writes those bytes to a given buffer.
/// </summary>
/// <param name="buffer">The buffer to write to.</param>
/// <param name="index">The index to start writing at.</param>
/// <param name="value">The value to write.</param>
public static void GetBytes(byte[] buffer, int index, Guid value)
{
var union = default(GuidByteUnion);
union.Value = value;
// First 10 bytes of a guid are always little endian
// Last 6 bytes depend on architecture endianness
// See http://stackoverflow.com/questions/10190817/guid-byte-order-in-net
// TODO: Test if this actually works on big-endian architecture. Where the hell do we find that?
buffer[index] = union.Byte0;
buffer[index + 1] = union.Byte1;
buffer[index + 2] = union.Byte2;
buffer[index + 3] = union.Byte3;
buffer[index + 4] = union.Byte4;
buffer[index + 5] = union.Byte5;
buffer[index + 6] = union.Byte6;
buffer[index + 7] = union.Byte7;
buffer[index + 8] = union.Byte8;
buffer[index + 9] = union.Byte9;
if (BitConverter.IsLittleEndian)
{
buffer[index + 10] = union.Byte10;
buffer[index + 11] = union.Byte11;
buffer[index + 12] = union.Byte12;
buffer[index + 13] = union.Byte13;
buffer[index + 14] = union.Byte14;
buffer[index + 15] = union.Byte15;
}
else
{
buffer[index + 10] = union.Byte15;
buffer[index + 11] = union.Byte14;
buffer[index + 12] = union.Byte13;
buffer[index + 13] = union.Byte12;
buffer[index + 14] = union.Byte11;
buffer[index + 15] = union.Byte10;
}
}
[StructLayout(LayoutKind.Explicit)]
private struct SingleByteUnion
{
[FieldOffset(0)]
public byte Byte0;
[FieldOffset(1)]
public byte Byte1;
[FieldOffset(2)]
public byte Byte2;
[FieldOffset(3)]
public byte Byte3;
[FieldOffset(0)]
public float Value;
}
[StructLayout(LayoutKind.Explicit)]
private struct DoubleByteUnion
{
[FieldOffset(0)]
public byte Byte0;
[FieldOffset(1)]
public byte Byte1;
[FieldOffset(2)]
public byte Byte2;
[FieldOffset(3)]
public byte Byte3;
[FieldOffset(4)]
public byte Byte4;
[FieldOffset(5)]
public byte Byte5;
[FieldOffset(6)]
public byte Byte6;
[FieldOffset(7)]
public byte Byte7;
[FieldOffset(0)]
public double Value;
}
[StructLayout(LayoutKind.Explicit)]
private struct DecimalByteUnion
{
[FieldOffset(0)]
public byte Byte0;
[FieldOffset(1)]
public byte Byte1;
[FieldOffset(2)]
public byte Byte2;
[FieldOffset(3)]
public byte Byte3;
[FieldOffset(4)]
public byte Byte4;
[FieldOffset(5)]
public byte Byte5;
[FieldOffset(6)]
public byte Byte6;
[FieldOffset(7)]
public byte Byte7;
[FieldOffset(8)]
public byte Byte8;
[FieldOffset(9)]
public byte Byte9;
[FieldOffset(10)]
public byte Byte10;
[FieldOffset(11)]
public byte Byte11;
[FieldOffset(12)]
public byte Byte12;
[FieldOffset(13)]
public byte Byte13;
[FieldOffset(14)]
public byte Byte14;
[FieldOffset(15)]
public byte Byte15;
[FieldOffset(0)]
public decimal Value;
}
[StructLayout(LayoutKind.Explicit)]
private struct GuidByteUnion
{
[FieldOffset(0)]
public byte Byte0;
[FieldOffset(1)]
public byte Byte1;
[FieldOffset(2)]
public byte Byte2;
[FieldOffset(3)]
public byte Byte3;
[FieldOffset(4)]
public byte Byte4;
[FieldOffset(5)]
public byte Byte5;
[FieldOffset(6)]
public byte Byte6;
[FieldOffset(7)]
public byte Byte7;
[FieldOffset(8)]
public byte Byte8;
[FieldOffset(9)]
public byte Byte9;
[FieldOffset(10)]
public byte Byte10;
[FieldOffset(11)]
public byte Byte11;
[FieldOffset(12)]
public byte Byte12;
[FieldOffset(13)]
public byte Byte13;
[FieldOffset(14)]
public byte Byte14;
[FieldOffset(15)]
public byte Byte15;
[FieldOffset(0)]
public Guid Value;
}
}
}
| |
/******************************************************************************************************
// Original code by: DLESKTECH at http://www.dlesktech.com/support.aspx
// Modifications by: KASL Technologies at www.kasltechnologies.com
// Mod date:7/21/2009
// Mods: working smileys, moved smilies to bottom, added clear button for admin, new stored procedure
// Mods: fixed the time to show the viewers time not the server time
// Mods: added small chat window popup that runs separately from forum
// Note: flyout button opens smaller chat window
// Note: clear button removes message more than 24hrs old from db
*/
namespace YAF.Controls
{
#region Using
using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using YAF.Classes;
using YAF.Classes.Data;
using YAF.Core;
using YAF.Core.Model;
using YAF.Core.Services;
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.Extensions;
using YAF.Types.Interfaces;
using YAF.Types.Models;
using YAF.Utils.Helpers;
#endregion
/// <summary>
/// The shout box.
/// </summary>
public partial class ShoutBox : BaseUserControl
{
#region Constructors and Destructors
#endregion
#region Properties
/// <summary>
/// Gets ShoutBoxMessages.
/// </summary>
public IEnumerable<DataRow> ShoutBoxMessages
{
get
{
return this.Get<YafDbBroker>().GetShoutBoxMessages(YafContext.Current.PageBoardID);
}
}
#endregion
#region Public Methods
/// <summary>
/// The data bind.
/// </summary>
public override void DataBind()
{
this.BindData();
base.DataBind();
}
#endregion
#region Methods
/// <summary>
/// Formats the Smilies on click string.
/// </summary>
/// <param name="code">The code.</param>
/// <param name="path">The path.</param>
/// <returns>
/// The format smilies on click string.
/// </returns>
protected static string FormatSmiliesOnClickString([NotNull] string code, [NotNull] string path)
{
code = Regex.Replace(code, "['\")(\\\\]", "\\$0");
string onClickScript = "insertsmiley('{0}','{1}');return false;".FormatWith(code, path);
return onClickScript;
}
/// <summary>
/// Changes The CollapsiblePanelState of the ShoutBox
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
protected void CollapsibleImageShoutBox_Click([NotNull] object sender, [NotNull] ImageClickEventArgs e)
{
this.DataBind();
}
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
protected override void OnPreRender([NotNull] EventArgs e)
{
this.CollapsibleImageShoutBox.DefaultState = (CollapsiblePanelState)this.Get<YafBoardSettings>().ShoutboxDefaultState;
base.OnPreRender(e);
}
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
{
if (!this.Get<YafBoardSettings>().ShowShoutbox
&& !this.Get<IPermissions>()
.Check(this.Get<YafBoardSettings>().ShoutboxViewPermissions))
{
return;
}
if (this.PageContext.IsAdmin)
{
this.btnClear.Visible = true;
}
this.shoutBoxPanel.Visible = true;
if (this.IsPostBack)
{
return;
}
this.btnFlyOut.Text = this.GetText("SHOUTBOX", "FLYOUT");
this.btnClear.Text = this.GetText("SHOUTBOX", "CLEAR");
this.btnButton.Text = this.GetText("SHOUTBOX", "SUBMIT");
this.FlyOutHolder.Visible = !YafControlSettings.Current.Popup;
this.CollapsibleImageShoutBox.Visible = !YafControlSettings.Current.Popup;
this.DataBind();
}
/// <summary>
/// Submit new Message
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Submit_Click([NotNull] object sender, [NotNull] EventArgs e)
{
string username = this.PageContext.PageUserName;
if (username != null && this.messageTextBox.Text != string.Empty)
{
LegacyDb.shoutbox_savemessage(
this.PageContext.PageBoardID,
this.messageTextBox.Text,
username,
this.PageContext.PageUserID,
this.Get<HttpRequestBase>().GetUserRealIPAddress());
this.Get<IDataCache>().Remove(Constants.Cache.Shoutbox);
}
this.DataBind();
this.messageTextBox.Text = string.Empty;
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager != null)
{
scriptManager.SetFocus(this.messageTextBox);
}
}
/// <summary>
/// Clears the ShoutBox
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Clear_Click([NotNull] object sender, [NotNull] EventArgs e)
{
LegacyDb.shoutbox_clearmessages(this.PageContext.PageBoardID);
// cleared... re-load from cache...
this.Get<IDataCache>().Remove(Constants.Cache.Shoutbox);
this.DataBind();
}
/// <summary>
/// Refreshes the ShoutBox
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Refresh_Click(object sender, EventArgs e)
{
this.DataBind();
}
/// <summary>
/// The bind data.
/// </summary>
private void BindData()
{
if (!this.shoutBoxPlaceHolder.Visible)
{
return;
}
this.shoutBoxRepeater.DataSource = this.ShoutBoxMessages;
if (this.Get<YafBoardSettings>().ShowShoutboxSmiles)
{
this.smiliesRepeater.DataSource = this.GetRepository<Smiley>().ListUnique(this.PageContext.PageBoardID);
}
}
#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 Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Tests.Common
{
public class MockScriptEngine : INonSharedRegionModule, IScriptModule, IScriptEngine
{
public IConfigSource ConfigSource { get; private set; }
public IConfig Config { get; private set; }
private Scene m_scene;
/// <summary>
/// Expose posted events to tests.
/// </summary>
public Dictionary<UUID, List<EventParams>> PostedEvents { get; private set; }
/// <summary>
/// A very primitive way of hooking text cose to a posed event.
/// </summary>
/// <remarks>
/// May be replaced with something that uses more original code in the future.
/// </remarks>
public event Action<UUID, EventParams> PostEventHook;
public void Initialise(IConfigSource source)
{
ConfigSource = source;
// Can set later on if required
Config = new IniConfig("MockScriptEngine", ConfigSource);
PostedEvents = new Dictionary<UUID, List<EventParams>>();
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.StackModuleInterface<IScriptModule>(this);
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
}
public string Name { get { return "Mock Script Engine"; } }
public string ScriptEngineName { get { return Name; } }
public Type ReplaceableInterface { get { return null; } }
#pragma warning disable 0067
public event ScriptRemoved OnScriptRemoved;
public event ObjectRemoved OnObjectRemoved;
#pragma warning restore 0067
public string GetXMLState(UUID itemID)
{
throw new System.NotImplementedException();
}
public bool SetXMLState(UUID itemID, string xml)
{
throw new System.NotImplementedException();
}
public bool PostScriptEvent(UUID itemID, string name, object[] args)
{
// Console.WriteLine("Posting event {0} for {1}", name, itemID);
return PostScriptEvent(itemID, new EventParams(name, args, null));
}
public bool PostScriptEvent(UUID itemID, EventParams evParams)
{
List<EventParams> eventsForItem;
if (!PostedEvents.ContainsKey(itemID))
{
eventsForItem = new List<EventParams>();
PostedEvents.Add(itemID, eventsForItem);
}
else
{
eventsForItem = PostedEvents[itemID];
}
eventsForItem.Add(evParams);
if (PostEventHook != null)
PostEventHook(itemID, evParams);
return true;
}
public bool PostObjectEvent(uint localID, EventParams evParams)
{
return PostObjectEvent(m_scene.GetSceneObjectPart(localID), evParams);
}
public bool PostObjectEvent(UUID itemID, string name, object[] args)
{
return PostObjectEvent(m_scene.GetSceneObjectPart(itemID), new EventParams(name, args, null));
}
private bool PostObjectEvent(SceneObjectPart part, EventParams evParams)
{
foreach (TaskInventoryItem item in part.Inventory.GetInventoryItems(InventoryType.LSL))
PostScriptEvent(item.ItemID, evParams);
return true;
}
public void SuspendScript(UUID itemID)
{
throw new System.NotImplementedException();
}
public void ResumeScript(UUID itemID)
{
throw new System.NotImplementedException();
}
public ArrayList GetScriptErrors(UUID itemID)
{
throw new System.NotImplementedException();
}
public bool HasScript(UUID itemID, out bool running)
{
throw new System.NotImplementedException();
}
public bool GetScriptState(UUID itemID)
{
throw new System.NotImplementedException();
}
public void SaveAllState()
{
throw new System.NotImplementedException();
}
public void StartProcessing()
{
throw new System.NotImplementedException();
}
public float GetScriptExecutionTime(List<UUID> itemIDs)
{
throw new System.NotImplementedException();
}
public Dictionary<uint, float> GetObjectScriptsExecutionTimes()
{
throw new System.NotImplementedException();
}
public IScriptWorkItem QueueEventHandler(object parms)
{
throw new System.NotImplementedException();
}
public DetectParams GetDetectParams(UUID item, int number)
{
throw new System.NotImplementedException();
}
public void SetMinEventDelay(UUID itemID, double delay)
{
throw new System.NotImplementedException();
}
public int GetStartParameter(UUID itemID)
{
throw new System.NotImplementedException();
}
public void SetScriptState(UUID itemID, bool state)
{
throw new System.NotImplementedException();
}
public void SetState(UUID itemID, string newState)
{
throw new System.NotImplementedException();
}
public void ApiResetScript(UUID itemID)
{
throw new System.NotImplementedException();
}
public void ResetScript(UUID itemID)
{
throw new System.NotImplementedException();
}
public IScriptApi GetApi(UUID itemID, string name)
{
throw new System.NotImplementedException();
}
public Scene World { get { return m_scene; } }
public IScriptModule ScriptModule { get { return this; } }
public string ScriptEnginePath { get { throw new System.NotImplementedException(); } }
public string ScriptClassName { get { throw new System.NotImplementedException(); } }
public string ScriptBaseClassName { get { throw new System.NotImplementedException(); } }
public string[] ScriptReferencedAssemblies { get { throw new System.NotImplementedException(); } }
public ParameterInfo[] ScriptBaseClassParameters { get { throw new System.NotImplementedException(); } }
public void ClearPostedEvents()
{
PostedEvents.Clear();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Internal.IL;
using Debug = System.Diagnostics.Debug;
using Internal.IL.Stubs;
namespace Internal.TypeSystem.Interop
{
public static class MarshalHelpers
{
/// <summary>
/// Returns true if this is a type that doesn't require marshalling.
/// </summary>
public static bool IsBlittableType(TypeDesc type)
{
type = type.UnderlyingType;
if (type.IsValueType)
{
if (type.IsPrimitive)
{
// All primitive types except char and bool are blittable
TypeFlags category = type.Category;
if (category == TypeFlags.Boolean || category == TypeFlags.Char)
return false;
return true;
}
foreach (FieldDesc field in type.GetFields())
{
if (field.IsStatic)
continue;
TypeDesc fieldType = field.FieldType;
// TODO: we should also reject fields that specify custom marshalling
if (!MarshalHelpers.IsBlittableType(fieldType))
{
// This field can still be blittable if it's a Char and marshals as Unicode
var owningType = field.OwningType as MetadataType;
if (owningType == null)
return false;
if (fieldType.Category != TypeFlags.Char ||
owningType.PInvokeStringFormat == PInvokeStringFormat.AnsiClass)
return false;
}
}
return true;
}
if (type.IsPointer || type.IsFunctionPointer)
return true;
return false;
}
public static bool IsStructMarshallingRequired(TypeDesc typeDesc)
{
if (typeDesc is ByRefType)
{
typeDesc = typeDesc.GetParameterType();
}
if (typeDesc.Category != TypeFlags.ValueType)
return false;
MetadataType type = typeDesc as MetadataType;
if (type == null)
{
return false;
}
//
// For struct marshalling it is required to have either Sequential
// or Explicit layout. For Auto layout the P/Invoke marshalling code
// will throw appropriate error message.
//
if (!type.IsSequentialLayout && !type.IsExplicitLayout)
return false;
// If it is not blittable we will need struct marshalling
return !IsBlittableType(type);
}
/// <summary>
/// Returns true if the PInvoke target should be resolved lazily.
/// </summary>
public static bool UseLazyResolution(MethodDesc method, string importModule, PInvokeILEmitterConfiguration configuration)
{
bool? forceLazyResolution = configuration.ForceLazyResolution;
if (forceLazyResolution.HasValue)
return forceLazyResolution.Value;
// In multi-module library mode, the WinRT p/invokes in System.Private.Interop cause linker failures
// since we don't link against the OS libraries containing those APIs. Force them to be lazy.
// See https://github.com/dotnet/corert/issues/2601
string assemblySimpleName = ((IAssemblyDesc)((MetadataType)method.OwningType).Module).GetName().Name;
if (assemblySimpleName == "System.Private.Interop")
{
return true;
}
// Determine whether this call should be made through a lazy resolution or a static reference
// Eventually, this should be controlled by a custom attribute (or an extension to the metadata format).
if (importModule == "[MRT]" || importModule == "*")
return false;
if (method.Context.Target.IsWindows)
{
return !importModule.StartsWith("api-ms-win-");
}
else
{
// Account for System.Private.CoreLib.Native / System.Globalization.Native / System.Native / etc
return !importModule.StartsWith("System.");
}
}
internal static TypeDesc GetNativeMethodParameterType(TypeDesc type, MarshalAsDescriptor marshalAs, InteropStateManager interopStateManager, bool isReturn, bool isAnsi)
{
MarshallerKind elementMarshallerKind;
MarshallerKind marshallerKind = MarshalHelpers.GetMarshallerKind(type,
marshalAs,
isReturn,
isAnsi,
MarshallerType.Argument,
out elementMarshallerKind);
return GetNativeTypeFromMarshallerKind(type,
marshallerKind,
elementMarshallerKind,
interopStateManager,
marshalAs);
}
internal static TypeDesc GetNativeStructFieldType(TypeDesc type, MarshalAsDescriptor marshalAs, InteropStateManager interopStateManager, bool isAnsi)
{
MarshallerKind elementMarshallerKind;
MarshallerKind marshallerKind = MarshalHelpers.GetMarshallerKind(type,
marshalAs,
false, /* isReturn */
isAnsi, /* isAnsi */
MarshallerType.Field,
out elementMarshallerKind);
return GetNativeTypeFromMarshallerKind(type,
marshallerKind,
elementMarshallerKind,
interopStateManager,
marshalAs);
}
internal static TypeDesc GetNativeTypeFromMarshallerKind(TypeDesc type,
MarshallerKind kind,
MarshallerKind elementMarshallerKind,
InteropStateManager interopStateManager,
MarshalAsDescriptor marshalAs,
bool isArrayElement = false)
{
TypeSystemContext context = type.Context;
NativeTypeKind nativeType = NativeTypeKind.Invalid;
if (marshalAs != null)
{
nativeType = isArrayElement ? marshalAs.ArraySubType : marshalAs.Type;
}
switch (kind)
{
case MarshallerKind.BlittableValue:
{
switch (nativeType)
{
case NativeTypeKind.I1:
return context.GetWellKnownType(WellKnownType.SByte);
case NativeTypeKind.U1:
return context.GetWellKnownType(WellKnownType.Byte);
case NativeTypeKind.I2:
return context.GetWellKnownType(WellKnownType.Int16);
case NativeTypeKind.U2:
return context.GetWellKnownType(WellKnownType.UInt16);
case NativeTypeKind.I4:
return context.GetWellKnownType(WellKnownType.Int32);
case NativeTypeKind.U4:
return context.GetWellKnownType(WellKnownType.UInt32);
case NativeTypeKind.I8:
return context.GetWellKnownType(WellKnownType.Int64);
case NativeTypeKind.U8:
return context.GetWellKnownType(WellKnownType.UInt64);
case NativeTypeKind.R4:
return context.GetWellKnownType(WellKnownType.Single);
case NativeTypeKind.R8:
return context.GetWellKnownType(WellKnownType.Double);
default:
return type.UnderlyingType;
}
}
case MarshallerKind.Bool:
return context.GetWellKnownType(WellKnownType.Int32);
case MarshallerKind.CBool:
return context.GetWellKnownType(WellKnownType.Byte);
case MarshallerKind.Enum:
case MarshallerKind.BlittableStruct:
case MarshallerKind.Decimal:
case MarshallerKind.VoidReturn:
return type;
case MarshallerKind.Struct:
return interopStateManager.GetStructMarshallingNativeType((MetadataType)type);
case MarshallerKind.BlittableStructPtr:
return type.MakePointerType();
case MarshallerKind.HandleRef:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.UnicodeChar:
if (nativeType == NativeTypeKind.U2)
return context.GetWellKnownType(WellKnownType.UInt16);
else
return context.GetWellKnownType(WellKnownType.Int16);
case MarshallerKind.OleDateTime:
return context.GetWellKnownType(WellKnownType.Double);
case MarshallerKind.SafeHandle:
case MarshallerKind.CriticalHandle:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.UnicodeString:
case MarshallerKind.UnicodeStringBuilder:
return context.GetWellKnownType(WellKnownType.Char).MakePointerType();
case MarshallerKind.AnsiString:
case MarshallerKind.AnsiStringBuilder:
return context.GetWellKnownType(WellKnownType.Byte).MakePointerType();
case MarshallerKind.BlittableArray:
case MarshallerKind.Array:
case MarshallerKind.AnsiCharArray:
{
ArrayType arrayType = type as ArrayType;
Debug.Assert(arrayType != null, "Expecting array");
//
// We need to construct the unsafe array from the right unsafe array element type
//
TypeDesc elementNativeType = GetNativeTypeFromMarshallerKind(
arrayType.ElementType,
elementMarshallerKind,
MarshallerKind.Unknown,
interopStateManager,
marshalAs,
isArrayElement: true);
return elementNativeType.MakePointerType();
}
case MarshallerKind.AnsiChar:
return context.GetWellKnownType(WellKnownType.Byte);
case MarshallerKind.FunctionPointer:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.ByValUnicodeString:
case MarshallerKind.ByValAnsiString:
{
var inlineArrayCandidate = GetInlineArrayCandidate(context.GetWellKnownType(WellKnownType.Char), elementMarshallerKind, interopStateManager, marshalAs);
return interopStateManager.GetInlineArrayType(inlineArrayCandidate);
}
case MarshallerKind.ByValAnsiCharArray:
case MarshallerKind.ByValArray:
{
ArrayType arrayType = type as ArrayType;
Debug.Assert(arrayType != null, "Expecting array");
var inlineArrayCandidate = GetInlineArrayCandidate(arrayType.ElementType, elementMarshallerKind, interopStateManager, marshalAs);
return interopStateManager.GetInlineArrayType(inlineArrayCandidate);
}
case MarshallerKind.Unknown:
default:
throw new NotSupportedException();
}
}
internal static InlineArrayCandidate GetInlineArrayCandidate(TypeDesc managedElementType, MarshallerKind elementMarshallerKind, InteropStateManager interopStateManager, MarshalAsDescriptor marshalAs)
{
TypeDesc nativeType = GetNativeTypeFromMarshallerKind(
managedElementType,
elementMarshallerKind,
MarshallerKind.Unknown,
interopStateManager,
null);
var elementNativeType = nativeType as MetadataType;
if (elementNativeType == null)
{
Debug.Assert(nativeType is PointerType);
// If it is a pointer type we will create InlineArray for IntPtr
elementNativeType = (MetadataType)managedElementType.Context.GetWellKnownType(WellKnownType.IntPtr);
}
Debug.Assert(marshalAs != null && marshalAs.SizeConst.HasValue);
// if SizeConst is not specified, we will default to 1.
// the marshaller will throw appropriate exception
uint size = 1;
if (marshalAs.SizeConst.HasValue)
{
size = marshalAs.SizeConst.Value;
}
return new InlineArrayCandidate(elementNativeType, size);
}
internal static MarshallerKind GetMarshallerKind(
TypeDesc type,
MarshalAsDescriptor marshalAs,
bool isReturn,
bool isAnsi,
MarshallerType marshallerType,
out MarshallerKind elementMarshallerKind)
{
if (type.IsByRef)
{
type = type.GetParameterType();
}
TypeSystemContext context = type.Context;
NativeTypeKind nativeType = NativeTypeKind.Invalid;
bool isField = marshallerType == MarshallerType.Field;
if (marshalAs != null)
nativeType = (NativeTypeKind)marshalAs.Type;
elementMarshallerKind = MarshallerKind.Invalid;
//
// Determine MarshalerKind
//
// This mostly resembles desktop CLR and .NET Native code as we need to match their behavior
//
if (type.IsPrimitive)
{
switch (type.Category)
{
case TypeFlags.Void:
return MarshallerKind.VoidReturn;
case TypeFlags.Boolean:
switch (nativeType)
{
case NativeTypeKind.Invalid:
case NativeTypeKind.Boolean:
return MarshallerKind.Bool;
case NativeTypeKind.U1:
case NativeTypeKind.I1:
return MarshallerKind.CBool;
default:
return MarshallerKind.Invalid;
}
case TypeFlags.Char:
switch (nativeType)
{
case NativeTypeKind.I1:
case NativeTypeKind.U1:
return MarshallerKind.AnsiChar;
case NativeTypeKind.I2:
case NativeTypeKind.U2:
return MarshallerKind.UnicodeChar;
case NativeTypeKind.Invalid:
if (isAnsi)
return MarshallerKind.AnsiChar;
else
return MarshallerKind.UnicodeChar;
default:
return MarshallerKind.Invalid;
}
case TypeFlags.SByte:
case TypeFlags.Byte:
if (nativeType == NativeTypeKind.I1 || nativeType == NativeTypeKind.U1 || nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Int16:
case TypeFlags.UInt16:
if (nativeType == NativeTypeKind.I2 || nativeType == NativeTypeKind.U2 || nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Int32:
case TypeFlags.UInt32:
if (nativeType == NativeTypeKind.I4 || nativeType == NativeTypeKind.U4 || nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Int64:
case TypeFlags.UInt64:
if (nativeType == NativeTypeKind.I8 || nativeType == NativeTypeKind.U8 || nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
if (nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Single:
if (nativeType == NativeTypeKind.R4 || nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Double:
if (nativeType == NativeTypeKind.R8 || nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
default:
return MarshallerKind.Invalid;
}
}
else if (type.IsValueType)
{
if (type.IsEnum)
return MarshallerKind.Enum;
if (InteropTypes.IsSystemDateTime(context, type))
{
if (nativeType == NativeTypeKind.Invalid ||
nativeType == NativeTypeKind.Struct)
return MarshallerKind.OleDateTime;
else
return MarshallerKind.Invalid;
}
/*
TODO: Bring HandleRef to CoreLib
https://github.com/dotnet/corert/issues/2570
else if (context.IsHandleRef(type))
{
if (nativeType == NativeType.Invalid)
return MarshallerKind.HandleRef;
else
return MarshallerKind.Invalid;
}
*/
switch (nativeType)
{
case NativeTypeKind.Invalid:
case NativeTypeKind.Struct:
if (InteropTypes.IsSystemDecimal(context, type))
return MarshallerKind.Decimal;
break;
case NativeTypeKind.LPStruct:
if (InteropTypes.IsSystemGuid(context, type) ||
InteropTypes.IsSystemDecimal(context, type))
{
if (isField || isReturn)
return MarshallerKind.Invalid;
else
return MarshallerKind.BlittableStructPtr;
}
break;
default:
return MarshallerKind.Invalid;
}
if (type is MetadataType)
{
MetadataType metadataType = (MetadataType)type;
// the struct type need to be either sequential or explicit. If it is
// auto layout we will throw exception.
if (!metadataType.IsSequentialLayout && !metadataType.IsExplicitLayout)
{
throw new InvalidProgramException("The specified structure " + metadataType.Name + " has invalid StructLayout information. It must be either Sequential or Explicit.");
}
}
if (MarshalHelpers.IsBlittableType(type))
{
return MarshallerKind.BlittableStruct;
}
else
{
return MarshallerKind.Struct;
}
}
else // !ValueType
{
if (type.Category == TypeFlags.Class)
{
if (type.IsString)
{
switch (nativeType)
{
case NativeTypeKind.LPWStr:
return MarshallerKind.UnicodeString;
case NativeTypeKind.LPStr:
return MarshallerKind.AnsiString;
case NativeTypeKind.LPTStr:
return MarshallerKind.UnicodeString;
case NativeTypeKind.ByValTStr:
if (isAnsi)
{
elementMarshallerKind = MarshallerKind.AnsiChar;
return MarshallerKind.ByValAnsiString;
}
else
{
elementMarshallerKind = MarshallerKind.UnicodeChar;
return MarshallerKind.ByValUnicodeString;
}
case NativeTypeKind.Invalid:
if (isAnsi)
return MarshallerKind.AnsiString;
else
return MarshallerKind.UnicodeString;
default:
return MarshallerKind.Invalid;
}
}
else if (type.IsDelegate)
{
if (nativeType == NativeTypeKind.Invalid || nativeType == NativeTypeKind.Func)
return MarshallerKind.FunctionPointer;
else
return MarshallerKind.Invalid;
}
else if (type.IsObject)
{
if (nativeType == NativeTypeKind.Invalid)
return MarshallerKind.Variant;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsStringBuilder(context, type))
{
switch (nativeType)
{
case NativeTypeKind.Invalid:
if (isAnsi)
{
return MarshallerKind.AnsiStringBuilder;
}
else
{
return MarshallerKind.UnicodeStringBuilder;
}
case NativeTypeKind.LPStr:
return MarshallerKind.AnsiStringBuilder;
case NativeTypeKind.LPWStr:
return MarshallerKind.UnicodeStringBuilder;
default:
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsSafeHandle(context, type))
{
if (nativeType == NativeTypeKind.Invalid)
return MarshallerKind.SafeHandle;
else
return MarshallerKind.Invalid;
}
/*
TODO: Bring CriticalHandle to CoreLib
https://github.com/dotnet/corert/issues/2570
else if (InteropTypes.IsCriticalHandle(context, type))
{
if (nativeType != NativeType.Invalid || isField)
{
return MarshallerKind.Invalid;
}
else
{
return MarshallerKind.CriticalHandle;
}
}
*/
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsSystemArray(context, type))
{
return MarshallerKind.Invalid;
}
else if (type.IsSzArray)
{
if (nativeType == NativeTypeKind.Invalid)
nativeType = NativeTypeKind.Array;
switch (nativeType)
{
case NativeTypeKind.Array:
{
if (isField || isReturn)
return MarshallerKind.Invalid;
var arrayType = (ArrayType)type;
elementMarshallerKind = GetArrayElementMarshallerKind(
arrayType,
marshalAs,
isAnsi);
// If element is invalid type, the array itself is invalid
if (elementMarshallerKind == MarshallerKind.Invalid)
return MarshallerKind.Invalid;
if (elementMarshallerKind == MarshallerKind.AnsiChar)
return MarshallerKind.AnsiCharArray;
else if (elementMarshallerKind == MarshallerKind.UnicodeChar // Arrays of unicode char should be marshalled as blittable arrays
|| elementMarshallerKind == MarshallerKind.Enum
|| elementMarshallerKind == MarshallerKind.BlittableValue)
return MarshallerKind.BlittableArray;
else
return MarshallerKind.Array;
}
case NativeTypeKind.ByValArray: // fix sized array
{
var arrayType = (ArrayType)type;
elementMarshallerKind = GetArrayElementMarshallerKind(
arrayType,
marshalAs,
isAnsi);
// If element is invalid type, the array itself is invalid
if (elementMarshallerKind == MarshallerKind.Invalid)
return MarshallerKind.Invalid;
if (elementMarshallerKind == MarshallerKind.AnsiChar)
return MarshallerKind.ByValAnsiCharArray;
else
return MarshallerKind.ByValArray;
}
default:
return MarshallerKind.Invalid;
}
}
else if (type.Category == TypeFlags.Pointer)
{
//
// @TODO - add checks for the pointee type in case the pointee type is not blittable
// C# already does this and will emit compilation errors (can't declare pointers to
// managed type).
//
if (nativeType == NativeTypeKind.Invalid)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
}
}
return MarshallerKind.Invalid;
}
private static MarshallerKind GetArrayElementMarshallerKind(
ArrayType arrayType,
MarshalAsDescriptor marshalAs,
bool isAnsi)
{
TypeDesc elementType = arrayType.ElementType;
NativeTypeKind nativeType = NativeTypeKind.Invalid;
TypeSystemContext context = arrayType.Context;
if (marshalAs != null)
nativeType = (NativeTypeKind)marshalAs.ArraySubType;
if (elementType.IsPrimitive)
{
switch (elementType.Category)
{
case TypeFlags.Char:
switch (nativeType)
{
case NativeTypeKind.I1:
case NativeTypeKind.U1:
return MarshallerKind.AnsiChar;
case NativeTypeKind.I2:
case NativeTypeKind.U2:
return MarshallerKind.UnicodeChar;
default:
if (isAnsi)
return MarshallerKind.AnsiChar;
else
return MarshallerKind.UnicodeChar;
}
case TypeFlags.Boolean:
switch (nativeType)
{
case NativeTypeKind.Boolean:
return MarshallerKind.Bool;
case NativeTypeKind.I1:
case NativeTypeKind.U1:
return MarshallerKind.CBool;
case NativeTypeKind.Invalid:
default:
return MarshallerKind.Bool;
}
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
return MarshallerKind.BlittableValue;
case TypeFlags.Void:
return MarshallerKind.Invalid;
case TypeFlags.SByte:
case TypeFlags.Int16:
case TypeFlags.Int32:
case TypeFlags.Int64:
case TypeFlags.Byte:
case TypeFlags.UInt16:
case TypeFlags.UInt32:
case TypeFlags.UInt64:
case TypeFlags.Single:
case TypeFlags.Double:
return MarshallerKind.BlittableValue;
default:
return MarshallerKind.Invalid;
}
}
else if (elementType.IsValueType)
{
if (elementType.IsEnum)
return MarshallerKind.Enum;
if (InteropTypes.IsSystemDecimal(context, elementType))
{
switch (nativeType)
{
case NativeTypeKind.Invalid:
case NativeTypeKind.Struct:
return MarshallerKind.Decimal;
case NativeTypeKind.LPStruct:
return MarshallerKind.BlittableStructPtr;
default:
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsSystemGuid(context, elementType))
{
switch (nativeType)
{
case NativeTypeKind.Invalid:
case NativeTypeKind.Struct:
return MarshallerKind.BlittableValue;
case NativeTypeKind.LPStruct:
return MarshallerKind.BlittableStructPtr;
default:
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsSystemDateTime(context, elementType))
{
if (nativeType == NativeTypeKind.Invalid ||
nativeType == NativeTypeKind.Struct)
{
return MarshallerKind.OleDateTime;
}
else
{
return MarshallerKind.Invalid;
}
}
/*
TODO: Bring HandleRef to CoreLib
https://github.com/dotnet/corert/issues/2570
else if (InteropTypes.IsHandleRef(context, elementType))
{
return MarshallerKind.HandleRef;
}
*/
else
{
if (MarshalHelpers.IsBlittableType(elementType))
{
switch (nativeType)
{
case NativeTypeKind.Invalid:
case NativeTypeKind.Struct:
return MarshallerKind.BlittableStruct;
default:
return MarshallerKind.Invalid;
}
}
else
{
// TODO: Differentiate between struct and Union, we only need to support struct not union here
return MarshallerKind.Struct;
}
}
}
else // !valueType
{
if (elementType.IsString)
{
switch (nativeType)
{
case NativeTypeKind.Invalid:
if (isAnsi)
return MarshallerKind.AnsiString;
else
return MarshallerKind.UnicodeString;
case NativeTypeKind.LPStr:
return MarshallerKind.AnsiString;
case NativeTypeKind.LPWStr:
return MarshallerKind.UnicodeString;
default:
return MarshallerKind.Invalid;
}
}
if (elementType.IsObject)
{
if (nativeType == NativeTypeKind.Invalid)
return MarshallerKind.Variant;
else
return MarshallerKind.Invalid;
}
if (elementType.IsSzArray)
{
return MarshallerKind.Invalid;
}
if (elementType.IsPointer)
{
return MarshallerKind.Invalid;
}
if (InteropTypes.IsSafeHandle(context, elementType))
{
return MarshallerKind.Invalid;
}
/*
TODO: Bring CriticalHandle to CoreLib
https://github.com/dotnet/corert/issues/2570
if (pInvokeData.IsCriticalHandle(elementType))
{
return MarshallerKind.Invalid;
}
*/
}
return MarshallerKind.Invalid;
}
//TODO: https://github.com/dotnet/corert/issues/2675
// This exception messages need to localized
// TODO: Log as warning
public static MethodIL EmitExceptionBody(string message, MethodDesc method)
{
ILEmitter emitter = new ILEmitter();
TypeSystemContext context = method.Context;
MethodSignature ctorSignature = new MethodSignature(0, 0, context.GetWellKnownType(WellKnownType.Void),
new TypeDesc[] { context.GetWellKnownType(WellKnownType.String) });
MethodDesc exceptionCtor = method.Context.GetWellKnownType(WellKnownType.Exception).GetKnownMethod(".ctor", ctorSignature);
ILCodeStream codeStream = emitter.NewCodeStream();
codeStream.Emit(ILOpcode.ldstr, emitter.NewToken(message));
codeStream.Emit(ILOpcode.newobj, emitter.NewToken(exceptionCtor));
codeStream.Emit(ILOpcode.throw_);
codeStream.Emit(ILOpcode.ret);
return new PInvokeILStubMethodIL((ILStubMethodIL)emitter.Link(method), true);
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
namespace WixSharp
{
public static partial class Win32
{
[DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern long GetClassName(IntPtr hwnd, StringBuilder lpClassName, long nMaxCount);
[DllImport("user32.dll")]
internal static extern bool SetCursorPos(int X, int Y);
// [DllImport("user32.dll", SetLastError = true)]
// public static extern IntPtr FindWindow(string className, string windowTitle);
// [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
// internal static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
// [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
// internal static extern int GetWindowTextLength(IntPtr hWnd);
delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);
[Flags]
enum MouseEventFlags
{
LEFTDOWN = 0x00000002,
LEFTUP = 0x00000004,
MIDDLEDOWN = 0x00000020,
MIDDLEUP = 0x00000040,
MOVE = 0x00000001,
ABSOLUTE = 0x00008000,
RIGHTDOWN = 0x00000008,
RIGHTUP = 0x00000010
}
[DllImport("user32.dll")]
internal static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
static string GetWindowClass(IntPtr hWnd)
{
var class_name = new StringBuilder(1024);
var t = GetClassName(hWnd, class_name, class_name.Capacity);
return class_name.ToString();
}
// [DllImport("user32.dll")]
// internal static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
// public static string GetWindowText(IntPtr wnd)
// {
// int length = GetWindowTextLength(wnd);
// var sb = new StringBuilder(length + 1);
// GetWindowText(wnd, sb, sb.Capacity);
// return sb.ToString();
// }
// [StructLayout(LayoutKind.Sequential)]
// public struct RECT
// {
// public int Left;
// public int Top;
// public int Right;
// public int Bottom;
// }
static void FireMouseClick(int x, int y)
{
SetCursorPos(x, y);
mouse_event((uint)MouseEventFlags.LEFTDOWN, 0, 0, 0, 0);
mouse_event((uint)MouseEventFlags.LEFTUP, 0, 0, 0, 0);
}
static RECT GetTaskbarRect()
{
IntPtr taskbar = GetTaskbarWindow();
RECT r;
GetWindowRect(taskbar, out r);
return r;
}
static int ContentHEnd(this Bitmap image)
{
int half_hight = image.Height / 2;
Color? curent_color = null;
int test_point = image.Width - 1;
for (; test_point >= 0; test_point--)
{
Color new_color = image.GetPixel(test_point, half_hight);
if (curent_color.HasValue && new_color != curent_color)
break;
curent_color = new_color;
}
return test_point;
}
static Bitmap HCrop(this Bitmap image, int left, int right)
{
var section_rect = new Rectangle(left,
0,
image.Width - left - right,
image.Height);
return image.Clone(section_rect, image.PixelFormat);
}
static Bitmap GetHSquareSection(this Bitmap image, int index, int? sectionWidth = null)
{
var section_rect = new Rectangle(sectionWidth ?? image.Height * index,
0,
image.Height,
image.Height);
return image.Clone(section_rect, image.PixelFormat);
}
static IntPtr GetTaskbarWindow()
{
var hwndTrayWnd = FindWindow("Shell_TrayWnd", null);
IntPtr taskbar = IntPtr.Zero;
EnumChildWindows(hwndTrayWnd, delegate (IntPtr hWnd, IntPtr param)
{
var name = GetWindowClass(hWnd);
// Debug.WriteLine(name);
if (name == "MSTaskListWClass")
{
taskbar = hWnd;
return false;
}
return true;
}, IntPtr.Zero);
return taskbar;
}
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);
[DllImport("gdi32.dll")]
static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);
[DllImport("user32.dll")]
static extern int GetWindowRgn(IntPtr hWnd, IntPtr hRgn);
static Bitmap GetWindowBitmap(IntPtr hwnd)
{
RECT rc;
GetWindowRect(hwnd, out rc);
Bitmap bmp = new Bitmap(rc.Right - rc.Left, rc.Bottom - rc.Top, PixelFormat.Format32bppArgb);
Graphics gfxBmp = Graphics.FromImage(bmp);
IntPtr hdcBitmap;
try
{
hdcBitmap = gfxBmp.GetHdc();
}
catch
{
return null;
}
bool succeeded = PrintWindow(hwnd, hdcBitmap, 0);
gfxBmp.ReleaseHdc(hdcBitmap);
if (!succeeded)
{
gfxBmp.FillRectangle(new SolidBrush(Color.Gray), new Rectangle(Point.Empty, bmp.Size));
}
IntPtr hRgn = CreateRectRgn(0, 0, 0, 0);
GetWindowRgn(hwnd, hRgn);
Region region = Region.FromHrgn(hRgn);//err here once
if (!region.IsEmpty(gfxBmp))
{
gfxBmp.ExcludeClip(region);
gfxBmp.Clear(Color.Transparent);
}
gfxBmp.Dispose();
return bmp;
}
static void StartMonitoringTaskbarForUAC()
{
Win32.RECT? taskbarLastItemRectangle = null;
#pragma warning disable 8321
bool ChechForUACTaskbarItem()
{
Bitmap image = Win32.GetWindowBitmap(Win32.GetTaskbarWindow());
var rect = Win32.GetTaskbarRect();
int item_size = image.Height; // it's roughly square
int item_right = image.ContentHEnd();
int item_left_offset = item_right - item_size;
int item_right_offset = image.Width - item_right;
image = image.HCrop(item_left_offset, item_right_offset);
rect.Left += item_left_offset;
rect.Right -= item_right_offset;
if (taskbarLastItemRectangle.HasValue)
{
if (Math.Abs(rect.Left - taskbarLastItemRectangle.Value.Left) >= item_size)
{
// new item has appeared on the taskbar
var half_size = item_size / 2;
// MessageBox.Show("Please activate the UAC prompt on the taskbar.");
Win32.FireMouseClick(rect.Left + half_size, rect.Top + half_size);
return true;
}
}
taskbarLastItemRectangle = rect;
return false;
}
ThreadPool.QueueUserWorkItem(x =>
{
bool done = false;
while (!done)
{
// if (ChechForUACTaskbarItem())
// break;
Thread.Sleep(1000);
Win32.SetForegroundWindow(Win32.GetTaskbarWindow());
}
});
}
static int count = 0;
static void KeepTaskbarFocused()
{
ThreadPool.QueueUserWorkItem(x =>
{
bool done = false;
while (!done)
{
Thread.Sleep(1000);
count++;
if (count < 4)
{
Win32.SetActiveWindow(Win32.GetTaskbarWindow());
// Win32.SetForegroundWindow(Win32.GetTaskbarWindow());
}
}
});
}
}
}
| |
// 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;
namespace System.Collections.ObjectModel
{
[Serializable]
[DebuggerTypeProxy(typeof(ICollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class ReadOnlyCollection<T> : IList<T>, IList, IReadOnlyList<T>
{
private readonly IList<T> list; // Do not rename (binary serialization)
public ReadOnlyCollection(IList<T> list)
{
if (list == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
}
this.list = list;
}
public int Count => list.Count;
public T this[int index] => list[index];
public bool Contains(T value)
{
return list.Contains(value);
}
public void CopyTo(T[] array, int index)
{
list.CopyTo(array, index);
}
public IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
}
public int IndexOf(T value)
{
return list.IndexOf(value);
}
protected IList<T> Items => list;
bool ICollection<T>.IsReadOnly => true;
T IList<T>.this[int index]
{
get => list[index];
set => ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void ICollection<T>.Add(T value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void ICollection<T>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IList<T>.Insert(int index, T value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool ICollection<T>.Remove(T value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
void IList<T>.RemoveAt(int index)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)list).GetEnumerator();
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => list is ICollection coll ? coll.SyncRoot : this;
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
if (array is T[] items)
{
list.CopyTo(items, index);
}
else
{
//
// Catch the obvious case assignment will fail.
// We can't find all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType()!;
Type sourceType = typeof(T);
if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType)))
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
//
// We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
//
object?[]? objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = list.Count;
try
{
for (int i = 0; i < count; i++)
{
objects[index++] = list[i];
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool IList.IsFixedSize => true;
bool IList.IsReadOnly => true;
object? IList.this[int index]
{
get => list[index];
set => ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
int IList.Add(object? value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return -1;
}
void IList.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
private static bool IsCompatibleObject(object? value)
{
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return (value is T) || (value == null && default(T)! == null);
}
bool IList.Contains(object? value)
{
if (IsCompatibleObject(value))
{
return Contains((T)value!);
}
return false;
}
int IList.IndexOf(object? value)
{
if (IsCompatibleObject(value))
{
return IndexOf((T)value!);
}
return -1;
}
void IList.Insert(int index, object? value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IList.Remove(object? value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IList.RemoveAt(int index)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
namespace GodLesZ.Library.Controls {
/// <summary>
/// ColumnComparer is the workhorse for all comparison between two values of a particular column.
/// If the column has a specific comparer, use that to compare the values. Otherwise, do
/// a case insensitive string compare of the string representations of the values.
/// </summary>
/// <remarks><para>This class inherits from both IComparer and its generic counterpart
/// so that it can be used on untyped and typed collections.</para></remarks>
public class ColumnComparer : IComparer, IComparer<OLVListItem> {
/// <summary>
/// Create a ColumnComparer that will order the rows in a list view according
/// to the values in a given column
/// </summary>
/// <param name="col">The column whose values will be compared</param>
/// <param name="order">The ordering for column values</param>
public ColumnComparer(OLVColumn col, SortOrder order) {
this.mColumn = col;
this.mSortOrder = order;
}
/// <summary>
/// Create a ColumnComparer that will order the rows in a list view according
/// to the values in a given column, and by a secondary column if the primary
/// column is equal.
/// </summary>
/// <param name="col">The column whose values will be compared</param>
/// <param name="order">The ordering for column values</param>
/// <param name="col2">The column whose values will be compared for secondary sorting</param>
/// <param name="order2">The ordering for secondary column values</param>
public ColumnComparer(OLVColumn col, SortOrder order, OLVColumn col2, SortOrder order2)
: this(col, order) {
// There is no point in secondary sorting on the same column
if (col != col2)
mSecondComparer = new ColumnComparer(col2, order2);
}
/// <summary>
/// Compare two rows
/// </summary>
/// <param name="x">row1</param>
/// <param name="y">row2</param>
/// <returns>An ordering indication: -1, 0, 1</returns>
public int Compare(object x, object y) {
return this.Compare((OLVListItem)x, (OLVListItem)y);
}
/// <summary>
/// Compare two rows
/// </summary>
/// <param name="x">row1</param>
/// <param name="y">row2</param>
/// <returns>An ordering indication: -1, 0, 1</returns>
public int Compare(OLVListItem x, OLVListItem y) {
if (this.mSortOrder == SortOrder.None)
return 0;
int result = 0;
object x1 = this.mColumn.GetValue(x.RowObject);
object y1 = this.mColumn.GetValue(y.RowObject);
// Handle nulls. Null values come last
bool xIsNull = (x1 == null || x1 == System.DBNull.Value);
bool yIsNull = (y1 == null || y1 == System.DBNull.Value);
if (xIsNull || yIsNull) {
if (xIsNull && yIsNull)
result = 0;
else
result = (xIsNull ? -1 : 1);
} else {
result = this.CompareValues(x1, y1);
}
if (this.mSortOrder == SortOrder.Descending)
result = 0 - result;
// If the result was equality, use the secondary comparer to resolve it
if (result == 0 && mSecondComparer != null)
result = mSecondComparer.Compare(x, y);
return result;
}
/// <summary>
/// Compare the actual values to be used for sorting
/// </summary>
/// <param name="x">The aspect extracted from the first row</param>
/// <param name="y">The aspect extracted from the second row</param>
/// <returns>An ordering indication: -1, 0, 1</returns>
public int CompareValues(object x, object y) {
if (x is IComparable) {
return (x as IComparable).CompareTo(y);
}
// Force case insensitive compares on strings
String xAsString = x as String;
if (xAsString != null) {
return String.Compare(xAsString, (String)y, StringComparison.CurrentCultureIgnoreCase);
} else {
IComparable comparable = x as IComparable;
if (comparable != null)
return comparable.CompareTo(y);
else
return 0;
}
}
protected OLVColumn mColumn;
protected SortOrder mSortOrder;
protected ColumnComparer mSecondComparer;
}
/// <summary>
/// This comparer sort list view groups. OLVGroups have a "SortValue" property,
/// which is used if present. Otherwise, the titles of the groups will be compared.
/// </summary>
public class OLVGroupComparer : IComparer<OLVGroup> {
/// <summary>
/// Create a group comparer
/// </summary>
/// <param name="order">The ordering for column values</param>
public OLVGroupComparer(SortOrder order) {
this.sortOrder = order;
}
/// <summary>
/// Compare the two groups. OLVGroups have a "SortValue" property,
/// which is used if present. Otherwise, the titles of the groups will be compared.
/// </summary>
/// <param name="x">group1</param>
/// <param name="y">group2</param>
/// <returns>An ordering indication: -1, 0, 1</returns>
public int Compare(OLVGroup x, OLVGroup y) {
// If we can compare the sort values, do that.
// Otherwise do a case insensitive compare on the group header.
int result;
if (x.SortValue != null && y.SortValue != null)
result = x.SortValue.CompareTo(y.SortValue);
else
result = String.Compare(x.Header, y.Header, StringComparison.CurrentCultureIgnoreCase);
if (this.sortOrder == SortOrder.Descending)
result = 0 - result;
return result;
}
private SortOrder sortOrder;
}
/// <summary>
/// This comparer can be used to sort a collection of model objects by a given column
/// </summary>
public class ModelObjectComparer : IComparer, IComparer<object> {
/// <summary>
/// Create a model object comparer
/// </summary>
/// <param name="col"></param>
/// <param name="order"></param>
public ModelObjectComparer(OLVColumn col, SortOrder order) {
this.column = col;
this.sortOrder = order;
}
/// <summary>
/// Create a model object comparer with a secondary sorting column
/// </summary>
/// <param name="col"></param>
/// <param name="order"></param>
/// <param name="col2"></param>
/// <param name="order2"></param>
public ModelObjectComparer(OLVColumn col, SortOrder order, OLVColumn col2, SortOrder order2)
: this(col, order) {
// There is no point in secondary sorting on the same column
if (col != col2 && col2 != null && order2 != SortOrder.None)
this.secondComparer = new ModelObjectComparer(col2, order2);
}
/// <summary>
/// Compare the two model objects
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Compare(object x, object y) {
int result = 0;
object x1 = this.column.GetValue(x);
object y1 = this.column.GetValue(y);
if (this.sortOrder == SortOrder.None)
return 0;
// Handle nulls. Null values come last
bool xIsNull = (x1 == null || x1 == System.DBNull.Value);
bool yIsNull = (y1 == null || y1 == System.DBNull.Value);
if (xIsNull || yIsNull) {
if (xIsNull && yIsNull)
result = 0;
else
result = (xIsNull ? -1 : 1);
} else {
result = this.CompareValues(x1, y1);
}
if (this.sortOrder == SortOrder.Descending)
result = 0 - result;
// If the result was equality, use the secondary comparer to resolve it
if (result == 0 && this.secondComparer != null)
result = this.secondComparer.Compare(x, y);
return result;
}
/// <summary>
/// Compare the actual values
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int CompareValues(object x, object y) {
if (x is IComparable) {
return (x as IComparable).CompareTo(y);
}
// Force case insensitive compares on strings
String xStr = x as String;
if (xStr != null)
return String.Compare(xStr, (String)y, StringComparison.CurrentCultureIgnoreCase);
else {
IComparable comparable = x as IComparable;
if (comparable != null)
return comparable.CompareTo(y);
else
return 0;
}
}
private OLVColumn column;
private SortOrder sortOrder;
private ModelObjectComparer secondComparer;
#region IComparer<object> Members
#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 System.Globalization;
using Lucene.Net.Support;
using NumericField = Lucene.Net.Documents.NumericField;
using IndexReader = Lucene.Net.Index.IndexReader;
using Single = Lucene.Net.Support.Single;
using Term = Lucene.Net.Index.Term;
using TermEnum = Lucene.Net.Index.TermEnum;
using StringHelper = Lucene.Net.Util.StringHelper;
namespace Lucene.Net.Search
{
/// <summary> Stores information about how to sort documents by terms in an individual
/// field. Fields must be indexed in order to sort by them.
///
/// <p/>Created: Feb 11, 2004 1:25:29 PM
/// </summary>
/// <seealso cref="Sort"></seealso>
[Serializable]
public class SortField
{
/// <summary>Sort by document score (relevancy). Sort values are Float and higher
/// values are at the front.
/// </summary>
public const int SCORE = 0;
/// <summary>Sort by document number (index order). Sort values are Integer and lower
/// values are at the front.
/// </summary>
public const int DOC = 1;
// reserved, in Lucene 2.9, there was a constant: AUTO = 2
/// <summary>Sort using term values as Strings. Sort values are String and lower
/// values are at the front.
/// </summary>
public const int STRING = 3;
/// <summary>Sort using term values as encoded Integers. Sort values are Integer and
/// lower values are at the front.
/// </summary>
public const int INT = 4;
/// <summary>Sort using term values as encoded Floats. Sort values are Float and
/// lower values are at the front.
/// </summary>
public const int FLOAT = 5;
/// <summary>Sort using term values as encoded Longs. Sort values are Long and
/// lower values are at the front.
/// </summary>
public const int LONG = 6;
/// <summary>Sort using term values as encoded Doubles. Sort values are Double and
/// lower values are at the front.
/// </summary>
public const int DOUBLE = 7;
/// <summary>Sort using term values as encoded Shorts. Sort values are Short and
/// lower values are at the front.
/// </summary>
public const int SHORT = 8;
/// <summary>Sort using a custom Comparator. Sort values are any Comparable and
/// sorting is done according to natural order.
/// </summary>
public const int CUSTOM = 9;
/// <summary>Sort using term values as encoded Bytes. Sort values are Byte and
/// lower values are at the front.
/// </summary>
public const int BYTE = 10;
/// <summary>Sort using term values as Strings, but comparing by
/// value (using String.compareTo) for all comparisons.
/// This is typically slower than <see cref="STRING" />, which
/// uses ordinals to do the sorting.
/// </summary>
public const int STRING_VAL = 11;
// IMPLEMENTATION NOTE: the FieldCache.STRING_INDEX is in the same "namespace"
// as the above static int values. Any new values must not have the same value
// as FieldCache.STRING_INDEX.
/// <summary>Represents sorting by document score (relevancy). </summary>
public static readonly SortField FIELD_SCORE = new SortField(null, SCORE);
/// <summary>Represents sorting by document number (index order). </summary>
public static readonly SortField FIELD_DOC = new SortField(null, DOC);
private System.String field;
private int type; // defaults to determining type dynamically
private System.Globalization.CultureInfo locale; // defaults to "natural order" (no Locale)
internal bool reverse = false; // defaults to natural order
private Lucene.Net.Search.Parser parser;
// Used for CUSTOM sort
private FieldComparatorSource comparatorSource;
/// <summary>Creates a sort by terms in the given field with the type of term
/// values explicitly given.
/// </summary>
/// <param name="field"> Name of field to sort by. Can be <c>null</c> if
/// <c>type</c> is SCORE or DOC.
/// </param>
/// <param name="type"> Type of values in the terms.
/// </param>
public SortField(System.String field, int type)
{
InitFieldType(field, type);
}
/// <summary>Creates a sort, possibly in reverse, by terms in the given field with the
/// type of term values explicitly given.
/// </summary>
/// <param name="field"> Name of field to sort by. Can be <c>null</c> if
/// <c>type</c> is SCORE or DOC.
/// </param>
/// <param name="type"> Type of values in the terms.
/// </param>
/// <param name="reverse">True if natural order should be reversed.
/// </param>
public SortField(System.String field, int type, bool reverse)
{
InitFieldType(field, type);
this.reverse = reverse;
}
/// <summary>Creates a sort by terms in the given field, parsed
/// to numeric values using a custom <see cref="Search.Parser" />.
/// </summary>
/// <param name="field"> Name of field to sort by. Must not be null.
/// </param>
/// <param name="parser">Instance of a <see cref="Search.Parser" />,
/// which must subclass one of the existing numeric
/// parsers from <see cref="FieldCache" />. Sort type is inferred
/// by testing which numeric parser the parser subclasses.
/// </param>
/// <throws> IllegalArgumentException if the parser fails to </throws>
/// <summary> subclass an existing numeric parser, or field is null
/// </summary>
public SortField(System.String field, Lucene.Net.Search.Parser parser):this(field, parser, false)
{
}
/// <summary>Creates a sort, possibly in reverse, by terms in the given field, parsed
/// to numeric values using a custom <see cref="Search.Parser" />.
/// </summary>
/// <param name="field"> Name of field to sort by. Must not be null.
/// </param>
/// <param name="parser">Instance of a <see cref="Search.Parser" />,
/// which must subclass one of the existing numeric
/// parsers from <see cref="FieldCache" />. Sort type is inferred
/// by testing which numeric parser the parser subclasses.
/// </param>
/// <param name="reverse">True if natural order should be reversed.
/// </param>
/// <throws> IllegalArgumentException if the parser fails to </throws>
/// <summary> subclass an existing numeric parser, or field is null
/// </summary>
public SortField(System.String field, Lucene.Net.Search.Parser parser, bool reverse)
{
if (parser is Lucene.Net.Search.IntParser)
InitFieldType(field, INT);
else if (parser is Lucene.Net.Search.FloatParser)
InitFieldType(field, FLOAT);
else if (parser is Lucene.Net.Search.ShortParser)
InitFieldType(field, SHORT);
else if (parser is Lucene.Net.Search.ByteParser)
InitFieldType(field, BYTE);
else if (parser is Lucene.Net.Search.LongParser)
InitFieldType(field, LONG);
else if (parser is Lucene.Net.Search.DoubleParser)
InitFieldType(field, DOUBLE);
else
{
throw new System.ArgumentException("Parser instance does not subclass existing numeric parser from FieldCache (got " + parser + ")");
}
this.reverse = reverse;
this.parser = parser;
}
/// <summary>Creates a sort by terms in the given field sorted
/// according to the given locale.
/// </summary>
/// <param name="field"> Name of field to sort by, cannot be <c>null</c>.
/// </param>
/// <param name="locale">Locale of values in the field.
/// </param>
public SortField(System.String field, System.Globalization.CultureInfo locale)
{
InitFieldType(field, STRING);
this.locale = locale;
}
/// <summary>Creates a sort, possibly in reverse, by terms in the given field sorted
/// according to the given locale.
/// </summary>
/// <param name="field"> Name of field to sort by, cannot be <c>null</c>.
/// </param>
/// <param name="locale">Locale of values in the field.
/// </param>
public SortField(System.String field, System.Globalization.CultureInfo locale, bool reverse)
{
InitFieldType(field, STRING);
this.locale = locale;
this.reverse = reverse;
}
/// <summary>Creates a sort with a custom comparison function.</summary>
/// <param name="field">Name of field to sort by; cannot be <c>null</c>.
/// </param>
/// <param name="comparator">Returns a comparator for sorting hits.
/// </param>
public SortField(System.String field, FieldComparatorSource comparator)
{
InitFieldType(field, CUSTOM);
this.comparatorSource = comparator;
}
/// <summary>Creates a sort, possibly in reverse, with a custom comparison function.</summary>
/// <param name="field">Name of field to sort by; cannot be <c>null</c>.
/// </param>
/// <param name="comparator">Returns a comparator for sorting hits.
/// </param>
/// <param name="reverse">True if natural order should be reversed.
/// </param>
public SortField(System.String field, FieldComparatorSource comparator, bool reverse)
{
InitFieldType(field, CUSTOM);
this.reverse = reverse;
this.comparatorSource = comparator;
}
// Sets field & type, and ensures field is not NULL unless
// type is SCORE or DOC
private void InitFieldType(System.String field, int type)
{
this.type = type;
if (field == null)
{
if (type != SCORE && type != DOC)
throw new System.ArgumentException("field can only be null when type is SCORE or DOC");
}
else
{
this.field = StringHelper.Intern(field);
}
}
/// <summary>Returns the name of the field. Could return <c>null</c>
/// if the sort is by SCORE or DOC.
/// </summary>
/// <value> Name of field, possibly <c>null</c>. </value>
public virtual string Field
{
get { return field; }
}
/// <summary>Returns the type of contents in the field.</summary>
/// <value> One of the constants SCORE, DOC, STRING, INT or FLOAT. </value>
public virtual int Type
{
get { return type; }
}
/// <summary>Returns the Locale by which term values are interpreted.
/// May return <c>null</c> if no Locale was specified.
/// </summary>
/// <value> Locale, or <c>null</c>. </value>
public virtual CultureInfo Locale
{
get { return locale; }
}
/// <summary>Returns the instance of a <see cref="FieldCache" /> parser that fits to the given sort type.
/// May return <c>null</c> if no parser was specified. Sorting is using the default parser then.
/// </summary>
/// <value> An instance of a <see cref="FieldCache" /> parser, or <c>null</c>. </value>
public virtual Parser Parser
{
get { return parser; }
}
/// <summary>Returns whether the sort should be reversed.</summary>
/// <value> True if natural order should be reversed. </value>
public virtual bool Reverse
{
get { return reverse; }
}
/// <summary>
/// Returns the <see cref="FieldComparatorSource"/> used for
/// custom sorting
/// </summary>
public virtual FieldComparatorSource ComparatorSource
{
get { return comparatorSource; }
}
public override System.String ToString()
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
switch (type)
{
case SCORE:
buffer.Append("<score>");
break;
case DOC:
buffer.Append("<doc>");
break;
case STRING:
buffer.Append("<string: \"").Append(field).Append("\">");
break;
case STRING_VAL:
buffer.Append("<string_val: \"").Append(field).Append("\">");
break;
case BYTE:
buffer.Append("<byte: \"").Append(field).Append("\">");
break;
case SHORT:
buffer.Append("<short: \"").Append(field).Append("\">");
break;
case INT:
buffer.Append("<int: \"").Append(field).Append("\">");
break;
case LONG:
buffer.Append("<long: \"").Append(field).Append("\">");
break;
case FLOAT:
buffer.Append("<float: \"").Append(field).Append("\">");
break;
case DOUBLE:
buffer.Append("<double: \"").Append(field).Append("\">");
break;
case CUSTOM:
buffer.Append("<custom:\"").Append(field).Append("\": ").Append(comparatorSource).Append('>');
break;
default:
buffer.Append("<???: \"").Append(field).Append("\">");
break;
}
if (locale != null)
buffer.Append('(').Append(locale).Append(')');
if (parser != null)
buffer.Append('(').Append(parser).Append(')');
if (reverse)
buffer.Append('!');
return buffer.ToString();
}
/// <summary>Returns true if <c>o</c> is equal to this. If a
/// <see cref="FieldComparatorSource" /> or <see cref="Search.Parser" />
/// was provided, it must properly
/// implement equals (unless a singleton is always used).
/// </summary>
public override bool Equals(System.Object o)
{
if (this == o)
return true;
if (!(o is SortField))
return false;
SortField other = (SortField) o;
return ((System.Object) other.field == (System.Object) this.field && other.type == this.type &&
other.reverse == this.reverse &&
(other.locale == null ? this.locale == null : other.locale.Equals(this.locale)) &&
(other.comparatorSource == null
? this.comparatorSource == null
: other.comparatorSource.Equals(this.comparatorSource)) &&
(other.parser == null ? this.parser == null : other.parser.Equals(this.parser)));
}
/// <summary>Returns true if <c>o</c> is equal to this. If a
/// <see cref="FieldComparatorSource" /> (deprecated) or <see cref="Search.Parser" />
/// was provided, it must properly
/// implement hashCode (unless a singleton is always
/// used).
/// </summary>
public override int GetHashCode()
{
int hash = type ^ 0x346565dd + (reverse ? Boolean.TrueString.GetHashCode() : Boolean.FalseString.GetHashCode()) ^ unchecked((int) 0xaf5998bb);
if (field != null)
hash += (field.GetHashCode() ^ unchecked((int) 0xff5685dd));
if (locale != null)
{
hash += (locale.GetHashCode() ^ 0x08150815);
}
if (comparatorSource != null)
hash += comparatorSource.GetHashCode();
if (parser != null)
hash += (parser.GetHashCode() ^ 0x3aaf56ff);
return hash;
}
//// field must be interned after reading from stream
// private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
// in.defaultReadObject();
// if (field != null)
// field = StringHelper.intern(field);
// }
[System.Runtime.Serialization.OnDeserialized]
internal void OnDeserialized(System.Runtime.Serialization.StreamingContext context)
{
field = StringHelper.Intern(field);
}
/// <summary>Returns the <see cref="FieldComparator" /> to use for
/// sorting.
///
/// <b>NOTE:</b> This API is experimental and might change in
/// incompatible ways in the next release.
///
/// </summary>
/// <param name="numHits">number of top hits the queue will store
/// </param>
/// <param name="sortPos">position of this SortField within <see cref="Sort" />
///. The comparator is primary if sortPos==0,
/// secondary if sortPos==1, etc. Some comparators can
/// optimize themselves when they are the primary sort.
/// </param>
/// <returns> <see cref="FieldComparator" /> to use when sorting
/// </returns>
public virtual FieldComparator GetComparator(int numHits, int sortPos)
{
if (locale != null)
{
// TODO: it'd be nice to allow FieldCache.getStringIndex
// to optionally accept a Locale so sorting could then use
// the faster StringComparator impls
return new FieldComparator.StringComparatorLocale(numHits, field, locale);
}
switch (type)
{
case SortField.SCORE:
return new FieldComparator.RelevanceComparator(numHits);
case SortField.DOC:
return new FieldComparator.DocComparator(numHits);
case SortField.INT:
return new FieldComparator.IntComparator(numHits, field, parser);
case SortField.FLOAT:
return new FieldComparator.FloatComparator(numHits, field, parser);
case SortField.LONG:
return new FieldComparator.LongComparator(numHits, field, parser);
case SortField.DOUBLE:
return new FieldComparator.DoubleComparator(numHits, field, parser);
case SortField.BYTE:
return new FieldComparator.ByteComparator(numHits, field, parser);
case SortField.SHORT:
return new FieldComparator.ShortComparator(numHits, field, parser);
case SortField.CUSTOM:
System.Diagnostics.Debug.Assert(comparatorSource != null);
return comparatorSource.NewComparator(field, numHits, sortPos, reverse);
case SortField.STRING:
return new FieldComparator.StringOrdValComparator(numHits, field, sortPos, reverse);
case SortField.STRING_VAL:
return new FieldComparator.StringValComparator(numHits, field);
default:
throw new System.SystemException("Illegal sort type: " + type);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
**
** Purpose: Synchronizes access to a shared resource or region of code in a multi-threaded
** program.
**
**
=============================================================================*/
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Internal.Runtime.CompilerServices;
namespace System.Threading
{
public static class Monitor
{
#region Object->Lock/Condition mapping
#if !FEATURE_SYNCTABLE
private static ConditionalWeakTable<object, Lock> s_lockTable = new ConditionalWeakTable<object, Lock>();
private static ConditionalWeakTable<object, Lock>.CreateValueCallback s_createLock = (o) => new Lock();
#endif
private static ConditionalWeakTable<object, Condition> s_conditionTable = new ConditionalWeakTable<object, Condition>();
private static ConditionalWeakTable<object, Condition>.CreateValueCallback s_createCondition = (o) => new Condition(GetLock(o));
internal static Lock GetLock(Object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
Debug.Assert(!(obj is Lock),
"Do not use Monitor.Enter or TryEnter on a Lock instance; use Lock methods directly instead.");
#if FEATURE_SYNCTABLE
return ObjectHeader.GetLockObject(obj);
#else
return s_lockTable.GetValue(obj, s_createLock);
#endif
}
private static Condition GetCondition(Object obj)
{
Debug.Assert(
!(obj is Condition || obj is Lock),
"Do not use Monitor.Pulse or Wait on a Lock or Condition instance; use the methods on Condition instead.");
return s_conditionTable.GetValue(obj, s_createCondition);
}
#endregion
#region Public Enter/Exit methods
public static void Enter(Object obj)
{
Lock lck = GetLock(obj);
if (lck.TryAcquire(0))
return;
TryAcquireContended(lck, obj, Timeout.Infinite);
}
public static void Enter(Object obj, ref bool lockTaken)
{
if (lockTaken)
throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken));
Lock lck = GetLock(obj);
if (lck.TryAcquire(0))
{
lockTaken = true;
return;
}
TryAcquireContended(lck, obj, Timeout.Infinite);
lockTaken = true;
}
public static bool TryEnter(Object obj)
{
return GetLock(obj).TryAcquire(0);
}
public static void TryEnter(Object obj, ref bool lockTaken)
{
if (lockTaken)
throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken));
lockTaken = GetLock(obj).TryAcquire(0);
}
public static bool TryEnter(Object obj, int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Lock lck = GetLock(obj);
if (lck.TryAcquire(0))
return true;
return TryAcquireContended(lck, obj, millisecondsTimeout);
}
public static void TryEnter(Object obj, int millisecondsTimeout, ref bool lockTaken)
{
if (lockTaken)
throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken));
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Lock lck = GetLock(obj);
if (lck.TryAcquire(0))
{
lockTaken = true;
return;
}
lockTaken = TryAcquireContended(lck, obj, millisecondsTimeout);
}
public static bool TryEnter(Object obj, TimeSpan timeout) =>
TryEnter(obj, WaitHandle.ToTimeoutMilliseconds(timeout));
public static void TryEnter(Object obj, TimeSpan timeout, ref bool lockTaken) =>
TryEnter(obj, WaitHandle.ToTimeoutMilliseconds(timeout), ref lockTaken);
public static void Exit(Object obj)
{
GetLock(obj).Release();
}
public static bool IsEntered(Object obj)
{
return GetLock(obj).IsAcquired;
}
#endregion
#region Public Wait/Pulse methods
// Remoting is not supported, ignore exitContext
public static bool Wait(Object obj, int millisecondsTimeout, bool exitContext) =>
Wait(obj, millisecondsTimeout);
// Remoting is not supported, ignore exitContext
public static bool Wait(Object obj, TimeSpan timeout, bool exitContext) =>
Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout));
public static bool Wait(Object obj, int millisecondsTimeout)
{
Condition condition = GetCondition(obj);
DebugBlockingItem blockingItem;
using (new DebugBlockingScope(obj, DebugBlockingItemType.MonitorEvent, millisecondsTimeout, out blockingItem))
{
return condition.Wait(millisecondsTimeout);
}
}
public static bool Wait(Object obj, TimeSpan timeout) => Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout));
public static bool Wait(Object obj) => Wait(obj, Timeout.Infinite);
public static void Pulse(object obj)
{
GetCondition(obj).SignalOne();
}
public static void PulseAll(object obj)
{
GetCondition(obj).SignalAll();
}
#endregion
#region Slow path for Entry/TryEnter methods.
internal static bool TryAcquireContended(Lock lck, Object obj, int millisecondsTimeout)
{
DebugBlockingItem blockingItem;
using (new DebugBlockingScope(obj, DebugBlockingItemType.MonitorCriticalSection, millisecondsTimeout, out blockingItem))
{
return lck.TryAcquire(millisecondsTimeout);
}
}
#endregion
#region Debugger support
// The debugger binds to the fields below by name. Do not change any names or types without
// updating the debugger!
// The head of the list of DebugBlockingItem stack objects used by the debugger to implement
// ICorDebugThread4::GetBlockingObjects. Usually the list either is empty or contains a single
// item. However, a wait on an STA thread may reenter via the message pump and cause the thread
// to be blocked on a second object.
[ThreadStatic]
private static IntPtr t_firstBlockingItem;
// Different ways a thread can be blocked that the debugger will expose.
// Do not change or add members without updating the debugger code.
private enum DebugBlockingItemType
{
MonitorCriticalSection = 0,
MonitorEvent = 1
}
// Represents an item a thread is blocked on. This structure is allocated on the stack and accessed by the debugger.
// Fields are volatile to avoid potential compiler optimizations.
private struct DebugBlockingItem
{
// The object the thread is waiting on
public volatile object _object;
// Indicates how the thread is blocked on the item
public volatile DebugBlockingItemType _blockingType;
// Blocking timeout in milliseconds or Timeout.Infinite for no timeout
public volatile int _timeout;
// Next pointer in the linked list of DebugBlockingItem records
public volatile IntPtr _next;
}
private unsafe struct DebugBlockingScope : IDisposable
{
public DebugBlockingScope(object obj, DebugBlockingItemType blockingType, int timeout, out DebugBlockingItem blockingItem)
{
blockingItem._object = obj;
blockingItem._blockingType = blockingType;
blockingItem._timeout = timeout;
blockingItem._next = t_firstBlockingItem;
t_firstBlockingItem = (IntPtr)Unsafe.AsPointer(ref blockingItem);
}
public void Dispose()
{
t_firstBlockingItem = Unsafe.Read<DebugBlockingItem>((void*)t_firstBlockingItem)._next;
}
}
#endregion
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| 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.Diagnostics;
using System.Reflection;
using System.Collections.Generic;
using System.Data.Objects;
using System.Data.EntityClient;
using System.Data.Metadata.Edm;
using System.Data.Objects.DataClasses;
using System.Data;
namespace ESRI.ArcLogistics.Data
{
/// <summary>
/// DataObjectContext class.
/// </summary>
internal class DataObjectContext : DataModel.Entities
{
#region constants
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
// EDM type names
private const string EDM_TYPE_String = "String";
// EDM facets
private const string FACET_MaxLength = "MaxLength";
// configuration schemes
private static readonly Guid SCHEME_ID_CAPACITIES = new Guid("101E2289-6E5B-4a4e-884D-78A6EB8AA26D");
private static readonly Guid SCHEME_ID_ORDERPROPERTIES = new Guid("5C7EBA4A-0415-481a-9E59-AED986277E1E");
private const string SCHEME_NAME_CAPACITIES = "Capacities";
private const string SCHEME_NAME_ORDERPROPERTIES = "OrderCustomProperties";
private const string SCHEMES_ENTITY_SET = "ConfigSchemes";
private const string SCHEMES_KEY = "Id";
#endregion constants
#region constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Initializes a new DataObjectContext instance.
/// </summary>
public DataObjectContext(string connectionString) :
base(connectionString)
{
_Init();
}
/// <summary>
/// Initializes a new DataObjectContext instance.
/// </summary>
public DataObjectContext(EntityConnection connection) :
base(connection)
{
_Init();
}
#endregion constructors
#region public events
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Raises when SaveChanges operation completed.
/// </summary>
public event SaveChangesCompletedEventHandler SaveChangesCompleted;
/// <summary>
/// Raises on saving changes.
/// </summary>
public event SavingChangesEventHandler PostSavingChanges;
#endregion public events
#region public methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Explicit initialization. Must be called on creating new project.
/// </summary>
public void PostInit(CapacitiesInfo capacitiesInfo,
OrderCustomPropertiesInfo orderCustomPropertiesInfo)
{
Debug.Assert(!_isInited); // init once
// add scheme objects
DataModel.ConfigSchemes scheme = DataModel.ConfigSchemes.CreateConfigSchemes(SCHEME_ID_CAPACITIES);
scheme.Name = SCHEME_NAME_CAPACITIES;
scheme.Value = ConfigDataSerializer.SerializeCapacitiesInfo(capacitiesInfo);
AddObject(SCHEMES_ENTITY_SET, scheme);
scheme = DataModel.ConfigSchemes.CreateConfigSchemes(SCHEME_ID_ORDERPROPERTIES);
scheme.Name = SCHEME_NAME_ORDERPROPERTIES;
scheme.Value = ConfigDataSerializer.SerializeOrderCustomPropertiesInfo(orderCustomPropertiesInfo);
AddObject(SCHEMES_ENTITY_SET, scheme);
base.SaveChanges();
// create object factory
ObjectInitData initData = new ObjectInitData();
initData.CapacitiesInfo = capacitiesInfo;
initData.OrderCustomPropertiesInfo = orderCustomPropertiesInfo;
_fact = new DataObjectFactory(initData);
_objInitData = initData;
// Attach handler for SavingChanges event.
this.SavingChanges += new EventHandler(DataObjectContext_SavingChanges);
_isInited = true;
}
/// <summary>
/// Creates data object by specified entity object.
/// </summary>
/// <param name="entity">Entity object.</param>
/// <returns>Generic data object.</returns>
public T CreateObject<T>(EntityObject entity)
where T : DataObject
{
if (!_isInited)
throw new InvalidOperationException();
return _fact.CreateObject<T>(entity);
}
public new int SaveChanges()
{
if (!_isInited)
throw new InvalidOperationException();
int result;
try
{
result = base.SaveChanges();
_NotifySaveChangesCompleted(true);
}
catch
{
_NotifySaveChangesCompleted(false);
throw;
}
return result;
}
/// <summary>
/// CapacitiesInfo.
/// </summary>
public CapacitiesInfo CapacitiesInfo
{
get
{
if (!_isInited)
throw new InvalidOperationException();
return _objInitData.CapacitiesInfo;
}
}
/// <summary>
/// OrderCustomPropertiesInfo.
/// </summary>
public OrderCustomPropertiesInfo OrderCustomPropertiesInfo
{
get
{
if (!_isInited)
throw new InvalidOperationException();
return _objInitData.OrderCustomPropertiesInfo;
}
}
/// <summary>
/// Updates order custom properties info in database.
/// </summary>
/// <param name="propertiesInfo">Order custom properrties info.</param>
public void UpdateCustomOrderPropertiesInfo(OrderCustomPropertiesInfo propertiesInfo)
{
Debug.Assert(propertiesInfo != null);
// Get custom order properties config scheme.
DataModel.ConfigSchemes customOrderPropertiesScheme = _GetConfigSchemeObject(SCHEME_ID_ORDERPROPERTIES);
// Update value of custom order properties database field.
customOrderPropertiesScheme.Value =
ConfigDataSerializer.SerializeOrderCustomPropertiesInfo(propertiesInfo);
// Update init data.
_objInitData.OrderCustomPropertiesInfo = propertiesInfo;
// Save changes to the database.
base.SaveChanges();
}
#endregion
#region private methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private void _Init()
{
Debug.Assert(!_isInited); // init once
// check if project DB contains config schemes
if (_IsConfigSchemeExist(SCHEME_ID_CAPACITIES) &&
_IsConfigSchemeExist(SCHEME_ID_ORDERPROPERTIES))
{
// load schemes
ObjectInitData initData = new ObjectInitData();
initData.CapacitiesInfo = _LoadCapacitiesInfo();
initData.OrderCustomPropertiesInfo = _LoadOrderPropertiesInfo();
// create object factory
_fact = new DataObjectFactory(initData);
_objInitData = initData;
// attach events
this.SavingChanges += new EventHandler(DataObjectContext_SavingChanges);
_isInited = true;
}
}
private void DataObjectContext_SavingChanges(object sender, EventArgs e)
{
IEnumerable<ObjectStateEntry> entries = this.ObjectStateManager.GetObjectStateEntries(
EntityState.Added |
EntityState.Modified |
EntityState.Deleted);
List<DataObject> addedItems = new List<DataObject>();
List<DataObject> modifiedItems = new List<DataObject>();
List<DataObject> deletedItems = new List<DataObject>();
foreach (ObjectStateEntry entry in entries)
{
if (!entry.IsRelationship &&
entry.EntitySet.ElementType is EntityType)
{
if (entry.State == EntityState.Added ||
entry.State == EntityState.Modified)
{
// apply database constraints
_ApplyConstraints(entry);
// check whether object can be saved
_CheckCanSave(entry);
// fill event collections
if (entry.State != EntityState.Detached)
{
DataObject item = DataObjectHelper.GetDataObject(
entry.Entity as EntityObject);
if (item != null)
{
if (entry.State == EntityState.Added)
addedItems.Add(item);
else if (entry.State == EntityState.Modified)
{
if (_IsMarkedAsDeleted(item))
deletedItems.Add(item);
else
modifiedItems.Add(item);
}
}
}
}
else if (entry.State == EntityState.Deleted)
{
DataObject item = DataObjectHelper.GetDataObject(
entry.Entity as EntityObject);
if (item != null)
deletedItems.Add(item);
}
}
}
_NotifySavingChanges(addedItems.AsReadOnly(),
modifiedItems.AsReadOnly(),
deletedItems.AsReadOnly());
}
private void _CheckCanSave(ObjectStateEntry entry)
{
Debug.Assert(entry != null);
if (entry.State == EntityState.Added)
{
DataObject obj = DataObjectHelper.GetDataObject(entry.Entity as EntityObject);
if (obj != null)
{
if (!obj.CanSave)
this.Detach(entry.Entity);
}
}
}
private void _ApplyConstraints(ObjectStateEntry entry)
{
Debug.Assert(entry != null);
EntityType entityType = (EntityType)entry.EntitySet.ElementType;
foreach (EdmProperty prop in entityType.Properties)
{
if (prop.TypeUsage.EdmType.Name.Equals(EDM_TYPE_String))
_ApplyStringConstraints(entry.Entity as EntityObject, prop);
}
}
private void _ApplyStringConstraints(EntityObject entity, EdmProperty prop)
{
_FixStrLength(entity, prop);
}
private void _FixStrLength(EntityObject entity, EdmProperty prop)
{
Debug.Assert(entity != null);
Debug.Assert(prop != null);
Facet facet = null;
if (prop.TypeUsage.Facets.TryGetValue(FACET_MaxLength, true, out facet) &&
facet.Value is int)
{
int maxLength = (int)facet.Value;
if (maxLength > 0)
{
PropertyInfo pi = entity.GetType().GetProperty(prop.Name);
if (pi != null)
{
object value = pi.GetValue(entity, null);
if (value != null && value is String)
{
string strValue = (string)value;
if (strValue.Length > maxLength)
pi.SetValue(entity, strValue.Remove(maxLength), null);
}
}
}
}
}
private void _NotifySaveChangesCompleted(bool isSucceeded)
{
if (SaveChangesCompleted != null)
SaveChangesCompleted(this, new SaveChangesCompletedEventArgs(isSucceeded));
}
private void _NotifySavingChanges(IList<DataObject> addedItems,
IList<DataObject> modifiedItems,
IList<DataObject> deletedItems)
{
if (PostSavingChanges != null)
{
PostSavingChanges(this, new SavingChangesEventArgs(addedItems,
modifiedItems,
deletedItems));
}
}
private CapacitiesInfo _LoadCapacitiesInfo()
{
CapacitiesInfo info = null;
try
{
string xml = _GetConfigScheme(SCHEME_ID_CAPACITIES);
info = ConfigDataSerializer.ParseCapacitiesInfo(xml);
}
catch (Exception e)
{
throw new DataException(String.Format(
Properties.Messages.Error_ConfigSchemeLoadFailed, SCHEME_ID_CAPACITIES), e);
}
return info;
}
private OrderCustomPropertiesInfo _LoadOrderPropertiesInfo()
{
OrderCustomPropertiesInfo info = null;
try
{
string xml = _GetConfigScheme(SCHEME_ID_ORDERPROPERTIES);
info = ConfigDataSerializer.ParseOrderCustomPropertiesInfo(xml);
}
catch (Exception e)
{
throw new DataException(String.Format(
Properties.Messages.Error_ConfigSchemeLoadFailed, SCHEME_ID_ORDERPROPERTIES), e);
}
return info;
}
private bool _IsConfigSchemeExist(Guid schemeId)
{
string entitySet = ContextHelper.GetFullEntitySetName(this,
SCHEMES_ENTITY_SET);
EntityKey key = new EntityKey(entitySet, SCHEMES_KEY,
schemeId);
object entity = null;
return TryGetObjectByKey(key, out entity);
}
private string _GetConfigScheme(Guid schemeId)
{
string entitySet = ContextHelper.GetFullEntitySetName(this,
SCHEMES_ENTITY_SET);
EntityKey key = new EntityKey(entitySet, SCHEMES_KEY,
schemeId);
string schemeXML = null;
object entity = null;
if (TryGetObjectByKey(key, out entity))
{
DataModel.ConfigSchemes scheme = entity as DataModel.ConfigSchemes;
if (scheme != null)
schemeXML = scheme.Value;
}
if (schemeXML == null)
throw new DataException();
return schemeXML;
}
/// <summary>
/// Gets config schemes object with given ID.
/// </summary>
/// <param name="schemeId">ID of scheme.</param>
/// <returns>ConfigSchemes object.</returns>
private DataModel.ConfigSchemes _GetConfigSchemeObject(Guid schemeId)
{
// Get full entity scheme name.
string entitySet = ContextHelper.GetFullEntitySetName(this,
SCHEMES_ENTITY_SET);
// Create entity key.
EntityKey key = new EntityKey(entitySet, SCHEMES_KEY,
schemeId);
DataModel.ConfigSchemes scheme = null;
object entity = null;
// Try to get object by key.
if (TryGetObjectByKey(key, out entity))
{
scheme = entity as DataModel.ConfigSchemes;
}
if (scheme == null)
throw new DataException();
return scheme;
}
private static bool _IsMarkedAsDeleted(DataObject obj)
{
bool isMarked = false;
IMarkableAsDeleted mark = obj as IMarkableAsDeleted;
if (mark != null)
isMarked = mark.IsMarkedAsDeleted;
return isMarked;
}
#endregion private methods
#region private members
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private ObjectInitData _objInitData;
private DataObjectFactory _fact;
private bool _isInited = false;
#endregion private members
}
}
| |
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Net.Code.ADONet.Extensions.SqlClient;
using Net.Code.ADONet.Tests.Integration.Data;
using Net.Code.ADONet.Tests.Integration.Databases;
using Xunit.Abstractions;
using Xunit;
namespace Net.Code.ADONet.Tests.Integration.TestSupport
{
public class DbTestHelper<T> where T : IDatabaseImpl, new()
{
private readonly IDatabaseImpl _target;
private readonly IDb _db;
private readonly ITestOutputHelper _output;
public DbTestHelper(ITestOutputHelper output)
{
_target = new T();
var isAvailable = _target.IsAvailable();
Skip.IfNot(isAvailable);
_output = output;
//Logger.Log = _output.WriteLine;
Logger.Log = s => { };
_db = _target.CreateDb();
}
public void Initialize()
{
_db.Connect();
_db.Sql(_target.CreatePersonTable).AsNonQuery();
_db.Sql(_target.CreateAddressTable).AsNonQuery();
_db.Sql(_target.CreateProductTable).AsNonQuery();
}
public void Cleanup()
{
_db.Execute(_target.DropPersonTable);
_db.Execute(_target.DropAddressTable);
_db.Execute(_target.DropProductTable);
_db.Disconnect();
Logger.Log = s => { };
}
public void Insert(
IEnumerable<Person> people = null,
IEnumerable<Address> addresses = null,
IEnumerable<Product> products = null
)
{
_db.Insert(people ?? Enumerable.Empty<Person>());
_db.Insert(addresses ?? Enumerable.Empty<Address>());
_db.Insert(products ?? Enumerable.Empty<Product>());
}
public async Task InsertAsync(
IEnumerable<Person> people = null,
IEnumerable<Address> addresses = null,
IEnumerable<Product> products = null
)
{
await Task.WhenAll(
_db.InsertAsync(people ?? Enumerable.Empty<Person>()),
_db.InsertAsync(addresses ?? Enumerable.Empty<Address>()),
_db.InsertAsync(products ?? Enumerable.Empty<Product>())
);
}
public void Update(IEnumerable<Person> items)
{
_db.Update(items);
}
public async Task InsertAsync(IEnumerable<Person> items)
{
foreach (var item in items)
{
await _db.Sql(_target.InsertPerson).WithParameters(item).AsNonQueryAsync();
}
}
public List<Person> GetAllPeopleGeneric()
{
return _db
.Sql(_target.CreateQuery<Person>().SelectAll)
.AsEnumerable<Person>()
.ToList();
}
public List<Person> GetAllPeopleGenericLegacy()
{
return _db
.Sql(_target.CreateQuery<Person>().SelectAll)
.AsEnumerableLegacy<Person>(((Db)_db).Config)
.ToList();
}
public DataTable GetSchemaTable()
{
var dataReader = _db
.Sql(_target.CreateQuery<Person>().SelectAll)
.AsReader();
using (dataReader)
{
var dt = dataReader.GetSchemaTable();
return dt;
}
}
public List<Person> GetAllPeopleAsDynamic()
{
return _db
.Sql(_target.CreateQuery<Person>().SelectAll)
.AsEnumerable()
.Select(d => (Person) _target.Project(d))
.ToList();
}
public async Task<List<Person>> GetAllPeopleAsDynamicAsync()
{
return await _db.Sql(_target.CreateQuery<Person>().SelectAll)
.AsEnumerableAsync()
.Select(d => (Person)_target.Project(d))
.ToListAsync();
}
public List<Product> GetAllProducts()
{
return _db
.Sql(_target.CreateQuery<Product>().SelectAll)
.AsEnumerable<Product>()
.ToList();
}
public DataTable PeopleAsDataTable()
{
return _db
.Sql(_target.CreateQuery<Person>().SelectAll)
.AsDataTable();
}
public (IReadOnlyCollection<Person>, IReadOnlyCollection<Address>) AsMultiResultSet()
{
if (!_target.SupportsMultipleResultSets)
throw new SkipException($"{_target.GetType().Name} does not support multiple result sets");
var result = _target.SelectPersonAndAddress(_db);
return result;
}
public Person Get(int id)
{
return _db
.Sql(_target.CreateQuery<Person>().Select)
.WithParameters(new { Id = id })
.Single<Person>();
}
public async Task<Person> GetAsync(int id)
{
return await _db
.Sql(_target.CreateQuery<Person>().Select)
.WithParameters(new { Id = id })
.SingleAsync<Person>();
}
public (int[], Person[]) GetByIdList()
{
if (!_target.SupportsTableValuedParameters)
throw new SkipException($"{_target.GetType().Name} does not support table valued parameters");
var ids = _db
.Sql($"SELECT TOP 3 Id FROM {nameof(Person)}")
.Select(d => (int)d.Id)
.ToArray();
return (ids, _db
.Sql("SELECT * FROM Person JOIN @IDs IdSet ON Person.Id = IdSet.Id")
.WithParameter("@IDs", ids.Select(id => new {Id = id}), "IdSet")
.AsEnumerable<Person>()
.ToArray());
}
public int GetCountOfPeople()
{
return _db.Sql($"SELECT count(*) FROM {nameof(Person)}").AsScalar<int>();
}
public async Task<int> GetCountOfPeopleAsync()
{
var result = await _db.Sql($"SELECT count(*) FROM {nameof(Person)}").AsScalarAsync<int>();
return result;
}
public void BulkInsert(IEnumerable<Person> list)
{
_target.BulkInsert(_db, list);
}
public string GetColumnName(string propertyName)
{
return ((Db)(_db)).Config.MappingConvention.ToDb(propertyName);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Geometry;
using Microsoft.Graphics.Canvas.Text;
using Microsoft.Graphics.Canvas.UI.Xaml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
using Windows.UI;
using Windows.UI.Input.Inking;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media;
namespace ExampleGallery
{
public sealed partial class InkExample : UserControl
{
CanvasRenderTarget renderTarget;
List<Point> selectionPolylinePoints;
Rect? selectionBoundingRect;
InkSynchronizer inkSynchronizer;
CanvasTextFormat textFormat;
bool needsClear;
bool needsInkSurfaceValidation;
bool needToCreateSizeDepdendentResources;
bool showTextLabels;
public enum DryInkRenderingType
{
BuiltIn,
CustomGeometry
}
public List<DryInkRenderingType> DryInkRenderingTypes { get { return Utils.GetEnumAsList<DryInkRenderingType>(); } }
public DryInkRenderingType SelectedDryInkRenderingType { get; set; }
// Since this app uses custom drying, it can't use the built-in stroke container on the ink canvas.
InkManager inkManager = new InkManager();
List<InkStroke> strokeList = new List<InkStroke>();
public InkExample()
{
this.InitializeComponent();
inkCanvas.InkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Mouse | Windows.UI.Core.CoreInputDeviceTypes.Pen | Windows.UI.Core.CoreInputDeviceTypes.Touch;
// By default, pen barrel button or right mouse button is processed for inking
// Set the configuration to instead allow processing these input on the UI thread
inkCanvas.InkPresenter.InputProcessingConfiguration.RightDragAction = InkInputRightDragAction.LeaveUnprocessed;
inkCanvas.InkPresenter.UnprocessedInput.PointerPressed += UnprocessedInput_PointerPressed;
inkCanvas.InkPresenter.UnprocessedInput.PointerMoved += UnprocessedInput_PointerMoved;
inkCanvas.InkPresenter.UnprocessedInput.PointerReleased += UnprocessedInput_PointerReleased;
inkCanvas.InkPresenter.StrokeInput.StrokeStarted += StrokeInput_StrokeStarted;
inkCanvas.InkPresenter.StrokesCollected += InkPresenter_StrokesCollected;
inkCanvas.InkPresenter.StrokesErased += InkPresenter_StrokesErased;
inkSynchronizer = inkCanvas.InkPresenter.ActivateCustomDrying();
textFormat = new CanvasTextFormat();
// Set defaults
SelectedDryInkRenderingType = DryInkRenderingType.BuiltIn;
SelectColor(color0);
showTextLabels = true;
needToCreateSizeDepdendentResources = true;
}
private void InkPresenter_StrokesCollected(InkPresenter sender, InkStrokesCollectedEventArgs args)
{
strokeList.AddRange(args.Strokes);
foreach (var s in args.Strokes)
{
inkManager.AddStroke(s);
}
canvasControl.Invalidate();
}
private void StrokeInput_StrokeStarted(InkStrokeInput sender, Windows.UI.Core.PointerEventArgs args)
{
ClearSelection();
canvasControl.Invalidate();
}
private void InkPresenter_StrokesErased(InkPresenter sender, InkStrokesErasedEventArgs args)
{
var removed = args.Strokes;
foreach (var s in removed)
{
strokeList.Remove(s);
}
inkManager = new InkManager();
foreach (var s in strokeList)
{
inkManager.AddStroke(s);
}
ClearSelection();
canvasControl.Invalidate();
}
private void UnprocessedInput_PointerPressed(InkUnprocessedInput sender, Windows.UI.Core.PointerEventArgs args)
{
selectionPolylinePoints = new List<Point>();
selectionPolylinePoints.Add(args.CurrentPoint.RawPosition);
canvasControl.Invalidate();
}
private void UnprocessedInput_PointerMoved(InkUnprocessedInput sender, Windows.UI.Core.PointerEventArgs args)
{
selectionPolylinePoints.Add(args.CurrentPoint.RawPosition);
canvasControl.Invalidate();
}
private void UnprocessedInput_PointerReleased(InkUnprocessedInput sender, Windows.UI.Core.PointerEventArgs args)
{
selectionPolylinePoints.Add(args.CurrentPoint.RawPosition);
selectionBoundingRect = inkManager.SelectWithPolyLine(selectionPolylinePoints);
selectionPolylinePoints = null;
canvasControl.Invalidate();
}
private void ClearSelection()
{
selectionPolylinePoints = null;
selectionBoundingRect = null;
}
private void CreateSizeDependentResources()
{
renderTarget = new CanvasRenderTarget(canvasControl, canvasControl.Size);
textFormat.FontSize = (float)canvasControl.Size.Width / 10.0f;
}
private async Task LoadThumbnailResources(CanvasControl sender)
{
var thumbnailFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/InkThumbnailStrokes.bin"));
using (var stream = await thumbnailFile.OpenReadAsync())
{
LoadStrokesFromStream(stream.AsStreamForRead());
}
}
private void canvasControl_CreateResources(CanvasControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args)
{
CreateSizeDependentResources();
if (ThumbnailGenerator.IsDrawingThumbnail)
{
args.TrackAsyncAction(LoadThumbnailResources(sender).AsAsyncAction());
}
needToCreateSizeDepdendentResources = false;
}
private void DrawSelectionLasso(CanvasControl sender, CanvasDrawingSession ds)
{
if (selectionPolylinePoints == null) return;
if (selectionPolylinePoints.Count == 0) return;
CanvasPathBuilder selectionLasso = new CanvasPathBuilder(canvasControl);
selectionLasso.BeginFigure(selectionPolylinePoints[0].ToVector2());
for (int i = 1; i < selectionPolylinePoints.Count; ++i)
{
selectionLasso.AddLine(selectionPolylinePoints[i].ToVector2());
}
selectionLasso.EndFigure(CanvasFigureLoop.Open);
CanvasGeometry pathGeometry = CanvasGeometry.CreatePath(selectionLasso);
ds.DrawGeometry(pathGeometry, Colors.Magenta, 5.0f);
}
private void DrawSelectionBoundingRect(CanvasDrawingSession ds)
{
if (selectionBoundingRect == null) return;
if ((selectionBoundingRect.Value.Width == 0) || (selectionBoundingRect.Value.Height == 0) || selectionBoundingRect.Value.IsEmpty)
{
return;
}
ds.DrawRectangle(selectionBoundingRect.Value, Colors.Magenta);
}
private void DrawDryInk_CustomGeometryMethod(CanvasDrawingSession ds, IReadOnlyList<InkStroke> strokes)
{
//
// This shows off the fact that apps can use the custom drying path
// to render dry ink using Win2D, and not necessarily
// rely on the built-in rendering in CanvasDrawingSession.DrawInk.
//
foreach (var stroke in strokes)
{
var color = stroke.DrawingAttributes.Color;
var inkPoints = stroke.GetInkPoints();
if (inkPoints.Count > 0)
{
CanvasPathBuilder pathBuilder = new CanvasPathBuilder(canvasControl);
pathBuilder.BeginFigure(inkPoints[0].Position.ToVector2());
for (int i = 1; i < inkPoints.Count; i++)
{
pathBuilder.AddLine(inkPoints[i].Position.ToVector2());
ds.DrawCircle(inkPoints[i].Position.ToVector2(), 3, color);
}
pathBuilder.EndFigure(CanvasFigureLoop.Open);
CanvasGeometry geometry = CanvasGeometry.CreatePath(pathBuilder);
ds.DrawGeometry(geometry, color);
}
}
}
private void DrawStrokeCollectionToInkSurface(IReadOnlyList<InkStroke> strokes)
{
using (CanvasDrawingSession ds = renderTarget.CreateDrawingSession())
{
if (SelectedDryInkRenderingType == DryInkRenderingType.BuiltIn)
{
ds.DrawInk(strokes);
}
else
{
DrawDryInk_CustomGeometryMethod(ds, strokes);
}
}
}
private void DrawBackgroundText(CanvasDrawingSession ds)
{
if (showTextLabels && !ThumbnailGenerator.IsDrawingThumbnail)
{
textFormat.VerticalAlignment = CanvasVerticalAlignment.Top;
textFormat.HorizontalAlignment = CanvasHorizontalAlignment.Left;
ds.DrawText("Dry Ink Background", new Vector2(10, 10), Colors.DarkGray, textFormat);
}
}
private void DrawForegroundText(CanvasDrawingSession ds)
{
if (showTextLabels && !ThumbnailGenerator.IsDrawingThumbnail)
{
textFormat.VerticalAlignment = CanvasVerticalAlignment.Bottom;
textFormat.HorizontalAlignment = CanvasHorizontalAlignment.Right;
ds.DrawText("Dry Ink Foreground", new Vector2((float)canvasControl.Size.Width - 10, (float)canvasControl.Size.Height - 10), Colors.DarkGoldenrod, textFormat);
}
}
private void canvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
if(needToCreateSizeDepdendentResources)
{
CreateSizeDependentResources();
}
if(needsClear || needsInkSurfaceValidation)
{
ClearInkSurface();
}
if(needsInkSurfaceValidation)
{
DrawStrokeCollectionToInkSurface(strokeList);
}
needToCreateSizeDepdendentResources = false;
needsClear = false;
needsInkSurfaceValidation = false;
DrawBackgroundText(args.DrawingSession);
var strokes = inkSynchronizer.BeginDry();
DrawStrokeCollectionToInkSurface(strokes); // Incremental draw only.
inkSynchronizer.EndDry();
args.DrawingSession.DrawImage(renderTarget);
DrawForegroundText(args.DrawingSession);
DrawSelectionBoundingRect(args.DrawingSession);
DrawSelectionLasso(sender, args.DrawingSession);
}
const string saveFileName = "savedFile.bin";
private void DeleteSelected_Clicked(object sender, RoutedEventArgs e)
{
inkManager.DeleteSelected();
strokeList.Clear();
var strokes = inkManager.GetStrokes();
strokeList.AddRange(strokes);
selectionBoundingRect = null;
needsInkSurfaceValidation = true;
canvasControl.Invalidate();
}
private async void LoadStrokesFromStream(Stream stream)
{
await inkManager.LoadAsync(stream.AsInputStream());
strokeList.Clear();
strokeList.AddRange(inkManager.GetStrokes());
needsInkSurfaceValidation = true;
}
private async void Load_Clicked(object sender, RoutedEventArgs e)
{
try
{
using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(saveFileName))
{
LoadStrokesFromStream(stream);
}
}
catch (FileNotFoundException)
{
MessageDialog dialog = new MessageDialog("No saved data was found.");
await dialog.ShowAsync();
}
canvasControl.Invalidate();
}
private async void Save_Clicked(object sender, RoutedEventArgs e)
{
using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(saveFileName, CreationCollisionOption.ReplaceExisting))
{
await inkManager.SaveAsync(stream.AsOutputStream());
}
}
void ClearInkSurface()
{
using (CanvasDrawingSession ds = renderTarget.CreateDrawingSession())
{
ds.Clear(Colors.Transparent);
}
}
private void Clear_Clicked(object sender, RoutedEventArgs e)
{
strokeList.Clear();
inkManager = new InkManager();
needsClear = true;
canvasControl.Invalidate();
}
void ResetColorSelectors()
{
Button[] buttons = { color0, color1, color2, color3, color4, color5, color6, color7 };
foreach (Button button in buttons)
{
button.BorderBrush = null;
button.BorderThickness = new Thickness(0);
}
}
void SelectColor(Button button)
{
ResetColorSelectors();
button.BorderBrush = new SolidColorBrush(Colors.Red);
button.BorderThickness = new Thickness(3);
InkDrawingAttributes drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
drawingAttributes.Color = ((SolidColorBrush)(button.Background)).Color;
inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
}
private void ColorPickerButton_Clicked(object sender, RoutedEventArgs e)
{
SelectColor((Button)e.OriginalSource);
}
private void StrokeWidth_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
if (inkCanvas != null)
{
InkDrawingAttributes drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
drawingAttributes.Size = new Size(e.NewValue, drawingAttributes.Size.Height);
inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
}
}
private void StrokeHeight_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
if (inkCanvas != null)
{
InkDrawingAttributes drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
drawingAttributes.Size = new Size(drawingAttributes.Size.Width, e.NewValue);
inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
}
}
private void Rotation_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
if (inkCanvas != null)
{
InkDrawingAttributes drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
float radians = Utils.DegreesToRadians((float)e.NewValue);
drawingAttributes.PenTipTransform = Matrix3x2.CreateRotation(radians);
inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
}
}
private void SettingsCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//
// Changing the rendering type will invalidate any ink we've
// already drawn, so we need to wipe the intermediate, and re-draw
// the strokes that have been collected so far.
//
needsInkSurfaceValidation = true;
canvasControl.Invalidate();
}
private void Canvas_SizeChanged(object sender, SizeChangedEventArgs e)
{
needToCreateSizeDepdendentResources = true;
needsInkSurfaceValidation = true;
canvasControl.Invalidate();
}
void ShowTextLabels_Checked(object sender, RoutedEventArgs e)
{
showTextLabels = true;
if(canvasControl != null)
canvasControl.Invalidate();
}
void ShowTextLabels_Unchecked(object sender, RoutedEventArgs e)
{
showTextLabels = false;
if (canvasControl != null)
canvasControl.Invalidate();
}
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;
namespace EdiEngine.Standards.X12_004010.Maps
{
public class M_867 : MapLoop
{
public M_867() : base(null)
{
Content.AddRange(new MapBaseEntity[] {
new BPT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new PSA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new L_LM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_PTD(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
new L_CTT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
//1000
public class L_N1 : MapLoop
{
public L_N1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new L_PER(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//1100
public class L_PER : MapLoop
{
public L_PER(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new PER() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2000
public class L_LM : MapLoop
{
public L_LM(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 },
});
}
}
//3000
public class L_PTD : MapLoop
{
public L_PTD(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new PTD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new PRF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new L_QTY(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//3100
public class L_N1_1 : MapLoop
{
public L_N1_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new L_SII(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//3110
public class L_SII : MapLoop
{
public L_SII(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SII() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//3200
public class L_QTY : MapLoop
{
public L_QTY(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new QTY() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PO3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new PO4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new UIT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new ITA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 },
new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 40 },
new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LDT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LM_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_FA1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//3210
public class L_LM_1 : MapLoop
{
public L_LM_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 },
});
}
}
//3220
public class L_LX : MapLoop
{
public L_LX(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LM_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//3221
public class L_LM_2 : MapLoop
{
public L_LM_2(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 },
});
}
}
//3230
public class L_FA1 : MapLoop
{
public L_FA1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new FA1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new FA2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//4000
public class L_CTT : MapLoop
{
public L_CTT(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new CTT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new ITA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Orchestration.Airflow.Service.V1.Snippets
{
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
using gcoasv = Google.Cloud.Orchestration.Airflow.Service.V1;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedEnvironmentsClientSnippets
{
/// <summary>Snippet for CreateEnvironment</summary>
public void CreateEnvironmentRequestObject()
{
// Snippet: CreateEnvironment(CreateEnvironmentRequest, CallSettings)
// Create client
EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
// Initialize request argument(s)
CreateEnvironmentRequest request = new CreateEnvironmentRequest
{
Parent = "",
Environment = new gcoasv::Environment(),
};
// Make the request
Operation<gcoasv::Environment, OperationMetadata> response = environmentsClient.CreateEnvironment(request);
// Poll until the returned long-running operation is complete
Operation<gcoasv::Environment, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
gcoasv::Environment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcoasv::Environment, OperationMetadata> retrievedResponse = environmentsClient.PollOnceCreateEnvironment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcoasv::Environment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateEnvironmentAsync</summary>
public async Task CreateEnvironmentRequestObjectAsync()
{
// Snippet: CreateEnvironmentAsync(CreateEnvironmentRequest, CallSettings)
// Additional: CreateEnvironmentAsync(CreateEnvironmentRequest, CancellationToken)
// Create client
EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
// Initialize request argument(s)
CreateEnvironmentRequest request = new CreateEnvironmentRequest
{
Parent = "",
Environment = new gcoasv::Environment(),
};
// Make the request
Operation<gcoasv::Environment, OperationMetadata> response = await environmentsClient.CreateEnvironmentAsync(request);
// Poll until the returned long-running operation is complete
Operation<gcoasv::Environment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
gcoasv::Environment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcoasv::Environment, OperationMetadata> retrievedResponse = await environmentsClient.PollOnceCreateEnvironmentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcoasv::Environment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateEnvironment</summary>
public void CreateEnvironment()
{
// Snippet: CreateEnvironment(string, Environment, CallSettings)
// Create client
EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
// Initialize request argument(s)
string parent = "";
gcoasv::Environment environment = new gcoasv::Environment();
// Make the request
Operation<gcoasv::Environment, OperationMetadata> response = environmentsClient.CreateEnvironment(parent, environment);
// Poll until the returned long-running operation is complete
Operation<gcoasv::Environment, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
gcoasv::Environment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcoasv::Environment, OperationMetadata> retrievedResponse = environmentsClient.PollOnceCreateEnvironment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcoasv::Environment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateEnvironmentAsync</summary>
public async Task CreateEnvironmentAsync()
{
// Snippet: CreateEnvironmentAsync(string, Environment, CallSettings)
// Additional: CreateEnvironmentAsync(string, Environment, CancellationToken)
// Create client
EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
gcoasv::Environment environment = new gcoasv::Environment();
// Make the request
Operation<gcoasv::Environment, OperationMetadata> response = await environmentsClient.CreateEnvironmentAsync(parent, environment);
// Poll until the returned long-running operation is complete
Operation<gcoasv::Environment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
gcoasv::Environment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcoasv::Environment, OperationMetadata> retrievedResponse = await environmentsClient.PollOnceCreateEnvironmentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcoasv::Environment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for GetEnvironment</summary>
public void GetEnvironmentRequestObject()
{
// Snippet: GetEnvironment(GetEnvironmentRequest, CallSettings)
// Create client
EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
// Initialize request argument(s)
GetEnvironmentRequest request = new GetEnvironmentRequest { Name = "", };
// Make the request
gcoasv::Environment response = environmentsClient.GetEnvironment(request);
// End snippet
}
/// <summary>Snippet for GetEnvironmentAsync</summary>
public async Task GetEnvironmentRequestObjectAsync()
{
// Snippet: GetEnvironmentAsync(GetEnvironmentRequest, CallSettings)
// Additional: GetEnvironmentAsync(GetEnvironmentRequest, CancellationToken)
// Create client
EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
// Initialize request argument(s)
GetEnvironmentRequest request = new GetEnvironmentRequest { Name = "", };
// Make the request
gcoasv::Environment response = await environmentsClient.GetEnvironmentAsync(request);
// End snippet
}
/// <summary>Snippet for GetEnvironment</summary>
public void GetEnvironment()
{
// Snippet: GetEnvironment(string, CallSettings)
// Create client
EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
gcoasv::Environment response = environmentsClient.GetEnvironment(name);
// End snippet
}
/// <summary>Snippet for GetEnvironmentAsync</summary>
public async Task GetEnvironmentAsync()
{
// Snippet: GetEnvironmentAsync(string, CallSettings)
// Additional: GetEnvironmentAsync(string, CancellationToken)
// Create client
EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
gcoasv::Environment response = await environmentsClient.GetEnvironmentAsync(name);
// End snippet
}
/// <summary>Snippet for ListEnvironments</summary>
public void ListEnvironmentsRequestObject()
{
// Snippet: ListEnvironments(ListEnvironmentsRequest, CallSettings)
// Create client
EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
// Initialize request argument(s)
ListEnvironmentsRequest request = new ListEnvironmentsRequest { Parent = "", };
// Make the request
PagedEnumerable<ListEnvironmentsResponse, gcoasv::Environment> response = environmentsClient.ListEnvironments(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (gcoasv::Environment item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListEnvironmentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (gcoasv::Environment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<gcoasv::Environment> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (gcoasv::Environment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEnvironmentsAsync</summary>
public async Task ListEnvironmentsRequestObjectAsync()
{
// Snippet: ListEnvironmentsAsync(ListEnvironmentsRequest, CallSettings)
// Create client
EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
// Initialize request argument(s)
ListEnvironmentsRequest request = new ListEnvironmentsRequest { Parent = "", };
// Make the request
PagedAsyncEnumerable<ListEnvironmentsResponse, gcoasv::Environment> response = environmentsClient.ListEnvironmentsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((gcoasv::Environment item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListEnvironmentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (gcoasv::Environment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<gcoasv::Environment> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (gcoasv::Environment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEnvironments</summary>
public void ListEnvironments()
{
// Snippet: ListEnvironments(string, string, int?, CallSettings)
// Create client
EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedEnumerable<ListEnvironmentsResponse, gcoasv::Environment> response = environmentsClient.ListEnvironments(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (gcoasv::Environment item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListEnvironmentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (gcoasv::Environment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<gcoasv::Environment> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (gcoasv::Environment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEnvironmentsAsync</summary>
public async Task ListEnvironmentsAsync()
{
// Snippet: ListEnvironmentsAsync(string, string, int?, CallSettings)
// Create client
EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedAsyncEnumerable<ListEnvironmentsResponse, gcoasv::Environment> response = environmentsClient.ListEnvironmentsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((gcoasv::Environment item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListEnvironmentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (gcoasv::Environment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<gcoasv::Environment> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (gcoasv::Environment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for UpdateEnvironment</summary>
public void UpdateEnvironmentRequestObject()
{
// Snippet: UpdateEnvironment(UpdateEnvironmentRequest, CallSettings)
// Create client
EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
// Initialize request argument(s)
UpdateEnvironmentRequest request = new UpdateEnvironmentRequest
{
Environment = new gcoasv::Environment(),
Name = "",
UpdateMask = new FieldMask(),
};
// Make the request
Operation<gcoasv::Environment, OperationMetadata> response = environmentsClient.UpdateEnvironment(request);
// Poll until the returned long-running operation is complete
Operation<gcoasv::Environment, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
gcoasv::Environment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcoasv::Environment, OperationMetadata> retrievedResponse = environmentsClient.PollOnceUpdateEnvironment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcoasv::Environment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateEnvironmentAsync</summary>
public async Task UpdateEnvironmentRequestObjectAsync()
{
// Snippet: UpdateEnvironmentAsync(UpdateEnvironmentRequest, CallSettings)
// Additional: UpdateEnvironmentAsync(UpdateEnvironmentRequest, CancellationToken)
// Create client
EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
// Initialize request argument(s)
UpdateEnvironmentRequest request = new UpdateEnvironmentRequest
{
Environment = new gcoasv::Environment(),
Name = "",
UpdateMask = new FieldMask(),
};
// Make the request
Operation<gcoasv::Environment, OperationMetadata> response = await environmentsClient.UpdateEnvironmentAsync(request);
// Poll until the returned long-running operation is complete
Operation<gcoasv::Environment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
gcoasv::Environment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcoasv::Environment, OperationMetadata> retrievedResponse = await environmentsClient.PollOnceUpdateEnvironmentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcoasv::Environment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateEnvironment</summary>
public void UpdateEnvironment()
{
// Snippet: UpdateEnvironment(string, Environment, FieldMask, CallSettings)
// Create client
EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
// Initialize request argument(s)
string name = "";
gcoasv::Environment environment = new gcoasv::Environment();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<gcoasv::Environment, OperationMetadata> response = environmentsClient.UpdateEnvironment(name, environment, updateMask);
// Poll until the returned long-running operation is complete
Operation<gcoasv::Environment, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
gcoasv::Environment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcoasv::Environment, OperationMetadata> retrievedResponse = environmentsClient.PollOnceUpdateEnvironment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcoasv::Environment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateEnvironmentAsync</summary>
public async Task UpdateEnvironmentAsync()
{
// Snippet: UpdateEnvironmentAsync(string, Environment, FieldMask, CallSettings)
// Additional: UpdateEnvironmentAsync(string, Environment, FieldMask, CancellationToken)
// Create client
EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
gcoasv::Environment environment = new gcoasv::Environment();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<gcoasv::Environment, OperationMetadata> response = await environmentsClient.UpdateEnvironmentAsync(name, environment, updateMask);
// Poll until the returned long-running operation is complete
Operation<gcoasv::Environment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
gcoasv::Environment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcoasv::Environment, OperationMetadata> retrievedResponse = await environmentsClient.PollOnceUpdateEnvironmentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcoasv::Environment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteEnvironment</summary>
public void DeleteEnvironmentRequestObject()
{
// Snippet: DeleteEnvironment(DeleteEnvironmentRequest, CallSettings)
// Create client
EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
// Initialize request argument(s)
DeleteEnvironmentRequest request = new DeleteEnvironmentRequest { Name = "", };
// Make the request
Operation<Empty, OperationMetadata> response = environmentsClient.DeleteEnvironment(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = environmentsClient.PollOnceDeleteEnvironment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteEnvironmentAsync</summary>
public async Task DeleteEnvironmentRequestObjectAsync()
{
// Snippet: DeleteEnvironmentAsync(DeleteEnvironmentRequest, CallSettings)
// Additional: DeleteEnvironmentAsync(DeleteEnvironmentRequest, CancellationToken)
// Create client
EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
// Initialize request argument(s)
DeleteEnvironmentRequest request = new DeleteEnvironmentRequest { Name = "", };
// Make the request
Operation<Empty, OperationMetadata> response = await environmentsClient.DeleteEnvironmentAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await environmentsClient.PollOnceDeleteEnvironmentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteEnvironment</summary>
public void DeleteEnvironment()
{
// Snippet: DeleteEnvironment(string, CallSettings)
// Create client
EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
Operation<Empty, OperationMetadata> response = environmentsClient.DeleteEnvironment(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = environmentsClient.PollOnceDeleteEnvironment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteEnvironmentAsync</summary>
public async Task DeleteEnvironmentAsync()
{
// Snippet: DeleteEnvironmentAsync(string, CallSettings)
// Additional: DeleteEnvironmentAsync(string, CancellationToken)
// Create client
EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
Operation<Empty, OperationMetadata> response = await environmentsClient.DeleteEnvironmentAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await environmentsClient.PollOnceDeleteEnvironmentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class RecordingSignalEventEncoder
{
public const ushort BLOCK_LENGTH = 44;
public const ushort TEMPLATE_ID = 24;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private RecordingSignalEventEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public RecordingSignalEventEncoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public RecordingSignalEventEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public RecordingSignalEventEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public RecordingSignalEventEncoder ControlSessionId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public RecordingSignalEventEncoder CorrelationId(long value)
{
_buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int RecordingIdEncodingOffset()
{
return 16;
}
public static int RecordingIdEncodingLength()
{
return 8;
}
public static long RecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long RecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long RecordingIdMaxValue()
{
return 9223372036854775807L;
}
public RecordingSignalEventEncoder RecordingId(long value)
{
_buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian);
return this;
}
public static int SubscriptionIdEncodingOffset()
{
return 24;
}
public static int SubscriptionIdEncodingLength()
{
return 8;
}
public static long SubscriptionIdNullValue()
{
return -9223372036854775808L;
}
public static long SubscriptionIdMinValue()
{
return -9223372036854775807L;
}
public static long SubscriptionIdMaxValue()
{
return 9223372036854775807L;
}
public RecordingSignalEventEncoder SubscriptionId(long value)
{
_buffer.PutLong(_offset + 24, value, ByteOrder.LittleEndian);
return this;
}
public static int PositionEncodingOffset()
{
return 32;
}
public static int PositionEncodingLength()
{
return 8;
}
public static long PositionNullValue()
{
return -9223372036854775808L;
}
public static long PositionMinValue()
{
return -9223372036854775807L;
}
public static long PositionMaxValue()
{
return 9223372036854775807L;
}
public RecordingSignalEventEncoder Position(long value)
{
_buffer.PutLong(_offset + 32, value, ByteOrder.LittleEndian);
return this;
}
public static int SignalEncodingOffset()
{
return 40;
}
public static int SignalEncodingLength()
{
return 4;
}
public RecordingSignalEventEncoder Signal(RecordingSignal value)
{
_buffer.PutInt(_offset + 40, (int)value, ByteOrder.LittleEndian);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
RecordingSignalEventDecoder writer = new RecordingSignalEventDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| |
// 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.Globalization {
using System;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
// This abstract class represents a calendar. A calendar reckons time in
// divisions such as weeks, months and years. The number, length and start of
// the divisions vary in each calendar.
//
// Any instant in time can be represented as an n-tuple of numeric values using
// a particular calendar. For example, the next vernal equinox occurs at (0.0, 0
// , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of
// Calendar can map any DateTime value to such an n-tuple and vice versa. The
// DateTimeFormat class can map between such n-tuples and a textual
// representation such as "8:46 AM March 20th 1999 AD".
//
// Most calendars identify a year which begins the current era. There may be any
// number of previous eras. The Calendar class identifies the eras as enumerated
// integers where the current era (CurrentEra) has the value zero.
//
// For consistency, the first unit in each interval, e.g. the first month, is
// assigned the value one.
// The calculation of hour/minute/second is moved to Calendar from GregorianCalendar,
// since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Calendar : ICloneable
{
// Number of 100ns (10E-7 second) ticks per time unit
internal const long TicksPerMillisecond = 10000;
internal const long TicksPerSecond = TicksPerMillisecond * 1000;
internal const long TicksPerMinute = TicksPerSecond * 60;
internal const long TicksPerHour = TicksPerMinute * 60;
internal const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
internal const int MillisPerSecond = 1000;
internal const int MillisPerMinute = MillisPerSecond * 60;
internal const int MillisPerHour = MillisPerMinute * 60;
internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
internal const int DaysPerYear = 365;
// Number of days in 4 years
internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 1/1/10000
internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
//
// Calendar ID Values. This is used to get data from calendar.nlp.
// The order of calendar ID means the order of data items in the table.
//
internal const int CAL_GREGORIAN = 1 ; // Gregorian (localized) calendar
internal const int CAL_GREGORIAN_US = 2 ; // Gregorian (U.S.) calendar
internal const int CAL_JAPAN = 3 ; // Japanese Emperor Era calendar
internal const int CAL_TAIWAN = 4 ; // Taiwan Era calendar
internal const int CAL_KOREA = 5 ; // Korean Tangun Era calendar
internal const int CAL_HIJRI = 6 ; // Hijri (Arabic Lunar) calendar
internal const int CAL_THAI = 7 ; // Thai calendar
internal const int CAL_HEBREW = 8 ; // Hebrew (Lunar) calendar
internal const int CAL_GREGORIAN_ME_FRENCH = 9 ; // Gregorian Middle East French calendar
internal const int CAL_GREGORIAN_ARABIC = 10; // Gregorian Arabic calendar
internal const int CAL_GREGORIAN_XLIT_ENGLISH = 11; // Gregorian Transliterated English calendar
internal const int CAL_GREGORIAN_XLIT_FRENCH = 12;
internal const int CAL_JULIAN = 13;
internal const int CAL_JAPANESELUNISOLAR = 14;
internal const int CAL_CHINESELUNISOLAR = 15;
internal const int CAL_SAKA = 16; // reserved to match Office but not implemented in our code
internal const int CAL_LUNAR_ETO_CHN = 17; // reserved to match Office but not implemented in our code
internal const int CAL_LUNAR_ETO_KOR = 18; // reserved to match Office but not implemented in our code
internal const int CAL_LUNAR_ETO_ROKUYOU = 19; // reserved to match Office but not implemented in our code
internal const int CAL_KOREANLUNISOLAR = 20;
internal const int CAL_TAIWANLUNISOLAR = 21;
internal const int CAL_PERSIAN = 22;
internal const int CAL_UMALQURA = 23;
internal int m_currentEraValue = -1;
[System.Runtime.Serialization.OptionalField(VersionAdded = 2)]
private bool m_isReadOnly = false;
// The minimum supported DateTime range for the calendar.
[System.Runtime.InteropServices.ComVisible(false)]
public virtual DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
// The maximum supported DateTime range for the calendar.
[System.Runtime.InteropServices.ComVisible(false)]
public virtual DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
protected Calendar() {
//Do-nothing constructor.
}
///
// This can not be abstract, otherwise no one can create a subclass of Calendar.
//
internal virtual int ID {
get {
return (-1);
}
}
///
// Return the Base calendar ID for calendars that didn't have defined data in calendarData
//
internal virtual int BaseCalendarID
{
get { return ID; }
}
// Returns the type of the calendar.
//
[System.Runtime.InteropServices.ComVisible(false)]
public virtual CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.Unknown;
}
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public bool IsReadOnly
{
get { return (m_isReadOnly); }
}
////////////////////////////////////////////////////////////////////////
//
// Clone
//
// Is the implementation of ICloneable.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public virtual Object Clone()
{
object o = MemberwiseClone();
((Calendar) o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public static Calendar ReadOnly(Calendar calendar)
{
if (calendar == null) { throw new ArgumentNullException("calendar"); }
Contract.EndContractBlock();
if (calendar.IsReadOnly) { return (calendar); }
Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone());
clonedCalendar.SetReadOnlyState(true);
return (clonedCalendar);
}
internal void VerifyWritable()
{
if (m_isReadOnly)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
}
internal void SetReadOnlyState(bool readOnly)
{
m_isReadOnly = readOnly;
}
/*=================================CurrentEraValue==========================
**Action: This is used to convert CurretEra(0) to an appropriate era value.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** The value is from calendar.nlp.
============================================================================*/
internal virtual int CurrentEraValue {
get {
// The following code assumes that the current era value can not be -1.
if (m_currentEraValue == -1) {
Contract.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0");
m_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (m_currentEraValue);
}
}
// The current era for a calendar.
public const int CurrentEra = 0;
internal int twoDigitYearMax = -1;
internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue) {
if (ticks < minValue.Ticks || ticks > maxValue.Ticks) {
throw new ArgumentException(
String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Argument_ResultCalendarRange"),
minValue, maxValue));
}
Contract.EndContractBlock();
}
internal DateTime Add(DateTime time, double value, int scale) {
// From ECMA CLI spec, Partition III, section 3.27:
//
// If overflow occurs converting a floating-point type to an integer, or if the floating-point value
// being converted to an integer is a NaN, the value returned is unspecified.
//
// Based upon this, this method should be performing the comparison against the double
// before attempting a cast. Otherwise, the result is undefined.
double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5));
if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis)))
{
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
}
long millis = (long)tempMillis;
long ticks = time.Ticks + millis * TicksPerMillisecond;
CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// milliseconds to the specified DateTime. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to the specified DateTime. The value
// argument is permitted to be negative.
//
public virtual DateTime AddMilliseconds(DateTime time, double milliseconds) {
return (Add(time, milliseconds, 1));
}
// Returns the DateTime resulting from adding a fractional number of
// days to the specified DateTime. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddDays(DateTime time, int days) {
return (Add(time, days, MillisPerDay));
}
// Returns the DateTime resulting from adding a fractional number of
// hours to the specified DateTime. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddHours(DateTime time, int hours) {
return (Add(time, hours, MillisPerHour));
}
// Returns the DateTime resulting from adding a fractional number of
// minutes to the specified DateTime. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddMinutes(DateTime time, int minutes) {
return (Add(time, minutes, MillisPerMinute));
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public abstract DateTime AddMonths(DateTime time, int months);
// Returns the DateTime resulting from adding a number of
// seconds to the specified DateTime. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddSeconds(DateTime time, int seconds) {
return Add(time, seconds, MillisPerSecond);
}
// Returns the DateTime resulting from adding a number of
// weeks to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddWeeks(DateTime time, int weeks) {
return (AddDays(time, weeks * 7));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public abstract DateTime AddYears(DateTime time, int years);
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public abstract int GetDayOfMonth(DateTime time);
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public abstract DayOfWeek GetDayOfWeek(DateTime time);
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public abstract int GetDayOfYear(DateTime time);
// Returns the number of days in the month given by the year and
// month arguments.
//
public virtual int GetDaysInMonth(int year, int month)
{
return (GetDaysInMonth(year, month, CurrentEra));
}
// Returns the number of days in the month given by the year and
// month arguments for the specified era.
//
public abstract int GetDaysInMonth(int year, int month, int era);
// Returns the number of days in the year given by the year argument for the current era.
//
public virtual int GetDaysInYear(int year)
{
return (GetDaysInYear(year, CurrentEra));
}
// Returns the number of days in the year given by the year argument for the current era.
//
public abstract int GetDaysInYear(int year, int era);
// Returns the era for the specified DateTime value.
public abstract int GetEra(DateTime time);
/*=================================Eras==========================
**Action: Get the list of era values.
**Returns: The int array of the era names supported in this calendar.
** null if era is not used.
**Arguments: None.
**Exceptions: None.
============================================================================*/
public abstract int[] Eras {
get;
}
// Returns the hour part of the specified DateTime. The returned value is an
// integer between 0 and 23.
//
public virtual int GetHour(DateTime time) {
return ((int)((time.Ticks / TicksPerHour) % 24));
}
// Returns the millisecond part of the specified DateTime. The returned value
// is an integer between 0 and 999.
//
public virtual double GetMilliseconds(DateTime time) {
return (double)((time.Ticks / TicksPerMillisecond) % 1000);
}
// Returns the minute part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetMinute(DateTime time) {
return ((int)((time.Ticks / TicksPerMinute) % 60));
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public abstract int GetMonth(DateTime time);
// Returns the number of months in the specified year in the current era.
public virtual int GetMonthsInYear(int year)
{
return (GetMonthsInYear(year, CurrentEra));
}
// Returns the number of months in the specified year and era.
public abstract int GetMonthsInYear(int year, int era);
// Returns the second part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetSecond(DateTime time) {
return ((int)((time.Ticks / TicksPerSecond) % 60));
}
/*=================================GetFirstDayWeekOfYear==========================
**Action: Get the week of year using the FirstDay rule.
**Returns: the week of year.
**Arguments:
** time
** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday)
**Notes:
** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year.
** Assume f is the specifed firstDayOfWeek,
** and n is the day of week for January 1 of the specified year.
** Assign offset = n - f;
** Case 1: offset = 0
** E.g.
** f=1
** weekday 0 1 2 3 4 5 6 0 1
** date 1/1
** week# 1 2
** then week of year = (GetDayOfYear(time) - 1) / 7 + 1
**
** Case 2: offset < 0
** e.g.
** n=1 f=3
** weekday 0 1 2 3 4 5 6 0
** date 1/1
** week# 1 2
** This means that the first week actually starts 5 days before 1/1.
** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1
** Case 3: offset > 0
** e.g.
** f=0 n=2
** weekday 0 1 2 3 4 5 6 0 1 2
** date 1/1
** week# 1 2
** This means that the first week actually starts 2 days before 1/1.
** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1
============================================================================*/
internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek) {
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
// Calculate the day of week for the first day of the year.
// dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays) {
int dayForJan1;
int offset;
int day;
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
//
// Calculate the number of days between the first day of year (1/1) and the first day of the week.
// This value will be a positive value from 0 ~ 6. We call this value as "offset".
//
// If offset is 0, it means that the 1/1 is the start of the first week.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 12/31 1/1 1/2 1/3 1/4 1/5 1/6
// +--> First week starts here.
//
// If offset is 1, it means that the first day of the week is 1 day ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7
// +--> First week starts here.
//
// If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sat Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8
// +--> First week starts here.
// Day of week is 0-based.
// Get the day of week for 1/1. This can be derived from the day of week of the target day.
// Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset.
dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
// Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value.
offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
if (offset != 0 && offset >= fullDays)
{
//
// If the offset is greater than the value of fullDays, it means that
// the first week of the year starts on the week where Jan/1 falls on.
//
offset -= 7;
}
//
// Calculate the day of year for specified time by taking offset into account.
//
day = dayOfYear - offset;
if (day >= 0) {
//
// If the day of year value is greater than zero, get the week of year.
//
return (day/7 + 1);
}
//
// Otherwise, the specified time falls on the week of previous year.
// Call this method again by passing the last day of previous year.
//
// the last day of the previous year may "underflow" to no longer be a valid date time for
// this calendar if we just subtract so we need the subclass to provide us with
// that information
if (time <= MinSupportedDateTime.AddDays(dayOfYear))
{
return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays);
}
return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays));
}
private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek)
{
int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7;
// Calculate the offset (how many days from the start of the year to the start of the week)
int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7;
if (offset == 0 || offset >= minimumDaysInFirstWeek)
{
// First of year falls in the first week of the year
return 1;
}
int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7);
// starting from first day of the year, how many days do you have to go forward
// before getting to the first day of the week?
int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7;
int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek;
if (daysInInitialPartialWeek >= minimumDaysInFirstWeek)
{
// If the offset is greater than the minimum Days in the first week, it means that
// First of year is part of the first week of the year even though it is only a partial week
// add another week
day += 7;
}
return (day / 7 + 1);
}
// it would be nice to make this abstract but we can't since that would break previous implementations
protected virtual int DaysInYearBeforeMinSupportedYear
{
get
{
return 365;
}
}
// Returns the week of year for the specified DateTime. The returned value is an
// integer between 1 and 53.
//
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) {
throw new ArgumentOutOfRangeException(
"firstDayOfWeek", Environment.GetResourceString("ArgumentOutOfRange_Range",
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
switch (rule) {
case CalendarWeekRule.FirstDay:
return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
case CalendarWeekRule.FirstFullWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7));
case CalendarWeekRule.FirstFourDayWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4));
}
throw new ArgumentOutOfRangeException(
"rule", Environment.GetResourceString("ArgumentOutOfRange_Range",
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public abstract int GetYear(DateTime time);
// Checks whether a given day in the current era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public virtual bool IsLeapDay(int year, int month, int day)
{
return (IsLeapDay(year, month, day, CurrentEra));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public abstract bool IsLeapDay(int year, int month, int day, int era);
// Checks whether a given month in the current era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public virtual bool IsLeapMonth(int year, int month) {
return (IsLeapMonth(year, month, CurrentEra));
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public abstract bool IsLeapMonth(int year, int month, int era);
// Returns the leap month in a calendar year of the current era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetLeapMonth(int year)
{
return (GetLeapMonth(year, CurrentEra));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetLeapMonth(int year, int era)
{
if (!IsLeapYear(year, era))
return 0;
int monthsCount = GetMonthsInYear(year, era);
for (int month=1; month<=monthsCount; month++)
{
if (IsLeapMonth(year, month, era))
return month;
}
return 0;
}
// Checks whether a given year in the current era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public virtual bool IsLeapYear(int year)
{
return (IsLeapYear(year, CurrentEra));
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public abstract bool IsLeapYear(int year, int era);
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era);
internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) {
result = DateTime.MinValue;
try {
result = ToDateTime(year, month, day, hour, minute, second, millisecond, era);
return true;
}
catch (ArgumentException) {
return false;
}
}
internal virtual bool IsValidYear(int year, int era) {
return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime));
}
internal virtual bool IsValidMonth(int year, int month, int era) {
return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era));
}
internal virtual bool IsValidDay(int year, int month, int day, int era)
{
return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era));
}
// Returns and assigns the maximum value to represent a two digit year. This
// value is the upper boundary of a 100 year range that allows a two digit year
// to be properly translated to a four digit year. For example, if 2029 is the
// upper boundary, then a two digit value of 30 should be interpreted as 1930
// while a two digit value of 29 should be interpreted as 2029. In this example
// , the 100 year range would be from 1930-2029. See ToFourDigitYear().
public virtual int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
twoDigitYearMax = value;
}
}
// Converts the year value to the appropriate century by using the
// TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029,
// then a two digit value of 30 will get converted to 1930 while a two digit
// value of 29 will get converted to 2029.
public virtual int ToFourDigitYear(int year) {
if (year < 0) {
throw new ArgumentOutOfRangeException("year",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
if (year < 100) {
return ((TwoDigitYearMax/100 - ( year > TwoDigitYearMax % 100 ? 1 : 0))*100 + year);
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
// Return the tick count corresponding to the given hour, minute, second.
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond) {
throw new ArgumentOutOfRangeException(
"millisecond",
String.Format(
CultureInfo.InvariantCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1));
}
return TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
}
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"));
}
[System.Security.SecuritySafeCritical] // auto-generated
internal static int GetSystemTwoDigitYearSetting(int CalID, int defaultYearValue)
{
// Call nativeGetTwoDigitYearMax
int twoDigitYearMax = CalendarData.nativeGetTwoDigitYearMax(CalID);
if (twoDigitYearMax < 0)
{
twoDigitYearMax = defaultYearValue;
}
return (twoDigitYearMax);
}
}
}
| |
using Xunit;
namespace ReverseMarkdown.Test
{
public class ConverterTests
{
[Fact]
public void WhenThereIsHtmlLink_ThenConvertToMarkdownLink()
{
const string html = @"This is <a href=""http://test.com"">a link</a>";
const string expected = @"This is [a link](http://test.com)";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereAreMultipleLinks_ThenConvertThemToMarkdownLinks()
{
const string html = @"This is <a href=""http://test.com"">first link</a> and <a href=""http://test1.com"">second link</a>";
const string expected = @"This is [first link](http://test.com) and [second link](http://test1.com)";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereAreStrongTag_ThenConvertToMarkdownDoubleAstericks()
{
const string html = @"This paragraph contains <strong>bold</strong> text";
const string expected = @"This paragraph contains **bold** text";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereAreBTag_ThenConvertToMarkdownDoubleAstericks()
{
const string html = @"This paragraph contains <b>bold</b> text";
const string expected = @"This paragraph contains **bold** text";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsEncompassingStrongOrBTag_ThenConvertToMarkdownDoubleAstericks_AnyStrongOrBTagsInsideAreIgnored()
{
const string html = @"<strong>Paragraph is encompassed with strong tag and also has <b>bold</b> text words within it</strong>";
const string expected = @"**Paragraph is encompassed with strong tag and also has bold text words within it**";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsSingleAsterickInText_ThenConvertToMarkdownEscapedAsterick()
{
const string html = @"This is a sample(*) paragraph";
const string expected = @"This is a sample(\*) paragraph";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsEmTag_ThenConvertToMarkdownSingleAstericks()
{
const string html = @"This is a <em>sample</em> paragraph";
const string expected = @"This is a *sample* paragraph";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsITag_ThenConvertToMarkdownSingleAstericks()
{
const string html = @"This is a <i>sample</i> paragraph";
const string expected = @"This is a *sample* paragraph";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsEncompassingEmOrITag_ThenConvertToMarkdownSingleAstericks_AnyEmOrITagsInsideAreIgnored()
{
const string html = @"<em>This is a <span><i>sample</i></span> paragraph<em>";
const string expected = @"*This is a sample paragraph*";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsBreakTag_ThenConvertToMarkdownDoubleSpacesCarriagleReturn()
{
const string html = @"This is a paragraph.<br />This line appears after break.";
string expected = @"This is a paragraph.
This line appears after break.";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsCodeTag_ThenConvertToMarkdownWithBackTick()
{
const string html = @"This text has code <code>alert();</code>";
const string expected = @"This text has code `alert();`";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsH1Tag_ThenConvertToMarkdownHeader()
{
const string html = @"This text has <h1>header</h1>. This text appear after header.";
const string expected = @"This text has
# header
. This text appear after header.";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsH2Tag_ThenConvertToMarkdownHeader()
{
const string html = @"This text has <h2>header</h2>. This text appear after header.";
const string expected = @"This text has
## header
. This text appear after header.";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsH3Tag_ThenConvertToMarkdownHeader()
{
const string html = @"This text has <h3>header</h3>. This text appear after header.";
const string expected = @"This text has
### header
. This text appear after header.";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsH4Tag_ThenConvertToMarkdownHeader()
{
const string html = @"This text has <h4>header</h4>. This text appear after header.";
const string expected = @"This text has
#### header
. This text appear after header.";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsH5Tag_ThenConvertToMarkdownHeader()
{
const string html = @"This text has <h5>header</h5>. This text appear after header.";
const string expected = @"This text has
##### header
. This text appear after header.";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsH6Tag_ThenConvertToMarkdownHeader()
{
const string html = @"This text has <h6>header</h6>. This text appear after header.";
const string expected = @"This text has
###### header
. This text appear after header.";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsBlockquoteTag_ThenConvertToMarkdownBlockquote()
{
const string html = @"This text has <blockquote>blockquote</blockquote>. This text appear after header.";
const string expected = @"This text has
> blockquote
. This text appear after header.";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsEmptyBlockquoteTag_ThenConvertToMarkdownBlockquote()
{
const string html = @"This text has <blockquote></blockquote>. This text appear after header.";
const string expected = @"This text has
. This text appear after header.";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsParagraphTag_ThenConvertToMarkdownDoubleLineBreakBeforeAndAfter()
{
const string html = @"This text has markup <p>paragraph.</p> Next line of text";
const string expected = @"This text has markup
paragraph.
Next line of text";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsHorizontalRule_ThenConvertToMarkdownHorizontalRule()
{
const string html = @"This text has horizontal rule.<hr/>Next line of text";
const string expected = @"This text has horizontal rule.
* * *
Next line of text";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsImgTag_ThenConvertToMarkdownImage()
{
const string html = @"This text has image <img alt=""alt"" title=""title"" src=""http://test.com/images/test.png""/>. Next line of text";
const string expected = @"This text has image . Next line of text";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsImgTagWithoutTitle_ThenConvertToMarkdownImagewithoutTitle()
{
const string html = @"This text has image <img alt=""alt"" src=""http://test.com/images/test.png""/>. Next line of text";
const string expected = @"This text has image . Next line of text";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsImgTagWithoutAltText_ThenConvertToMarkdownImagewithoutAltText()
{
const string html = @"This text has image <img src=""http://test.com/images/test.png""/>. Next line of text";
const string expected = @"This text has image . Next line of text";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsPreTag_ThenConvertToMarkdownPre()
{
const string html = @"This text has pre tag content <pre>Predefined text</pre>Next line of text";
const string expected = @"This text has pre tag content
Predefined text
Next line of text";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsEmptyPreTag_ThenConvertToMarkdownPre()
{
const string html = @"This text has pre tag content <pre><br/ ></pre>Next line of text";
const string expected = @"This text has pre tag content
Next line of text";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsUnorderedList_ThenConvertToMarkdownList()
{
const string html = @"This text has unordered list.<ul><li>Item1</li><li>Item2</li></ul>";
const string expected = @"This text has unordered list.
- Item1
- Item2
";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsOrderedList_ThenConvertToMarkdownList()
{
const string html = @"This text has ordered list.<ol><li>Item1</li><li>Item2</li></ol>";
const string expected = @"This text has ordered list.
1. Item1
2. Item2
";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsOrderedListWithNestedUnorderedList_ThenConvertToMarkdownListWithNestedList()
{
const string html = @"This text has ordered list.<ol><li><ul><li>InnerItem1</li><li>InnerItem2</li></ul></li><li>Item2</li></ol>";
const string expected = @"This text has ordered list.
1. - InnerItem1
- InnerItem2
2. Item2
";
CheckConversion(html, expected);
}
[Fact]
public void WhenThereIsUnorderedListWithNestedOrderedList_ThenConvertToMarkdownListWithNestedList()
{
const string html = @"This text has ordered list.<ul><li><ol><li>InnerItem1</li><li>InnerItem2</li></ol></li><li>Item2</li></ul>";
const string expected = @"This text has ordered list.
- 1. InnerItem1
2. InnerItem2
- Item2
";
CheckConversion(html, expected);
}
[Fact]
public void WhenListItemTextContainsLeadingAndTrailingSpacesAndTabs_TheConvertToMarkdownListItemWithSpacesAndTabsStripped()
{
const string html = @"<ol><li> This is a text with leading and trailing spaces and tabs </li></ol>";
const string expected = @"
1. This is a text with leading and trailing spaces and tabs
";
CheckConversion(html, expected);
}
[Fact]
public void WhenListContainsNewlineAndTabBetweenTagBorders_CleanupAndConvertToMarkdown()
{
const string html = @"<ol>
<li>
<strong>Item1</strong></li>
<li>
Item2</li></ol>";
const string expected = @"
1. **Item1**
2. Item2
";
CheckConversion(html, expected);
}
[Fact]
public void WhenListContainsMultipleParagraphs_ConvertToMarkdownAndIndentSiblings()
{
const string html = @"<ol>
<li>
<p>Item1</p>
<p>Item2</p></li>
<li>
<p>Item3</p></li></ol>";
const string expected = @"
1. Item1
Item2
2. Item3
";
CheckConversion(html, expected);
}
private static void CheckConversion(string html, string expected)
{
var converter = new Converter();
var result = converter.Convert(html);
Assert.Equal<string>(expected, result);
}
}
}
| |
using Android.App;
using Android.OS;
using MvvmCross.Droid.Views;
using Android.Webkit;
using Android.Views;
using Android.Widget;
using Android.Views.Animations;
using Android.Content;
using Android.Speech;
using Android.Speech.Tts;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ProgrammingSupport.Core.ViewModels;
namespace ProgrammingSupport.Droid.Views
{
[Activity(Label = "View for FirstViewModel", ScreenOrientation = Android.Content.PM.ScreenOrientation.Landscape)]
public class FirstView : MvxActivity, TextToSpeech.IOnInitListener
{
private WebView _webView;
private RelativeLayout _click;
private ImageView _text;
private bool isRecording = false;
private readonly int VOICE = 10;
private TextToSpeech speaker;
private string toSpeak;
private Intent _voiceIntent;
private FirstViewModel FirstViewModel
{
get { return (ViewModel as FirstViewModel); }
}
protected override void OnCreate(Bundle bundle)
{
ActionBar.Hide();
base.OnCreate(bundle);
SetContentView(Resource.Layout.FirstView);
_webView = FindViewById<WebView>(Resource.Id.webview);
_click = FindViewById<RelativeLayout>(Resource.Id.clickLayout);
_text = FindViewById<ImageView>(Resource.Id.txtBubble);
string fileName = "file:///android_asset/Content/southparkidle.gif";
_webView.LoadDataWithBaseURL(null, "<html><body style=\"width: 100%; height:100%; margin:0px; padding:0px;\">\n<img style=\"width: 100%; height:100%; margin:0px; padding:0px;\" id=\"selector\" src=\"" + fileName + "\"></body></html>", "text/html", "utf-8", null);
//_webView.LoadDataWithBaseURL(null, "<html><body style=\"width: 100%; height:100%; margin:0px; padding:0px;\">\n<img style=\"width: 100%; height:100%; margin:0px; padding:0px;\" id=\"selector\" src=\"https://media.giphy.com/media/1iUlZloL4DiH8HL2/giphy.gif\"></body></html>", "text/html", "utf-8", null);
_webView.Settings.JavaScriptEnabled = true;
_webView.SetBackgroundColor(Android.Graphics.Color.Transparent);
string rec = Android.Content.PM.PackageManager.FeatureMicrophone;
if (rec != "android.hardware.microphone")
{
var alert = new AlertDialog.Builder(this);
alert.SetTitle("You don't seem to have a microphone to record with");
alert.Show();
}
else
_click.Click += delegate
{
_text.Visibility = ViewStates.Invisible;
isRecording = !isRecording;
if (isRecording)
{
// create the intent and start the activity
_voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
_voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
// put a message on the modal dialog
_voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, "Speak now!");
// if there is more then 1.5s of silence, consider the speech over
_voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 2500);
_voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 2500);
_voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 20000);
_voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1);
// you can specify other languages recognised here, for example
// voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.German);
// if you wish it to recognise the default Locale language and German
// if you do use another locale, regional dialects may not be recognised very well
_voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.English);
StartActivityForResult(_voiceIntent, VOICE);
}
};
}
private bool pizza = false;
private bool skype = false;
protected override async void OnActivityResult(int requestCode, Result resultVal, Intent data)
{
if (requestCode == VOICE)
{
if (resultVal == Result.Ok)
{
var matches = data.GetStringArrayListExtra(RecognizerIntent.ExtraResults);
if (matches.Count != 0)
{
string textInput = matches[0];
// limit the output to 500 characters
if (textInput.Length > 500)
textInput = textInput.Substring(0, 500);
var ditIsResult = textInput;
if (skype)
{
if (ditIsResult.ToLower().Contains("yes"))
{
Speak("Opening Skype Bot for you.");
skype = false;
(ViewModel as FirstViewModel).GoToAnswerCommand.Execute(null);
}
else if (ditIsResult.ToLower().Contains("no"))
{
Speak("Why did you ask then, you stupid asshole!");
skype = false;
_text.SetImageResource(Resource.Drawable.txtWhyAsk);
_text.Visibility = ViewStates.Visible;
}
else
{
Speak("Speak up, you mumbling idiot!");
_text.SetImageResource(Resource.Drawable.txtSpeakUp);
_text.Visibility = ViewStates.Visible;
}
}
else if (textInput.Contains("Skype") && textInput.Contains("open") || textInput.Contains("bot"))
{
//(ViewModel as QuestionViewModel).Question = textInput;
skype = true;
Speak("Do you want to see our Skype bot?");
_text.SetImageResource(Resource.Drawable.txtSkypeBot);
_text.Visibility = ViewStates.Visible;
}
else if (pizza)
{
if (ditIsResult.ToLower().Contains("yes"))
{
Speak("I will get you a pepperoni pizza, buddy!");
pizza = false;
_text.SetImageResource(Resource.Drawable.txtPizzaYes);
_text.Visibility = ViewStates.Visible;
}
else if (ditIsResult.ToLower().Contains("no"))
{
Speak("More for me, you fat fuck!");
pizza = false;
_text.SetImageResource(Resource.Drawable.txtPizzaNo);
_text.Visibility = ViewStates.Visible;
}
else
{
Speak("Speak up, you mumbling idiot!");
_text.SetImageResource(Resource.Drawable.txtSpeakUp);
_text.Visibility = ViewStates.Visible;
}
}
else
{
//Speak("You want to search Stackoverflow for: " + textInput + "?");
Random rnd = new Random();
if (rnd.Next(2) == 0)
_text.SetImageResource(Resource.Drawable.txtImSorry);
else
_text.SetImageResource(Resource.Drawable.txtPizza);
_text.Visibility = ViewStates.Visible;
Speak("I am sorry, I could not find " + ditIsResult + ". Would you like a pizza?");
pizza = true;
await Task.Delay(5000).ConfigureAwait(false);
StartActivityForResult(_voiceIntent, VOICE);
}
}
else
Speak("No speech was recognised");
isRecording = false;
}
}
base.OnActivityResult(requestCode, resultVal, data);
}
public void Speak(string text)
{
toSpeak = text;
if (speaker == null)
{
speaker = new TextToSpeech(this, this);
speaker.SetPitch(1.5f);
speaker.SetSpeechRate(1.5f);
speaker.SetLanguage(Java.Util.Locale.English);
}
else {
var p = new Dictionary<string, string>();
speaker.Speak(toSpeak, QueueMode.Flush, p);
}
}
public override void OnBackPressed()
{
speaker?.Stop();
base.OnBackPressed();
}
void TextToSpeech.IOnInitListener.OnInit(OperationResult status)
{
if (status.Equals(OperationResult.Success))
{
var p = new Dictionary<string, string>();
speaker.Speak(toSpeak, QueueMode.Flush, p);
}
}
}
}
| |
// Copyright 2017, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Language.V1
{
/// <summary>
/// Settings for a <see cref="LanguageServiceClient"/>.
/// </summary>
public sealed partial class LanguageServiceSettings : ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="LanguageServiceSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="LanguageServiceSettings"/>.
/// </returns>
public static LanguageServiceSettings GetDefault() => new LanguageServiceSettings();
/// <summary>
/// Constructs a new <see cref="LanguageServiceSettings"/> object with default settings.
/// </summary>
public LanguageServiceSettings() { }
private LanguageServiceSettings(LanguageServiceSettings existing) : base(existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
AnalyzeSentimentSettings = existing.AnalyzeSentimentSettings;
AnalyzeEntitiesSettings = existing.AnalyzeEntitiesSettings;
AnalyzeEntitySentimentSettings = existing.AnalyzeEntitySentimentSettings;
AnalyzeSyntaxSettings = existing.AnalyzeSyntaxSettings;
AnnotateTextSettings = existing.AnnotateTextSettings;
OnCopy(existing);
}
partial void OnCopy(LanguageServiceSettings existing);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="LanguageServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> IdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="LanguageServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "NonIdempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> NonIdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.Unavailable);
/// <summary>
/// "Default" retry backoff for <see cref="LanguageServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="LanguageServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="LanguageServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 60000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.3</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(100),
maxDelay: TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.3
);
/// <summary>
/// "Default" timeout backoff for <see cref="LanguageServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="LanguageServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="LanguageServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Maximum timeout: 60000 milliseconds</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(60000),
maxDelay: TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.0
);
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>LanguageServiceClient.AnalyzeSentiment</c> and <c>LanguageServiceClient.AnalyzeSentimentAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>LanguageServiceClient.AnalyzeSentiment</c> and
/// <c>LanguageServiceClient.AnalyzeSentimentAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings AnalyzeSentimentSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>LanguageServiceClient.AnalyzeEntities</c> and <c>LanguageServiceClient.AnalyzeEntitiesAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>LanguageServiceClient.AnalyzeEntities</c> and
/// <c>LanguageServiceClient.AnalyzeEntitiesAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings AnalyzeEntitiesSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>LanguageServiceClient.AnalyzeEntitySentiment</c> and <c>LanguageServiceClient.AnalyzeEntitySentimentAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>LanguageServiceClient.AnalyzeEntitySentiment</c> and
/// <c>LanguageServiceClient.AnalyzeEntitySentimentAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings AnalyzeEntitySentimentSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>LanguageServiceClient.AnalyzeSyntax</c> and <c>LanguageServiceClient.AnalyzeSyntaxAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>LanguageServiceClient.AnalyzeSyntax</c> and
/// <c>LanguageServiceClient.AnalyzeSyntaxAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings AnalyzeSyntaxSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>LanguageServiceClient.AnnotateText</c> and <c>LanguageServiceClient.AnnotateTextAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>LanguageServiceClient.AnnotateText</c> and
/// <c>LanguageServiceClient.AnnotateTextAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings AnnotateTextSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="LanguageServiceSettings"/> object.</returns>
public LanguageServiceSettings Clone() => new LanguageServiceSettings(this);
}
/// <summary>
/// LanguageService client wrapper, for convenient use.
/// </summary>
public abstract partial class LanguageServiceClient
{
/// <summary>
/// The default endpoint for the LanguageService service, which is a host of "language.googleapis.com" and a port of 443.
/// </summary>
public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("language.googleapis.com", 443);
/// <summary>
/// The default LanguageService scopes.
/// </summary>
/// <remarks>
/// The default LanguageService scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// </list>
/// </remarks>
public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
});
private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes);
// Note: we could have parameterless overloads of Create and CreateAsync,
// documented to just use the default endpoint, settings and credentials.
// Pros:
// - Might be more reassuring on first use
// - Allows method group conversions
// Con: overloads!
/// <summary>
/// Asynchronously creates a <see cref="LanguageServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="LanguageServiceSettings"/>.</param>
/// <returns>The task representing the created <see cref="LanguageServiceClient"/>.</returns>
public static async Task<LanguageServiceClient> CreateAsync(ServiceEndpoint endpoint = null, LanguageServiceSettings settings = null)
{
Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="LanguageServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="LanguageServiceSettings"/>.</param>
/// <returns>The created <see cref="LanguageServiceClient"/>.</returns>
public static LanguageServiceClient Create(ServiceEndpoint endpoint = null, LanguageServiceSettings settings = null)
{
Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="LanguageServiceClient"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="LanguageServiceSettings"/>.</param>
/// <returns>The created <see cref="LanguageServiceClient"/>.</returns>
public static LanguageServiceClient Create(Channel channel, LanguageServiceSettings settings = null)
{
GaxPreconditions.CheckNotNull(channel, nameof(channel));
LanguageService.LanguageServiceClient grpcClient = new LanguageService.LanguageServiceClient(channel);
return new LanguageServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, LanguageServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, LanguageServiceSettings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, LanguageServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, LanguageServiceSettings)"/> will create new channels, which could
/// in turn be shut down by another call to this method.</remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC LanguageService client.
/// </summary>
public virtual LanguageService.LanguageServiceClient GrpcClient
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeSentimentResponse> AnalyzeSentimentAsync(
Document document,
CallSettings callSettings = null) => AnalyzeSentimentAsync(
new AnalyzeSentimentRequest
{
Document = GaxPreconditions.CheckNotNull(document, nameof(document)),
},
callSettings);
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeSentimentResponse> AnalyzeSentimentAsync(
Document document,
CancellationToken cancellationToken) => AnalyzeSentimentAsync(
document,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnalyzeSentimentResponse AnalyzeSentiment(
Document document,
CallSettings callSettings = null) => AnalyzeSentiment(
new AnalyzeSentimentRequest
{
Document = GaxPreconditions.CheckNotNull(document, nameof(document)),
},
callSettings);
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeSentimentResponse> AnalyzeSentimentAsync(
AnalyzeSentimentRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnalyzeSentimentResponse AnalyzeSentiment(
AnalyzeSentimentRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Finds named entities (currently proper names and common nouns) in the text
/// along with entity types, salience, mentions for each entity, and
/// other properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(
Document document,
EncodingType encodingType,
CallSettings callSettings = null) => AnalyzeEntitiesAsync(
new AnalyzeEntitiesRequest
{
Document = GaxPreconditions.CheckNotNull(document, nameof(document)),
EncodingType = encodingType,
},
callSettings);
/// <summary>
/// Finds named entities (currently proper names and common nouns) in the text
/// along with entity types, salience, mentions for each entity, and
/// other properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(
Document document,
EncodingType encodingType,
CancellationToken cancellationToken) => AnalyzeEntitiesAsync(
document,
encodingType,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Finds named entities (currently proper names and common nouns) in the text
/// along with entity types, salience, mentions for each entity, and
/// other properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnalyzeEntitiesResponse AnalyzeEntities(
Document document,
EncodingType encodingType,
CallSettings callSettings = null) => AnalyzeEntities(
new AnalyzeEntitiesRequest
{
Document = GaxPreconditions.CheckNotNull(document, nameof(document)),
EncodingType = encodingType,
},
callSettings);
/// <summary>
/// Finds named entities (currently proper names and common nouns) in the text
/// along with entity types, salience, mentions for each entity, and
/// other properties.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(
AnalyzeEntitiesRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Finds named entities (currently proper names and common nouns) in the text
/// along with entity types, salience, mentions for each entity, and
/// other properties.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnalyzeEntitiesResponse AnalyzeEntities(
AnalyzeEntitiesRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes
/// sentiment associated with each entity and its mentions.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeEntitySentimentResponse> AnalyzeEntitySentimentAsync(
Document document,
EncodingType encodingType,
CallSettings callSettings = null) => AnalyzeEntitySentimentAsync(
new AnalyzeEntitySentimentRequest
{
Document = GaxPreconditions.CheckNotNull(document, nameof(document)),
EncodingType = encodingType,
},
callSettings);
/// <summary>
/// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes
/// sentiment associated with each entity and its mentions.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeEntitySentimentResponse> AnalyzeEntitySentimentAsync(
Document document,
EncodingType encodingType,
CancellationToken cancellationToken) => AnalyzeEntitySentimentAsync(
document,
encodingType,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes
/// sentiment associated with each entity and its mentions.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnalyzeEntitySentimentResponse AnalyzeEntitySentiment(
Document document,
EncodingType encodingType,
CallSettings callSettings = null) => AnalyzeEntitySentiment(
new AnalyzeEntitySentimentRequest
{
Document = GaxPreconditions.CheckNotNull(document, nameof(document)),
EncodingType = encodingType,
},
callSettings);
/// <summary>
/// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes
/// sentiment associated with each entity and its mentions.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeEntitySentimentResponse> AnalyzeEntitySentimentAsync(
AnalyzeEntitySentimentRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes
/// sentiment associated with each entity and its mentions.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnalyzeEntitySentimentResponse AnalyzeEntitySentiment(
AnalyzeEntitySentimentRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(
Document document,
EncodingType encodingType,
CallSettings callSettings = null) => AnalyzeSyntaxAsync(
new AnalyzeSyntaxRequest
{
Document = GaxPreconditions.CheckNotNull(document, nameof(document)),
EncodingType = encodingType,
},
callSettings);
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(
Document document,
EncodingType encodingType,
CancellationToken cancellationToken) => AnalyzeSyntaxAsync(
document,
encodingType,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnalyzeSyntaxResponse AnalyzeSyntax(
Document document,
EncodingType encodingType,
CallSettings callSettings = null) => AnalyzeSyntax(
new AnalyzeSyntaxRequest
{
Document = GaxPreconditions.CheckNotNull(document, nameof(document)),
EncodingType = encodingType,
},
callSettings);
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(
AnalyzeSyntaxRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnalyzeSyntaxResponse AnalyzeSyntax(
AnalyzeSyntaxRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// A convenience method that provides all syntax, sentiment, and entity
/// features in one call.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="features">
/// The enabled features.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnnotateTextResponse> AnnotateTextAsync(
Document document,
AnnotateTextRequest.Types.Features features,
EncodingType encodingType,
CallSettings callSettings = null) => AnnotateTextAsync(
new AnnotateTextRequest
{
Document = GaxPreconditions.CheckNotNull(document, nameof(document)),
Features = GaxPreconditions.CheckNotNull(features, nameof(features)),
EncodingType = encodingType,
},
callSettings);
/// <summary>
/// A convenience method that provides all syntax, sentiment, and entity
/// features in one call.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="features">
/// The enabled features.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnnotateTextResponse> AnnotateTextAsync(
Document document,
AnnotateTextRequest.Types.Features features,
EncodingType encodingType,
CancellationToken cancellationToken) => AnnotateTextAsync(
document,
features,
encodingType,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// A convenience method that provides all syntax, sentiment, and entity
/// features in one call.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="features">
/// The enabled features.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnnotateTextResponse AnnotateText(
Document document,
AnnotateTextRequest.Types.Features features,
EncodingType encodingType,
CallSettings callSettings = null) => AnnotateText(
new AnnotateTextRequest
{
Document = GaxPreconditions.CheckNotNull(document, nameof(document)),
Features = GaxPreconditions.CheckNotNull(features, nameof(features)),
EncodingType = encodingType,
},
callSettings);
/// <summary>
/// A convenience method that provides all syntax, sentiment, and entity
/// features in one call.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnnotateTextResponse> AnnotateTextAsync(
AnnotateTextRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// A convenience method that provides all syntax, sentiment, and entity
/// features in one call.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnnotateTextResponse AnnotateText(
AnnotateTextRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
}
/// <summary>
/// LanguageService client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class LanguageServiceClientImpl : LanguageServiceClient
{
private readonly ApiCall<AnalyzeSentimentRequest, AnalyzeSentimentResponse> _callAnalyzeSentiment;
private readonly ApiCall<AnalyzeEntitiesRequest, AnalyzeEntitiesResponse> _callAnalyzeEntities;
private readonly ApiCall<AnalyzeEntitySentimentRequest, AnalyzeEntitySentimentResponse> _callAnalyzeEntitySentiment;
private readonly ApiCall<AnalyzeSyntaxRequest, AnalyzeSyntaxResponse> _callAnalyzeSyntax;
private readonly ApiCall<AnnotateTextRequest, AnnotateTextResponse> _callAnnotateText;
/// <summary>
/// Constructs a client wrapper for the LanguageService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="LanguageServiceSettings"/> used within this client </param>
public LanguageServiceClientImpl(LanguageService.LanguageServiceClient grpcClient, LanguageServiceSettings settings)
{
this.GrpcClient = grpcClient;
LanguageServiceSettings effectiveSettings = settings ?? LanguageServiceSettings.GetDefault();
ClientHelper clientHelper = new ClientHelper(effectiveSettings);
_callAnalyzeSentiment = clientHelper.BuildApiCall<AnalyzeSentimentRequest, AnalyzeSentimentResponse>(
GrpcClient.AnalyzeSentimentAsync, GrpcClient.AnalyzeSentiment, effectiveSettings.AnalyzeSentimentSettings);
_callAnalyzeEntities = clientHelper.BuildApiCall<AnalyzeEntitiesRequest, AnalyzeEntitiesResponse>(
GrpcClient.AnalyzeEntitiesAsync, GrpcClient.AnalyzeEntities, effectiveSettings.AnalyzeEntitiesSettings);
_callAnalyzeEntitySentiment = clientHelper.BuildApiCall<AnalyzeEntitySentimentRequest, AnalyzeEntitySentimentResponse>(
GrpcClient.AnalyzeEntitySentimentAsync, GrpcClient.AnalyzeEntitySentiment, effectiveSettings.AnalyzeEntitySentimentSettings);
_callAnalyzeSyntax = clientHelper.BuildApiCall<AnalyzeSyntaxRequest, AnalyzeSyntaxResponse>(
GrpcClient.AnalyzeSyntaxAsync, GrpcClient.AnalyzeSyntax, effectiveSettings.AnalyzeSyntaxSettings);
_callAnnotateText = clientHelper.BuildApiCall<AnnotateTextRequest, AnnotateTextResponse>(
GrpcClient.AnnotateTextAsync, GrpcClient.AnnotateText, effectiveSettings.AnnotateTextSettings);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void OnConstruction(LanguageService.LanguageServiceClient grpcClient, LanguageServiceSettings effectiveSettings, ClientHelper clientHelper);
/// <summary>
/// The underlying gRPC LanguageService client.
/// </summary>
public override LanguageService.LanguageServiceClient GrpcClient { get; }
// Partial modifier methods contain '_' to ensure no name conflicts with RPC methods.
partial void Modify_AnalyzeSentimentRequest(ref AnalyzeSentimentRequest request, ref CallSettings settings);
partial void Modify_AnalyzeEntitiesRequest(ref AnalyzeEntitiesRequest request, ref CallSettings settings);
partial void Modify_AnalyzeEntitySentimentRequest(ref AnalyzeEntitySentimentRequest request, ref CallSettings settings);
partial void Modify_AnalyzeSyntaxRequest(ref AnalyzeSyntaxRequest request, ref CallSettings settings);
partial void Modify_AnnotateTextRequest(ref AnnotateTextRequest request, ref CallSettings settings);
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<AnalyzeSentimentResponse> AnalyzeSentimentAsync(
AnalyzeSentimentRequest request,
CallSettings callSettings = null)
{
Modify_AnalyzeSentimentRequest(ref request, ref callSettings);
return _callAnalyzeSentiment.Async(request, callSettings);
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override AnalyzeSentimentResponse AnalyzeSentiment(
AnalyzeSentimentRequest request,
CallSettings callSettings = null)
{
Modify_AnalyzeSentimentRequest(ref request, ref callSettings);
return _callAnalyzeSentiment.Sync(request, callSettings);
}
/// <summary>
/// Finds named entities (currently proper names and common nouns) in the text
/// along with entity types, salience, mentions for each entity, and
/// other properties.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(
AnalyzeEntitiesRequest request,
CallSettings callSettings = null)
{
Modify_AnalyzeEntitiesRequest(ref request, ref callSettings);
return _callAnalyzeEntities.Async(request, callSettings);
}
/// <summary>
/// Finds named entities (currently proper names and common nouns) in the text
/// along with entity types, salience, mentions for each entity, and
/// other properties.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override AnalyzeEntitiesResponse AnalyzeEntities(
AnalyzeEntitiesRequest request,
CallSettings callSettings = null)
{
Modify_AnalyzeEntitiesRequest(ref request, ref callSettings);
return _callAnalyzeEntities.Sync(request, callSettings);
}
/// <summary>
/// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes
/// sentiment associated with each entity and its mentions.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<AnalyzeEntitySentimentResponse> AnalyzeEntitySentimentAsync(
AnalyzeEntitySentimentRequest request,
CallSettings callSettings = null)
{
Modify_AnalyzeEntitySentimentRequest(ref request, ref callSettings);
return _callAnalyzeEntitySentiment.Async(request, callSettings);
}
/// <summary>
/// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes
/// sentiment associated with each entity and its mentions.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override AnalyzeEntitySentimentResponse AnalyzeEntitySentiment(
AnalyzeEntitySentimentRequest request,
CallSettings callSettings = null)
{
Modify_AnalyzeEntitySentimentRequest(ref request, ref callSettings);
return _callAnalyzeEntitySentiment.Sync(request, callSettings);
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(
AnalyzeSyntaxRequest request,
CallSettings callSettings = null)
{
Modify_AnalyzeSyntaxRequest(ref request, ref callSettings);
return _callAnalyzeSyntax.Async(request, callSettings);
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override AnalyzeSyntaxResponse AnalyzeSyntax(
AnalyzeSyntaxRequest request,
CallSettings callSettings = null)
{
Modify_AnalyzeSyntaxRequest(ref request, ref callSettings);
return _callAnalyzeSyntax.Sync(request, callSettings);
}
/// <summary>
/// A convenience method that provides all syntax, sentiment, and entity
/// features in one call.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<AnnotateTextResponse> AnnotateTextAsync(
AnnotateTextRequest request,
CallSettings callSettings = null)
{
Modify_AnnotateTextRequest(ref request, ref callSettings);
return _callAnnotateText.Async(request, callSettings);
}
/// <summary>
/// A convenience method that provides all syntax, sentiment, and entity
/// features in one call.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override AnnotateTextResponse AnnotateText(
AnnotateTextRequest request,
CallSettings callSettings = null)
{
Modify_AnnotateTextRequest(ref request, ref callSettings);
return _callAnnotateText.Sync(request, callSettings);
}
}
// Partial classes to enable page-streaming
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace Cocos2D
{
public class CCLabelBMFont : CCSpriteBatchNode, ICCLabelProtocol, ICCRGBAProtocol
{
public const int kCCLabelAutomaticWidth = -1;
public static Dictionary<string, CCBMFontConfiguration> s_pConfigurations = new Dictionary<string, CCBMFontConfiguration>();
protected bool m_bLineBreakWithoutSpaces;
protected CCTextAlignment m_pHAlignment = CCTextAlignment.Center;
protected CCVerticalTextAlignment m_pVAlignment = CCVerticalTextAlignment.Top;
protected CCBMFontConfiguration m_pConfiguration;
protected string m_sFntFile;
protected string m_sInitialString;
protected string m_sString = "";
protected CCPoint m_tImageOffset;
protected CCSize m_tDimensions;
protected CCSprite m_pReusedChar;
protected bool m_bLabelDirty;
public override CCPoint AnchorPoint
{
get { return base.AnchorPoint; }
set
{
if (!m_obAnchorPoint.Equals(value))
{
base.AnchorPoint = value;
m_bLabelDirty = true;
}
}
}
public override float Scale
{
get { return base.Scale; }
set
{
base.Scale = value;
m_bLabelDirty = true;
}
}
public override float ScaleX
{
get { return base.ScaleX; }
set
{
base.ScaleX = value;
UpdateLabel();
}
}
public override float ScaleY
{
get { return base.ScaleY; }
set
{
base.ScaleY = value;
m_bLabelDirty = true;
}
}
public CCTextAlignment HorizontalAlignment
{
get { return m_pHAlignment; }
set
{
if (m_pHAlignment != value)
{
m_pHAlignment = value;
m_bLabelDirty = true;
}
}
}
public CCVerticalTextAlignment VerticalAlignment
{
get { return m_pVAlignment; }
set
{
if (m_pVAlignment != value)
{
m_pVAlignment = value;
m_bLabelDirty = true;
}
}
}
public CCSize Dimensions
{
get { return m_tDimensions; }
set
{
if (m_tDimensions != value)
{
m_tDimensions = value;
m_bLabelDirty = true;
}
}
}
public bool LineBreakWithoutSpace
{
get { return m_bLineBreakWithoutSpaces; }
set
{
m_bLineBreakWithoutSpaces = value;
m_bLabelDirty = true;
}
}
public string FntFile
{
get { return m_sFntFile; }
set
{
if (value != null && m_sFntFile != value)
{
CCBMFontConfiguration newConf = FNTConfigLoadFile(value);
Debug.Assert(newConf != null, "CCLabelBMFont: Impossible to create font. Please check file");
m_sFntFile = value;
m_pConfiguration = newConf;
Texture = CCTextureCache.SharedTextureCache.AddImage(m_pConfiguration.AtlasName);
m_bLabelDirty = true;
}
}
}
#region ICCLabelProtocol Members
public virtual string Text
{
get { return m_sInitialString; }
set
{
if (m_sInitialString != value)
{
m_sInitialString = value;
m_bLabelDirty = true;
}
}
}
[Obsolete("Use Label Property")]
public void SetString(string label)
{
Text = label;
}
[Obsolete("Use Label Property")]
public string GetString()
{
return Text;
}
#endregion
#region ICCRGBAProtocol Members
protected byte m_cDisplayedOpacity = 255;
protected byte m_cRealOpacity = 255;
protected CCColor3B m_tDisplayedColor = CCTypes.CCWhite;
protected CCColor3B m_tRealColor = CCTypes.CCWhite;
protected bool m_bCascadeColorEnabled = true;
protected bool m_bCascadeOpacityEnabled = true;
protected bool m_bIsOpacityModifyRGB = false;
public virtual CCColor3B Color
{
get { return m_tRealColor; }
set
{
m_tDisplayedColor = m_tRealColor = value;
if (m_bCascadeColorEnabled)
{
var parentColor = CCTypes.CCWhite;
var parent = m_pParent as ICCRGBAProtocol;
if (parent != null && parent.CascadeColorEnabled)
{
parentColor = parent.DisplayedColor;
}
UpdateDisplayedColor(parentColor);
}
}
}
public virtual CCColor3B DisplayedColor
{
get { return m_tDisplayedColor; }
}
public virtual byte Opacity
{
get { return m_cRealOpacity; }
set
{
m_cDisplayedOpacity = m_cRealOpacity = value;
if (m_bCascadeOpacityEnabled)
{
byte parentOpacity = 255;
var pParent = m_pParent as ICCRGBAProtocol;
if (pParent != null && pParent.CascadeOpacityEnabled)
{
parentOpacity = pParent.DisplayedOpacity;
}
UpdateDisplayedOpacity(parentOpacity);
}
}
}
public virtual byte DisplayedOpacity
{
get { return m_cDisplayedOpacity; }
}
public virtual bool IsOpacityModifyRGB
{
get { return m_bIsOpacityModifyRGB; }
set
{
m_bIsOpacityModifyRGB = value;
if (m_pChildren != null && m_pChildren.count > 0)
{
for (int i = 0, count = m_pChildren.count; i < count; i++)
{
var item = m_pChildren.Elements[i] as ICCRGBAProtocol;
if (item != null)
{
item.IsOpacityModifyRGB = value;
}
}
}
}
}
public virtual bool CascadeColorEnabled
{
get { return false; }
set { m_bCascadeColorEnabled = value; }
}
public virtual bool CascadeOpacityEnabled
{
get { return false; }
set { m_bCascadeOpacityEnabled = value; }
}
public virtual void UpdateDisplayedColor(CCColor3B parentColor)
{
m_tDisplayedColor.R = (byte) (m_tRealColor.R * parentColor.R / 255.0f);
m_tDisplayedColor.G = (byte) (m_tRealColor.G * parentColor.G / 255.0f);
m_tDisplayedColor.B = (byte) (m_tRealColor.B * parentColor.B / 255.0f);
if (m_pChildren != null)
{
for (int i = 0, count = m_pChildren.count; i < count; i++)
{
((CCSprite) m_pChildren.Elements[i]).UpdateDisplayedColor(m_tDisplayedColor);
}
}
}
public virtual void UpdateDisplayedOpacity(byte parentOpacity)
{
m_cDisplayedOpacity = (byte) (m_cRealOpacity * parentOpacity / 255.0f);
if (m_pChildren != null)
{
for (int i = 0, count = m_pChildren.count; i < count; i++)
{
((CCSprite) m_pChildren.Elements[i]).UpdateDisplayedOpacity(m_cDisplayedOpacity);
}
}
}
#endregion
public static void FNTConfigRemoveCache()
{
if (s_pConfigurations != null)
{
s_pConfigurations.Clear();
}
}
public static void PurgeCachedData()
{
FNTConfigRemoveCache();
}
public CCLabelBMFont()
{
Init();
}
public CCLabelBMFont(string str, string fntFile, float width)
: this(str, fntFile, width, CCTextAlignment.Left, CCPoint.Zero)
{
}
public CCLabelBMFont(string str, string fntFile)
: this(str, fntFile, kCCLabelAutomaticWidth, CCTextAlignment.Left, CCPoint.Zero)
{
}
public CCLabelBMFont(string str, string fntFile, float width, CCTextAlignment alignment)
: this(str, fntFile, width, alignment, CCPoint.Zero)
{
}
public CCLabelBMFont(string str, string fntFile, float width, CCTextAlignment alignment, CCPoint imageOffset)
{
InitWithString(str, fntFile, new CCSize(width, 0), alignment, CCVerticalTextAlignment.Top, imageOffset, null);
}
public override bool Init()
{
return InitWithString(null, null, new CCSize(kCCLabelAutomaticWidth, 0), CCTextAlignment.Left, CCVerticalTextAlignment.Top, CCPoint.Zero, null);
}
protected virtual bool InitWithString(string theString, string fntFile, CCSize dimentions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
CCPoint imageOffset, CCTexture2D texture)
{
Debug.Assert(m_pConfiguration == null, "re-init is no longer supported");
Debug.Assert((theString == null && fntFile == null) || (theString != null && fntFile != null),
"Invalid params for CCLabelBMFont");
if (!String.IsNullOrEmpty(fntFile))
{
CCBMFontConfiguration newConf = FNTConfigLoadFile(fntFile);
if (newConf == null)
{
CCLog.Log("CCLabelBMFont: Impossible to create font. Please check file: '{0}'", fntFile);
return false;
}
m_pConfiguration = newConf;
m_sFntFile = fntFile;
if (texture == null)
{
try
{
texture = CCTextureCache.SharedTextureCache.AddImage(m_pConfiguration.AtlasName);
}
catch (Exception)
{
// Try the 'images' ref location just in case.
try
{
texture =
CCTextureCache.SharedTextureCache.AddImage(System.IO.Path.Combine("images",
m_pConfiguration
.AtlasName));
}
catch (Exception)
{
// Lastly, try <font_path>/images/<font_name>
string dir = System.IO.Path.GetDirectoryName(m_pConfiguration.AtlasName);
string fname = System.IO.Path.GetFileName(m_pConfiguration.AtlasName);
string newName = System.IO.Path.Combine(System.IO.Path.Combine(dir, "images"), fname);
texture = CCTextureCache.SharedTextureCache.AddImage(newName);
}
}
}
}
else
{
texture = new CCTexture2D();
}
if (String.IsNullOrEmpty(theString))
{
theString = String.Empty;
}
if (base.InitWithTexture(texture, theString.Length))
{
m_tDimensions = dimentions;
m_pHAlignment = hAlignment;
m_pVAlignment = vAlignment;
m_cDisplayedOpacity = m_cRealOpacity = 255;
m_tDisplayedColor = m_tRealColor = CCTypes.CCWhite;
m_bCascadeOpacityEnabled = true;
m_bCascadeColorEnabled = true;
m_obContentSize = CCSize.Zero;
m_bIsOpacityModifyRGB = m_pobTextureAtlas.Texture.HasPremultipliedAlpha;
AnchorPoint = new CCPoint(0.5f, 0.5f);
m_tImageOffset = imageOffset;
m_pReusedChar = new CCSprite();
m_pReusedChar.InitWithTexture(m_pobTextureAtlas.Texture, CCRect.Zero, false);
m_pReusedChar.BatchNode = this;
SetString(theString, true);
return true;
}
return false;
}
private int KerningAmountForFirst(int first, int second)
{
int ret = 0;
int key = (first << 16) | (second & 0xffff);
if (m_pConfiguration.m_pKerningDictionary != null)
{
CCBMFontConfiguration.CCKerningHashElement element;
if (m_pConfiguration.m_pKerningDictionary.TryGetValue(key, out element))
{
ret = element.amount;
}
}
return ret;
}
public void CreateFontChars()
{
int nextFontPositionX = 0;
int nextFontPositionY = 0;
char prev = (char) 255;
int kerningAmount = 0;
CCSize tmpSize = CCSize.Zero;
int longestLine = 0;
int totalHeight = 0;
int quantityOfLines = 1;
if (String.IsNullOrEmpty(m_sString))
{
return;
}
int stringLen = m_sString.Length;
var charSet = m_pConfiguration.CharacterSet;
if (charSet.Count == 0)
{
throw (new InvalidOperationException(
"Can not compute the size of the font because the character set is empty."));
}
for (int i = 0; i < stringLen - 1; ++i)
{
if (m_sString[i] == '\n')
{
quantityOfLines++;
}
}
totalHeight = m_pConfiguration.m_nCommonHeight * quantityOfLines;
nextFontPositionY = 0 -
(m_pConfiguration.m_nCommonHeight - m_pConfiguration.m_nCommonHeight * quantityOfLines);
CCBMFontConfiguration.CCBMFontDef fontDef = null;
CCRect rect;
for (int i = 0; i < stringLen; i++)
{
char c = m_sString[i];
if (c == '\n')
{
nextFontPositionX = 0;
nextFontPositionY -= m_pConfiguration.m_nCommonHeight;
continue;
}
if (charSet.IndexOf(c) == -1)
{
CCLog.Log("Cocos2D.CCLabelBMFont: Attempted to use character not defined in this bitmap: {0}",
(int) c);
continue;
}
kerningAmount = this.KerningAmountForFirst(prev, c);
// unichar is a short, and an int is needed on HASH_FIND_INT
if (!m_pConfiguration.m_pFontDefDictionary.TryGetValue(c, out fontDef))
{
CCLog.Log("cocos2d::CCLabelBMFont: characer not found {0}", (int) c);
continue;
}
rect = fontDef.rect;
rect = rect.PixelsToPoints();
rect.Origin.X += m_tImageOffset.X;
rect.Origin.Y += m_tImageOffset.Y;
CCSprite fontChar;
//bool hasSprite = true;
fontChar = (CCSprite) (GetChildByTag(i));
if (fontChar != null)
{
// Reusing previous Sprite
fontChar.Visible = true;
}
else
{
// New Sprite ? Set correct color, opacity, etc...
//if( false )
//{
// /* WIP: Doesn't support many features yet.
// But this code is super fast. It doesn't create any sprite.
// Ideal for big labels.
// */
// fontChar = m_pReusedChar;
// fontChar.BatchNode = null;
// hasSprite = false;
//}
//else
{
fontChar = new CCSprite();
fontChar.InitWithTexture(m_pobTextureAtlas.Texture, rect);
AddChild(fontChar, i, i);
}
// Apply label properties
fontChar.IsOpacityModifyRGB = m_bIsOpacityModifyRGB;
// Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
fontChar.UpdateDisplayedColor(m_tDisplayedColor);
fontChar.UpdateDisplayedOpacity(m_cDisplayedOpacity);
}
// updating previous sprite
fontChar.SetTextureRect(rect, false, rect.Size);
// See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!)
int yOffset = m_pConfiguration.m_nCommonHeight - fontDef.yOffset;
var fontPos =
new CCPoint(
(float) nextFontPositionX + fontDef.xOffset + fontDef.rect.Size.Width * 0.5f + kerningAmount,
(float) nextFontPositionY + yOffset - rect.Size.Height * 0.5f * CCMacros.CCContentScaleFactor());
fontChar.Position = fontPos.PixelsToPoints();
// update kerning
nextFontPositionX += fontDef.xAdvance + kerningAmount;
prev = c;
if (longestLine < nextFontPositionX)
{
longestLine = nextFontPositionX;
}
//if (! hasSprite)
//{
// UpdateQuadFromSprite(fontChar, i);
//}
}
// If the last character processed has an xAdvance which is less that the width of the characters image, then we need
// to adjust the width of the string to take this into account, or the character will overlap the end of the bounding
// box
if (fontDef.xAdvance < fontDef.rect.Size.Width)
{
tmpSize.Width = longestLine + fontDef.rect.Size.Width - fontDef.xAdvance;
}
else
{
tmpSize.Width = longestLine;
}
tmpSize.Height = totalHeight;
tmpSize = new CCSize(
m_tDimensions.Width > 0 ? m_tDimensions.Width : tmpSize.Width,
m_tDimensions.Height > 0 ? m_tDimensions.Height : tmpSize.Height
);
ContentSize = tmpSize.PixelsToPoints();
}
public virtual void SetString(string newString, bool needUpdateLabel)
{
if (!needUpdateLabel)
{
m_sString = newString;
}
else
{
m_sInitialString = newString;
}
UpdateString(needUpdateLabel);
}
private void UpdateString(bool needUpdateLabel)
{
if (m_pChildren != null && m_pChildren.count != 0)
{
CCNode[] elements = m_pChildren.Elements;
for (int i = 0, count = m_pChildren.count; i < count; i++)
{
elements[i].Visible = false;
}
}
CreateFontChars();
if (needUpdateLabel)
{
UpdateLabel();
}
}
protected void UpdateLabel()
{
SetString(m_sInitialString, false);
if (m_sString == null)
{
return;
}
if (m_tDimensions.Width > 0)
{
// Step 1: Make multiline
string str_whole = m_sString;
int stringLength = str_whole.Length;
var multiline_string = new StringBuilder(stringLength);
var last_word = new StringBuilder(stringLength);
int line = 1, i = 0;
bool start_line = false, start_word = false;
float startOfLine = -1, startOfWord = -1;
int skip = 0;
CCRawList<CCNode> children = m_pChildren;
for (int j = 0; j < children.count; j++)
{
CCSprite characterSprite;
int justSkipped = 0;
while ((characterSprite = (CCSprite) GetChildByTag(j + skip + justSkipped)) == null)
{
justSkipped++;
}
skip += justSkipped;
if (!characterSprite.Visible)
{
continue;
}
if (i >= stringLength)
{
break;
}
char character = str_whole[i];
if (!start_word)
{
startOfWord = GetLetterPosXLeft(characterSprite);
start_word = true;
}
if (!start_line)
{
startOfLine = startOfWord;
start_line = true;
}
// Newline.
if (character == '\n')
{
int len = last_word.Length;
while (len > 0 && Char.IsWhiteSpace(last_word[len - 1]))
{
len--;
last_word.Remove(len, 1);
}
multiline_string.Append(last_word);
multiline_string.Append('\n');
#if XBOX || XBOX360
last_word.Length = 0;
#else
last_word.Clear();
#endif
start_word = false;
start_line = false;
startOfWord = -1;
startOfLine = -1;
i += justSkipped;
line++;
if (i >= stringLength)
break;
character = str_whole[i];
if (startOfWord == 0)
{
startOfWord = GetLetterPosXLeft(characterSprite);
start_word = true;
}
if (startOfLine == 0)
{
startOfLine = startOfWord;
start_line = true;
}
}
// Whitespace.
if (Char.IsWhiteSpace(character))
{
last_word.Append(character);
multiline_string.Append(last_word);
#if XBOX || XBOX360
last_word.Length = 0;
#else
last_word.Clear();
#endif
start_word = false;
startOfWord = -1;
i++;
continue;
}
// Out of bounds.
if (GetLetterPosXRight(characterSprite) - startOfLine > m_tDimensions.Width)
{
if (!m_bLineBreakWithoutSpaces)
{
last_word.Append(character);
int len = multiline_string.Length;
while (len > 0 && Char.IsWhiteSpace(multiline_string[len - 1]))
{
len--;
multiline_string.Remove(len, 1);
}
if (multiline_string.Length > 0)
{
multiline_string.Append('\n');
}
line++;
start_line = false;
startOfLine = -1;
i++;
}
else
{
int len = last_word.Length;
while (len > 0 && Char.IsWhiteSpace(last_word[len - 1]))
{
len--;
last_word.Remove(len, 1);
}
multiline_string.Append(last_word);
multiline_string.Append('\n');
#if XBOX || XBOX360
last_word.Length = 0;
#else
last_word.Clear();
#endif
start_word = false;
start_line = false;
startOfWord = -1;
startOfLine = -1;
line++;
if (i >= stringLength)
break;
if (startOfWord == 0)
{
startOfWord = GetLetterPosXLeft(characterSprite);
start_word = true;
}
if (startOfLine == 0)
{
startOfLine = startOfWord;
start_line = true;
}
j--;
}
continue;
}
else
{
// Character is normal.
last_word.Append(character);
i++;
continue;
}
}
multiline_string.Append(last_word);
SetString(multiline_string.ToString(), false);
}
// Step 2: Make alignment
if (m_pHAlignment != CCTextAlignment.Left)
{
int i = 0;
int lineNumber = 0;
int str_len = m_sString.Length;
var last_line = new CCRawList<char>();
for (int ctr = 0; ctr <= str_len; ++ctr)
{
if (ctr == str_len || m_sString[ctr] == '\n')
{
float lineWidth = 0.0f;
int line_length = last_line.Count;
// if last line is empty we must just increase lineNumber and work with next line
if (line_length == 0)
{
lineNumber++;
continue;
}
int index = i + line_length - 1 + lineNumber;
if (index < 0) continue;
var lastChar = (CCSprite) GetChildByTag(index);
if (lastChar == null)
continue;
lineWidth = lastChar.Position.X + lastChar.ContentSize.Width / 2.0f;
float shift = 0;
switch (m_pHAlignment)
{
case CCTextAlignment.Center:
shift = ContentSize.Width / 2.0f - lineWidth / 2.0f;
break;
case CCTextAlignment.Right:
shift = ContentSize.Width - lineWidth;
break;
default:
break;
}
if (shift != 0)
{
for (int j = 0; j < line_length; j++)
{
index = i + j + lineNumber;
if (index < 0) continue;
var characterSprite = (CCSprite) GetChildByTag(index);
characterSprite.Position = characterSprite.Position + new CCPoint(shift, 0.0f);
}
}
i += line_length;
lineNumber++;
last_line.Clear();
continue;
}
last_line.Add(m_sString[ctr]);
}
}
if (m_pVAlignment != CCVerticalTextAlignment.Bottom && m_tDimensions.Height > 0)
{
int lineNumber = 1;
int str_len = m_sString.Length;
for (int ctr = 0; ctr < str_len; ++ctr)
{
if (m_sString[ctr] == '\n')
{
lineNumber++;
}
}
float yOffset = 0;
if (m_pVAlignment == CCVerticalTextAlignment.Center)
{
yOffset = m_tDimensions.Height / 2f - (m_pConfiguration.m_nCommonHeight * lineNumber) / 2f;
}
else
{
yOffset = m_tDimensions.Height - m_pConfiguration.m_nCommonHeight * lineNumber;
}
for (int i = 0; i < str_len; i++)
{
var characterSprite = GetChildByTag(i);
characterSprite.PositionY += yOffset;
}
}
}
private float GetLetterPosXLeft(CCSprite sp)
{
return sp.Position.X * m_fScaleX - (sp.ContentSize.Width * m_fScaleX * sp.AnchorPoint.X);
}
private float GetLetterPosXRight(CCSprite sp)
{
return sp.Position.X * m_fScaleX + (sp.ContentSize.Width * m_fScaleX * sp.AnchorPoint.X);
}
private static CCBMFontConfiguration FNTConfigLoadFile(string file)
{
CCBMFontConfiguration pRet;
if (!s_pConfigurations.TryGetValue(file, out pRet))
{
pRet = CCBMFontConfiguration.Create(file);
s_pConfigurations.Add(file, pRet);
}
return pRet;
}
public override void Draw()
{
if (m_bLabelDirty)
{
UpdateLabel();
m_bLabelDirty = false;
}
base.Draw();
}
}
}
| |
// 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.Globalization;
namespace System.Net.Http.Headers
{
public class RangeItemHeaderValue : ICloneable
{
private readonly long? _from;
private readonly long? _to;
public long? From
{
get { return _from; }
}
public long? To
{
get { return _to; }
}
public RangeItemHeaderValue(long? from, long? to)
{
if (!from.HasValue && !to.HasValue)
{
throw new ArgumentException(SR.net_http_headers_invalid_range);
}
if (from.HasValue && (from.Value < 0))
{
throw new ArgumentOutOfRangeException(nameof(from));
}
if (to.HasValue && (to.Value < 0))
{
throw new ArgumentOutOfRangeException(nameof(to));
}
if (from.HasValue && to.HasValue && (from.Value > to.Value))
{
throw new ArgumentOutOfRangeException(nameof(from));
}
_from = from;
_to = to;
}
private RangeItemHeaderValue(RangeItemHeaderValue source)
{
Debug.Assert(source != null);
_from = source._from;
_to = source._to;
}
public override string ToString()
{
if (!_from.HasValue)
{
return "-" + _to.Value.ToString(NumberFormatInfo.InvariantInfo);
}
else if (!_to.HasValue)
{
return _from.Value.ToString(NumberFormatInfo.InvariantInfo) + "-";
}
return _from.Value.ToString(NumberFormatInfo.InvariantInfo) + "-" +
_to.Value.ToString(NumberFormatInfo.InvariantInfo);
}
public override bool Equals(object obj)
{
RangeItemHeaderValue other = obj as RangeItemHeaderValue;
if (other == null)
{
return false;
}
return ((_from == other._from) && (_to == other._to));
}
public override int GetHashCode()
{
if (!_from.HasValue)
{
return _to.GetHashCode();
}
else if (!_to.HasValue)
{
return _from.GetHashCode();
}
return _from.GetHashCode() ^ _to.GetHashCode();
}
// Returns the length of a range list. E.g. "1-2, 3-4, 5-6" adds 3 ranges to 'rangeCollection'. Note that empty
// list segments are allowed, e.g. ",1-2, , 3-4,,".
internal static int GetRangeItemListLength(string input, int startIndex,
ICollection<RangeItemHeaderValue> rangeCollection)
{
Debug.Assert(rangeCollection != null);
Debug.Assert(startIndex >= 0);
if ((string.IsNullOrEmpty(input)) || (startIndex >= input.Length))
{
return 0;
}
// Empty segments are allowed, so skip all delimiter-only segments (e.g. ", ,").
bool separatorFound = false;
int current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, startIndex, true, out separatorFound);
// It's OK if we didn't find leading separator characters. Ignore 'separatorFound'.
if (current == input.Length)
{
return 0;
}
RangeItemHeaderValue range = null;
while (true)
{
int rangeLength = GetRangeItemLength(input, current, out range);
if (rangeLength == 0)
{
return 0;
}
rangeCollection.Add(range);
current = current + rangeLength;
current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out separatorFound);
// If the string is not consumed, we must have a delimiter, otherwise the string is not a valid
// range list.
if ((current < input.Length) && !separatorFound)
{
return 0;
}
if (current == input.Length)
{
return current - startIndex;
}
}
}
internal static int GetRangeItemLength(string input, int startIndex, out RangeItemHeaderValue parsedValue)
{
Debug.Assert(startIndex >= 0);
// This parser parses number ranges: e.g. '1-2', '1-', '-2'.
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Caller must remove leading whitespace. If not, we'll return 0.
int current = startIndex;
// Try parse the first value of a value pair.
int fromStartIndex = current;
int fromLength = HttpRuleParser.GetNumberLength(input, current, false);
if (fromLength > HttpRuleParser.MaxInt64Digits)
{
return 0;
}
current = current + fromLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
// After the first value, the '-' character must follow.
if ((current == input.Length) || (input[current] != '-'))
{
// We need a '-' character otherwise this can't be a valid range.
return 0;
}
current++; // skip the '-' character
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
int toStartIndex = current;
int toLength = 0;
// If we didn't reach the end of the string, try parse the second value of the range.
if (current < input.Length)
{
toLength = HttpRuleParser.GetNumberLength(input, current, false);
if (toLength > HttpRuleParser.MaxInt64Digits)
{
return 0;
}
current = current + toLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
if ((fromLength == 0) && (toLength == 0))
{
return 0; // At least one value must be provided in order to be a valid range.
}
// Try convert first value to int64
long from = 0;
if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input, fromStartIndex, fromLength, out from))
{
return 0;
}
// Try convert second value to int64
long to = 0;
if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input, toStartIndex, toLength, out to))
{
return 0;
}
// 'from' must not be greater than 'to'
if ((fromLength > 0) && (toLength > 0) && (from > to))
{
return 0;
}
parsedValue = new RangeItemHeaderValue((fromLength == 0 ? (long?)null : (long?)from),
(toLength == 0 ? (long?)null : (long?)to));
return current - startIndex;
}
object ICloneable.Clone()
{
return new RangeItemHeaderValue(this);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Xml.Linq
{
public static partial class Extensions
{
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> AncestorsAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source) { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> AncestorsAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source, System.Xml.Linq.XName name) { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XNode { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors<T>(this System.Collections.Generic.IEnumerable<T> source, System.Xml.Linq.XName name) where T : System.Xml.Linq.XNode { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source) { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source, System.Xml.Linq.XName name) { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodesAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source) { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodes<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> DescendantsAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source) { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> DescendantsAndSelf(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source, System.Xml.Linq.XName name) { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants<T>(this System.Collections.Generic.IEnumerable<T> source, System.Xml.Linq.XName name) where T : System.Xml.Linq.XContainer { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements<T>(this System.Collections.Generic.IEnumerable<T> source, System.Xml.Linq.XName name) where T : System.Xml.Linq.XContainer { throw null; }
public static System.Collections.Generic.IEnumerable<T> InDocumentOrder<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XNode { throw null; }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> Nodes<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer { throw null; }
public static void Remove(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> source) { }
public static void Remove<T>(this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XNode { }
}
[System.FlagsAttribute]
public enum LoadOptions
{
None = 0,
PreserveWhitespace = 1,
SetBaseUri = 2,
SetLineInfo = 4,
}
[System.FlagsAttribute]
public enum ReaderOptions
{
None = 0,
OmitDuplicateNamespaces = 1,
}
[System.FlagsAttribute]
public enum SaveOptions
{
None = 0,
DisableFormatting = 1,
OmitDuplicateNamespaces = 2,
}
public partial class XAttribute : System.Xml.Linq.XObject
{
public XAttribute(System.Xml.Linq.XAttribute other) { }
public XAttribute(System.Xml.Linq.XName name, object value) { }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> EmptySequence { get { throw null; } }
public bool IsNamespaceDeclaration { get { throw null; } }
public System.Xml.Linq.XName Name { get { throw null; } }
public System.Xml.Linq.XAttribute NextAttribute { get { throw null; } }
public override System.Xml.XmlNodeType NodeType { get { throw null; } }
public System.Xml.Linq.XAttribute PreviousAttribute { get { throw null; } }
public string Value { get { throw null; } set { } }
[System.CLSCompliantAttribute(false)]
public static explicit operator bool (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.DateTime (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.DateTimeOffset (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator decimal (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator double (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.Guid (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator int (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator long (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator bool? (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.DateTimeOffset? (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.DateTime? (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator decimal? (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator double? (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.Guid? (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator int? (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator long? (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator float? (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.TimeSpan? (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator uint? (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator ulong? (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator float (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator string (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.TimeSpan (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator uint (System.Xml.Linq.XAttribute attribute) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator ulong (System.Xml.Linq.XAttribute attribute) { throw null; }
public void Remove() { }
public void SetValue(object value) { }
public override string ToString() { throw null; }
}
public partial class XCData : System.Xml.Linq.XText
{
public XCData(string value) : base (default(string)) { }
public XCData(System.Xml.Linq.XCData other) : base (default(string)) { }
public override System.Xml.XmlNodeType NodeType { get { throw null; } }
public override void WriteTo(System.Xml.XmlWriter writer) { }
public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class XComment : System.Xml.Linq.XNode
{
public XComment(string value) { }
public XComment(System.Xml.Linq.XComment other) { }
public override System.Xml.XmlNodeType NodeType { get { throw null; } }
public string Value { get { throw null; } set { } }
public override void WriteTo(System.Xml.XmlWriter writer) { }
public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public abstract partial class XContainer : System.Xml.Linq.XNode
{
internal XContainer() { }
public System.Xml.Linq.XNode FirstNode { get { throw null; } }
public System.Xml.Linq.XNode LastNode { get { throw null; } }
public void Add(object content) { }
public void Add(params object[] content) { }
public void AddFirst(object content) { }
public void AddFirst(params object[] content) { }
public System.Xml.XmlWriter CreateWriter() { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodes() { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants() { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants(System.Xml.Linq.XName name) { throw null; }
public System.Xml.Linq.XElement Element(System.Xml.Linq.XName name) { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements() { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements(System.Xml.Linq.XName name) { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> Nodes() { throw null; }
public void RemoveNodes() { }
public void ReplaceNodes(object content) { }
public void ReplaceNodes(params object[] content) { }
}
public partial class XDeclaration
{
public XDeclaration(string version, string encoding, string standalone) { }
public XDeclaration(System.Xml.Linq.XDeclaration other) { }
public string Encoding { get { throw null; } set { } }
public string Standalone { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
public override string ToString() { throw null; }
}
public partial class XDocument : System.Xml.Linq.XContainer
{
public XDocument() { }
public XDocument(params object[] content) { }
public XDocument(System.Xml.Linq.XDeclaration declaration, params object[] content) { }
public XDocument(System.Xml.Linq.XDocument other) { }
public System.Xml.Linq.XDeclaration Declaration { get { throw null; } set { } }
public System.Xml.Linq.XDocumentType DocumentType { get { throw null; } }
public override System.Xml.XmlNodeType NodeType { get { throw null; } }
public System.Xml.Linq.XElement Root { get { throw null; } }
public static System.Xml.Linq.XDocument Load(System.IO.Stream stream) { throw null; }
public static System.Xml.Linq.XDocument Load(System.IO.Stream stream, System.Xml.Linq.LoadOptions options) { throw null; }
public static System.Xml.Linq.XDocument Load(System.IO.TextReader textReader) { throw null; }
public static System.Xml.Linq.XDocument Load(System.IO.TextReader textReader, System.Xml.Linq.LoadOptions options) { throw null; }
public static System.Xml.Linq.XDocument Load(string uri) { throw null; }
public static System.Xml.Linq.XDocument Load(string uri, System.Xml.Linq.LoadOptions options) { throw null; }
public static System.Xml.Linq.XDocument Load(System.Xml.XmlReader reader) { throw null; }
public static System.Xml.Linq.XDocument Load(System.Xml.XmlReader reader, System.Xml.Linq.LoadOptions options) { throw null; }
public static System.Threading.Tasks.Task<System.Xml.Linq.XDocument> LoadAsync(System.IO.Stream stream, System.Xml.Linq.LoadOptions options, System.Threading.CancellationToken cancellationToken) { throw null; }
public static System.Threading.Tasks.Task<System.Xml.Linq.XDocument> LoadAsync(System.IO.TextReader textReader, System.Xml.Linq.LoadOptions options, System.Threading.CancellationToken cancellationToken) { throw null; }
public static System.Threading.Tasks.Task<System.Xml.Linq.XDocument> LoadAsync(System.Xml.XmlReader reader, System.Xml.Linq.LoadOptions options, System.Threading.CancellationToken cancellationToken) { throw null; }
public static System.Xml.Linq.XDocument Parse(string text) { throw null; }
public static System.Xml.Linq.XDocument Parse(string text, System.Xml.Linq.LoadOptions options) { throw null; }
public void Save(System.IO.Stream stream) { }
public void Save(System.IO.Stream stream, System.Xml.Linq.SaveOptions options) { }
public void Save(System.IO.TextWriter textWriter) { }
public void Save(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options) { }
public void Save(string fileName) { }
public void Save(string fileName, System.Xml.Linq.SaveOptions options) { }
public void Save(System.Xml.XmlWriter writer) { }
public System.Threading.Tasks.Task SaveAsync(System.IO.Stream stream, System.Xml.Linq.SaveOptions options, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task SaveAsync(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task SaveAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; }
public override void WriteTo(System.Xml.XmlWriter writer) { }
public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class XDocumentType : System.Xml.Linq.XNode
{
public XDocumentType(string name, string publicId, string systemId, string internalSubset) { }
public XDocumentType(System.Xml.Linq.XDocumentType other) { }
public string InternalSubset { get { throw null; } set { } }
public string Name { get { throw null; } set { } }
public override System.Xml.XmlNodeType NodeType { get { throw null; } }
public string PublicId { get { throw null; } set { } }
public string SystemId { get { throw null; } set { } }
public override void WriteTo(System.Xml.XmlWriter writer) { }
public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; }
}
[System.Xml.Serialization.XmlSchemaProviderAttribute(null, IsAny=true)]
public partial class XElement : System.Xml.Linq.XContainer, System.Xml.Serialization.IXmlSerializable
{
public XElement(System.Xml.Linq.XElement other) { }
public XElement(System.Xml.Linq.XName name) { }
public XElement(System.Xml.Linq.XName name, object content) { }
public XElement(System.Xml.Linq.XName name, params object[] content) { }
public XElement(System.Xml.Linq.XStreamingElement other) { }
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> EmptySequence { get { throw null; } }
public System.Xml.Linq.XAttribute FirstAttribute { get { throw null; } }
public bool HasAttributes { get { throw null; } }
public bool HasElements { get { throw null; } }
public bool IsEmpty { get { throw null; } }
public System.Xml.Linq.XAttribute LastAttribute { get { throw null; } }
public System.Xml.Linq.XName Name { get { throw null; } set { } }
public override System.Xml.XmlNodeType NodeType { get { throw null; } }
public string Value { get { throw null; } set { } }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> AncestorsAndSelf() { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> AncestorsAndSelf(System.Xml.Linq.XName name) { throw null; }
public System.Xml.Linq.XAttribute Attribute(System.Xml.Linq.XName name) { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes() { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(System.Xml.Linq.XName name) { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodesAndSelf() { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> DescendantsAndSelf() { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> DescendantsAndSelf(System.Xml.Linq.XName name) { throw null; }
public System.Xml.Linq.XNamespace GetDefaultNamespace() { throw null; }
public System.Xml.Linq.XNamespace GetNamespaceOfPrefix(string prefix) { throw null; }
public string GetPrefixOfNamespace(System.Xml.Linq.XNamespace ns) { throw null; }
public static System.Xml.Linq.XElement Load(System.IO.Stream stream) { throw null; }
public static System.Xml.Linq.XElement Load(System.IO.Stream stream, System.Xml.Linq.LoadOptions options) { throw null; }
public static System.Xml.Linq.XElement Load(System.IO.TextReader textReader) { throw null; }
public static System.Xml.Linq.XElement Load(System.IO.TextReader textReader, System.Xml.Linq.LoadOptions options) { throw null; }
public static System.Xml.Linq.XElement Load(string uri) { throw null; }
public static System.Xml.Linq.XElement Load(string uri, System.Xml.Linq.LoadOptions options) { throw null; }
public static System.Xml.Linq.XElement Load(System.Xml.XmlReader reader) { throw null; }
public static System.Xml.Linq.XElement Load(System.Xml.XmlReader reader, System.Xml.Linq.LoadOptions options) { throw null; }
public static System.Threading.Tasks.Task<System.Xml.Linq.XElement> LoadAsync(System.IO.Stream stream, System.Xml.Linq.LoadOptions options, System.Threading.CancellationToken cancellationToken) { throw null; }
public static System.Threading.Tasks.Task<System.Xml.Linq.XElement> LoadAsync(System.IO.TextReader textReader, System.Xml.Linq.LoadOptions options, System.Threading.CancellationToken cancellationToken) { throw null; }
public static System.Threading.Tasks.Task<System.Xml.Linq.XElement> LoadAsync(System.Xml.XmlReader reader, System.Xml.Linq.LoadOptions options, System.Threading.CancellationToken cancellationToken) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator bool (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.DateTime (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.DateTimeOffset (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator decimal (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator double (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.Guid (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator int (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator long (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator bool? (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.DateTimeOffset? (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.DateTime? (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator decimal? (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator double? (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.Guid? (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator int? (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator long? (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator float? (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.TimeSpan? (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator uint? (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator ulong? (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator float (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator string (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.TimeSpan (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator uint (System.Xml.Linq.XElement element) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator ulong (System.Xml.Linq.XElement element) { throw null; }
public static System.Xml.Linq.XElement Parse(string text) { throw null; }
public static System.Xml.Linq.XElement Parse(string text, System.Xml.Linq.LoadOptions options) { throw null; }
public void RemoveAll() { }
public void RemoveAttributes() { }
public void ReplaceAll(object content) { }
public void ReplaceAll(params object[] content) { }
public void ReplaceAttributes(object content) { }
public void ReplaceAttributes(params object[] content) { }
public void Save(System.IO.Stream stream) { }
public void Save(System.IO.Stream stream, System.Xml.Linq.SaveOptions options) { }
public void Save(System.IO.TextWriter textWriter) { }
public void Save(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options) { }
public void Save(string fileName) { }
public void Save(string fileName, System.Xml.Linq.SaveOptions options) { }
public void Save(System.Xml.XmlWriter writer) { }
public System.Threading.Tasks.Task SaveAsync(System.IO.Stream stream, System.Xml.Linq.SaveOptions options, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task SaveAsync(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task SaveAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; }
public void SetAttributeValue(System.Xml.Linq.XName name, object value) { }
public void SetElementValue(System.Xml.Linq.XName name, object value) { }
public void SetValue(object value) { }
System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; }
void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { }
void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { }
public override void WriteTo(System.Xml.XmlWriter writer) { }
public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public sealed partial class XName : System.IEquatable<System.Xml.Linq.XName>, System.Runtime.Serialization.ISerializable
{
internal XName() { }
public string LocalName { get { throw null; } }
public System.Xml.Linq.XNamespace Namespace { get { throw null; } }
public string NamespaceName { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public static System.Xml.Linq.XName Get(string expandedName) { throw null; }
public static System.Xml.Linq.XName Get(string localName, string namespaceName) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Xml.Linq.XName left, System.Xml.Linq.XName right) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator System.Xml.Linq.XName (string expandedName) { throw null; }
public static bool operator !=(System.Xml.Linq.XName left, System.Xml.Linq.XName right) { throw null; }
bool System.IEquatable<System.Xml.Linq.XName>.Equals(System.Xml.Linq.XName other) { throw null; }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public override string ToString() { throw null; }
}
public sealed partial class XNamespace
{
internal XNamespace() { }
public string NamespaceName { get { throw null; } }
public static System.Xml.Linq.XNamespace None { get { throw null; } }
public static System.Xml.Linq.XNamespace Xml { get { throw null; } }
public static System.Xml.Linq.XNamespace Xmlns { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public static System.Xml.Linq.XNamespace Get(string namespaceName) { throw null; }
public override int GetHashCode() { throw null; }
public System.Xml.Linq.XName GetName(string localName) { throw null; }
public static System.Xml.Linq.XName operator +(System.Xml.Linq.XNamespace ns, string localName) { throw null; }
public static bool operator ==(System.Xml.Linq.XNamespace left, System.Xml.Linq.XNamespace right) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator System.Xml.Linq.XNamespace (string namespaceName) { throw null; }
public static bool operator !=(System.Xml.Linq.XNamespace left, System.Xml.Linq.XNamespace right) { throw null; }
public override string ToString() { throw null; }
}
public abstract partial class XNode : System.Xml.Linq.XObject
{
internal XNode() { }
public static System.Xml.Linq.XNodeDocumentOrderComparer DocumentOrderComparer { get { throw null; } }
public static System.Xml.Linq.XNodeEqualityComparer EqualityComparer { get { throw null; } }
public System.Xml.Linq.XNode NextNode { get { throw null; } }
public System.Xml.Linq.XNode PreviousNode { get { throw null; } }
public void AddAfterSelf(object content) { }
public void AddAfterSelf(params object[] content) { }
public void AddBeforeSelf(object content) { }
public void AddBeforeSelf(params object[] content) { }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors() { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors(System.Xml.Linq.XName name) { throw null; }
public static int CompareDocumentOrder(System.Xml.Linq.XNode n1, System.Xml.Linq.XNode n2) { throw null; }
public System.Xml.XmlReader CreateReader() { throw null; }
public System.Xml.XmlReader CreateReader(System.Xml.Linq.ReaderOptions readerOptions) { throw null; }
public static bool DeepEquals(System.Xml.Linq.XNode n1, System.Xml.Linq.XNode n2) { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsAfterSelf() { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsAfterSelf(System.Xml.Linq.XName name) { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsBeforeSelf() { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsBeforeSelf(System.Xml.Linq.XName name) { throw null; }
public bool IsAfter(System.Xml.Linq.XNode node) { throw null; }
public bool IsBefore(System.Xml.Linq.XNode node) { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> NodesAfterSelf() { throw null; }
public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> NodesBeforeSelf() { throw null; }
public static System.Xml.Linq.XNode ReadFrom(System.Xml.XmlReader reader) { throw null; }
public static System.Threading.Tasks.Task<System.Xml.Linq.XNode> ReadFromAsync(System.Xml.XmlReader reader, System.Threading.CancellationToken cancellationToken) { throw null; }
public void Remove() { }
public void ReplaceWith(object content) { }
public void ReplaceWith(params object[] content) { }
public override string ToString() { throw null; }
public string ToString(System.Xml.Linq.SaveOptions options) { throw null; }
public abstract void WriteTo(System.Xml.XmlWriter writer);
public abstract System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken);
}
public sealed partial class XNodeDocumentOrderComparer : System.Collections.Generic.IComparer<System.Xml.Linq.XNode>, System.Collections.IComparer
{
public XNodeDocumentOrderComparer() { }
public int Compare(System.Xml.Linq.XNode x, System.Xml.Linq.XNode y) { throw null; }
int System.Collections.IComparer.Compare(object x, object y) { throw null; }
}
public sealed partial class XNodeEqualityComparer : System.Collections.Generic.IEqualityComparer<System.Xml.Linq.XNode>, System.Collections.IEqualityComparer
{
public XNodeEqualityComparer() { }
public bool Equals(System.Xml.Linq.XNode x, System.Xml.Linq.XNode y) { throw null; }
public int GetHashCode(System.Xml.Linq.XNode obj) { throw null; }
bool System.Collections.IEqualityComparer.Equals(object x, object y) { throw null; }
int System.Collections.IEqualityComparer.GetHashCode(object obj) { throw null; }
}
public abstract partial class XObject : System.Xml.IXmlLineInfo
{
internal XObject() { }
public string BaseUri { get { throw null; } }
public System.Xml.Linq.XDocument Document { get { throw null; } }
public abstract System.Xml.XmlNodeType NodeType { get; }
public System.Xml.Linq.XElement Parent { get { throw null; } }
int System.Xml.IXmlLineInfo.LineNumber { get { throw null; } }
int System.Xml.IXmlLineInfo.LinePosition { get { throw null; } }
public event System.EventHandler<System.Xml.Linq.XObjectChangeEventArgs> Changed { add { } remove { } }
public event System.EventHandler<System.Xml.Linq.XObjectChangeEventArgs> Changing { add { } remove { } }
public void AddAnnotation(object annotation) { }
public object Annotation(System.Type type) { throw null; }
public System.Collections.Generic.IEnumerable<object> Annotations(System.Type type) { throw null; }
public System.Collections.Generic.IEnumerable<T> Annotations<T>() where T : class { throw null; }
public T Annotation<T>() where T : class { throw null; }
public void RemoveAnnotations(System.Type type) { }
public void RemoveAnnotations<T>() where T : class { }
bool System.Xml.IXmlLineInfo.HasLineInfo() { throw null; }
}
public enum XObjectChange
{
Add = 0,
Remove = 1,
Name = 2,
Value = 3,
}
public partial class XObjectChangeEventArgs : System.EventArgs
{
public static readonly System.Xml.Linq.XObjectChangeEventArgs Add;
public static readonly System.Xml.Linq.XObjectChangeEventArgs Name;
public static readonly System.Xml.Linq.XObjectChangeEventArgs Remove;
public static readonly System.Xml.Linq.XObjectChangeEventArgs Value;
public XObjectChangeEventArgs(System.Xml.Linq.XObjectChange objectChange) { }
public System.Xml.Linq.XObjectChange ObjectChange { get { throw null; } }
}
public partial class XProcessingInstruction : System.Xml.Linq.XNode
{
public XProcessingInstruction(string target, string data) { }
public XProcessingInstruction(System.Xml.Linq.XProcessingInstruction other) { }
public string Data { get { throw null; } set { } }
public override System.Xml.XmlNodeType NodeType { get { throw null; } }
public string Target { get { throw null; } set { } }
public override void WriteTo(System.Xml.XmlWriter writer) { }
public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public partial class XStreamingElement
{
public XStreamingElement(System.Xml.Linq.XName name) { }
public XStreamingElement(System.Xml.Linq.XName name, object content) { }
public XStreamingElement(System.Xml.Linq.XName name, params object[] content) { }
public System.Xml.Linq.XName Name { get { throw null; } set { } }
public void Add(object content) { }
public void Add(params object[] content) { }
public void Save(System.IO.Stream stream) { }
public void Save(System.IO.Stream stream, System.Xml.Linq.SaveOptions options) { }
public void Save(System.IO.TextWriter textWriter) { }
public void Save(System.IO.TextWriter textWriter, System.Xml.Linq.SaveOptions options) { }
public void Save(string fileName) { }
public void Save(string fileName, System.Xml.Linq.SaveOptions options) { }
public void Save(System.Xml.XmlWriter writer) { }
public override string ToString() { throw null; }
public string ToString(System.Xml.Linq.SaveOptions options) { throw null; }
public void WriteTo(System.Xml.XmlWriter writer) { }
}
public partial class XText : System.Xml.Linq.XNode
{
public XText(string value) { }
public XText(System.Xml.Linq.XText other) { }
public override System.Xml.XmlNodeType NodeType { get { throw null; } }
public string Value { get { throw null; } set { } }
public override void WriteTo(System.Xml.XmlWriter writer) { }
public override System.Threading.Tasks.Task WriteToAsync(System.Xml.XmlWriter writer, System.Threading.CancellationToken cancellationToken) { throw null; }
}
}
namespace System.Xml.Schema
{
public static partial class Extensions
{
public static System.Xml.Schema.IXmlSchemaInfo GetSchemaInfo(this System.Xml.Linq.XAttribute source) { throw null; }
public static System.Xml.Schema.IXmlSchemaInfo GetSchemaInfo(this System.Xml.Linq.XElement source) { throw null; }
public static void Validate(this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler) { }
public static void Validate(this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo) { }
public static void Validate(this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler) { }
public static void Validate(this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo) { }
public static void Validate(this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler) { }
public static void Validate(this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo) { }
}
}
| |
// 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.Management
{
public enum AuthenticationLevel
{
Call = 3,
Connect = 2,
Default = 0,
None = 1,
Packet = 4,
PacketIntegrity = 5,
PacketPrivacy = 6,
Unchanged = -1,
}
public enum CimType
{
Boolean = 11,
Char16 = 103,
DateTime = 101,
None = 0,
Object = 13,
Real32 = 4,
Real64 = 5,
Reference = 102,
SInt16 = 2,
SInt32 = 3,
SInt64 = 20,
SInt8 = 16,
String = 8,
UInt16 = 18,
UInt32 = 19,
UInt64 = 21,
UInt8 = 17,
}
public enum CodeLanguage
{
CSharp = 0,
JScript = 1,
Mcpp = 4,
VB = 2,
VJSharp = 3,
}
[System.FlagsAttribute]
public enum ComparisonSettings
{
IgnoreCase = 16,
IgnoreClass = 8,
IgnoreDefaultValues = 4,
IgnoreFlavor = 32,
IgnoreObjectSource = 2,
IgnoreQualifiers = 1,
IncludeAll = 0,
}
public partial class CompletedEventArgs : System.Management.ManagementEventArgs
{
internal CompletedEventArgs() { }
public System.Management.ManagementStatus Status { get { throw null; } }
public System.Management.ManagementBaseObject StatusObject { get { throw null; } }
}
public delegate void CompletedEventHandler(object sender, System.Management.CompletedEventArgs e);
public partial class ConnectionOptions : System.Management.ManagementOptions
{
public ConnectionOptions() { }
public ConnectionOptions(string locale, string username, System.Security.SecureString password, string authority, System.Management.ImpersonationLevel impersonation, System.Management.AuthenticationLevel authentication, bool enablePrivileges, System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout) { }
public ConnectionOptions(string locale, string username, string password, string authority, System.Management.ImpersonationLevel impersonation, System.Management.AuthenticationLevel authentication, bool enablePrivileges, System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout) { }
public System.Management.AuthenticationLevel Authentication { get { throw null; } set { } }
public string Authority { get { throw null; } set { } }
public bool EnablePrivileges { get { throw null; } set { } }
public System.Management.ImpersonationLevel Impersonation { get { throw null; } set { } }
public string Locale { get { throw null; } set { } }
public string Password { set { } }
public System.Security.SecureString SecurePassword { set { } }
public string Username { get { throw null; } set { } }
public override object Clone() { throw null; }
}
public partial class DeleteOptions : System.Management.ManagementOptions
{
public DeleteOptions() { }
public DeleteOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout) { }
public override object Clone() { throw null; }
}
public partial class EnumerationOptions : System.Management.ManagementOptions
{
public EnumerationOptions() { }
public EnumerationOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout, int blockSize, bool rewindable, bool returnImmediatley, bool useAmendedQualifiers, bool ensureLocatable, bool prototypeOnly, bool directRead, bool enumerateDeep) { }
public int BlockSize { get { throw null; } set { } }
public bool DirectRead { get { throw null; } set { } }
public bool EnsureLocatable { get { throw null; } set { } }
public bool EnumerateDeep { get { throw null; } set { } }
public bool PrototypeOnly { get { throw null; } set { } }
public bool ReturnImmediately { get { throw null; } set { } }
public bool Rewindable { get { throw null; } set { } }
public bool UseAmendedQualifiers { get { throw null; } set { } }
public override object Clone() { throw null; }
}
public partial class EventArrivedEventArgs : System.Management.ManagementEventArgs
{
internal EventArrivedEventArgs() { }
public System.Management.ManagementBaseObject NewEvent { get { throw null; } }
}
public delegate void EventArrivedEventHandler(object sender, System.Management.EventArrivedEventArgs e);
public partial class EventQuery : System.Management.ManagementQuery
{
public EventQuery() { }
public EventQuery(string query) { }
public EventQuery(string language, string query) { }
public override object Clone() { throw null; }
}
public partial class EventWatcherOptions : System.Management.ManagementOptions
{
public EventWatcherOptions() { }
public EventWatcherOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout, int blockSize) { }
public int BlockSize { get { throw null; } set { } }
public override object Clone() { throw null; }
}
public enum ImpersonationLevel
{
Anonymous = 1,
Default = 0,
Delegate = 4,
Identify = 2,
Impersonate = 3,
}
public partial class InvokeMethodOptions : System.Management.ManagementOptions
{
public InvokeMethodOptions() { }
public InvokeMethodOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout) { }
public override object Clone() { throw null; }
}
[System.ComponentModel.ToolboxItemAttribute(false)]
public partial class ManagementBaseObject : System.ComponentModel.Component, System.ICloneable, System.Runtime.Serialization.ISerializable
{
protected ManagementBaseObject(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public virtual System.Management.ManagementPath ClassPath { get { throw null; } }
public object this[string propertyName] { get { throw null; } set { } }
public virtual System.Management.PropertyDataCollection Properties { get { throw null; } }
public virtual System.Management.QualifierDataCollection Qualifiers { get { throw null; } }
public virtual System.Management.PropertyDataCollection SystemProperties { get { throw null; } }
public virtual object Clone() { throw null; }
public bool CompareTo(System.Management.ManagementBaseObject otherObject, System.Management.ComparisonSettings settings) { throw null; }
public new void Dispose() { }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public object GetPropertyQualifierValue(string propertyName, string qualifierName) { throw null; }
public object GetPropertyValue(string propertyName) { throw null; }
public object GetQualifierValue(string qualifierName) { throw null; }
public string GetText(System.Management.TextFormat format) { throw null; }
public static explicit operator System.IntPtr (System.Management.ManagementBaseObject managementObject) { throw null; }
public void SetPropertyQualifierValue(string propertyName, string qualifierName, object qualifierValue) { }
public void SetPropertyValue(string propertyName, object propertyValue) { }
public void SetQualifierValue(string qualifierName, object qualifierValue) { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class ManagementClass : System.Management.ManagementObject
{
public ManagementClass() { }
public ManagementClass(System.Management.ManagementPath path) { }
public ManagementClass(System.Management.ManagementPath path, System.Management.ObjectGetOptions options) { }
public ManagementClass(System.Management.ManagementScope scope, System.Management.ManagementPath path, System.Management.ObjectGetOptions options) { }
protected ManagementClass(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public ManagementClass(string path) { }
public ManagementClass(string path, System.Management.ObjectGetOptions options) { }
public ManagementClass(string scope, string path, System.Management.ObjectGetOptions options) { }
public System.Collections.Specialized.StringCollection Derivation { get { throw null; } }
public System.Management.MethodDataCollection Methods { get { throw null; } }
public override System.Management.ManagementPath Path { get { throw null; } set { } }
public override object Clone() { throw null; }
public System.Management.ManagementObject CreateInstance() { throw null; }
public System.Management.ManagementClass Derive(string newClassName) { throw null; }
public System.Management.ManagementObjectCollection GetInstances() { throw null; }
public System.Management.ManagementObjectCollection GetInstances(System.Management.EnumerationOptions options) { throw null; }
public void GetInstances(System.Management.ManagementOperationObserver watcher) { }
public void GetInstances(System.Management.ManagementOperationObserver watcher, System.Management.EnumerationOptions options) { }
protected override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public System.Management.ManagementObjectCollection GetRelatedClasses() { throw null; }
public void GetRelatedClasses(System.Management.ManagementOperationObserver watcher) { }
public void GetRelatedClasses(System.Management.ManagementOperationObserver watcher, string relatedClass) { }
public void GetRelatedClasses(System.Management.ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, System.Management.EnumerationOptions options) { }
public System.Management.ManagementObjectCollection GetRelatedClasses(string relatedClass) { throw null; }
public System.Management.ManagementObjectCollection GetRelatedClasses(string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, System.Management.EnumerationOptions options) { throw null; }
public System.Management.ManagementObjectCollection GetRelationshipClasses() { throw null; }
public void GetRelationshipClasses(System.Management.ManagementOperationObserver watcher) { }
public void GetRelationshipClasses(System.Management.ManagementOperationObserver watcher, string relationshipClass) { }
public void GetRelationshipClasses(System.Management.ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, System.Management.EnumerationOptions options) { }
public System.Management.ManagementObjectCollection GetRelationshipClasses(string relationshipClass) { throw null; }
public System.Management.ManagementObjectCollection GetRelationshipClasses(string relationshipClass, string relationshipQualifier, string thisRole, System.Management.EnumerationOptions options) { throw null; }
public System.CodeDom.CodeTypeDeclaration GetStronglyTypedClassCode(bool includeSystemClassInClassDef, bool systemPropertyClass) { throw null; }
public bool GetStronglyTypedClassCode(System.Management.CodeLanguage lang, string filePath, string classNamespace) { throw null; }
public System.Management.ManagementObjectCollection GetSubclasses() { throw null; }
public System.Management.ManagementObjectCollection GetSubclasses(System.Management.EnumerationOptions options) { throw null; }
public void GetSubclasses(System.Management.ManagementOperationObserver watcher) { }
public void GetSubclasses(System.Management.ManagementOperationObserver watcher, System.Management.EnumerationOptions options) { }
}
public sealed partial class ManagementDateTimeConverter
{
internal ManagementDateTimeConverter() { }
public static System.DateTime ToDateTime(string dmtfDate) { throw null; }
public static string ToDmtfDateTime(System.DateTime date) { throw null; }
public static string ToDmtfTimeInterval(System.TimeSpan timespan) { throw null; }
public static System.TimeSpan ToTimeSpan(string dmtfTimespan) { throw null; }
}
public abstract partial class ManagementEventArgs : System.EventArgs
{
internal ManagementEventArgs() { }
public object Context { get { throw null; } }
}
[System.ComponentModel.ToolboxItemAttribute(false)]
public partial class ManagementEventWatcher : System.ComponentModel.Component
{
public ManagementEventWatcher() { }
public ManagementEventWatcher(System.Management.EventQuery query) { }
public ManagementEventWatcher(System.Management.ManagementScope scope, System.Management.EventQuery query) { }
public ManagementEventWatcher(System.Management.ManagementScope scope, System.Management.EventQuery query, System.Management.EventWatcherOptions options) { }
public ManagementEventWatcher(string query) { }
public ManagementEventWatcher(string scope, string query) { }
public ManagementEventWatcher(string scope, string query, System.Management.EventWatcherOptions options) { }
public System.Management.EventWatcherOptions Options { get { throw null; } set { } }
public System.Management.EventQuery Query { get { throw null; } set { } }
public System.Management.ManagementScope Scope { get { throw null; } set { } }
public event System.Management.EventArrivedEventHandler EventArrived { add { } remove { } }
public event System.Management.StoppedEventHandler Stopped { add { } remove { } }
~ManagementEventWatcher() { }
public void Start() { }
public void Stop() { }
public System.Management.ManagementBaseObject WaitForNextEvent() { throw null; }
}
public partial class ManagementException : System.SystemException
{
public ManagementException() { }
protected ManagementException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public ManagementException(string message) { }
public ManagementException(string message, System.Exception innerException) { }
public System.Management.ManagementStatus ErrorCode { get { throw null; } }
public System.Management.ManagementBaseObject ErrorInformation { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class ManagementNamedValueCollection : System.Collections.Specialized.NameObjectCollectionBase
{
public ManagementNamedValueCollection() { }
protected ManagementNamedValueCollection(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public object this[string name] { get { throw null; } }
public void Add(string name, object value) { }
public System.Management.ManagementNamedValueCollection Clone() { throw null; }
public void Remove(string name) { }
public void RemoveAll() { }
}
public partial class ManagementObject : System.Management.ManagementBaseObject, System.ICloneable
{
public ManagementObject() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public ManagementObject(System.Management.ManagementPath path) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public ManagementObject(System.Management.ManagementPath path, System.Management.ObjectGetOptions options) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public ManagementObject(System.Management.ManagementScope scope, System.Management.ManagementPath path, System.Management.ObjectGetOptions options) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
protected ManagementObject(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public ManagementObject(string path) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public ManagementObject(string path, System.Management.ObjectGetOptions options) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public ManagementObject(string scopeString, string pathString, System.Management.ObjectGetOptions options) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { }
public override System.Management.ManagementPath ClassPath { get { throw null; } }
public System.Management.ObjectGetOptions Options { get { throw null; } set { } }
public virtual System.Management.ManagementPath Path { get { throw null; } set { } }
public System.Management.ManagementScope Scope { get { throw null; } set { } }
public override object Clone() { throw null; }
public void CopyTo(System.Management.ManagementOperationObserver watcher, System.Management.ManagementPath path) { }
public void CopyTo(System.Management.ManagementOperationObserver watcher, System.Management.ManagementPath path, System.Management.PutOptions options) { }
public void CopyTo(System.Management.ManagementOperationObserver watcher, string path) { }
public void CopyTo(System.Management.ManagementOperationObserver watcher, string path, System.Management.PutOptions options) { }
public System.Management.ManagementPath CopyTo(System.Management.ManagementPath path) { throw null; }
public System.Management.ManagementPath CopyTo(System.Management.ManagementPath path, System.Management.PutOptions options) { throw null; }
public System.Management.ManagementPath CopyTo(string path) { throw null; }
public System.Management.ManagementPath CopyTo(string path, System.Management.PutOptions options) { throw null; }
public void Delete() { }
public void Delete(System.Management.DeleteOptions options) { }
public void Delete(System.Management.ManagementOperationObserver watcher) { }
public void Delete(System.Management.ManagementOperationObserver watcher, System.Management.DeleteOptions options) { }
public new void Dispose() { }
public void Get() { }
public void Get(System.Management.ManagementOperationObserver watcher) { }
public System.Management.ManagementBaseObject GetMethodParameters(string methodName) { throw null; }
protected override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public System.Management.ManagementObjectCollection GetRelated() { throw null; }
public void GetRelated(System.Management.ManagementOperationObserver watcher) { }
public void GetRelated(System.Management.ManagementOperationObserver watcher, string relatedClass) { }
public void GetRelated(System.Management.ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly, System.Management.EnumerationOptions options) { }
public System.Management.ManagementObjectCollection GetRelated(string relatedClass) { throw null; }
public System.Management.ManagementObjectCollection GetRelated(string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly, System.Management.EnumerationOptions options) { throw null; }
public System.Management.ManagementObjectCollection GetRelationships() { throw null; }
public void GetRelationships(System.Management.ManagementOperationObserver watcher) { }
public void GetRelationships(System.Management.ManagementOperationObserver watcher, string relationshipClass) { }
public void GetRelationships(System.Management.ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly, System.Management.EnumerationOptions options) { }
public System.Management.ManagementObjectCollection GetRelationships(string relationshipClass) { throw null; }
public System.Management.ManagementObjectCollection GetRelationships(string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly, System.Management.EnumerationOptions options) { throw null; }
public void InvokeMethod(System.Management.ManagementOperationObserver watcher, string methodName, System.Management.ManagementBaseObject inParameters, System.Management.InvokeMethodOptions options) { }
public void InvokeMethod(System.Management.ManagementOperationObserver watcher, string methodName, object[] args) { }
public System.Management.ManagementBaseObject InvokeMethod(string methodName, System.Management.ManagementBaseObject inParameters, System.Management.InvokeMethodOptions options) { throw null; }
public object InvokeMethod(string methodName, object[] args) { throw null; }
public System.Management.ManagementPath Put() { throw null; }
public void Put(System.Management.ManagementOperationObserver watcher) { }
public void Put(System.Management.ManagementOperationObserver watcher, System.Management.PutOptions options) { }
public System.Management.ManagementPath Put(System.Management.PutOptions options) { throw null; }
public override string ToString() { throw null; }
}
public partial class ManagementObjectCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.IDisposable
{
internal ManagementObjectCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(System.Array array, int index) { }
public void CopyTo(System.Management.ManagementBaseObject[] objectCollection, int index) { }
public void Dispose() { }
~ManagementObjectCollection() { }
public System.Management.ManagementObjectCollection.ManagementObjectEnumerator GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public partial class ManagementObjectEnumerator : System.Collections.IEnumerator, System.IDisposable
{
internal ManagementObjectEnumerator() { }
public System.Management.ManagementBaseObject Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
~ManagementObjectEnumerator() { }
public bool MoveNext() { throw null; }
public void Reset() { }
}
}
[System.ComponentModel.ToolboxItemAttribute(false)]
public partial class ManagementObjectSearcher : System.ComponentModel.Component
{
public ManagementObjectSearcher() { }
public ManagementObjectSearcher(System.Management.ManagementScope scope, System.Management.ObjectQuery query) { }
public ManagementObjectSearcher(System.Management.ManagementScope scope, System.Management.ObjectQuery query, System.Management.EnumerationOptions options) { }
public ManagementObjectSearcher(System.Management.ObjectQuery query) { }
public ManagementObjectSearcher(string queryString) { }
public ManagementObjectSearcher(string scope, string queryString) { }
public ManagementObjectSearcher(string scope, string queryString, System.Management.EnumerationOptions options) { }
public System.Management.EnumerationOptions Options { get { throw null; } set { } }
public System.Management.ObjectQuery Query { get { throw null; } set { } }
public System.Management.ManagementScope Scope { get { throw null; } set { } }
public System.Management.ManagementObjectCollection Get() { throw null; }
public void Get(System.Management.ManagementOperationObserver watcher) { }
}
public partial class ManagementOperationObserver
{
public ManagementOperationObserver() { }
public event System.Management.CompletedEventHandler Completed { add { } remove { } }
public event System.Management.ObjectPutEventHandler ObjectPut { add { } remove { } }
public event System.Management.ObjectReadyEventHandler ObjectReady { add { } remove { } }
public event System.Management.ProgressEventHandler Progress { add { } remove { } }
public void Cancel() { }
}
public abstract partial class ManagementOptions : System.ICloneable
{
internal ManagementOptions() { }
public static readonly System.TimeSpan InfiniteTimeout;
public System.Management.ManagementNamedValueCollection Context { get { throw null; } set { } }
public System.TimeSpan Timeout { get { throw null; } set { } }
public abstract object Clone();
}
public partial class ManagementPath : System.ICloneable
{
public ManagementPath() { }
public ManagementPath(string path) { }
[System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))]
public string ClassName { get { throw null; } set { } }
public static System.Management.ManagementPath DefaultPath { get { throw null; } set { } }
public bool IsClass { get { throw null; } }
public bool IsInstance { get { throw null; } }
public bool IsSingleton { get { throw null; } }
[System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))]
public string NamespacePath { get { throw null; } set { } }
[System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))]
public string Path { get { throw null; } set { } }
[System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))]
public string RelativePath { get { throw null; } set { } }
[System.ComponentModel.RefreshPropertiesAttribute((System.ComponentModel.RefreshProperties)(1))]
public string Server { get { throw null; } set { } }
public System.Management.ManagementPath Clone() { throw null; }
public void SetAsClass() { }
public void SetAsSingleton() { }
object System.ICloneable.Clone() { throw null; }
public override string ToString() { throw null; }
}
public abstract partial class ManagementQuery : System.ICloneable
{
internal ManagementQuery() { }
public virtual string QueryLanguage { get { throw null; } set { } }
public virtual string QueryString { get { throw null; } set { } }
public abstract object Clone();
protected internal virtual void ParseQuery(string query) { }
}
public partial class ManagementScope : System.ICloneable
{
public ManagementScope() { }
public ManagementScope(System.Management.ManagementPath path) { }
public ManagementScope(System.Management.ManagementPath path, System.Management.ConnectionOptions options) { }
public ManagementScope(string path) { }
public ManagementScope(string path, System.Management.ConnectionOptions options) { }
public bool IsConnected { get { throw null; } }
public System.Management.ConnectionOptions Options { get { throw null; } set { } }
public System.Management.ManagementPath Path { get { throw null; } set { } }
public System.Management.ManagementScope Clone() { throw null; }
public void Connect() { }
object System.ICloneable.Clone() { throw null; }
}
public enum ManagementStatus
{
AccessDenied = -2147217405,
AggregatingByObject = -2147217315,
AlreadyExists = -2147217383,
AmendedObject = -2147217306,
BackupRestoreWinmgmtRunning = -2147217312,
BufferTooSmall = -2147217348,
CallCanceled = -2147217358,
CannotBeAbstract = -2147217307,
CannotBeKey = -2147217377,
CannotBeSingleton = -2147217364,
CannotChangeIndexInheritance = -2147217328,
CannotChangeKeyInheritance = -2147217335,
CircularReference = -2147217337,
ClassHasChildren = -2147217371,
ClassHasInstances = -2147217370,
ClientTooSlow = -2147217305,
CriticalError = -2147217398,
Different = 262147,
DuplicateObjects = 262152,
Failed = -2147217407,
False = 1,
IllegalNull = -2147217368,
IllegalOperation = -2147217378,
IncompleteClass = -2147217376,
InitializationFailure = -2147217388,
InvalidCimType = -2147217363,
InvalidClass = -2147217392,
InvalidContext = -2147217401,
InvalidDuplicateParameter = -2147217341,
InvalidFlavor = -2147217338,
InvalidMethod = -2147217362,
InvalidMethodParameters = -2147217361,
InvalidNamespace = -2147217394,
InvalidObject = -2147217393,
InvalidObjectPath = -2147217350,
InvalidOperation = -2147217386,
InvalidOperator = -2147217309,
InvalidParameter = -2147217400,
InvalidParameterID = -2147217353,
InvalidProperty = -2147217359,
InvalidPropertyType = -2147217366,
InvalidProviderRegistration = -2147217390,
InvalidQualifier = -2147217342,
InvalidQualifierType = -2147217367,
InvalidQuery = -2147217385,
InvalidQueryType = -2147217384,
InvalidStream = -2147217397,
InvalidSuperclass = -2147217395,
InvalidSyntax = -2147217375,
LocalCredentials = -2147217308,
MarshalInvalidSignature = -2147217343,
MarshalVersionMismatch = -2147217344,
MethodDisabled = -2147217322,
MethodNotImplemented = -2147217323,
MissingAggregationList = -2147217317,
MissingGroupWithin = -2147217318,
MissingParameterID = -2147217354,
NoError = 0,
NoMoreData = 262149,
NonconsecutiveParameterIDs = -2147217352,
NondecoratedObject = -2147217374,
NotAvailable = -2147217399,
NotEventClass = -2147217319,
NotFound = -2147217406,
NotSupported = -2147217396,
OperationCanceled = 262150,
OutOfDiskSpace = -2147217349,
OutOfMemory = -2147217402,
OverrideNotAllowed = -2147217382,
ParameterIDOnRetval = -2147217351,
PartialResults = 262160,
Pending = 262151,
PrivilegeNotHeld = -2147217310,
PropagatedMethod = -2147217356,
PropagatedProperty = -2147217380,
PropagatedQualifier = -2147217381,
PropertyNotAnObject = -2147217316,
ProviderFailure = -2147217404,
ProviderLoadFailure = -2147217389,
ProviderNotCapable = -2147217372,
ProviderNotFound = -2147217391,
QueryNotImplemented = -2147217369,
QueueOverflow = -2147217311,
ReadOnly = -2147217373,
RefresherBusy = -2147217321,
RegistrationTooBroad = -2147213311,
RegistrationTooPrecise = -2147213310,
ResetToDefault = 262146,
ServerTooBusy = -2147217339,
ShuttingDown = -2147217357,
SystemProperty = -2147217360,
Timedout = 262148,
TooManyProperties = -2147217327,
TooMuchData = -2147217340,
TransportFailure = -2147217387,
TypeMismatch = -2147217403,
Unexpected = -2147217379,
UninterpretableProviderQuery = -2147217313,
UnknownObjectType = -2147217346,
UnknownPacketType = -2147217345,
UnparsableQuery = -2147217320,
UnsupportedClassUpdate = -2147217336,
UnsupportedParameter = -2147217355,
UnsupportedPutExtension = -2147217347,
UpdateOverrideNotAllowed = -2147217325,
UpdatePropagatedMethod = -2147217324,
UpdateTypeMismatch = -2147217326,
ValueOutOfRange = -2147217365,
}
public partial class MethodData
{
internal MethodData() { }
public System.Management.ManagementBaseObject InParameters { get { throw null; } }
public string Name { get { throw null; } }
public string Origin { get { throw null; } }
public System.Management.ManagementBaseObject OutParameters { get { throw null; } }
public System.Management.QualifierDataCollection Qualifiers { get { throw null; } }
}
public partial class MethodDataCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal MethodDataCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public virtual System.Management.MethodData this[string methodName] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public virtual void Add(string methodName) { }
public virtual void Add(string methodName, System.Management.ManagementBaseObject inParameters, System.Management.ManagementBaseObject outParameters) { }
public void CopyTo(System.Array array, int index) { }
public void CopyTo(System.Management.MethodData[] methodArray, int index) { }
public System.Management.MethodDataCollection.MethodDataEnumerator GetEnumerator() { throw null; }
public virtual void Remove(string methodName) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public partial class MethodDataEnumerator : System.Collections.IEnumerator
{
internal MethodDataEnumerator() { }
public System.Management.MethodData Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
}
}
public partial class ObjectGetOptions : System.Management.ManagementOptions
{
public ObjectGetOptions() { }
public ObjectGetOptions(System.Management.ManagementNamedValueCollection context) { }
public ObjectGetOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout, bool useAmendedQualifiers) { }
public bool UseAmendedQualifiers { get { throw null; } set { } }
public override object Clone() { throw null; }
}
public partial class ObjectPutEventArgs : System.Management.ManagementEventArgs
{
internal ObjectPutEventArgs() { }
public System.Management.ManagementPath Path { get { throw null; } }
}
public delegate void ObjectPutEventHandler(object sender, System.Management.ObjectPutEventArgs e);
public partial class ObjectQuery : System.Management.ManagementQuery
{
public ObjectQuery() { }
public ObjectQuery(string query) { }
public ObjectQuery(string language, string query) { }
public override object Clone() { throw null; }
}
public partial class ObjectReadyEventArgs : System.Management.ManagementEventArgs
{
internal ObjectReadyEventArgs() { }
public System.Management.ManagementBaseObject NewObject { get { throw null; } }
}
public delegate void ObjectReadyEventHandler(object sender, System.Management.ObjectReadyEventArgs e);
public partial class ProgressEventArgs : System.Management.ManagementEventArgs
{
internal ProgressEventArgs() { }
public int Current { get { throw null; } }
public string Message { get { throw null; } }
public int UpperBound { get { throw null; } }
}
public delegate void ProgressEventHandler(object sender, System.Management.ProgressEventArgs e);
public partial class PropertyData
{
internal PropertyData() { }
public bool IsArray { get { throw null; } }
public bool IsLocal { get { throw null; } }
public string Name { get { throw null; } }
public string Origin { get { throw null; } }
public System.Management.QualifierDataCollection Qualifiers { get { throw null; } }
public System.Management.CimType Type { get { throw null; } }
public object Value { get { throw null; } set { } }
}
public partial class PropertyDataCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal PropertyDataCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public virtual System.Management.PropertyData this[string propertyName] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void Add(string propertyName, System.Management.CimType propertyType, bool isArray) { }
public virtual void Add(string propertyName, object propertyValue) { }
public void Add(string propertyName, object propertyValue, System.Management.CimType propertyType) { }
public void CopyTo(System.Array array, int index) { }
public void CopyTo(System.Management.PropertyData[] propertyArray, int index) { }
public System.Management.PropertyDataCollection.PropertyDataEnumerator GetEnumerator() { throw null; }
public virtual void Remove(string propertyName) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public partial class PropertyDataEnumerator : System.Collections.IEnumerator
{
internal PropertyDataEnumerator() { }
public System.Management.PropertyData Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
}
}
public partial class PutOptions : System.Management.ManagementOptions
{
public PutOptions() { }
public PutOptions(System.Management.ManagementNamedValueCollection context) { }
public PutOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout, bool useAmendedQualifiers, System.Management.PutType putType) { }
public System.Management.PutType Type { get { throw null; } set { } }
public bool UseAmendedQualifiers { get { throw null; } set { } }
public override object Clone() { throw null; }
}
public enum PutType
{
CreateOnly = 2,
None = 0,
UpdateOnly = 1,
UpdateOrCreate = 3,
}
public partial class QualifierData
{
internal QualifierData() { }
public bool IsAmended { get { throw null; } set { } }
public bool IsLocal { get { throw null; } }
public bool IsOverridable { get { throw null; } set { } }
public string Name { get { throw null; } }
public bool PropagatesToInstance { get { throw null; } set { } }
public bool PropagatesToSubclass { get { throw null; } set { } }
public object Value { get { throw null; } set { } }
}
public partial class QualifierDataCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal QualifierDataCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public virtual System.Management.QualifierData this[string qualifierName] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public virtual void Add(string qualifierName, object qualifierValue) { }
public virtual void Add(string qualifierName, object qualifierValue, bool isAmended, bool propagatesToInstance, bool propagatesToSubclass, bool isOverridable) { }
public void CopyTo(System.Array array, int index) { }
public void CopyTo(System.Management.QualifierData[] qualifierArray, int index) { }
public System.Management.QualifierDataCollection.QualifierDataEnumerator GetEnumerator() { throw null; }
public virtual void Remove(string qualifierName) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public partial class QualifierDataEnumerator : System.Collections.IEnumerator
{
internal QualifierDataEnumerator() { }
public System.Management.QualifierData Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
}
}
public partial class RelatedObjectQuery : System.Management.WqlObjectQuery
{
public RelatedObjectQuery() { }
public RelatedObjectQuery(bool isSchemaQuery, string sourceObject, string relatedClass, string relationshipClass, string relatedQualifier, string relationshipQualifier, string relatedRole, string thisRole) { }
public RelatedObjectQuery(string queryOrSourceObject) { }
public RelatedObjectQuery(string sourceObject, string relatedClass) { }
public RelatedObjectQuery(string sourceObject, string relatedClass, string relationshipClass, string relatedQualifier, string relationshipQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly) { }
public bool ClassDefinitionsOnly { get { throw null; } set { } }
public bool IsSchemaQuery { get { throw null; } set { } }
public string RelatedClass { get { throw null; } set { } }
public string RelatedQualifier { get { throw null; } set { } }
public string RelatedRole { get { throw null; } set { } }
public string RelationshipClass { get { throw null; } set { } }
public string RelationshipQualifier { get { throw null; } set { } }
public string SourceObject { get { throw null; } set { } }
public string ThisRole { get { throw null; } set { } }
protected internal void BuildQuery() { }
public override object Clone() { throw null; }
protected internal override void ParseQuery(string query) { }
}
public partial class RelationshipQuery : System.Management.WqlObjectQuery
{
public RelationshipQuery() { }
public RelationshipQuery(bool isSchemaQuery, string sourceObject, string relationshipClass, string relationshipQualifier, string thisRole) { }
public RelationshipQuery(string queryOrSourceObject) { }
public RelationshipQuery(string sourceObject, string relationshipClass) { }
public RelationshipQuery(string sourceObject, string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly) { }
public bool ClassDefinitionsOnly { get { throw null; } set { } }
public bool IsSchemaQuery { get { throw null; } set { } }
public string RelationshipClass { get { throw null; } set { } }
public string RelationshipQualifier { get { throw null; } set { } }
public string SourceObject { get { throw null; } set { } }
public string ThisRole { get { throw null; } set { } }
protected internal void BuildQuery() { }
public override object Clone() { throw null; }
protected internal override void ParseQuery(string query) { }
}
public partial class SelectQuery : System.Management.WqlObjectQuery
{
public SelectQuery() { }
public SelectQuery(bool isSchemaQuery, string condition) { }
public SelectQuery(string queryOrClassName) { }
public SelectQuery(string className, string condition) { }
public SelectQuery(string className, string condition, string[] selectedProperties) { }
public string ClassName { get { throw null; } set { } }
public string Condition { get { throw null; } set { } }
public bool IsSchemaQuery { get { throw null; } set { } }
public override string QueryString { get { throw null; } set { } }
public System.Collections.Specialized.StringCollection SelectedProperties { get { throw null; } set { } }
protected internal void BuildQuery() { }
public override object Clone() { throw null; }
protected internal override void ParseQuery(string query) { }
}
public partial class StoppedEventArgs : System.Management.ManagementEventArgs
{
internal StoppedEventArgs() { }
public System.Management.ManagementStatus Status { get { throw null; } }
}
public delegate void StoppedEventHandler(object sender, System.Management.StoppedEventArgs e);
public enum TextFormat
{
CimDtd20 = 1,
Mof = 0,
WmiDtd20 = 2,
}
public partial class WqlEventQuery : System.Management.EventQuery
{
public WqlEventQuery() { }
public WqlEventQuery(string queryOrEventClassName) { }
public WqlEventQuery(string eventClassName, string condition) { }
public WqlEventQuery(string eventClassName, string condition, System.TimeSpan groupWithinInterval) { }
public WqlEventQuery(string eventClassName, string condition, System.TimeSpan groupWithinInterval, string[] groupByPropertyList) { }
public WqlEventQuery(string eventClassName, System.TimeSpan withinInterval) { }
public WqlEventQuery(string eventClassName, System.TimeSpan withinInterval, string condition) { }
public WqlEventQuery(string eventClassName, System.TimeSpan withinInterval, string condition, System.TimeSpan groupWithinInterval, string[] groupByPropertyList, string havingCondition) { }
public string Condition { get { throw null; } set { } }
public string EventClassName { get { throw null; } set { } }
public System.Collections.Specialized.StringCollection GroupByPropertyList { get { throw null; } set { } }
public System.TimeSpan GroupWithinInterval { get { throw null; } set { } }
public string HavingCondition { get { throw null; } set { } }
public override string QueryLanguage { get { throw null; } }
public override string QueryString { get { throw null; } set { } }
public System.TimeSpan WithinInterval { get { throw null; } set { } }
protected internal void BuildQuery() { }
public override object Clone() { throw null; }
protected internal override void ParseQuery(string query) { }
}
public partial class WqlObjectQuery : System.Management.ObjectQuery
{
public WqlObjectQuery() { }
public WqlObjectQuery(string query) { }
public override string QueryLanguage { get { throw null; } }
public override object Clone() { throw null; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.