context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei [email protected]
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SLua
{
#if !SLUA_STANDALONE
using UnityEngine;
#endif
using System.Collections;
using System.Collections.Generic;
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Struct)]
public class CustomLuaClassAttribute : System.Attribute
{
public CustomLuaClassAttribute()
{
//
}
}
public class DoNotToLuaAttribute : System.Attribute
{
public DoNotToLuaAttribute()
{
//
}
}
public class LuaBinderAttribute : System.Attribute
{
public int order;
public LuaBinderAttribute(int order)
{
this.order = order;
}
}
[AttributeUsage(AttributeTargets.Method)]
public class StaticExportAttribute : System.Attribute
{
public StaticExportAttribute()
{
//
}
}
[AttributeUsage(AttributeTargets.Method)]
public class LuaOverrideAttribute : System.Attribute {
public string fn;
public LuaOverrideAttribute(string fn) {
this.fn = fn;
}
}
public class OverloadLuaClassAttribute : System.Attribute {
public OverloadLuaClassAttribute(Type target) {
targetType = target;
}
public Type targetType;
}
public class LuaOut { }
public partial class LuaObject
{
static protected LuaCSFunction lua_gc = new LuaCSFunction(luaGC);
static protected LuaCSFunction lua_add = new LuaCSFunction(luaAdd);
static protected LuaCSFunction lua_sub = new LuaCSFunction(luaSub);
static protected LuaCSFunction lua_mul = new LuaCSFunction(luaMul);
static protected LuaCSFunction lua_div = new LuaCSFunction(luaDiv);
static protected LuaCSFunction lua_unm = new LuaCSFunction(luaUnm);
static protected LuaCSFunction lua_eq = new LuaCSFunction(luaEq);
static protected LuaCSFunction lua_lt = new LuaCSFunction(luaLt);
static protected LuaCSFunction lua_le = new LuaCSFunction(luaLe);
static protected LuaCSFunction lua_tostring = new LuaCSFunction(ToString);
const string DelgateTable = "__LuaDelegate";
static protected LuaFunction newindex_func;
static protected LuaFunction index_func;
internal const int VersionNumber = 0x1201;
public static void init(IntPtr l)
{
string newindexfun = @"
local getmetatable=getmetatable
local rawget=rawget
local error=error
local type=type
local function newindex(ud,k,v)
local t=getmetatable(ud)
repeat
local h=rawget(t,k)
if h then
if h[2] then
h[2](ud,v)
return
else
error('property '..k..' is read only')
end
end
t=rawget(t,'__parent')
until t==nil
error('can not find '..k)
end
return newindex
";
string indexfun = @"
local type=type
local error=error
local rawget=rawget
local getmetatable=getmetatable
local function index(ud,k)
local t=getmetatable(ud)
repeat
local fun=rawget(t,k)
local tp=type(fun)
if tp=='function' then
return fun
elseif tp=='table' then
local f=fun[1]
if f then
return f(ud)
else
error('property '..k..' is write only')
end
end
t = rawget(t,'__parent')
until t==nil
error('Can not find '..k)
end
return index
";
LuaState L = LuaState.get(l);
newindex_func = (LuaFunction)L.doString(newindexfun);
index_func = (LuaFunction)L.doString(indexfun);
// object method
LuaDLL.lua_createtable(l, 0, 4);
addMember(l, ToString);
addMember(l, GetHashCode);
addMember(l, Equals);
addMember (l, GetType);
LuaDLL.lua_setfield(l, LuaIndexes.LUA_REGISTRYINDEX, "__luabaseobject");
LuaArray.init(l);
LuaVarObject.init(l);
LuaDLL.lua_newtable(l);
LuaDLL.lua_setglobal(l, DelgateTable);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int ToString(IntPtr l)
{
try
{
object obj = checkVar(l, 1);
pushValue(l, true);
pushValue(l, obj.ToString());
return 2;
}
catch (Exception e)
{
return error(l, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int GetHashCode(IntPtr l)
{
try
{
object obj = checkVar(l, 1);
pushValue(l, true);
pushValue(l, obj.GetHashCode());
return 2;
}
catch (Exception e)
{
return error(l, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int Equals(IntPtr l)
{
try
{
object obj = checkVar(l, 1);
object other = checkVar(l, 2);
pushValue(l, true);
pushValue(l, obj.Equals(other));
return 2;
}
catch (Exception e)
{
return error(l, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int GetType(IntPtr l)
{
try
{
object obj = checkVar(l, 1);
pushValue(l, true);
pushObject(l, obj.GetType());
return 2;
}
catch (Exception e)
{
return error(l, e);
}
}
static int getOpFunction(IntPtr l, string f, string tip)
{
int err = pushTry(l);
checkLuaObject(l, 1);
while (!LuaDLL.lua_isnil(l, -1))
{
LuaDLL.lua_getfield(l, -1, f);
if (!LuaDLL.lua_isnil(l, -1))
{
LuaDLL.lua_remove(l, -2);
break;
}
LuaDLL.lua_pop(l, 1); //pop nil
LuaDLL.lua_getfield(l, -1, "__parent");
LuaDLL.lua_remove(l, -2); //pop base
}
if (LuaDLL.lua_isnil(l, -1))
{
LuaDLL.lua_pop(l, 1);
throw new Exception(string.Format("No {0} operator", tip));
}
return err;
}
static int luaOp(IntPtr l, string f, string tip)
{
int err = getOpFunction(l, f, tip);
LuaDLL.lua_pushvalue(l, 1);
LuaDLL.lua_pushvalue(l, 2);
if (LuaDLL.lua_pcall(l, 2, 1, err) != 0)
LuaDLL.lua_pop(l, 1);
LuaDLL.lua_remove(l, err);
pushValue(l, true);
LuaDLL.lua_insert(l, -2);
return 2;
}
static int luaUnaryOp(IntPtr l, string f, string tip)
{
int err = getOpFunction(l, f, tip);
LuaDLL.lua_pushvalue(l, 1);
if (LuaDLL.lua_pcall(l, 1, 1, err) != 0)
LuaDLL.lua_pop(l, 1);
LuaDLL.lua_remove(l, err);
pushValue(l, true);
LuaDLL.lua_insert(l, -2);
return 2;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int luaAdd(IntPtr l)
{
try
{
return luaOp(l, "op_Addition", "add");
}
catch(Exception e)
{
return error(l, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int luaSub(IntPtr l)
{
try
{
return luaOp(l, "op_Subtraction", "sub");
}
catch (Exception e)
{
return error(l, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int luaMul(IntPtr l)
{
try
{
return luaOp(l, "op_Multiply", "mul");
}
catch (Exception e)
{
return error(l, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int luaDiv(IntPtr l)
{
try
{
return luaOp(l, "op_Division", "div");
}
catch (Exception e)
{
return error(l, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int luaUnm(IntPtr l)
{
try
{
return luaUnaryOp(l, "op_UnaryNegation", "unm");
}
catch (Exception e)
{
return error(l, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int luaEq(IntPtr l)
{
try
{
return luaOp(l, "op_Equality", "eq");
}
catch (Exception e)
{
return error(l, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int luaLt(IntPtr l)
{
try
{
return luaOp(l, "op_LessThan", "lt");
}
catch (Exception e)
{
return error(l, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int luaLe(IntPtr l)
{
try
{
return luaOp(l, "op_LessThanOrEqual", "le");
}
catch (Exception e)
{
return error(l, e);
}
}
public static void getEnumTable(IntPtr l, string t)
{
newTypeTable(l, t);
}
public static void getTypeTable(IntPtr l, string t)
{
newTypeTable(l, t);
// for static
LuaDLL.lua_newtable(l);
// for instance
LuaDLL.lua_newtable(l);
}
public static void newTypeTable(IntPtr l, string name)
{
string[] subt = name.Split('.');
LuaDLL.lua_pushglobaltable(l);
foreach(string t in subt)
{
LuaDLL.lua_pushstring(l, t);
LuaDLL.lua_rawget(l, -2);
if (LuaDLL.lua_isnil(l, -1))
{
LuaDLL.lua_pop(l, 1);
LuaDLL.lua_createtable(l, 0, 0);
LuaDLL.lua_pushstring(l, t);
LuaDLL.lua_pushvalue(l, -2);
LuaDLL.lua_rawset(l, -4);
}
LuaDLL.lua_remove(l, -2);
}
}
public static void createTypeMetatable(IntPtr l, Type self)
{
createTypeMetatable(l, null, self, null);
}
public static void createTypeMetatable(IntPtr l, LuaCSFunction con, Type self)
{
createTypeMetatable(l, con, self, null);
}
static void checkMethodValid(LuaCSFunction f)
{
#if UNITY_EDITOR
if (f != null && !Attribute.IsDefined(f.Method, typeof(MonoPInvokeCallbackAttribute)))
{
Logger.LogError(string.Format("MonoPInvokeCallbackAttribute not defined for LuaCSFunction {0}.", f.Method));
}
#endif
}
public static void createTypeMetatable(IntPtr l, LuaCSFunction con, Type self, Type parent)
{
checkMethodValid(con);
// set parent
bool parentSet = false;
LuaDLL.lua_pushstring(l, "__parent");
while (parent != null && parent != typeof(object) && parent != typeof(ValueType))
{
LuaDLL.luaL_getmetatable(l, ObjectCache.getAQName(parent));
// if parentType is not exported to lua
if (LuaDLL.lua_isnil(l, -1))
{
LuaDLL.lua_pop(l, 1);
parent = parent.BaseType;
}
else
{
LuaDLL.lua_rawset(l, -3);
LuaDLL.lua_pushstring(l, "__parent");
LuaDLL.luaL_getmetatable(l, parent.FullName);
LuaDLL.lua_rawset(l, -4);
parentSet = true;
break;
}
}
if(!parentSet)
{
LuaDLL.luaL_getmetatable(l, "__luabaseobject");
LuaDLL.lua_rawset(l, -3);
}
completeInstanceMeta(l, self);
completeTypeMeta(l, con, self);
LuaDLL.lua_pop(l, 1); // pop type Table
}
static void completeTypeMeta(IntPtr l, LuaCSFunction con, Type self)
{
LuaDLL.lua_pushstring(l, ObjectCache.getAQName(self));
LuaDLL.lua_setfield(l, -3, "__fullname");
index_func.push(l);
LuaDLL.lua_setfield(l, -2, "__index");
newindex_func.push(l);
LuaDLL.lua_setfield(l, -2, "__newindex");
if (con == null) con = noConstructor;
pushValue(l, con);
LuaDLL.lua_setfield(l, -2, "__call");
LuaDLL.lua_pushcfunction(l, typeToString);
LuaDLL.lua_setfield(l, -2, "__tostring");
LuaDLL.lua_pushvalue(l, -1);
LuaDLL.lua_setmetatable(l, -3);
LuaDLL.lua_setfield(l, LuaIndexes.LUA_REGISTRYINDEX, self.FullName);
}
private static void completeInstanceMeta(IntPtr l, Type self)
{
LuaDLL.lua_pushstring(l, "__typename");
LuaDLL.lua_pushstring(l, self.Name);
LuaDLL.lua_rawset(l, -3);
// for instance
index_func.push(l);
LuaDLL.lua_setfield(l, -2, "__index");
newindex_func.push(l);
LuaDLL.lua_setfield(l, -2, "__newindex");
pushValue(l, lua_add);
LuaDLL.lua_setfield(l, -2, "__add");
pushValue(l, lua_sub);
LuaDLL.lua_setfield(l, -2, "__sub");
pushValue(l, lua_mul);
LuaDLL.lua_setfield(l, -2, "__mul");
pushValue(l, lua_div);
LuaDLL.lua_setfield(l, -2, "__div");
pushValue(l, lua_unm);
LuaDLL.lua_setfield(l, -2, "__unm");
pushValue(l, lua_eq);
LuaDLL.lua_setfield(l, -2, "__eq");
pushValue(l, lua_le);
LuaDLL.lua_setfield(l, -2, "__le");
pushValue(l, lua_lt);
LuaDLL.lua_setfield(l, -2, "__lt");
pushValue(l, lua_tostring);
LuaDLL.lua_setfield(l, -2, "__tostring");
LuaDLL.lua_pushcfunction(l, lua_gc);
LuaDLL.lua_setfield(l, -2, "__gc");
if (self.IsValueType && isImplByLua(self))
{
LuaDLL.lua_pushvalue(l, -1);
LuaDLL.lua_setglobal(l, self.FullName + ".Instance");
}
LuaDLL.lua_setfield(l, LuaIndexes.LUA_REGISTRYINDEX, ObjectCache.getAQName(self));
}
public static bool isImplByLua(Type t)
{
#if !SLUA_STANDALONE
return t == typeof(Color)
|| t == typeof(Vector2)
|| t == typeof(Vector3)
|| t == typeof(Vector4)
|| t == typeof(Quaternion);
#else
return false;
#endif
}
public static void reg(IntPtr l, LuaCSFunction func, string ns)
{
checkMethodValid(func);
newTypeTable(l, ns);
pushValue(l, func);
LuaDLL.lua_setfield(l, -2, func.Method.Name);
LuaDLL.lua_pop(l, 1);
}
protected static void addMember(IntPtr l, LuaCSFunction func)
{
checkMethodValid(func);
pushValue(l, func);
string name = func.Method.Name;
if (name.EndsWith("_s"))
{
name = name.Substring(0, name.Length - 2);
LuaDLL.lua_setfield(l, -3, name);
}
else
LuaDLL.lua_setfield(l, -2, name);
}
protected static void addMember(IntPtr l, LuaCSFunction func, bool instance)
{
checkMethodValid(func);
pushValue(l, func);
string name = func.Method.Name;
LuaDLL.lua_setfield(l, instance ? -2 : -3, name);
}
protected static void addMember(IntPtr l, string name, LuaCSFunction get, LuaCSFunction set, bool instance)
{
checkMethodValid(get);
checkMethodValid(set);
int t = instance ? -2 : -3;
LuaDLL.lua_createtable(l, 2, 0);
if (get == null)
LuaDLL.lua_pushnil(l);
else
pushValue(l, get);
LuaDLL.lua_rawseti(l, -2, 1);
if (set == null)
LuaDLL.lua_pushnil(l);
else
pushValue(l, set);
LuaDLL.lua_rawseti(l, -2, 2);
LuaDLL.lua_setfield(l, t, name);
}
protected static void addMember(IntPtr l, int v, string name)
{
LuaDLL.lua_pushinteger(l, v);
LuaDLL.lua_setfield(l, -2, name);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int luaGC(IntPtr l)
{
int index = LuaDLL.luaS_rawnetobj(l, 1);
if (index > 0)
{
ObjectCache t = ObjectCache.get(l);
t.gc(index);
}
return 0;
}
#if !SLUA_STANDALONE
static internal void gc(IntPtr l,int p,UnityEngine.Object o)
{
// set ud's metatable is nil avoid gc again
LuaDLL.lua_pushnil(l);
LuaDLL.lua_setmetatable(l, p);
ObjectCache t = ObjectCache.get(l);
t.gc(o);
}
#endif
static public void checkLuaObject(IntPtr l, int p)
{
LuaDLL.lua_getmetatable(l, p);
if (LuaDLL.lua_isnil(l, -1))
{
LuaDLL.lua_pop(l, 1);
throw new Exception("expect luaobject as first argument");
}
}
public static void pushObject(IntPtr l, object o)
{
ObjectCache oc = ObjectCache.get(l);
oc.push(l, o);
}
public static void pushObject(IntPtr l, Array o)
{
ObjectCache oc = ObjectCache.get(l);
oc.push(l, o);
}
// lightobj is non-exported object used for re-get from c#, not for lua
public static void pushLightObject(IntPtr l, object t)
{
ObjectCache oc = ObjectCache.get(l);
oc.push(l, t, false);
}
public static int pushTry(IntPtr l)
{
var state = LuaState.get(l);
if (!state.isMainThread())
{
Logger.LogError("Can't call lua function in bg thread");
return 0;
}
return state.pushTry();
}
public static bool matchType(IntPtr l, int p, LuaTypes lt, Type t)
{
if (t == typeof(object))
{
return true;
}
else if (t == typeof(Type) && isTypeTable(l, p))
{
return true;
}
else if (t == typeof(char[]) || t==typeof(byte[]))
{
return lt == LuaTypes.LUA_TSTRING;
}
switch (lt)
{
case LuaTypes.LUA_TNIL:
return !t.IsValueType && !t.IsPrimitive;
case LuaTypes.LUA_TNUMBER:
#if LUA_5_3
if (LuaDLL.lua_isinteger(l, p) > 0)
return (t.IsPrimitive && t != typeof(float) && t != typeof(double)) || t.IsEnum;
else
return t == typeof(float) || t == typeof(double);
#else
return t.IsPrimitive || t.IsEnum;
#endif
case LuaTypes.LUA_TUSERDATA:
object o = checkObj (l, p);
Type ot = o.GetType ();
return ot == t || ot.IsSubclassOf (t) || t.IsAssignableFrom (ot);
case LuaTypes.LUA_TSTRING:
return t == typeof(string);
case LuaTypes.LUA_TBOOLEAN:
return t == typeof(bool);
case LuaTypes.LUA_TTABLE:
{
if (t == typeof(LuaTable) || t.IsArray)
return true;
else if (t.IsValueType)
return true;//luaTypeCheck(l, p, t.Name);
else if (LuaDLL.luaS_subclassof(l, p, t.Name) == 1)
return true;
else
return false;
}
case LuaTypes.LUA_TFUNCTION:
return t == typeof(LuaFunction) || t.BaseType == typeof(MulticastDelegate);
case LuaTypes.LUA_TTHREAD:
return t == typeof(LuaThread);
}
return false;
}
public static bool isTypeTable(IntPtr l, int p)
{
if (LuaDLL.lua_type(l, p) != LuaTypes.LUA_TTABLE)
return false;
LuaDLL.lua_pushstring(l, "__fullname");
LuaDLL.lua_rawget(l, p);
if (LuaDLL.lua_isnil(l, -1))
{
LuaDLL.lua_pop(l, 1);
return false;
}
return true;
}
public static bool isLuaClass(IntPtr l, int p)
{
return LuaDLL.luaS_subclassof(l, p, null) == 1;
}
static bool isLuaValueType(IntPtr l, int p)
{
return LuaDLL.luaS_checkluatype(l, p, null) == 1;
}
public static bool matchType(IntPtr l, int p, Type t1)
{
LuaTypes t = LuaDLL.lua_type(l, p);
return matchType(l, p, t, t1);
}
public static bool matchType(IntPtr l, int total, int from, Type t1)
{
if (total - from + 1 != 1)
return false;
return matchType(l, from, t1);
}
public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2)
{
if (total - from + 1 != 2)
return false;
return matchType(l, from, t1) && matchType(l, from + 1, t2);
}
public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2, Type t3)
{
if (total - from + 1 != 3)
return false;
return matchType(l, from, t1) && matchType(l, from + 1, t2) && matchType(l, from + 2, t3);
}
public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4)
{
if (total - from + 1 != 4)
return false;
return matchType(l, from, t1) && matchType(l, from + 1, t2) && matchType(l, from + 2, t3) && matchType(l, from + 3, t4);
}
public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4, Type t5)
{
if (total - from + 1 != 5)
return false;
return matchType(l, from, t1) && matchType(l, from + 1, t2) && matchType(l, from + 2, t3) && matchType(l, from + 3, t4)
&& matchType(l, from + 4, t5);
}
public static bool matchType
(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4, Type t5,Type t6)
{
if (total - from + 1 != 6)
return false;
return matchType(l, from, t1) && matchType(l, from + 1, t2) && matchType(l, from + 2, t3) && matchType(l, from + 3, t4)
&& matchType(l, from + 4, t5)
&& matchType(l, from + 5, t6);
}
public static bool matchType
(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4, Type t5,Type t6,Type t7)
{
if (total - from + 1 != 7)
return false;
return matchType(l, from, t1) && matchType(l, from + 1, t2) && matchType(l, from + 2, t3) && matchType(l, from + 3, t4)
&& matchType(l, from + 4, t5)
&& matchType(l, from + 5, t6)
&& matchType(l, from + 6, t7);
}
public static bool matchType
(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4, Type t5,Type t6,Type t7,Type t8)
{
if (total - from + 1 != 8)
return false;
return matchType(l, from, t1) && matchType(l, from + 1, t2) && matchType(l, from + 2, t3) && matchType(l, from + 3, t4)
&& matchType(l, from + 4, t5)
&& matchType(l, from + 5, t6)
&& matchType(l, from + 6, t7)
&& matchType(l, from + 7, t8);
}
public static bool matchType
(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4, Type t5,Type t6,Type t7,Type t8,Type t9)
{
if (total - from + 1 != 9)
return false;
return matchType(l, from, t1) && matchType(l, from + 1, t2) && matchType(l, from + 2, t3) && matchType(l, from + 3, t4)
&& matchType(l, from + 4, t5)
&& matchType(l, from + 5, t6)
&& matchType(l, from + 6, t7)
&& matchType(l, from + 7, t8)
&& matchType(l, from + 8, t9);
}
public static bool matchType
(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4, Type t5,Type t6,Type t7,Type t8,Type t9,Type t10)
{
if (total - from + 1 != 10)
return false;
return matchType(l, from, t1) && matchType(l, from + 1, t2) && matchType(l, from + 2, t3) && matchType(l, from + 3, t4)
&& matchType(l, from + 4, t5)
&& matchType(l, from + 5, t6)
&& matchType(l, from + 6, t7)
&& matchType(l, from + 7, t8)
&& matchType(l, from + 8, t9)
&& matchType(l, from + 9, t10);
}
public static bool matchType(IntPtr l, int total, int from, params Type[] t)
{
if (total - from + 1 != t.Length)
return false;
for (int i = 0; i < t.Length; ++i)
{
if (!matchType(l, from + i, t[i]))
return false;
}
return true;
}
public static bool matchType(IntPtr l, int total, int from, ParameterInfo[] pars)
{
if (total - from + 1 != pars.Length)
return false;
for (int n = 0; n < pars.Length; n++)
{
int p = n + from;
LuaTypes t = LuaDLL.lua_type(l, p);
if (!matchType(l, p, t, pars[n].ParameterType))
return false;
}
return true;
}
static public bool luaTypeCheck(IntPtr l, int p, string t)
{
return LuaDLL.luaS_checkluatype(l, p, t) != 0;
}
static LuaDelegate newDelegate(IntPtr l, int p)
{
LuaState state = LuaState.get(l);
LuaDLL.lua_pushvalue(l, p); // push function
int fref = LuaDLL.luaL_ref(l, LuaIndexes.LUA_REGISTRYINDEX); // new ref function
LuaDelegate f = new LuaDelegate(l, fref);
LuaDLL.lua_pushvalue(l, p);
LuaDLL.lua_pushinteger(l, fref);
LuaDLL.lua_settable(l, -3); // __LuaDelegate[func]= fref
state.delgateMap[fref] = f;
return f;
}
static public void removeDelgate(IntPtr l, int r)
{
LuaDLL.lua_getglobal(l, DelgateTable);
LuaDLL.lua_getref(l, r); // push key
LuaDLL.lua_pushnil(l); // push nil value
LuaDLL.lua_settable(l, -3); // remove function from __LuaDelegate table
LuaDLL.lua_pop(l, 1); // pop __LuaDelegate
}
static public object checkObj(IntPtr l, int p)
{
ObjectCache oc = ObjectCache.get(l);
return oc.get(l, p);
}
static public bool checkArray<T>(IntPtr l, int p, out T[] ta)
{
if (LuaDLL.lua_type(l, p) == LuaTypes.LUA_TTABLE)
{
int n = LuaDLL.lua_rawlen(l, p);
ta = new T[n];
for (int k = 0; k < n; k++)
{
LuaDLL.lua_rawgeti(l, p, k + 1);
object o = checkVar(l, -1);
Type fromT = o.GetType();
Type toT = typeof(T);
if (toT.IsAssignableFrom(fromT))
{
ta[k] = (T)o;
}
else
{
ta[k] = (T)Convert.ChangeType(o, typeof(T));
}
LuaDLL.lua_pop(l, 1);
}
return true;
}
else
{
Array array = checkObj(l, p) as Array;
ta = array as T[];
return ta != null;
}
}
static public bool checkParams<T>(IntPtr l, int p, out T[] pars) where T:class
{
int top = LuaDLL.lua_gettop(l);
if (top - p >= 0)
{
pars = new T[top - p + 1];
for (int n = p, k = 0; n <= top; n++, k++)
{
checkType(l, n, out pars[k]);
}
return true;
}
pars = new T[0];
return true;
}
static public bool checkValueParams<T>(IntPtr l, int p, out T[] pars) where T : struct
{
int top = LuaDLL.lua_gettop(l);
if (top - p >= 0)
{
pars = new T[top - p + 1];
for (int n = p, k = 0; n <= top; n++, k++)
{
checkValueType(l, n, out pars[k]);
}
return true;
}
pars = new T[0];
return true;
}
static public bool checkParams(IntPtr l, int p, out float[] pars)
{
int top = LuaDLL.lua_gettop(l);
if (top - p >= 0)
{
pars = new float[top - p + 1];
for (int n = p, k = 0; n <= top; n++, k++)
{
checkType(l, n, out pars[k]);
}
return true;
}
pars = new float[0];
return true;
}
static public bool checkParams(IntPtr l, int p, out int[] pars)
{
int top = LuaDLL.lua_gettop(l);
if (top - p >= 0)
{
pars = new int[top - p + 1];
for (int n = p, k = 0; n <= top; n++, k++)
{
checkType(l, n, out pars[k]);
}
return true;
}
pars = new int[0];
return true;
}
static public bool checkParams(IntPtr l, int p, out string[] pars)
{
int top = LuaDLL.lua_gettop(l);
if (top - p >= 0)
{
pars = new string[top - p + 1];
for (int n = p, k = 0; n <= top; n++, k++)
{
checkType(l, n, out pars[k]);
}
return true;
}
pars = new string[0];
return true;
}
static public bool checkParams(IntPtr l, int p, out char[] pars)
{
LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TSTRING);
string s;
checkType(l, p, out s);
pars = s.ToCharArray();
return true;
}
static public object checkVar(IntPtr l, int p, Type t)
{
object obj = checkVar(l, p);
try
{
if (t.IsEnum)
{
// double to int
var number = Convert.ChangeType(obj, typeof(int));
return Enum.ToObject(t, number);
}
object convertObj = null;
if(obj!=null) {
if (t.IsInstanceOfType(obj))
{
convertObj = obj; // if t is parent of obj, ignore change type
}
else
{
convertObj = Convert.ChangeType(obj, t);
}
}
return obj == null ? null : convertObj;
}
catch(Exception e) {
throw new Exception(string.Format("parameter {0} expected {1}, got {2}, exception: {3}", p, t.Name, obj == null ? "null" : obj.GetType().Name, e.Message));
}
}
static public object checkVar(IntPtr l, int p)
{
LuaTypes type = LuaDLL.lua_type(l, p);
switch (type)
{
case LuaTypes.LUA_TNUMBER:
{
return LuaDLL.lua_tonumber(l, p);
}
case LuaTypes.LUA_TSTRING:
{
return LuaDLL.lua_tostring(l, p);
}
case LuaTypes.LUA_TBOOLEAN:
{
return LuaDLL.lua_toboolean(l, p);
}
case LuaTypes.LUA_TFUNCTION:
{
LuaFunction v;
LuaObject.checkType(l, p, out v);
return v;
}
case LuaTypes.LUA_TTABLE:
{
if (isLuaValueType(l, p))
{
#if !SLUA_STANDALONE
if (luaTypeCheck(l, p, "Vector2"))
{
Vector2 v;
checkType(l, p, out v);
return v;
}
else if (luaTypeCheck(l, p, "Vector3"))
{
Vector3 v;
checkType(l, p, out v);
return v;
}
else if (luaTypeCheck(l, p, "Vector4"))
{
Vector4 v;
checkType(l, p, out v);
return v;
}
else if (luaTypeCheck(l, p, "Quaternion"))
{
Quaternion v;
checkType(l, p, out v);
return v;
}
else if (luaTypeCheck(l, p, "Color"))
{
Color c;
checkType(l, p, out c);
return c;
}
#endif
Logger.LogError("unknown lua value type");
return null;
}
else if (isLuaClass(l, p))
{
return checkObj(l, p);
}
else
{
LuaTable v;
checkType(l,p,out v);
return v;
}
}
case LuaTypes.LUA_TUSERDATA:
return LuaObject.checkObj(l, p);
case LuaTypes.LUA_TTHREAD:
{
LuaThread lt;
LuaObject.checkType(l, p, out lt);
return lt;
}
default:
return null;
}
}
public static void pushValue(IntPtr l, object o)
{
pushVar(l, o);
}
public static void pushValue(IntPtr l, Array a)
{
pushObject(l, a);
}
public static void pushVar(IntPtr l, object o)
{
if (o == null)
{
LuaDLL.lua_pushnil(l);
return;
}
Type t = o.GetType();
LuaState.PushVarDelegate push;
LuaState ls = LuaState.get(l);
if (ls.tryGetTypePusher(t, out push))
push(l, o);
else if (t.IsEnum)
{
pushEnum(l, Convert.ToInt32(o));
}
else if (t.IsArray)
pushObject(l, (Array)o);
else
pushObject(l, o);
}
public static T checkSelf<T>(IntPtr l)
{
object o = checkObj(l, 1);
if (o != null)
{
return (T)o;
}
throw new Exception("arg 1 expect self, but get null");
}
public static object checkSelf(IntPtr l)
{
object o = checkObj(l, 1);
if (o == null)
throw new Exception("expect self, but get null");
return o;
}
public static void setBack(IntPtr l, object o)
{
ObjectCache t = ObjectCache.get(l);
t.setBack(l, 1, o);
}
#if !SLUA_STANDALONE
public static void setBack(IntPtr l, Vector3 v)
{
LuaDLL.luaS_setDataVec(l, 1, v.x, v.y, v.z, float.NaN);
}
public static void setBack(IntPtr l, Vector2 v)
{
LuaDLL.luaS_setDataVec(l, 1, v.x, v.y, float.NaN, float.NaN);
}
public static void setBack(IntPtr l, Vector4 v)
{
LuaDLL.luaS_setDataVec(l, 1, v.x, v.y, v.z, v.w);
}
public static void setBack(IntPtr l, Quaternion v)
{
LuaDLL.luaS_setDataVec(l, 1, v.x, v.y, v.z, v.w);
}
public static void setBack(IntPtr l, Color v)
{
LuaDLL.luaS_setDataVec(l, 1, v.r, v.g, v.b, v.a);
}
#endif
public static int extractFunction(IntPtr l, int p)
{
int op = 0;
LuaTypes t = LuaDLL.lua_type(l, p);
switch (t)
{
case LuaTypes.LUA_TNIL:
case LuaTypes.LUA_TUSERDATA:
op = 0;
break;
case LuaTypes.LUA_TTABLE:
LuaDLL.lua_rawgeti(l, p, 1);
LuaDLL.lua_pushstring(l, "+=");
if (LuaDLL.lua_rawequal(l, -1, -2) == 1)
op = 1;
else
op = 2;
LuaDLL.lua_pop(l, 2);
LuaDLL.lua_rawgeti(l, p, 2);
break;
case LuaTypes.LUA_TFUNCTION:
LuaDLL.lua_pushvalue(l, p);
break;
default:
throw new Exception("expect valid Delegate");
}
return op;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int noConstructor(IntPtr l)
{
return error(l, "Can't new this object");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int typeToString(IntPtr l)
{
LuaDLL.lua_pushstring (l, "__fullname");
LuaDLL.lua_rawget (l, -2);
return 1;
}
static public int error(IntPtr l,Exception e)
{
LuaDLL.lua_pushboolean(l, false);
LuaDLL.lua_pushstring(l, e.ToString());
return 2;
}
static public int error(IntPtr l, string err)
{
LuaDLL.lua_pushboolean(l, false);
LuaDLL.lua_pushstring(l, err);
return 2;
}
static public int error(IntPtr l, string err, params object[] args)
{
err = string.Format(err, args);
LuaDLL.lua_pushboolean(l, false);
LuaDLL.lua_pushstring(l, err);
return 2;
}
static public int ok(IntPtr l)
{
LuaDLL.lua_pushboolean(l, true);
return 1;
}
static public int ok(IntPtr l, int retCount)
{
LuaDLL.lua_pushboolean(l, true);
LuaDLL.lua_insert(l, -(retCount + 1));
return retCount + 1;
}
static public void assert(bool cond,string err) {
if(!cond) throw new Exception(err);
}
/// <summary>
/// Change Type, alternative for Convert.ChangeType, but has exception handling
/// change fail, return origin value directly, useful for some LuaVarObject value assign
/// </summary>
/// <param name="obj"></param>
/// <param name="t"></param>
/// <returns></returns>
static public object changeType(object obj, Type t)
{
if (t == typeof (object)) return obj;
if (obj.GetType() == t) return obj;
try
{
return Convert.ChangeType(obj, t);
}
catch
{
return obj;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Gac.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Framework
{
using System;
using System.Globalization;
using System.Management;
using Microsoft.Build.Framework;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>AddAssembly</i> (<b>Required: </b> AssemblyPath <b>Optional: </b>MachineName, RemoteAssemblyPath, UserName, UserPassword)</para>
/// <para><i>CheckExists</i> (<b>Required: </b> AssemblyName <b>Optional: </b>MachineName)</para>
/// <para><i>RemoveAssembly</i> (<b>Required: </b> AssemblyName <b>Optional: </b>MachineName, UserName, UserPassword)</para>
/// <para><b>Remote Execution Support:</b> Partial (not for CheckExists)</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <!-- Add an assembly to the local cache -->
/// <MSBuild.ExtensionPack.Framework.Gac TaskAction="AddAssembly" AssemblyPath="c:\AnAssembly.dll"/>
/// <!-- Remove an assembly from the local cache. -->
/// <MSBuild.ExtensionPack.Framework.Gac TaskAction="RemoveAssembly" AssemblyName="AnAssembly Version=3.0.8000.0,PublicKeyToken=f251491100750aea"/>
/// <!-- Add an assembly to a remote machine cache. Note that gacutil.exe must exist on the remote server and be in it's Path environment variable -->
/// <MSBuild.ExtensionPack.Framework.Gac TaskAction="AddAssembly" AssemblyPath="c:\aaa.dll" RemoteAssemblyPath="\\ANEWVM\c$\apath\aaa.dll" MachineName="ANEWVM" UserName="Administrator" UserPassword="O123"/>
/// <!-- Remove an assembly from a remote machine cache -->
/// <MSBuild.ExtensionPack.Framework.Gac TaskAction="RemoveAssembly" AssemblyName="aaa, Version=1.0.0.0,PublicKeyToken=e24a7ed7109b7e39" MachineName="ANEWVM" UserName="Admministrator" UserPassword="O123"/>
/// <!-- Check whether an assembly exists in the local cache -->
/// <MSBuild.ExtensionPack.Framework.Gac TaskAction="CheckExists" AssemblyName="aaa, Version=1.0.0.0,PublicKeyToken=e24a7ed7109b7e39">
/// <Output PropertyName="Exists2" TaskParameter="Exists"/>
/// </MSBuild.ExtensionPack.Framework.Gac>
/// <Message Text="Exists: $(Exists2)"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class Gac : BaseTask
{
/// <summary>
/// Sets the remote path of the assembly. Note that gacutil.exe must exist on the remote server and be in it's Path environment variable
/// </summary>
public string RemoteAssemblyPath { get; set; }
/// <summary>
/// Sets the path to the assembly to be added the GAC
/// </summary>
public ITaskItem AssemblyPath { get; set; }
/// <summary>
/// Sets the name of the assembly.
/// </summary>
public string AssemblyName { get; set; }
/// <summary>
/// Set to True to force the file to be gacc'ed (overwrite any existing)
/// </summary>
public bool Force { get; set; }
/// <summary>
/// Gets whether the assembly exists in the GAC
/// </summary>
[Output]
public bool Exists { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
switch (this.TaskAction)
{
case "AddAssembly":
this.AddAssembly();
break;
case "CheckExists":
this.CheckExists();
break;
case "RemoveAssembly":
this.RemoveAssembly();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
/// <summary>
/// Gets the IAssemblyCache interface.
/// </summary>
/// <returns>
/// An IAssemblyCache interface.
/// </returns>
private NativeMethods.IAssemblyCache GetIAssemblyCache()
{
// Get the IAssemblyCache interface
NativeMethods.IAssemblyCache assemblyCache;
int result = NativeMethods.CreateAssemblyCache(out assemblyCache, 0);
// If the result is not zero throw an exception
if (result != 0)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Failed to get the IAssemblyCache interface. Result Code: {0}", result));
return null;
}
// Return the IAssemblyCache interface
return assemblyCache;
}
private void Install(string path, bool force)
{
// Get the IAssemblyCache interface
NativeMethods.IAssemblyCache assemblyCache = this.GetIAssemblyCache();
// Set the flag depending on the value of force
int flag = force ? 2 : 1;
// Install the assembly in the cache
int result = assemblyCache.InstallAssembly(flag, path, IntPtr.Zero);
// If the result is not zero throw an exception
if (result != 0)
{
Log.LogError(string.Format(CultureInfo.CurrentCulture, "Failed to install assembly into the global assembly cache. Result Code: {0}", result));
}
}
private void Uninstall(string name)
{
// Get the IAssemblyCache interface
NativeMethods.IAssemblyCache assemblyCache = this.GetIAssemblyCache();
// Uninstall the assembly from the cache
int disposition;
int result = assemblyCache.UninstallAssembly(0, name, IntPtr.Zero, out disposition);
// If the result is not zero or the disposition is not 1 then throw an exception
if (result != 0)
{
// If result is not 0 then something happened. Check the value of disposition to see if we should throw an error.
// Determined the values of the codes returned in disposition from
switch (disposition)
{
case 1:
// Assembly was removed from GAC.
break;
case 2:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "An application is using: {0} so it could not be uninstalled.", name));
return;
case 3:
// Assembly is not in the assembly. Don't throw an error, just proceed to install it.
break;
case 4:
// Not used.
break;
case 5:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "{0} was not uninstalled from the GAC because another reference exists to it.", name));
return;
case 6:
// Problem where a reference doesn't exist to the pointer. We aren't using the pointer so this shouldn't be a problem.
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Failed to uninstall: {0} from the GAC.", name));
return;
}
}
}
private void CheckExists()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking if Assembly: {0} exists", this.AssemblyName));
this.Exists = this.GetIAssemblyCache().QueryAssemblyInfo(0, this.AssemblyName, IntPtr.Zero) == 0;
}
private void RemoveAssembly()
{
if (string.Compare(this.MachineName, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0)
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "UnGAC Assembly: {0}", this.AssemblyName));
this.Uninstall(this.AssemblyName);
}
else
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "UnGAC Assembly: {0} on Remote Server: {1}", this.AssemblyName, this.MachineName));
this.GetManagementScope(@"\root\cimv2");
using (ManagementClass m = new ManagementClass(this.Scope, new ManagementPath("Win32_Process"), new ObjectGetOptions(null, System.TimeSpan.MaxValue, true)))
{
ManagementBaseObject methodParameters = m.GetMethodParameters("Create");
methodParameters["CommandLine"] = @"gacutil.exe /u " + "\"" + this.AssemblyName + "\"";
ManagementBaseObject outParams = m.InvokeMethod("Create", methodParameters, null);
if (outParams != null)
{
this.LogTaskMessage(MessageImportance.Low, "Process returned: " + outParams["returnValue"]);
this.LogTaskMessage(MessageImportance.Low, "Process ID: " + outParams["processId"]);
}
else
{
this.Log.LogError("Remote Remove returned null");
}
}
}
}
private void AddAssembly()
{
if (System.IO.File.Exists(this.AssemblyPath.GetMetadata("FullPath")) == false)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "The AssemblyPath was not found: {0}", this.AssemblyPath.GetMetadata("FullPath")));
}
else
{
if (string.Compare(this.MachineName, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0)
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "GAC Assembly: {0}", this.AssemblyPath.GetMetadata("FullPath")));
this.Install(this.AssemblyPath.GetMetadata("FullPath"), this.Force);
}
else
{
if (string.IsNullOrEmpty(this.RemoteAssemblyPath))
{
this.Log.LogError("RemoteAssemblyPath is Required");
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "GAC Assembly: {0} on Remote Server: {1}", this.RemoteAssemblyPath, this.MachineName));
// the assembly needs to be copied to the remote server for gaccing.
if (System.IO.File.Exists(this.RemoteAssemblyPath))
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Deleting old Remote Assembly: {0}", this.RemoteAssemblyPath));
System.IO.File.Delete(this.RemoteAssemblyPath);
}
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Copying Assembly from: {0} to: {1}", this.AssemblyPath.GetMetadata("FullPath"), this.RemoteAssemblyPath));
System.IO.File.Copy(this.AssemblyPath.GetMetadata("FullPath"), this.RemoteAssemblyPath);
this.GetManagementScope(@"\root\cimv2");
using (ManagementClass m = new ManagementClass(this.Scope, new ManagementPath("Win32_Process"), new ObjectGetOptions(null, System.TimeSpan.MaxValue, true)))
{
ManagementBaseObject methodParameters = m.GetMethodParameters("Create");
methodParameters["CommandLine"] = @"gacutil.exe /i " + "\"" + this.RemoteAssemblyPath + "\"";
ManagementBaseObject outParams = m.InvokeMethod("Create", methodParameters, null);
if (outParams != null)
{
if (int.Parse(outParams["returnValue"].ToString(), CultureInfo.InvariantCulture) != 0)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Remote AddAssembly returned non-zero returnValue: {0}", outParams["returnValue"]));
return;
}
this.LogTaskMessage(MessageImportance.Low, "Process ReturnValue: " + outParams["returnValue"]);
this.LogTaskMessage(MessageImportance.Low, "Process ID: " + outParams["processId"]);
}
else
{
Log.LogError("Remote Create returned null");
}
}
}
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainViewModel.cs" company="Helix Toolkit">
// Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CustomShaderDemo
{
using System.Linq;
using System.Windows.Media;
using DemoCore;
using HelixToolkit.Wpf;
using HelixToolkit.Wpf.SharpDX;
using HelixToolkit.Wpf.SharpDX.Core;
using SharpDX;
using Media3D = System.Windows.Media.Media3D;
using Color = System.Windows.Media.Color;
using Point3D = System.Windows.Media.Media3D.Point3D;
using Vector3D = System.Windows.Media.Media3D.Vector3D;
using System.Collections.Generic;
using System.Windows.Input;
using System;
using SharpDX.Direct3D11;
public class MainViewModel : BaseViewModel
{
public MeshGeometry3D Model { get; private set; }
public MeshGeometry3D SphereModel { get; private set; }
public LineGeometry3D AxisModel { get; private set; }
public BillboardText3D AxisLabel { private set; get; }
public PhongMaterial ModelMaterial { get; private set; } = PhongMaterials.White;
public PhongMaterial SphereMaterial { private set; get; } = PhongMaterials.Copper;
private Color startColor;
/// <summary>
/// Gets or sets the StartColor.
/// </summary>
/// <value>
/// StartColor
/// </value>
public Color StartColor
{
set
{
if (SetValue(ref startColor, value))
{
ColorGradient = new Color4Collection(GetGradients(startColor.ToColor4(), midColor.ToColor4(), endColor.ToColor4(), 100));
}
}
get { return startColor; }
}
private Color midColor;
/// <summary>
/// Gets or sets the StartColor.
/// </summary>
/// <value>
/// StartColor
/// </value>
public Color MidColor
{
set
{
if (SetValue(ref midColor, value))
{
ColorGradient = new Color4Collection(GetGradients(startColor.ToColor4(), midColor.ToColor4(), endColor.ToColor4(), 100));
}
}
get { return midColor; }
}
private Color endColor;
/// <summary>
/// Gets or sets the StartColor.
/// </summary>
/// <value>
/// StartColor
/// </value>
public Color EndColor
{
set
{
if (SetValue(ref endColor, value))
{
ColorGradient = new Color4Collection(GetGradients(startColor.ToColor4(), midColor.ToColor4(), endColor.ToColor4(), 100));
}
}
get { return endColor; }
}
private Color4Collection colorGradient;
public Color4Collection ColorGradient
{
private set
{
SetValue(ref colorGradient, value);
}
get { return colorGradient; }
}
private FillMode fillMode = FillMode.Solid;
public FillMode FillMode
{
set
{
SetValue(ref fillMode, value);
}
get { return fillMode; }
}
private bool showWireframe = false;
public bool ShowWireframe
{
set
{
if(SetValue(ref showWireframe, value))
{
FillMode = value ? FillMode.Wireframe : FillMode.Solid;
}
}
get { return showWireframe; }
}
private int Width = 100;
private int Height = 100;
public ICommand GenerateNoiseCommand { private set; get; }
public MainViewModel()
{
// titles
Title = "Simple Demo";
SubTitle = "WPF & SharpDX";
// camera setup
Camera = new PerspectiveCamera {
Position = new Point3D(-6, 8, 23),
LookDirection = new Vector3D(11, -4, -23),
UpDirection = new Vector3D(0, 1, 0),
FarPlaneDistance = 5000
};
EffectsManager = new CustomEffectsManager();
RenderTechnique = EffectsManager[CustomShaderNames.NoiseMesh];
var builder = new MeshBuilder(true);
Vector3[] points = new Vector3[Width*Height];
for(int i=0; i<Width; ++i)
{
for(int j=0; j<Height; ++j)
{
points[i * Width + j] = new Vector3(i / 10f, 0, j / 10f);
}
}
builder.AddRectangularMesh(points, Width);
Model = builder.ToMesh();
for(int i=0; i<Model.Normals.Count; ++i)
{
Model.Normals[i] = new Vector3(0, Math.Abs(Model.Normals[i].Y), 0);
}
StartColor = Colors.Blue;
MidColor = Colors.Green;
EndColor = Colors.Red;
var lineBuilder = new LineBuilder();
lineBuilder.AddLine(new Vector3(0, 0, 0), new Vector3(10, 0, 0));
lineBuilder.AddLine(new Vector3(0, 0, 0), new Vector3(0, 10, 0));
lineBuilder.AddLine(new Vector3(0, 0, 0), new Vector3(0, 0, 10));
AxisModel = lineBuilder.ToLineGeometry3D();
AxisModel.Colors = new Color4Collection(AxisModel.Positions.Count);
AxisModel.Colors.Add(Colors.Red.ToColor4());
AxisModel.Colors.Add(Colors.Red.ToColor4());
AxisModel.Colors.Add(Colors.Green.ToColor4());
AxisModel.Colors.Add(Colors.Green.ToColor4());
AxisModel.Colors.Add(Colors.Blue.ToColor4());
AxisModel.Colors.Add(Colors.Blue.ToColor4());
AxisLabel = new BillboardText3D();
AxisLabel.TextInfo.Add(new TextInfo() { Origin = new Vector3(11, 0, 0), Text = "X", Foreground = Colors.Red.ToColor4() });
AxisLabel.TextInfo.Add(new TextInfo() { Origin = new Vector3(0, 11, 0), Text = "Y", Foreground = Colors.Green.ToColor4() });
AxisLabel.TextInfo.Add(new TextInfo() { Origin = new Vector3(0, 0, 11), Text = "Z", Foreground = Colors.Blue.ToColor4() });
builder = new MeshBuilder(true);
builder.AddSphere(new Vector3(-15, 0, 0), 5);
SphereModel = builder.ToMesh();
GenerateNoiseCommand = new RelayCommand((o) => { CreatePerlinNoise(); });
CreatePerlinNoise();
}
public static IEnumerable<Color4> GetGradients(Color4 start, Color4 mid, Color4 end, int steps)
{
return GetGradients(start, mid, steps / 2).Concat(GetGradients(mid, end, steps / 2));
}
public static IEnumerable<Color4> GetGradients(Color4 start, Color4 end, int steps)
{
float stepA = ((end.Alpha - start.Alpha) / (steps - 1));
float stepR = ((end.Red - start.Red) / (steps - 1));
float stepG = ((end.Green - start.Green) / (steps - 1));
float stepB = ((end.Blue - start.Blue) / (steps - 1));
for (int i = 0; i < steps; i++)
{
yield return new Color4((start.Red + (stepR * i)),
(start.Green + (stepG * i)),
(start.Blue + (stepB * i)),
(start.Alpha + (stepA * i)));
}
}
private void CreatePerlinNoise()
{
float[] noise;
MathHelper.GenerateNoiseMap(Width, Height, 8, out noise);
Vector2Collection collection = new Vector2Collection(Width * Height);
for(int i=0; i<Width; ++i)
{
for(int j=0; j<Height; ++j)
{
collection.Add(new Vector2(Math.Abs(noise[Width * i + j]), 0));
}
}
Model.TextureCoordinates = collection;
}
}
}
| |
/*
* Copyright 2012-2015 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more contributor
* license agreements.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using System;
using System.Collections.Generic;
using Aerospike.Client;
namespace Aerospike.Demo
{
public class Batch : SyncExample
{
public Batch(Console console) : base(console)
{
}
/// <summary>
/// Batch multiple gets in one call to the server.
/// </summary>
public override void RunExample(AerospikeClient client, Arguments args)
{
string keyPrefix = "batchkey";
string valuePrefix = "batchvalue";
string binName = args.GetBinName("batchbin");
int size = 8;
WriteRecords(client, args, keyPrefix, binName, valuePrefix, size);
BatchExists(client, args, keyPrefix, size);
BatchReads(client, args, keyPrefix, binName, size);
BatchReadHeaders(client, args, keyPrefix, size);
try
{
BatchReadComplex(client, args, keyPrefix, binName);
}
catch (Exception ex)
{
// Server version may not yet support new batch protocol.
Node[] nodes = client.Nodes;
foreach (Node node in nodes)
{
if (!node.HasBatchIndex)
{
Log.Warn("Server does not support new batch protocol");
return;
}
}
throw ex;
}
}
/// <summary>
/// Write records individually.
/// </summary>
private void WriteRecords(AerospikeClient client, Arguments args, string keyPrefix, string binName, string valuePrefix, int size)
{
for (int i = 1; i <= size; i++)
{
Key key = new Key(args.ns, args.set, keyPrefix + i);
Bin bin = new Bin(binName, valuePrefix + i);
console.Info("Put: namespace={0} set={1} key={2} bin={3} value={4}",
key.ns, key.setName, key.userKey, bin.name, bin.value);
client.Put(args.writePolicy, key, bin);
}
}
/// <summary>
/// Check existence of records in one batch.
/// </summary>
private void BatchExists(AerospikeClient client, Arguments args, string keyPrefix, int size)
{
// Batch into one call.
Key[] keys = new Key[size];
for (int i = 0; i < size; i++)
{
keys[i] = new Key(args.ns, args.set, keyPrefix + (i + 1));
}
bool[] existsArray = client.Exists(null, keys);
for (int i = 0; i < existsArray.Length; i++)
{
Key key = keys[i];
bool exists = existsArray[i];
console.Info("Record: namespace={0} set={1} key={2} exists={3}",
key.ns, key.setName, key.userKey, exists);
}
}
/// <summary>
/// Read records in one batch.
/// </summary>
private void BatchReads(AerospikeClient client, Arguments args, string keyPrefix, string binName, int size)
{
// Batch gets into one call.
Key[] keys = new Key[size];
for (int i = 0; i < size; i++)
{
keys[i] = new Key(args.ns, args.set, keyPrefix + (i + 1));
}
Record[] records = client.Get(null, keys, binName);
for (int i = 0; i < records.Length; i++)
{
Key key = keys[i];
Record record = records[i];
Log.Level level = Log.Level.ERROR;
object value = null;
if (record != null)
{
level = Log.Level.INFO;
value = record.GetValue(binName);
}
console.Write(level, "Record: namespace={0} set={1} key={2} bin={3} value={4}",
key.ns, key.setName, key.userKey, binName, value);
}
if (records.Length != size)
{
console.Error("Record size mismatch. Expected {0}. Received {1}.", size, records.Length);
}
}
/// <summary>
/// Read record header data in one batch.
/// </summary>
private void BatchReadHeaders(AerospikeClient client, Arguments args, string keyPrefix, int size)
{
// Batch gets into one call.
Key[] keys = new Key[size];
for (int i = 0; i < size; i++)
{
keys[i] = new Key(args.ns, args.set, keyPrefix + (i + 1));
}
Record[] records = client.GetHeader(null, keys);
for (int i = 0; i < records.Length; i++)
{
Key key = keys[i];
Record record = records[i];
Log.Level level = Log.Level.ERROR;
int generation = 0;
int expiration = 0;
if (record != null && (record.generation > 0 || record.expiration > 0))
{
level = Log.Level.INFO;
generation = record.generation;
expiration = record.expiration;
}
console.Write(level, "Record: namespace={0} set={1} key={2} generation={3} expiration={4}",
key.ns, key.setName, key.userKey, generation, expiration);
}
if (records.Length != size)
{
console.Error("Record size mismatch. Expected %d. Received %d.", size, records.Length);
}
}
/// <summary>
/// Read records with varying namespaces, bin names and read types in one batch.
/// This requires Aerospike Server version >= 3.6.0.
/// </summary>
private void BatchReadComplex(AerospikeClient client, Arguments args, string keyPrefix, string binName)
{
// Batch gets into one call.
// Batch allows multiple namespaces in one call, but example test environment may only have one namespace.
string[] bins = new string[] {binName};
List<BatchRead> records = new List<BatchRead>();
records.Add(new BatchRead(new Key(args.ns, args.set, keyPrefix + 1), bins));
records.Add(new BatchRead(new Key(args.ns, args.set, keyPrefix + 2), true));
records.Add(new BatchRead(new Key(args.ns, args.set, keyPrefix + 3), true));
records.Add(new BatchRead(new Key(args.ns, args.set, keyPrefix + 4), false));
records.Add(new BatchRead(new Key(args.ns, args.set, keyPrefix + 5), true));
records.Add(new BatchRead(new Key(args.ns, args.set, keyPrefix + 6), true));
records.Add(new BatchRead(new Key(args.ns, args.set, keyPrefix + 7), bins));
// This record should be found, but the requested bin will not be found.
records.Add(new BatchRead(new Key(args.ns, args.set, keyPrefix + 8), new string[] { "binnotfound" }));
// This record should not be found.
records.Add(new BatchRead(new Key(args.ns, args.set, "keynotfound"), bins));
// Execute batch.
client.Get(null, records);
// Show results.
int found = 0;
foreach (BatchRead record in records)
{
Key key = record.key;
Record rec = record.record;
if (rec != null)
{
found++;
console.Info("Record: ns={0} set={1} key={2} bin={3} value={4}",
key.ns, key.setName, key.userKey, binName, rec.GetValue(binName));
}
else
{
console.Info("Record not found: ns={0} set={1} key={2} bin={3}",
key.ns, key.setName, key.userKey, binName);
}
}
if (found != 8)
{
console.Error("Records found mismatch. Expected %d. Received %d.", 8, found);
}
}
}
}
| |
// <copyright file="HttpWebRequestActivitySourceTests.netfx.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>
#if NETFRAMEWORK
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using OpenTelemetry.Instrumentation.Http.Implementation;
using OpenTelemetry.Tests;
using OpenTelemetry.Trace;
using Xunit;
namespace OpenTelemetry.Instrumentation.Http.Tests
{
public class HttpWebRequestActivitySourceTests : IDisposable
{
private static bool validateBaggage;
private readonly IDisposable testServer;
private readonly string testServerHost;
private readonly int testServerPort;
private readonly string hostNameAndPort;
static HttpWebRequestActivitySourceTests()
{
HttpWebRequestInstrumentationOptions options = new HttpWebRequestInstrumentationOptions
{
Enrich = ActivityEnrichment,
};
HttpWebRequestActivitySource.Options = options;
// Need to touch something in HttpWebRequestActivitySource/Sdk to do the static injection.
GC.KeepAlive(HttpWebRequestActivitySource.Options);
_ = Sdk.SuppressInstrumentation;
}
public HttpWebRequestActivitySourceTests()
{
Assert.Null(Activity.Current);
Activity.DefaultIdFormat = ActivityIdFormat.W3C;
Activity.ForceDefaultIdFormat = false;
this.testServer = TestHttpServer.RunServer(
ctx => ProcessServerRequest(ctx),
out this.testServerHost,
out this.testServerPort);
this.hostNameAndPort = $"{this.testServerHost}:{this.testServerPort}";
void ProcessServerRequest(HttpListenerContext context)
{
string redirects = context.Request.QueryString["redirects"];
if (!string.IsNullOrWhiteSpace(redirects) && int.TryParse(redirects, out int parsedRedirects) && parsedRedirects > 0)
{
context.Response.Redirect(this.BuildRequestUrl(queryString: $"redirects={--parsedRedirects}"));
context.Response.OutputStream.Close();
return;
}
string responseContent;
if (context.Request.QueryString["skipRequestContent"] == null)
{
using StreamReader readStream = new StreamReader(context.Request.InputStream);
responseContent = readStream.ReadToEnd();
}
else
{
responseContent = $"{{\"Id\":\"{Guid.NewGuid()}\"}}";
}
string responseCode = context.Request.QueryString["responseCode"];
if (!string.IsNullOrWhiteSpace(responseCode))
{
context.Response.StatusCode = int.Parse(responseCode);
}
else
{
context.Response.StatusCode = 200;
}
if (context.Response.StatusCode != 204)
{
using StreamWriter writeStream = new StreamWriter(context.Response.OutputStream);
writeStream.Write(responseContent);
}
else
{
context.Response.OutputStream.Close();
}
}
}
public void Dispose()
{
this.testServer.Dispose();
}
/// <summary>
/// A simple test to make sure the Http Diagnostic Source is added into the list of DiagnosticListeners.
/// </summary>
[Fact]
public void TestHttpDiagnosticListenerIsRegistered()
{
bool listenerFound = false;
using ActivityListener activityListener = new ActivityListener
{
ShouldListenTo = activitySource =>
{
if (activitySource.Name == HttpWebRequestActivitySource.ActivitySourceName)
{
listenerFound = true;
return true;
}
return false;
},
};
ActivitySource.AddActivityListener(activityListener);
Assert.True(listenerFound, "The Http Diagnostic Listener didn't get added to the AllListeners list.");
}
/// <summary>
/// A simple test to make sure the Http Diagnostic Source is initialized properly after we subscribed to it, using
/// the subscribe overload with just the observer argument.
/// </summary>
[Fact]
public async Task TestReflectInitializationViaSubscription()
{
using var eventRecords = new ActivitySourceRecorder();
// Send a random Http request to generate some events
using (var client = new HttpClient())
{
(await client.GetAsync(this.BuildRequestUrl())).Dispose();
}
// Just make sure some events are written, to confirm we successfully subscribed to it.
// We should have exactly one Start and one Stop event
Assert.Equal(2, eventRecords.Records.Count);
}
/// <summary>
/// Test to make sure we get both request and response events.
/// </summary>
[Theory]
[InlineData("GET")]
[InlineData("POST")]
[InlineData("POST", "skipRequestContent=1")]
public async Task TestBasicReceiveAndResponseEvents(string method, string queryString = null)
{
var url = this.BuildRequestUrl(queryString: queryString);
using var eventRecords = new ActivitySourceRecorder();
// Send a random Http request to generate some events
using (var client = new HttpClient())
{
(method == "GET"
? await client.GetAsync(url)
: await client.PostAsync(url, new StringContent("hello world"))).Dispose();
}
// We should have exactly one Start and one Stop event
Assert.Equal(2, eventRecords.Records.Count);
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start"));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop"));
// Check to make sure: The first record must be a request, the next record must be a response.
Activity activity = AssertFirstEventWasStart(eventRecords);
VerifyActivityStartTags(this.hostNameAndPort, method, url, activity);
Assert.True(eventRecords.Records.TryDequeue(out var stopEvent));
Assert.Equal("Stop", stopEvent.Key);
VerifyActivityStopTags(200, activity);
}
[Theory]
[InlineData("GET")]
[InlineData("POST")]
public async Task TestBasicReceiveAndResponseEventsWithoutSampling(string method)
{
using var eventRecords = new ActivitySourceRecorder(activitySamplingResult: ActivitySamplingResult.None);
// Send a random Http request to generate some events
using (var client = new HttpClient())
{
(method == "GET"
? await client.GetAsync(this.BuildRequestUrl())
: await client.PostAsync(this.BuildRequestUrl(), new StringContent("hello world"))).Dispose();
}
// There should be no events because we turned off sampling.
Assert.Empty(eventRecords.Records);
}
[Theory]
[InlineData("GET", 0)]
[InlineData("GET", 1)]
[InlineData("GET", 2)]
[InlineData("GET", 3)]
[InlineData("POST", 0)]
[InlineData("POST", 1)]
[InlineData("POST", 2)]
[InlineData("POST", 3)]
public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int mode)
{
string url = this.BuildRequestUrl();
using var eventRecords = new ActivitySourceRecorder();
// Send a random Http request to generate some events
var webRequest = (HttpWebRequest)WebRequest.Create(url);
if (method == "POST")
{
webRequest.Method = method;
Stream stream = null;
switch (mode)
{
case 0:
stream = webRequest.GetRequestStream();
break;
case 1:
stream = await webRequest.GetRequestStreamAsync();
break;
case 2:
{
object state = new object();
using EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);
IAsyncResult asyncResult = webRequest.BeginGetRequestStream(
ar =>
{
Assert.Equal(state, ar.AsyncState);
handle.Set();
},
state);
stream = webRequest.EndGetRequestStream(asyncResult);
if (!handle.WaitOne(TimeSpan.FromSeconds(30)))
{
throw new InvalidOperationException();
}
handle.Dispose();
}
break;
case 3:
{
using EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);
object state = new object();
webRequest.BeginGetRequestStream(
ar =>
{
stream = webRequest.EndGetRequestStream(ar);
Assert.Equal(state, ar.AsyncState);
handle.Set();
},
state);
if (!handle.WaitOne(TimeSpan.FromSeconds(30)))
{
throw new InvalidOperationException();
}
handle.Dispose();
}
break;
default:
throw new NotSupportedException();
}
Assert.NotNull(stream);
using StreamWriter writer = new StreamWriter(stream);
writer.WriteLine("hello world");
}
WebResponse webResponse = null;
switch (mode)
{
case 0:
webResponse = webRequest.GetResponse();
break;
case 1:
webResponse = await webRequest.GetResponseAsync();
break;
case 2:
{
object state = new object();
using EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);
IAsyncResult asyncResult = webRequest.BeginGetResponse(
ar =>
{
Assert.Equal(state, ar.AsyncState);
handle.Set();
},
state);
webResponse = webRequest.EndGetResponse(asyncResult);
if (!handle.WaitOne(TimeSpan.FromSeconds(30)))
{
throw new InvalidOperationException();
}
handle.Dispose();
}
break;
case 3:
{
using EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);
object state = new object();
webRequest.BeginGetResponse(
ar =>
{
webResponse = webRequest.EndGetResponse(ar);
Assert.Equal(state, ar.AsyncState);
handle.Set();
},
state);
if (!handle.WaitOne(TimeSpan.FromSeconds(30)))
{
throw new InvalidOperationException();
}
handle.Dispose();
}
break;
default:
throw new NotSupportedException();
}
Assert.NotNull(webResponse);
using StreamReader reader = new StreamReader(webResponse.GetResponseStream());
reader.ReadToEnd(); // Make sure response is not disposed.
// We should have exactly one Start and one Stop event
Assert.Equal(2, eventRecords.Records.Count);
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start"));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop"));
// Check to make sure: The first record must be a request, the next record must be a response.
Activity activity = AssertFirstEventWasStart(eventRecords);
VerifyActivityStartTags(this.hostNameAndPort, method, url, activity);
Assert.True(eventRecords.Records.TryDequeue(out var stopEvent));
Assert.Equal("Stop", stopEvent.Key);
VerifyActivityStopTags(200, activity);
}
[Fact]
public async Task TestTraceStateAndBaggage()
{
try
{
using var eventRecords = new ActivitySourceRecorder();
var parent = new Activity("w3c activity");
parent.SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom());
parent.TraceStateString = "some=state";
parent.Start();
Baggage.SetBaggage("k", "v");
// Send a random Http request to generate some events
using (var client = new HttpClient())
{
(await client.GetAsync(this.BuildRequestUrl())).Dispose();
}
parent.Stop();
Assert.Equal(2, eventRecords.Records.Count());
// Check to make sure: The first record must be a request, the next record must be a response.
_ = AssertFirstEventWasStart(eventRecords);
}
finally
{
this.CleanUpActivity();
}
}
[Theory]
[InlineData("GET")]
[InlineData("POST")]
public async Task DoNotInjectTraceParentWhenPresent(string method)
{
try
{
using var eventRecords = new ActivitySourceRecorder();
// Send a random Http request to generate some events
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Get, this.BuildRequestUrl()))
{
request.Headers.Add("traceparent", "00-abcdef0123456789abcdef0123456789-abcdef0123456789-01");
if (method == "GET")
{
request.Method = HttpMethod.Get;
}
else
{
request.Method = HttpMethod.Post;
request.Content = new StringContent("hello world");
}
(await client.SendAsync(request)).Dispose();
}
// No events are sent.
Assert.Empty(eventRecords.Records);
}
finally
{
this.CleanUpActivity();
}
}
/// <summary>
/// Test to make sure we get both request and response events.
/// </summary>
[Theory]
[InlineData("GET")]
[InlineData("POST")]
public async Task TestResponseWithoutContentEvents(string method)
{
string url = this.BuildRequestUrl(queryString: "responseCode=204");
using var eventRecords = new ActivitySourceRecorder();
// Send a random Http request to generate some events
using (var client = new HttpClient())
{
using HttpResponseMessage response = method == "GET"
? await client.GetAsync(url)
: await client.PostAsync(url, new StringContent("hello world"));
}
// We should have exactly one Start and one Stop event
Assert.Equal(2, eventRecords.Records.Count);
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start"));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop"));
// Check to make sure: The first record must be a request, the next record must be a response.
Activity activity = AssertFirstEventWasStart(eventRecords);
VerifyActivityStartTags(this.hostNameAndPort, method, url, activity);
Assert.True(eventRecords.Records.TryDequeue(out var stopEvent));
Assert.Equal("Stop", stopEvent.Key);
VerifyActivityStopTags(204, activity);
}
/// <summary>
/// Test that if request is redirected, it gets only one Start and one Stop event.
/// </summary>
[Theory]
[InlineData("GET")]
[InlineData("POST")]
public async Task TestRedirectedRequest(string method)
{
using var eventRecords = new ActivitySourceRecorder();
using (var client = new HttpClient())
{
using HttpResponseMessage response = method == "GET"
? await client.GetAsync(this.BuildRequestUrl(queryString: "redirects=10"))
: await client.PostAsync(this.BuildRequestUrl(queryString: "redirects=10"), new StringContent("hello world"));
}
// We should have exactly one Start and one Stop event
Assert.Equal(2, eventRecords.Records.Count());
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start"));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop"));
}
/// <summary>
/// Test exception in request processing: exception should have expected type/status and now be swallowed by reflection hook.
/// </summary>
[Theory]
[InlineData("GET")]
[InlineData("POST")]
public async Task TestRequestWithException(string method)
{
string url = method == "GET"
? $"http://{Guid.NewGuid()}.com"
: $"http://{Guid.NewGuid()}.com";
using var eventRecords = new ActivitySourceRecorder();
var ex = await Assert.ThrowsAsync<HttpRequestException>(() =>
{
return method == "GET"
? new HttpClient().GetAsync(url)
: new HttpClient().PostAsync(url, new StringContent("hello world"));
});
// check that request failed because of the wrong domain name and not because of reflection
var webException = (WebException)ex.InnerException;
Assert.NotNull(webException);
Assert.True(webException.Status == WebExceptionStatus.NameResolutionFailure);
// We should have one Start event and one Stop event with an exception.
Assert.Equal(2, eventRecords.Records.Count());
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start"));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop"));
// Check to make sure: The first record must be a request, the next record must be an exception.
Activity activity = AssertFirstEventWasStart(eventRecords);
VerifyActivityStartTags(null, method, url, activity);
Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair<string, Activity> exceptionEvent));
Assert.Equal("Stop", exceptionEvent.Key);
Assert.NotNull(activity.GetTagValue(SpanAttributeConstants.StatusCodeKey));
Assert.NotNull(activity.GetTagValue(SpanAttributeConstants.StatusDescriptionKey));
}
/// <summary>
/// Test request cancellation: reflection hook does not throw.
/// </summary>
[Theory]
[InlineData("GET")]
[InlineData("POST")]
public async Task TestCanceledRequest(string method)
{
string url = this.BuildRequestUrl();
CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
using var eventRecords = new ActivitySourceRecorder(_ => { cts.Cancel(); });
using (var client = new HttpClient())
{
var ex = await Assert.ThrowsAnyAsync<Exception>(() =>
{
return method == "GET"
? client.GetAsync(url, cts.Token)
: client.PostAsync(url, new StringContent("hello world"), cts.Token);
});
Assert.True(ex is TaskCanceledException || ex is WebException);
}
// We should have one Start event and one Stop event with an exception.
Assert.Equal(2, eventRecords.Records.Count());
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start"));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop"));
Activity activity = AssertFirstEventWasStart(eventRecords);
VerifyActivityStartTags(this.hostNameAndPort, method, url, activity);
Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair<string, Activity> exceptionEvent));
Assert.Equal("Stop", exceptionEvent.Key);
Assert.NotNull(exceptionEvent.Value.GetTagValue(SpanAttributeConstants.StatusCodeKey));
Assert.Null(exceptionEvent.Value.GetTagValue(SpanAttributeConstants.StatusDescriptionKey));
}
/// <summary>
/// Test request connection exception: reflection hook does not throw.
/// </summary>
[Theory]
[InlineData("GET")]
[InlineData("POST")]
public async Task TestSecureTransportFailureRequest(string method)
{
string url = "https://expired.badssl.com/";
using var eventRecords = new ActivitySourceRecorder();
using (var client = new HttpClient())
{
var ex = await Assert.ThrowsAnyAsync<Exception>(() =>
{
// https://expired.badssl.com/ has an expired certificae.
return method == "GET"
? client.GetAsync(url)
: client.PostAsync(url, new StringContent("hello world"));
});
Assert.True(ex is HttpRequestException);
}
// We should have one Start event and one Stop event with an exception.
Assert.Equal(2, eventRecords.Records.Count());
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start"));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop"));
Activity activity = AssertFirstEventWasStart(eventRecords);
VerifyActivityStartTags(null, method, url, activity);
Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair<string, Activity> exceptionEvent));
Assert.Equal("Stop", exceptionEvent.Key);
Assert.NotNull(exceptionEvent.Value.GetTagValue(SpanAttributeConstants.StatusCodeKey));
Assert.NotNull(exceptionEvent.Value.GetTagValue(SpanAttributeConstants.StatusDescriptionKey));
}
/// <summary>
/// Test request connection retry: reflection hook does not throw.
/// </summary>
[Theory]
[InlineData("GET")]
[InlineData("POST")]
public async Task TestSecureTransportRetryFailureRequest(string method)
{
// This test sends an https request to an endpoint only set up for http.
// It should retry. What we want to test for is 1 start, 1 exception event even
// though multiple are actually sent.
string url = this.BuildRequestUrl(useHttps: true);
using var eventRecords = new ActivitySourceRecorder();
using (var client = new HttpClient())
{
var ex = await Assert.ThrowsAnyAsync<Exception>(() =>
{
return method == "GET"
? client.GetAsync(url)
: client.PostAsync(url, new StringContent("hello world"));
});
Assert.True(ex is HttpRequestException);
}
// We should have one Start event and one Stop event with an exception.
Assert.Equal(2, eventRecords.Records.Count());
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start"));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop"));
Activity activity = AssertFirstEventWasStart(eventRecords);
VerifyActivityStartTags(this.hostNameAndPort, method, url, activity);
Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair<string, Activity> exceptionEvent));
Assert.Equal("Stop", exceptionEvent.Key);
Assert.NotNull(exceptionEvent.Value.GetTagValue(SpanAttributeConstants.StatusCodeKey));
Assert.NotNull(exceptionEvent.Value.GetTagValue(SpanAttributeConstants.StatusDescriptionKey));
}
[Fact]
public async Task TestInvalidBaggage()
{
validateBaggage = true;
Baggage
.SetBaggage("key", "value")
.SetBaggage("bad/key", "value")
.SetBaggage("goodkey", "bad/value");
using var eventRecords = new ActivitySourceRecorder();
using (var client = new HttpClient())
{
(await client.GetAsync(this.BuildRequestUrl())).Dispose();
}
Assert.Equal(2, eventRecords.Records.Count());
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start"));
Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop"));
validateBaggage = false;
}
/// <summary>
/// Test to make sure every event record has the right dynamic properties.
/// </summary>
[Fact]
public void TestMultipleConcurrentRequests()
{
ServicePointManager.DefaultConnectionLimit = int.MaxValue;
var parentActivity = new Activity("parent").Start();
using var eventRecords = new ActivitySourceRecorder();
Dictionary<Uri, Tuple<WebRequest, WebResponse>> requestData = new Dictionary<Uri, Tuple<WebRequest, WebResponse>>();
for (int i = 0; i < 10; i++)
{
Uri uriWithRedirect = new Uri(this.BuildRequestUrl(queryString: $"q={i}&redirects=3"));
requestData[uriWithRedirect] = null;
}
// Issue all requests simultaneously
HttpClient httpClient = new HttpClient();
Dictionary<Uri, Task<HttpResponseMessage>> tasks = new Dictionary<Uri, Task<HttpResponseMessage>>();
CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
foreach (var url in requestData.Keys)
{
tasks.Add(url, httpClient.GetAsync(url, cts.Token));
}
// wait up to 10 sec for all requests and suppress exceptions
Task.WhenAll(tasks.Select(t => t.Value).ToArray()).ContinueWith(tt =>
{
foreach (var task in tasks)
{
task.Value.Result?.Dispose();
}
}).Wait();
// Examine the result. Make sure we got all successful requests.
// Just make sure some events are written, to confirm we successfully subscribed to it. We should have
// exactly 1 Start event per request and exactly 1 Stop event per response (if request succeeded)
var successfulTasks = tasks.Where(t => t.Value.Status == TaskStatus.RanToCompletion);
Assert.Equal(tasks.Count, eventRecords.Records.Count(rec => rec.Key == "Start"));
Assert.Equal(successfulTasks.Count(), eventRecords.Records.Count(rec => rec.Key == "Stop"));
// Check to make sure: We have a WebRequest and a WebResponse for each successful request
foreach (var pair in eventRecords.Records)
{
Activity activity = pair.Value;
Assert.True(
pair.Key == "Start" ||
pair.Key == "Stop",
"An unexpected event of name " + pair.Key + "was received");
}
}
private static Activity AssertFirstEventWasStart(ActivitySourceRecorder eventRecords)
{
Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair<string, Activity> startEvent));
Assert.Equal("Start", startEvent.Key);
return startEvent.Value;
}
private static void VerifyHeaders(HttpWebRequest startRequest)
{
var tracestate = startRequest.Headers["tracestate"];
Assert.Equal("some=state", tracestate);
var baggage = startRequest.Headers["baggage"];
Assert.Equal("k=v", baggage);
var traceparent = startRequest.Headers["traceparent"];
Assert.NotNull(traceparent);
Assert.Matches("^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$", traceparent);
}
private static void VerifyActivityStartTags(string hostNameAndPort, string method, string url, Activity activity)
{
Assert.NotNull(activity.TagObjects);
Assert.Equal(method, activity.GetTagValue(SemanticConventions.AttributeHttpMethod));
if (hostNameAndPort != null)
{
Assert.Equal(hostNameAndPort, activity.GetTagValue(SemanticConventions.AttributeHttpHost));
}
Assert.Equal(url, activity.GetTagValue(SemanticConventions.AttributeHttpUrl));
}
private static void VerifyActivityStopTags(int statusCode, Activity activity)
{
Assert.Equal(statusCode, activity.GetTagValue(SemanticConventions.AttributeHttpStatusCode));
}
private static void ActivityEnrichment(Activity activity, string method, object obj)
{
switch (method)
{
case "OnStartActivity":
Assert.True(obj is HttpWebRequest);
VerifyHeaders(obj as HttpWebRequest);
if (validateBaggage)
{
ValidateBaggage(obj as HttpWebRequest);
}
break;
case "OnStopActivity":
Assert.True(obj is HttpWebResponse);
break;
case "OnException":
Assert.True(obj is Exception);
break;
default:
break;
}
}
private static void ValidateBaggage(HttpWebRequest request)
{
string[] baggage = request.Headers["baggage"].Split(',');
Assert.Equal(3, baggage.Length);
Assert.Contains("key=value", baggage);
Assert.Contains("bad%2Fkey=value", baggage);
Assert.Contains("goodkey=bad%2Fvalue", baggage);
}
private string BuildRequestUrl(bool useHttps = false, string path = "echo", string queryString = null)
{
return $"{(useHttps ? "https" : "http")}://{this.testServerHost}:{this.testServerPort}/{path}{(string.IsNullOrWhiteSpace(queryString) ? string.Empty : $"?{queryString}")}";
}
private void CleanUpActivity()
{
while (Activity.Current != null)
{
Activity.Current.Stop();
}
}
/// <summary>
/// <see cref="ActivitySourceRecorder"/> is a helper class for recording <see cref="HttpWebRequestActivitySource.ActivitySourceName"/> events.
/// </summary>
private class ActivitySourceRecorder : IDisposable
{
private readonly Action<KeyValuePair<string, Activity>> onEvent;
private readonly ActivityListener activityListener;
public ActivitySourceRecorder(Action<KeyValuePair<string, Activity>> onEvent = null, ActivitySamplingResult activitySamplingResult = ActivitySamplingResult.AllDataAndRecorded)
{
this.activityListener = new ActivityListener
{
ShouldListenTo = (activitySource) => activitySource.Name == HttpWebRequestActivitySource.ActivitySourceName,
ActivityStarted = this.ActivityStarted,
ActivityStopped = this.ActivityStopped,
Sample = (ref ActivityCreationOptions<ActivityContext> options) => activitySamplingResult,
};
ActivitySource.AddActivityListener(this.activityListener);
this.onEvent = onEvent;
}
public ConcurrentQueue<KeyValuePair<string, Activity>> Records { get; } = new ConcurrentQueue<KeyValuePair<string, Activity>>();
public void Dispose()
{
this.activityListener.Dispose();
}
public void ActivityStarted(Activity activity) => this.Record("Start", activity);
public void ActivityStopped(Activity activity) => this.Record("Stop", activity);
private void Record(string eventName, Activity activity)
{
var record = new KeyValuePair<string, Activity>(eventName, activity);
this.Records.Enqueue(record);
this.onEvent?.Invoke(record);
}
}
}
}
#endif
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualNetworkGatewayConnectionsOperations operations.
/// </summary>
public partial interface IVirtualNetworkGatewayConnectionsOperations
{
/// <summary>
/// Creates or updates a virtual network gateway connection in the
/// specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network gateway
/// connection operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified virtual network gateway connection by resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network Gateway connection.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the
/// virtual network gateway connection shared key for passed virtual
/// network gateway connection in the specified resource group through
/// Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Set Virtual Network Gateway
/// connection Shared key operation throughNetwork resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ConnectionSharedKey>> SetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Get VirtualNetworkGatewayConnectionSharedKey operation
/// retrieves information about the specified virtual network gateway
/// connection shared key through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection shared key name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ConnectionSharedKey>> GetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The List VirtualNetworkGatewayConnections operation retrieves all
/// the virtual network gateways connections created.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The VirtualNetworkGatewayConnectionResetSharedKey operation resets
/// the virtual network gateway connection shared key for passed
/// virtual network gateway connection in the specified resource group
/// through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection reset shared key Name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the begin reset virtual network gateway
/// connection shared key operation through network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ConnectionResetSharedKey>> ResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a virtual network gateway connection in the
/// specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network gateway
/// connection operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network Gateway connection.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the
/// virtual network gateway connection shared key for passed virtual
/// network gateway connection in the specified resource group through
/// Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Set Virtual Network Gateway
/// connection Shared key operation throughNetwork resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ConnectionSharedKey>> BeginSetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The VirtualNetworkGatewayConnectionResetSharedKey operation resets
/// the virtual network gateway connection shared key for passed
/// virtual network gateway connection in the specified resource group
/// through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection reset shared key Name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the begin reset virtual network gateway
/// connection shared key operation through network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ConnectionResetSharedKey>> BeginResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The List VirtualNetworkGatewayConnections operation retrieves all
/// the virtual network gateways connections created.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green ([email protected])
*
* SharpNEAT is free software; you can redistribute it and/or modify
* it under the terms of The MIT License (MIT).
*
* You should have received a copy of the MIT License
* along with SharpNEAT; if not, see https://opensource.org/licenses/MIT.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using SharpNeat.Network;
namespace SharpNeat.Genomes.Neat
{
// ENHANCEMENT: Consider switching to a SortedList[K,V] - which guarantees item sort order at all times.
/// <summary>
/// Represents a sorted list of NeuronGene objects. The sorting of the items is done on request
/// rather than being strictly enforced at all times (e.g. as part of adding and removing items). This
/// approach is currently more convenient for use in some of the routines that work with NEAT genomes.
///
/// Because we are not using a strictly sorted list such as the generic class SortedList[K,V] a customised
/// BinarySearch() method is provided for fast lookup of items if the list is known to be sorted. If the list is
/// not sorted then the BinarySearch method's behaviour is undefined. This is potentially a source of bugs
/// and thus this class should probably migrate to SortedList[K,V] or be modified to ensure items are sorted
/// prior to a binary search.
///
/// Sort order is with respect to connection gene innovation ID.
/// </summary>
public class NeuronGeneList : List<NeuronGene>, INodeList
{
#region Constructors
/// <summary>
/// Construct an empty list.
/// </summary>
public NeuronGeneList()
{
}
/// <summary>
/// Construct an empty list with the specified capacity.
/// </summary>
public NeuronGeneList(int capacity) : base(capacity)
{
}
/// <summary>
/// Copy constructor. The newly allocated list has a capacity 1 larger than copyFrom
/// allowing for a single add node mutation to occur without reallocation of memory.
/// </summary>
public NeuronGeneList(ICollection<NeuronGene> copyFrom)
: base(copyFrom.Count+1)
{
// ENHANCEMENT: List.Foreach() is potentially faster than a foreach loop.
// http://diditwith.net/2006/10/05/PerformanceOfForeachVsListForEach.aspx
foreach(NeuronGene srcGene in copyFrom) {
Add(srcGene.CreateCopy());
}
}
#endregion
#region Public Methods
/// <summary>
/// Inserts a NeuronGene into its correct (sorted) location within the gene list.
/// Normally neuron genes can safely be assumed to have a new Innovation ID higher
/// than all existing IDs, and so we can just call Add().
/// This routine handles genes with older IDs that need placing correctly.
/// </summary>
public void InsertIntoPosition(NeuronGene neuronGene)
{
// Determine the insert idx with a linear search, starting from the end
// since mostly we expect to be adding genes that belong only 1 or 2 genes
// from the end at most.
int idx=Count-1;
for(; idx > -1; idx--)
{
if(this[idx].InnovationId < neuronGene.InnovationId)
{ // Insert idx found.
break;
}
}
Insert(idx+1, neuronGene);
}
/// <summary>
/// Remove the neuron gene with the specified innovation ID.
/// Returns the removed gene.
/// </summary>
public NeuronGene Remove(uint neuronId)
{
int idx = BinarySearch(neuronId);
if(idx<0) {
throw new ApplicationException("Attempt to remove neuron with an unknown neuronId");
}
NeuronGene neuronGene = this[idx];
RemoveAt(idx);
return neuronGene;
}
/// <summary>
/// Gets the neuron gene with the specified innovation ID using a fast binary search.
/// Returns null if no such gene is in the list.
/// </summary>
public NeuronGene GetNeuronById(uint neuronId)
{
int idx = BinarySearch(neuronId);
if(idx<0)
{ // Not found.
return null;
}
return this[idx];
}
/// <summary>
/// Sort neuron gene's into ascending order by their innovation IDs.
/// </summary>
public void SortByInnovationId()
{
Sort(delegate(NeuronGene x, NeuronGene y)
{
// Test the most likely cases first.
if(x.InnovationId < y.InnovationId) {
return -1;
}
if(x.InnovationId > y.InnovationId) {
return 1;
}
return 0;
});
}
/// <summary>
/// Obtain the index of the gene with the specified ID by performing a binary search.
/// Binary search is fast and can be performed so long as the genes are sorted by ID.
/// If the genes are not sorted then the behaviour of this method is undefined.
/// </summary>
public int BinarySearch(uint id)
{
int lo = 0;
int hi = Count-1;
while (lo <= hi)
{
int i = (lo + hi) >> 1;
if(this[i].Id < id) {
lo = i + 1;
}
else if(this[i].Id > id) {
hi = i - 1;
}
else {
return i;
}
}
return ~lo;
}
/// <summary>
/// For debug purposes only. Don't call this method in normal circumstances as it is an
/// expensive O(n) operation.
/// </summary>
public bool IsSorted()
{
int count = this.Count;
if(0 == count) {
return true;
}
uint prev = this[0].InnovationId;
for(int i=1; i<count; i++)
{
if(this[i].InnovationId <= prev) {
return false;
}
}
return true;
}
#endregion
#region INodeList<INetworkNode> Members
INetworkNode INodeList.this[int index]
{
get { return this[index]; }
}
int INodeList.Count
{
get { return this.Count; }
}
IEnumerator<INetworkNode> IEnumerable<INetworkNode>.GetEnumerator()
{
foreach(NeuronGene nGene in this) {
yield return nGene;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<INetworkNode>)this).GetEnumerator();
}
#endregion
}
}
| |
/* Microsoft SQL Server Integration Services Script Component
* Write scripts using Microsoft Visual C# 2008.
* ScriptMain is the entry point class of the script.*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
#region Script Setup
// Ensure you've set up output columns and supplied an Excel Connection Manager in the Script Editor UI
/// <summary>
/// Set the following variable value to the name of the table in Excel. To find or set the name of the table in Excel,
/// go to the Design ribbon in the Table Tools group. The table name is shown on the left side.
/// </summary>
// private static readonly string ExcelTableName = "IF - COA - LNS - Centnl";
private static readonly string ExcelSheetName = "IF - COA - LNS - Centnl";
/// <summary>
/// Set this variable to true if you want copious reporting done (for debugging)
/// </summary>
private static readonly bool VerboseLogging = true;
/// <summary>
/// Fill this method with calls to MapColumn to map Excel column names to SSIS output columns, and provide data types.
/// </summary>
private void MapColumns()
{
// sample:
// this.MapColumn("Excel Column Header", "SSIS Column Name", typeof(string));
this.MapColumn("FA", "FA", typeof(string), true);
this.MapColumn("USID", "USID", typeof(int), true);
this.MapColumn("OOF VENDOR TYPE", "OOFVendorType", typeof(string), true);
this.MapColumn("ECD", "ECD", typeof(string), true);
// this.MapColumn("ECD", "ECD", typeof(int), true);
this.MapColumn("Revised ECD", "RevisedECD", typeof(string), true);
this.MapColumn("ACD", "ACD", typeof(string), true);
this.MapColumn("ACD 2", "ACD2", typeof(string), true);
this.MapColumn("Reported", "Reported", typeof(string), true);
}
#endregion
#region Code You Don't Touch
// The following code is configured based on the information you supplied in the section above,
// and what columns and connection in the Script Editor UI.
private const string SCRIPT_NAME = "OpenXML API Script Source for SpreadsheetML";
private const string LAST_UPDATED = "2013-11-20 23:50";
private static bool __script_last_updated_logged = false;
private static IDTSComponentMetaData100 __metadata;
/// <summary>
/// The list of Excel to SSIS column maps
/// </summary>
private readonly List<ColumnMapping> _columnMappings = new List<ColumnMapping>();
#endregion
#region CLASS: ColumnMapping
private class ColumnMapping
{
#region Property Setting Delegates
public delegate void NullSetter(bool isNull);
public delegate void StringSetter(string value);
public delegate void Int32Setter(Int32 value);
public delegate void DateTimeSetter(DateTime value);
public delegate void BooleanSetter(bool value);
//ADD_DATATYPES_HERE
#endregion
#region Private Variables
private readonly string _excelColumnName;
private int _excelColumnOffset;
private readonly string _ssisColumnName;
private readonly System.Type _dataType;
private readonly bool _treatBlanksAsNulls;
#endregion
public NullSetter SetNull;
public StringSetter SetString;
public Int32Setter SetInt;
public DateTimeSetter SetDateTime;
public BooleanSetter SetBoolean;
//ADD_DATATYPES_HERE
#region Constructor
public ColumnMapping(string excelColumnName, string ssisColumnName, System.Type dataType, bool treatBlanksAsNulls)
{
this._excelColumnName = excelColumnName;
this._excelColumnOffset = -1;
this._ssisColumnName = ssisColumnName;
this._dataType = dataType;
this._treatBlanksAsNulls = treatBlanksAsNulls;
}
#endregion
#region Public Properties
public System.Type DataType
{
get { return this._dataType; }
}
public string ExcelColumnName
{
get { return this._excelColumnName; }
}
public string SSISColumnName
{
get { return this._ssisColumnName; }
}
public int ExcelColumnOffset
{
get { return this._excelColumnOffset; }
set { this._excelColumnOffset = value; }
}
public bool ExcelColumnFound
{
get { return (this._excelColumnOffset >= 0); }
}
public bool TreatBlanksAsNulls
{
get { return this._treatBlanksAsNulls; }
}
#endregion
#region SSIS Buffer Setter
public void SetSSISBuffer(string value)
{
#region String
if (this._dataType == typeof(string))
{
try
{
this.SetString(value);
}
#region catch...
catch (Exception ex)
{
ReportError("Error encountered setting SSIS column '" + this._ssisColumnName + "' with string value '" + value + "': " + ex.Message, true);
}
#endregion
VerboseLog("Set SSIS column '" + this._ssisColumnName + "' with string value '" + value + "'");
}
#endregion
#region Int
else if (this._dataType == typeof(int))
{
int intValue = 0;
try
{
intValue = Convert.ToInt32(value);
}
#region catch...
catch (Exception ex)
{
ReportError("Error encountered converting Excel column '" + this._excelColumnName + "' value '" + value + "' to integer: " + ex.Message, true);
}
#endregion
try
{
this.SetInt(intValue);
}
#region catch...
catch (Exception ex)
{
ReportError("Error encountered setting SSIS column '" + this._ssisColumnName + "' with int value '" + intValue.ToString() + "': " + ex.Message, true);
}
#endregion
VerboseLog("Set SSIS column '" + this._ssisColumnName + "' with int value '" + intValue.ToString() + "'");
}
#endregion
#region DateTime
else if (this._dataType == typeof(DateTime))
{
DateTime dateValue = new DateTime(1900, 1, 1);
try
{
dateValue = dateValue.AddDays(Convert.ToDouble(value) - 2);
}
#region catch...
catch (Exception ex)
{
ReportError("Error encountered converting Excel column '" + this._excelColumnName + "' value '" + value + "' to DateTime: " + ex.Message, true);
}
#endregion
try
{
this.SetDateTime(dateValue);
}
#region catch...
catch (Exception ex)
{
ReportError("Error encountered setting SSIS column '" + this._ssisColumnName + "' with DateTime value '" + dateValue.ToString() + "': " + ex.Message, true);
}
#endregion
VerboseLog("Set SSIS column '" + this._ssisColumnName + "' with DateTime value '" + dateValue.ToString("yyyy-MM-dd hh:mm:ss") + "'");
}
#endregion
#region Boolean
else if (this._dataType == typeof(bool))
{
bool boolValue = false;
try
{
if ((value.ToUpper().Trim() == "YES")
|| (value.ToUpper().Trim() == "Y")
|| (value.ToUpper().Trim() == "TRUE"))
{
boolValue = true;
}
else if ((value.ToUpper().Trim() == "NO")
|| (value.ToUpper().Trim() == "N")
|| (value.ToUpper().Trim() == "FALSE"))
{
boolValue = false;
}
else
{
ReportError("Invalid boolean value in column '" + this._excelColumnName + "': '" + value + "'", true);
}
}
#region catch...
catch (Exception ex)
{
ReportError("Error encountered converting Excel column '" + this._excelColumnName + "' value '" + value + "' to boolean: " + ex.Message, true);
}
#endregion
try
{
this.SetBoolean(boolValue);
}
#region catch...
catch (Exception ex)
{
ReportError("Error encountered setting SSIS column '" + this._ssisColumnName + "' with boolean value '" + boolValue.ToString() + "': " + ex.Message, true);
}
#endregion
VerboseLog("Set SSIS column '" + this._ssisColumnName + "' with Boolean value '" + boolValue.ToString() + "'");
}
#endregion
//ADD_DATATYPES_HERE
else
{
ReportUnhandledDataTypeError(this._dataType);
}
}
#endregion
}
#endregion
#region Sets up map from Excel column to an SSIS column
public void MapColumn(string excelColumnName, string ssisColumnName, System.Type dataType, bool treatBlanksAsNulls)
{
string methodName = "set_" + ssisColumnName.Replace(" ", "");
VerboseLog("Creating " + dataType.ToString() + " mapping from '" + excelColumnName + "' to '" + ssisColumnName + "' via " + methodName);
ColumnMapping mapping = new ColumnMapping(excelColumnName, ssisColumnName, dataType, treatBlanksAsNulls);
#region Code to create delegates I'd have liked to have inside the ColumnMapping class itself if I could pass Output0Buffer...
VerboseLog("Creating delegate for " + methodName + "_IsNull");
mapping.SetNull = (ColumnMapping.NullSetter)Delegate.CreateDelegate(typeof(ColumnMapping.NullSetter), Output0Buffer, methodName + "_IsNull");
if (dataType == typeof(string))
{
VerboseLog("Creating delegate for " + methodName + "string");
mapping.SetString = (ColumnMapping.StringSetter)Delegate.CreateDelegate(typeof(ColumnMapping.StringSetter), Output0Buffer, methodName);
}
else if (dataType == typeof(int))
{
VerboseLog("Creating delegate for " + methodName + "int");
mapping.SetInt = (ColumnMapping.Int32Setter)Delegate.CreateDelegate(typeof(ColumnMapping.Int32Setter), Output0Buffer, methodName);
}
else if (dataType == typeof(DateTime))
{
mapping.SetDateTime = (ColumnMapping.DateTimeSetter)Delegate.CreateDelegate(typeof(ColumnMapping.DateTimeSetter), Output0Buffer, methodName);
}
else if (dataType == typeof(bool))
{
mapping.SetBoolean = (ColumnMapping.BooleanSetter)Delegate.CreateDelegate(typeof(ColumnMapping.BooleanSetter), Output0Buffer, methodName);
}
//ADD_DATATYPES_HERE
else
{
ReportUnhandledDataTypeError(dataType);
}
this._columnMappings.Add(mapping);
#endregion
}
#endregion
#region CreateNewOutputRows - the only method called from SSIS, this is the "entry point"
public override void CreateNewOutputRows()
{
#region Set up verbose logging
__metadata = ComponentMetaData;
#endregion
// See http://blogs.msdn.com/b/brian_jones/archive/2008/11/10/reading-data-from-spreadsheetml.aspx
// http://openxmldeveloper.org/discussions/formats/f/14/p/5029/157797.aspx
// http://blogs.msdn.com/b/ericwhite/archive/2010/07/21/table-markup-in-open-xml-spreadsheetml.aspx
#region Configure Column Mapping
this.MapColumns();
if (this._columnMappings.Count != ComponentMetaData.OutputCollection[0].OutputColumnCollection.Count)
{
string message = this._columnMappings.Count.ToString() + " column relationships have been set up, but the Script Source has "
+ ComponentMetaData.OutputCollection[0].OutputColumnCollection.Count.ToString() + " output columns defined.";
ReportError(message, true);
throw new ArgumentException(message);
}
VerboseLog(this._columnMappings.Count.ToString() + " column mappings defined.");
#endregion
#region Extract Excel file name from connection manager
string workbookFileName = null;
SpreadsheetDocument document = null;
try
{
VerboseLog("Extracting Excel file name from connection manager.");
string connectionString = ComponentMetaData.RuntimeConnectionCollection[0].ConnectionManager.ConnectionString;
string[] connectionStringParts = connectionString.Split(';');
foreach (string connectionStringPart in connectionStringParts)
{
string[] pair = connectionStringPart.Split('=');
if (pair[0] == "Data Source")
{
workbookFileName = pair[1];
VerboseLog("File name of '" + workbookFileName + "' identified in connection manager.");
break;
}
}
}
#region catch ...
catch (Exception ex)
{
ReportError("Unable to parse connection string: " + ex.Message, true);
}
#endregion
#endregion
#region Opening Excel file
if (workbookFileName != null)
{
try
{
VerboseLog("Attempting to open Excel file.");
document = SpreadsheetDocument.Open(workbookFileName, false);
}
#region catch ...
catch (Exception ex)
{
ReportError("Unable to open '" + workbookFileName + "': " + ex.Message, true);
}
#endregion
}
VerboseLog("Excel file opened.");
#endregion
try
{
WorkbookPart workbook = document.WorkbookPart;
SharedStringTablePart sharedStringTablePart = workbook.SharedStringTablePart;
#region Unused code for finding ranges
//ComponentMetaData.FireInformation(0, "", "Got WorkbookPart", "", 0, ref fireAgain);
//#region Look at Ranges
//bool foundRange = false;
//RangeDef rangeDef = new RangeDef();
//foreach (DefinedName name in workbook.Workbook.GetFirstChild<DefinedNames>())
//{
// ComponentMetaData.FireInformation(0, "", "Looking at defined name '" + name.Name + "'", "", 0, ref fireAgain);
// if (name.Name == this._rangeName)
// {
// ComponentMetaData.FireInformation(0, "", "Saving def", "", 0, ref fireAgain);
// rangeDef.Name = name.Name;
// string reference = name.InnerText;
// ComponentMetaData.FireInformation(0, "", " reference: " + reference, "", 0, ref fireAgain);
// rangeDef.Sheet = reference.Split('!')[0].Trim('\'');
// string[] rangeArray = reference.Split('!')[1].Split('$');
// rangeDef.StartCol = rangeArray[1];
// rangeDef.StartRow = rangeArray[2].TrimEnd(':');
// rangeDef.EndCol = rangeArray[3];
// rangeDef.EndRow = rangeArray[4];
// foundRange = true;
// break;
// }
//}
//ComponentMetaData.FireInformation(0, "", "Done looking for defined names", "", 0, ref fireAgain);
//if (foundRange)
//{
// string rangeID = workbook.Workbook.Descendants<Sheet>().Where(r => r.Name.Equals(rangeDef.Sheet)).First().Id;
// ComponentMetaData.FireInformation(0, "", "Got rangeID " + rangeID, "", 0, ref fireAgain);
// WorksheetPart range = (WorksheetPart)workbook.GetPartById(rangeID);
// ComponentMetaData.FireInformation(0, "", "Got Range", "", 0, ref fireAgain);
//}
//#endregion
#endregion
#region Iterate over sheets to find table
// VerboseLog("Searching sheets for table '" + ExcelTableName + "'.");
VerboseLog("Searching for sheet '" + ExcelSheetName + "'.");
// Table table = null;
Worksheet worksheet = null;
foreach (Sheet sheet in workbook.Workbook.Sheets)
{
VerboseLog("Examining sheet '" + sheet.Name + "'.");
WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheet.Id);
if (sheet.Name == ExcelSheetName)
{
worksheet = worksheetPart.Worksheet;
VerboseLog("Sheet found.");
break;
}
//foreach (TableDefinitionPart tableDefinitionPart in worksheetPart.TableDefinitionParts)
//{
// VerboseLog("Sheet contains table '" + tableDefinitionPart.Table.DisplayName + "'.");
// if (tableDefinitionPart.Table.DisplayName == ExcelTableName)
// {
// worksheet = worksheetPart.Worksheet;
// table = tableDefinitionPart.Table;
// VerboseLog("Sheet and table found.");
// break;
// }
//}
//if (table != null)
//{
// break;
//}
}
#endregion
//if (table == null)
//{
// ReportError("Table '" + ExcelTableName + "' wasn't found in '" + workbookFileName + "'.", true);
//}
//else
//{
// string firstColumnHeader = "";
// #region Find Excel Column Offsets
// VerboseLog("Collecting column offsets for mapped columns.");
// int columnIndex = 1;
// foreach (TableColumn tableColumn in table.TableColumns)
// {
// if (columnIndex == 1)
// {
// firstColumnHeader = tableColumn.Name;
// }
// foreach (ColumnMapping columnRelationship in this._columnMappings)
// {
// if (tableColumn.Name == columnRelationship.ExcelColumnName)
// {
// VerboseLog("Found Excel column " + tableColumn.Name + " at offset " + columnIndex.ToString());
// columnRelationship.ExcelColumnOffset = columnIndex;
// break;
// }
// }
// columnIndex++;
// }
// #region Throw an error if not all columns were found
// foreach (ColumnMapping columnRelationship in this._columnMappings)
// {
// if (!columnRelationship.ExcelColumnFound)
// {
// string message = "Unable to locate column '" + columnRelationship.ExcelColumnName + "' in table '" + ExcelTableName + "'.";
// ReportError(message, true);
// }
// }
// #endregion
// #endregion
if (worksheet == null)
{
ReportError("Sheet '" + ExcelSheetName + "' wasn't found in '" + workbookFileName + "'.", true);
}
else
{
string firstColumnHeader = "";
#region Read spreadsheet data into SSIS output buffer
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
IEnumerable<Row> rows = sheetData.Elements<Row>();
#region Find First Row
UInt32 firstRow = 0;
// VerboseLog("Finding first row of table.");
VerboseLog("Finding first row of sheet.");
foreach (Row row in rows)
{
foreach (Cell cell in row.Elements<Cell>())
{
if (this.CellReferenceToCoordinates(cell.CellReference)[0] == 1)
{
if (this.GetCellValue(cell, sharedStringTablePart) == firstColumnHeader)
{
firstRow = row.RowIndex + 1;
}
}
}
}
// VerboseLog("First row of table is on row " + firstRow.ToString() + ".");
VerboseLog("First row of sheet is on row " + firstRow.ToString() + ".");
#endregion
// VerboseLog("Preparing to read " + rows.Count<Row>().ToString() + " table rows from Excel.");
VerboseLog("Preparing to read " + rows.Count<Row>().ToString() + " sheet rows from Excel.");
foreach (Row row in rows)
{
VerboseLog("Reading row " + row.RowIndex.ToString() + ".");
if (row.RowIndex < firstRow)
{
VerboseLog("Skipping non-table or header row.");
}
else
{
VerboseLog("Reading data row " + (row.RowIndex - 1).ToString() + ".");
bool rowAdded = false;
foreach (Cell cell in row.Elements<Cell>())
{
foreach (ColumnMapping columnRelationship in this._columnMappings)
{
if (this.CellReferenceToCoordinates(cell.CellReference)[0] == columnRelationship.ExcelColumnOffset)
{
string cellValue = this.GetCellValue(cell, sharedStringTablePart);
if ((cellValue == null)
|| ((cellValue == "") && columnRelationship.TreatBlanksAsNulls))
{
// do nothing
}
else
{
if (!rowAdded)
{
Output0Buffer.AddRow();
rowAdded = true;
}
VerboseLog("Excel column '" + columnRelationship.ExcelColumnName + "' contains '" + cellValue + "'.");
columnRelationship.SetSSISBuffer(this.GetCellValue(cell, sharedStringTablePart));
}
}
}
}
}
}
#endregion
}
}
#region catch ...
catch (Exception ex)
{
ReportError("Unable to open Excel file using OpenXML API: " + ex.Message, true);
}
#endregion
VerboseLog("Closing Excel file");
document.Close();
}
#endregion
#region Helper functions to change Excel ranges to numeric coordinates/offsets
private int[] RangeReferenceToCoordinates(string rangeReference)
{
int[] coordinates = new int[4];
string[] cellReferences = rangeReference.Split(':');
int[] startCellReference = this.CellReferenceToCoordinates(cellReferences[0]);
int[] endCellReference = this.CellReferenceToCoordinates(cellReferences[1]);
coordinates[0] = startCellReference[0];
coordinates[1] = startCellReference[1];
coordinates[2] = endCellReference[0];
coordinates[3] = endCellReference[1];
return coordinates;
}
private int[] CellReferenceToCoordinates(string cellReference)
{
//bool fireAgain = true;
int[] coordinates = new int[2];
//ComponentMetaData.FireInformation(0, "", "CellRef: [" + cellReference + "]", "", 0, ref fireAgain);
int index;
cellReference = cellReference.Replace("$", "").Trim();
#region Collect column letters -> column
string column = "";
for (index = 0; index < cellReference.Length; index++)
{
if ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".Contains(cellReference[index]))
{
column += cellReference[index];
}
else
{
break;
}
}
#endregion
//ComponentMetaData.FireInformation(0, "", "column: [" + column + "]", "", 0, ref fireAgain);
#region Convert column into number -> coordinates[0]
for (int power = 0; power < index; power++)
{
coordinates[0] += ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".IndexOf(column[column.Length - power - 1]) + 1) * (int)Math.Pow(26, power);
}
#endregion
//ComponentMetaData.FireInformation(0, "", "col coords: [" + coordinates[0].ToString() + "]", "", 0, ref fireAgain);
#region Convert row into number -> coordinates[1]
coordinates[1] = Convert.ToInt32(cellReference.Substring(index));
#endregion
//ComponentMetaData.FireInformation(0, "", "row coords: [" + coordinates[1].ToString() + "]", "", 0, ref fireAgain);
return coordinates;
}
#endregion
#region Helper function to read Excel cell values
private string GetCellValue(Cell cell, SharedStringTablePart sharedStringTablePart)
{
if (cell.ChildElements.Count == 0)
{
return null;
}
if ((cell.DataType != null) && (cell.DataType == CellValues.SharedString))
{
return sharedStringTablePart.SharedStringTable.ChildElements[Int32.Parse(cell.CellValue.InnerText)].InnerText;
}
else
{
return cell.CellValue.InnerText;
}
}
#endregion
#region Logging functions
private static void VerboseLog(string message)
{
bool pbFireAgain = true;
if (!__script_last_updated_logged)
{
__metadata.FireInformation(0, __metadata.Name, "Excel OpenXML API Source Script (" + LAST_UPDATED + ") running.", "", 0, ref pbFireAgain);
__script_last_updated_logged = true;
}
if (VerboseLogging)
{
__metadata.FireInformation(0, __metadata.Name, message, "", 0, ref pbFireAgain);
}
}
private static void ReportError(string message, bool fatal)
{
bool pbCancel;
__metadata.FireError(0, __metadata.Name, message, "", 0, out pbCancel);
if (fatal)
{
throw new ApplicationException(SCRIPT_NAME + " had a fatal error.");
}
}
private static void ReportUnhandledDataTypeError(System.Type dataType)
{
// Need to add a Data Type? Search for ADD_DATATYPES_HERE
ReportError("This script can't handle " + dataType.ToString() + " types.", true);
throw new ArgumentException("This script can't handle " + dataType.ToString() + " types.");
}
#endregion
//public override void PreExecute()
//{
// base.PreExecute();
// /*
// Add your code here for preprocessing or remove if not needed
// */
//}
//public override void PostExecute()
//{
// base.PostExecute();
// /*
// Add your code here for postprocessing or remove if not needed
// You can set read/write variables here, for example:
// Variables.MyIntVar = 100
// */
//}
//public override void CreateNewOutputRows()
//{
// /*
// Add rows by calling the AddRow method on the member variable named "<Output Name>Buffer".
// For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".
// */
//}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TdsParserStaticFunctionality.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
using System;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Data.Sql;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Runtime.Versioning;
internal sealed class TdsParserStaticMethods {
private TdsParserStaticMethods() { /* prevent utility class from being insantiated*/ }
//
// Static methods
//
// SxS: this method accesses registry to resolve the alias.
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
static internal void AliasRegistryLookup(ref string host, ref string protocol) {
#if !MOBILE
if (!ADP.IsEmpty(host)) {
const String folder = "SOFTWARE\\Microsoft\\MSSQLServer\\Client\\ConnectTo";
// Put a try...catch... around this so we don't abort ANY connection if we can't read the registry.
string aliasLookup = (string) ADP.LocalMachineRegistryValue(folder, host);
if (!ADP.IsEmpty(aliasLookup)) {
/* Result will be in the form of: "DBNMPNTW,\\blained1\pipe\sql\query". or
Result will be in the form of: "DBNETLIB, via:\\blained1\pipe\sql\query".
supported formats:
tcp - DBMSSOCN,[server|server\instance][,port]
np - DBNMPNTW,[\\server\pipe\sql\query | \\server\pipe\MSSQL$instance\sql\query]
where \sql\query is the pipename and can be replaced with any other pipe name
via - [DBMSGNET,server,port | DBNETLIB, via:server, port]
sm - DBMSLPCN,server
unsupported formats:
rpc - DBMSRPCN,server,[parameters] where parameters could be "username,password"
bv - DBMSVINN,service@group@organization
appletalk - DBMSADSN,objectname@zone
spx - DBMSSPXN,[service | address,port,network]
*/
// We must parse into the two component pieces, then map the first protocol piece to the
// appropriate value.
int index = aliasLookup.IndexOf(',');
// If we found the key, but there was no "," in the string, it is a bad Alias so return.
if (-1 != index) {
string parsedProtocol = aliasLookup.Substring(0, index).ToLower(CultureInfo.InvariantCulture);
// If index+1 >= length, Alias consisted of "FOO," which is a bad alias so return.
if (index+1 < aliasLookup.Length) {
string parsedAliasName = aliasLookup.Substring(index+1);
// Fix bug 298286
if ("dbnetlib" == parsedProtocol) {
index = parsedAliasName.IndexOf(':');
if (-1 != index && index + 1 < parsedAliasName.Length) {
parsedProtocol = parsedAliasName.Substring (0, index);
if (SqlConnectionString.ValidProtocal (parsedProtocol)) {
protocol = parsedProtocol;
host = parsedAliasName.Substring(index + 1);
}
}
}
else {
protocol = (string)SqlConnectionString.NetlibMapping()[parsedProtocol];
if (null != protocol) {
host = parsedAliasName;
}
}
}
}
}
}
#endif
}
// Encrypt password to be sent to SQL Server
// Note: The same logic is used in SNIPacketSetData (SniManagedWrapper) to encrypt passwords stored in SecureString
// If this logic changed, SNIPacketSetData needs to be changed as well
static internal Byte[] EncryptPassword(string password) {
Byte[] bEnc = new Byte[password.Length << 1];
int s;
byte bLo;
byte bHi;
for (int i = 0; i < password.Length; i ++) {
s = (int) password[i];
bLo = (byte) (s & 0xff);
bHi = (byte) ((s >> 8) & 0xff);
bEnc[i<<1] = (Byte) ( (((bLo & 0x0f) << 4) | (bLo >> 4)) ^ 0xa5 );
bEnc[(i<<1)+1] = (Byte) ( (((bHi & 0x0f) << 4) | (bHi >> 4)) ^ 0xa5);
}
return bEnc;
}
[ResourceExposure(ResourceScope.None)] // SxS: we use this method for TDS login only
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
static internal int GetCurrentProcessIdForTdsLoginOnly() {
return SafeNativeMethods.GetCurrentProcessId();
}
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
[ResourceExposure(ResourceScope.None)] // SxS: we use this method for TDS login only
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
static internal Int32 GetCurrentThreadIdForTdsLoginOnly() {
#pragma warning disable 618
return AppDomain.GetCurrentThreadId(); // don't need this to be support fibres;
#pragma warning restore 618
}
[ResourceExposure(ResourceScope.None)] // SxS: we use MAC address for TDS login only
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
static internal byte[] GetNetworkPhysicalAddressForTdsLoginOnly() {
// NIC address is stored in NetworkAddress key. However, if NetworkAddressLocal key
// has a value that is not zero, then we cannot use the NetworkAddress key and must
// instead generate a random one. I do not fully understand why, this is simply what
// the native providers do. As for generation, I use a random number generator, which
// means that different processes on the same machine will have different NIC address
// values on the server. It is not ideal, but native does not have the same value for
// different processes either.
const string key = "NetworkAddress";
const string localKey = "NetworkAddressLocal";
const string folder = "SOFTWARE\\Description\\Microsoft\\Rpc\\UuidTemporaryData";
int result = 0;
byte[] nicAddress = null;
object temp = ADP.LocalMachineRegistryValue(folder, localKey);
if (temp is int) {
result = (int) temp;
}
if (result <= 0) {
temp = ADP.LocalMachineRegistryValue(folder, key);
if (temp is byte[]) {
nicAddress = (byte[]) temp;
}
}
if (null == nicAddress) {
nicAddress = new byte[TdsEnums.MAX_NIC_SIZE];
Random random = new Random();
random.NextBytes(nicAddress);
}
return nicAddress;
}
// translates remaining time in stateObj (from user specified timeout) to timout value for SNI
static internal Int32 GetTimeoutMilliseconds(long timeoutTime) {
// User provided timeout t | timeout value for SNI | meaning
// ------------------------+-----------------------+------------------------------
// t == long.MaxValue | -1 | infinite timeout (no timeout)
// t>0 && t<int.MaxValue | t |
// t>int.MaxValue | int.MaxValue | must not exceed int.MaxValue
if (Int64.MaxValue == timeoutTime) {
return -1; // infinite timeout
}
long msecRemaining = ADP.TimerRemainingMilliseconds(timeoutTime);
if (msecRemaining < 0) {
return 0;
}
if (msecRemaining > (long)Int32.MaxValue) {
return Int32.MaxValue;
}
return (Int32)msecRemaining;
}
static internal long GetTimeoutSeconds(int timeout) {
return GetTimeout((long)timeout * 1000L);
}
static internal long GetTimeout(long timeoutMilliseconds) {
long result;
if (timeoutMilliseconds <= 0) {
result = Int64.MaxValue; // no timeout...
}
else {
try
{
result = checked(ADP.TimerCurrent() + ADP.TimerFromMilliseconds(timeoutMilliseconds));
}
catch (OverflowException)
{
// In case of overflow, set to 'infinite' timeout
result = Int64.MaxValue;
}
}
return result;
}
static internal bool TimeoutHasExpired(long timeoutTime) {
bool result = false;
if (0 != timeoutTime && Int64.MaxValue != timeoutTime) {
result = ADP.TimerHasExpired(timeoutTime);
}
return result;
}
static internal int NullAwareStringLength(string str) {
if (str == null) {
return 0;
}
else {
return str.Length;
}
}
static internal int GetRemainingTimeout(int timeout, long start) {
if (timeout <= 0) {
return timeout;
}
long remaining = ADP.TimerRemainingSeconds(start + ADP.TimerFromSeconds(timeout));
if (remaining <= 0) {
return 1;
}
else {
return checked((int)remaining);
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 PackageManagement.Sdk
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security;
using Resources;
public abstract class Request
{
private Dictionary<string, string[]> _options;
private string[] _packageSources;
#region PackageMangaement Interfaces
public interface IProviderServices
{
bool IsElevated { get; }
IEnumerable<object> FindPackageByCanonicalId(string canonicalId, Request requestObject);
string GetCanonicalPackageId(string providerName, string packageName, string version, string source);
string ParseProviderName(string canonicalPackageId);
string ParsePackageName(string canonicalPackageId);
string ParsePackageVersion(string canonicalPackageId);
string ParsePackageSource(string canonicalPackageId);
void DownloadFile(Uri remoteLocation, string localFilename, Request requestObject);
bool IsSupportedArchive(string localFilename, Request requestObject);
IEnumerable<string> UnpackArchive(string localFilename, string destinationFolder, Request requestObject);
bool Install(string fileName, string additionalArgs, Request requestObject);
bool IsSignedAndTrusted(string filename, Request requestObject);
}
public interface IPackageProvider
{
}
public interface IPackageManagementService
{
int Version { get; }
IEnumerable<string> ProviderNames { get; }
IEnumerable<string> AllProviderNames { get; }
IEnumerable<IPackageProvider> PackageProviders { get; }
IEnumerable<IPackageProvider> SelectProvidersWithFeature(string featureName);
IEnumerable<IPackageProvider> SelectProvidersWithFeature(string featureName, string value);
IEnumerable<IPackageProvider> SelectProviders(string providerName, Request requestObject);
bool RequirePackageProvider(string requestor, string packageProviderName, string minimumVersion, Request requestObject);
}
#endregion
#region core-apis
public abstract dynamic PackageManagementService { get; }
public abstract IProviderServices ProviderServices { get; }
#endregion
#region copy host-apis
/* Synced/Generated code =================================================== */
public abstract bool IsCanceled { get; }
public abstract string GetMessageString(string messageText, string defaultText);
public abstract bool Warning(string messageText);
public abstract bool Error(string id, string category, string targetObjectValue, string messageText);
public abstract bool Message(string messageText);
public abstract bool Verbose(string messageText);
public abstract bool Debug(string messageText);
public abstract int StartProgress(int parentActivityId, string messageText);
public abstract bool Progress(int activityId, int progressPercentage, string messageText);
public abstract bool CompleteProgress(int activityId, bool isSuccessful);
/// <summary>
/// Used by a provider to request what metadata keys were passed from the user
/// </summary>
/// <returns></returns>
public abstract IEnumerable<string> OptionKeys { get; }
/// <summary>
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public abstract IEnumerable<string> GetOptionValues(string key);
public abstract IEnumerable<string> Sources { get; }
public abstract string CredentialUsername { get; }
public abstract SecureString CredentialPassword { get; }
public abstract bool ShouldBootstrapProvider(string requestor, string providerName, string providerVersion, string providerType, string location, string destination);
public abstract bool ShouldContinueWithUntrustedPackageSource(string package, string packageSource);
public abstract bool AskPermission(string permission);
public abstract bool IsInteractive { get; }
public abstract int CallCount { get; }
#endregion
#region copy response-apis
/* Synced/Generated code =================================================== */
/// <summary>
/// Used by a provider to return fields for a SoftwareIdentity.
/// </summary>
/// <param name="fastPath"></param>
/// <param name="name"></param>
/// <param name="version"></param>
/// <param name="versionScheme"></param>
/// <param name="summary"></param>
/// <param name="source"></param>
/// <param name="searchKey"></param>
/// <param name="fullPath"></param>
/// <param name="packageFileName"></param>
/// <returns></returns>
public abstract string YieldSoftwareIdentity(string fastPath, string name, string version, string versionScheme, string summary, string source, string searchKey, string fullPath, string packageFileName);
public abstract string AddMetadata(string name, string value);
public abstract string AddMetadata(string elementPath, string name, string value);
public abstract string AddMetadata(string elementPath, Uri @namespace, string name, string value);
public abstract string AddTagId(string tagId);
public abstract string AddMeta(string elementPath);
public abstract string AddEntity(string name, string regid, string role, string thumbprint);
public abstract string AddLink(Uri referenceUri, string relationship, string mediaType, string ownership, string use, string appliesToMedia, string artifact);
public abstract string AddDependency(string providerName, string packageName, string version, string source, string appliesTo);
public abstract string AddPayload();
public abstract string AddEvidence(DateTime date, string deviceId);
public abstract string AddDirectory(string elementPath, string directoryName, string location, string root, bool isKey);
public abstract string AddFile(string elementPath, string fileName, string location, string root, bool isKey, long size, string version);
public abstract string AddProcess(string elementPath, string processName, int pid);
public abstract string AddResource(string elementPath, string type);
/// <summary>
/// Used by a provider to return fields for a package source (repository)
/// </summary>
/// <param name="name"></param>
/// <param name="location"></param>
/// <param name="isTrusted"></param>
/// <param name="isRegistered"></param>
/// <param name="isValidated"></param>
/// <returns></returns>
public abstract bool YieldPackageSource(string name, string location, bool isTrusted, bool isRegistered, bool isValidated);
/// <summary>
/// Used by a provider to return the fields for a Metadata Definition
/// The cmdlets can use this to supply tab-completion for metadata to the user.
/// </summary>
/// <param name="name">the provider-defined name of the option</param>
/// <param name="expectedType"> one of ['string','int','path','switch']</param>
/// <param name="isRequired">if the parameter is mandatory</param>
/// <returns></returns>
public abstract bool YieldDynamicOption(string name, string expectedType, bool isRequired);
public abstract bool YieldKeyValuePair(string key, string value);
public abstract bool YieldValue(string value);
#endregion
/// <summary>
/// Yield values in a dictionary as key/value pairs. (one pair for each value in each key)
/// </summary>
/// <param name="dictionary"></param>
/// <returns></returns>
public bool Yield(Dictionary<string, string[]> dictionary)
{
return dictionary.All(Yield);
}
public bool Yield(KeyValuePair<string, string[]> pair)
{
if (pair.Value.Length == 0)
{
return YieldKeyValuePair(pair.Key, null);
}
return pair.Value.All(each => YieldKeyValuePair(pair.Key, each));
}
public bool Error(ErrorCategory category, string targetObjectValue, string messageText, params object[] args)
{
return Error(messageText, category.ToString(), targetObjectValue, FormatMessageString(messageText, args));
}
public bool Warning(string messageText, params object[] args)
{
return Warning(FormatMessageString(messageText, args));
}
public bool Message(string messageText, params object[] args)
{
return Message(FormatMessageString(messageText, args));
}
public bool Verbose(string messageText, params object[] args)
{
return Verbose(FormatMessageString(messageText, args));
}
public bool Debug(string messageText, params object[] args)
{
return Debug(FormatMessageString(messageText, args));
}
public int StartProgress(int parentActivityId, string messageText, params object[] args)
{
return StartProgress(parentActivityId, FormatMessageString(messageText, args));
}
public bool Progress(int activityId, int progressPercentage, string messageText, params object[] args)
{
return Progress(activityId, progressPercentage, FormatMessageString(messageText, args));
}
public string GetOptionValue(string name)
{
// get the value from the request
return (GetOptionValues(name) ?? Enumerable.Empty<string>()).LastOrDefault();
}
private static string FixMeFormat(string formatString, object[] args)
{
if (args == null || args.Length == 0)
{
// not really any args, and not really expectng any
return formatString.Replace('{', '\u00ab').Replace('}', '\u00bb');
}
return args.Aggregate(formatString.Replace('{', '\u00ab').Replace('}', '\u00bb'), (current, arg) => current + string.Format(CultureInfo.CurrentCulture, " \u00ab{0}\u00bb", arg));
}
internal string GetMessageStringInternal(string messageText)
{
return Messages.ResourceManager.GetString(messageText);
}
internal string FormatMessageString(string messageText, params object[] args)
{
if (string.IsNullOrEmpty(messageText))
{
return string.Empty;
}
if (args == null)
{
return messageText;
}
if (messageText.StartsWith(Constants.MSGPrefix, true, CultureInfo.CurrentCulture))
{
// check with the caller first, then with the local resources, and fall back to using the messageText itself.
messageText = GetMessageString(messageText.Substring(Constants.MSGPrefix.Length), GetMessageStringInternal(messageText) ?? messageText) ?? GetMessageStringInternal(messageText) ?? messageText;
}
// if it doesn't look like we have the correct number of parameters
// let's return a fix-me-format string.
var c = messageText.ToCharArray().Where(each => each == '{').Count();
if (c < args.Length)
{
return FixMeFormat(messageText, args);
}
return string.Format(CultureInfo.CurrentCulture, messageText, args);
}
public bool YieldDynamicOption(string name, string expectedType, bool isRequired, IEnumerable<string> permittedValues)
{
return YieldDynamicOption(name, expectedType, isRequired) && (permittedValues ?? Enumerable.Empty<string>()).All(each => YieldKeyValuePair(name, each));
}
public Dictionary<string, string[]> Options
{
get
{
return _options ?? (_options = OptionKeys.Where(each => !string.IsNullOrWhiteSpace(each)).ToDictionary(k => k, (k) => (GetOptionValues(k) ?? new string[0]).ToArray()));
}
}
public IEnumerable<string> PackageSources
{
get
{
return _packageSources ?? (_packageSources = (Sources ?? new string[0]).ToArray());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class SendFileTest : FileCleanupTestBase
{
public static IEnumerable<object[]> SendFile_MemberData()
{
foreach (IPAddress listenAt in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback })
{
foreach (bool sendPreAndPostBuffers in new[] { true, false })
{
foreach (int bytesToSend in new[] { 512, 1024, 12345678 })
{
yield return new object[] { listenAt, sendPreAndPostBuffers, bytesToSend };
}
}
}
}
public static IEnumerable<object[]> SendFileSync_MemberData()
{
foreach (object[] memberData in SendFile_MemberData())
{
yield return memberData.Concat(new object[] { true }).ToArray();
yield return memberData.Concat(new object[] { false }).ToArray();
}
}
private string CreateFileToSend(int size, bool sendPreAndPostBuffers, out byte[] preBuffer, out byte[] postBuffer, out Fletcher32 checksum)
{
// Create file to send
var random = new Random();
int fileSize = sendPreAndPostBuffers ? size - 512 : size;
checksum = new Fletcher32();
preBuffer = null;
if (sendPreAndPostBuffers)
{
preBuffer = new byte[256];
random.NextBytes(preBuffer);
checksum.Add(preBuffer, 0, preBuffer.Length);
}
byte[] fileBuffer = new byte[fileSize];
random.NextBytes(fileBuffer);
string path = Path.GetTempFileName();
File.WriteAllBytes(path, fileBuffer);
checksum.Add(fileBuffer, 0, fileBuffer.Length);
postBuffer = null;
if (sendPreAndPostBuffers)
{
postBuffer = new byte[256];
random.NextBytes(postBuffer);
checksum.Add(postBuffer, 0, postBuffer.Length);
}
return path;
}
[Fact]
public void Disposed_ThrowsException()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
s.Dispose();
Assert.Throws<ObjectDisposedException>(() => s.SendFile(null));
Assert.Throws<ObjectDisposedException>(() => s.BeginSendFile(null, null, null));
Assert.Throws<ObjectDisposedException>(() => s.BeginSendFile(null, null, null, TransmitFileOptions.UseDefaultWorkerThread, null, null));
Assert.Throws<ObjectDisposedException>(() => s.EndSendFile(null));
}
}
[Fact]
public void EndSendFile_NullAsyncResult_Throws()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<ArgumentNullException>(() => s.EndSendFile(null));
}
}
[Fact]
public void NotConnected_ThrowsException()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<NotSupportedException>(() => s.SendFile(null));
Assert.Throws<NotSupportedException>(() => s.BeginSendFile(null, null, null));
Assert.Throws<NotSupportedException>(() => s.BeginSendFile(null, null, null, TransmitFileOptions.UseDefaultWorkerThread, null, null));
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(SendFileSync_MemberData))]
public void SendFile_Synchronous(IPAddress listenAt, bool sendPreAndPostBuffers, int bytesToSend, bool forceNonBlocking)
{
const int ListenBacklog = 1;
const int TestTimeout = 30000;
// Create file to send
byte[] preBuffer;
byte[] postBuffer;
Fletcher32 sentChecksum;
string filename = CreateFileToSend(bytesToSend, sendPreAndPostBuffers, out preBuffer, out postBuffer, out sentChecksum);
// Start server
var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
server.BindToAnonymousPort(listenAt);
server.Listen(ListenBacklog);
server.ForceNonBlocking(forceNonBlocking);
int bytesReceived = 0;
var receivedChecksum = new Fletcher32();
var serverThread = new Thread(() =>
{
using (server)
{
Socket remote = server.Accept();
Assert.NotNull(remote);
remote.ForceNonBlocking(forceNonBlocking);
using (remote)
{
var recvBuffer = new byte[256];
while (true)
{
int received = remote.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None);
if (received == 0)
{
break;
}
bytesReceived += received;
receivedChecksum.Add(recvBuffer, 0, received);
}
}
}
});
serverThread.Start();
// Run client
EndPoint clientEndpoint = server.LocalEndPoint;
var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
client.ForceNonBlocking(forceNonBlocking);
client.Connect(clientEndpoint);
using (client)
{
client.SendFile(filename, preBuffer, postBuffer, TransmitFileOptions.UseDefaultWorkerThread);
client.Shutdown(SocketShutdown.Send);
}
Assert.True(serverThread.Join(TestTimeout), "Completed within allowed time");
Assert.Equal(bytesToSend, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
// Clean up the file we created
File.Delete(filename);
}
[Fact]
public async Task SyncSendFileGetsCanceledByDispose()
{
// We try this a couple of times to deal with a timing race: if the Dispose happens
// before the operation is started, the peer won't see a ConnectionReset SocketException and we won't
// see a SocketException either.
int msDelay = 100;
await RetryHelper.ExecuteAsync(async () =>
{
(Socket socket1, Socket socket2) = CreateConnectedSocketPair();
using (socket2)
{
Task socketOperation = Task.Run(() =>
{
// Create a large file that will cause SendFile to block until the peer starts reading.
string filename = GetTestFilePath();
using (var fs = new FileStream(filename, FileMode.CreateNew, FileAccess.Write))
{
fs.SetLength(20 * 1024 * 1024 /* 20MB */);
}
socket1.SendFile(filename);
});
// Wait a little so the operation is started.
await Task.Delay(msDelay);
msDelay *= 2;
Task disposeTask = Task.Run(() => socket1.Dispose());
var cts = new CancellationTokenSource();
Task timeoutTask = Task.Delay(30000, cts.Token);
Assert.NotSame(timeoutTask, await Task.WhenAny(disposeTask, socketOperation, timeoutTask));
cts.Cancel();
await disposeTask;
SocketError? localSocketError = null;
try
{
await socketOperation;
}
catch (SocketException se)
{
localSocketError = se.SocketErrorCode;
}
catch (ObjectDisposedException)
{ }
Assert.Equal(SocketError.ConnectionAborted, localSocketError);
// On OSX, we're unable to unblock the on-going socket operations and
// perform an abortive close.
if (!PlatformDetection.IsOSX)
{
SocketError? peerSocketError = null;
var receiveBuffer = new byte[4096];
while (true)
{
try
{
int received = socket2.Receive(receiveBuffer);
if (received == 0)
{
break;
}
}
catch (SocketException se)
{
peerSocketError = se.SocketErrorCode;
break;
}
}
Assert.Equal(SocketError.ConnectionReset, peerSocketError);
}
}
}, maxAttempts: 10);
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(SendFile_MemberData))]
public async Task SendFile_APM(IPAddress listenAt, bool sendPreAndPostBuffers, int bytesToSend)
{
const int ListenBacklog = 1, TestTimeout = 30000;
// Create file to send
byte[] preBuffer, postBuffer;
Fletcher32 sentChecksum;
string filename = CreateFileToSend(bytesToSend, sendPreAndPostBuffers, out preBuffer, out postBuffer, out sentChecksum);
// Start server
using (var listener = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
listener.BindToAnonymousPort(listenAt);
listener.Listen(ListenBacklog);
int bytesReceived = 0;
var receivedChecksum = new Fletcher32();
Task serverTask = Task.Run(async () =>
{
using (var serverStream = new NetworkStream(await listener.AcceptAsync(), ownsSocket: true))
{
var buffer = new byte[256];
int bytesRead;
while ((bytesRead = await serverStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
bytesReceived += bytesRead;
receivedChecksum.Add(buffer, 0, bytesRead);
}
}
});
Task clientTask = Task.Run(async () =>
{
using (var client = new Socket(listener.LocalEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
await client.ConnectAsync(listener.LocalEndPoint);
await Task.Factory.FromAsync(
(callback, state) => client.BeginSendFile(filename, preBuffer, postBuffer, TransmitFileOptions.UseDefaultWorkerThread, callback, state),
iar => client.EndSendFile(iar),
null);
client.Shutdown(SocketShutdown.Send);
}
});
// Wait for the tasks to complete
await (new[] { serverTask, clientTask }).WhenAllOrAnyFailed(TestTimeout);
// Validate the results
Assert.Equal(bytesToSend, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
}
// Clean up the file we created
File.Delete(filename);
}
protected static (Socket, Socket) CreateConnectedSocketPair()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(listener.LocalEndPoint);
Socket server = listener.Accept();
return (client, server);
}
}
}
}
| |
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Tests.Serialization
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Context;
using Magnum.TestFramework;
using MassTransit.Serialization;
using MassTransit.Services.Subscriptions.Messages;
using NUnit.Framework;
[TestFixture(typeof(XmlMessageSerializer))]
[TestFixture(typeof(JsonMessageSerializer))]
[TestFixture(typeof(BsonMessageSerializer))]
[TestFixture(typeof(VersionOneXmlMessageSerializer))]
[TestFixture(typeof(BinaryMessageSerializer))]
public class MoreSerialization_Specs<TSerializer> :
SerializationSpecificationBase<TSerializer> where TSerializer : IMessageSerializer, new()
{
[Serializable]
public class ContainerClass
{
public IList<OuterClass> Elements { get; set; }
public bool Equals(ContainerClass other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
if (ReferenceEquals(other.Elements, Elements)) return true;
if (other.Elements == null && Elements != null) return false;
if (other.Elements != null && Elements == null) return false;
if (other.Elements != null && Elements != null)
{
if (other.Elements.Count != Elements.Count) return false;
for (int i = 0; i < Elements.Count; i++)
{
if (!Equals(other.Elements[i], Elements[i]))
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (ContainerClass)) return false;
return Equals((ContainerClass) obj);
}
public override int GetHashCode()
{
return (Elements != null ? Elements.GetHashCode() : 0);
}
}
[Serializable]
public class DictionaryContainerClass
{
public IDictionary<string, OuterClass> Elements { get; set; }
public DictionaryContainerClass()
{
Elements = new Dictionary<string, OuterClass>();
}
public bool Equals(DictionaryContainerClass other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
if (ReferenceEquals(other.Elements, Elements)) return true;
if (other.Elements == null && Elements != null)
{
Trace.WriteLine("other element was null");
return false;
}
if (other.Elements != null && Elements == null)
{
Trace.WriteLine("other element was not null");
return false;
}
if (other.Elements != null && Elements != null)
{
if (other.Elements.Count != Elements.Count) return false;
foreach (KeyValuePair<string, OuterClass> pair in Elements)
{
if (!other.Elements.ContainsKey(pair.Key))
return false;
if (!Equals(pair.Value, other.Elements[pair.Key]))
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(DictionaryContainerClass)) return false;
return Equals((DictionaryContainerClass)obj);
}
public override int GetHashCode()
{
return (Elements != null ? Elements.GetHashCode() : 0);
}
}
[Serializable]
public class PrimitiveArrayClass
{
public PrimitiveArrayClass()
{
Values = new int[] {};
}
public int[] Values { get; set; }
public bool Equals(PrimitiveArrayClass other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
if (ReferenceEquals(other.Values, Values)) return true;
if (other.Values == null && Values != null) return false;
if (other.Values != null && Values == null) return false;
if (other.Values != null && Values != null)
{
if (other.Values.Length != Values.Length) return false;
for (int i = 0; i < Values.Length; i++)
{
if (!Equals(other.Values[i], Values[i]))
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (PrimitiveArrayClass)) return false;
return Equals((PrimitiveArrayClass) obj);
}
public override int GetHashCode()
{
return (Values != null ? Values.GetHashCode() : 0);
}
}
[Serializable]
public class GenericArrayClass<T>
{
public T[] Values { get; set; }
public bool Equals(GenericArrayClass<T> other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
if (ReferenceEquals(other.Values, Values)) return true;
if (other.Values == null && Values != null) return false;
if (other.Values != null && Values == null) return false;
if (other.Values != null && Values != null)
{
if (other.Values.Length != Values.Length) return false;
for (int i = 0; i < Values.Length; i++)
{
if (!Equals(other.Values[i], Values[i]))
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(GenericArrayClass<T>)) return false;
return Equals((GenericArrayClass<T>)obj);
}
public override int GetHashCode()
{
return (Values != null ? Values.GetHashCode() : 0);
}
}
[Serializable]
public class OuterClass
{
public InnerClass Inner { get; set; }
public bool Equals(OuterClass other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Inner, Inner);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (OuterClass)) return false;
return Equals((OuterClass) obj);
}
public override int GetHashCode()
{
return (Inner != null ? Inner.GetHashCode() : 0);
}
}
[Serializable]
public class InnerClass
{
public string Name { get; set; }
public bool Equals(InnerClass other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Name, Name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (InnerClass)) return false;
return Equals((InnerClass) obj);
}
public override int GetHashCode()
{
return (Name != null ? Name.GetHashCode() : 0);
}
}
[Serializable]
public class EmptyClass
{
public bool Equals(EmptyClass other)
{
return !ReferenceEquals(null, other);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (EmptyClass)) return false;
return Equals((EmptyClass) obj);
}
public override int GetHashCode()
{
return 0;
}
}
[Test]
public void Should_serialize_an_empty_message()
{
byte[] serializedMessageData;
var serializer = new TSerializer();
var message = new SubscriptionRefresh(Enumerable.Empty<SubscriptionInformation>());
using (var output = new MemoryStream())
{
serializer.Serialize(output, new SendContext<SubscriptionRefresh>(message));
serializedMessageData = output.ToArray();
Trace.WriteLine(Encoding.UTF8.GetString(serializedMessageData));
}
using (var input = new MemoryStream(serializedMessageData))
{
var receiveContext = ReceiveContext.FromBodyStream(input);
serializer.Deserialize(receiveContext);
IConsumeContext<SubscriptionRefresh> context;
receiveContext.TryGetContext(out context).ShouldBeTrue();
context.ShouldNotBeNull();
context.Message.Subscriptions.Count.ShouldEqual(message.Subscriptions.Count);
}
}
[Test]
public void Should_serialize_a_message_with_one_list_item()
{
byte[] serializedMessageData;
var serializer = new TSerializer();
var message = new SubscriptionRefresh(new[]{new SubscriptionInformation(Guid.NewGuid(),1,typeof(object),new Uri("http://localhost/"))});
using (var output = new MemoryStream())
{
serializer.Serialize(output, new SendContext<SubscriptionRefresh>(message));
serializedMessageData = output.ToArray();
Trace.WriteLine(Encoding.UTF8.GetString(serializedMessageData));
}
using (var input = new MemoryStream(serializedMessageData))
{
var receiveContext = ReceiveContext.FromBodyStream(input);
serializer.Deserialize(receiveContext);
IConsumeContext<SubscriptionRefresh> context;
receiveContext.TryGetContext(out context).ShouldBeTrue();
context.ShouldNotBeNull();
context.Message.Subscriptions.Count.ShouldEqual(message.Subscriptions.Count);
}
}
[Test]
public void A_collection_of_objects_should_be_properly_serialized()
{
ContainerClass message = new ContainerClass
{
Elements = new List<OuterClass>
{
new OuterClass
{
Inner = new InnerClass {Name = "Chris"},
},
new OuterClass
{
Inner = new InnerClass {Name = "David"},
},
}
};
TestSerialization(message);
}
[Test]
public void A_dictionary_of_objects_should_be_properly_serialized()
{
DictionaryContainerClass message = new DictionaryContainerClass
{
Elements = new Dictionary<string, OuterClass>
{
{"Chris", new OuterClass{Inner = new InnerClass {Name = "Chris"}}},
{"David", new OuterClass{Inner = new InnerClass {Name = "David"}}},
}
};
TestSerialization(message);
}
[Test]
public void A_dictionary_of_one_objects_should_be_properly_serialized()
{
DictionaryContainerClass message = new DictionaryContainerClass
{
Elements = new Dictionary<string, OuterClass>
{
{"David", new OuterClass{Inner = new InnerClass {Name = "David"}}},
}
};
TestSerialization(message);
}
[Test]
public void A_dictionary_of_no_objects_should_be_properly_serialized()
{
DictionaryContainerClass message = new DictionaryContainerClass
{
Elements = new Dictionary<string, OuterClass>
{
}
};
TestSerialization(message);
}
[Test]
public void A_primitive_array_of_objects_should_be_properly_serialized()
{
PrimitiveArrayClass message = new PrimitiveArrayClass
{
Values = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
};
TestSerialization(message);
}
[Test]
public void A_primitive_array_of_objects_with_one_element_should_be_properly_serialized()
{
var message = new PrimitiveArrayClass
{
Values = new[] { 1 }
};
TestSerialization(message);
}
[Test]
public void A_primitive_array_of_objects_with_no_elements_should_be_properly_serialized()
{
var message = new PrimitiveArrayClass
{
Values = new int[] { }
};
TestSerialization(message);
}
[Test]
public void An_empty_class_should_not_break_the_mold()
{
EmptyClass message = new EmptyClass();
TestSerialization(message);
}
[Test]
public void A_private_setter_should_be_serializable()
{
const string expected = "Dr. Cox";
PrivateSetter message = new PrivateSetter(expected);
TestSerialization(message);
}
[Serializable]
public class EnumClass
{
public SomeEnum Setting { get; set; }
public bool Equals(EnumClass other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Setting, Setting);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (EnumClass)) return false;
return Equals((EnumClass) obj);
}
public override int GetHashCode()
{
return Setting.GetHashCode();
}
}
[Test]
public void An_enumeration_should_be_serializable()
{
EnumClass message = new EnumClass {Setting = SomeEnum.Second};
TestSerialization(message);
}
[Test]
public void An_empty_array_of_objects_should_be_properly_serialized()
{
PrimitiveArrayClass message = new PrimitiveArrayClass
{
Values = new int[] {}
};
TestSerialization(message);
}
[Test]
public void An_array_of_objects_should_be_properly_serialized()
{
var message = new GenericArrayClass<InnerClass>
{
Values = new[]
{
new InnerClass { Name = "Chris" },
new InnerClass { Name = "David" },
}
};
TestSerialization(message);
}
[Test]
public void A_nested_object_should_be_properly_serialized()
{
OuterClass message = new OuterClass
{
Inner = new InnerClass {Name = "Chris"},
};
TestSerialization(message);
}
}
[Serializable]
public class PrivateSetter
{
public PrivateSetter(string name)
{
Name = name;
}
protected PrivateSetter()
{
}
public string Name { get; private set; }
public bool Equals(PrivateSetter other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Name, Name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (PrivateSetter)) return false;
return Equals((PrivateSetter) obj);
}
public override int GetHashCode()
{
return (Name != null ? Name.GetHashCode() : 0);
}
}
public enum SomeEnum
{
First,
Second,
Third,
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Orders.Fills;
using QuantConnect.Securities;
using static QuantConnect.StringExtensions;
namespace QuantConnect.Orders.Fees
{
/// <summary>
/// Provides the default implementation of <see cref="IFeeModel"/>
/// </summary>
public class InteractiveBrokersFeeModel : FeeModel
{
private readonly decimal _forexCommissionRate;
private readonly decimal _forexMinimumOrderFee;
// option commission function takes number of contracts and the size of the option premium and returns total commission
private readonly Dictionary<string, Func<decimal, decimal, CashAmount>> _optionFee =
new Dictionary<string, Func<decimal, decimal, CashAmount>>();
/// <summary>
/// Reference at https://www.interactivebrokers.com/en/index.php?f=commission&p=futures1
/// </summary>
private readonly Dictionary<string, Func<Security, CashAmount>> _futureFee =
// IB fee + exchange fee
new()
{
{ Market.USA, UnitedStatesFutureFees },
{ Market.HKFE, HongKongFutureFees }
};
/// <summary>
/// Initializes a new instance of the <see cref="ImmediateFillModel"/>
/// </summary>
/// <param name="monthlyForexTradeAmountInUSDollars">Monthly FX dollar volume traded</param>
/// <param name="monthlyOptionsTradeAmountInContracts">Monthly options contracts traded</param>
public InteractiveBrokersFeeModel(decimal monthlyForexTradeAmountInUSDollars = 0, decimal monthlyOptionsTradeAmountInContracts = 0)
{
ProcessForexRateSchedule(monthlyForexTradeAmountInUSDollars, out _forexCommissionRate, out _forexMinimumOrderFee);
Func<decimal, decimal, CashAmount> optionsCommissionFunc;
ProcessOptionsRateSchedule(monthlyOptionsTradeAmountInContracts, out optionsCommissionFunc);
// only USA for now
_optionFee.Add(Market.USA, optionsCommissionFunc);
}
/// <summary>
/// Gets the order fee associated with the specified order. This returns the cost
/// of the transaction in the account currency
/// </summary>
/// <param name="parameters">A <see cref="OrderFeeParameters"/> object
/// containing the security and order</param>
/// <returns>The cost of the order in units of the account currency</returns>
public override OrderFee GetOrderFee(OrderFeeParameters parameters)
{
var order = parameters.Order;
var security = parameters.Security;
// Option exercise for equity options is free of charge
if (order.Type == OrderType.OptionExercise)
{
var optionOrder = (OptionExerciseOrder)order;
// For Futures Options, contracts are charged the standard commission at expiration of the contract.
// Read more here: https://www1.interactivebrokers.com/en/index.php?f=14718#trading-related-fees
if (optionOrder.Symbol.ID.SecurityType == SecurityType.Option)
{
return OrderFee.Zero;
}
}
decimal feeResult;
string feeCurrency;
var market = security.Symbol.ID.Market;
switch (security.Type)
{
case SecurityType.Forex:
// get the total order value in the account currency
var totalOrderValue = order.GetValue(security);
var fee = Math.Abs(_forexCommissionRate*totalOrderValue);
feeResult = Math.Max(_forexMinimumOrderFee, fee);
// IB Forex fees are all in USD
feeCurrency = Currencies.USD;
break;
case SecurityType.Option:
case SecurityType.IndexOption:
Func<decimal, decimal, CashAmount> optionsCommissionFunc;
if (!_optionFee.TryGetValue(market, out optionsCommissionFunc))
{
throw new KeyNotFoundException($"InteractiveBrokersFeeModel(): unexpected option Market {market}");
}
// applying commission function to the order
var optionFee = optionsCommissionFunc(order.AbsoluteQuantity, order.Price);
feeResult = optionFee.Amount;
feeCurrency = optionFee.Currency;
break;
case SecurityType.Future:
case SecurityType.FutureOption:
// The futures options fee model is exactly the same as futures' fees on IB.
if (market == Market.Globex || market == Market.NYMEX
|| market == Market.CBOT || market == Market.ICE
|| market == Market.CFE || market == Market.COMEX
|| market == Market.CME || market == Market.NYSELIFFE)
{
// just in case...
market = Market.USA;
}
if (!_futureFee.TryGetValue(market, out var feeRatePerContractFunc))
{
throw new KeyNotFoundException($"InteractiveBrokersFeeModel(): unexpected future Market {market}");
}
var feeRatePerContract = feeRatePerContractFunc(security);
feeResult = order.AbsoluteQuantity * feeRatePerContract.Amount;
feeCurrency = feeRatePerContract.Currency;
break;
case SecurityType.Equity:
EquityFee equityFee;
switch (market)
{
case Market.USA:
equityFee = new EquityFee(Currencies.USD, feePerShare: 0.005m, minimumFee: 1, maximumFeeRate: 0.005m);
break;
case Market.India:
equityFee = new EquityFee(Currencies.INR, feePerShare: 0.01m, minimumFee: 6, maximumFeeRate: 20);
break;
default:
throw new KeyNotFoundException($"InteractiveBrokersFeeModel(): unexpected equity Market {market}");
}
var tradeValue = Math.Abs(order.GetValue(security));
//Per share fees
var tradeFee = equityFee.FeePerShare * order.AbsoluteQuantity;
//Maximum Per Order: equityFee.MaximumFeeRate
//Minimum per order. $equityFee.MinimumFee
var maximumPerOrder = equityFee.MaximumFeeRate * tradeValue;
if (tradeFee < equityFee.MinimumFee)
{
tradeFee = equityFee.MinimumFee;
}
else if (tradeFee > maximumPerOrder)
{
tradeFee = maximumPerOrder;
}
feeCurrency = equityFee.Currency;
//Always return a positive fee.
feeResult = Math.Abs(tradeFee);
break;
default:
// unsupported security type
throw new ArgumentException(Invariant($"Unsupported security type: {security.Type}"));
}
return new OrderFee(new CashAmount(
feeResult,
feeCurrency));
}
/// <summary>
/// Determines which tier an account falls into based on the monthly trading volume
/// </summary>
private static void ProcessForexRateSchedule(decimal monthlyForexTradeAmountInUSDollars, out decimal commissionRate, out decimal minimumOrderFee)
{
const decimal bp = 0.0001m;
if (monthlyForexTradeAmountInUSDollars <= 1000000000) // 1 billion
{
commissionRate = 0.20m * bp;
minimumOrderFee = 2.00m;
}
else if (monthlyForexTradeAmountInUSDollars <= 2000000000) // 2 billion
{
commissionRate = 0.15m * bp;
minimumOrderFee = 1.50m;
}
else if (monthlyForexTradeAmountInUSDollars <= 5000000000) // 5 billion
{
commissionRate = 0.10m * bp;
minimumOrderFee = 1.25m;
}
else
{
commissionRate = 0.08m * bp;
minimumOrderFee = 1.00m;
}
}
/// <summary>
/// Determines which tier an account falls into based on the monthly trading volume
/// </summary>
private static void ProcessOptionsRateSchedule(decimal monthlyOptionsTradeAmountInContracts, out Func<decimal, decimal, CashAmount> optionsCommissionFunc)
{
if (monthlyOptionsTradeAmountInContracts <= 10000)
{
optionsCommissionFunc = (orderSize, premium) =>
{
var commissionRate = premium >= 0.1m ?
0.7m :
(0.05m <= premium && premium < 0.1m ? 0.5m : 0.25m);
return new CashAmount(Math.Max(orderSize * commissionRate, 1.0m), Currencies.USD);
};
}
else if (monthlyOptionsTradeAmountInContracts <= 50000)
{
optionsCommissionFunc = (orderSize, premium) =>
{
var commissionRate = premium >= 0.05m ? 0.5m : 0.25m;
return new CashAmount(Math.Max(orderSize * commissionRate, 1.0m), Currencies.USD);
};
}
else if (monthlyOptionsTradeAmountInContracts <= 100000)
{
optionsCommissionFunc = (orderSize, premium) =>
{
var commissionRate = 0.25m;
return new CashAmount(Math.Max(orderSize * commissionRate, 1.0m), Currencies.USD);
};
}
else
{
optionsCommissionFunc = (orderSize, premium) =>
{
var commissionRate = 0.15m;
return new CashAmount(Math.Max(orderSize * commissionRate, 1.0m), Currencies.USD);
};
}
}
private static CashAmount UnitedStatesFutureFees(Security security)
{
return new CashAmount(0.85m + 1, Currencies.USD);
}
/// <summary>
/// See https://www.hkex.com.hk/Services/Rules-and-Forms-and-Fees/Fees/Listed-Derivatives/Trading/Transaction?sc_lang=en
/// </summary>
private static CashAmount HongKongFutureFees(Security security)
{
if (security.Symbol.ID.Symbol.Equals("HSI", StringComparison.InvariantCultureIgnoreCase))
{
// IB fee + exchange fee
return new CashAmount(30 + 10, Currencies.HKD);
}
decimal ibFeePerContract;
switch (security.QuoteCurrency.Symbol)
{
case Currencies.CNH:
ibFeePerContract = 13;
break;
case Currencies.HKD:
ibFeePerContract = 20;
break;
case Currencies.USD:
ibFeePerContract = 2.40m;
break;
default:
throw new ArgumentException($"Unexpected quote currency {security.QuoteCurrency.Symbol} for Hong Kong futures exchange");
}
// let's add a 50% extra charge for exchange fees
return new CashAmount(ibFeePerContract * 1.5m, security.QuoteCurrency.Symbol);
}
/// <summary>
/// Helper class to handle IB Equity fees
/// </summary>
private class EquityFee
{
public string Currency { get; }
public decimal FeePerShare { get; }
public decimal MinimumFee { get; }
public decimal MaximumFeeRate { get; }
public EquityFee(string currency,
decimal feePerShare,
decimal minimumFee,
decimal maximumFeeRate)
{
Currency = currency;
FeePerShare = feePerShare;
MinimumFee = minimumFee;
MaximumFeeRate = maximumFeeRate;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Postman.WebApi.MsBuildTask.SampleGeneration
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using VolumetricLines.Utils;
namespace VolumetricLines
{
/// <summary>
/// Render a line strip of volumetric lines
///
/// Based on the Volumetric lines algorithm by Sebastien Hillaire
/// http://sebastien.hillaire.free.fr/index.php?option=com_content&view=article&id=57&Itemid=74
///
/// Thread in the Unity3D Forum:
/// http://forum.unity3d.com/threads/181618-Volumetric-lines
///
/// Unity3D port by Johannes Unterguggenberger
/// [email protected]
///
/// Thanks to Michael Probst for support during development.
///
/// Thanks for bugfixes and improvements to Unity Forum User "Mistale"
/// http://forum.unity3d.com/members/102350-Mistale
///
/// /// Shader code optimization and cleanup by Lex Darlog (aka DRL)
/// http://forum.unity3d.com/members/lex-drl.67487/
///
/// </summary>
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(Renderer))]
[ExecuteInEditMode]
public class VolumetricLineStripBehavior : MonoBehaviour
{
#region member variables
/// <summary>
/// Set to true to change the material's color to the color specified with "Line Color"
/// </summary>
[SerializeField]
[HideInInspector]
private bool m_setLineColorAtStart;
/// <summary>
/// The material is set to this color in Start() if "Set Material Color" is set to true
/// </summary>
[SerializeField]
[HideInInspector]
private Color m_lineColor;
/// <summary>
/// The width of the line
/// </summary>
[SerializeField]
[HideInInspector]
private float m_lineWidth;
/// <summary>
/// The vertices of the line
/// </summary>
[SerializeField]
private Vector3[] m_lineVertices;
#endregion
#region properties shown in inspector via ExposeProperty
/// <summary>
/// Set to true to change the line material's color to the color specified via 'LineColor' property.
/// Set to false to leave the color like in the original material.
/// Does not have any effect after Start() has been called.
/// </summary>
[ExposeProperty]
public bool SetLineColorAtStart
{
get { return m_setLineColorAtStart; }
set { m_setLineColorAtStart = value; }
}
/// <summary>
/// Gets or sets the color of the line. This can be used during runtime
/// regardless of SetLinePropertiesAtStart-property's value.
/// </summary>
[ExposeProperty]
public Color LineColor
{
get { return m_lineColor; }
set
{
m_lineColor = value;
GetComponent<Renderer>().sharedMaterial.color = m_lineColor;
}
}
/// <summary>
/// Gets or sets the width of the line. This can be used during runtime
/// regardless of SetLineColorAtStart-propertie's value.
/// </summary>
[ExposeProperty]
public float LineWidth
{
get { return m_lineWidth; }
set
{
m_lineWidth = value;
GetComponent<Renderer>().sharedMaterial.SetFloat("_LineWidth", m_lineWidth);
}
}
#endregion
/// <summary>
/// Gets the vertices of this line strip
/// </summary>
public Vector3[] LineVertices
{
get { return m_lineVertices; }
}
#region Unity callbacks and public methods
void Start ()
{
UpdateLineVertices(m_lineVertices);
// Need to duplicate the material, otherwise multiple volume lines would interfere
GetComponent<Renderer>().material = GetComponent<Renderer>().sharedMaterial;
if (m_setLineColorAtStart)
{
GetComponent<Renderer>().sharedMaterial.color = m_lineColor;
GetComponent<Renderer>().sharedMaterial.SetFloat("_LineWidth", m_lineWidth);
}
else
{
m_lineColor = GetComponent<Renderer>().sharedMaterial.color;
m_lineWidth = GetComponent<Renderer>().sharedMaterial.GetFloat("_LineWidth");
}
GetComponent<Renderer>().sharedMaterial.SetFloat("_LineScale", transform.GetGlobalUniformScaleForLineWidth());
}
/// <summary>
/// Updates the vertices of this VolumetricLineStrip.
/// This is an expensive operation.
/// </summary>
/// <param name="m_newSetOfVertices">M_new set of vertices.</param>
public void UpdateLineVertices(Vector3[] m_newSetOfVertices)
{
if (m_newSetOfVertices.Length < 3)
{
Debug.LogError("Add at least 3 vertices to the VolumetricLineStrip");
return;
}
m_lineVertices = m_newSetOfVertices;
// fill vertex positions, and indices
// 2 for each position, + 2 for the start, + 2 for the end
Vector3[] vertexPositions = new Vector3[m_lineVertices.Length * 2 + 4];
// there are #vertices - 2 faces, and 3 indices each
int[] indices = new int[(m_lineVertices.Length * 2 + 2) * 3];
int v = 0;
int x = 0;
vertexPositions[v++] = m_lineVertices[0];
vertexPositions[v++] = m_lineVertices[0];
for (int i=0; i < m_lineVertices.Length; ++i)
{
vertexPositions[v++] = m_lineVertices[i];
vertexPositions[v++] = m_lineVertices[i];
indices[x++] = v - 2;
indices[x++] = v - 3;
indices[x++] = v - 4;
indices[x++] = v - 1;
indices[x++] = v - 2;
indices[x++] = v - 3;
}
vertexPositions[v++] = m_lineVertices[m_lineVertices.Length - 1];
vertexPositions[v++] = m_lineVertices[m_lineVertices.Length - 1];
indices[x++] = v - 2;
indices[x++] = v - 3;
indices[x++] = v - 4;
indices[x++] = v - 1;
indices[x++] = v - 2;
indices[x++] = v - 3;
// fill texture coordinates and vertex offsets
Vector2[] texCoords = new Vector2[vertexPositions.Length];
Vector2[] vertexOffsets = new Vector2[vertexPositions.Length];
int t = 0;
int o = 0;
texCoords[t++] = new Vector2(1.0f, 0.0f);
texCoords[t++] = new Vector2(1.0f, 1.0f);
texCoords[t++] = new Vector2(0.5f, 0.0f);
texCoords[t++] = new Vector2(0.5f, 1.0f);
vertexOffsets[o++] = new Vector2(1.0f, -1.0f);
vertexOffsets[o++] = new Vector2(1.0f, 1.0f);
vertexOffsets[o++] = new Vector2(0.0f, -1.0f);
vertexOffsets[o++] = new Vector2(0.0f, 1.0f);
for (int i=1; i < m_lineVertices.Length - 1; ++i)
{
if ((i & 0x1) == 0x1)
{
texCoords[t++] = new Vector2(0.5f, 0.0f);
texCoords[t++] = new Vector2(0.5f, 1.0f);
}
else
{
texCoords[t++] = new Vector2(0.5f, 0.0f);
texCoords[t++] = new Vector2(0.5f, 1.0f);
}
vertexOffsets[o++] = new Vector2(0.0f, 1.0f);
vertexOffsets[o++] = new Vector2(0.0f, -1.0f);
}
texCoords[t++] = new Vector2(0.5f, 0.0f);
texCoords[t++] = new Vector2(0.5f, 1.0f);
texCoords[t++] = new Vector2(0.0f, 0.0f);
texCoords[t++] = new Vector2(0.0f, 1.0f);
vertexOffsets[o++] = new Vector2(0.0f, 1.0f);
vertexOffsets[o++] = new Vector2(0.0f, -1.0f);
vertexOffsets[o++] = new Vector2(1.0f, 1.0f);
vertexOffsets[o++] = new Vector2(1.0f, -1.0f);
// fill previous and next positions
Vector3[] prevPositions = new Vector3[vertexPositions.Length];
Vector4[] nextPositions = new Vector4[vertexPositions.Length];
int p = 0;
int n = 0;
prevPositions[p++] = m_lineVertices[1];
prevPositions[p++] = m_lineVertices[1];
prevPositions[p++] = m_lineVertices[1];
prevPositions[p++] = m_lineVertices[1];
nextPositions[n++] = m_lineVertices[1];
nextPositions[n++] = m_lineVertices[1];
nextPositions[n++] = m_lineVertices[1];
nextPositions[n++] = m_lineVertices[1];
for (int i=1; i < m_lineVertices.Length - 1; ++i)
{
prevPositions[p++] = m_lineVertices[i-1];
prevPositions[p++] = m_lineVertices[i-1];
nextPositions[n++] = m_lineVertices[i+1];
nextPositions[n++] = m_lineVertices[i+1];
}
prevPositions[p++] = m_lineVertices[m_lineVertices.Length - 2];
prevPositions[p++] = m_lineVertices[m_lineVertices.Length - 2];
prevPositions[p++] = m_lineVertices[m_lineVertices.Length - 2];
prevPositions[p++] = m_lineVertices[m_lineVertices.Length - 2];
nextPositions[n++] = m_lineVertices[m_lineVertices.Length - 2];
nextPositions[n++] = m_lineVertices[m_lineVertices.Length - 2];
nextPositions[n++] = m_lineVertices[m_lineVertices.Length - 2];
nextPositions[n++] = m_lineVertices[m_lineVertices.Length - 2];
// Need to set vertices before assigning new Mesh to the MeshFilter's mesh property
Mesh mesh = new Mesh();
mesh.vertices = vertexPositions;
mesh.normals = prevPositions;
mesh.tangents = nextPositions;
mesh.uv = texCoords;
mesh.uv2 = vertexOffsets;
mesh.SetIndices(indices, MeshTopology.Triangles, 0);
mesh.RecalculateBounds();
GetComponent<MeshFilter>().mesh = mesh;
}
void Update()
{
if (transform.hasChanged)
{
GetComponent<Renderer>().sharedMaterial.SetFloat("_LineScale", transform.GetGlobalUniformScaleForLineWidth());
}
}
void OnDrawGizmos()
{
Gizmos.color = Color.green;
for (int i=0; i < m_lineVertices.Length - 1; ++i)
{
Gizmos.DrawLine(gameObject.transform.TransformPoint(m_lineVertices[i]), gameObject.transform.TransformPoint(m_lineVertices[i+1]));
}
}
#endregion
}
}
| |
namespace Nancy.Authentication.Forms.Tests
{
using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading;
using FakeItEasy;
using Nancy.Bootstrapper;
using Nancy.Cryptography;
using Nancy.Helpers;
using Nancy.Tests;
using Nancy.Tests.Fakes;
using Xunit;
public class FormsAuthenticationFixture
{
private FormsAuthenticationConfiguration config;
private FormsAuthenticationConfiguration secureConfig;
private FormsAuthenticationConfiguration domainPathConfig;
private NancyContext context;
private Guid userGuid;
private string validCookieValue =
"C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9";
private string cookieWithNoHmac =
"k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9";
private string cookieWithEmptyHmac =
"k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9";
private string cookieWithInvalidHmac =
"C+QzbqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9";
private string cookieWithBrokenEncryptedData =
"C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3spwI0jB0KeVY9";
private CryptographyConfiguration cryptographyConfiguration;
private string domain = ".nancyfx.org";
private string path = "/";
public FormsAuthenticationFixture()
{
this.cryptographyConfiguration = new CryptographyConfiguration(
new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)),
new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)));
this.config = new FormsAuthenticationConfiguration()
{
CryptographyConfiguration = this.cryptographyConfiguration,
RedirectUrl = "/login",
UserMapper = A.Fake<IUserMapper>(),
RequiresSSL = false
};
this.secureConfig = new FormsAuthenticationConfiguration()
{
CryptographyConfiguration = this.cryptographyConfiguration,
RedirectUrl = "/login",
UserMapper = A.Fake<IUserMapper>(),
RequiresSSL = true
};
this.domainPathConfig = new FormsAuthenticationConfiguration()
{
CryptographyConfiguration = this.cryptographyConfiguration,
RedirectUrl = "/login",
UserMapper = A.Fake<IUserMapper>(),
RequiresSSL = false,
Domain = domain,
Path = path
};
this.context = new NancyContext
{
Request = new Request(
"GET",
new Url { Scheme = "http", BasePath = "/testing", HostName = "test.com", Path = "test" })
};
this.userGuid = new Guid("3D97EB33-824A-4173-A2C1-633AC16C1010");
}
[Fact]
public void Should_throw_with_null_application_pipelines_passed_to_enable()
{
var result = Record.Exception(() => FormsAuthentication.Enable((IPipelines)null, this.config));
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_with_null_config_passed_to_enable()
{
var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), null));
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_with_invalid_config_passed_to_enable()
{
var fakeConfig = A.Fake<FormsAuthenticationConfiguration>();
A.CallTo(() => fakeConfig.IsValid).Returns(false);
var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), fakeConfig));
result.ShouldBeOfType(typeof(ArgumentException));
}
[Fact]
public void Should_add_a_pre_and_post_hook_when_enabled()
{
var pipelines = A.Fake<IPipelines>();
FormsAuthentication.Enable(pipelines, this.config);
A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_add_a_pre_hook_but_not_a_post_hook_when_DisableRedirect_is_true()
{
var pipelines = A.Fake<IPipelines>();
this.config.DisableRedirect = true;
FormsAuthentication.Enable(pipelines, this.config);
A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored))
.MustNotHaveHappened();
}
[Fact]
public void Should_return_redirect_response_when_user_logs_in_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
}
[Fact]
public void Should_return_ok_response_when_user_logs_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.OK);
}
[Fact]
public void Should_have_authentication_cookie_in_login_response_when_logging_in_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue();
}
[Fact]
public void Should_have_authentication_cookie_in_login_response_when_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_httponly_when_logging_in_with_redirect()
{
//Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
//When
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
//Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.HttpOnly.ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_httponly_when_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.HttpOnly.ShouldBeTrue();
}
[Fact]
public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.Expires.ShouldBeNull();
}
[Fact]
public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.Expires.ShouldBeNull();
}
[Fact]
public void Should_set_expiry_date_if_one_specified_when_logging_in_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1));
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.Expires.ShouldNotBeNull();
}
[Fact]
public void Should_set_expiry_date_if_one_specified_when_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1));
// Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.Expires.ShouldNotBeNull();
}
[Fact]
public void Should_encrypt_cookie_when_logging_in_with_redirect()
{
var mockEncrypter = A.Fake<IEncryptionProvider>();
this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider);
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1));
A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_encrypt_cookie_when_logging_in_without_redirect()
{
// Given
var mockEncrypter = A.Fake<IEncryptionProvider>();
this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider);
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1));
// Then
A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_with_redirect()
{
var fakeEncrypter = A.Fake<IEncryptionProvider>();
var fakeCryptoText = "FakeText";
A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored))
.Returns(fakeCryptoText);
var mockHmac = A.Fake<IHmacProvider>();
this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac);
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1));
A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_without_redirect()
{
// Given
var fakeEncrypter = A.Fake<IEncryptionProvider>();
var fakeCryptoText = "FakeText";
A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored))
.Returns(fakeCryptoText);
var mockHmac = A.Fake<IHmacProvider>();
this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac);
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1));
// Then
A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_return_redirect_response_when_user_logs_out_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/");
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
}
[Fact]
public void Should_return_ok_response_when_user_logs_out_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.LogOutResponse();
// Then
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.OK);
}
[Fact]
public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/");
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Value.ShouldBeEmpty();
cookie.Expires.ShouldNotBeNull();
(cookie.Expires < DateTime.Now).ShouldBeTrue();
}
[Fact]
public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.LogOutResponse();
// Then
var cookie = result.Cookies.First(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName);
cookie.Value.ShouldBeEmpty();
cookie.Expires.ShouldNotBeNull();
(cookie.Expires < DateTime.Now).ShouldBeTrue();
}
[Fact]
public void Should_get_username_from_mapping_service_with_valid_cookie()
{
var fakePipelines = new Pipelines();
var mockMapper = A.Fake<IUserMapper>();
this.config.UserMapper = mockMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue);
fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
A.CallTo(() => mockMapper.GetUserFromIdentifier(this.userGuid, this.context))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_set_user_in_context_with_valid_cookie()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob"));
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeSameAs(fakeUser);
}
[Fact]
public void Should_not_set_user_in_context_with_empty_cookie()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob"));
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, string.Empty);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_not_set_user_in_context_with_invalid_hmac()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob"));
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithInvalidHmac);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_not_set_user_in_context_with_empty_hmac()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob"));
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithEmptyHmac);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_not_set_user_in_context_with_no_hmac()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob"));
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithNoHmac);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_not_set_username_in_context_with_broken_encryption_data()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new ClaimsPrincipal(new GenericIdentity("Bob"));
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithBrokenEncryptedData);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_retain_querystring_when_redirecting_to_login_page()
{
// Given
var fakePipelines = new Pipelines();
FormsAuthentication.Enable(fakePipelines, this.config);
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "?foo=bar"),
Response = HttpStatusCode.Unauthorized
};
// When
fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());
// Then
queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar");
}
[Fact]
public void Should_change_the_forms_authentication_redirect_uri_querystring_key()
{
// Given
var fakePipelines = new Pipelines();
this.config.RedirectQuerystringKey = "next";
FormsAuthentication.Enable(fakePipelines, this.config);
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "?foo=bar"),
Response = HttpStatusCode.Unauthorized
};
// When
fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());
// Then
queryContext.Response.Headers["Location"].ShouldEqual("/login?next=/secure%3ffoo%3dbar");
}
[Fact]
public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_null()
{
// Given
var fakePipelines = new Pipelines();
this.config.RedirectQuerystringKey = null;
FormsAuthentication.Enable(fakePipelines, this.config);
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "?foo=bar"),
Response = HttpStatusCode.Unauthorized
};
// When
fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());
// Then
queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar");
}
[Fact]
public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_empty()
{
// Given
var fakePipelines = new Pipelines();
this.config.RedirectQuerystringKey = string.Empty;
FormsAuthentication.Enable(fakePipelines, this.config);
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "?foo=bar"),
Response = HttpStatusCode.Unauthorized
};
// When
fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());
// Then
queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar");
}
[Fact]
public void Should_retain_querystring_when_redirecting_after_successfull_login()
{
// Given
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "returnUrl=/secure%3Ffoo%3Dbar")
};
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInRedirectResponse(queryContext, userGuid, DateTime.Now.AddDays(1));
// Then
result.Headers["Location"].ShouldEqual("/secure?foo=bar");
}
[Fact]
public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_with_redirect()
{
//Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);
//When
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
//Then
result.Cookies
.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName)
.First()
.Secure.ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.Cookies
.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName)
.First()
.Secure.ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);
var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/");
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Secure.ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);
// When
var result = FormsAuthentication.LogOutResponse();
// Then
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Secure.ShouldBeTrue();
}
[Fact]
public void Should_redirect_to_base_path_if_non_local_url_and_no_fallback()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/";
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
result.Headers["Location"].ShouldEqual("/testing");
}
[Fact]
public void Should_redirect_to_fallback_if_non_local_url_and_fallback_set()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/";
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, fallbackRedirectUrl:"/moo");
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
result.Headers["Location"].ShouldEqual("/moo");
}
[Fact]
public void Should_redirect_to_given_url_if_local()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
context.Request.Query[config.RedirectQuerystringKey] = "~/login";
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
result.Headers["Location"].ShouldEqual("/testing/login");
}
[Fact]
public void Should_set_Domain_when_config_provides_domain_value()
{
//Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig);
//When
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
//Then
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Domain.ShouldEqual(domain);
}
[Fact]
public void Should_set_Path_when_config_provides_path_value()
{
//Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig);
//When
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
//Then
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Path.ShouldEqual(path);
}
[Fact]
public void Should_throw_with_null_module_passed_to_enable()
{
var result = Record.Exception(() => FormsAuthentication.Enable((INancyModule)null, this.config));
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_with_null_config_passed_to_enable_with_module()
{
var result = Record.Exception(() => FormsAuthentication.Enable(new FakeModule(), null));
result.ShouldBeOfType(typeof(ArgumentNullException));
}
class FakeModule : NancyModule
{
public FakeModule()
{
this.After = new AfterPipeline();
this.Before = new BeforePipeline();
this.OnError = new ErrorPipeline();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Test.Cryptography
{
internal abstract partial class CertLoader
{
private static readonly X509KeyStorageFlags s_defaultKeyStorageFlags = GetBestKeyStorageFlags();
// Prefer ephemeral when available
private static X509KeyStorageFlags GetBestKeyStorageFlags()
{
#if netcoreapp
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// On Windows 7 ephemeral keys with a key usage embedded in the PFX
// are treated differently than Windows 8. So just use the default
// storage flags for Win7.
Version win8 = new Version(6, 2, 9200);
if (Environment.OSVersion.Version >= win8)
{
return X509KeyStorageFlags.EphemeralKeySet;
}
}
else if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// OSX doesn't allow ephemeral, but every other Unix does.
return X509KeyStorageFlags.EphemeralKeySet;
}
#endif
return X509KeyStorageFlags.DefaultKeySet;
}
protected X509KeyStorageFlags KeyStorageFlags = s_defaultKeyStorageFlags;
/// <summary>
/// Returns a freshly allocated X509Certificate2 instance that has a public key only.
///
/// This method never returns null.
/// </summary>
public X509Certificate2 GetCertificate()
{
return new X509Certificate2(CerData);
}
/// <summary>
/// Attempts to return a freshly allocated X509Certificate2 instance that has a public and private key. Only use this method if your test
/// needs the private key to work. Otherwise, use GetCertificate() which places far fewer conditions on you.
///
/// The test must check the return value for null. If it is null, exit the test without reporting a failure. A null means
/// the test host chose to disable loading private keys.
///
/// If this method does return a certificate, the test must Dispose() it manually and as soon it no longer needs the certificate.
/// Due to the way PFX loading works on Windows, failure to dispose may leave an artifact on the test machine's disk.
/// </summary>
public X509Certificate2 TryGetCertificateWithPrivateKey()
{
if (PfxData == null)
throw new Exception("Cannot call TryGetCertificateWithPrivateKey() on this CertLoader: No PfxData provided.");
if (!_alreadySearchedMyStore)
{
// Machine config check: Make sure that a matching certificate isn't stored in the MY store. Apis such as EnvelopedCms.Decrypt() look in the MY store for matching certs (with no opt-out)
// and having our test certificates there can cause false test errors or false test successes.
//
// This may be an odd place to do this check but it's better than expecting every individual test to remember to do this.
CheckIfCertWasLeftInCertStore();
_alreadySearchedMyStore = true;
}
CertLoadMode testMode = CertLoader.TestMode;
switch (testMode)
{
case CertLoadMode.Disable:
return null;
case CertLoadMode.LoadFromPfx:
return new X509Certificate2(PfxData, Password, KeyStorageFlags);
case CertLoadMode.LoadFromStore:
{
X509Certificate2Collection matches = FindMatches(CertLoader.StoreName, StoreLocation.CurrentUser);
if (matches.Count == 1)
return matches[0];
if (matches.Count == 0)
throw new Exception($"No matching certificate found in store {CertLoader.StoreName}");
else
throw new Exception($"Multiple matching certificates found in store {CertLoader.StoreName}");
}
default:
throw new Exception($"Unexpected CertLoader.TestMode value: {testMode}");
}
}
public abstract byte[] CerData { get; }
public abstract byte[] PfxData { get; }
public abstract string Password { get; }
private void CheckIfCertWasLeftInCertStore()
{
X509Certificate2Collection matches = FindMatches("MY", StoreLocation.CurrentUser);
if (matches.Count == 0)
{
matches = FindMatches("MY", StoreLocation.LocalMachine);
}
if (matches.Count != 0)
{
X509Certificate2 cer = new X509Certificate2(CerData);
string issuer = cer.Issuer;
string serial = cer.SerialNumber;
throw new Exception($"A certificate issued to {issuer} with serial number {serial} was found in your Personal certificate store. This will cause some tests to fail due to machine configuration. Please remove these.");
}
}
private X509Certificate2Collection FindMatches(string storeName, StoreLocation storeLocation)
{
using (X509Certificate2 cer = new X509Certificate2(CerData))
{
X509Certificate2Collection matches = new X509Certificate2Collection();
using (X509Store store = new X509Store(storeName, storeLocation))
{
try
{
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
}
catch (CryptographicException)
{
return matches;
}
foreach (X509Certificate2 candidate in store.Certificates)
{
// X509Certificate2.Equals() compares issuer and serial.
if (cer.Equals(candidate))
{
matches.Add(candidate);
}
}
return matches;
}
}
}
internal abstract CertLoader CloneAsEphemeralLoader();
internal abstract CertLoader CloneAsPerphemeralLoader();
private bool _alreadySearchedMyStore = false;
}
internal sealed class CertLoaderFromRawData : CertLoader
{
public CertLoaderFromRawData(byte[] cerData, byte[] pfxData = null, string password = null)
{
CerData = cerData;
PfxData = pfxData;
Password = password;
}
public sealed override byte[] CerData { get; }
public sealed override byte[] PfxData { get; }
public sealed override string Password { get; }
internal override CertLoader CloneAsEphemeralLoader()
{
#if netcoreapp
return new CertLoaderFromRawData(CerData, PfxData, Password)
{
KeyStorageFlags = X509KeyStorageFlags.EphemeralKeySet,
};
#else
throw new PlatformNotSupportedException();
#endif
}
internal override CertLoader CloneAsPerphemeralLoader()
{
return new CertLoaderFromRawData(CerData, PfxData, Password)
{
KeyStorageFlags = X509KeyStorageFlags.DefaultKeySet,
};
}
}
internal enum CertLoadMode
{
// Disable all tests that rely on private keys. Unfortunately, this has to be the default for checked in tests to avoid cluttering
// people's machines with leaked keys on disk every time they build.
Disable = 1,
// Load certs from PFX data. This is convenient as it requires no preparatory steps. The downside is that every time you open a CNG .PFX,
// a temporarily key is permanently leaked to your disk. (And every time you open a CAPI PFX, a key is leaked if the test aborts before
// Disposing the certificate.)
//
// Only use if you're testing on a VM or if you just don't care about your machine accumulating leaked keys.
LoadFromPfx = 2,
// Load certs from the certificate store (set StoreName to the name you want to use.) This requires that you preinstall the certificates
// into the cert store (say by File.WriteAllByte()'ing the PFX blob into a "foo.pfx" file, then launching it and following the wizard.)
// but then you don't need to worry about key leaks.
LoadFromStore = 3,
}
}
| |
namespace Gu.Analyzers
{
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Gu.Roslyn.AnalyzerExtensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class TestMethodAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(
GU0080TestAttributeCountMismatch.Descriptor,
GU0081TestCasesAttributeMismatch.Descriptor,
GU0082IdenticalTestCase.Descriptor,
GU0083TestCaseAttributeMismatchMethod.Descriptor);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(c => Handle(c), SyntaxKind.MethodDeclaration);
}
private static void Handle(SyntaxNodeAnalysisContext context)
{
if (context.IsExcludedFromAnalysis())
{
return;
}
if (context.Node is MethodDeclarationSyntax methodDeclaration &&
methodDeclaration.ParameterList is ParameterListSyntax parameterList &&
methodDeclaration.AttributeLists.Count > 0 &&
context.ContainingSymbol is IMethodSymbol testMethod)
{
if (TrySingleTestAttribute(methodDeclaration, context.SemanticModel, context.CancellationToken, out var attribute) &&
testMethod.Parameters.Length > 0)
{
context.ReportDiagnostic(Diagnostic.Create(GU0080TestAttributeCountMismatch.Descriptor, parameterList.GetLocation(), parameterList, attribute));
}
if (TrySingleTestCaseAttribute(methodDeclaration, context.SemanticModel, context.CancellationToken, out attribute) &&
!CountMatches(testMethod, attribute))
{
context.ReportDiagnostic(Diagnostic.Create(GU0080TestAttributeCountMismatch.Descriptor, parameterList.GetLocation(), parameterList, attribute));
}
foreach (var attributeList in methodDeclaration.AttributeLists)
{
foreach (var candidate in attributeList.Attributes)
{
if (Roslyn.AnalyzerExtensions.Attribute.IsType(candidate, KnownSymbol.NUnitTestCaseAttribute, context.SemanticModel, context.CancellationToken))
{
if (!CountMatches(testMethod, candidate))
{
context.ReportDiagnostic(Diagnostic.Create(GU0081TestCasesAttributeMismatch.Descriptor, candidate.GetLocation(), parameterList, attribute));
}
if (TryFindIdentical(methodDeclaration, candidate, context, out _))
{
context.ReportDiagnostic(Diagnostic.Create(GU0082IdenticalTestCase.Descriptor, candidate.GetLocation(), candidate));
}
if (TryGetFirstMismatch(testMethod, candidate, context, out var argument))
{
context.ReportDiagnostic(Diagnostic.Create(GU0083TestCaseAttributeMismatchMethod.Descriptor, argument.GetLocation(), candidate, parameterList));
}
}
}
}
}
}
private static bool TrySingleTestAttribute(MethodDeclarationSyntax method, SemanticModel semanticModel, CancellationToken cancellationToken, out AttributeSyntax attribute)
{
attribute = null;
var count = 0;
foreach (var attributeList in method.AttributeLists)
{
foreach (var candidate in attributeList.Attributes)
{
if (Roslyn.AnalyzerExtensions.Attribute.IsType(candidate, KnownSymbol.NUnitTestAttribute, semanticModel, cancellationToken))
{
attribute = candidate;
count++;
}
else if (Roslyn.AnalyzerExtensions.Attribute.IsType(candidate, KnownSymbol.NUnitTestCaseAttribute, semanticModel, cancellationToken) ||
Roslyn.AnalyzerExtensions.Attribute.IsType(candidate, KnownSymbol.NUnitTestCaseSourceAttribute, semanticModel, cancellationToken))
{
count++;
}
}
}
return count == 1 && attribute != null;
}
private static bool TrySingleTestCaseAttribute(MethodDeclarationSyntax method, SemanticModel semanticModel, CancellationToken cancellationToken, out AttributeSyntax attribute)
{
attribute = null;
foreach (var attributeList in method.AttributeLists)
{
foreach (var candidate in attributeList.Attributes)
{
if (Roslyn.AnalyzerExtensions.Attribute.IsType(candidate, KnownSymbol.NUnitTestCaseAttribute, semanticModel, cancellationToken))
{
if (attribute != null)
{
return false;
}
attribute = candidate;
}
}
}
return attribute != null;
}
private static bool CountMatches(IMethodSymbol method, AttributeSyntax attribute)
{
if (method.Parameters.TryLast(out var lastParameter) &&
lastParameter.IsParams)
{
return CountArgs(attribute) >= method.Parameters.Length - 1;
}
return CountArgs(attribute) == method.Parameters.Length;
}
private static bool TryGetFirstMismatch(IMethodSymbol methodSymbol, AttributeSyntax attributeSyntax, SyntaxNodeAnalysisContext context, out AttributeArgumentSyntax attributeArgument)
{
attributeArgument = null;
if (methodSymbol.Parameters.Length > 0 &&
methodSymbol.Parameters != null &&
attributeSyntax.ArgumentList is AttributeArgumentListSyntax argumentList &&
argumentList.Arguments.Count > 0)
{
for (var i = 0; i < Math.Min(CountArgs(attributeSyntax), methodSymbol.Parameters.Length); i++)
{
var argument = argumentList.Arguments[i];
var parameter = methodSymbol.Parameters[i];
if (argument is null ||
argument.NameEquals != null ||
parameter is null)
{
attributeArgument = argument;
return true;
}
if (parameter.IsParams &&
parameter.Type is IArrayTypeSymbol arrayType)
{
for (var j = i; j < CountArgs(attributeSyntax); j++)
{
if (!IsTypeMatch(arrayType.ElementType, argument))
{
attributeArgument = argument;
return true;
}
}
return false;
}
if (!IsTypeMatch(parameter.Type, argument))
{
attributeArgument = argument;
return true;
}
}
}
return false;
bool IsTypeMatch(ITypeSymbol parameterType, AttributeArgumentSyntax argument)
{
if (parameterType == KnownSymbol.Object)
{
return true;
}
if (parameterType is ITypeParameterSymbol typeParameter)
{
foreach (var constraintType in typeParameter.ConstraintTypes)
{
if (constraintType is INamedTypeSymbol namedType &&
namedType.IsGenericType &&
namedType.TypeArguments.Any(x => x is ITypeParameterSymbol))
{
// Lazy here.
continue;
}
if (!IsTypeMatch(constraintType, argument))
{
return false;
}
}
return true;
}
if (argument.Expression.IsKind(SyntaxKind.NullLiteralExpression))
{
if (parameterType.IsValueType &&
parameterType.Name != "Nullable")
{
return false;
}
return true;
}
if (!argument.Expression.IsAssignableTo(parameterType, context.SemanticModel))
{
return false;
}
return true;
}
}
private static bool TryFindIdentical(MethodDeclarationSyntax method, AttributeSyntax attribute, SyntaxNodeAnalysisContext context, out AttributeSyntax identical)
{
if (Roslyn.AnalyzerExtensions.Attribute.TryGetTypeName(attribute, out var name))
{
foreach (var attributeList in method.AttributeLists)
{
foreach (var candidate in attributeList.Attributes)
{
if (Roslyn.AnalyzerExtensions.Attribute.TryGetTypeName(candidate, out var candidateName) &&
name == candidateName &&
!ReferenceEquals(candidate, attribute) &&
IsIdentical(attribute, candidate))
{
identical = candidate;
return true;
}
}
}
}
identical = null;
return false;
bool IsIdentical(AttributeSyntax x, AttributeSyntax y)
{
if (x.ArgumentList == null &&
y.ArgumentList == null)
{
return true;
}
if (x.ArgumentList == null ||
y.ArgumentList == null)
{
return false;
}
if (x.ArgumentList.Arguments.LastIndexOf(a => a.NameEquals == null) !=
y.ArgumentList.Arguments.LastIndexOf(a => a.NameEquals == null))
{
return false;
}
for (var i = 0; i < Math.Min(x.ArgumentList.Arguments.Count, y.ArgumentList.Arguments.Count); i++)
{
var xa = x.ArgumentList.Arguments[i];
var ya = y.ArgumentList.Arguments[i];
if (xa.NameEquals != null ||
ya.NameEquals != null)
{
return xa.NameEquals != null && ya.NameEquals != null;
}
if (xa.Expression is LiteralExpressionSyntax xl &&
ya.Expression is LiteralExpressionSyntax yl)
{
if (xl.Token.Text == yl.Token.Text)
{
continue;
}
return false;
}
if (xa.Expression is IdentifierNameSyntax xn &&
ya.Expression is IdentifierNameSyntax yn)
{
if (xn.Identifier.ValueText == yn.Identifier.ValueText &&
context.SemanticModel.TryGetSymbol(xn, context.CancellationToken, out ISymbol xs) &&
context.SemanticModel.TryGetSymbol(yn, context.CancellationToken, out ISymbol ys) &&
xs.Equals(ys))
{
continue;
}
return false;
}
if (xa.Expression is MemberAccessExpressionSyntax xma &&
ya.Expression is MemberAccessExpressionSyntax yma)
{
if (xma.Name.Identifier.ValueText == yma.Name.Identifier.ValueText &&
context.SemanticModel.TryGetSymbol(xma, context.CancellationToken, out ISymbol xs) &&
context.SemanticModel.TryGetSymbol(yma, context.CancellationToken, out ISymbol ys) &&
xs.Equals(ys))
{
continue;
}
return false;
}
if (TryGetArrayExpressions(xa.Expression, out var xExpressions) &&
TryGetArrayExpressions(ya.Expression, out var yExpressions))
{
if (xExpressions.Count != yExpressions.Count)
{
return false;
}
for (var j = 0; j < xExpressions.Count; j++)
{
if (xExpressions[j] is LiteralExpressionSyntax xLiteral &&
yExpressions[j] is LiteralExpressionSyntax yLiteral &&
xLiteral.Token.Text != yLiteral.Token.Text)
{
return false;
}
}
continue;
}
return false;
}
return true;
}
}
private static int CountArgs(AttributeSyntax attribute)
{
var count = 0;
if (attribute?.ArgumentList is AttributeArgumentListSyntax argumentList)
{
foreach (var argument in argumentList.Arguments)
{
if (argument.NameEquals == null)
{
count++;
}
}
}
return count;
}
private static bool TryGetArrayExpressions(ExpressionSyntax expression, out SeparatedSyntaxList<ExpressionSyntax> expressions)
{
expressions = default(SeparatedSyntaxList<ExpressionSyntax>);
if (expression is ImplicitArrayCreationExpressionSyntax implicitArrayCreation &&
implicitArrayCreation.Initializer != null)
{
expressions = implicitArrayCreation.Initializer.Expressions;
return true;
}
if (expression is ArrayCreationExpressionSyntax arrayCreation &&
arrayCreation.Initializer != null)
{
expressions = arrayCreation.Initializer.Expressions;
return true;
}
return false;
}
}
}
| |
namespace CanankaTest {
partial class MainForm {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.mnu = new System.Windows.Forms.ToolStrip();
this.mnuNew = new System.Windows.Forms.ToolStripButton();
this.mnuCopy = new System.Windows.Forms.ToolStripButton();
this.mnuGotoEnd = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.mnuPorts = new System.Windows.Forms.ToolStripComboBox();
this.mnuConnect = new System.Windows.Forms.ToolStripButton();
this.mnuDisconnect = new System.Windows.Forms.ToolStripButton();
this.mnuApp = new System.Windows.Forms.ToolStripDropDownButton();
this.mnuAppFeedback = new System.Windows.Forms.ToolStripMenuItem();
this.mnuAppUpgrade = new System.Windows.Forms.ToolStripMenuItem();
this.mnuAppDonate = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.mnuAppAbout = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.mnuSend = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.mnuVersion = new System.Windows.Forms.ToolStripButton();
this.sta = new System.Windows.Forms.StatusStrip();
this.staStatus = new System.Windows.Forms.ToolStripStatusLabel();
this.staRxQueueFull = new System.Windows.Forms.ToolStripStatusLabel();
this.staTxQueueFull = new System.Windows.Forms.ToolStripStatusLabel();
this.staTxRxWarning = new System.Windows.Forms.ToolStripStatusLabel();
this.staRxOverflow = new System.Windows.Forms.ToolStripStatusLabel();
this.staErrorPassive = new System.Windows.Forms.ToolStripStatusLabel();
this.staArbitationLost = new System.Windows.Forms.ToolStripStatusLabel();
this.staBusError = new System.Windows.Forms.ToolStripStatusLabel();
this.staPower = new System.Windows.Forms.ToolStripStatusLabel();
this.staTermination = new System.Windows.Forms.ToolStripStatusLabel();
this.staLoad = new System.Windows.Forms.ToolStripStatusLabel();
this.staMessagesPerSecond = new System.Windows.Forms.ToolStripStatusLabel();
this.mnxPower = new System.Windows.Forms.ContextMenuStrip(this.components);
this.mnxPowerOff = new System.Windows.Forms.ToolStripMenuItem();
this.mnxPowerOn = new System.Windows.Forms.ToolStripMenuItem();
this.tmrRefresh = new System.Windows.Forms.Timer(this.components);
this.bwDevice = new System.ComponentModel.BackgroundWorker();
this.lsvMessages = new CanankaTest.ListViewEx();
this.lsvMessages_colTime = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.lsvMessages_colID = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.lsvMessages_colData = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.lsvMessages_colFlags = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.mnxTermination = new System.Windows.Forms.ContextMenuStrip(this.components);
this.mnxTerminationOff = new System.Windows.Forms.ToolStripMenuItem();
this.mnxTerminationOn = new System.Windows.Forms.ToolStripMenuItem();
this.mnxLoad = new System.Windows.Forms.ContextMenuStrip(this.components);
this.mnxLoadOff = new System.Windows.Forms.ToolStripMenuItem();
this.mnxLoad1 = new System.Windows.Forms.ToolStripSeparator();
this.mnxLoadOn1 = new System.Windows.Forms.ToolStripMenuItem();
this.mnxLoadOn2 = new System.Windows.Forms.ToolStripMenuItem();
this.mnxLoadOn3 = new System.Windows.Forms.ToolStripMenuItem();
this.mnxLoadOn4 = new System.Windows.Forms.ToolStripMenuItem();
this.mnxLoadOn5 = new System.Windows.Forms.ToolStripMenuItem();
this.mnxLoad2 = new System.Windows.Forms.ToolStripSeparator();
this.mnxLoadOn6 = new System.Windows.Forms.ToolStripMenuItem();
this.mnxLoadOn7 = new System.Windows.Forms.ToolStripMenuItem();
this.mnxLoadOn8 = new System.Windows.Forms.ToolStripMenuItem();
this.mnxLoadOn9 = new System.Windows.Forms.ToolStripMenuItem();
this.mnu.SuspendLayout();
this.sta.SuspendLayout();
this.mnxPower.SuspendLayout();
this.mnxTermination.SuspendLayout();
this.mnxLoad.SuspendLayout();
this.SuspendLayout();
//
// mnu
//
this.mnu.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.mnu.ImageScalingSize = new System.Drawing.Size(20, 20);
this.mnu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuNew,
this.mnuCopy,
this.mnuGotoEnd,
this.toolStripSeparator2,
this.mnuPorts,
this.mnuConnect,
this.mnuDisconnect,
this.mnuApp,
this.toolStripSeparator1,
this.mnuSend,
this.toolStripSeparator3,
this.mnuVersion});
this.mnu.Location = new System.Drawing.Point(0, 0);
this.mnu.Name = "mnu";
this.mnu.Padding = new System.Windows.Forms.Padding(1, 0, 1, 1);
this.mnu.Size = new System.Drawing.Size(602, 29);
this.mnu.TabIndex = 0;
//
// mnuNew
//
this.mnuNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuNew.Enabled = false;
this.mnuNew.Image = global::CanankaTest.Properties.Resources.mnuNew_16;
this.mnuNew.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuNew.Name = "mnuNew";
this.mnuNew.Size = new System.Drawing.Size(24, 25);
this.mnuNew.Text = "New";
this.mnuNew.ToolTipText = "New (Ctrl+N)";
this.mnuNew.Click += new System.EventHandler(this.mnuNew_Click);
//
// mnuCopy
//
this.mnuCopy.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuCopy.Enabled = false;
this.mnuCopy.Image = global::CanankaTest.Properties.Resources.mnuCopy_16;
this.mnuCopy.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuCopy.Name = "mnuCopy";
this.mnuCopy.Size = new System.Drawing.Size(24, 25);
this.mnuCopy.Text = "Copy (Ctrl+C)";
this.mnuCopy.Click += new System.EventHandler(this.mnuCopy_Click);
//
// mnuGotoEnd
//
this.mnuGotoEnd.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuGotoEnd.Enabled = false;
this.mnuGotoEnd.Image = global::CanankaTest.Properties.Resources.mnuGotoEnd_16;
this.mnuGotoEnd.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuGotoEnd.Name = "mnuGotoEnd";
this.mnuGotoEnd.Size = new System.Drawing.Size(24, 25);
this.mnuGotoEnd.Text = "Move to end";
this.mnuGotoEnd.Click += new System.EventHandler(this.mnuGotoEnd_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 28);
//
// mnuPorts
//
this.mnuPorts.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.mnuPorts.Name = "mnuPorts";
this.mnuPorts.Size = new System.Drawing.Size(121, 28);
//
// mnuConnect
//
this.mnuConnect.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuConnect.Image = global::CanankaTest.Properties.Resources.mnuConnect_16;
this.mnuConnect.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuConnect.Name = "mnuConnect";
this.mnuConnect.Size = new System.Drawing.Size(24, 25);
this.mnuConnect.Text = "Connect";
this.mnuConnect.ToolTipText = "Connect (F8)";
this.mnuConnect.Click += new System.EventHandler(this.mnuConnect_Click);
//
// mnuDisconnect
//
this.mnuDisconnect.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuDisconnect.Enabled = false;
this.mnuDisconnect.Image = global::CanankaTest.Properties.Resources.mnuDisconnect_16;
this.mnuDisconnect.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuDisconnect.Name = "mnuDisconnect";
this.mnuDisconnect.Size = new System.Drawing.Size(24, 25);
this.mnuDisconnect.Text = "Disconnect";
this.mnuDisconnect.Click += new System.EventHandler(this.mnuDisconnect_Click);
//
// mnuApp
//
this.mnuApp.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.mnuApp.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuApp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuAppFeedback,
this.mnuAppUpgrade,
this.mnuAppDonate,
this.toolStripMenuItem1,
this.mnuAppAbout});
this.mnuApp.Image = global::CanankaTest.Properties.Resources.mnuApp_16;
this.mnuApp.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuApp.Name = "mnuApp";
this.mnuApp.Size = new System.Drawing.Size(34, 25);
this.mnuApp.Text = "Application";
//
// mnuAppFeedback
//
this.mnuAppFeedback.Name = "mnuAppFeedback";
this.mnuAppFeedback.Size = new System.Drawing.Size(212, 26);
this.mnuAppFeedback.Text = "Send &feedback";
this.mnuAppFeedback.Click += new System.EventHandler(this.mnuAppFeedback_Click);
//
// mnuAppUpgrade
//
this.mnuAppUpgrade.Name = "mnuAppUpgrade";
this.mnuAppUpgrade.Size = new System.Drawing.Size(212, 26);
this.mnuAppUpgrade.Text = "Check for &upgrades";
this.mnuAppUpgrade.Click += new System.EventHandler(this.mnuAppUpgrade_Click);
//
// mnuAppDonate
//
this.mnuAppDonate.Name = "mnuAppDonate";
this.mnuAppDonate.Size = new System.Drawing.Size(212, 26);
this.mnuAppDonate.Text = "&Donate";
this.mnuAppDonate.Click += new System.EventHandler(this.mnuAppDonate_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(209, 6);
//
// mnuAppAbout
//
this.mnuAppAbout.Name = "mnuAppAbout";
this.mnuAppAbout.Size = new System.Drawing.Size(212, 26);
this.mnuAppAbout.Text = "&About";
this.mnuAppAbout.Click += new System.EventHandler(this.mnuAppAbout_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 28);
//
// mnuSend
//
this.mnuSend.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuSend.Image = global::CanankaTest.Properties.Resources.mnuSend_16;
this.mnuSend.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuSend.Name = "mnuSend";
this.mnuSend.Size = new System.Drawing.Size(24, 25);
this.mnuSend.Text = "Send";
this.mnuSend.ToolTipText = "Send message";
this.mnuSend.Click += new System.EventHandler(this.mnuSend_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(6, 28);
//
// mnuVersion
//
this.mnuVersion.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mnuVersion.Image = global::CanankaTest.Properties.Resources.mnuVersion_16;
this.mnuVersion.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mnuVersion.Name = "mnuVersion";
this.mnuVersion.Size = new System.Drawing.Size(24, 25);
this.mnuVersion.Text = "toolStripButton1";
this.mnuVersion.Click += new System.EventHandler(this.mnuVersion_Click);
//
// sta
//
this.sta.ImageScalingSize = new System.Drawing.Size(20, 20);
this.sta.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.staStatus,
this.staRxQueueFull,
this.staTxQueueFull,
this.staTxRxWarning,
this.staRxOverflow,
this.staErrorPassive,
this.staArbitationLost,
this.staBusError,
this.staPower,
this.staTermination,
this.staLoad,
this.staMessagesPerSecond});
this.sta.Location = new System.Drawing.Point(0, 328);
this.sta.Name = "sta";
this.sta.ShowItemToolTips = true;
this.sta.Size = new System.Drawing.Size(602, 25);
this.sta.TabIndex = 2;
//
// staStatus
//
this.staStatus.Name = "staStatus";
this.staStatus.Size = new System.Drawing.Size(390, 20);
this.staStatus.Spring = true;
this.staStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.staStatus.ToolTipText = "Status";
//
// staRxQueueFull
//
this.staRxQueueFull.Name = "staRxQueueFull";
this.staRxQueueFull.Size = new System.Drawing.Size(18, 20);
this.staRxQueueFull.Text = "R";
this.staRxQueueFull.ToolTipText = "Rx queue full";
this.staRxQueueFull.Visible = false;
//
// staTxQueueFull
//
this.staTxQueueFull.Name = "staTxQueueFull";
this.staTxQueueFull.Size = new System.Drawing.Size(17, 20);
this.staTxQueueFull.Text = "T";
this.staTxQueueFull.ToolTipText = "Tx queue full";
this.staTxQueueFull.Visible = false;
//
// staTxRxWarning
//
this.staTxRxWarning.Name = "staTxRxWarning";
this.staTxRxWarning.Size = new System.Drawing.Size(23, 20);
this.staTxRxWarning.Text = "W";
this.staTxRxWarning.ToolTipText = "Tx/Rx warning";
this.staTxRxWarning.Visible = false;
//
// staRxOverflow
//
this.staRxOverflow.Name = "staRxOverflow";
this.staRxOverflow.Size = new System.Drawing.Size(20, 20);
this.staRxOverflow.Text = "O";
this.staRxOverflow.ToolTipText = "Rx overflow";
this.staRxOverflow.Visible = false;
//
// staErrorPassive
//
this.staErrorPassive.Name = "staErrorPassive";
this.staErrorPassive.Size = new System.Drawing.Size(17, 20);
this.staErrorPassive.Text = "P";
this.staErrorPassive.ToolTipText = "Error-passive";
this.staErrorPassive.Visible = false;
//
// staArbitationLost
//
this.staArbitationLost.Name = "staArbitationLost";
this.staArbitationLost.Size = new System.Drawing.Size(19, 20);
this.staArbitationLost.Text = "A";
this.staArbitationLost.ToolTipText = "Arbitration lost";
this.staArbitationLost.Visible = false;
//
// staBusError
//
this.staBusError.Name = "staBusError";
this.staBusError.Size = new System.Drawing.Size(17, 20);
this.staBusError.Text = "E";
this.staBusError.ToolTipText = "Bus error";
this.staBusError.Visible = false;
//
// staPower
//
this.staPower.Margin = new System.Windows.Forms.Padding(3, 3, 0, 2);
this.staPower.Name = "staPower";
this.staPower.Size = new System.Drawing.Size(49, 20);
this.staPower.Text = "Power";
this.staPower.ToolTipText = "Power output status";
this.staPower.MouseDown += new System.Windows.Forms.MouseEventHandler(this.staPower_MouseDown);
//
// staTermination
//
this.staTermination.Name = "staTermination";
this.staTermination.Size = new System.Drawing.Size(88, 20);
this.staTermination.Text = "Termination";
this.staTermination.ToolTipText = "Termination status";
this.staTermination.MouseDown += new System.Windows.Forms.MouseEventHandler(this.staTermination_MouseDown);
//
// staLoad
//
this.staLoad.Name = "staLoad";
this.staLoad.Size = new System.Drawing.Size(42, 20);
this.staLoad.Text = "Load";
this.staLoad.ToolTipText = "Load generator status";
this.staLoad.MouseDown += new System.Windows.Forms.MouseEventHandler(this.staLoad_MouseDown);
//
// staMessagesPerSecond
//
this.staMessagesPerSecond.Name = "staMessagesPerSecond";
this.staMessagesPerSecond.Size = new System.Drawing.Size(15, 20);
this.staMessagesPerSecond.Text = "-";
this.staMessagesPerSecond.ToolTipText = "Messages per second";
//
// mnxPower
//
this.mnxPower.ImageScalingSize = new System.Drawing.Size(20, 20);
this.mnxPower.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnxPowerOff,
this.mnxPowerOn});
this.mnxPower.Name = "mnxPower";
this.mnxPower.Size = new System.Drawing.Size(177, 52);
this.mnxPower.Opening += new System.ComponentModel.CancelEventHandler(this.mnxPower_Opening);
//
// mnxPowerOff
//
this.mnxPowerOff.Name = "mnxPowerOff";
this.mnxPowerOff.Size = new System.Drawing.Size(176, 24);
this.mnxPowerOff.Text = "Turn power off";
this.mnxPowerOff.Click += new System.EventHandler(this.mnxPowerOff_Click);
//
// mnxPowerOn
//
this.mnxPowerOn.Name = "mnxPowerOn";
this.mnxPowerOn.Size = new System.Drawing.Size(176, 24);
this.mnxPowerOn.Text = "Turn power on";
this.mnxPowerOn.Click += new System.EventHandler(this.mnxPowerOn_Click);
//
// tmrRefresh
//
this.tmrRefresh.Enabled = true;
this.tmrRefresh.Interval = 1000;
this.tmrRefresh.Tick += new System.EventHandler(this.tmrRefresh_Tick);
//
// bwDevice
//
this.bwDevice.WorkerReportsProgress = true;
this.bwDevice.WorkerSupportsCancellation = true;
this.bwDevice.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bwDevice_DoWork);
this.bwDevice.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.bwDevice_ProgressChanged);
this.bwDevice.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bwDevice_RunWorkerCompleted);
//
// lsvMessages
//
this.lsvMessages.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lsvMessages.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.lsvMessages_colTime,
this.lsvMessages_colID,
this.lsvMessages_colData,
this.lsvMessages_colFlags});
this.lsvMessages.Dock = System.Windows.Forms.DockStyle.Fill;
this.lsvMessages.FullRowSelect = true;
this.lsvMessages.GridLines = true;
this.lsvMessages.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.lsvMessages.HideSelection = false;
this.lsvMessages.Location = new System.Drawing.Point(0, 29);
this.lsvMessages.Name = "lsvMessages";
this.lsvMessages.Size = new System.Drawing.Size(602, 299);
this.lsvMessages.TabIndex = 1;
this.lsvMessages.UseCompatibleStateImageBehavior = false;
this.lsvMessages.View = System.Windows.Forms.View.Details;
//
// lsvMessages_colTime
//
this.lsvMessages_colTime.Text = "Time";
this.lsvMessages_colTime.Width = 90;
//
// lsvMessages_colID
//
this.lsvMessages_colID.Text = "ID";
this.lsvMessages_colID.Width = 120;
//
// lsvMessages_colData
//
this.lsvMessages_colData.Text = "Data";
this.lsvMessages_colData.Width = 240;
//
// lsvMessages_colFlags
//
this.lsvMessages_colFlags.Text = "Flags";
//
// mnxTermination
//
this.mnxTermination.ImageScalingSize = new System.Drawing.Size(20, 20);
this.mnxTermination.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnxTerminationOff,
this.mnxTerminationOn});
this.mnxTermination.Name = "mnxPower";
this.mnxTermination.Size = new System.Drawing.Size(212, 52);
this.mnxTermination.Opening += new System.ComponentModel.CancelEventHandler(this.mnxTermination_Opening);
//
// mnxTerminationOff
//
this.mnxTerminationOff.Name = "mnxTerminationOff";
this.mnxTerminationOff.Size = new System.Drawing.Size(211, 24);
this.mnxTerminationOff.Text = "Turn termination off";
this.mnxTerminationOff.Click += new System.EventHandler(this.mnxTerminationOff_Click);
//
// mnxTerminationOn
//
this.mnxTerminationOn.Name = "mnxTerminationOn";
this.mnxTerminationOn.Size = new System.Drawing.Size(211, 24);
this.mnxTerminationOn.Text = "Turn termination on";
this.mnxTerminationOn.Click += new System.EventHandler(this.mnxTerminationOn_Click);
//
// mnxLoad
//
this.mnxLoad.ImageScalingSize = new System.Drawing.Size(20, 20);
this.mnxLoad.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnxLoadOff,
this.mnxLoad1,
this.mnxLoadOn1,
this.mnxLoadOn2,
this.mnxLoadOn3,
this.mnxLoadOn4,
this.mnxLoadOn5,
this.mnxLoad2,
this.mnxLoadOn6,
this.mnxLoadOn7,
this.mnxLoadOn8,
this.mnxLoadOn9});
this.mnxLoad.Name = "mnxPower";
this.mnxLoad.Size = new System.Drawing.Size(220, 284);
this.mnxLoad.Opening += new System.ComponentModel.CancelEventHandler(this.mnxLoad_Opening);
//
// mnxLoadOff
//
this.mnxLoadOff.Name = "mnxLoadOff";
this.mnxLoadOff.Size = new System.Drawing.Size(219, 24);
this.mnxLoadOff.Text = "Turn load off";
this.mnxLoadOff.Click += new System.EventHandler(this.mnxLoadOff_Click);
//
// mnxLoad1
//
this.mnxLoad1.Name = "mnxLoad1";
this.mnxLoad1.Size = new System.Drawing.Size(216, 6);
//
// mnxLoadOn1
//
this.mnxLoadOn1.Name = "mnxLoadOn1";
this.mnxLoadOn1.Size = new System.Drawing.Size(219, 24);
this.mnxLoadOn1.Text = "Turn load on (level 1)";
this.mnxLoadOn1.Click += new System.EventHandler(this.mnxLoadOn1_Click);
//
// mnxLoadOn2
//
this.mnxLoadOn2.Name = "mnxLoadOn2";
this.mnxLoadOn2.Size = new System.Drawing.Size(219, 24);
this.mnxLoadOn2.Text = "Turn load on (level 2)";
this.mnxLoadOn2.Click += new System.EventHandler(this.mnxLoadOn2_Click);
//
// mnxLoadOn3
//
this.mnxLoadOn3.Name = "mnxLoadOn3";
this.mnxLoadOn3.Size = new System.Drawing.Size(219, 24);
this.mnxLoadOn3.Text = "Turn load on (level 3)";
this.mnxLoadOn3.Click += new System.EventHandler(this.mnxLoadOn3_Click);
//
// mnxLoadOn4
//
this.mnxLoadOn4.Name = "mnxLoadOn4";
this.mnxLoadOn4.Size = new System.Drawing.Size(219, 24);
this.mnxLoadOn4.Text = "Turn load on (level 4)";
this.mnxLoadOn4.Click += new System.EventHandler(this.mnxLoadOn4_Click);
//
// mnxLoadOn5
//
this.mnxLoadOn5.Name = "mnxLoadOn5";
this.mnxLoadOn5.Size = new System.Drawing.Size(219, 24);
this.mnxLoadOn5.Text = "Turn load on (level 5)";
this.mnxLoadOn5.Click += new System.EventHandler(this.mnxLoadOn5_Click);
//
// mnxLoad2
//
this.mnxLoad2.Name = "mnxLoad2";
this.mnxLoad2.Size = new System.Drawing.Size(216, 6);
//
// mnxLoadOn6
//
this.mnxLoadOn6.Name = "mnxLoadOn6";
this.mnxLoadOn6.Size = new System.Drawing.Size(219, 24);
this.mnxLoadOn6.Text = "Turn load on (level 6)";
this.mnxLoadOn6.Click += new System.EventHandler(this.mnxLoadOn6_Click);
//
// mnxLoadOn7
//
this.mnxLoadOn7.Name = "mnxLoadOn7";
this.mnxLoadOn7.Size = new System.Drawing.Size(219, 24);
this.mnxLoadOn7.Text = "Turn load on (level 7)";
this.mnxLoadOn7.Click += new System.EventHandler(this.mnxLoadOn7_Click);
//
// mnxLoadOn8
//
this.mnxLoadOn8.Name = "mnxLoadOn8";
this.mnxLoadOn8.Size = new System.Drawing.Size(219, 24);
this.mnxLoadOn8.Text = "Turn load on (level 8)";
this.mnxLoadOn8.Click += new System.EventHandler(this.mnxLoadOn8_Click);
//
// mnxLoadOn9
//
this.mnxLoadOn9.Name = "mnxLoadOn9";
this.mnxLoadOn9.Size = new System.Drawing.Size(219, 24);
this.mnxLoadOn9.Text = "Turn load on (level 9)";
this.mnxLoadOn9.Click += new System.EventHandler(this.mnxLoadOn9_Click);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(602, 353);
this.Controls.Add(this.lsvMessages);
this.Controls.Add(this.sta);
this.Controls.Add(this.mnu);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(400, 320);
this.Name = "MainForm";
this.Text = "Cananka";
this.mnu.ResumeLayout(false);
this.mnu.PerformLayout();
this.sta.ResumeLayout(false);
this.sta.PerformLayout();
this.mnxPower.ResumeLayout(false);
this.mnxTermination.ResumeLayout(false);
this.mnxLoad.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStrip mnu;
private System.Windows.Forms.ToolStripComboBox mnuPorts;
private System.Windows.Forms.ToolStripButton mnuConnect;
private System.Windows.Forms.ToolStripButton mnuDisconnect;
private System.Windows.Forms.ToolStripButton mnuNew;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripButton mnuCopy;
private ListViewEx lsvMessages;
private System.Windows.Forms.ColumnHeader lsvMessages_colID;
private System.Windows.Forms.ColumnHeader lsvMessages_colData;
private System.Windows.Forms.ColumnHeader lsvMessages_colFlags;
private System.Windows.Forms.ToolStripDropDownButton mnuApp;
private System.Windows.Forms.StatusStrip sta;
private System.Windows.Forms.ToolStripStatusLabel staStatus;
private System.Windows.Forms.ToolStripStatusLabel staTxQueueFull;
private System.Windows.Forms.Timer tmrRefresh;
private System.Windows.Forms.ToolStripMenuItem mnuAppFeedback;
private System.Windows.Forms.ToolStripMenuItem mnuAppUpgrade;
private System.Windows.Forms.ToolStripMenuItem mnuAppDonate;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem mnuAppAbout;
private System.Windows.Forms.ToolStripStatusLabel staRxQueueFull;
private System.ComponentModel.BackgroundWorker bwDevice;
private System.Windows.Forms.ToolStripStatusLabel staPower;
private System.Windows.Forms.ToolStripStatusLabel staTermination;
private System.Windows.Forms.ToolStripStatusLabel staTxRxWarning;
private System.Windows.Forms.ContextMenuStrip mnxPower;
private System.Windows.Forms.ToolStripMenuItem mnxPowerOn;
private System.Windows.Forms.ToolStripMenuItem mnxPowerOff;
private System.Windows.Forms.ToolStripStatusLabel staMessagesPerSecond;
private System.Windows.Forms.ToolStripButton mnuGotoEnd;
private System.Windows.Forms.ToolStripStatusLabel staRxOverflow;
private System.Windows.Forms.ToolStripStatusLabel staErrorPassive;
private System.Windows.Forms.ToolStripStatusLabel staArbitationLost;
private System.Windows.Forms.ToolStripStatusLabel staBusError;
private System.Windows.Forms.ColumnHeader lsvMessages_colTime;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton mnuSend;
private System.Windows.Forms.ToolStripStatusLabel staLoad;
private System.Windows.Forms.ContextMenuStrip mnxTermination;
private System.Windows.Forms.ToolStripMenuItem mnxTerminationOn;
private System.Windows.Forms.ToolStripMenuItem mnxTerminationOff;
private System.Windows.Forms.ContextMenuStrip mnxLoad;
private System.Windows.Forms.ToolStripMenuItem mnxLoadOff;
private System.Windows.Forms.ToolStripSeparator mnxLoad1;
private System.Windows.Forms.ToolStripMenuItem mnxLoadOn1;
private System.Windows.Forms.ToolStripMenuItem mnxLoadOn2;
private System.Windows.Forms.ToolStripMenuItem mnxLoadOn3;
private System.Windows.Forms.ToolStripMenuItem mnxLoadOn4;
private System.Windows.Forms.ToolStripMenuItem mnxLoadOn5;
private System.Windows.Forms.ToolStripSeparator mnxLoad2;
private System.Windows.Forms.ToolStripMenuItem mnxLoadOn6;
private System.Windows.Forms.ToolStripMenuItem mnxLoadOn7;
private System.Windows.Forms.ToolStripMenuItem mnxLoadOn8;
private System.Windows.Forms.ToolStripMenuItem mnxLoadOn9;
private System.Windows.Forms.ToolStripButton mnuVersion;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
}
}
| |
/*
* Copyright (c) 2009, Stefan Simek
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace TriAxis.RunSharp
{
public struct AttributeType
{
Type t;
private AttributeType(Type t)
{
this.t = t;
}
public static implicit operator Type(AttributeType t)
{
return t.t;
}
public static implicit operator AttributeType(Type t)
{
if (!typeof(Attribute).IsAssignableFrom(t))
throw new ArgumentException("Attribute types must derive from the 'Attribute' class", "t");
return new AttributeType(t);
}
public static implicit operator AttributeType(TypeGen tg)
{
if (!typeof(Attribute).IsAssignableFrom(tg.TypeBuilder))
throw new ArgumentException("Attribute types must derive from the 'Attribute' class", "t");
return new AttributeType(tg.TypeBuilder);
}
}
public class AttributeGen
{
Type attributeType;
object[] args;
ApplicableFunction ctor;
Dictionary<PropertyInfo, object> namedProperties;
Dictionary<FieldInfo, object> namedFields;
internal AttributeGen(AttributeTargets target, AttributeType attributeType, object[] args)
{
if (args != null)
{
foreach (object arg in args)
{
CheckValue(arg);
}
}
// TODO: target validation
this.attributeType = attributeType;
Operand[] argOperands;
if (args == null || args.Length == 0)
{
this.args = EmptyArray<object>.Instance;
argOperands = Operand.EmptyArray;
}
else
{
this.args = args;
argOperands = new Operand[args.Length];
for (int i = 0; i < args.Length; i++)
{
argOperands[i] = GetOperand(args[i]);
}
}
this.ctor = TypeInfo.FindConstructor(attributeType, argOperands);
}
static bool IsValidAttributeParamType(Type t)
{
return t != null && (t.IsPrimitive || t.IsEnum || typeof(Type).IsAssignableFrom(t) || t == typeof(string));
}
static bool IsSingleDimensionalZeroBasedArray(Array a)
{
return a != null && a.Rank == 1 && a.GetLowerBound(0) == 0;
}
static void CheckValue(object arg)
{
if (arg == null)
throw new ArgumentNullException();
Type t = arg.GetType();
if (IsValidAttributeParamType(t))
return;
if (IsSingleDimensionalZeroBasedArray(arg as Array) && IsValidAttributeParamType(t.GetElementType()))
return;
throw new ArgumentException();
}
static Operand GetOperand(object arg)
{
return Operand.FromObject(arg);
}
public AttributeGen SetField(string name, object value)
{
CheckValue(value);
FieldInfo fi = (FieldInfo)TypeInfo.FindField(attributeType, name, false).Member;
SetFieldIntl(fi, value);
return this;
}
void SetFieldIntl(FieldInfo fi, object value)
{
if (namedFields != null)
{
if (namedFields.ContainsKey(fi))
throw new InvalidOperationException(string.Format(Properties.Messages.ErrAttributeMultiField, fi.Name));
}
else
{
namedFields = new Dictionary<FieldInfo, object>();
}
namedFields[fi] = value;
}
public AttributeGen SetProperty(string name, object value)
{
CheckValue(value);
PropertyInfo pi = (PropertyInfo)TypeInfo.FindProperty(attributeType, name, null, false).Method.Member;
SetPropertyIntl(pi, value);
return this;
}
void SetPropertyIntl(PropertyInfo pi, object value)
{
if (!pi.CanWrite)
throw new InvalidOperationException(string.Format(Properties.Messages.ErrAttributeReadOnlyProperty, pi.Name));
if (namedProperties != null)
{
if (namedProperties.ContainsKey(pi))
throw new InvalidOperationException(string.Format(Properties.Messages.ErrAttributeMultiProperty, pi.Name));
}
else
{
namedProperties = new Dictionary<PropertyInfo, object>();
}
namedProperties[pi] = value;
}
public AttributeGen Set(string name, object value)
{
CheckValue(value);
for (Type t = attributeType; t != null; t = t.BaseType)
{
foreach (IMemberInfo mi in TypeInfo.GetFields(t))
{
if (mi.Name == name && !mi.IsStatic)
{
SetFieldIntl((FieldInfo)mi.Member, value);
return this;
}
}
ApplicableFunction af = OverloadResolver.Resolve(TypeInfo.Filter(TypeInfo.GetProperties(t), name, false, false, false), Operand.EmptyArray);
if (af != null)
{
SetPropertyIntl((PropertyInfo)af.Method.Member, value);
return this;
}
}
throw new MissingMemberException(Properties.Messages.ErrMissingProperty);
}
CustomAttributeBuilder GetAttributeBuilder()
{
ConstructorInfo ci = (ConstructorInfo)ctor.Method.Member;
if (namedProperties == null && namedFields == null)
{
return new CustomAttributeBuilder(ci, args);
}
if (namedProperties == null)
{
return new CustomAttributeBuilder(ci, args, ArrayUtils.ToArray(namedFields.Keys), ArrayUtils.ToArray(namedFields.Values));
}
if (namedFields == null)
{
return new CustomAttributeBuilder(ci, args, ArrayUtils.ToArray(namedProperties.Keys), ArrayUtils.ToArray(namedProperties.Values));
}
return new CustomAttributeBuilder(ci, args,
ArrayUtils.ToArray(namedProperties.Keys), ArrayUtils.ToArray(namedProperties.Values),
ArrayUtils.ToArray(namedFields.Keys), ArrayUtils.ToArray(namedFields.Values));
}
internal static void ApplyList(ref List<AttributeGen> customAttributes, Action<CustomAttributeBuilder> setCustomAttribute)
{
if (customAttributes != null)
{
foreach (AttributeGen ag in customAttributes)
setCustomAttribute(ag.GetAttributeBuilder());
customAttributes = null;
}
}
}
public class AttributeGen<TOuterContext> : AttributeGen
{
TOuterContext context;
internal AttributeGen(TOuterContext context, AttributeTargets target, AttributeType attributeType, object[] args)
: base(target, attributeType, args)
{
this.context = context;
}
internal static AttributeGen<TOuterContext> CreateAndAdd(TOuterContext context, ref List<AttributeGen> list, AttributeTargets target, AttributeType attributeType, object[] args)
{
AttributeGen<TOuterContext> ag = new AttributeGen<TOuterContext>(context, target, attributeType, args);
if (list == null)
list = new List<AttributeGen>();
list.Add(ag);
return ag;
}
public new AttributeGen<TOuterContext> SetField(string name, object value)
{
base.SetField(name, value);
return this;
}
public new AttributeGen<TOuterContext> SetProperty(string name, object value)
{
base.SetProperty(name, value);
return this;
}
public new AttributeGen<TOuterContext> Set(string name, object value)
{
base.Set(name, value);
return this;
}
public TOuterContext End()
{
return context;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ConfigurationErrorsException.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Configuration {
using System.Configuration.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Xml;
using System.Runtime.Versioning;
using System.Diagnostics.CodeAnalysis;
[Serializable]
public class ConfigurationErrorsException : ConfigurationException {
// Constants
private const string HTTP_PREFIX = "http:";
private const string SERIALIZATION_PARAM_FILENAME = "firstFilename";
private const string SERIALIZATION_PARAM_LINE = "firstLine";
private const string SERIALIZATION_PARAM_ERROR_COUNT = "count";
private const string SERIALIZATION_PARAM_ERROR_DATA = "_errors";
private const string SERIALIZATION_PARAM_ERROR_TYPE = "_errors_type";
private string _firstFilename;
private int _firstLine;
private ConfigurationException[] _errors;
void Init(string filename, int line) {
HResult = HResults.Configuration;
// BaseConfigurationRecord.cs uses -1 as uninitialized line number.
if (line == -1) {
line = 0;
}
_firstFilename = filename;
_firstLine = line;
}
// The ConfigurationException class is obsolete, but we still need to derive from it and call the base ctor, so we
// just disable the obsoletion warning.
#pragma warning disable 0618
public ConfigurationErrorsException(string message, Exception inner, string filename, int line) : base(message, inner) {
#pragma warning restore 0618
Init(filename, line);
}
public ConfigurationErrorsException() :
this(null, null, null, 0) {}
public ConfigurationErrorsException(string message) :
this(message, null, null, 0) {}
public ConfigurationErrorsException(string message, Exception inner) :
this(message, inner, null, 0) {}
public ConfigurationErrorsException(string message, string filename, int line) :
this(message, null, filename, line) {}
public ConfigurationErrorsException(string message, XmlNode node) :
this(message, null, GetUnsafeFilename(node), GetLineNumber(node)) {}
public ConfigurationErrorsException(string message, Exception inner, XmlNode node) :
this(message, inner, GetUnsafeFilename(node), GetLineNumber(node)) {}
public ConfigurationErrorsException(string message, XmlReader reader) :
this(message, null, GetUnsafeFilename(reader), GetLineNumber(reader)) {}
public ConfigurationErrorsException(string message, Exception inner, XmlReader reader) :
this(message, inner, GetUnsafeFilename(reader), GetLineNumber(reader)) {}
internal ConfigurationErrorsException(string message, IConfigErrorInfo errorInfo) :
this(message, null, GetUnsafeConfigErrorInfoFilename(errorInfo), GetConfigErrorInfoLineNumber(errorInfo)) {}
internal ConfigurationErrorsException(string message, Exception inner, IConfigErrorInfo errorInfo) :
this(message, inner, GetUnsafeConfigErrorInfoFilename(errorInfo), GetConfigErrorInfoLineNumber(errorInfo)) {}
internal ConfigurationErrorsException(ConfigurationException e) :
this(GetBareMessage(e), GetInnerException(e), GetUnsafeFilename(e), GetLineNumber(e)) {}
[ResourceExposure(ResourceScope.None)]
internal ConfigurationErrorsException(ICollection<ConfigurationException> coll) :
this(GetFirstException(coll)) {
if (coll.Count > 1) {
_errors = new ConfigurationException[coll.Count];
coll.CopyTo(_errors, 0);
}
}
internal ConfigurationErrorsException(ArrayList coll) :
this((ConfigurationException) (coll.Count > 0 ? coll[0] : null)) {
if (coll.Count > 1) {
_errors = new ConfigurationException[coll.Count];
coll.CopyTo(_errors, 0);
foreach (object error in _errors) {
// force an illegal typecast exception if the object is not
// of the right type
ConfigurationException exception = (ConfigurationException) error;
}
}
}
static private ConfigurationException GetFirstException(ICollection<ConfigurationException> coll) {
foreach (ConfigurationException e in coll) {
return e;
}
return null;
}
static private string GetBareMessage(ConfigurationException e) {
if (e != null) {
return e.BareMessage;
}
return null;
}
static private Exception GetInnerException(ConfigurationException e) {
if (e != null) {
return e.InnerException;
}
return null;
}
//
// We assert PathDiscovery so that we get the full filename when calling ConfigurationException.Filename
//
[FileIOPermission(SecurityAction.Assert, AllFiles=FileIOPermissionAccess.PathDiscovery)]
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "Our Filename property getter demands the appropriate permissions.")]
static private string GetUnsafeFilename(ConfigurationException e) {
if (e != null) {
return e.Filename;
}
return null;
}
static private int GetLineNumber(ConfigurationException e) {
if (e != null) {
return e.Line;
}
return 0;
}
// Serialization methods
protected ConfigurationErrorsException(SerializationInfo info, StreamingContext context) :
base(info, context) {
string firstFilename;
int firstLine;
int count;
string numPrefix;
string currentType;
Type currentExceptionType;
// Retrieve out members
firstFilename = info.GetString(SERIALIZATION_PARAM_FILENAME);
firstLine = info.GetInt32(SERIALIZATION_PARAM_LINE);
Init(firstFilename, firstLine);
// Retrieve errors for _errors object
count = info.GetInt32(SERIALIZATION_PARAM_ERROR_COUNT);
if (count != 0) {
_errors = new ConfigurationException[count];
for (int i = 0; i < count; i++) {
numPrefix = i.ToString(CultureInfo.InvariantCulture);
currentType = info.GetString(numPrefix + SERIALIZATION_PARAM_ERROR_TYPE);
currentExceptionType = Type.GetType(currentType, true);
// Only allow our exception types
if ( ( currentExceptionType != typeof( ConfigurationException ) ) &&
( currentExceptionType != typeof( ConfigurationErrorsException ) ) ) {
throw ExceptionUtil.UnexpectedError( "ConfigurationErrorsException" );
}
_errors[i] = (ConfigurationException)
info.GetValue(numPrefix + SERIALIZATION_PARAM_ERROR_DATA,
currentExceptionType);
}
}
}
[SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter=true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
int subErrors = 0;
string numPrefix;
// call base implementation
base.GetObjectData(info, context);
// Serialize our members
info.AddValue(SERIALIZATION_PARAM_FILENAME, Filename);
info.AddValue(SERIALIZATION_PARAM_LINE, Line);
// Serialize rest of errors, along with count
// (since first error duplicates this error, only worry if
// there is more than one)
if ((_errors != null) &&
(_errors.Length > 1 )){
subErrors = _errors.Length;
for (int i = 0; i < _errors.Length; i++) {
numPrefix = i.ToString(CultureInfo.InvariantCulture);
info.AddValue(numPrefix + SERIALIZATION_PARAM_ERROR_DATA,
_errors[i]);
info.AddValue(numPrefix + SERIALIZATION_PARAM_ERROR_TYPE,
_errors[i].GetType());
}
}
info.AddValue(SERIALIZATION_PARAM_ERROR_COUNT, subErrors);
}
// The message includes the file/line number information.
// To get the message without the extra information, use BareMessage.
public override string Message {
get {
string file = Filename;
if (!string.IsNullOrEmpty(file)) {
if (Line != 0) {
return BareMessage + " (" + file + " line " + Line.ToString(CultureInfo.CurrentCulture) + ")";
}
else {
return BareMessage + " (" + file + ")";
}
}
else if (Line != 0) {
return BareMessage + " (line " + Line.ToString("G", CultureInfo.CurrentCulture) + ")";
}
else {
return BareMessage;
}
}
}
public override string BareMessage {
get {
return base.BareMessage;
}
}
public override string Filename {
get {
return SafeFilename(_firstFilename);
}
}
public override int Line {
get {
return _firstLine;
}
}
public ICollection Errors {
get {
if (_errors != null) {
return _errors;
}
else {
ConfigurationErrorsException e = new ConfigurationErrorsException(BareMessage, base.InnerException, _firstFilename, _firstLine);
ConfigurationException[] a = new ConfigurationException[] {e};
return a;
}
}
}
internal ICollection<ConfigurationException> ErrorsGeneric {
get {
return (ICollection<ConfigurationException>) this.Errors;
}
}
//
// Get file and linenumber from an XML Node in a DOM
//
public static int GetLineNumber(XmlNode node) {
return GetConfigErrorInfoLineNumber(node as IConfigErrorInfo);
}
public static string GetFilename(XmlNode node) {
return SafeFilename(GetUnsafeFilename(node));
}
private static string GetUnsafeFilename(XmlNode node) {
return GetUnsafeConfigErrorInfoFilename(node as IConfigErrorInfo);
}
//
// Get file and linenumber from an XML Reader
//
public static int GetLineNumber(XmlReader reader) {
return GetConfigErrorInfoLineNumber(reader as IConfigErrorInfo);
}
public static string GetFilename(XmlReader reader) {
return SafeFilename(GetUnsafeFilename(reader));
}
private static string GetUnsafeFilename(XmlReader reader) {
return GetUnsafeConfigErrorInfoFilename(reader as IConfigErrorInfo);
}
//
// Get file and linenumber from an IConfigErrorInfo
//
private static int GetConfigErrorInfoLineNumber(IConfigErrorInfo errorInfo) {
if (errorInfo != null) {
return errorInfo.LineNumber;
}
else {
return 0;
}
}
private static string GetUnsafeConfigErrorInfoFilename(IConfigErrorInfo errorInfo) {
if (errorInfo != null) {
return errorInfo.Filename;
}
else {
return null;
}
}
[FileIOPermission(SecurityAction.Assert, AllFiles = FileIOPermissionAccess.PathDiscovery)]
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "This method simply extracts the filename, which isn't sensitive information.")]
private static string ExtractFileNameWithAssert(string filename) {
// This method can throw; callers should wrap in try / catch.
string fullPath = Path.GetFullPath(filename);
return Path.GetFileName(fullPath);
}
//
// Internal Helper to strip a full path to just filename.ext when caller
// does not have path discovery to the path (used for sane error handling).
//
internal static string SafeFilename(string filename) {
if (string.IsNullOrEmpty(filename)) {
return filename;
}
// configuration file can be an http URL in IE
if (StringUtil.StartsWithIgnoreCase(filename, HTTP_PREFIX)) {
return filename;
}
//
// If it is a relative path, return it as is.
// This could happen if the exception was constructed from the serialization constructor,
// and the caller did not have PathDiscoveryPermission for the file.
//
try {
if (!Path.IsPathRooted(filename)) {
return filename;
}
}
catch {
return null;
}
try {
// Confirm that it is a full path.
// GetFullPath will also Demand PathDiscovery for the resulting path
string fullPath = Path.GetFullPath(filename);
}
catch (SecurityException) {
// Get just the name of the file without the directory part.
try {
filename = ExtractFileNameWithAssert(filename);
}
catch {
filename = null;
}
}
catch {
filename = null;
}
return filename;
}
//
// Internal Helper to always strip a full path to just filename.ext.
//
internal static string AlwaysSafeFilename(string filename) {
if (string.IsNullOrEmpty(filename)) {
return filename;
}
// configuration file can be an http URL in IE
if (StringUtil.StartsWithIgnoreCase(filename, HTTP_PREFIX)) {
return filename;
}
//
// If it is a relative path, return it as is.
// This could happen if the exception was constructed from the serialization constructor,
// and the caller did not have PathDiscoveryPermission for the file.
//
try {
if (!Path.IsPathRooted(filename)) {
return filename;
}
}
catch {
return null;
}
// Get just the name of the file without the directory part.
try {
filename = ExtractFileNameWithAssert(filename);
}
catch {
filename = null;
}
return filename;
}
}
}
| |
using System;
using NBitcoin.BouncyCastle.Crypto.Parameters;
using NBitcoin.BouncyCastle.Math;
using NBitcoin.BouncyCastle.Utilities;
namespace NBitcoin.BouncyCastle.Crypto.Engines
{
/**
* support class for constructing intergrated encryption ciphers
* for doing basic message exchanges on top of key agreement ciphers
*/
public class IesEngine
{
private readonly IBasicAgreement agree;
private readonly IDerivationFunction kdf;
private readonly IMac mac;
private readonly BufferedBlockCipher cipher;
private readonly byte[] macBuf;
private bool forEncryption;
private ICipherParameters privParam, pubParam;
private IesParameters param;
/**
* set up for use with stream mode, where the key derivation function
* is used to provide a stream of bytes to xor with the message.
*
* @param agree the key agreement used as the basis for the encryption
* @param kdf the key derivation function used for byte generation
* @param mac the message authentication code generator for the message
*/
public IesEngine(
IBasicAgreement agree,
IDerivationFunction kdf,
IMac mac)
{
this.agree = agree;
this.kdf = kdf;
this.mac = mac;
this.macBuf = new byte[mac.GetMacSize()];
// this.cipher = null;
}
/**
* set up for use in conjunction with a block cipher to handle the
* message.
*
* @param agree the key agreement used as the basis for the encryption
* @param kdf the key derivation function used for byte generation
* @param mac the message authentication code generator for the message
* @param cipher the cipher to used for encrypting the message
*/
public IesEngine(
IBasicAgreement agree,
IDerivationFunction kdf,
IMac mac,
BufferedBlockCipher cipher)
{
this.agree = agree;
this.kdf = kdf;
this.mac = mac;
this.macBuf = new byte[mac.GetMacSize()];
this.cipher = cipher;
}
/**
* Initialise the encryptor.
*
* @param forEncryption whether or not this is encryption/decryption.
* @param privParam our private key parameters
* @param pubParam the recipient's/sender's public key parameters
* @param param encoding and derivation parameters.
*/
public void Init(
bool forEncryption,
ICipherParameters privParameters,
ICipherParameters pubParameters,
ICipherParameters iesParameters)
{
this.forEncryption = forEncryption;
this.privParam = privParameters;
this.pubParam = pubParameters;
this.param = (IesParameters)iesParameters;
}
private byte[] DecryptBlock(
byte[] in_enc,
int inOff,
int inLen,
byte[] z)
{
byte[] M = null;
KeyParameter macKey = null;
KdfParameters kParam = new KdfParameters(z, param.GetDerivationV());
int macKeySize = param.MacKeySize;
kdf.Init(kParam);
inLen -= mac.GetMacSize();
if (cipher == null) // stream mode
{
byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8));
M = new byte[inLen];
for (int i = 0; i != inLen; i++)
{
M[i] = (byte)(in_enc[inOff + i] ^ Buffer[i]);
}
macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8));
}
else
{
int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize;
byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8));
cipher.Init(false, new KeyParameter(Buffer, 0, (cipherKeySize / 8)));
M = cipher.DoFinal(in_enc, inOff, inLen);
macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8));
}
byte[] macIV = param.GetEncodingV();
mac.Init(macKey);
mac.BlockUpdate(in_enc, inOff, inLen);
mac.BlockUpdate(macIV, 0, macIV.Length);
mac.DoFinal(macBuf, 0);
inOff += inLen;
byte[] T1 = Arrays.CopyOfRange(in_enc, inOff, inOff + macBuf.Length);
if (!Arrays.ConstantTimeAreEqual(T1, macBuf))
throw (new InvalidCipherTextException("Invalid MAC."));
return M;
}
private byte[] EncryptBlock(
byte[] input,
int inOff,
int inLen,
byte[] z)
{
byte[] C = null;
KeyParameter macKey = null;
KdfParameters kParam = new KdfParameters(z, param.GetDerivationV());
int c_text_length = 0;
int macKeySize = param.MacKeySize;
if (cipher == null) // stream mode
{
byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8));
C = new byte[inLen + mac.GetMacSize()];
c_text_length = inLen;
for (int i = 0; i != inLen; i++)
{
C[i] = (byte)(input[inOff + i] ^ Buffer[i]);
}
macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8));
}
else
{
int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize;
byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8));
cipher.Init(true, new KeyParameter(Buffer, 0, (cipherKeySize / 8)));
c_text_length = cipher.GetOutputSize(inLen);
byte[] tmp = new byte[c_text_length];
int len = cipher.ProcessBytes(input, inOff, inLen, tmp, 0);
len += cipher.DoFinal(tmp, len);
C = new byte[len + mac.GetMacSize()];
c_text_length = len;
Array.Copy(tmp, 0, C, 0, len);
macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8));
}
byte[] macIV = param.GetEncodingV();
mac.Init(macKey);
mac.BlockUpdate(C, 0, c_text_length);
mac.BlockUpdate(macIV, 0, macIV.Length);
//
// return the message and it's MAC
//
mac.DoFinal(C, c_text_length);
return C;
}
private byte[] GenerateKdfBytes(
KdfParameters kParam,
int length)
{
byte[] buf = new byte[length];
kdf.Init(kParam);
kdf.GenerateBytes(buf, 0, buf.Length);
return buf;
}
public byte[] ProcessBlock(
byte[] input,
int inOff,
int inLen)
{
agree.Init(privParam);
BigInteger z = agree.CalculateAgreement(pubParam);
byte[] zBytes = BigIntegers.AsUnsignedByteArray(agree.GetFieldSize(), z);
return forEncryption
? EncryptBlock(input, inOff, inLen, zBytes)
: DecryptBlock(input, inOff, inLen, zBytes);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Globalization;
using System.IO;
using System.Runtime;
using System.Runtime.Serialization;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Xml;
namespace System.ServiceModel.Channels
{
public abstract class MessageHeader : MessageHeaderInfo
{
private const bool DefaultRelayValue = false;
private const bool DefaultMustUnderstandValue = false;
private const string DefaultActorValue = "";
public override string Actor
{
get { return ""; }
}
public override bool IsReferenceParameter
{
get { return false; }
}
public override bool MustUnderstand
{
get { return DefaultMustUnderstandValue; }
}
public override bool Relay
{
get { return DefaultRelayValue; }
}
public virtual bool IsMessageVersionSupported(MessageVersion messageVersion)
{
if (messageVersion == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion");
}
return true;
}
public override string ToString()
{
StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
XmlWriterSettings xmlSettings = new XmlWriterSettings() { Indent = true };
XmlWriter textWriter = XmlWriter.Create(stringWriter, xmlSettings);
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(textWriter);
if (IsMessageVersionSupported(MessageVersion.Soap12WSAddressing10))
{
WriteHeader(writer, MessageVersion.Soap12WSAddressing10);
}
else if (IsMessageVersionSupported(MessageVersion.Soap11WSAddressing10))
{
WriteHeader(writer, MessageVersion.Soap11WSAddressing10);
}
else if (IsMessageVersionSupported(MessageVersion.Soap12))
{
WriteHeader(writer, MessageVersion.Soap12);
}
else if (IsMessageVersionSupported(MessageVersion.Soap11))
{
WriteHeader(writer, MessageVersion.Soap11);
}
else
{
WriteHeader(writer, MessageVersion.None);
}
writer.Flush();
return stringWriter.ToString();
}
public void WriteHeader(XmlWriter writer, MessageVersion messageVersion)
{
WriteHeader(XmlDictionaryWriter.CreateDictionaryWriter(writer), messageVersion);
}
public void WriteHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer"));
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion"));
OnWriteStartHeader(writer, messageVersion);
OnWriteHeaderContents(writer, messageVersion);
writer.WriteEndElement();
}
public void WriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer"));
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion"));
OnWriteStartHeader(writer, messageVersion);
}
protected virtual void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteStartElement(this.Name, this.Namespace);
WriteHeaderAttributes(writer, messageVersion);
}
public void WriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer"));
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion"));
OnWriteHeaderContents(writer, messageVersion);
}
protected abstract void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion);
protected void WriteHeaderAttributes(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
string actor = this.Actor;
if (actor.Length > 0)
writer.WriteAttributeString(messageVersion.Envelope.DictionaryActor, messageVersion.Envelope.DictionaryNamespace, actor);
if (this.MustUnderstand)
writer.WriteAttributeString(XD.MessageDictionary.MustUnderstand, messageVersion.Envelope.DictionaryNamespace, "1");
if (this.Relay && messageVersion.Envelope == EnvelopeVersion.Soap12)
writer.WriteAttributeString(XD.Message12Dictionary.Relay, XD.Message12Dictionary.Namespace, "1");
}
public static MessageHeader CreateHeader(string name, string ns, object value)
{
return CreateHeader(name, ns, value, DefaultMustUnderstandValue, DefaultActorValue, DefaultRelayValue);
}
public static MessageHeader CreateHeader(string name, string ns, object value, bool mustUnderstand)
{
return CreateHeader(name, ns, value, mustUnderstand, DefaultActorValue, DefaultRelayValue);
}
public static MessageHeader CreateHeader(string name, string ns, object value, bool mustUnderstand, string actor)
{
return CreateHeader(name, ns, value, mustUnderstand, actor, DefaultRelayValue);
}
public static MessageHeader CreateHeader(string name, string ns, object value, bool mustUnderstand, string actor, bool relay)
{
return new XmlObjectSerializerHeader(name, ns, value, null, mustUnderstand, actor, relay);
}
public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer)
{
return CreateHeader(name, ns, value, serializer, DefaultMustUnderstandValue, DefaultActorValue, DefaultRelayValue);
}
public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand)
{
return CreateHeader(name, ns, value, serializer, mustUnderstand, DefaultActorValue, DefaultRelayValue);
}
public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand, string actor)
{
return CreateHeader(name, ns, value, serializer, mustUnderstand, actor, DefaultRelayValue);
}
public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay)
{
if (serializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer"));
return new XmlObjectSerializerHeader(name, ns, value, serializer, mustUnderstand, actor, relay);
}
internal static void GetHeaderAttributes(XmlDictionaryReader reader, MessageVersion version,
out string actor, out bool mustUnderstand, out bool relay, out bool isReferenceParameter)
{
int attributeCount = reader.AttributeCount;
if (attributeCount == 0)
{
mustUnderstand = false;
actor = string.Empty;
relay = false;
isReferenceParameter = false;
}
else
{
string mustUnderstandString = reader.GetAttribute(XD.MessageDictionary.MustUnderstand, version.Envelope.DictionaryNamespace);
if (mustUnderstandString != null && ToBoolean(mustUnderstandString))
mustUnderstand = true;
else
mustUnderstand = false;
if (mustUnderstand && attributeCount == 1)
{
actor = string.Empty;
relay = false;
}
else
{
actor = reader.GetAttribute(version.Envelope.DictionaryActor, version.Envelope.DictionaryNamespace);
if (actor == null)
actor = "";
if (version.Envelope == EnvelopeVersion.Soap12)
{
string relayString = reader.GetAttribute(XD.Message12Dictionary.Relay, version.Envelope.DictionaryNamespace);
if (relayString != null && ToBoolean(relayString))
relay = true;
else
relay = false;
}
else
{
relay = false;
}
}
isReferenceParameter = false;
if (version.Addressing == AddressingVersion.WSAddressing10)
{
string refParam = reader.GetAttribute(XD.AddressingDictionary.IsReferenceParameter, version.Addressing.DictionaryNamespace);
if (refParam != null)
isReferenceParameter = ToBoolean(refParam);
}
}
}
private static bool ToBoolean(string value)
{
if (value.Length == 1)
{
char ch = value[0];
if (ch == '1')
{
return true;
}
if (ch == '0')
{
return false;
}
}
else
{
if (value == "true")
{
return true;
}
else if (value == "false")
{
return false;
}
}
try
{
return XmlConvert.ToBoolean(value);
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(exception.Message, null));
}
}
}
internal abstract class DictionaryHeader : MessageHeader
{
public override string Name
{
get { return DictionaryName.Value; }
}
public override string Namespace
{
get { return DictionaryNamespace.Value; }
}
public abstract XmlDictionaryString DictionaryName { get; }
public abstract XmlDictionaryString DictionaryNamespace { get; }
protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteStartElement(DictionaryName, DictionaryNamespace);
WriteHeaderAttributes(writer, messageVersion);
}
}
internal class XmlObjectSerializerHeader : MessageHeader
{
private XmlObjectSerializer _serializer;
private bool _mustUnderstand;
private bool _relay;
private bool _isOneTwoSupported;
private bool _isOneOneSupported;
private bool _isNoneSupported;
private object _objectToSerialize;
private string _name;
private string _ns;
private string _actor;
private object _syncRoot = new object();
private XmlObjectSerializerHeader(XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay)
{
if (actor == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("actor");
}
_mustUnderstand = mustUnderstand;
_relay = relay;
_serializer = serializer;
_actor = actor;
if (actor == EnvelopeVersion.Soap12.UltimateDestinationActor)
{
_isOneOneSupported = false;
_isOneTwoSupported = true;
}
else if (actor == EnvelopeVersion.Soap12.NextDestinationActorValue)
{
_isOneOneSupported = false;
_isOneTwoSupported = true;
}
else if (actor == EnvelopeVersion.Soap11.NextDestinationActorValue)
{
_isOneOneSupported = true;
_isOneTwoSupported = false;
}
else
{
_isOneOneSupported = true;
_isOneTwoSupported = true;
_isNoneSupported = true;
}
}
public XmlObjectSerializerHeader(string name, string ns, object objectToSerialize, XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay)
: this(serializer, mustUnderstand, actor, relay)
{
if (null == name)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name"));
}
if (name.Length == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.SFXHeaderNameCannotBeNullOrEmpty, "name"));
}
if (ns == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns");
}
if (ns.Length > 0)
{
NamingHelper.CheckUriParameter(ns, "ns");
}
_objectToSerialize = objectToSerialize;
_name = name;
_ns = ns;
}
public override bool IsMessageVersionSupported(MessageVersion messageVersion)
{
if (messageVersion == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion");
}
if (messageVersion.Envelope == EnvelopeVersion.Soap12)
{
return _isOneTwoSupported;
}
else if (messageVersion.Envelope == EnvelopeVersion.Soap11)
{
return _isOneOneSupported;
}
else if (messageVersion.Envelope == EnvelopeVersion.None)
{
return _isNoneSupported;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.EnvelopeVersionUnknown, messageVersion.Envelope.ToString())));
}
}
public override string Name
{
get { return _name; }
}
public override string Namespace
{
get { return _ns; }
}
public override bool MustUnderstand
{
get { return _mustUnderstand; }
}
public override bool Relay
{
get { return _relay; }
}
public override string Actor
{
get { return _actor; }
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
lock (_syncRoot)
{
if (_serializer == null)
{
_serializer = DataContractSerializerDefaults.CreateSerializer(
(_objectToSerialize == null ? typeof(object) : _objectToSerialize.GetType()), this.Name, this.Namespace, int.MaxValue/*maxItems*/);
}
_serializer.WriteObjectContent(writer, _objectToSerialize);
}
}
}
internal abstract class ReadableMessageHeader : MessageHeader
{
public abstract XmlDictionaryReader GetHeaderReader();
protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
if (!IsMessageVersionSupported(messageVersion))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MessageHeaderVersionNotSupported, this.GetType().FullName, messageVersion.ToString()), "version"));
XmlDictionaryReader reader = GetHeaderReader();
writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
writer.WriteAttributes(reader, false);
reader.Dispose();
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
XmlDictionaryReader reader = GetHeaderReader();
reader.ReadStartElement();
while (reader.NodeType != XmlNodeType.EndElement)
writer.WriteNode(reader, false);
reader.ReadEndElement();
reader.Dispose();
}
}
internal interface IMessageHeaderWithSharedNamespace
{
XmlDictionaryString SharedNamespace { get; }
XmlDictionaryString SharedPrefix { get; }
}
internal class BufferedHeader : ReadableMessageHeader
{
private MessageVersion _version;
private XmlBuffer _buffer;
private int _bufferIndex;
private string _actor;
private bool _relay;
private bool _mustUnderstand;
private string _name;
private string _ns;
private bool _streamed;
private bool _isRefParam;
public BufferedHeader(MessageVersion version, XmlBuffer buffer, int bufferIndex, string name, string ns, bool mustUnderstand, string actor, bool relay, bool isRefParam)
{
_version = version;
_buffer = buffer;
_bufferIndex = bufferIndex;
_name = name;
_ns = ns;
_mustUnderstand = mustUnderstand;
_actor = actor;
_relay = relay;
_isRefParam = isRefParam;
}
public BufferedHeader(MessageVersion version, XmlBuffer buffer, int bufferIndex, MessageHeaderInfo headerInfo)
{
_version = version;
_buffer = buffer;
_bufferIndex = bufferIndex;
_actor = headerInfo.Actor;
_relay = headerInfo.Relay;
_name = headerInfo.Name;
_ns = headerInfo.Namespace;
_isRefParam = headerInfo.IsReferenceParameter;
_mustUnderstand = headerInfo.MustUnderstand;
}
public BufferedHeader(MessageVersion version, XmlBuffer buffer, XmlDictionaryReader reader, XmlAttributeHolder[] envelopeAttributes, XmlAttributeHolder[] headerAttributes)
{
_streamed = true;
_buffer = buffer;
_version = version;
GetHeaderAttributes(reader, version, out _actor, out _mustUnderstand, out _relay, out _isRefParam);
_name = reader.LocalName;
_ns = reader.NamespaceURI;
Fx.Assert(_name != null, "");
Fx.Assert(_ns != null, "");
_bufferIndex = buffer.SectionCount;
XmlDictionaryWriter writer = buffer.OpenSection(reader.Quotas);
// Write an enclosing Envelope tag
writer.WriteStartElement(MessageStrings.Envelope);
if (envelopeAttributes != null)
XmlAttributeHolder.WriteAttributes(envelopeAttributes, writer);
// Write and enclosing Header tag
writer.WriteStartElement(MessageStrings.Header);
if (headerAttributes != null)
XmlAttributeHolder.WriteAttributes(headerAttributes, writer);
writer.WriteNode(reader, false);
writer.WriteEndElement();
writer.WriteEndElement();
buffer.CloseSection();
}
public override string Actor
{
get { return _actor; }
}
public override bool IsReferenceParameter
{
get { return _isRefParam; }
}
public override string Name
{
get { return _name; }
}
public override string Namespace
{
get { return _ns; }
}
public override bool MustUnderstand
{
get { return _mustUnderstand; }
}
public override bool Relay
{
get { return _relay; }
}
public override bool IsMessageVersionSupported(MessageVersion messageVersion)
{
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion"));
return messageVersion == _version;
}
public override XmlDictionaryReader GetHeaderReader()
{
XmlDictionaryReader reader = _buffer.GetReader(_bufferIndex);
// See if we need to move past the enclosing envelope/header
if (_streamed)
{
reader.MoveToContent();
reader.Read(); // Envelope
reader.Read(); // Header
reader.MoveToContent();
}
return reader;
}
}
}
| |
// 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.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Common.Core;
using Microsoft.R.Platform.Composition;
using Microsoft.UnitTests.Core.Mef;
namespace Microsoft.Languages.Editor.Test.Shell {
/// <summary>
/// Composition catalog that is primarily used in interactive tests.
/// It is assigned to shell.Current.CompositionService.
/// In interactive tests catalog that also includes host application
/// objects such as VS components is not suitable as it may be exporting
/// objects that cannot be instantiated in a limited test environment.
/// </summary>
[ExcludeFromCodeCoverage]
public class EditorTestCompositionCatalog : ICompositionCatalog {
/// <summary>
/// Instance of the compostion catalog to use in editor tests.
/// It should not be used in the app/package level tests.
/// </summary>
private static readonly Lazy<EditorTestCompositionCatalog> _instance = Lazy.Create(() => new EditorTestCompositionCatalog());
private static readonly object _containerLock = new object();
/// <summary>
/// MEF container of this instance. Note that there may be more
/// than one container in test runs. For example, editor tests
/// just the editor-levle container that does not have objects
/// exported from the package. Package tests use bigger container
/// that also includes objects exported from package-level assemblies.
/// </summary>
private readonly CompositionContainer _container;
private static bool _traceExportImports = false;
/// <summary>
/// Assemblies used at the R editor level
/// </summary>
private static readonly string[] _rtvsEditorAssemblies = {
"Microsoft.Markdown.Editor.Windows.dll",
"Microsoft.Languages.Editor.dll",
"Microsoft.Languages.Editor.Windows.dll",
"Microsoft.Languages.Editor.Application.dll",
"Microsoft.R.Editor.dll",
"Microsoft.R.Editor.Windows.dll",
"Microsoft.R.Editor.Test.dll",
"Microsoft.R.Components.dll",
"Microsoft.R.Components.Windows.dll",
"Microsoft.R.Components.Windows.Test.dll",
"Microsoft.R.Common.Core.dll",
"Microsoft.R.Host.Client.Windows.dll",
"Microsoft.R.Debugger.dll",
};
/// <summary>
/// Assemblies of the VS core text editor
/// </summary>
private static readonly string[] _coreEditorAssemblies = {
"Microsoft.VisualStudio.CoreUtility.dll",
"Microsoft.VisualStudio.Text.Data.dll",
"Microsoft.VisualStudio.Text.Internal.dll",
"Microsoft.VisualStudio.Text.Logic.dll",
"Microsoft.VisualStudio.Text.UI.dll",
"Microsoft.VisualStudio.Text.UI.Wpf.dll",
"Microsoft.VisualStudio.Editor.dll",
"Microsoft.VisualStudio.Language.Intellisense.dll",
"Microsoft.VisualStudio.Platform.VSEditor.dll",
"Microsoft.VisualStudio.Platform.VSEditor.Interop.dll"
};
/// <summary>
/// Additional assemblies supplied by the creator class
/// </summary>
private static string[] _additionalAssemblies = new string[0];
/// <summary>
/// Instance of the compostion catalog to use in editor tests.
/// It should not be used in the app/package level tests.
/// </summary>
public static ICompositionCatalog Current => _instance.Value;
/// <summary>
/// Only used if catalog is created as part of a bigger catalog
/// such as when package-level tests supply additional assemblies.
/// </summary>
/// <param name="additionalAssemblies"></param>
public EditorTestCompositionCatalog(string[] additionalAssemblies) {
_additionalAssemblies = additionalAssemblies;
_container = CreateContainer();
}
private EditorTestCompositionCatalog() {
_container = CreateContainer();
}
private CompositionContainer CreateContainer() {
lock (_containerLock) {
var assemblies = new List<string>();
assemblies.AddRange(_coreEditorAssemblies);
assemblies.AddRange(_rtvsEditorAssemblies);
assemblies.AddRange(_additionalAssemblies);
var aggregateCatalog = CatalogFactory.CreateAssembliesCatalog(assemblies);
var thisAssemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
aggregateCatalog.Catalogs.Add(thisAssemblyCatalog);
var filteredCatalog = aggregateCatalog.Filter(cpd => !cpd.ContainsPartMetadataWithKey(PartMetadataAttributeNames.SkipInEditorTestCompositionCatalog));
var container = BuildCatalog(filteredCatalog);
return container;
}
}
private CompositionContainer BuildCatalog(ComposablePartCatalog aggregateCatalog) {
var container = new CompositionContainer(aggregateCatalog, isThreadSafe: true);
container.ComposeParts(container.Catalog.Parts.AsEnumerable());
TraceExportImports(container);
return container;
}
private void TraceExportImports(CompositionContainer container) {
if (!_traceExportImports) {
return;
}
var parts = new StringBuilder();
var exports = new StringBuilder();
foreach (var part in container.Catalog.Parts) {
parts.AppendLine("===============================================================");
parts.AppendLine(part.ToString());
exports.AppendLine("===============================================================");
exports.AppendLine(part.ToString());
var first = true;
if (part.ExportDefinitions.Any()) {
parts.AppendLine("\t --- EXPORTS --");
exports.AppendLine("\t --- EXPORTS --");
foreach (var exportDefinition in part.ExportDefinitions) {
parts.AppendLine("\t" + exportDefinition.ContractName);
exports.AppendLine("\t" + exportDefinition.ContractName);
foreach (var kvp in exportDefinition.Metadata) {
string valueString = kvp.Value?.ToString() ?? string.Empty;
parts.AppendLine("\t" + kvp.Key + " : " + valueString);
exports.AppendLine("\t" + kvp.Key + " : " + valueString);
}
if (first) {
first = false;
} else {
parts.AppendLine("------------------------------------------------------");
exports.AppendLine("------------------------------------------------------");
}
}
}
if (part.ImportDefinitions.Any()) {
parts.AppendLine("\t --- IMPORTS ---");
foreach (var importDefinition in part.ImportDefinitions) {
parts.AppendLine("\t" + importDefinition.ContractName);
parts.AppendLine("\t" + importDefinition.Constraint.ToString());
parts.AppendLine("\t" + importDefinition.Cardinality.ToString());
if (first) {
first = false;
} else {
parts.AppendLine("------------------------------------------------------");
}
}
}
}
WriteTraceToFile(parts.ToString(), "Parts.txt");
WriteTraceToFile(exports.ToString(), "Exports.txt");
}
private void WriteTraceToFile(string s, string fileName) {
var filePath = Path.Combine(Path.GetTempPath(), fileName);
File.Delete(filePath);
using (var sw = new StreamWriter(filePath)) {
sw.Write(s);
}
}
#region ICompositionCatalog
public ICompositionService CompositionService => _container;
public ExportProvider ExportProvider => _container;
public CompositionContainer Container => _container;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace NotJavaScript.Tree
{
public interface gType
{
string str();
bool Suitable(Environment E, gType X);
}
public class Type_Boolean : gType
{
public string str() { return "bool"; }
public bool Suitable(Environment E, gType X)
{
return X is Type_Boolean;
}
}
public class Type_Integer : gType
{
public string str() { return "int"; }
public bool Suitable(Environment E, gType X)
{
return X is Type_Integer;
}
}
public class Type_Real : gType
{
public string str() { return "real"; }
public bool Suitable(Environment E, gType X)
{
return X is Type_Integer || X is Type_Real;
}
}
public class Type_String : gType
{
public string str() { return "string"; }
public bool Suitable(Environment E, gType X)
{
return X is Type_String || X is Type_Real || X is Type_Integer || X is Type_Boolean;
}
}
public class Type_Unknown : gType
{
public string str() { return "???"; }
public bool Suitable(Environment E, gType X)
{
return false;
}
}
public class Type_Unit : gType
{
public string str() { return "void"; }
public bool Suitable(Environment E, gType X)
{
if (X is Type_Unit) return true;
if (X is Type_Tuple)
{
if ((X as Type_Tuple).Empty())
return true;
}
return false;
}
}
public class Type_NamedType : gType
{
public string Name;
public Type_NamedType(string n)
{
Name = n;
}
public bool Suitable(Environment E, gType X)
{
if (X is Type_NamedType)
{
if ((X as Type_NamedType).Name.Equals(Name))
{
return true;
}
}
if (E.Enumerations.ContainsKey(Name))
{
return E.Enumerations[Name].Suitable(E, X);
}
if(E.Contracts.ContainsKey(Name))
{
return E.Contracts[Name].Suitable(E, X);
}
throw new Exception("Could not find Contract Type:" + Name);
}
public string str() { return "" + Name +""; }
}
public class Type_EnumerationBySet : gType
{
public List<string> Elements;
public Type_EnumerationBySet()
{
Elements = new List<string>();
}
public void Add(string x)
{
Elements.Add(x);
}
public bool Suitable(Environment E, gType Y)
{
gType X = Y;
if (X is Type_NamedType)
{
if (E.Enumerations.ContainsKey((X as Type_NamedType).Name))
{
X = E.Enumerations[(X as Type_NamedType).Name];
}
}
if (X is Type_EnumerationBySet)
{
Type_EnumerationBySet S = (X as Type_EnumerationBySet);
foreach (string x in S.Elements)
{
bool z = false;
foreach (string y in Elements)
{
if (y.Equals(x))
{
z = true;
}
}
if (!z)
{
return false;
}
}
return true;
}
return false;
}
public string str2(string N)
{
return "enum " + N + str();
}
public string str()
{
string z = "|";
int k = 0;
foreach (string x in Elements)
{
if (k > 0) z += ",";
z += x;
}
z += "|";
return z;
}
}
public class Type_ContractByMembers : gType
{
public SortedDictionary<string, gType> Members;
public Type_ContractByMembers()
{
Members = new SortedDictionary<string, gType>();
}
public void Map(string x, gType t)
{
Members.Add(x, t);
}
public bool Suitable(Environment E, gType X)
{
gType Y = X;
if (Y is Type_NamedType)
{
string name = (Y as Type_NamedType).Name;
if(E.Contracts.ContainsKey(name))
{
Y = E.Contracts[name];
}
else
{
return false;
}
}
if (Y is Type_ContractByMembers)
{
Type_ContractByMembers R = Y as Type_ContractByMembers;
if (R.Members.Count == 0)
{
// Null Special Case
return true;
}
foreach (string x in Members.Keys)
{
if (R.Members.ContainsKey(x))
{
if (!Members[x].Suitable(E, R.Members[x]))
{
return false;
}
}
else
{
return false;
}
}
return true;
}
return false;
}
public string str()
{
string z = "{";
foreach (string x in Members.Keys)
{
z += x + " " + Members[x].str() + ";";
}
z += "}";
return z;
}
public string str2(string N)
{
string z = "constract " + N + " {";
foreach (string x in Members.Keys)
{
z += x + " " + Members[x].str() + ";";
}
z += "}";
return z;
}
}
public class Type_ArrayOf : gType
{
public gType Base;
public Type_ArrayOf(gType b)
{
Base = b;
}
public bool Suitable(Environment E, gType X)
{
if (X is Type_ArrayOf)
{
return Base.Suitable(E,(X as Type_ArrayOf).Base);
}
return false;
}
public string str() { return Base.str() + "[]"; }
}
public class Type_Tuple : gType
{
List<gType> Args;
public Type_Tuple()
{
Args = new List<gType>();
}
public void Add(gType x)
{
Args.Add(x);
}
public bool Empty()
{
return Args.Count == 0;
}
public gType Reduce()
{
if (Args.Count == 0) return new Type_Unit();
if (Args.Count == 1) return Args[0];
return this;
}
public int Arity()
{
return Args.Count;
}
public bool Suitable(Environment E, gType X)
{
if (Empty())
{
if (X is Type_Unit)
return true;
}
if (X is Type_Tuple)
{
List<gType> Xargs = (X as Type_Tuple).Args;
if (Args.Count == Xargs.Count)
{
for (int k = 0; k < Args.Count; k++)
{
if (!Args[k].Suitable(E, Xargs[k]))
return false;
}
return true;
}
}
return false;
}
public string str()
{
string x = "";
int k = 0;
foreach(gType T in Args)
{
if(k > 0) x+= ",";
x += T.str();
k++;
}
return "(" + x + ")";
}
};
public class Type_Nil : gType
{
public bool Suitable(Environment E, gType X)
{
return X is Type_Nil;
}
public string str()
{
return "nil";
}
}
public class Type_Functional : gType
{
public gType Inputs;
public gType Output;
public gType Requirements;
public Type_Functional(gType I, gType O)
{
Inputs = I;
if (I is Type_Tuple)
{
Inputs = (I as Type_Tuple).Reduce();
}
Output = O;
Requirements = null;
}
public bool Suitable(Environment E, gType X)
{
if (X is Type_Nil)
{
return true;
}
if(X is Type_Functional)
{
return (Inputs.Suitable(E, (X as Type_Functional).Inputs)) && (Output.Suitable(E, (X as Type_Functional).Output));
}
return false;
}
public int Arity()
{
if (Inputs is Type_Unit) return 0;
if (Inputs is Type_Tuple)
{
return (Inputs as Type_Tuple).Arity();
}
return 1;
}
public string str()
{
string z = Inputs.str() + "->" + Output.str();
if (Requirements != null)
{
z += " requires " + Requirements.str();
}
return z;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Binary;
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());
for (int i = 0; i < span.Length; i++)
{
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], 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], 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], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
}
}
[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());
for (int i = 0; i < span.Length; i++)
{
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], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
}
}
[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);
try
{
spanA.CopyTo(spanB);
Assert.True(false);
}
catch (Exception)
{
Assert.True(true);
}
}
}
[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);
try
{
spanA.CopyTo(spanB);
Assert.True(false);
}
catch (Exception)
{
Assert.True(true);
}
}
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);
a.CopyTo(na);
IntPtr pb = Marshal.AllocHGlobal(b.Length);
Span<byte> nb = new Span<byte>(pb.ToPointer(), b.Length);
b.CopyTo(nb);
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 {
try
{
spanA.CopyTo(spanB);
Assert.True(false);
}
catch (Exception)
{
Assert.True(true);
}
}
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);
try
{
spanA.CopyTo(b);
Assert.True(false);
}
catch (Exception)
{
Assert.True(true);
}
}
}
[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);
try
{
spanA.CopyTo(b);
Assert.True(false);
}
catch (Exception)
{
Assert.True(true);
}
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.DataFactories;
using Microsoft.Azure.Management.DataFactories.Models;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.DataFactories
{
/// <summary>
/// Operations for managing hubs.
/// </summary>
internal partial class HubOperations : IServiceOperations<DataPipelineManagementClient>, IHubOperations
{
/// <summary>
/// Initializes a new instance of the HubOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal HubOperations(DataPipelineManagementClient client)
{
this._client = client;
}
private DataPipelineManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.DataFactories.DataPipelineManagementClient.
/// </summary>
public DataPipelineManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a new hub instance or update an existing instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a hub.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The create or update hub operation response.
/// </returns>
public async Task<HubCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string dataFactoryName, HubCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("dataFactoryName", dataFactoryName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "/providers/Microsoft.DataFactory/datafactories/" + dataFactoryName.Trim() + "/hubs/" + (parameters.Hub.Name != null ? parameters.Hub.Name.Trim() : "") + "?";
url = url + "api-version=2014-10-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject hubCreateOrUpdateParametersValue = new JObject();
requestDoc = hubCreateOrUpdateParametersValue;
if (parameters.Hub != null)
{
if (parameters.Hub.Name != null)
{
hubCreateOrUpdateParametersValue["name"] = parameters.Hub.Name;
}
if (parameters.Hub.Properties != null)
{
JObject propertiesValue = new JObject();
hubCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Hub.Properties is HubProperties)
{
propertiesValue["type"] = "Hub";
HubProperties derived = ((HubProperties)parameters.Hub.Properties);
if (derived.HubId != null)
{
propertiesValue["hubId"] = derived.HubId;
}
if (derived.ProvisioningState != null)
{
propertiesValue["provisioningState"] = derived.ProvisioningState;
}
}
if (parameters.Hub.Properties is InternalHubProperties)
{
propertiesValue["type"] = "InternalHub";
InternalHubProperties derived2 = ((InternalHubProperties)parameters.Hub.Properties);
if (derived2.HubId != null)
{
propertiesValue["hubId"] = derived2.HubId;
}
if (derived2.ProvisioningState != null)
{
propertiesValue["provisioningState"] = derived2.ProvisioningState;
}
}
}
}
requestContent = requestDoc.ToString(Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HubCreateOrUpdateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new HubCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Hub hubInstance = new Hub();
result.Hub = hubInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
hubInstance.Name = nameInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string typeName = ((string)propertiesValue2["type"]);
if (typeName == "Hub")
{
HubProperties hubPropertiesInstance = new HubProperties();
JToken hubIdValue = propertiesValue2["hubId"];
if (hubIdValue != null && hubIdValue.Type != JTokenType.Null)
{
string hubIdInstance = ((string)hubIdValue);
hubPropertiesInstance.HubId = hubIdInstance;
}
JToken provisioningStateValue = propertiesValue2["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
hubPropertiesInstance.ProvisioningState = provisioningStateInstance;
}
hubInstance.Properties = hubPropertiesInstance;
}
if (typeName == "InternalHub")
{
InternalHubProperties internalHubPropertiesInstance = new InternalHubProperties();
JToken hubIdValue2 = propertiesValue2["hubId"];
if (hubIdValue2 != null && hubIdValue2.Type != JTokenType.Null)
{
string hubIdInstance2 = ((string)hubIdValue2);
internalHubPropertiesInstance.HubId = hubIdInstance2;
}
JToken provisioningStateValue2 = propertiesValue2["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
internalHubPropertiesInstance.ProvisioningState = provisioningStateInstance2;
}
hubInstance.Properties = internalHubPropertiesInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
result.Location = url;
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete a hub instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='hubName'>
/// Required. The name of the hub.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> BeginDeleteAsync(string resourceGroupName, string dataFactoryName, string hubName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
if (hubName == null)
{
throw new ArgumentNullException("hubName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("dataFactoryName", dataFactoryName);
tracingParameters.Add("hubName", hubName);
Tracing.Enter(invocationId, this, "BeginDeleteAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "/providers/Microsoft.DataFactory/datafactories/" + dataFactoryName.Trim() + "/hubs/" + hubName.Trim() + "?";
url = url + "api-version=2014-10-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResponse result = null;
result = new LongRunningOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create a new hub instance or update an existing instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a hub.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The create or update hub operation response.
/// </returns>
public async Task<HubCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string dataFactoryName, HubCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
DataPipelineManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("dataFactoryName", dataFactoryName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
HubCreateOrUpdateResponse response = await client.Hubs.BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
HubCreateOrUpdateResponse result = await client.Hubs.GetCreateOrUpdateStatusAsync(response.Location, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 5;
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.Hubs.GetCreateOrUpdateStatusAsync(response.Location, cancellationToken).ConfigureAwait(false);
delayInSeconds = 5;
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
/// <summary>
/// Create a new hub instance or update an existing instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='hubName'>
/// Required. The name of the data factory hub to be created or updated.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a hub.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The create or update hub operation response.
/// </returns>
public async Task<HubCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(string resourceGroupName, string dataFactoryName, string hubName, HubCreateOrUpdateWithRawJsonContentParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
if (hubName == null)
{
throw new ArgumentNullException("hubName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Content == null)
{
throw new ArgumentNullException("parameters.Content");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("dataFactoryName", dataFactoryName);
tracingParameters.Add("hubName", hubName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateOrUpdateWithRawJsonContentAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "/providers/Microsoft.DataFactory/datafactories/" + dataFactoryName.Trim() + "/hubs/" + hubName.Trim() + "?";
url = url + "api-version=2014-10-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Content;
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HubCreateOrUpdateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new HubCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Hub hubInstance = new Hub();
result.Hub = hubInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
hubInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string typeName = ((string)propertiesValue["type"]);
if (typeName == "Hub")
{
HubProperties hubPropertiesInstance = new HubProperties();
JToken hubIdValue = propertiesValue["hubId"];
if (hubIdValue != null && hubIdValue.Type != JTokenType.Null)
{
string hubIdInstance = ((string)hubIdValue);
hubPropertiesInstance.HubId = hubIdInstance;
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
hubPropertiesInstance.ProvisioningState = provisioningStateInstance;
}
hubInstance.Properties = hubPropertiesInstance;
}
if (typeName == "InternalHub")
{
InternalHubProperties internalHubPropertiesInstance = new InternalHubProperties();
JToken hubIdValue2 = propertiesValue["hubId"];
if (hubIdValue2 != null && hubIdValue2.Type != JTokenType.Null)
{
string hubIdInstance2 = ((string)hubIdValue2);
internalHubPropertiesInstance.HubId = hubIdInstance2;
}
JToken provisioningStateValue2 = propertiesValue["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
internalHubPropertiesInstance.ProvisioningState = provisioningStateInstance2;
}
hubInstance.Properties = internalHubPropertiesInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
result.Location = url;
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete a hub instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='hubName'>
/// Required. The name of the hub.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> DeleteAsync(string resourceGroupName, string dataFactoryName, string hubName, CancellationToken cancellationToken)
{
DataPipelineManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("dataFactoryName", dataFactoryName);
tracingParameters.Add("hubName", hubName);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResponse response = await client.Hubs.BeginDeleteAsync(resourceGroupName, dataFactoryName, hubName, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
/// <summary>
/// Gets a hub instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='hubName'>
/// Required. The name of the hub.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The get hub operation response.
/// </returns>
public async Task<HubGetResponse> GetAsync(string resourceGroupName, string dataFactoryName, string hubName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
if (hubName == null)
{
throw new ArgumentNullException("hubName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("dataFactoryName", dataFactoryName);
tracingParameters.Add("hubName", hubName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "/providers/Microsoft.DataFactory/datafactories/" + dataFactoryName.Trim() + "/hubs/" + hubName.Trim() + "?";
url = url + "api-version=2014-10-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HubGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new HubGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Hub hubInstance = new Hub();
result.Hub = hubInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
hubInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string typeName = ((string)propertiesValue["type"]);
if (typeName == "Hub")
{
HubProperties hubPropertiesInstance = new HubProperties();
JToken hubIdValue = propertiesValue["hubId"];
if (hubIdValue != null && hubIdValue.Type != JTokenType.Null)
{
string hubIdInstance = ((string)hubIdValue);
hubPropertiesInstance.HubId = hubIdInstance;
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
hubPropertiesInstance.ProvisioningState = provisioningStateInstance;
}
hubInstance.Properties = hubPropertiesInstance;
}
if (typeName == "InternalHub")
{
InternalHubProperties internalHubPropertiesInstance = new InternalHubProperties();
JToken hubIdValue2 = propertiesValue["hubId"];
if (hubIdValue2 != null && hubIdValue2.Type != JTokenType.Null)
{
string hubIdInstance2 = ((string)hubIdValue2);
internalHubPropertiesInstance.HubId = hubIdInstance2;
}
JToken provisioningStateValue2 = propertiesValue["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
internalHubPropertiesInstance.ProvisioningState = provisioningStateInstance2;
}
hubInstance.Properties = internalHubPropertiesInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The create or update hub operation response.
/// </returns>
public async Task<HubCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
Tracing.Enter(invocationId, this, "GetCreateOrUpdateStatusAsync", tracingParameters);
}
// Construct URL
string url = operationStatusLink.Trim();
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
httpRequest.Headers.Add("x-ms-version", "2014-10-01-preview");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HubCreateOrUpdateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new HubCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Hub hubInstance = new Hub();
result.Hub = hubInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
hubInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string typeName = ((string)propertiesValue["type"]);
if (typeName == "Hub")
{
HubProperties hubPropertiesInstance = new HubProperties();
JToken hubIdValue = propertiesValue["hubId"];
if (hubIdValue != null && hubIdValue.Type != JTokenType.Null)
{
string hubIdInstance = ((string)hubIdValue);
hubPropertiesInstance.HubId = hubIdInstance;
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
hubPropertiesInstance.ProvisioningState = provisioningStateInstance;
}
hubInstance.Properties = hubPropertiesInstance;
}
if (typeName == "InternalHub")
{
InternalHubProperties internalHubPropertiesInstance = new InternalHubProperties();
JToken hubIdValue2 = propertiesValue["hubId"];
if (hubIdValue2 != null && hubIdValue2.Type != JTokenType.Null)
{
string hubIdInstance2 = ((string)hubIdValue2);
internalHubPropertiesInstance.HubId = hubIdInstance2;
}
JToken provisioningStateValue2 = propertiesValue["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
internalHubPropertiesInstance.ProvisioningState = provisioningStateInstance2;
}
hubInstance.Properties = internalHubPropertiesInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
result.Location = url;
if (result.Hub.Properties.ProvisioningState == "Failed")
{
result.Status = OperationStatus.Failed;
}
if (result.Hub.Properties.ProvisioningState == "Succeeded")
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the first page of data factory hub instances with the link to
/// the next page.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The list hub operation response.
/// </returns>
public async Task<HubListResponse> ListAsync(string resourceGroupName, string dataFactoryName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("dataFactoryName", dataFactoryName);
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "/providers/Microsoft.DataFactory/datafactories/" + dataFactoryName.Trim() + "/hubs?";
url = url + "api-version=2014-10-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HubListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new HubListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Hub hubInstance = new Hub();
result.Hubs.Add(hubInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
hubInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string typeName = ((string)propertiesValue["type"]);
if (typeName == "Hub")
{
HubProperties hubPropertiesInstance = new HubProperties();
JToken hubIdValue = propertiesValue["hubId"];
if (hubIdValue != null && hubIdValue.Type != JTokenType.Null)
{
string hubIdInstance = ((string)hubIdValue);
hubPropertiesInstance.HubId = hubIdInstance;
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
hubPropertiesInstance.ProvisioningState = provisioningStateInstance;
}
hubInstance.Properties = hubPropertiesInstance;
}
if (typeName == "InternalHub")
{
InternalHubProperties internalHubPropertiesInstance = new InternalHubProperties();
JToken hubIdValue2 = propertiesValue["hubId"];
if (hubIdValue2 != null && hubIdValue2.Type != JTokenType.Null)
{
string hubIdInstance2 = ((string)hubIdValue2);
internalHubPropertiesInstance.HubId = hubIdInstance2;
}
JToken provisioningStateValue2 = propertiesValue["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
internalHubPropertiesInstance.ProvisioningState = provisioningStateInstance2;
}
hubInstance.Properties = internalHubPropertiesInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the next page of data factory hub instances with the link to
/// the next page.
/// </summary>
/// <param name='nextLink'>
/// Required. The url to the next data factory hubs page.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The list hub operation response.
/// </returns>
public async Task<HubListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
Tracing.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = nextLink.Trim();
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HubListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new HubListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Hub hubInstance = new Hub();
result.Hubs.Add(hubInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
hubInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string typeName = ((string)propertiesValue["type"]);
if (typeName == "Hub")
{
HubProperties hubPropertiesInstance = new HubProperties();
JToken hubIdValue = propertiesValue["hubId"];
if (hubIdValue != null && hubIdValue.Type != JTokenType.Null)
{
string hubIdInstance = ((string)hubIdValue);
hubPropertiesInstance.HubId = hubIdInstance;
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
hubPropertiesInstance.ProvisioningState = provisioningStateInstance;
}
hubInstance.Properties = hubPropertiesInstance;
}
if (typeName == "InternalHub")
{
InternalHubProperties internalHubPropertiesInstance = new InternalHubProperties();
JToken hubIdValue2 = propertiesValue["hubId"];
if (hubIdValue2 != null && hubIdValue2.Type != JTokenType.Null)
{
string hubIdInstance2 = ((string)hubIdValue2);
internalHubPropertiesInstance.HubId = hubIdInstance2;
}
JToken provisioningStateValue2 = propertiesValue["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
internalHubPropertiesInstance.ProvisioningState = provisioningStateInstance2;
}
hubInstance.Properties = internalHubPropertiesInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Result = com.google.zxing.Result;
namespace com.google.zxing.client.result
{
/// <summary> <p>Abstract class representing the result of decoding a barcode, as more than
/// a String -- as some type of structured data. This might be a subclass which represents
/// a URL, or an e-mail address. {@link #parseResult(com.google.zxing.Result)} will turn a raw
/// decoded string into the most appropriate type of structured representation.</p>
///
/// <p>Thanks to Jeff Griffin for proposing rewrite of these classes that relies less
/// on exception-based mechanisms during parsing.</p>
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source
/// </author>
public abstract class ResultParser
{
public static ParsedResult parseResult(Result theResult)
{
// Simplification of original if - if else logic using Null Coalescing operator ??
//
// ?? Simply checks from left to right for a non null object
// when an object evaluates to null the next object after the ?? is evaluated
// This continues until a non null value is found or the last object is evaluated
return
BookmarkDoCoMoResultParser.parse(theResult) as ParsedResult ??
AddressBookDoCoMoResultParser.parse(theResult) as ParsedResult ??
EmailDoCoMoResultParser.parse(theResult) as ParsedResult ??
AddressBookAUResultParser.parse(theResult) as ParsedResult ??
VCardResultParser.parse(theResult) as ParsedResult ??
BizcardResultParser.parse(theResult) as ParsedResult ??
VEventResultParser.parse(theResult) as ParsedResult ??
EmailAddressResultParser.parse(theResult) as ParsedResult ??
TelResultParser.parse(theResult) as ParsedResult ??
SMSMMSResultParser.parse(theResult) as ParsedResult ??
GeoResultParser.parse(theResult) as ParsedResult ??
URLTOResultParser.parse(theResult) as ParsedResult ??
URIResultParser.parse(theResult) as ParsedResult ??
ISBNResultParser.parse(theResult) as ParsedResult ??
ProductResultParser.parse(theResult) as ParsedResult ??
new TextParsedResult(theResult.Text, null) as ParsedResult;
}
protected internal static void maybeAppend(System.String value_Renamed, System.Text.StringBuilder result)
{
if (value_Renamed != null)
{
result.Append('\n');
result.Append(value_Renamed);
}
}
protected internal static void maybeAppend(System.String[] value_Renamed, System.Text.StringBuilder result)
{
if (value_Renamed != null)
{
for (int i = 0; i < value_Renamed.Length; i++)
{
result.Append('\n');
result.Append(value_Renamed[i]);
}
}
}
protected internal static System.String[] maybeWrap(System.String value_Renamed)
{
return value_Renamed == null?null:new System.String[]{value_Renamed};
}
protected internal static System.String unescapeBackslash(System.String escaped)
{
if (escaped != null)
{
int backslash = escaped.IndexOf('\\');
if (backslash >= 0)
{
int max = escaped.Length;
System.Text.StringBuilder unescaped = new System.Text.StringBuilder(max - 1);
unescaped.Append(escaped.ToCharArray(), 0, backslash);
bool nextIsEscaped = false;
for (int i = backslash; i < max; i++)
{
char c = escaped[i];
if (nextIsEscaped || c != '\\')
{
unescaped.Append(c);
nextIsEscaped = false;
}
else
{
nextIsEscaped = true;
}
}
return unescaped.ToString();
}
}
return escaped;
}
private static System.String urlDecode(System.String escaped)
{
// No we can't use java.net.URLDecoder here. JavaME doesn't have it.
if (escaped == null)
{
return null;
}
char[] escapedArray = escaped.ToCharArray();
int first = findFirstEscape(escapedArray);
if (first < 0)
{
return escaped;
}
int max = escapedArray.Length;
// final length is at most 2 less than original due to at least 1 unescaping
System.Text.StringBuilder unescaped = new System.Text.StringBuilder(max - 2);
// Can append everything up to first escape character
unescaped.Append(escapedArray, 0, first);
for (int i = first; i < max; i++)
{
char c = escapedArray[i];
if (c == '+')
{
// + is translated directly into a space
unescaped.Append(' ');
}
else if (c == '%')
{
// Are there even two more chars? if not we will just copy the escaped sequence and be done
if (i >= max - 2)
{
unescaped.Append('%'); // append that % and move on
}
else
{
int firstDigitValue = parseHexDigit(escapedArray[++i]);
int secondDigitValue = parseHexDigit(escapedArray[++i]);
if (firstDigitValue < 0 || secondDigitValue < 0)
{
// bad digit, just move on
unescaped.Append('%');
unescaped.Append(escapedArray[i - 1]);
unescaped.Append(escapedArray[i]);
}
unescaped.Append((char) ((firstDigitValue << 4) + secondDigitValue));
}
}
else
{
unescaped.Append(c);
}
}
return unescaped.ToString();
}
private static int findFirstEscape(char[] escapedArray)
{
int max = escapedArray.Length;
for (int i = 0; i < max; i++)
{
char c = escapedArray[i];
if (c == '+' || c == '%')
{
return i;
}
}
return - 1;
}
private static int parseHexDigit(char c)
{
if (c >= 'a')
{
if (c <= 'f')
{
return 10 + (c - 'a');
}
}
else if (c >= 'A')
{
if (c <= 'F')
{
return 10 + (c - 'A');
}
}
else if (c >= '0')
{
if (c <= '9')
{
return c - '0';
}
}
return - 1;
}
protected internal static bool isStringOfDigits(System.String value_Renamed, int length)
{
if (value_Renamed == null)
{
return false;
}
int stringLength = value_Renamed.Length;
if (length != stringLength)
{
return false;
}
for (int i = 0; i < length; i++)
{
char c = value_Renamed[i];
if (c < '0' || c > '9')
{
return false;
}
}
return true;
}
protected internal static bool isSubstringOfDigits(System.String value_Renamed, int offset, int length)
{
if (value_Renamed == null)
{
return false;
}
int stringLength = value_Renamed.Length;
int max = offset + length;
if (stringLength < max)
{
return false;
}
for (int i = offset; i < max; i++)
{
char c = value_Renamed[i];
if (c < '0' || c > '9')
{
return false;
}
}
return true;
}
internal static System.Collections.Hashtable parseNameValuePairs(System.String uri)
{
int paramStart = uri.IndexOf('?');
if (paramStart < 0)
{
return null;
}
System.Collections.Hashtable result = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable(3));
paramStart++;
int paramEnd;
//UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
while ((paramEnd = uri.IndexOf('&', paramStart)) >= 0)
{
appendKeyValue(uri, paramStart, paramEnd, result);
paramStart = paramEnd + 1;
}
appendKeyValue(uri, paramStart, uri.Length, result);
return result;
}
private static void appendKeyValue(System.String uri, int paramStart, int paramEnd, System.Collections.Hashtable result)
{
//UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
int separator = uri.IndexOf('=', paramStart);
if (separator >= 0)
{
// key = value
System.String key = uri.Substring(paramStart, (separator) - (paramStart));
System.String value_Renamed = uri.Substring(separator + 1, (paramEnd) - (separator + 1));
value_Renamed = urlDecode(value_Renamed);
result[key] = value_Renamed;
}
// Can't put key, null into a hashtable
}
internal static System.String[] matchPrefixedField(System.String prefix, System.String rawText, char endChar, bool trim)
{
System.Collections.ArrayList matches = null;
int i = 0;
int max = rawText.Length;
while (i < max)
{
//UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
i = rawText.IndexOf(prefix, i);
if (i < 0)
{
break;
}
i += prefix.Length; // Skip past this prefix we found to start
int start = i; // Found the start of a match here
bool done = false;
while (!done)
{
//UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
i = rawText.IndexOf((System.Char) endChar, i);
if (i < 0)
{
// No terminating end character? uh, done. Set i such that loop terminates and break
i = rawText.Length;
done = true;
}
else if (rawText[i - 1] == '\\')
{
// semicolon was escaped so continue
i++;
}
else
{
// found a match
if (matches == null)
{
matches = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(3)); // lazy init
}
System.String element = unescapeBackslash(rawText.Substring(start, (i) - (start)));
if (trim)
{
element = element.Trim();
}
matches.Add(element);
i++;
done = true;
}
}
}
if (matches == null || (matches.Count == 0))
{
return null;
}
return toStringArray(matches);
}
internal static System.String matchSinglePrefixedField(System.String prefix, System.String rawText, char endChar, bool trim)
{
System.String[] matches = matchPrefixedField(prefix, rawText, endChar, trim);
return matches == null?null:matches[0];
}
internal static System.String[] toStringArray(System.Collections.ArrayList strings)
{
int size = strings.Count;
System.String[] result = new System.String[size];
for (int j = 0; j < size; j++)
{
result[j] = ((System.String) strings[j]);
}
return result;
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Workflow.CallCustomServiceWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Security;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using TestLibrary;
namespace PInvokeTests
{
[StructLayout(LayoutKind.Sequential)]
public class SeqClass
{
public int a;
public bool b;
public string str;
public SeqClass(int _a, bool _b, string _str)
{
a = _a;
b = _b;
str = String.Concat(_str, "");
}
}
[StructLayout(LayoutKind.Explicit)]
public class ExpClass
{
[FieldOffset(0)]
public DialogResult type;
[FieldOffset(8)]
public int i;
[FieldOffset(8)]
public bool b;
[FieldOffset(8)]
public double c;
public ExpClass(DialogResult t, int num)
{
type = t;
b = false;
c = num;
i = num;
}
public ExpClass(DialogResult t, double dnum)
{
type = t;
b = false;
i = 0;
c = dnum;
}
public ExpClass(DialogResult t, bool bnum)
{
type = t;
i = 0;
c = 0;
b = bnum;
}
}
public enum DialogResult
{
None = 0,
OK = 1,
Cancel = 2
}
[StructLayout(LayoutKind.Sequential)]
public class Blittable
{
public int a;
public Blittable(int _a)
{
a = _a;
}
}
public struct NestedLayout
{
public SeqClass value;
}
[StructLayout(LayoutKind.Sequential)]
public class RecursiveTestClass
{
public RecursiveTestStruct s;
}
public struct RecursiveTestStruct
{
public RecursiveTestClass c;
}
class StructureTests
{
[DllImport("LayoutClassNative")]
private static extern bool SimpleSeqLayoutClassByRef(SeqClass p);
[DllImport("LayoutClassNative")]
private static extern bool SimpleExpLayoutClassByRef(ExpClass p);
[DllImport("LayoutClassNative")]
private static extern bool SimpleNestedLayoutClassByValue(NestedLayout p);
[DllImport("LayoutClassNative")]
private static extern bool SimpleBlittableSeqLayoutClassByRef(Blittable p);
[DllImport("LayoutClassNative", EntryPoint = "Invalid")]
private static extern void RecursiveNativeLayoutInvalid(RecursiveTestStruct str);
public static bool SequentialClass()
{
string s = "before";
bool retval = true;
SeqClass p = new SeqClass(0, false, s);
TestFramework.BeginScenario("Test #1 Pass a sequential layout class.");
try
{
retval = SimpleSeqLayoutClassByRef(p);
if (retval == false)
{
TestFramework.LogError("01", "PInvokeTests->SequentialClass : Unexpected error occured on unmanaged side");
return false;
}
}
catch (Exception e)
{
TestFramework.LogError("04", "Unexpected exception: " + e.ToString());
retval = false;
}
return retval;
}
public static bool ExplicitClass()
{
ExpClass p;
bool retval = false;
TestFramework.BeginScenario("Test #2 Pass an explicit layout class.");
try
{
p = new ExpClass(DialogResult.None, 10);
retval = SimpleExpLayoutClassByRef(p);
if (retval == false)
{
TestFramework.LogError("01", "PInvokeTests->ExplicitClass : Unexpected error occured on unmanaged side");
return false;
}
}
catch (Exception e)
{
TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
retval = false;
}
return retval;
}
public static bool BlittableClass()
{
bool retval = true;
Blittable p = new Blittable(10);
TestFramework.BeginScenario("Test #3 Pass a blittable sequential layout class.");
try
{
retval = SimpleBlittableSeqLayoutClassByRef(p);
if (retval == false)
{
TestFramework.LogError("01", "PInvokeTests->Blittable : Unexpected error occured on unmanaged side");
return false;
}
}
catch (Exception e)
{
TestFramework.LogError("04", "Unexpected exception: " + e.ToString());
retval = false;
}
return retval;
}
public static bool NestedLayoutClass()
{
string s = "before";
bool retval = true;
SeqClass p = new SeqClass(0, false, s);
NestedLayout target = new NestedLayout
{
value = p
};
TestFramework.BeginScenario("Test #4 Nested sequential layout class in a structure.");
try
{
retval = SimpleNestedLayoutClassByValue(target);
if (retval == false)
{
TestFramework.LogError("01", "PInvokeTests->NestedLayoutClass : Unexpected error occured on unmanaged side");
return false;
}
}
catch (Exception e)
{
TestFramework.LogError("04", "Unexpected exception: " + e.ToString());
retval = false;
}
return retval;
}
public static bool RecursiveNativeLayout()
{
TestFramework.BeginScenario("Test #5 Structure with field of nested layout class with field of containing structure.");
try
{
RecursiveNativeLayoutInvalid(new RecursiveTestStruct());
}
catch (TypeLoadException)
{
return true;
}
return false;
}
public static int Main(string[] argv)
{
bool retVal = true;
retVal = retVal && SequentialClass();
retVal = retVal && ExplicitClass();
retVal = retVal && BlittableClass();
retVal = retVal && NestedLayoutClass();
retVal = retVal && RecursiveNativeLayout();
return (retVal ? 100 : 101);
}
}
}
| |
//
// FileSystemQueueSource.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 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 System.IO;
using Mono.Unix;
using Gtk;
using Hyena;
using Banshee.Base;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Configuration;
using Banshee.Kernel;
using Banshee.Playlist;
using Banshee.Gui;
namespace Banshee.FileSystemQueue
{
public class FileSystemQueueSource : PrimarySource, IDisposable
{
private DatabaseImportManager importer;
private bool visible = false;
private bool actions_loaded = false;
private bool play_enqueued = false;
private string path_to_play;
public FileSystemQueueSource () : base (Catalog.GetString ("File System Queue"),
Catalog.GetString ("File System Queue"), "file-system-queue", 30)
{
TypeUniqueId = "file-system-queue";
Properties.SetStringList ("Icon.Name", "system-file-manager");
Properties.Set<bool> ("AutoAddSource", false);
IsLocal = true;
ServiceManager.Get<DBusCommandService> ().ArgumentPushed += OnCommandLineArgument;
AfterInitialized ();
InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
uia_service.GlobalActions.AddImportant (
new ActionEntry ("ClearFileSystemQueueAction", Stock.Clear,
Catalog.GetString ("Clear"), null,
Catalog.GetString ("Remove all tracks from the file system queue"),
OnClearFileSystemQueue)
);
uia_service.GlobalActions.Add (new ToggleActionEntry [] {
new ToggleActionEntry ("ClearFileSystemQueueOnQuitAction", null,
Catalog.GetString ("Clear on Quit"), null,
Catalog.GetString ("Clear the file system queue when quitting"),
OnClearFileSystemQueueOnQuit, ClearOnQuitSchema.Get ())
});
uia_service.UIManager.AddUiFromResource ("GlobalUI.xml");
Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml");
Properties.SetString ("GtkActionPath", "/FileSystemQueueContextMenu");
actions_loaded = true;
UpdateActions ();
ServiceManager.SourceManager.ActiveSourceChanged += delegate { Banshee.Base.ThreadAssist.ProxyToMain (UpdateActions); };
TrackModel.Reloaded += OnTrackModelReloaded;
Reload ();
play_enqueued = ApplicationContext.CommandLine.Contains ("play-enqueued");
foreach (string path in ApplicationContext.CommandLine.Files) {
// If it looks like a URI with a protocol, leave it as is
if (System.Text.RegularExpressions.Regex.IsMatch (path, "^\\w+\\:\\/")) {
Log.DebugFormat ("URI file : {0}", path);
Enqueue (path);
} else {
Log.DebugFormat ("Relative file : {0} -> {1}", path, Path.GetFullPath (path));
Enqueue (Path.GetFullPath (path));
}
}
}
public void Enqueue (string path)
{
try {
SafeUri uri = new SafeUri (path);
if (uri.IsLocalPath && !String.IsNullOrEmpty (uri.LocalPath)) {
path = uri.LocalPath;
}
} catch {
}
lock (this) {
if (importer == null) {
importer = new DatabaseImportManager (this);
importer.KeepUserJobHidden = true;
importer.ImportResult += delegate (object o, DatabaseImportResultArgs args) {
Banshee.ServiceStack.Application.Invoke (delegate {
if (args.Error != null || path_to_play != null) {
return;
}
path_to_play = args.Path;
if (args.Track == null) {
// Play immediately if the track is already in the source,
// otherwise the call will be deferred until the track has
// been imported and loaded into the cache
PlayEnqueued ();
}
});
};
importer.Finished += delegate {
if (visible) {
Banshee.Base.ThreadAssist.ProxyToMain (delegate {
TrackInfo current_track = ServiceManager.PlaybackController.CurrentTrack;
// Don't switch to FSQ if the current item is a video
if (current_track == null || !current_track.HasAttribute (TrackMediaAttributes.VideoStream)) {
ServiceManager.SourceManager.SetActiveSource (this);
}
});
}
};
}
if (PlaylistFileUtil.PathHasPlaylistExtension (path)) {
Banshee.Kernel.Scheduler.Schedule (new DelegateJob (delegate {
// If it's in /tmp it probably came from Firefox - just play it
if (path.StartsWith (Paths.SystemTempDir)) {
Banshee.Streaming.RadioTrackInfo.OpenPlay (path);
} else {
PlaylistFileUtil.ImportPlaylistToLibrary (path, this, importer);
}
}));
} else {
importer.Enqueue (path);
}
}
}
private void PlayEnqueued ()
{
if (!play_enqueued || path_to_play == null) {
return;
}
SafeUri uri = null;
ServiceManager.PlaybackController.NextSource = this;
try {
uri = new SafeUri (path_to_play);
} catch {
}
if (uri == null) {
return;
}
int id = DatabaseTrackInfo.GetTrackIdForUri (uri, new int [] { DbId });
if (id >= 0) {
int index = (int)TrackCache.IndexOf ((long)id);
if (index >= 0) {
TrackInfo track = TrackModel[index];
if (track != null) {
ServiceManager.PlayerEngine.OpenPlay (track);
play_enqueued = false;
}
}
}
}
// until we implement DeleteTrack, at least
public override bool CanDeleteTracks {
get { return false; }
}
public override void Dispose ()
{
ServiceManager.Get<DBusCommandService> ().ArgumentPushed -= OnCommandLineArgument;
if (ClearOnQuitSchema.Get ()) {
OnClearFileSystemQueue (this, EventArgs.Empty);
}
base.Dispose ();
}
private void OnCommandLineArgument (string argument, object value, bool isFile)
{
if (!isFile) {
if (argument == "play-enqueued") {
play_enqueued = true;
path_to_play = null;
}
return;
}
Log.DebugFormat ("FSQ Enqueue: {0}", argument);
try {
if (Banshee.IO.Directory.Exists (argument) || Banshee.IO.File.Exists (new SafeUri (argument))) {
Enqueue (argument);
}
} catch {
}
}
protected override void OnUpdated ()
{
base.OnUpdated ();
if (actions_loaded) {
UpdateActions ();
}
}
private void OnTrackModelReloaded (object sender, EventArgs args)
{
if (Count > 0 && !visible) {
ServiceManager.SourceManager.AddSource (this);
visible = true;
} else if (Count <= 0 && visible) {
ServiceManager.SourceManager.RemoveSource (this);
visible = false;
}
if (Count > 0) {
PlayEnqueued ();
}
}
private void OnClearFileSystemQueue (object o, EventArgs args)
{
// Delete any child playlists
ClearChildSources ();
ServiceManager.DbConnection.Execute (@"
DELETE FROM CorePlaylistEntries WHERE PlaylistID IN
(SELECT PlaylistID FROM CorePlaylists WHERE PrimarySourceID = ?);
DELETE FROM CorePlaylists WHERE PrimarySourceID = ?;",
this.DbId, this.DbId
);
RemoveTrackRange ((DatabaseTrackListModel)TrackModel, new Hyena.Collections.RangeCollection.Range (0, Count));
Reload ();
}
private void OnClearFileSystemQueueOnQuit (object o, EventArgs args)
{
InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
if (uia_service == null) {
return;
}
ToggleAction action = (ToggleAction)uia_service.GlobalActions["ClearFileSystemQueueOnQuitAction"];
ClearOnQuitSchema.Set (action.Active);
}
private void UpdateActions ()
{
InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
if (uia_service == null) {
return;
}
uia_service.GlobalActions.UpdateAction ("ClearFileSystemQueueAction", true, Count > 0);
}
public static readonly SchemaEntry<bool> ClearOnQuitSchema = new SchemaEntry<bool> (
"plugins.file_system_queue", "clear_on_quit",
false,
"Clear on Quit",
"Clear the file system queue when quitting"
);
}
}
| |
namespace java.net
{
[global::MonoJavaBridge.JavaClass()]
public partial class ServerSocket : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ServerSocket()
{
InitJNI();
}
protected ServerSocket(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _toString13734;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.net.ServerSocket._toString13734)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._toString13734)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _close13735;
public virtual void close()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.ServerSocket._close13735);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._close13735);
}
internal static global::MonoJavaBridge.MethodId _accept13736;
public virtual global::java.net.Socket accept()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.net.ServerSocket._accept13736)) as java.net.Socket;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._accept13736)) as java.net.Socket;
}
internal static global::MonoJavaBridge.MethodId _getChannel13737;
public virtual global::java.nio.channels.ServerSocketChannel getChannel()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.net.ServerSocket._getChannel13737)) as java.nio.channels.ServerSocketChannel;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._getChannel13737)) as java.nio.channels.ServerSocketChannel;
}
internal static global::MonoJavaBridge.MethodId _isClosed13738;
public virtual bool isClosed()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.net.ServerSocket._isClosed13738);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._isClosed13738);
}
internal static global::MonoJavaBridge.MethodId _bind13739;
public virtual void bind(java.net.SocketAddress arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.ServerSocket._bind13739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._bind13739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _bind13740;
public virtual void bind(java.net.SocketAddress arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.ServerSocket._bind13740, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._bind13740, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getLocalSocketAddress13741;
public virtual global::java.net.SocketAddress getLocalSocketAddress()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.net.ServerSocket._getLocalSocketAddress13741)) as java.net.SocketAddress;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._getLocalSocketAddress13741)) as java.net.SocketAddress;
}
internal static global::MonoJavaBridge.MethodId _setReceiveBufferSize13742;
public virtual void setReceiveBufferSize(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.ServerSocket._setReceiveBufferSize13742, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._setReceiveBufferSize13742, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getReceiveBufferSize13743;
public virtual int getReceiveBufferSize()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.net.ServerSocket._getReceiveBufferSize13743);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._getReceiveBufferSize13743);
}
internal static global::MonoJavaBridge.MethodId _setSoTimeout13744;
public virtual void setSoTimeout(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.ServerSocket._setSoTimeout13744, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._setSoTimeout13744, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSoTimeout13745;
public virtual int getSoTimeout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.net.ServerSocket._getSoTimeout13745);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._getSoTimeout13745);
}
internal static global::MonoJavaBridge.MethodId _isBound13746;
public virtual bool isBound()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.net.ServerSocket._isBound13746);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._isBound13746);
}
internal static global::MonoJavaBridge.MethodId _getInetAddress13747;
public virtual global::java.net.InetAddress getInetAddress()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.net.ServerSocket._getInetAddress13747)) as java.net.InetAddress;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._getInetAddress13747)) as java.net.InetAddress;
}
internal static global::MonoJavaBridge.MethodId _getLocalPort13748;
public virtual int getLocalPort()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.net.ServerSocket._getLocalPort13748);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._getLocalPort13748);
}
internal static global::MonoJavaBridge.MethodId _setReuseAddress13749;
public virtual void setReuseAddress(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.ServerSocket._setReuseAddress13749, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._setReuseAddress13749, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getReuseAddress13750;
public virtual bool getReuseAddress()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.net.ServerSocket._getReuseAddress13750);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._getReuseAddress13750);
}
internal static global::MonoJavaBridge.MethodId _setPerformancePreferences13751;
public virtual void setPerformancePreferences(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.ServerSocket._setPerformancePreferences13751, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._setPerformancePreferences13751, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _implAccept13752;
protected virtual void implAccept(java.net.Socket arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.ServerSocket._implAccept13752, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.ServerSocket.staticClass, global::java.net.ServerSocket._implAccept13752, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setSocketFactory13753;
public static void setSocketFactory(java.net.SocketImplFactory arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(java.net.ServerSocket.staticClass, global::java.net.ServerSocket._setSocketFactory13753, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _ServerSocket13754;
public ServerSocket() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.ServerSocket.staticClass, global::java.net.ServerSocket._ServerSocket13754);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _ServerSocket13755;
public ServerSocket(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.ServerSocket.staticClass, global::java.net.ServerSocket._ServerSocket13755, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _ServerSocket13756;
public ServerSocket(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.ServerSocket.staticClass, global::java.net.ServerSocket._ServerSocket13756, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _ServerSocket13757;
public ServerSocket(int arg0, int arg1, java.net.InetAddress arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.ServerSocket.staticClass, global::java.net.ServerSocket._ServerSocket13757, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.net.ServerSocket.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/net/ServerSocket"));
global::java.net.ServerSocket._toString13734 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "toString", "()Ljava/lang/String;");
global::java.net.ServerSocket._close13735 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "close", "()V");
global::java.net.ServerSocket._accept13736 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "accept", "()Ljava/net/Socket;");
global::java.net.ServerSocket._getChannel13737 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "getChannel", "()Ljava/nio/channels/ServerSocketChannel;");
global::java.net.ServerSocket._isClosed13738 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "isClosed", "()Z");
global::java.net.ServerSocket._bind13739 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "bind", "(Ljava/net/SocketAddress;)V");
global::java.net.ServerSocket._bind13740 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "bind", "(Ljava/net/SocketAddress;I)V");
global::java.net.ServerSocket._getLocalSocketAddress13741 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "getLocalSocketAddress", "()Ljava/net/SocketAddress;");
global::java.net.ServerSocket._setReceiveBufferSize13742 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "setReceiveBufferSize", "(I)V");
global::java.net.ServerSocket._getReceiveBufferSize13743 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "getReceiveBufferSize", "()I");
global::java.net.ServerSocket._setSoTimeout13744 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "setSoTimeout", "(I)V");
global::java.net.ServerSocket._getSoTimeout13745 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "getSoTimeout", "()I");
global::java.net.ServerSocket._isBound13746 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "isBound", "()Z");
global::java.net.ServerSocket._getInetAddress13747 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "getInetAddress", "()Ljava/net/InetAddress;");
global::java.net.ServerSocket._getLocalPort13748 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "getLocalPort", "()I");
global::java.net.ServerSocket._setReuseAddress13749 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "setReuseAddress", "(Z)V");
global::java.net.ServerSocket._getReuseAddress13750 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "getReuseAddress", "()Z");
global::java.net.ServerSocket._setPerformancePreferences13751 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "setPerformancePreferences", "(III)V");
global::java.net.ServerSocket._implAccept13752 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "implAccept", "(Ljava/net/Socket;)V");
global::java.net.ServerSocket._setSocketFactory13753 = @__env.GetStaticMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "setSocketFactory", "(Ljava/net/SocketImplFactory;)V");
global::java.net.ServerSocket._ServerSocket13754 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "<init>", "()V");
global::java.net.ServerSocket._ServerSocket13755 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "<init>", "(I)V");
global::java.net.ServerSocket._ServerSocket13756 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "<init>", "(II)V");
global::java.net.ServerSocket._ServerSocket13757 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "<init>", "(IILjava/net/InetAddress;)V");
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
//#define OVR_USE_PROJ_MATRIX
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// A head-tracked stereoscopic virtual reality camera rig.
/// </summary>
[ExecuteInEditMode]
public class OVRCameraRig : MonoBehaviour
{
/// <summary>
/// The left eye camera.
/// </summary>
private Camera leftEyeCamera;
/// <summary>
/// The right eye camera.
/// </summary>
private Camera rightEyeCamera;
/// <summary>
/// Always coincides with the pose of the left eye.
/// </summary>
public Transform leftEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with average of the left and right eye poses.
/// </summary>
public Transform centerEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the right eye.
/// </summary>
public Transform rightEyeAnchor { get; private set; }
public bool disableTracking = false;
private bool needsCameraConfigure;
#region Unity Messages
private void Awake()
{
EnsureGameObjectIntegrity();
if (!Application.isPlaying)
return;
needsCameraConfigure = true;
}
private void Start()
{
EnsureGameObjectIntegrity();
if (!Application.isPlaying)
return;
UpdateCameras();
UpdateAnchors();
}
#if !UNITY_ANDROID || UNITY_EDITOR
private void LateUpdate()
#else
private void Update()
#endif
{
EnsureGameObjectIntegrity();
if (!Application.isPlaying)
return;
UpdateCameras();
UpdateAnchors();
}
#endregion
private void UpdateAnchors()
{
if (disableTracking)
return;
OVRPose leftEye = OVRManager.display.GetEyePose(OVREye.Left);
OVRPose rightEye = OVRManager.display.GetEyePose(OVREye.Right);
leftEyeAnchor.localRotation = leftEye.orientation;
centerEyeAnchor.localRotation = leftEye.orientation; // using left eye for now
rightEyeAnchor.localRotation = rightEye.orientation;
leftEyeAnchor.localPosition = leftEye.position;
centerEyeAnchor.localPosition = 0.5f * (leftEye.position + rightEye.position);
rightEyeAnchor.localPosition = rightEye.position;
}
private void UpdateCameras()
{
if (needsCameraConfigure)
{
leftEyeCamera = ConfigureCamera(OVREye.Left);
rightEyeCamera = ConfigureCamera(OVREye.Right);
#if !UNITY_ANDROID || UNITY_EDITOR
#if OVR_USE_PROJ_MATRIX
OVRManager.display.ForceSymmetricProj(false);
#else
OVRManager.display.ForceSymmetricProj(true);
#endif
needsCameraConfigure = false;
#endif
}
}
private void EnsureGameObjectIntegrity()
{
if (leftEyeAnchor == null)
leftEyeAnchor = ConfigureEyeAnchor(OVREye.Left);
if (centerEyeAnchor == null)
centerEyeAnchor = ConfigureEyeAnchor(OVREye.Center);
if (rightEyeAnchor == null)
rightEyeAnchor = ConfigureEyeAnchor(OVREye.Right);
if (leftEyeCamera == null)
{
leftEyeCamera = leftEyeAnchor.GetComponent<Camera>();
if (leftEyeCamera == null)
{
leftEyeCamera = leftEyeAnchor.gameObject.AddComponent<Camera>();
}
}
if (rightEyeCamera == null)
{
rightEyeCamera = rightEyeAnchor.GetComponent<Camera>();
if (rightEyeCamera == null)
{
rightEyeCamera = rightEyeAnchor.gameObject.AddComponent<Camera>();
}
}
}
private Transform ConfigureEyeAnchor(OVREye eye)
{
string name = eye.ToString() + "EyeAnchor";
Transform anchor = transform.Find(name);
if (anchor == null)
{
string oldName = "Camera" + eye.ToString();
anchor = transform.Find(oldName);
}
if (anchor == null)
anchor = new GameObject(name).transform;
anchor.parent = transform;
anchor.localScale = Vector3.one;
anchor.localPosition = Vector3.zero;
anchor.localRotation = Quaternion.identity;
return anchor;
}
private Camera ConfigureCamera(OVREye eye)
{
Transform anchor = (eye == OVREye.Left) ? leftEyeAnchor : rightEyeAnchor;
Camera cam = anchor.GetComponent<Camera>();
OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(eye);
cam.fieldOfView = eyeDesc.fov.y;
cam.aspect = eyeDesc.resolution.x / eyeDesc.resolution.y;
cam.rect = new Rect(0f, 0f, OVRManager.instance.virtualTextureScale, OVRManager.instance.virtualTextureScale);
cam.targetTexture = OVRManager.display.GetEyeTexture(eye);
// AA is documented to have no effect in deferred, but it causes black screens.
if (cam.actualRenderingPath == RenderingPath.DeferredLighting)
QualitySettings.antiAliasing = 0;
#if !UNITY_ANDROID || UNITY_EDITOR
#if OVR_USE_PROJ_MATRIX
cam.projectionMatrix = OVRManager.display.GetProjection((int)eye, cam.nearClipPlane, cam.farClipPlane);
#endif
#endif
return cam;
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
function EditorGui::buildMenus(%this)
{
if(isObject(%this.menuBar))
return;
//set up %cmdctrl variable so that it matches OS standards
if( $platform $= "macos" )
{
%cmdCtrl = "Cmd";
%menuCmdCtrl = "Cmd";
%quitShortcut = "Cmd Q";
%redoShortcut = "Cmd-Shift Z";
}
else
{
%cmdCtrl = "Ctrl";
%menuCmdCtrl = "Alt";
%quitShortcut = "Alt F4";
%redoShortcut = "Ctrl Y";
}
// Sub menus (temporary, until MenuBuilder gets updated)
// The speed increments located here are overwritten in EditorCameraSpeedMenu::setupDefaultState.
// The new min/max for the editor camera speed range can be set in each level's levelInfo object.
if(!isObject(EditorCameraSpeedOptions))
{
%this.cameraSpeedMenu = new PopupMenu(EditorCameraSpeedOptions)
{
superClass = "MenuBuilder";
class = "EditorCameraSpeedMenu";
item[0] = "Slowest" TAB %cmdCtrl @ "-Shift 1" TAB "5";
item[1] = "Slow" TAB %cmdCtrl @ "-Shift 2" TAB "35";
item[2] = "Slower" TAB %cmdCtrl @ "-Shift 3" TAB "70";
item[3] = "Normal" TAB %cmdCtrl @ "-Shift 4" TAB "100";
item[4] = "Faster" TAB %cmdCtrl @ "-Shift 5" TAB "130";
item[5] = "Fast" TAB %cmdCtrl @ "-Shift 6" TAB "165";
item[6] = "Fastest" TAB %cmdCtrl @ "-Shift 7" TAB "200";
};
}
if(!isObject(EditorFreeCameraTypeOptions))
{
%this.freeCameraTypeMenu = new PopupMenu(EditorFreeCameraTypeOptions)
{
superClass = "MenuBuilder";
class = "EditorFreeCameraTypeMenu";
item[0] = "Standard" TAB "Ctrl 1" TAB "EditorGuiStatusBar.setCamera(\"Standard Camera\");";
item[1] = "Orbit Camera" TAB "Ctrl 2" TAB "EditorGuiStatusBar.setCamera(\"Orbit Camera\");";
Item[2] = "-";
item[3] = "Smoothed" TAB "" TAB "EditorGuiStatusBar.setCamera(\"Smooth Camera\");";
item[4] = "Smoothed Rotate" TAB "" TAB "EditorGuiStatusBar.setCamera(\"Smooth Rot Camera\");";
};
}
if(!isObject(EditorPlayerCameraTypeOptions))
{
%this.playerCameraTypeMenu = new PopupMenu(EditorPlayerCameraTypeOptions)
{
superClass = "MenuBuilder";
class = "EditorPlayerCameraTypeMenu";
Item[0] = "First Person" TAB "" TAB "EditorGuiStatusBar.setCamera(\"1st Person Camera\");";
Item[1] = "Third Person" TAB "" TAB "EditorGuiStatusBar.setCamera(\"3rd Person Camera\");";
};
}
if(!isObject(EditorCameraBookmarks))
{
%this.cameraBookmarksMenu = new PopupMenu(EditorCameraBookmarks)
{
superClass = "MenuBuilder";
class = "EditorCameraBookmarksMenu";
//item[0] = "None";
};
}
%this.viewTypeMenu = new PopupMenu()
{
superClass = "MenuBuilder";
item[ 0 ] = "Top" TAB "Alt 2" TAB "EditorGuiStatusBar.setCamera(\"Top View\");";
item[ 1 ] = "Bottom" TAB "Alt 5" TAB "EditorGuiStatusBar.setCamera(\"Bottom View\");";
item[ 2 ] = "Front" TAB "Alt 3" TAB "EditorGuiStatusBar.setCamera(\"Front View\");";
item[ 3 ] = "Back" TAB "Alt 6" TAB "EditorGuiStatusBar.setCamera(\"Back View\");";
item[ 4 ] = "Left" TAB "Alt 4" TAB "EditorGuiStatusBar.setCamera(\"Left View\");";
item[ 5 ] = "Right" TAB "Alt 7" TAB "EditorGuiStatusBar.setCamera(\"Right View\");";
item[ 6 ] = "Perspective" TAB "Alt 1" TAB "EditorGuiStatusBar.setCamera(\"Standard Camera\");";
item[ 7 ] = "Isometric" TAB "Alt 8" TAB "EditorGuiStatusBar.setCamera(\"Isometric View\");";
};
// Menu bar
%this.menuBar = new MenuBar(WorldEditorMenubar)
{
dynamicItemInsertPos = 3;
};
// File Menu
%fileMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorFileMenu";
barTitle = "File";
};
%fileMenu.appendItem("New Level" TAB "" TAB "schedule( 1, 0, \"EditorNewLevel\" );");
%fileMenu.appendItem("Open Level..." TAB %cmdCtrl SPC "O" TAB "schedule( 1, 0, \"EditorOpenMission\" );");
%fileMenu.appendItem("Save Level" TAB %cmdCtrl SPC "S" TAB "EditorSaveMissionMenu();");
%fileMenu.appendItem("Save Level As..." TAB "" TAB "EditorSaveMissionAs();");
%fileMenu.appendItem("-");
if( $platform $= "windows" )
{
%fileMenu.appendItem( "Open Project in Torsion" TAB "" TAB "EditorOpenTorsionProject();" );
%fileMenu.appendItem( "Open Level File in Torsion" TAB "" TAB "EditorOpenFileInTorsion();" );
%fileMenu.appendItem( "-" );
}
%fileMenu.appendItem("Create Blank Terrain" TAB "" TAB "Canvas.pushDialog( CreateNewTerrainGui );");
%fileMenu.appendItem("Import Terrain Heightmap" TAB "" TAB "Canvas.pushDialog( TerrainImportGui );");
%fileMenu.appendItem("Export Terrain Heightmap" TAB "" TAB "Canvas.pushDialog( TerrainExportGui );");
%fileMenu.appendItem("-");
%fileMenu.appendItem("Export To COLLADA..." TAB "" TAB "EditorExportToCollada();");
//item[5] = "Import Terraform Data..." TAB "" TAB "Heightfield::import();";
//item[6] = "Import Texture Data..." TAB "" TAB "Texture::import();";
//item[7] = "-";
//item[8] = "Export Terraform Data..." TAB "" TAB "Heightfield::saveBitmap(\"\");";
%fileMenu.appendItem( "-" );
%fileMenu.appendItem( "Add FMOD Designer Audio..." TAB "" TAB "AddFMODProjectDlg.show();" );
%fileMenu.appendItem("-");
%fileMenu.appendItem("Play Level" TAB "F11" TAB "Editor.close(\"PlayGui\");");
%fileMenu.appendItem("Exit Level" TAB "" TAB "EditorExitMission();");
%fileMenu.appendItem("Quit" TAB %quitShortcut TAB "EditorQuitGame();");
%this.menuBar.insert(%fileMenu, %this.menuBar.getCount());
// Edit Menu
%editMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorEditMenu";
internalName = "EditMenu";
barTitle = "Edit";
item[0] = "Undo" TAB %cmdCtrl SPC "Z" TAB "Editor.getUndoManager().undo();";
item[1] = "Redo" TAB %redoShortcut TAB "Editor.getUndoManager().redo();";
item[2] = "-";
item[3] = "Cut" TAB %cmdCtrl SPC "X" TAB "EditorMenuEditCut();";
item[4] = "Copy" TAB %cmdCtrl SPC "C" TAB "EditorMenuEditCopy();";
item[5] = "Paste" TAB %cmdCtrl SPC "V" TAB "EditorMenuEditPaste();";
item[6] = "Delete" TAB "Delete" TAB "EditorMenuEditDelete();";
item[7] = "-";
item[8] = "Deselect" TAB "X" TAB "EditorMenuEditDeselect();";
Item[9] = "Select..." TAB "" TAB "EditorGui.toggleObjectSelectionsWindow();";
item[10] = "-";
item[11] = "Audio Parameters..." TAB "" TAB "EditorGui.toggleSFXParametersWindow();";
item[12] = "Editor Settings..." TAB "" TAB "ESettingsWindow.ToggleVisibility();";
item[13] = "Snap Options..." TAB "" TAB "ESnapOptions.ToggleVisibility();";
item[14] = "-";
item[15] = "Game Options..." TAB "" TAB "Canvas.pushDialog(optionsDlg);";
item[16] = "PostEffect Manager" TAB "" TAB "Canvas.pushDialog(PostFXManager);";
};
%this.menuBar.insert(%editMenu, %this.menuBar.getCount());
// View Menu
%viewMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorViewMenu";
internalName = "viewMenu";
barTitle = "View";
item[ 0 ] = "Visibility Layers" TAB "Alt V" TAB "VisibilityDropdownToggle();";
item[ 1 ] = "Show Grid in Ortho Views" TAB %cmdCtrl @ "-Shift-Alt G" TAB "EditorGui.toggleOrthoGrid();";
};
%this.menuBar.insert(%viewMenu, %this.menuBar.getCount());
// Camera Menu
%cameraMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorCameraMenu";
barTitle = "Camera";
item[0] = "World Camera" TAB %this.freeCameraTypeMenu;
item[1] = "Player Camera" TAB %this.playerCameraTypeMenu;
item[2] = "-";
Item[3] = "Toggle Camera" TAB %menuCmdCtrl SPC "C" TAB "commandToServer('ToggleCamera');";
item[4] = "Place Camera at Selection" TAB "Ctrl Q" TAB "EWorldEditor.dropCameraToSelection();";
item[5] = "Place Camera at Player" TAB "Alt Q" TAB "commandToServer('dropCameraAtPlayer');";
item[6] = "Place Player at Camera" TAB "Alt W" TAB "commandToServer('DropPlayerAtCamera');";
item[7] = "-";
item[8] = "Fit View to Selection" TAB "F" TAB "commandToServer('EditorCameraAutoFit', EWorldEditor.getSelectionRadius()+1);";
item[9] = "Fit View To Selection and Orbit" TAB "Alt F" TAB "EditorGuiStatusBar.setCamera(\"Orbit Camera\"); commandToServer('EditorCameraAutoFit', EWorldEditor.getSelectionRadius()+1);";
item[10] = "-";
item[11] = "Speed" TAB %this.cameraSpeedMenu;
item[12] = "View" TAB %this.viewTypeMenu;
item[13] = "-";
Item[14] = "Add Bookmark..." TAB "Ctrl B" TAB "EditorGui.addCameraBookmarkByGui();";
Item[15] = "Manage Bookmarks..." TAB "Ctrl-Shift B" TAB "EditorGui.toggleCameraBookmarkWindow();";
item[16] = "Jump to Bookmark" TAB %this.cameraBookmarksMenu;
};
%this.menuBar.insert(%cameraMenu, %this.menuBar.getCount());
// Editors Menu
%editorsMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorToolsMenu";
barTitle = "Editors";
//item[0] = "Object Editor" TAB "F1" TAB WorldEditorInspectorPlugin;
//item[1] = "Material Editor" TAB "F2" TAB MaterialEditorPlugin;
//item[2] = "-";
//item[3] = "Terrain Editor" TAB "F3" TAB TerrainEditorPlugin;
//item[4] = "Terrain Painter" TAB "F4" TAB TerrainPainterPlugin;
//item[5] = "-";
};
%this.menuBar.insert(%editorsMenu, %this.menuBar.getCount());
// Lighting Menu
%lightingMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorLightingMenu";
barTitle = "Lighting";
item[0] = "Full Relight" TAB "Alt L" TAB "Editor.lightScene(\"\", forceAlways);";
item[1] = "Toggle ShadowViz" TAB "" TAB "toggleShadowViz();";
item[2] = "-";
// NOTE: The light managers will be inserted as the
// last menu items in EditorLightingMenu::onAdd().
};
%this.menuBar.insert(%lightingMenu, %this.menuBar.getCount());
// Tools Menu
%toolsMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorUtilitiesMenu";
barTitle = "Tools";
item[0] = "Network Graph" TAB "n" TAB "toggleNetGraph();";
item[1] = "Profiler" TAB "ctrl F2" TAB "showMetrics(true);";
item[2] = "Torque SimView" TAB "" TAB "tree();";
item[3] = "Make Selected a Mesh" TAB "" TAB "makeSelectedAMesh();";
};
%this.menuBar.insert(%toolsMenu, %this.menuBar.getCount());
// Help Menu
%helpMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorHelpMenu";
barTitle = "Help";
item[0] = "Online Documentation..." TAB "Alt F1" TAB "gotoWebPage(EWorldEditor.documentationURL);";
item[1] = "Offline User Guide..." TAB "" TAB "gotoWebPage(EWorldEditor.documentationLocal);";
item[2] = "Offline Reference Guide..." TAB "" TAB "shellexecute(EWorldEditor.documentationReference);";
item[3] = "Torque 3D Forums..." TAB "" TAB "gotoWebPage(EWorldEditor.forumURL);";
};
%this.menuBar.insert(%helpMenu, %this.menuBar.getCount());
// Menus that are added/removed dynamically (temporary)
// World Menu
if(! isObject(%this.worldMenu))
{
%this.dropTypeMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorDropTypeMenu";
// The onSelectItem() callback for this menu re-purposes the command field
// as the MenuBuilder version is not used.
item[0] = "at Origin" TAB "" TAB "atOrigin";
item[1] = "at Camera" TAB "" TAB "atCamera";
item[2] = "at Camera w/Rotation" TAB "" TAB "atCameraRot";
item[3] = "Below Camera" TAB "" TAB "belowCamera";
item[4] = "Screen Center" TAB "" TAB "screenCenter";
item[5] = "at Centroid" TAB "" TAB "atCentroid";
item[6] = "to Terrain" TAB "" TAB "toTerrain";
item[7] = "Below Selection" TAB "" TAB "belowSelection";
};
%this.alignBoundsMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorAlignBoundsMenu";
// The onSelectItem() callback for this menu re-purposes the command field
// as the MenuBuilder version is not used.
item[0] = "+X Axis" TAB "" TAB "0";
item[1] = "+Y Axis" TAB "" TAB "1";
item[2] = "+Z Axis" TAB "" TAB "2";
item[3] = "-X Axis" TAB "" TAB "3";
item[4] = "-Y Axis" TAB "" TAB "4";
item[5] = "-Z Axis" TAB "" TAB "5";
};
%this.alignCenterMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorAlignCenterMenu";
// The onSelectItem() callback for this menu re-purposes the command field
// as the MenuBuilder version is not used.
item[0] = "X Axis" TAB "" TAB "0";
item[1] = "Y Axis" TAB "" TAB "1";
item[2] = "Z Axis" TAB "" TAB "2";
};
%this.worldMenu = new PopupMenu()
{
superClass = "MenuBuilder";
class = "EditorWorldMenu";
barTitle = "Object";
item[0] = "Lock Selection" TAB %cmdCtrl @ " L" TAB "EWorldEditor.lockSelection(true); EWorldEditor.syncGui();";
item[1] = "Unlock Selection" TAB %cmdCtrl @ "-Shift L" TAB "EWorldEditor.lockSelection(false); EWorldEditor.syncGui();";
item[2] = "-";
item[3] = "Hide Selection" TAB %cmdCtrl @ " H" TAB "EWorldEditor.hideSelection(true); EWorldEditor.syncGui();";
item[4] = "Show Selection" TAB %cmdCtrl @ "-Shift H" TAB "EWorldEditor.hideSelection(false); EWorldEditor.syncGui();";
item[5] = "-";
item[6] = "Align Bounds" TAB %this.alignBoundsMenu;
item[7] = "Align Center" TAB %this.alignCenterMenu;
item[8] = "-";
item[9] = "Reset Transforms" TAB "Ctrl R" TAB "EWorldEditor.resetTransforms();";
item[10] = "Reset Selected Rotation" TAB "" TAB "EWorldEditor.resetSelectedRotation();";
item[11] = "Reset Selected Scale" TAB "" TAB "EWorldEditor.resetSelectedScale();";
item[12] = "Transform Selection..." TAB "Ctrl T" TAB "ETransformSelection.ToggleVisibility();";
item[13] = "-";
//item[13] = "Drop Camera to Selection" TAB "Ctrl Q" TAB "EWorldEditor.dropCameraToSelection();";
//item[14] = "Add Selection to Instant Group" TAB "" TAB "EWorldEditor.addSelectionToAddGroup();";
item[14] = "Drop Selection" TAB "Ctrl D" TAB "EWorldEditor.dropSelection();";
//item[15] = "-";
item[15] = "Drop Location" TAB %this.dropTypeMenu;
Item[16] = "-";
Item[17] = "Make Selection Prefab" TAB "" TAB "EditorMakePrefab();";
Item[18] = "Explode Selected Prefab" TAB "" TAB "EditorExplodePrefab();";
Item[19] = "-";
Item[20] = "Mount Selection A to B" TAB "" TAB "EditorMount();";
Item[21] = "Unmount Selected Object" TAB "" TAB "EditorUnmount();";
};
}
}
//////////////////////////////////////////////////////////////////////////
function EditorGui::attachMenus(%this)
{
%this.menuBar.attachToCanvas(Canvas, 0);
}
function EditorGui::detachMenus(%this)
{
%this.menuBar.removeFromCanvas();
}
function EditorGui::setMenuDefaultState(%this)
{
if(! isObject(%this.menuBar))
return 0;
for(%i = 0;%i < %this.menuBar.getCount();%i++)
{
%menu = %this.menuBar.getObject(%i);
%menu.setupDefaultState();
}
%this.worldMenu.setupDefaultState();
}
//////////////////////////////////////////////////////////////////////////
function EditorGui::findMenu(%this, %name)
{
if(! isObject(%this.menuBar))
return 0;
for(%i = 0;%i < %this.menuBar.getCount();%i++)
{
%menu = %this.menuBar.getObject(%i);
if(%name $= %menu.barTitle)
return %menu;
}
return 0;
}
| |
//
// LogicalOperator.cs.cs
//
// This file was generated by XMLSPY 2004 Enterprise Edition.
//
// YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE
// OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION.
//
// Refer to the XMLSPY Documentation for further details.
// http://www.altova.com/xmlspy
//
using System;
using System.Collections;
using System.Xml;
using Altova.Types;
namespace XMLRules
{
public class LogicalOperator : Altova.Node
{
#region Forward constructors
public LogicalOperator() : base() { SetCollectionParents(); }
public LogicalOperator(XmlDocument doc) : base(doc) { SetCollectionParents(); }
public LogicalOperator(XmlNode node) : base(node) { SetCollectionParents(); }
public LogicalOperator(Altova.Node node) : base(node) { SetCollectionParents(); }
#endregion // Forward constructors
public override void AdjustPrefix()
{
int nCount;
nCount = DomChildCount(NodeType.Element, "", "And");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "And", i);
InternalAdjustPrefix(DOMNode, true);
}
nCount = DomChildCount(NodeType.Element, "", "Or");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "Or", i);
InternalAdjustPrefix(DOMNode, true);
}
}
#region And accessor methods
public int GetAndMinCount()
{
return 1;
}
public int AndMinCount
{
get
{
return 1;
}
}
public int GetAndMaxCount()
{
return 1;
}
public int AndMaxCount
{
get
{
return 1;
}
}
public int GetAndCount()
{
return DomChildCount(NodeType.Element, "", "And");
}
public int AndCount
{
get
{
return DomChildCount(NodeType.Element, "", "And");
}
}
public bool HasAnd()
{
return HasDomChild(NodeType.Element, "", "And");
}
public SchemaString GetAndAt(int index)
{
return new SchemaString(GetDomNodeValue(GetDomChildAt(NodeType.Element, "", "And", index)));
}
public SchemaString GetAnd()
{
return GetAndAt(0);
}
public SchemaString And
{
get
{
return GetAndAt(0);
}
}
public void RemoveAndAt(int index)
{
RemoveDomChildAt(NodeType.Element, "", "And", index);
}
public void RemoveAnd()
{
while (HasAnd())
RemoveAndAt(0);
}
public void AddAnd(SchemaString newValue)
{
AppendDomChild(NodeType.Element, "", "And", newValue.ToString());
}
public void InsertAndAt(SchemaString newValue, int index)
{
InsertDomChildAt(NodeType.Element, "", "And", index, newValue.ToString());
}
public void ReplaceAndAt(SchemaString newValue, int index)
{
ReplaceDomChildAt(NodeType.Element, "", "And", index, newValue.ToString());
}
#endregion // And accessor methods
#region And collection
public AndCollection MyAnds = new AndCollection( );
public class AndCollection: IEnumerable
{
LogicalOperator parent;
public LogicalOperator Parent
{
set
{
parent = value;
}
}
public AndEnumerator GetEnumerator()
{
return new AndEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class AndEnumerator: IEnumerator
{
int nIndex;
LogicalOperator parent;
public AndEnumerator(LogicalOperator par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.AndCount );
}
public SchemaString Current
{
get
{
return(parent.GetAndAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // And collection
#region Or accessor methods
public int GetOrMinCount()
{
return 1;
}
public int OrMinCount
{
get
{
return 1;
}
}
public int GetOrMaxCount()
{
return 1;
}
public int OrMaxCount
{
get
{
return 1;
}
}
public int GetOrCount()
{
return DomChildCount(NodeType.Element, "", "Or");
}
public int OrCount
{
get
{
return DomChildCount(NodeType.Element, "", "Or");
}
}
public bool HasOr()
{
return HasDomChild(NodeType.Element, "", "Or");
}
public SchemaString GetOrAt(int index)
{
return new SchemaString(GetDomNodeValue(GetDomChildAt(NodeType.Element, "", "Or", index)));
}
public SchemaString GetOr()
{
return GetOrAt(0);
}
public SchemaString Or
{
get
{
return GetOrAt(0);
}
}
public void RemoveOrAt(int index)
{
RemoveDomChildAt(NodeType.Element, "", "Or", index);
}
public void RemoveOr()
{
while (HasOr())
RemoveOrAt(0);
}
public void AddOr(SchemaString newValue)
{
AppendDomChild(NodeType.Element, "", "Or", newValue.ToString());
}
public void InsertOrAt(SchemaString newValue, int index)
{
InsertDomChildAt(NodeType.Element, "", "Or", index, newValue.ToString());
}
public void ReplaceOrAt(SchemaString newValue, int index)
{
ReplaceDomChildAt(NodeType.Element, "", "Or", index, newValue.ToString());
}
#endregion // Or accessor methods
#region Or collection
public OrCollection MyOrs = new OrCollection( );
public class OrCollection: IEnumerable
{
LogicalOperator parent;
public LogicalOperator Parent
{
set
{
parent = value;
}
}
public OrEnumerator GetEnumerator()
{
return new OrEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class OrEnumerator: IEnumerator
{
int nIndex;
LogicalOperator parent;
public OrEnumerator(LogicalOperator par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.OrCount );
}
public SchemaString Current
{
get
{
return(parent.GetOrAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // Or collection
private void SetCollectionParents()
{
MyAnds.Parent = this;
MyOrs.Parent = this;
}
}
}
| |
using AE.Net.Mail.Imap;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace AE.Net.Mail {
public class ImapClient : TextClient, IMailClient {
private string _SelectedMailbox;
private int _tag = 0;
private string[] _Capability;
private bool _Idling;
private Thread _IdleEvents;
private string _FetchHeaders = null;
public ImapClient() { }
public ImapClient(string host, string username, string password, AuthMethods method = AuthMethods.Login, int port = 143, bool secure = false, bool skipSslValidation = false) {
Connect(host, port, secure, skipSslValidation);
AuthMethod = method;
Login(username, password);
}
public enum AuthMethods {
Login,
CRAMMD5,
SaslOAuth
}
public virtual AuthMethods AuthMethod { get; set; }
private string GetTag() {
_tag++;
return string.Format("xm{0:000} ", _tag);
}
public virtual bool Supports(string command) {
return (_Capability ?? Capability()).Contains(command, StringComparer.OrdinalIgnoreCase);
}
private EventHandler<MessageEventArgs> _NewMessage;
public virtual event EventHandler<MessageEventArgs> NewMessage {
add {
_NewMessage += value;
IdleStart();
}
remove {
_NewMessage -= value;
if (!HasEvents)
IdleStop();
}
}
private EventHandler<MessageEventArgs> _MessageDeleted;
public virtual event EventHandler<MessageEventArgs> MessageDeleted {
add {
_MessageDeleted += value;
IdleStart();
}
remove {
_MessageDeleted -= value;
if (!HasEvents)
IdleStop();
}
}
protected virtual void IdleStart() {
if (string.IsNullOrEmpty(_SelectedMailbox)) {
SelectMailbox("Inbox");
}
_Idling = true;
if (!Supports("IDLE")) {
throw new InvalidOperationException("This IMAP server does not support the IDLE command");
}
CheckMailboxSelected();
IdleResume();
}
protected virtual void IdlePause() {
if (_IdleEvents == null || !_Idling)
return;
CheckConnectionStatus();
SendCommand("DONE");
if (!_IdleEvents.Join(2000))
_IdleEvents.Abort();
_IdleEvents = null;
}
protected virtual void IdleResume() {
if (!_Idling)
return;
IdleResumeCommand();
if (_IdleEvents == null) {
_IdleARE = new AutoResetEvent(false);
_IdleEvents = new Thread(WatchIdleQueue);
_IdleEvents.Name = "_IdleEvents";
_IdleEvents.Start();
}
}
private void IdleResumeCommand() {
SendCommandGetResponse(GetTag() + "IDLE");
if (_IdleARE != null) _IdleARE.Set();
}
private bool HasEvents {
get {
return _MessageDeleted != null || _NewMessage != null;
}
}
protected virtual void IdleStop() {
_Idling = false;
IdlePause();
if (_IdleEvents != null) {
_IdleARE.Close();
if (!_IdleEvents.Join(2000))
_IdleEvents.Abort();
_IdleEvents = null;
}
}
public virtual bool TryGetResponse(out string response, int millisecondsTimeout) {
using (var mre = new System.Threading.ManualResetEventSlim(false)) {
string resp = response = null;
ThreadPool.QueueUserWorkItem(_ => {
resp = GetResponse();
mre.Set();
});
if (mre.Wait(millisecondsTimeout)) {
response = resp;
return true;
} else
return false;
}
}
private static readonly int idleTimeout = (int)TimeSpan.FromMinutes(10).TotalMilliseconds;
private static AutoResetEvent _IdleARE;
private void WatchIdleQueue() {
try {
string last = null, resp;
while (true) {
if (!TryGetResponse(out resp, idleTimeout)) { //send NOOP every 20 minutes
Noop(false); //call noop without aborting this Idle thread
continue;
}
if (resp.Contains("OK IDLE"))
return;
var data = resp.Split(' ');
if (data[0] == "*" && data.Length >= 3) {
var e = new MessageEventArgs { Client = this, MessageCount = int.Parse(data[1]) };
if (data[2].Is("EXISTS") && !last.Is("EXPUNGE") && e.MessageCount > 0) {
ThreadPool.QueueUserWorkItem(callback => _NewMessage.Fire(this, e)); //Fire the event on a separate thread
} else if (data[2].Is("EXPUNGE")) {
_MessageDeleted.Fire(this, e);
}
last = data[2];
}
}
} catch (Exception) { }
}
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
if (disposing) {
if (_IdleEvents != null) {
_IdleEvents.Abort();
}
if (_IdleARE != null) {
_IdleARE.Dispose();
}
}
_IdleEvents = null;
_IdleARE = null;
}
public virtual void AppendMail(MailMessage email, string mailbox = null) {
IdlePause();
mailbox = ModifiedUtf7Encoding.Encode(mailbox);
string flags = String.Empty;
var body = new StringBuilder();
using (var txt = new System.IO.StringWriter(body))
email.Save(txt);
string size = body.Length.ToString();
if (email.RawFlags.Length > 0) {
flags = " (" + string.Join(" ", email.Flags) + ")";
}
if (mailbox == null)
CheckMailboxSelected();
mailbox = mailbox ?? _SelectedMailbox;
string command = GetTag() + "APPEND " + (mailbox ?? _SelectedMailbox).QuoteString() + flags + " {" + size + "}";
string response = SendCommandGetResponse(command);
if (response.StartsWith("+")) {
response = SendCommandGetResponse(body.ToString());
}
IdleResume();
}
public virtual void Noop() {
Noop(true);
}
private void Noop(bool pauseIdle) {
if (pauseIdle)
IdlePause();
else
SendCommandGetResponse("DONE");
var tag = GetTag();
var response = SendCommandGetResponse(tag + "NOOP");
while (!response.StartsWith(tag)) {
response = GetResponse();
}
if (pauseIdle)
IdleResume();
else
IdleResumeCommand();
}
public virtual string[] Capability() {
IdlePause();
string command = GetTag() + "CAPABILITY";
string response = SendCommandGetResponse(command);
if (response.StartsWith("* CAPABILITY "))
response = response.Substring(13);
_Capability = response.Trim().Split(' ');
GetResponse();
IdleResume();
return _Capability;
}
public virtual void Copy(string messageset, string destination) {
CheckMailboxSelected();
IdlePause();
string prefix = null;
if (messageset.StartsWith("UID ", StringComparison.OrdinalIgnoreCase)) {
messageset = messageset.Substring(4);
prefix = "UID ";
}
string command = string.Concat(GetTag(), prefix, "COPY ", messageset, " " + destination.QuoteString());
SendCommandCheckOK(command);
IdleResume();
}
public virtual void CreateMailbox(string mailbox) {
IdlePause();
string command = GetTag() + "CREATE " + ModifiedUtf7Encoding.Encode(mailbox).QuoteString();
SendCommandCheckOK(command);
IdleResume();
}
public virtual void DeleteMailbox(string mailbox) {
IdlePause();
string command = GetTag() + "DELETE " + ModifiedUtf7Encoding.Encode(mailbox).QuoteString();
SendCommandCheckOK(command);
IdleResume();
}
public virtual Mailbox Examine(string mailbox) {
IdlePause();
Mailbox x = null;
string tag = GetTag();
string command = tag + "EXAMINE " + ModifiedUtf7Encoding.Encode(mailbox).QuoteString();
string response = SendCommandGetResponse(command);
if (response.StartsWith("*")) {
x = new Mailbox(mailbox);
while (response.StartsWith("*")) {
Match m;
m = Regex.Match(response, @"(\d+) EXISTS");
if (m.Groups.Count > 1)
x.NumMsg = m.Groups[1].ToString().ToInt();
m = Regex.Match(response, @"(\d+) RECENT");
if (m.Groups.Count > 1)
x.NumNewMsg = m.Groups[1].Value.ToInt();
m = Regex.Match(response, @"UNSEEN (\d+)");
if (m.Groups.Count > 1)
x.NumUnSeen = m.Groups[1].Value.ToInt();
m = Regex.Match(response, @"UIDVALIDITY (\d+)");
if (m.Groups.Count > 1)
x.UIDValidity = m.Groups[1].Value.ToInt();
m = Regex.Match(response, @" FLAGS \((.*?)\)");
if (m.Groups.Count > 1)
x.SetFlags(m.Groups[1].ToString());
response = GetResponse();
}
_SelectedMailbox = mailbox;
}
IdleResume();
return x;
}
public virtual void Expunge() {
CheckMailboxSelected();
IdlePause();
string tag = GetTag();
string command = tag + "EXPUNGE";
string response = SendCommandGetResponse(command);
while (response.StartsWith("*")) {
response = GetResponse();
}
IdleResume();
}
public virtual void DeleteMessage(AE.Net.Mail.MailMessage msg) {
DeleteMessage(msg.Uid);
}
public virtual void DeleteMessage(string uid) {
CheckMailboxSelected();
Store("UID " + uid, true, "\\Seen \\Deleted");
}
public virtual void MarkMessageRead(string uid)
{
CheckMailboxSelected();
Store("UID " + uid, true, "\\Seen");
}
public virtual void MoveMessage(string uid, string folderName) {
CheckMailboxSelected();
Copy("UID " + uid, folderName);
DeleteMessage(uid);
}
protected virtual void CheckMailboxSelected() {
if (string.IsNullOrEmpty(_SelectedMailbox))
SelectMailbox("INBOX");
}
public virtual MailMessage GetMessage(string uid, bool headersonly = false) {
return GetMessage(uid, headersonly, true);
}
public virtual MailMessage GetMessage(int index, bool headersonly = false) {
return GetMessage(index, headersonly, true);
}
public virtual MailMessage GetMessage(int index, bool headersonly, bool setseen) {
return GetMessages(index, index, headersonly, setseen).FirstOrDefault();
}
public virtual MailMessage GetMessage(string uid, bool headersonly, bool setseen) {
return GetMessages(uid, uid, headersonly, setseen).FirstOrDefault();
}
public virtual MailMessage[] GetMessages(string startUID, string endUID, bool headersonly = true, bool setseen = false) {
return GetMessages(startUID, endUID, true, headersonly, setseen);
}
public virtual MailMessage[] GetMessages(int startIndex, int endIndex, bool headersonly = true, bool setseen = false) {
return GetMessages((startIndex + 1).ToString(), (endIndex + 1).ToString(), false, headersonly, setseen);
}
public virtual void DownloadMessage(System.IO.Stream stream, int index, bool setseen) {
GetMessages((index + 1).ToString(), (index + 1).ToString(), false, false, setseen, (message, size, headers) => {
Utilities.CopyStream(message, stream, size);
return null;
});
}
public virtual void DownloadMessage(System.IO.Stream stream, string uid, bool setseen) {
GetMessages(uid, uid, true, false, setseen, (message, size, headers) => {
Utilities.CopyStream(message, stream, size);
return null;
});
}
public virtual MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen) {
var x = new List<MailMessage>();
GetMessages(start, end, uid, headersonly, setseen, (stream, size, imapHeaders) => {
var mail = new MailMessage { Encoding = Encoding };
mail.Size = size;
if (imapHeaders["UID"] != null)
mail.Uid = imapHeaders["UID"];
if (imapHeaders["Flags"] != null)
mail.SetFlags(imapHeaders["Flags"]);
mail.Load(_Stream, headersonly, mail.Size);
foreach (var key in imapHeaders.AllKeys.Except(new[] { "UID", "Flags", "BODY[]", "BODY[HEADER]" }, StringComparer.OrdinalIgnoreCase))
mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));
x.Add(mail);
return mail;
});
return x.ToArray();
}
public virtual void GetMessages(string start, string end, bool uid, bool headersonly, bool setseen, Func<System.IO.Stream, int, NameValueCollection, MailMessage> action) {
CheckMailboxSelected();
IdlePause();
string tag = GetTag();
string command = tag + (uid ? "UID " : null)
+ "FETCH " + start + ":" + end + " ("
+ _FetchHeaders + "UID FLAGS BODY"
+ (setseen ? null : ".PEEK")
+ "[" + (headersonly ? "HEADER" : null) + "])";
string response;
SendCommand(command);
while (true) {
response = GetResponse();
if (string.IsNullOrEmpty(response) || response.Contains(tag + "OK"))
break;
if (response[0] != '*' || !response.Contains("FETCH ("))
continue;
var imapHeaders = Utilities.ParseImapHeader(response.Substring(response.IndexOf('(') + 1));
var size = (imapHeaders["BODY[HEADER]"] ?? imapHeaders["BODY[]"]).Trim('{', '}').ToInt();
var msg = action(_Stream, size, imapHeaders);
response = GetResponse();
var n = response.Trim().LastOrDefault();
if (n != ')') {
System.Diagnostics.Debugger.Break();
RaiseWarning(null, "Expected \")\" in stream, but received \"" + response + "\"");
}
}
IdleResume();
}
public virtual Quota GetQuota(string mailbox) {
if (!Supports("NAMESPACE"))
throw new Exception("This command is not supported by the server!");
IdlePause();
Quota quota = null;
string command = GetTag() + "GETQUOTAROOT " + ModifiedUtf7Encoding.Encode(mailbox).QuoteString();
string response = SendCommandGetResponse(command);
string reg = "\\* QUOTA (.*?) \\((.*?) (.*?) (.*?)\\)";
while (response.StartsWith("*")) {
Match m = Regex.Match(response, reg);
if (m.Groups.Count > 1) {
quota = new Quota(m.Groups[1].ToString(),
m.Groups[2].ToString(),
Int32.Parse(m.Groups[3].ToString()),
Int32.Parse(m.Groups[4].ToString())
);
break;
}
response = GetResponse();
}
IdleResume();
return quota;
}
public virtual Mailbox[] ListMailboxes(string reference, string pattern) {
IdlePause();
var x = new List<Mailbox>();
string command = GetTag() + "LIST " + reference.QuoteString() + " " + pattern.QuoteString();
const string reg = "\\* LIST \\(([^\\)]*)\\) \\\"([^\\\"]+)\\\" \\\"?([^\\\"]+)\\\"?";
string response = SendCommandGetResponse(command);
Match m = Regex.Match(response, reg);
while (m.Groups.Count > 1) {
Mailbox mailbox = new Mailbox(m.Groups[3].ToString());
mailbox.SetFlags(m.Groups[1].ToString());
x.Add(mailbox);
response = GetResponse();
m = Regex.Match(response, reg);
}
IdleResume();
return x.ToArray();
}
public virtual Mailbox[] ListSuscribesMailboxes(string reference, string pattern) {
IdlePause();
var x = new List<Mailbox>();
string command = GetTag() + "LSUB " + reference.QuoteString() + " " + pattern.QuoteString();
string reg = "\\* LSUB \\(([^\\)]*)\\) \\\"([^\\\"]+)\\\" \\\"([^\\\"]+)\\\"";
string response = SendCommandGetResponse(command);
Match m = Regex.Match(response, reg);
while (m.Groups.Count > 1) {
Mailbox mailbox = new Mailbox(m.Groups[3].ToString());
x.Add(mailbox);
response = GetResponse();
m = Regex.Match(response, reg);
}
IdleResume();
return x.ToArray();
}
internal override void OnLogin(string login, string password) {
string command = String.Empty;
string result = String.Empty;
string tag = GetTag();
string key;
switch (AuthMethod) {
case AuthMethods.CRAMMD5:
command = tag + "AUTHENTICATE CRAM-MD5";
result = SendCommandGetResponse(command);
// retrieve server key
key = result.Replace("+ ", "");
key = System.Text.Encoding.Default.GetString(Convert.FromBase64String(key));
// calcul hash
using (var kMd5 = new HMACMD5(System.Text.Encoding.ASCII.GetBytes(password))) {
byte[] hash1 = kMd5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(key));
key = BitConverter.ToString(hash1).ToLower().Replace("-", "");
result = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(login + " " + key));
result = SendCommandGetResponse(result);
}
break;
case AuthMethods.Login:
command = tag + "LOGIN " + login.QuoteString() + " " + password.QuoteString();
result = SendCommandGetResponse(command);
break;
case AuthMethods.SaslOAuth:
string sasl = "user=" + login + "\x01" + "auth=Bearer " + password + "\x01" + "\x01";
string base64 = Convert.ToBase64String(Encoding.GetBytes(sasl));
command = tag + "AUTHENTICATE XOAUTH2 " + base64;
result = SendCommandGetResponse(command);
break;
default:
throw new NotSupportedException();
}
if (result.StartsWith("* CAPABILITY ")) {
_Capability = result.Substring(13).Trim().Split(' ');
result = GetResponse();
}
if (!result.StartsWith(tag + "OK")) {
if (result.StartsWith("+ ") && result.EndsWith("==")) {
string jsonErr = Utilities.DecodeBase64(result.Substring(2), System.Text.Encoding.UTF7);
throw new Exception(jsonErr);
} else
throw new Exception(result);
}
//if (Supports("COMPRESS=DEFLATE")) {
// SendCommandCheckOK(GetTag() + "compress deflate");
// _Stream0 = _Stream;
// // _Reader = new System.IO.StreamReader(new System.IO.Compression.DeflateStream(_Stream0, System.IO.Compression.CompressionMode.Decompress, true), System.Text.Encoding.Default);
// // _Stream = new System.IO.Compression.DeflateStream(_Stream0, System.IO.Compression.CompressionMode.Compress, true);
//}
if (Supports("X-GM-EXT-1")) {
_FetchHeaders = "X-GM-MSGID X-GM-THRID X-GM-LABELS ";
}
}
internal override void OnLogout() {
if (IsConnected)
SendCommand(GetTag() + "LOGOUT");
}
public virtual Namespaces Namespace() {
if (!Supports("NAMESPACE"))
throw new NotSupportedException("This command is not supported by the server!");
IdlePause();
string command = GetTag() + "NAMESPACE";
string response = SendCommandGetResponse(command);
if (!response.StartsWith("* NAMESPACE")) {
throw new Exception("Unknow server response !");
}
response = response.Substring(12);
Namespaces n = new Namespaces();
//[TODO] be sure to parse correctly namespace when not all namespaces are present. NIL character
string reg = @"\((.*?)\) \((.*?)\) \((.*?)\)$";
Match m = Regex.Match(response, reg);
if (m.Groups.Count != 4)
throw new Exception("En error occure, this command is not fully supported !");
string reg2 = "\\(\\\"(.*?)\\\" \\\"(.*?)\\\"\\)";
Match m2 = Regex.Match(m.Groups[1].ToString(), reg2);
while (m2.Groups.Count > 1) {
n.ServerNamespace.Add(new Namespace(m2.Groups[1].Value, m2.Groups[2].Value));
m2 = m2.NextMatch();
}
m2 = Regex.Match(m.Groups[2].ToString(), reg2);
while (m2.Groups.Count > 1) {
n.UserNamespace.Add(new Namespace(m2.Groups[1].Value, m2.Groups[2].Value));
m2 = m2.NextMatch();
}
m2 = Regex.Match(m.Groups[3].ToString(), reg2);
while (m2.Groups.Count > 1) {
n.SharedNamespace.Add(new Namespace(m2.Groups[1].Value, m2.Groups[2].Value));
m2 = m2.NextMatch();
}
GetResponse();
IdleResume();
return n;
}
public virtual int GetMessageCount() {
CheckMailboxSelected();
return GetMessageCount(null);
}
public virtual int GetMessageCount(string mailbox) {
IdlePause();
string command = GetTag() + "STATUS " + Utilities.QuoteString(ModifiedUtf7Encoding.Encode(mailbox) ?? _SelectedMailbox) + " (MESSAGES)";
string response = SendCommandGetResponse(command);
string reg = @"\* STATUS.*MESSAGES (\d+)";
int result = 0;
while (response.StartsWith("*")) {
Match m = Regex.Match(response, reg);
if (m.Groups.Count > 1)
result = Convert.ToInt32(m.Groups[1].ToString());
response = GetResponse();
m = Regex.Match(response, reg);
}
IdleResume();
return result;
}
public virtual void RenameMailbox(string frommailbox, string tomailbox) {
IdlePause();
string command = GetTag() + "RENAME " + frommailbox.QuoteString() + " " + tomailbox.QuoteString();
SendCommandCheckOK(command);
IdleResume();
}
public virtual string[] Search(SearchCondition criteria, bool uid = true) {
return Search(criteria.ToString(), uid);
}
public virtual string[] Search(string criteria, bool uid = true) {
CheckMailboxSelected();
string isuid = uid ? "UID " : "";
string tag = GetTag();
string command = tag + isuid + "SEARCH " + criteria;
string response = SendCommandGetResponse(command);
if (!response.StartsWith("* SEARCH", StringComparison.InvariantCultureIgnoreCase) && !IsResultOK(response)) {
throw new Exception(response);
}
string temp;
while (!(temp = GetResponse()).StartsWith(tag)) {
response += Environment.NewLine + temp;
}
var m = Regex.Match(response, @"^\* SEARCH (.*)");
return m.Groups[1].Value.Trim().Split(' ').Where(x => !string.IsNullOrEmpty(x)).ToArray();
}
public virtual Lazy<MailMessage>[] SearchMessages(SearchCondition criteria, bool headersonly = false, bool setseen = false) {
return Search(criteria, true)
.Select(x => new Lazy<MailMessage>(() => GetMessage(x, headersonly, setseen)))
.ToArray();
}
public virtual Mailbox SelectMailbox(string mailboxName) {
IdlePause();
mailboxName = ModifiedUtf7Encoding.Encode(mailboxName);
var tag = GetTag();
var command = tag + "SELECT " + mailboxName.QuoteString();
var response = SendCommandGetResponse(command);
if (IsResultOK(response))
response = GetResponse();
var mailbox = new Mailbox(mailboxName);
Match match;
while (response.StartsWith("*")) {
if ((match = Regex.Match(response, @"\d+(?=\s+EXISTS)")).Success)
mailbox.NumMsg = match.Value.ToInt();
else if ((match = Regex.Match(response, @"\d+(?=\s+RECENT)")).Success)
mailbox.NumNewMsg = match.Value.ToInt();
else if ((match = Regex.Match(response, @"(?<=UNSEEN\s+)\d+")).Success)
mailbox.NumUnSeen = match.Value.ToInt();
else if ((match = Regex.Match(response, @"(?<=\sFLAGS\s+\().*?(?=\))")).Success)
mailbox.SetFlags(match.Value);
response = GetResponse();
}
CheckResultOK(response);
mailbox.IsWritable = Regex.IsMatch(response, "READ.WRITE", RegexOptions.IgnoreCase);
_SelectedMailbox = mailboxName;
IdleResume();
return mailbox;
}
public virtual void SetFlags(Flags flags, params MailMessage[] msgs) {
SetFlags(FlagsToFlagString(flags), msgs);
}
public virtual void SetFlags(string flags, params MailMessage[] msgs) {
Store("UID " + string.Join(" ", msgs.Select(x => x.Uid)), true, flags);
foreach (var msg in msgs) {
msg.SetFlags(flags);
}
}
private string FlagsToFlagString(Flags flags) {
return string.Join(" ", flags.ToString().Split(',').Select(x => "\\" + x.Trim()));
}
public virtual void AddFlags(Flags flags, params MailMessage[] msgs) {
AddFlags(FlagsToFlagString(flags), msgs);
}
public virtual void AddFlags(string flags, params MailMessage[] msgs) {
Store("UID " + string.Join(" ", msgs.Select(x => x.Uid)), false, flags);
foreach (var msg in msgs) {
msg.SetFlags(FlagsToFlagString(msg.Flags) + " " + flags);
}
}
public virtual void Store(string messageset, bool replace, string flags) {
CheckMailboxSelected();
IdlePause();
string prefix = null;
if (messageset.StartsWith("UID ", StringComparison.OrdinalIgnoreCase)) {
messageset = messageset.Substring(4);
prefix = "UID ";
}
string command = string.Concat(GetTag(), prefix, "STORE ", messageset, " ", replace ? "" : "+", "FLAGS.SILENT (" + flags + ")");
string response = SendCommandGetResponse(command);
while (response.StartsWith("*")) {
response = GetResponse();
}
CheckResultOK(response);
IdleResume();
}
public virtual void SuscribeMailbox(string mailbox) {
IdlePause();
string command = GetTag() + "SUBSCRIBE " + ModifiedUtf7Encoding.Encode(mailbox).QuoteString();
SendCommandCheckOK(command);
IdleResume();
}
public virtual void UnSuscribeMailbox(string mailbox) {
IdlePause();
string command = GetTag() + "UNSUBSCRIBE " + ModifiedUtf7Encoding.Encode(mailbox).QuoteString();
SendCommandCheckOK(command);
IdleResume();
}
internal override void CheckResultOK(string response) {
if (!IsResultOK(response)) {
response = response.Substring(response.IndexOf(" ")).Trim();
throw new Exception(response);
}
}
internal bool IsResultOK(string response) {
response = response.Substring(response.IndexOf(" ")).Trim();
return response.ToUpper().StartsWith("OK");
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using RealtimeFramework.Messaging.Ext;
using RealtimeFramework.Messaging.Exceptions;
namespace RealtimeFramework.Messaging
{
/// <summary>
/// The ORTC (Open Real-Time Connectivity) was developed to add a layer of abstraction to real-time full-duplex web communications platforms by making real-time web applications independent of those platforms.
/// OrtcClient instance provides methods for sending and receiving data in real-time over the web.
/// </summary>
/// /// <example>
/// <code>
/// string applicationKey = "myApplicationKey";
/// string authenticationToken = "myAuthenticationToken";
///
/// // Create ORTC client
/// OrtcClient ortcClient = new RealtimeFramework.Messaging.OrtcClient();
/// ortcClient.ClusterUrl = "http://ortc-developers.realtime.co/server/2.1/";
///
/// // Ortc client handlers
/// ortcClient.OnConnected += new OnConnectedDelegate(ortc_OnConnected);
/// ortcClient.OnSubscribed += new OnSubscribedDelegate(ortc_OnSubscribed);
/// ortcClient.OnException += new OnExceptionDelegate(ortc_OnException);
///
/// ortcClient.connect(applicationKey, authenticationToken);
///
/// private void ortc_OnConnected(object sender)
/// {
/// ortcClient.Subscribe("channel1", true, OnMessageCallback);
/// }
///
/// private void OnMessageCallback(object sender, string channel, string message)
/// {
/// System.Diagnostics.Debug.Writeline("Message received: " + message);
/// }
/// private void ortc_OnSubscribed(object sender, string channel)
/// {
/// ortcClient.Send(channel, "your message");
/// }
///
/// private void ortc_OnException(object sender, Exception ex)
/// {
/// System.Diagnostics.Debug.Writeline(ex.Message);
/// }
///
/// </code>
/// </example>
public class OrtcClient
{
#region Attributes (5)
internal RealtimeFramework.Messaging.Client _client;
private string _url;
private string _clusterUrl;
private bool _isCluster;
private int _heartbeatTime;
private int _heartbeatFail;
internal string _applicationKey;
internal string _authenticationToken;
internal SynchronizationContext _synchContext; // To synchronize different contexts, preventing cross-thread operation errors (Windows Application and WPF Application))
#endregion
#region Properties (9)
/// <summary>
/// Gets or sets the client object identifier.
/// </summary>
/// <value>Object identifier.</value>
public string Id { get; set; }
/// <summary>
/// Gets or sets the gateway URL.
/// </summary>
/// <value>Gateway URL where the socket is going to connect.</value>
public string Url {
get {
return _url;
}
set {
_isCluster = false;
_url = String.IsNullOrEmpty(value) ? String.Empty : value.Trim();
}
}
/// <summary>
/// Gets or sets the cluster gateway URL.
/// </summary>
public string ClusterUrl {
get {
return _clusterUrl;
}
set {
_isCluster = true;
_clusterUrl = String.IsNullOrEmpty(value) ? String.Empty : value.Trim();
}
}
/// <summary>
/// Gets or sets a value indicating whether this instance is cluster.
/// </summary>
/// <value>
/// <c>true</c> if this instance is cluster; otherwise, <c>false</c>.
/// </value>
public bool IsCluster {
get { return _isCluster; }
set { _isCluster = value; }
}
/// <summary>
/// Gets or sets the connection timeout. Default value is 5000 miliseconds.
/// </summary>
public int ConnectionTimeout { get; set; }
/// <summary>
/// Gets a value indicating whether this client object is connected.
/// </summary>
/// <value>
/// <c>true</c> if this client is connected; otherwise, <c>false</c>.
/// </value>
public bool IsConnected { get; set; }
/// <summary>
/// Gets or sets the client connection metadata.
/// </summary>
/// <value>
/// Connection metadata.
/// </value>
public string ConnectionMetadata { get; set; }
/// <summary>
/// Gets or sets the client announcement subchannel.
/// </summary>
/// /// <value>
/// Announcement subchannel.
/// </value>
public string AnnouncementSubChannel { get; set; }
/// <summary>
/// Gets or sets the session id.
/// </summary>
/// <value>
/// The session id.
/// </value>
public string SessionId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this client has a heartbeat activated.
/// </summary>
/// <value>
/// <c>true</c> if the heartbeat is active; otherwise, <c>false</c>.
/// </value>
public bool HeartbeatActive { get; set; }
/// <summary>
/// Gets or sets a value indicating how many times can the client fail the heartbeat.
/// </summary>
/// <value>
/// Failure limit.
/// </value>
public int HeartbeatFails {
get { return _heartbeatFail; }
set { _heartbeatFail = value > Constants.HEARTBEAT_MAX_FAIL ? Constants.HEARTBEAT_MAX_FAIL : (value < Constants.HEARTBEAT_MIN_FAIL ? Constants.HEARTBEAT_MIN_FAIL : value); }
}
/// <summary>
/// Gets or sets the heartbeat interval.
/// </summary>
/// <value>
/// Interval in seconds between heartbeats.
/// </value>
public int HeartbeatTime {
get { return _heartbeatTime; }
set { _heartbeatTime = value > Constants.HEARTBEAT_MAX_TIME ? Constants.HEARTBEAT_MAX_TIME : (value < Constants.HEARTBEAT_MIN_TIME ? Constants.HEARTBEAT_MIN_TIME : value); }
}
#endregion
#region Delegates
/// <summary>
/// Occurs when the client connects to the gateway.
/// </summary>
/// <exclude/>
public delegate void OnConnectedDelegate(object sender);
/// <summary>
/// Occurs when the client disconnects from the gateway.
/// </summary>
/// <exclude/>
public delegate void OnDisconnectedDelegate(object sender);
/// <summary>
/// Occurs when the client subscribed to a channel.
/// </summary>
/// <exclude/>
public delegate void OnSubscribedDelegate(object sender, string channel);
/// <summary>
/// Occurs when the client unsubscribed from a channel.
/// </summary>
/// <exclude/>
public delegate void OnUnsubscribedDelegate(object sender, string channel);
/// <summary>
/// Occurs when there is an exception.
/// </summary>
/// <exclude/>
public delegate void OnExceptionDelegate(object sender, Exception ex);
/// <summary>
/// Occurs when the client attempts to reconnect to the gateway.
/// </summary>
/// <exclude/>
public delegate void OnReconnectingDelegate(object sender);
/// <summary>
/// Occurs when the client reconnected to the gateway.
/// </summary>
/// <exclude/>
public delegate void OnReconnectedDelegate(object sender);
/// <summary>
/// Occurs when the client receives a message in the specified channel.
/// </summary>
/// <exclude/>
public delegate void OnMessageDelegate(object sender, string channel, string message);
#endregion
/// <summary>
/// OrtcClient Constructor
/// </summary>
public OrtcClient() {
ConnectionTimeout = 5;
IsConnected = false;
IsCluster = false;
HeartbeatActive = false;
HeartbeatFails = 3;
HeartbeatTime = 15;
//_heartbeatTimer.Elapsed += new ElapsedEventHandler(_heartbeatTimer_Elapsed);
// To catch unobserved exceptions
TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException);
// To use the same context inside the tasks and prevent cross-thread operation errors (Windows Application and WPF Application)
_synchContext = System.Threading.SynchronizationContext.Current;
_client = new RealtimeFramework.Messaging.Client(this);
}
#region Public Methods
/// <summary>
/// Connects to the gateway with the application key and authentication token. The gateway must be set before using this method.
/// </summary>
/// <param name="appKey">Your application key to use ORTC.</param>
/// <param name="authToken">Authentication token that identifies your permissions.</param>
/// <example>
/// <code>
/// ortcClient.Connect("myApplicationKey", "myAuthenticationToken");
/// </code>
/// </example>
public void Connect(string appKey, string authToken) {
if (IsConnected) {
DelegateExceptionCallback(new OrtcAlreadyConnectedException("Already connected"));
} else if (String.IsNullOrEmpty(ClusterUrl) && String.IsNullOrEmpty(Url)) {
DelegateExceptionCallback(new OrtcEmptyFieldException("URL and Cluster URL are null or empty"));
} else if (String.IsNullOrEmpty(appKey)) {
DelegateExceptionCallback(new OrtcEmptyFieldException("Application Key is null or empty"));
} else if (String.IsNullOrEmpty(authToken)) {
DelegateExceptionCallback(new OrtcEmptyFieldException("Authentication ToKen is null or empty"));
} else if (!IsCluster && !Url.OrtcIsValidUrl()) {
DelegateExceptionCallback(new OrtcInvalidCharactersException("Invalid URL"));
} else if (IsCluster && !ClusterUrl.OrtcIsValidUrl()) {
DelegateExceptionCallback(new OrtcInvalidCharactersException("Invalid Cluster URL"));
} else if (!appKey.OrtcIsValidInput()) {
DelegateExceptionCallback(new OrtcInvalidCharactersException("Application Key has invalid characters"));
} else if (!authToken.OrtcIsValidInput()) {
DelegateExceptionCallback(new OrtcInvalidCharactersException("Authentication Token has invalid characters"));
} else if (AnnouncementSubChannel != null && !AnnouncementSubChannel.OrtcIsValidInput()) {
DelegateExceptionCallback(new OrtcInvalidCharactersException("Announcement Subchannel has invalid characters"));
} else if (!String.IsNullOrEmpty(ConnectionMetadata) && ConnectionMetadata.Length > Constants.MAX_CONNECTION_METADATA_SIZE) {
DelegateExceptionCallback(new OrtcMaxLengthException(String.Format("Connection metadata size exceeds the limit of {0} characters", Constants.MAX_CONNECTION_METADATA_SIZE)));
} else if (_client._isConnecting) {
DelegateExceptionCallback(new OrtcAlreadyConnectedException("Already trying to connect"));
} else {
_client.DoStopReconnecting();
_authenticationToken = authToken;
_applicationKey = appKey;
_client.DoConnect();
}
}
/// <summary>
/// Sends a message to a channel.
/// </summary>
/// <param name="channel">Channel name.</param>
/// <param name="message">Message to be sent.</param>
/// <example>
/// <code>
/// ortcClient.Send("channelName", "messageToSend");
/// </code>
/// </example>
public void Send(string channel, string message) {
if (!IsConnected) {
DelegateExceptionCallback(new OrtcNotConnectedException("Not connected"));
} else if (String.IsNullOrEmpty(channel)) {
DelegateExceptionCallback(new OrtcEmptyFieldException("Channel is null or empty"));
} else if (!channel.OrtcIsValidInput()) {
DelegateExceptionCallback(new OrtcInvalidCharactersException("Channel has invalid characters"));
} else if (String.IsNullOrEmpty(message)) {
DelegateExceptionCallback(new OrtcEmptyFieldException("Message is null or empty"));
} else if (channel.Length > Constants.MAX_CHANNEL_SIZE) {
DelegateExceptionCallback(new OrtcMaxLengthException(String.Format("Channel size exceeds the limit of {0} characters", Constants.MAX_CHANNEL_SIZE)));
} else {
_client.Send(channel, message);
}
}
/// <summary>
/// Sends a message to a channel for a specific application key
/// </summary>
/// <param name="applicationKey">An application key</param>
/// <param name="privateKey">A private key</param>
/// <param name="channel">A channel name</param>
/// <param name="message">A message to send</param>
public void SendProxy(string applicationKey, string privateKey, string channel, string message) {
if (!IsConnected) {
DelegateExceptionCallback(new OrtcNotConnectedException("Not connected"));
} else if (String.IsNullOrEmpty(applicationKey)) {
DelegateExceptionCallback(new OrtcEmptyFieldException("Application Key is null or empty"));
} else if (String.IsNullOrEmpty(privateKey)) {
DelegateExceptionCallback(new OrtcEmptyFieldException("Private Key is null or empty"));
} else if (String.IsNullOrEmpty(channel)) {
DelegateExceptionCallback(new OrtcEmptyFieldException("Channel is null or empty"));
} else if (!channel.OrtcIsValidInput()) {
DelegateExceptionCallback(new OrtcInvalidCharactersException("Channel has invalid characters"));
} else if (String.IsNullOrEmpty(message)) {
DelegateExceptionCallback(new OrtcEmptyFieldException("Message is null or empty"));
} else if (channel.Length > Constants.MAX_CHANNEL_SIZE) {
DelegateExceptionCallback(new OrtcMaxLengthException(String.Format("Channel size exceeds the limit of {0} characters", Constants.MAX_CHANNEL_SIZE)));
} else {
_client.SendProxy(applicationKey, privateKey, channel, message);
}
}
/// <summary>
/// Subscribes to a channel.
/// </summary>
/// <param name="channel">Channel name.</param>
/// <param name="subscribeOnReconnected">Subscribe to the specified channel on reconnect.</param>
/// <param name="onMessage"><see cref="OnMessageDelegate"/> callback.</param>
/// <example>
/// <code>
/// ortcClient.Subscribe("channelName", true, OnMessageCallback);
/// private void OnMessageCallback(object sender, string channel, string message)
/// {
/// // Do something
/// }
/// </code>
/// </example>
public void Subscribe(string channel, bool subscribeOnReconnected, OnMessageDelegate onMessage) {
if (!IsConnected) {
DelegateExceptionCallback(new OrtcNotConnectedException("Not connected"));
} else if (String.IsNullOrEmpty(channel)) {
DelegateExceptionCallback(new OrtcEmptyFieldException("Channel is null or empty"));
} else if (!channel.OrtcIsValidInput()) {
DelegateExceptionCallback(new OrtcInvalidCharactersException("Channel has invalid characters"));
} else if(channel.Length > Constants.MAX_CHANNEL_SIZE) {
DelegateExceptionCallback(new OrtcMaxLengthException(String.Format("Channel size exceeds the limit of {0} characters", Constants.MAX_CHANNEL_SIZE)));
} else if (_client._subscribedChannels.ContainsKey(channel)) {
ChannelSubscription channelSubscription = null;
_client._subscribedChannels.TryGetValue(channel, out channelSubscription);
if (channelSubscription != null) {
if (channelSubscription.IsSubscribing) {
DelegateExceptionCallback(new OrtcSubscribedException(String.Format("Already subscribing to the channel {0}", channel)));
} else if (channelSubscription.IsSubscribed) {
DelegateExceptionCallback(new OrtcSubscribedException(String.Format("Already subscribed to the channel {0}", channel)));
} else {
_client.subscribe(channel, subscribeOnReconnected, onMessage);
}
}
} else {
_client.subscribe(channel, subscribeOnReconnected, onMessage);
}
}
/// <summary>
/// Unsubscribes from a channel.
/// </summary>
/// <param name="channel">Channel name.</param>
/// <example>
/// <code>
/// ortcClient.Unsubscribe("channelName");
/// </code>
/// </example>
public void Unsubscribe(string channel) {
if (!IsConnected) {
DelegateExceptionCallback(new OrtcNotConnectedException("Not connected"));
} else if (String.IsNullOrEmpty(channel)) {
DelegateExceptionCallback(new OrtcEmptyFieldException("Channel is null or empty"));
} else if (!channel.OrtcIsValidInput()) {
DelegateExceptionCallback(new OrtcInvalidCharactersException("Channel has invalid characters"));
} else if (!_client._subscribedChannels.ContainsKey(channel)) {
DelegateExceptionCallback(new OrtcNotSubscribedException(String.Format("Not subscribed to the channel {0}", channel)));
} else if (channel.Length > Constants.MAX_CHANNEL_SIZE){
DelegateExceptionCallback(new OrtcMaxLengthException(String.Format("Channel size exceeds the limit of {0} characters", Constants.MAX_CHANNEL_SIZE)));
} else if (_client._subscribedChannels.ContainsKey(channel)) {
ChannelSubscription channelSubscription = null;
_client._subscribedChannels.TryGetValue(channel, out channelSubscription);
if (channelSubscription != null && !channelSubscription.IsSubscribed) {
DelegateExceptionCallback(new OrtcNotSubscribedException(String.Format("Not subscribed to the channel {0}", channel)));
} else {
_client.unsubscribe(channel);
}
} else {
DelegateExceptionCallback(new OrtcNotSubscribedException(String.Format("Not subscribed to the channel {0}", channel)));
}
}
/// <summary>
/// Disconnects from the gateway.
/// </summary>
/// <example>
/// <code>
/// ortcClient.Disconnect();
/// </code>
/// </example>
public void Disconnect() {
_client.DoStopReconnecting();
// Clear subscribed channels
_client._subscribedChannels.Clear();
if (!IsConnected) {
_client.DoDisconnect();
DelegateDisconnectedCallback ();
} else {
_client.DoDisconnect();
}
}
/// <summary>
/// Indicates whether is subscribed to a channel.
/// </summary>
/// <param name="channel">The channel name.</param>
/// <returns>
/// <c>true</c> if subscribed to the channel; otherwise, <c>false</c>.
/// </returns>
public bool IsSubscribed(string channel) {
bool result = false;
if (!IsConnected) {
DelegateExceptionCallback(new OrtcNotConnectedException("Not connected"));
} else if (String.IsNullOrEmpty(channel)) {
DelegateExceptionCallback(new OrtcEmptyFieldException("Channel is null or empty"));
} else if (!channel.OrtcIsValidInput()) {
DelegateExceptionCallback(new OrtcInvalidCharactersException("Channel has invalid characters"));
} else {
result = false;
if (_client._subscribedChannels.ContainsKey(channel)) {
ChannelSubscription channelSubscription = null;
_client._subscribedChannels.TryGetValue(channel, out channelSubscription);
if (channelSubscription != null && channelSubscription.IsSubscribed) {
result = true;
}
}
}
return result;
}
/// <summary>
/// Gets the subscriptions in the specified channel and if active the first 100 unique metadata.
/// </summary>
/// <param name="channel">Channel with presence data active.</param>
/// <param name="callback"><see cref="OnPresenceDelegate"/>Callback with error <see cref="OrtcPresenceException"/> and result <see cref="Presence"/>.</param>
/// <example>
/// <code>
/// client.Presence("presence-channel", (error, result) =>
/// {
/// if (error != null)
/// {
/// System.Diagnostics.Debug.Writeline(error.Message);
/// }
/// else
/// {
/// if (result != null)
/// {
/// System.Diagnostics.Debug.Writeline(result.Subscriptions);
///
/// if (result.Metadata != null)
/// {
/// foreach (var metadata in result.Metadata)
/// {
/// System.Diagnostics.Debug.Writeline(metadata.Key + " - " + metadata.Value);
/// }
/// }
/// }
/// else
/// {
/// System.Diagnostics.Debug.Writeline("There is no presence data");
/// }
/// }
/// });
/// </code>
/// </example>
public void Presence(String channel, OnPresenceDelegate callback) {
var isCluster = !String.IsNullOrEmpty(this.ClusterUrl);
var url = String.IsNullOrEmpty(this.ClusterUrl) ? this.Url : this.ClusterUrl;
Ext.Presence.GetPresence(url, isCluster, this._applicationKey, this._authenticationToken, channel, callback);
}
/// <summary>
/// Enables presence for the specified channel with first 100 unique metadata if metadata is set to true.
/// </summary>
/// <param name="privateKey">The private key provided when the ORTC service is purchased.</param>
/// <param name="channel">Channel to activate presence.</param>
/// <param name="metadata">Defines if to collect first 100 unique metadata.</param>
/// <param name="callback">Callback with error <see cref="OrtcPresenceException"/> and result.</param>
/// /// <example>
/// <code>
/// client.EnablePresence("myPrivateKey", "presence-channel", false, (error, result) =>
/// {
/// if (error != null)
/// {
/// System.Diagnostics.Debug.Writeline(error.Message);
/// }
/// else
/// {
/// System.Diagnostics.Debug.Writeline(result);
/// }
/// });
/// </code>
/// </example>
public void EnablePresence(String privateKey, String channel, bool metadata, OnEnablePresenceDelegate callback) {
var isCluster = !String.IsNullOrEmpty(this.ClusterUrl);
var url = String.IsNullOrEmpty(this.ClusterUrl) ? this.Url : this.ClusterUrl;
Ext.Presence.EnablePresence(url, isCluster, this._applicationKey, privateKey, channel, metadata, callback);
}
/// <summary>
/// Disables presence for the specified channel.
/// </summary>
/// <param name="privateKey">The private key provided when the ORTC service is purchased.</param>
/// <param name="channel">Channel to disable presence.</param>
/// <param name="callback">Callback with error <see cref="OrtcPresenceException"/> and result.</param>
public void DisablePresence(String privateKey, String channel, OnDisablePresenceDelegate callback) {
var isCluster = !String.IsNullOrEmpty(this.ClusterUrl);
var url = String.IsNullOrEmpty(this.ClusterUrl) ? this.Url : this.ClusterUrl;
Ext.Presence.DisablePresence(url, isCluster, this._applicationKey, privateKey, channel, callback);
}
#endregion
/// <summary>
/// Occurs when a connection attempt was successful.
/// </summary>
public event OrtcClient.OnConnectedDelegate OnConnected;
/// <summary>
/// Occurs when the client connection terminated.
/// </summary>
public event OrtcClient.OnDisconnectedDelegate OnDisconnected;
/// <summary>
/// Occurs when the client subscribed to a channel.
/// </summary>
public event OrtcClient.OnSubscribedDelegate OnSubscribed;
/// <summary>
/// Occurs when the client unsubscribed from a channel.
/// </summary>
public event OrtcClient.OnUnsubscribedDelegate OnUnsubscribed;
/// <summary>
/// Occurs when there is an error.
/// </summary>
public event OrtcClient.OnExceptionDelegate OnException;
/// <summary>
/// Occurs when a client attempts to reconnect.
/// </summary>
public event OrtcClient.OnReconnectingDelegate OnReconnecting;
/// <summary>
/// Occurs when a client reconnected.
/// </summary>
public event OrtcClient.OnReconnectedDelegate OnReconnected;
internal void DelegateConnectedCallback() {
var ev = OnConnected;
if (ev != null) {
if (_synchContext != null) {
_synchContext.Post(obj => ev(obj), this);
} else {
Task.Factory.StartNew(() => ev(this));
}
}
}
internal void DelegateDisconnectedCallback() {
var ev = OnDisconnected;
if (ev != null) {
if (_synchContext != null) {
_synchContext.Post(obj => ev(obj), this);
} else {
Task.Factory.StartNew(() => ev(this));
}
}
}
internal void DelegateSubscribedCallback(string channel) {
var ev = OnSubscribed;
if (ev != null) {
if (_synchContext != null) {
_synchContext.Post(obj => ev(obj, channel), this);
} else {
Task.Factory.StartNew(() => ev(this, channel));
}
}
}
internal void DelegateUnsubscribedCallback(string channel) {
var ev = OnUnsubscribed;
if (ev != null) {
if (_synchContext != null) {
_synchContext.Post(obj => ev(obj, channel), this);
} else {
Task.Factory.StartNew(() => ev(this, channel));
}
}
}
internal void DelegateExceptionCallback(Exception ex) {
var ev = OnException;
if (ev != null) {
if (_synchContext != null) {
_synchContext.Post(obj => ev(obj, ex), this);
} else {
Task.Factory.StartNew(() => ev(this, ex));
}
}
}
internal void DelegateReconnectingCallback() {
var ev = OnReconnecting;
if (ev != null) {
if (_synchContext != null) {
_synchContext.Post(obj => ev(obj), this);
} else {
Task.Factory.StartNew(() => ev(this));
}
}
}
internal void DelegateReconnectedCallback() {
var ev = OnReconnected;
if (ev != null) {
if (_synchContext != null) {
_synchContext.Post(obj => ev(obj), this);
} else {
Task.Factory.StartNew(() => ev(this));
}
}
}
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) {
e.SetObserved();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Xunit;
namespace Test
{
public class SumTests
{
public static IEnumerable<object[]> SumData(object[] counts)
{
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), x => Functions.SumRange(0L, x))) yield return results;
}
//
// Sum
//
[Theory]
[MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Sum_Int(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Sum());
Assert.Equal(sum, query.Select(x => (int?)x).Sum());
Assert.Equal(default(int), query.Select(x => (int?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -x));
Assert.Equal(-sum, query.Sum(x => -(int?)x));
Assert.Equal(default(int), query.Sum(x => (int?)null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (int?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(int?)x : null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (int?)null).Sum());
Assert.Equal(0, query.Sum(x => (int?)null));
}
[Theory]
[OuterLoop]
[MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 64 }))]
public static void Sum_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
Sum_Int(labeled, count, sum);
}
[Theory]
[MemberData("SumData", (object)(new int[] { 2 }))]
public static void Sum_Int_Overflow(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? int.MaxValue : x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? int.MaxValue : (int?)x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? int.MinValue : -x));
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? int.MinValue : -(int?)x));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Sum_Long(Labeled<ParallelQuery<int>> labeled, int count, long sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Select(x => (long)x).Sum());
Assert.Equal(sum, query.Select(x => (long?)x).Sum());
Assert.Equal(default(long), query.Select(x => (long?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -(long)x));
Assert.Equal(-sum, query.Sum(x => -(long?)x));
Assert.Equal(default(long), query.Sum(x => (long?)null));
}
[Theory]
[OuterLoop]
[MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Sum_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, long sum)
{
Sum_Long(labeled, count, sum);
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, long sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0L, count / 2), query.Select(x => x < count / 2 ? (long?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0L, count / 2), query.Sum(x => x < count / 2 ? -(long?)x : null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, long sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (long?)null).Sum());
Assert.Equal(0, query.Sum(x => (long?)null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 2 }))]
public static void Sum_Long_Overflow(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? long.MaxValue : x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? long.MaxValue : (long?)x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? long.MinValue : -x));
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? long.MinValue : -(long?)x));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Sum_Float(Labeled<ParallelQuery<int>> labeled, int count, float sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Select(x => (float)x).Sum());
Assert.Equal(sum, query.Select(x => (float?)x).Sum());
Assert.Equal(default(float), query.Select(x => (float?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -(float)x));
Assert.Equal(-sum, query.Sum(x => -(float?)x));
Assert.Equal(default(float), query.Sum(x => (float?)null));
}
[Theory]
[OuterLoop]
[MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Sum_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float sum)
{
Sum_Float(labeled, count, sum);
}
[Theory]
[MemberData("SumData", (object)(new int[] { 2 }))]
public static void Sum_Float_Overflow(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
Assert.True(float.IsInfinity(labeled.Item.Select(x => float.MaxValue).Sum()));
Assert.True(float.IsInfinity(labeled.Item.Select(x => (float?)float.MaxValue).Sum().Value));
Assert.True(float.IsInfinity(labeled.Item.Sum(x => float.MinValue)));
Assert.True(float.IsInfinity(labeled.Item.Sum(x => (float?)float.MaxValue).Value));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (float?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(float?)x : null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (float?)null).Sum());
Assert.Equal(0, query.Sum(x => (float?)null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Sum_Double(Labeled<ParallelQuery<int>> labeled, int count, double sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Select(x => (double)x).Sum());
Assert.Equal(sum, query.Select(x => (double?)x).Sum());
Assert.Equal(default(double), query.Select(x => (double?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -(double)x));
Assert.Equal(-sum, query.Sum(x => -(double?)x));
Assert.Equal(default(double), query.Sum(x => (double?)null));
}
[Theory]
[OuterLoop]
[MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Sum_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double sum)
{
Sum_Double(labeled, count, sum);
}
[Theory]
[MemberData("SumData", (object)(new int[] { 2 }))]
public static void Sum_Double_Overflow(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
Assert.True(double.IsInfinity(labeled.Item.Select(x => double.MaxValue).Sum()));
Assert.True(double.IsInfinity(labeled.Item.Select(x => (double?)double.MaxValue).Sum().Value));
Assert.True(double.IsInfinity(labeled.Item.Sum(x => double.MinValue)));
Assert.True(double.IsInfinity(labeled.Item.Sum(x => (double?)double.MaxValue).Value));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (double?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(double?)x : null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (double?)null).Sum());
Assert.Equal(0, query.Sum(x => (double?)null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Sum_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Select(x => (decimal)x).Sum());
Assert.Equal(sum, query.Select(x => (decimal?)x).Sum());
Assert.Equal(default(decimal), query.Select(x => (decimal?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -(decimal)x));
Assert.Equal(default(decimal), query.Sum(x => (decimal?)null));
}
[Theory]
[OuterLoop]
[MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Sum_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal sum)
{
Sum_Decimal(labeled, count, sum);
}
[Theory]
[MemberData("SumData", (object)(new int[] { 2 }))]
public static void Sum_Decimal_Overflow(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? decimal.MaxValue : x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? decimal.MaxValue : (decimal?)x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? decimal.MinValue : -x));
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? decimal.MinValue : -(decimal?)x));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (decimal?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(decimal?)x : null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (decimal?)null).Sum());
Assert.Equal(0, query.Sum(x => (decimal?)null));
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Sum_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (int?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (long)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (long?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (float)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (float?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (double)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (double?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (decimal)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (decimal?)x));
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Sum_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, int>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, int?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, long>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, long?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, float>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, float?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, double>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, double?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, decimal>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, decimal?>)(x => { throw new DeliberateTestException(); })));
}
[Fact]
public static void Sum_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Sum((Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Sum((Func<int?, int?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Sum((Func<long, long>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Sum((Func<long?, long?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Sum((Func<float, float>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Sum((Func<float?, float>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Sum((Func<double, double>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Sum((Func<double?, double>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Sum((Func<decimal, decimal>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Sum((Func<decimal?, decimal>)null));
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.3
*
* Copyright (c) 2013-2015, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to use, install, execute and perform the Spine
* Runtimes Software (the "Software") and derivative works solely for personal
* or internal use. Without the written permission of Esoteric Software (see
* Section 2 of the Spine Software License Agreement), you may not (a) modify,
* translate, adapt or otherwise create derivative works, improvements of the
* Software or develop new applications using the Software or (b) remove,
* delete, alter or obscure any trademarks or any copyright, trademark, patent
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE 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 UnityEngine;
using System.Collections.Generic;
using Spine;
namespace Spine.Unity.Modules {
public class SpriteAttacher : MonoBehaviour {
public bool attachOnStart = true;
public bool keepLoaderInMemory = true;
public Sprite sprite;
[SpineSlot]
public string slot;
private SpriteAttachmentLoader loader;
private RegionAttachment attachment;
void Start () {
if (attachOnStart)
Attach();
}
public void Attach () {
var skeletonRenderer = GetComponent<SkeletonRenderer>();
if (loader == null)
//create loader instance, tell it what sprite and shader to use
loader = new SpriteAttachmentLoader(sprite, Shader.Find("Spine/Skeleton"));
if (attachment == null)
attachment = loader.NewRegionAttachment(null, sprite.name, "");
skeletonRenderer.skeleton.FindSlot(slot).Attachment = attachment;
if (!keepLoaderInMemory)
loader = null;
}
}
public class SpriteAttachmentLoader : AttachmentLoader {
//TODO: Memory cleanup functions
//IMPORTANT: Make sure you clear this when you don't need it anymore. Goodluck.
public static Dictionary<int, AtlasRegion> atlasTable = new Dictionary<int, AtlasRegion>();
//Shouldn't need to clear this, should just prevent redoing premultiply alpha pass on packed atlases
public static List<int> premultipliedAtlasIds = new List<int>();
Sprite sprite;
Shader shader;
public SpriteAttachmentLoader (Sprite sprite, Shader shader) {
if (sprite.packed && sprite.packingMode == SpritePackingMode.Tight) {
Debug.LogError("Tight Packer Policy not supported yet!");
return;
}
this.sprite = sprite;
this.shader = shader;
Texture2D tex = sprite.texture;
//premultiply texture if it hasn't been yet
int instanceId = tex.GetInstanceID();
if (!premultipliedAtlasIds.Contains(instanceId)) {
try {
var colors = tex.GetPixels();
Color c;
float a;
for (int i = 0; i < colors.Length; i++) {
c = colors[i];
a = c.a;
c.r *= a;
c.g *= a;
c.b *= a;
colors[i] = c;
}
tex.SetPixels(colors);
tex.Apply();
premultipliedAtlasIds.Add(instanceId);
} catch {
//texture is not readable! Can't pre-multiply it, you're on your own.
}
}
}
public RegionAttachment NewRegionAttachment (Skin skin, string name, string path) {
RegionAttachment attachment = new RegionAttachment(name);
Texture2D tex = sprite.texture;
int instanceId = tex.GetInstanceID();
AtlasRegion atlasRegion;
//check cache first
if (atlasTable.ContainsKey(instanceId)) {
atlasRegion = atlasTable[instanceId];
} else {
//Setup new material
Material mat = new Material(shader);
if (sprite.packed)
mat.name = "Unity Packed Sprite Material";
else
mat.name = sprite.name + " Sprite Material";
mat.mainTexture = tex;
//create faux-region to play nice with SkeletonRenderer
atlasRegion = new AtlasRegion();
AtlasPage page = new AtlasPage();
page.rendererObject = mat;
atlasRegion.page = page;
//cache it
atlasTable[instanceId] = atlasRegion;
}
Rect texRect = sprite.textureRect;
//normalize rect to UV space of packed atlas
texRect.x = Mathf.InverseLerp(0, tex.width, texRect.x);
texRect.y = Mathf.InverseLerp(0, tex.height, texRect.y);
texRect.width = Mathf.InverseLerp(0, tex.width, texRect.width);
texRect.height = Mathf.InverseLerp(0, tex.height, texRect.height);
Bounds bounds = sprite.bounds;
Vector3 size = bounds.size;
//TODO: make sure this rotation thing actually works
bool rotated = false;
if (sprite.packed)
rotated = sprite.packingRotation == SpritePackingRotation.Any;
//do some math and assign UVs and sizes
attachment.SetUVs(texRect.xMin, texRect.yMax, texRect.xMax, texRect.yMin, rotated);
attachment.RendererObject = atlasRegion;
attachment.SetColor(Color.white);
attachment.ScaleX = 1;
attachment.ScaleY = 1;
attachment.RegionOffsetX = sprite.rect.width * (0.5f - Mathf.InverseLerp(bounds.min.x, bounds.max.x, 0)) / sprite.pixelsPerUnit;
attachment.RegionOffsetY = sprite.rect.height * (0.5f - Mathf.InverseLerp(bounds.min.y, bounds.max.y, 0)) / sprite.pixelsPerUnit;
attachment.Width = size.x;
attachment.Height = size.y;
attachment.RegionWidth = size.x;
attachment.RegionHeight = size.y;
attachment.RegionOriginalWidth = size.x;
attachment.RegionOriginalHeight = size.y;
attachment.UpdateOffset();
return attachment;
}
public MeshAttachment NewMeshAttachment (Skin skin, string name, string path) {
//TODO: Unity 5 only
throw new System.NotImplementedException();
}
public WeightedMeshAttachment NewWeightedMeshAttachment(Skin skin, string name, string path) {
throw new System.NotImplementedException();
}
public BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, string name) {
throw new System.NotImplementedException();
}
}
public static class SpriteAttachmentExtensions {
public static Attachment AttachUnitySprite (this Skeleton skeleton, string slotName, Sprite sprite, string shaderName = "Spine/Skeleton") {
var att = sprite.ToRegionAttachment(shaderName);
skeleton.FindSlot(slotName).Attachment = att;
return att;
}
public static Attachment AddUnitySprite (this SkeletonData skeletonData, string slotName, Sprite sprite, string skinName = "", string shaderName = "Spine/Skeleton") {
var att = sprite.ToRegionAttachment(shaderName);
var slotIndex = skeletonData.FindSlotIndex(slotName);
Skin skin = skeletonData.defaultSkin;
if (skinName != "")
skin = skeletonData.FindSkin(skinName);
skin.AddAttachment(slotIndex, att.Name, att);
return att;
}
public static RegionAttachment ToRegionAttachment (this Sprite sprite, string shaderName = "Spine/Skeleton") {
var loader = new SpriteAttachmentLoader(sprite, Shader.Find(shaderName));
var att = loader.NewRegionAttachment(null, sprite.name, "");
loader = null;
return att;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
namespace tk2dEditor.TileMap
{
public class Importer
{
// Dynamically resolved types
System.Type zlibType = null;
// Format enums
public enum Format
{
TMX,
};
// Local tile map copy
int width, height;
class LayerProxy
{
public string name;
public uint[] tiles;
};
List<LayerProxy> layers = new List<LayerProxy>();
// Constructor - attempt resolving types
private Importer()
{
// Find all required modules
foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies())
{
try
{
foreach (var module in assembly.GetModules())
{
if (module.ScopeName == "zlib.net.dll")
{
zlibType = module.GetType("zlib.ZOutputStream");
break;
}
}
}
catch { }
}
}
// Xml helpers
static int ReadIntAttribute(XmlNode node, string attribute) { return int.Parse(node.Attributes[attribute].Value, System.Globalization.NumberFormatInfo.InvariantInfo); }
const string FormatErrorString = "Unsupported format error.\n" +
"Please ensure layer data is stored as xml, base64(zlib) * or base64(uncompressed) in TileD preferences.\n\n" +
"* - Preferred format";
// Import TMX
string ImportTMX(string path)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
var mapNode = doc.SelectSingleNode("/map");
width = ReadIntAttribute(mapNode, "width");
height = ReadIntAttribute(mapNode, "height");
// var tileSetNodes = mapNode.SelectNodes("tileset");
// if (tileSetNodes.Count > 1) return "Only one tileset supported"; // just ignore this
var layersNodes = mapNode.SelectNodes("layer");
foreach (XmlNode layerNode in layersNodes)
{
string name = layerNode.Attributes["name"].Value;
int layerWidth = ReadIntAttribute(layerNode, "width");
int layerHeight = ReadIntAttribute(layerNode, "height");
if (layerHeight != height || layerWidth != width) return "Layer \"" + name + "\" has invalid dimensions";
var dataNode = layerNode.SelectSingleNode("data");
string encoding = (dataNode.Attributes["encoding"] != null)?dataNode.Attributes["encoding"].Value:"";
string compression = (dataNode.Attributes["compression"] != null)?dataNode.Attributes["compression"].Value:"";
uint[] data = null;
if (encoding == "base64")
{
if (compression == "zlib")
{
data = BytesToInts(ZlibInflate(System.Convert.FromBase64String(dataNode.InnerText)));
}
else if (compression == "")
{
data = BytesToInts(System.Convert.FromBase64String(dataNode.InnerText));
}
else return FormatErrorString;
}
else if (encoding == "")
{
List<uint> values = new List<uint>();
var tileNodes = dataNode.SelectNodes("tile");
foreach (XmlNode tileNode in tileNodes)
values.Add( uint.Parse(tileNode.Attributes["gid"].Value, System.Globalization.NumberFormatInfo.InvariantInfo) );
data = values.ToArray();
}
else
{
return FormatErrorString;
}
if (data != null)
{
var layerProxy = new LayerProxy();
layerProxy.name = name;
layerProxy.tiles = data;
layers.Add(layerProxy);
}
}
}
catch (System.Exception e) { return e.ToString(); }
return "";
}
// Zlib helper
byte[] ZlibInflate(byte[] data)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
var obj = System.Activator.CreateInstance(zlibType, ms);
var invokeFlags = System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod;
zlibType.InvokeMember("Write",
invokeFlags,
null,
obj,
new object[] { data, 0, data.Length });
byte[] bytes = ms.ToArray();
zlibType.InvokeMember("Close", invokeFlags, null, obj, null);
return bytes;
}
// Read little endian ints from byte array
uint[] BytesToInts(byte[] bytes)
{
uint[] ints = new uint[bytes.Length / 4];
for (int i = 0, j = 0; i < ints.Length; ++i, j += 4)
{
ints[i] = (uint)bytes[j] | ((uint)bytes[j+1] << 8) | ((uint)bytes[j+2] << 16) | ((uint)bytes[j+3] << 24);
}
return ints;
}
void PopulateTilemap(tk2dTileMap tileMap)
{
tk2dEditor.TileMap.TileMapUtility.ResizeTileMap(tileMap, width, height, tileMap.partitionSizeX, tileMap.partitionSizeY);
foreach (var layer in layers)
{
int index = tk2dEditor.TileMap.TileMapUtility.FindOrCreateLayer(tileMap, layer.name);
var target = tileMap.Layers[index];
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
int tile = (int)(layer.tiles[y * width + x] & ~(0xE0000000)); // ignore flipping
target.SetTile(x, height - 1 - y, tile - 1);
}
}
target.Optimize();
}
}
#region Static and helper functions
////////////////////////////////////////////////////////////////////////////////////////////////
/// Static and helper functions
////////////////////////////////////////////////////////////////////////////////////////////////
public static bool Import(tk2dTileMap tileMap, Format format)
{
var importer = new Importer();
string ext = "";
switch (format)
{
case Format.TMX:
if (!importer.CheckZlib()) return false;
ext = "tmx";
break;
}
string path = EditorUtility.OpenFilePanel("Import tilemap", "", ext);
if (path.Length == 0)
return false;
string message = "";
switch (format)
{
case Format.TMX: message = importer.ImportTMX(path); break;
}
if (message.Length != 0)
{
EditorUtility.DisplayDialog("Tilemap failed to import", message, "Ok");
return false;
}
importer.PopulateTilemap(tileMap);
return true;
}
// Check and handle required modules
bool CheckZlib()
{
if (zlibType == null)
{
if (EditorUtility.DisplayDialog("Unable to load required module zlib.net",
"You can get zlib.net by clicking \"Download\" button.\n\n" +
"You can also manually get it from http://www.componentace.com/zlib_.NET.htm, and copy the zip file into your Assets folder",
"Download", "Cancel"))
{
Application.OpenURL("http://www.2dtoolkit.com/external/zlib/");
}
return false;
}
return true;
}
#endregion
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright [email protected]
// Copyright iced contributors
#if ENCODER && BLOCK_ENCODER
using System;
using Iced.Intel;
using Xunit;
namespace Iced.UnitTests.Intel.EncoderTests {
public sealed class BlockEncoderTest32_jmp : BlockEncoderTest {
const int bitness = 32;
const ulong origRip = 0x8000;
const ulong newRip = 0x80000000;
[Fact]
void Jmp_fwd() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x09,// jmp short 0000800Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xE9, 0x02, 0x00, 0x00, 0x00,// jmp near ptr 0000800Dh
/*000B*/ 0xB0, 0x02,// mov al,2
/*000D*/ 0x90,// nop
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x06,// jmp short 8000000Ah
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xEB, 0x02,// jmp short 8000000Ah
/*0008*/ 0xB0, 0x02,// mov al,2
/*000A*/ 0x90,// nop
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0004,
0x0006,
0x0008,
0x000A,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, newRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Jmp_bwd() {
var originalData = new byte[] {
/*0000*/ 0x90,// nop
/*0001*/ 0xB0, 0x00,// mov al,0
/*0003*/ 0xEB, 0xFB,// jmp short 00008000h
/*0005*/ 0xB0, 0x01,// mov al,1
/*0007*/ 0xE9, 0xF4, 0xFF, 0xFF, 0xFF,// jmp near ptr 00008000h
/*000C*/ 0xB0, 0x02,// mov al,2
};
var newData = new byte[] {
/*0000*/ 0x90,// nop
/*0001*/ 0xB0, 0x00,// mov al,0
/*0003*/ 0xEB, 0xFB,// jmp short 80000000h
/*0005*/ 0xB0, 0x01,// mov al,1
/*0007*/ 0xEB, 0xF7,// jmp short 80000000h
/*0009*/ 0xB0, 0x02,// mov al,2
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0001,
0x0003,
0x0005,
0x0007,
0x0009,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, newRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Jmp_other_short_os() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0x66, 0xEB, 0x08,// jmp short 800Dh
/*0005*/ 0xB0, 0x01,// mov al,1
/*0007*/ 0x66, 0xE9, 0x02, 0x00,// jmp near ptr 800Dh
/*000B*/ 0xB0, 0x02,// mov al,2
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0x66, 0xEB, 0x09,// jmp short 800Dh
/*0005*/ 0xB0, 0x01,// mov al,1
/*0007*/ 0x66, 0xEB, 0x04,// jmp short 800Dh
/*000A*/ 0xB0, 0x02,// mov al,2
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0005,
0x0007,
0x000A,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, origRip - 1, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Jmp_other_near_os() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0x66, 0xEB, 0x08,// jmp short 800Dh
/*0005*/ 0xB0, 0x01,// mov al,1
/*0007*/ 0x66, 0xE9, 0x02, 0x00,// jmp near ptr 800Dh
/*000B*/ 0xB0, 0x02,// mov al,2
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0x66, 0xE9, 0x07, 0xF0,// jmp near ptr 800Dh
/*0006*/ 0xB0, 0x01,// mov al,1
/*0008*/ 0x66, 0xE9, 0x01, 0xF0,// jmp near ptr 800Dh
/*000C*/ 0xB0, 0x02,// mov al,2
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0006,
0x0008,
0x000C,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, origRip + 0x1000, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Jmp_other_short() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x09,// jmp short 0000800Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xE9, 0x02, 0x00, 0x00, 0x00,// jmp near ptr 0000800Dh
/*000B*/ 0xB0, 0x02,// mov al,2
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x0A,// jmp short 0000800Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xEB, 0x06,// jmp short 0000800Dh
/*0008*/ 0xB0, 0x02,// mov al,2
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0004,
0x0006,
0x0008,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, origRip - 1, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Jmp_other_near() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x09,// jmp short 0000800Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xE9, 0x02, 0x00, 0x00, 0x00,// jmp near ptr 0000800Dh
/*000B*/ 0xB0, 0x02,// mov al,2
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xE9, 0x06, 0xF0, 0xFF, 0xFF,// jmp near ptr 0000800Dh
/*0007*/ 0xB0, 0x01,// mov al,1
/*0009*/ 0xE9, 0xFF, 0xEF, 0xFF, 0xFF,// jmp near ptr 0000800Dh
/*000E*/ 0xB0, 0x02,// mov al,2
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0007,
0x0009,
0x000E,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, origRip + 0x1000, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Jmp_fwd_no_opt() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x09,// jmp short 0000800Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xE9, 0x02, 0x00, 0x00, 0x00,// jmp near ptr 0000800Dh
/*000B*/ 0xB0, 0x02,// mov al,2
/*000D*/ 0x90,// nop
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x09,// jmp short 0000800Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xE9, 0x02, 0x00, 0x00, 0x00,// jmp near ptr 0000800Dh
/*000B*/ 0xB0, 0x02,// mov al,2
/*000D*/ 0x90,// nop
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0004,
0x0006,
0x000B,
0x000D,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.DontFixBranches;
EncodeBase(bitness, origRip, originalData, newRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ClosedXML.Excel
{
internal class XLPageSetup : IXLPageSetup
{
public XLPageSetup(XLPageSetup defaultPageOptions, XLWorksheet worksheet)
{
if (defaultPageOptions != null)
{
PrintAreas = new XLPrintAreas(defaultPageOptions.PrintAreas as XLPrintAreas, worksheet);
CenterHorizontally = defaultPageOptions.CenterHorizontally;
CenterVertically = defaultPageOptions.CenterVertically;
FirstPageNumber = defaultPageOptions.FirstPageNumber;
HorizontalDpi = defaultPageOptions.HorizontalDpi;
PageOrientation = defaultPageOptions.PageOrientation;
VerticalDpi = defaultPageOptions.VerticalDpi;
FirstRowToRepeatAtTop = defaultPageOptions.FirstRowToRepeatAtTop;
LastRowToRepeatAtTop = defaultPageOptions.LastRowToRepeatAtTop;
FirstColumnToRepeatAtLeft = defaultPageOptions.FirstColumnToRepeatAtLeft;
LastColumnToRepeatAtLeft = defaultPageOptions.LastColumnToRepeatAtLeft;
ShowComments = defaultPageOptions.ShowComments;
PaperSize = defaultPageOptions.PaperSize;
_pagesTall = defaultPageOptions.PagesTall;
_pagesWide = defaultPageOptions.PagesWide;
_scale = defaultPageOptions.Scale;
if (defaultPageOptions.Margins != null)
{
Margins = new XLMargins
{
Top = defaultPageOptions.Margins.Top,
Bottom = defaultPageOptions.Margins.Bottom,
Left = defaultPageOptions.Margins.Left,
Right = defaultPageOptions.Margins.Right,
Header = defaultPageOptions.Margins.Header,
Footer = defaultPageOptions.Margins.Footer
};
}
AlignHFWithMargins = defaultPageOptions.AlignHFWithMargins;
ScaleHFWithDocument = defaultPageOptions.ScaleHFWithDocument;
ShowGridlines = defaultPageOptions.ShowGridlines;
ShowRowAndColumnHeadings = defaultPageOptions.ShowRowAndColumnHeadings;
BlackAndWhite = defaultPageOptions.BlackAndWhite;
DraftQuality = defaultPageOptions.DraftQuality;
PageOrder = defaultPageOptions.PageOrder;
ColumnBreaks = defaultPageOptions.ColumnBreaks.ToList();
RowBreaks = defaultPageOptions.RowBreaks.ToList();
Header = new XLHeaderFooter(defaultPageOptions.Header as XLHeaderFooter, worksheet);
Footer = new XLHeaderFooter(defaultPageOptions.Footer as XLHeaderFooter, worksheet);
PrintErrorValue = defaultPageOptions.PrintErrorValue;
}
else
{
PrintAreas = new XLPrintAreas(worksheet);
Header = new XLHeaderFooter(worksheet);
Footer = new XLHeaderFooter(worksheet);
ColumnBreaks = new List<Int32>();
RowBreaks = new List<Int32>();
}
}
public IXLPrintAreas PrintAreas { get; private set; }
public Int32 FirstRowToRepeatAtTop { get; private set; }
public Int32 LastRowToRepeatAtTop { get; private set; }
public void SetRowsToRepeatAtTop(String range)
{
var arrRange = range.Replace("$", "").Split(':');
SetRowsToRepeatAtTop(Int32.Parse(arrRange[0]), Int32.Parse(arrRange[1]));
}
public void SetRowsToRepeatAtTop(Int32 firstRowToRepeatAtTop, Int32 lastRowToRepeatAtTop)
{
if (firstRowToRepeatAtTop <= 0) throw new ArgumentOutOfRangeException("The first row has to be greater than zero.");
if (firstRowToRepeatAtTop > lastRowToRepeatAtTop) throw new ArgumentOutOfRangeException("The first row has to be less than the second row.");
FirstRowToRepeatAtTop = firstRowToRepeatAtTop;
LastRowToRepeatAtTop = lastRowToRepeatAtTop;
}
public Int32 FirstColumnToRepeatAtLeft { get; private set; }
public Int32 LastColumnToRepeatAtLeft { get; private set; }
public void SetColumnsToRepeatAtLeft(String range)
{
var arrRange = range.Replace("$", "").Split(':');
if (Int32.TryParse(arrRange[0], out int iTest))
SetColumnsToRepeatAtLeft(Int32.Parse(arrRange[0]), Int32.Parse(arrRange[1]));
else
SetColumnsToRepeatAtLeft(arrRange[0], arrRange[1]);
}
public void SetColumnsToRepeatAtLeft(String firstColumnToRepeatAtLeft, String lastColumnToRepeatAtLeft)
{
SetColumnsToRepeatAtLeft(XLHelper.GetColumnNumberFromLetter(firstColumnToRepeatAtLeft), XLHelper.GetColumnNumberFromLetter(lastColumnToRepeatAtLeft));
}
public void SetColumnsToRepeatAtLeft(Int32 firstColumnToRepeatAtLeft, Int32 lastColumnToRepeatAtLeft)
{
if (firstColumnToRepeatAtLeft <= 0) throw new ArgumentOutOfRangeException("The first column has to be greater than zero.");
if (firstColumnToRepeatAtLeft > lastColumnToRepeatAtLeft) throw new ArgumentOutOfRangeException("The first column has to be less than the second column.");
FirstColumnToRepeatAtLeft = firstColumnToRepeatAtLeft;
LastColumnToRepeatAtLeft = lastColumnToRepeatAtLeft;
}
public XLPageOrientation PageOrientation { get; set; }
public XLPaperSize PaperSize { get; set; }
public Int32 HorizontalDpi { get; set; }
public Int32 VerticalDpi { get; set; }
public UInt32? FirstPageNumber { get; set; }
public Boolean CenterHorizontally { get; set; }
public Boolean CenterVertically { get; set; }
public XLPrintErrorValues PrintErrorValue { get; set; }
public IXLMargins Margins { get; set; }
private Int32 _pagesWide;
public Int32 PagesWide
{
get
{
return _pagesWide;
}
set
{
_pagesWide = value;
if (_pagesWide >0)
_scale = 0;
}
}
private Int32 _pagesTall;
public Int32 PagesTall
{
get
{
return _pagesTall;
}
set
{
_pagesTall = value;
if (_pagesTall >0)
_scale = 0;
}
}
private Int32 _scale;
public Int32 Scale
{
get
{
return _scale;
}
set
{
_scale = value;
if (_scale <= 0) return;
_pagesTall = 0;
_pagesWide = 0;
}
}
public void AdjustTo(Int32 percentageOfNormalSize)
{
Scale = percentageOfNormalSize;
_pagesWide = 0;
_pagesTall = 0;
}
public void FitToPages(Int32 pagesWide, Int32 pagesTall)
{
_pagesWide = pagesWide;
this._pagesTall = pagesTall;
_scale = 0;
}
public IXLHeaderFooter Header { get; private set; }
public IXLHeaderFooter Footer { get; private set; }
public Boolean ScaleHFWithDocument { get; set; }
public Boolean AlignHFWithMargins { get; set; }
public Boolean ShowGridlines { get; set; }
public Boolean ShowRowAndColumnHeadings { get; set; }
public Boolean BlackAndWhite { get; set; }
public Boolean DraftQuality { get; set; }
public XLPageOrderValues PageOrder { get; set; }
public XLShowCommentsValues ShowComments { get; set; }
public List<Int32> RowBreaks { get; private set; }
public List<Int32> ColumnBreaks { get; private set; }
public void AddHorizontalPageBreak(Int32 row)
{
if (!RowBreaks.Contains(row))
RowBreaks.Add(row);
RowBreaks.Sort();
}
public void AddVerticalPageBreak(Int32 column)
{
if (!ColumnBreaks.Contains(column))
ColumnBreaks.Add(column);
ColumnBreaks.Sort();
}
//public void SetPageBreak(IXLRange range, XLPageBreakLocations breakLocation)
//{
// switch (breakLocation)
// {
// case XLPageBreakLocations.AboveRange: RowBreaks.Add(range.Internals.Worksheet.Row(range.RowNumber)); break;
// case XLPageBreakLocations.BelowRange: RowBreaks.Add(range.Internals.Worksheet.Row(range.RowCount())); break;
// case XLPageBreakLocations.LeftOfRange: ColumnBreaks.Add(range.Internals.Worksheet.Column(range.ColumnNumber)); break;
// case XLPageBreakLocations.RightOfRange: ColumnBreaks.Add(range.Internals.Worksheet.Column(range.ColumnCount())); break;
// default: throw new NotImplementedException();
// }
//}
public IXLPageSetup SetPageOrientation(XLPageOrientation value) { PageOrientation = value; return this; }
public IXLPageSetup SetPagesWide(Int32 value) { PagesWide = value; return this; }
public IXLPageSetup SetPagesTall(Int32 value) { PagesTall = value; return this; }
public IXLPageSetup SetScale(Int32 value) { Scale = value; return this; }
public IXLPageSetup SetHorizontalDpi(Int32 value) { HorizontalDpi = value; return this; }
public IXLPageSetup SetVerticalDpi(Int32 value) { VerticalDpi = value; return this; }
public IXLPageSetup SetFirstPageNumber(UInt32? value) { FirstPageNumber = value; return this; }
public IXLPageSetup SetCenterHorizontally() { CenterHorizontally = true; return this; } public IXLPageSetup SetCenterHorizontally(Boolean value) { CenterHorizontally = value; return this; }
public IXLPageSetup SetCenterVertically() { CenterVertically = true; return this; } public IXLPageSetup SetCenterVertically(Boolean value) { CenterVertically = value; return this; }
public IXLPageSetup SetPaperSize(XLPaperSize value) { PaperSize = value; return this; }
public IXLPageSetup SetScaleHFWithDocument() { ScaleHFWithDocument = true; return this; } public IXLPageSetup SetScaleHFWithDocument(Boolean value) { ScaleHFWithDocument = value; return this; }
public IXLPageSetup SetAlignHFWithMargins() { AlignHFWithMargins = true; return this; } public IXLPageSetup SetAlignHFWithMargins(Boolean value) { AlignHFWithMargins = value; return this; }
public IXLPageSetup SetShowGridlines() { ShowGridlines = true; return this; } public IXLPageSetup SetShowGridlines(Boolean value) { ShowGridlines = value; return this; }
public IXLPageSetup SetShowRowAndColumnHeadings() { ShowRowAndColumnHeadings = true; return this; } public IXLPageSetup SetShowRowAndColumnHeadings(Boolean value) { ShowRowAndColumnHeadings = value; return this; }
public IXLPageSetup SetBlackAndWhite() { BlackAndWhite = true; return this; } public IXLPageSetup SetBlackAndWhite(Boolean value) { BlackAndWhite = value; return this; }
public IXLPageSetup SetDraftQuality() { DraftQuality = true; return this; } public IXLPageSetup SetDraftQuality(Boolean value) { DraftQuality = value; return this; }
public IXLPageSetup SetPageOrder(XLPageOrderValues value) { PageOrder = value; return this; }
public IXLPageSetup SetShowComments(XLShowCommentsValues value) { ShowComments = value; return this; }
public IXLPageSetup SetPrintErrorValue(XLPrintErrorValues value) { PrintErrorValue = value; return this; }
public Boolean DifferentFirstPageOnHF { get; set; }
public IXLPageSetup SetDifferentFirstPageOnHF()
{
return SetDifferentFirstPageOnHF(true);
}
public IXLPageSetup SetDifferentFirstPageOnHF(Boolean value)
{
DifferentFirstPageOnHF = value;
return this;
}
public Boolean DifferentOddEvenPagesOnHF { get; set; }
public IXLPageSetup SetDifferentOddEvenPagesOnHF()
{
return SetDifferentOddEvenPagesOnHF(true);
}
public IXLPageSetup SetDifferentOddEvenPagesOnHF(Boolean value)
{
DifferentOddEvenPagesOnHF = value;
return 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.
//// Copyright (c) Microsoft. All rights reserved.
//// Licensed under the MIT license. See LICENSE file in the project root for full license information.
////#define PERFORMANCE_TESTING
//using System;
//using Xunit;
//using System.Drawing.Graphics;
//using System.IO;
//using System.Diagnostics;
//using System.Reflection;
//using System.Threading.Tasks;
//public partial class GraphicsUnitTests
//{
// /* Functionality test Constants */
// static string SquareCatLogicalName = "SquareCatJpeg";
// static string BlackCatLogicalName = "BlackCatPng";
// static string SoccerCatLogicalName = "SoccerCatJpeg";
// static string CuteCatLogicalName = "CuteCatPng";
// static string JpegCatLogicalName = "JpegCat";
// static string PngCatLogicalName = "PngCat";
// /* Performance Tests Constants */
//#if PERFORMANCE_TESTING
// static StreamWriter streamwriter;
// static Stopwatch stopwatchSingleThread = new Stopwatch();
// static Stopwatch stopwatchMultiThread = new Stopwatch();
// /* Performance Tests Variables */
// static string jpegCatPath = "";
// static string jpegDogPath = "";
// static string pngCatPath = "";
// static string pngDogPath = "";
//#endif
// /*----------------------Functionality Unit Tests------------------------------------*/
// private static void ValidateImagePng(Image img, string embeddedLogicalName)
// {
// Stream toCompare = typeof(GraphicsUnitTests).GetTypeInfo().Assembly.GetManifestResourceStream(embeddedLogicalName);
// Image comparison = Png.Load(toCompare);
// Assert.Equal(comparison.HeightInPixels, img.HeightInPixels);
// Assert.Equal(comparison.WidthInPixels, img.WidthInPixels);
// Assert.Equal(comparison.TrueColor, img.TrueColor);
// }
// private static void ValidateImageJpeg(Image img, string embeddedLogicalName)
// {
// Stream toCompare = typeof(GraphicsUnitTests).GetTypeInfo().Assembly.GetManifestResourceStream(embeddedLogicalName);
// Image comparison = Jpg.Load(toCompare);
// Assert.Equal(comparison.HeightInPixels, img.HeightInPixels);
// Assert.Equal(comparison.WidthInPixels, img.WidthInPixels);
// Assert.Equal(comparison.TrueColor, img.TrueColor);
// }
// private static void ValidateCreatedImage(Image img, int widthToCompare, int heightToCompare)
// {
// Assert.Equal(widthToCompare, img.WidthInPixels);
// Assert.Equal(heightToCompare, img.HeightInPixels);
// }
// private static string ChooseExtension(string filepath)
// {
// if (filepath.Contains("Jpeg"))
// return ".jpg";
// else
// return ".png";
// }
// private static string SaveEmbeddedResourceToFile(string logicalName)
// {
// //get a temp file path
// string toReturn = Path.GetTempFileName();
// toReturn = Path.ChangeExtension(toReturn, ChooseExtension(logicalName));
// //get stream of embedded resoruce
// Stream embeddedResourceStream = typeof(GraphicsUnitTests).GetTypeInfo().Assembly.GetManifestResourceStream(logicalName);
// //write stream to temp file path
// using (FileStream fileStream = new FileStream(toReturn, FileMode.OpenOrCreate))
// {
// embeddedResourceStream.Seek(0, SeekOrigin.Begin);
// embeddedResourceStream.CopyTo(fileStream);
// }
// //return where the resource is saved
// return toReturn;
// }
// /* Tests Create Method */
// [Fact]
// public static void WhenCreatingAnEmptyImageThenValidateAnImage()
// {
// Image emptyTenSquare = Image.Create(10, 10);
// ValidateCreatedImage(emptyTenSquare, 10, 10);
// }
// [Fact]
// public void WhenCreatingABlankImageWithNegativeHeightThenThrowException()
// {
// Assert.Throws<InvalidOperationException>(() => Image.Create(1, -1));
// }
// [Fact]
// public void WhenCreatingABlankImageWithNegativeWidthThenThrowException()
// {
// Assert.Throws<InvalidOperationException>(() => Image.Create(-1, 1));
// }
// [Fact]
// public void WhenCreatingABlankImageWithNegativeSizesThenThrowException()
// {
// Assert.Throws<InvalidOperationException>(() => Image.Create(-1, -1));
// }
// [Fact]
// public void WhenCreatingABlankImageWithZeroHeightThenThrowException()
// {
// Assert.Throws<InvalidOperationException>(() => Image.Create(1, 0));
// }
// [Fact]
// public void WhenCreatingABlankImageWithZeroWidthThenThrowException()
// {
// Assert.Throws<InvalidOperationException>(() => Image.Create(0, 1));
// }
// [Fact]
// public void WhenCreatingABlankImageWithZeroParametersThenThrowException()
// {
// Assert.Throws<InvalidOperationException>(() => Image.Create(0, 0));
// }
// /* Tests Load(filepath) method */
// [Fact]
// public void WhenCreatingAJpegFromAValidFileGiveAValidImage()
// {
// //save embedded resource to a file
// string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName);
// //read it
// Image newJpeg = Jpg.Load(filepath);
// File.Delete(filepath);
// //validate it
// ValidateImageJpeg(newJpeg, SquareCatLogicalName);
// }
// [Fact]
// public void WhenCreatingAPngFromAValidFileGiveAValidImage()
// {
// //save embedded resource to a file
// string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName);
// //read it
// Image newJpeg = Png.Load(filepath);
// File.Delete(filepath);
// //validate it
// ValidateImagePng(newJpeg, BlackCatLogicalName);
// }
// [Fact]
// public void WhenCreatingAJpegFromAMalformedPathThenThrowException()
// {
// //place holder string to demonstrate what would be the error case
// string temporaryPath = Path.GetTempPath();
// string invalidFilepath = temporaryPath + "\\Hi.jpg";
// Assert.Throws<FileNotFoundException>(() => Jpg.Load(invalidFilepath));
// }
// [Fact]
// public void WhenCreatingAPngFromAMalformedPathThenThrowException()
// {
// string temporaryPath = Path.GetTempPath();
// string invalidFilepath = temporaryPath + "\\Hi.png";
// Assert.Throws<FileNotFoundException>(() => Png.Load(invalidFilepath));
// }
// [Fact]
// public void WhenCreatingAnImageFromAnUnfoundPathThenThrowException()
// {
// string temporaryPath = Path.GetTempPath();
// string invalidFilepath = temporaryPath + "\\Hi.jpg";
// Assert.Throws<FileNotFoundException>(() => Jpg.Load(invalidFilepath));
// }
// [Fact]
// public void WhenCreatingAnImageFromAFileTypeThatIsNotAnImageThenThrowException()
// {
// string temporaryPath = Path.GetTempPath();
// string invalidFilepath = temporaryPath + "text.txt";
// Assert.Throws<FileNotFoundException>(() => Jpg.Load(invalidFilepath));
// }
// /* Tests Load(stream) mehtod*/
// [Fact]
// public void WhenCreatingAJpegFromAValidStreamThenWriteAValidImageToFile()
// {
// string filepath = SaveEmbeddedResourceToFile(SoccerCatLogicalName);
// using (FileStream filestream = new FileStream(filepath, FileMode.Open))
// {
// Image fromStream = Jpg.Load(filestream);
// ValidateImageJpeg(fromStream, SoccerCatLogicalName);
// }
// File.Delete(filepath);
// }
// [Fact]
// public void WhenCreatingAPngFromAValidStreamThenWriteAValidImageToFile()
// {
// string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName);
// using (FileStream filestream = new FileStream(filepath, FileMode.Open))
// {
// Image fromStream = Png.Load(filestream);
// ValidateImagePng(fromStream, CuteCatLogicalName);
// }
// File.Delete(filepath);
// }
// [Fact]
// public void WhenCreatingAnImageFromAnInvalidStreamThenThrowException()
// {
// Stream stream = null;
// Assert.Throws<InvalidOperationException>(() => Png.Load(stream));
// }
// /* Test Resize */
// [Fact]
// public void WhenResizingEmptyImageDownThenGiveAValidatedResizedImage()
// {
// Image emptyResizeSquare = Image.Create(100, 100);
// emptyResizeSquare = emptyResizeSquare.Resize(10, 10);
// ValidateCreatedImage(emptyResizeSquare, 10, 10);
// }
// [Fact]
// public void WhenResizingEmptyImageUpThenGiveAValidatedResizedImage()
// {
// Image emptyResizeSquare = Image.Create(100, 100);
// emptyResizeSquare = emptyResizeSquare.Resize(200, 200);
// ValidateCreatedImage(emptyResizeSquare, 200, 200);
// }
// [Fact]
// public void WhenResizingJpegLoadedFromFileThenGiveAValidatedResizedImage()
// {
// //what to do? Have embedded resource stream of expected result?
// string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName);
// Image fromFileResizeSquare = Jpg.Load(filepath);
// fromFileResizeSquare = fromFileResizeSquare.Resize(200, 200);
// ValidateCreatedImage(fromFileResizeSquare, 200, 200);
// File.Delete(filepath);
// }
// [Fact]
// public void WhenResizingPngLoadedFromFileThenGiveAValidatedResizedImage()
// {
// //what to do? Have embedded resource stream of expected result?
// string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName);
// Image fromFileResizeSquare = Png.Load(filepath);
// fromFileResizeSquare = fromFileResizeSquare.Resize(400, 400);
// ValidateCreatedImage(fromFileResizeSquare, 400, 400);
// File.Delete(filepath);
// }
// [Fact]
// public void WhenResizingJpegLoadedFromStreamThenGiveAValidatedResizedImage()
// {
// string filepath = SaveEmbeddedResourceToFile(SoccerCatLogicalName);
// using (FileStream filestream = new FileStream(filepath, FileMode.Open))
// {
// Image fromStream = Jpg.Load(filestream);
// fromStream = fromStream.Resize(400, 400);
// ValidateCreatedImage(fromStream, 400, 400);
// }
// File.Delete(filepath);
// }
// [Fact]
// public void WhenResizingPngLoadedFromStreamThenGiveAValidatedResizedImage()
// {
// string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName);
// using (FileStream filestream = new FileStream(filepath, FileMode.Open))
// {
// Image fromStream = Png.Load(filestream);
// fromStream = fromStream.Resize(400, 400);
// ValidateCreatedImage(fromStream, 400, 400);
// }
// File.Delete(filepath);
// }
// /* Testing Resize parameters */
// [Fact]
// public void WhenResizingImageGivenNegativeHeightThenThrowException()
// {
// Image img = Image.Create(1, 1);
// Assert.Throws<InvalidOperationException>(() => img.Resize(-1, 1));
// }
// [Fact]
// public void WhenResizingImageGivenNegativeWidthThenThrowException()
// {
// Image img = Image.Create(1, 1);
// Assert.Throws<InvalidOperationException>(() => img.Resize(1, -1));
// }
// [Fact]
// public void WhenResizingImageGivenNegativeSizesThenThrowException()
// {
// Image img = Image.Create(1, 1);
// Assert.Throws<InvalidOperationException>(() => img.Resize(-1, -1));
// }
// [Fact]
// public void WhenResizingImageGivenZeroHeightThenThrowException()
// {
// Image img = Image.Create(1, 1);
// Assert.Throws<InvalidOperationException>(() => img.Resize(0, 1));
// }
// [Fact]
// public void WhenResizingImageGivenZeroWidthThenThrowException()
// {
// Image img = Image.Create(1, 1);
// Assert.Throws<InvalidOperationException>(() => img.Resize(1, 0));
// }
// [Fact]
// public void WhenResizingImageGivenZeroSizesThenThrowException()
// {
// Image img = Image.Create(1, 1);
// Assert.Throws<InvalidOperationException>(() => img.Resize(0, 0));
// }
// /* Test Write */
// [Fact]
// public void WhenWritingABlankCreatedJpegToAValidFileWriteAValidFile()
// {
// Image emptyImage = Image.Create(10, 10);
// ValidateCreatedImage(emptyImage, 10, 10);
// string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".jpg");
// Jpg.Write(emptyImage, tempFilePath);
// File.Delete(tempFilePath);
// }
// [Fact]
// public void WhenWritingABlankCreatedPngToAValidFileWriteAValidFile()
// {
// Image emptyImage = Image.Create(10, 10);
// ValidateCreatedImage(emptyImage, 10, 10);
// string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".png");
// Png.Write(emptyImage, tempFilePath);
// File.Delete(tempFilePath);
// }
// [Fact]
// public void WhenWritingAJpegCreatedFromFileToAValidFileWriteAValidImage()
// {
// string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName);
// Image fromFile = Jpg.Load(filepath);
// ValidateImageJpeg(fromFile, SquareCatLogicalName);
// string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".jpg");
// Png.Write(fromFile, tempFilePath);
// File.Delete(filepath);
// File.Delete(tempFilePath);
// }
// [Fact]
// public void WhenWritingAPngCreatedFromFileToAValidFileWriteAValidImage()
// {
// string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName);
// Image fromFile = Png.Load(filepath);
// ValidateImagePng(fromFile, BlackCatLogicalName);
// string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".png");
// Png.Write(fromFile, tempFilePath);
// File.Delete(filepath);
// File.Delete(tempFilePath);
// }
// [Fact]
// public void WhenWritingAPngMadeTransparentToAValidFileWriteAValidImage()
// {
// string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName);
// Image img = Png.Load(filepath);
// ValidateImagePng(img, BlackCatLogicalName);
// img.SetAlphaPercentage(.2);
// ValidateImagePng(img, BlackCatLogicalName);
// string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".png");
// Png.Write(img, tempFilePath);
// File.Delete(filepath);
// File.Delete(tempFilePath);
// }
// [Fact]
// public void WhenWritingATransparentResizedPngToAValidFileWriteAValidImage()
// {
// string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName);
// Image img = Png.Load(filepath);
// ValidateImagePng(img, BlackCatLogicalName);
// img.SetAlphaPercentage(.2);
// img = img.Resize(400, 400);
// ValidateCreatedImage(img, 400, 400);
// string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".png");
// Png.Write(img, tempFilePath);
// File.Delete(filepath);
// File.Delete(tempFilePath);
// }
// [Fact]
// public void WhenWritingAResizedTransparentPngToAValidFileWriteAValidImage()
// {
// string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName);
// Image img = Png.Load(filepath);
// ValidateImagePng(img, BlackCatLogicalName);
// img = img.Resize(400, 400);
// ValidateCreatedImage(img, 400, 400);
// img.SetAlphaPercentage(.2);
// string tempFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".png");
// Png.Write(img, tempFilePath);
// File.Delete(filepath);
// File.Delete(tempFilePath);
// }
// /* Tests Writing to a Stream*/
// [Fact]
// public void WhenWritingABlankCreatedJpegToAValidStreamWriteAValidStream()
// {
// Image img = Image.Create(100, 100);
// using (MemoryStream stream = new MemoryStream())
// {
// Jpg.Write(img, stream);
// stream.Position = 0;
// Image img2 = Jpg.Load(stream);
// ValidateCreatedImage(img2, 100, 100);
// }
// }
// [Fact]
// public void WhenWritingABlankCreatedPngToAValidStreamWriteAValidStream()
// {
// Image img = Image.Create(100, 100);
// using (MemoryStream stream = new MemoryStream())
// {
// Png.Write(img, stream);
// stream.Position = 0;
// Image img2 = Png.Load(stream);
// ValidateCreatedImage(img2, 100, 100);
// }
// }
// [Fact]
// public void WhenWritingAJpegFromFileToAValidStreamWriteAValidImage()
// {
// string filepath = SaveEmbeddedResourceToFile(SoccerCatLogicalName);
// Image img = Jpg.Load(filepath);
// using (MemoryStream stream = new MemoryStream())
// {
// Jpg.Write(img, stream);
// stream.Position = 0;
// Image img2 = Jpg.Load(stream);
// ValidateImageJpeg(img2, SoccerCatLogicalName);
// }
// File.Delete(filepath);
// }
// [Fact]
// public void WhenWritingAPngCreatedFromFileToAValidStreamWriteAValidImage()
// {
// string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName);
// Image img = Png.Load(filepath);
// using (MemoryStream stream = new MemoryStream())
// {
// Png.Write(img, stream);
// stream.Position = 0;
// Image img2 = Png.Load(stream);
// ValidateImagePng(img2, CuteCatLogicalName);
// }
// File.Delete(filepath);
// }
// [Fact]
// public void WhenWritingAResizedJpegToAValidStreamWriteAValidImage()
// {
// string filepath = SaveEmbeddedResourceToFile(SoccerCatLogicalName);
// Image img = Jpg.Load(filepath);
// using (MemoryStream stream = new MemoryStream())
// {
// img = img.Resize(40, 40);
// ValidateCreatedImage(img, 40, 40);
// Jpg.Write(img, stream);
// stream.Position = 0;
// Image img2 = Jpg.Load(stream);
// ValidateCreatedImage(img, 40, 40);
// }
// File.Delete(filepath);
// }
// [Fact]
// public void WhenWritingAResizedPngToAValidStreamWriteAValidImage()
// {
// string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName);
// Image img = Png.Load(filepath);
// using (MemoryStream stream = new MemoryStream())
// {
// img = img.Resize(40, 40);
// ValidateCreatedImage(img, 40, 40);
// Png.Write(img, stream);
// stream.Position = 0;
// Image img2 = Png.Load(stream);
// ValidateCreatedImage(img, 40, 40);
// }
// File.Delete(filepath);
// }
// [Fact]
// public void WhenWritingAPngMadeTransparentToAValidStreamWriteAValidImage()
// {
// string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName);
// Image img = Png.Load(filepath);
// using (MemoryStream stream = new MemoryStream())
// {
// img.SetAlphaPercentage(.2);
// ValidateImagePng(img, CuteCatLogicalName);
// Png.Write(img, stream);
// stream.Position = 0;
// Image img2 = Png.Load(stream);
// ValidateImagePng(img2, CuteCatLogicalName);
// }
// File.Delete(filepath);
// }
// [Fact]
// public void WhenWritingATransparentResizedPngToAValidStreamWriteAValidImage()
// {
// string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName);
// Image img = Png.Load(filepath);
// using (MemoryStream stream = new MemoryStream())
// {
// img.SetAlphaPercentage(.2);
// img = img.Resize(400, 400);
// ValidateCreatedImage(img, 400, 400);
// Png.Write(img, stream);
// stream.Position = 0;
// Image img2 = Png.Load(stream);
// ValidateCreatedImage(img2, 400, 400);
// }
// File.Delete(filepath);
// }
// [Fact]
// public void WhenWritingAResizedTransparentPngToAValidStreamWriteAValidImage()
// {
// string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName);
// Image img = Png.Load(filepath);
// ValidateImagePng(img, CuteCatLogicalName);
// img = img.Resize(400, 400);
// ValidateCreatedImage(img, 400, 400);
// img.SetAlphaPercentage(.2);
// File.Delete(filepath);
// }
// /* Test Draw */
// [Fact]
// public void WhenDrawingTwoImagesWriteACorrectResult()
// {
// //open yellow cat image
// string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName);
// Image yellowCat = Jpg.Load(filepath);
// ValidateImageJpeg(yellowCat, SquareCatLogicalName);
// //open black cat image
// string filepath2 = SaveEmbeddedResourceToFile(BlackCatLogicalName);
// Image blackCat = Jpg.Load(filepath2);
// ValidateImagePng(blackCat, BlackCatLogicalName);
// //draw
// yellowCat.Draw(blackCat, 0, 0);
// ValidateImageJpeg(yellowCat, SquareCatLogicalName);
// File.Delete(filepath);
// File.Delete(filepath2);
// }
// /* Test SetTransparency */
// [Fact]
// public void WhenSettingTheTransparencyOfAnImageWriteAnImageWithChangedTransparency()
// {
// //open black cat image
// string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName);
// Image blackCat0 = Jpg.Load(filepath);
// ValidateImagePng(blackCat0, BlackCatLogicalName);
// blackCat0.SetAlphaPercentage(0);
// ValidateImagePng(blackCat0, BlackCatLogicalName);
// Image blackCat1 = Jpg.Load(filepath);
// ValidateImagePng(blackCat1, BlackCatLogicalName);
// blackCat0.SetAlphaPercentage(0.5);
// ValidateImagePng(blackCat1, BlackCatLogicalName);
// Image blackCat2 = Jpg.Load(filepath);
// ValidateImagePng(blackCat2, BlackCatLogicalName);
// blackCat0.SetAlphaPercentage(1);
// ValidateImagePng(blackCat2, BlackCatLogicalName);
// File.Delete(filepath);
// }
// /* Test Draw and Set Transparency */
// [Fact]
// public void WhenDrawingAnImageWithTransparencyChangedGiveACorrectWrittenFile()
// {
// //black cat load
// string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName);
// Image blackCat = Jpg.Load(filepath);
// ValidateImagePng(blackCat, BlackCatLogicalName);
// blackCat.SetAlphaPercentage(0.5);
// //yellow cat load
// string filepath2 = SaveEmbeddedResourceToFile(SquareCatLogicalName);
// Image yellowCat = Jpg.Load(filepath2);
// ValidateImageJpeg(yellowCat, SquareCatLogicalName);
// yellowCat.Draw(blackCat, 0, 0);
// ValidateImageJpeg(yellowCat, SquareCatLogicalName);
// }
// [Fact]
// public static void WhenAddingAGreyScaleFilterToAJpegGiveAValidGreyScaledImage()
// {
// string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName);
// Image img1 = Jpg.Load(filepath);
// img1.ApplyMatrixMultiplier(ImageExtensions.GreyScaleMatrix);
// ValidateImageJpeg(img1, SquareCatLogicalName);
// Jpg.Write(img1, Path.GetTempPath() + "GreyscaleCat.jpg");
// }
// [Fact]
// public static void WhenAddingAGreyScaleFilterToAPngGiveAValidGreyScaledImage()
// {
// string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName);
// Image img1 = Png.Load(filepath);
// img1.ApplyMatrixMultiplier(ImageExtensions.GreyScaleMatrix);
// ValidateImagePng(img1, BlackCatLogicalName);
// Png.Write(img1, Path.GetTempPath() + "GreyscaleCat.png");
// }
// [Fact]
// public static void WhenAddingASepiaFilterToAJpegGiveAValidGreyScaledImage()
// {
// string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName);
// Image img1 = Jpg.Load(filepath);
// img1.ApplyMatrixMultiplier(ImageExtensions.SepiaMatrix);
// ValidateImageJpeg(img1, SquareCatLogicalName);
// Jpg.Write(img1, Path.GetTempPath() + "SepiaCat.jpg");
// }
// [Fact]
// public static void WhenAddingASepiaFilterToAPngGiveAValidGreyScaledImage()
// {
// string filepath = SaveEmbeddedResourceToFile(CuteCatLogicalName);
// Image img1 = Png.Load(filepath);
// img1.ApplyMatrixMultiplier(ImageExtensions.SepiaMatrix);
// ValidateImagePng(img1, CuteCatLogicalName);
// Png.Write(img1, Path.GetTempPath() + "SepiaCat.png");
// }
// [Fact]
// public static void WhenAddingANegativeFilterToAJpegGiveAValidGreyScaledImage()
// {
// string filepath = SaveEmbeddedResourceToFile(SquareCatLogicalName);
// Image img1 = Jpg.Load(filepath);
// img1.ApplyMatrixMultiplier(ImageExtensions.NegativeMatrix);
// ValidateImageJpeg(img1, SquareCatLogicalName);
// Jpg.Write(img1, Path.GetTempPath() + "NegativeCat.jpg");
// }
// [Fact]
// public static void WhenAddingANegativeFilterToAPngGiveAValidGreyScaledImage()
// {
// string filepath = SaveEmbeddedResourceToFile(BlackCatLogicalName);
// Image img1 = Png.Load(filepath);
// img1.ApplyMatrixMultiplier(ImageExtensions.NegativeMatrix);
// ValidateImagePng(img1, BlackCatLogicalName);
// Png.Write(img1, Path.GetTempPath() + "NegativeCat.png");
// }
// /*Tests CircleCrop*/
// //Tests filpath
// //Tests jpg
// [Fact]
// public void WhenCropingAnJpgImageFromFileGiveACorrectCroppedImage()
// {
// //checking with cat image
// string filepath = SaveEmbeddedResourceToFile(JpegCatLogicalName);
// Image avatarImage = Jpg.Load(filepath);
// Image newImage = avatarImage.CircleCrop(0, 0);
// }
// //Tests png
// [Fact]
// public void WhenCropingAnPngImageFromFileGiveACorrectCroppedImage()
// {
// //checking with cat image
// string filepath = SaveEmbeddedResourceToFile(PngCatLogicalName);
// Image avatarImage = Png.Load(filepath);
// Image newImage = avatarImage.CircleCrop(0, 0);
// }
// //Tests stream
// //Tests jpg
// [Fact]
// public void WhenCropingAnJpgImageFromFileStreamACorrectCroppedImage()
// {
// string filepath = SaveEmbeddedResourceToFile(JpegCatLogicalName);
// using (FileStream filestream = new FileStream(filepath, FileMode.Open))
// {
// Image avatarImage = Jpg.Load(filestream);
// Image newImage = avatarImage.CircleCrop(0, 0);
// }
// }
// //Tests png
// [Fact]
// public void WhenCropingAnPngImageFromFileStreamACorrectCroppedImage()
// {
// string filepath = SaveEmbeddedResourceToFile(PngCatLogicalName);
// using (FileStream filestream = new FileStream(filepath, FileMode.Open))
// {
// Image avatarImage = Png.Load(filestream);
// Image newImage = avatarImage.CircleCrop(0, 0);
// }
// }
// /* ------------------Performance Tests-------------------------*/
//#if PERFORMANCE_TESTING
// [Fact]
// public static void RunAllPerfTests()
// {
// string filepath = Path.GetTempPath() + "Trial1Results.txt";
// if (File.Exists(filepath)) File.Delete(filepath);
// FileStream fstream = new FileStream(filepath, FileMode.OpenOrCreate);
// streamwriter = new StreamWriter(fstream);
// //set temppaths of files perf test images
// SetTempPathsOfPerfTestFiles();
// runTests(1);
// runTests(10);
// runTests(100);
// runTests(1000);
// runTests(5000);
// streamwriter.Dispose();
// fstream.Dispose();
// //delete perf test images files
// DeletePerfTestFileConstants();
// }
// public static void runTests(int numRuns)
// {
// WriteTestHeader(numRuns);
// //LoadFileJpg
// WriteCurrentTest("LoadFileJpeg", numRuns);
// LoadFileJpegPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "LoadFileJpeg");
// //LoadFilePng
// WriteCurrentTest("LoadFilePng", numRuns);
// LoadFilePngPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "LoadFilePng");
// //WriteJpg
// WriteCurrentTest("WriteJpeg", numRuns);
// WriteFileJpegPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "WriteFileJpeg");
// //WritePng
// WriteCurrentTest("WritePng", numRuns);
// WriteFilePngPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "WriteFilePng");
// //ResizeJpg
// WriteCurrentTest("ResizeJpeg", numRuns);
// ResizeJpegPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "ResizeJpeg");
// //resize png
// WriteCurrentTest("ResizePng", numRuns);
// ResizePngPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "ResizePng");
// //ChangeAlphaJpg
// WriteCurrentTest("ChangeAlphaJpeg", numRuns);
// ChangeAlphaJpegPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "ChangeAlphaJpeg");
// //ChangeAlphaPng
// WriteCurrentTest("ChangeAlphaPng", numRuns);
// ChangeAlphaPngPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "ChangeAlphaPng");
// //DrawJpgOverJpg
// WriteCurrentTest("DrawJpegOverJpeg", numRuns);
// DrawJpegOverJpegPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "DrawJpegOverJpeg");
// //DrawPngOverPng
// WriteCurrentTest("DrawPngOverPng", numRuns);
// DrawPngOverPngPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "DrawPngOverPng");
// //DrawJpgOverPng
// WriteCurrentTest("DrawJpegOverPng", numRuns);
// DrawJpegOverPngPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "DrawJpegOverPng");
// //DrawPngOverJpg
// WriteCurrentTest("DrawPngOverJpeg", numRuns);
// DrawPngOverJpegPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "DrawPngOverJpeg");
// //LoadStreamJpg
// WriteCurrentTest("LoadStreamJpeg", numRuns);
// LoadStreamJpegPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "LoadStreamJpeg");
// //LoadStreamPng
// WriteCurrentTest("LoadStreamPng", numRuns);
// LoadStreamPngPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "LoadStreamPng");
// //WriteJpg
// WriteCurrentTest("WriteJpeg", numRuns);
// WriteStreamJpegPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "WriteStreamJpeg");
// //WritePng
// WriteCurrentTest("WritePng", numRuns);
// WriteStreamPngPerfTest(numRuns);
// WriteStopWatch(stopwatchSingleThread, "WriteStreamPng");
// }
// [Fact]
// public static void SetUpAllPerfTestsWithThreads()
// {
// int numOfTasks = 4;
// string filepath = Path.GetTempPath() + "Trial2Results.txt";
// if (File.Exists(filepath)) File.Delete(filepath);
// //set temp paths of files perf test images
// SetTempPathsOfPerfTestFiles();
// FileStream fstream = new FileStream(filepath, FileMode.OpenOrCreate);
// streamwriter = new StreamWriter(fstream);
// WriteTestHeader(1);
// RunAllPerfTestsWithThreads(numOfTasks, 1);
// WriteTestHeader(10);
// RunAllPerfTestsWithThreads(numOfTasks, 10);
// WriteTestHeader(100);
// RunAllPerfTestsWithThreads(numOfTasks, 100);
// WriteTestHeader(1000);
// RunAllPerfTestsWithThreads(numOfTasks, 1000);
// WriteTestHeader(5000);
// RunAllPerfTestsWithThreads(numOfTasks, 5000);
// streamwriter.Dispose();
// fstream.Dispose();
// //delete temp perf tests images files
// DeletePerfTestFileConstants();
// }
// private static void RunAllPerfTestsWithThreads(int numOfTasks, int numRuns)
// {
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "LoadFileJpegPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "LoadFilePngPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "WriteJpegPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "WritePngPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "ResizeJpegPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "ResizePngPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "ChangeAlphaJpegPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "ChangeAlphaPngPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "DrawJpegOverJpegPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "DrawPngOverPngPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "DrawJpegOverPngPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "DrawPngOverJpegPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "LoadStreamJpegPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "LoadStreamPngPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "WriteJpegPerfTest");
// RunOneFuntionWithMultipleTasks(numOfTasks, numRuns, "WritePngPerfTest");
// }
// private static void RunOneFuntionWithMultipleTasks(int numOfTasks, int numRuns, string functionToRun)
// {
// WriteCurrentTest(functionToRun, numRuns);
// Task[] tasks = new Task[numOfTasks];
// stopwatchMultiThread.Start();
// for (int i = 0; i < numOfTasks; i++)
// {
// switch (functionToRun)
// {
// case "LoadFileJpegPerfTest":
// tasks[i] = Task.Factory.StartNew(() => LoadFileJpegPerfTest(numRuns / numOfTasks));
// break;
// case "LoadFilePngPerfTest":
// tasks[i] = Task.Factory.StartNew(() => LoadFilePngPerfTest(numRuns / numOfTasks));
// break;
// case "WriteFileJpegPerfTest":
// tasks[i] = Task.Factory.StartNew(() => WriteFileJpegPerfTest(numRuns / numOfTasks));
// break;
// case "WriteFilePngPerfTest":
// tasks[i] = Task.Factory.StartNew(() => WriteFilePngPerfTest(numRuns / numOfTasks));
// break;
// case "ResizeJpegPerfTest":
// tasks[i] = Task.Factory.StartNew(() => ResizeJpegPerfTest(numRuns / numOfTasks));
// break;
// case "ResizePngPerfTest":
// tasks[i] = Task.Factory.StartNew(() => ResizePngPerfTest(numRuns / numOfTasks));
// break;
// case "ChangeAlphaJpegPerfTest":
// tasks[i] = Task.Factory.StartNew(() => ChangeAlphaJpegPerfTest(numRuns / numOfTasks));
// break;
// case "ChangeAlphaPngPerfTest":
// tasks[i] = Task.Factory.StartNew(() => ChangeAlphaPngPerfTest(numRuns / numOfTasks));
// break;
// case "DrawJpegOverJpegPerfTest":
// tasks[i] = Task.Factory.StartNew(() => DrawJpegOverJpegPerfTest(numRuns / numOfTasks));
// break;
// case "DrawPngOverPngPerfTest":
// tasks[i] = Task.Factory.StartNew(() => DrawPngOverPngPerfTest(numRuns / numOfTasks));
// break;
// case "DrawJpegOverPngPerfTest":
// tasks[i] = Task.Factory.StartNew(() => DrawJpegOverPngPerfTest(numRuns / numOfTasks));
// break;
// case "DrawPngOverJpegPerfTest":
// tasks[i] = Task.Factory.StartNew(() => DrawPngOverJpegPerfTest(numRuns / numOfTasks));
// break;
// case "LoadStreamJpegPerfTest":
// tasks[i] = Task.Factory.StartNew(() => LoadStreamJpegPerfTest(numRuns / numOfTasks));
// break;
// case "LoadStreamPngPerfTest":
// tasks[i] = Task.Factory.StartNew(() => LoadStreamPngPerfTest(numRuns / numOfTasks));
// break;
// case "WriteStreamJpegPerfTest":
// tasks[i] = Task.Factory.StartNew(() => WriteStreamJpegPerfTest(numRuns / numOfTasks));
// break;
// case "WriteStreamPngPerfTest":
// tasks[i] = Task.Factory.StartNew(() => WriteStreamPngPerfTest(numRuns / numOfTasks));
// break;
// default:
// throw new NotSupportedException("A task was created but not given a proper task. Check the code/swithc statement.");
// }
// }
// Task.WaitAll(tasks);
// stopwatchMultiThread.Stop();
// WriteStopWatch(stopwatchMultiThread, functionToRun);
// //delete dump dir
// }
// private static void SetTempPathsOfPerfTestFiles()
// {
// jpegDogPath = SaveEmbeddedResourceToFile("JpegDog");
// jpegCatPath = SaveEmbeddedResourceToFile("JpegCat");
// pngDogPath = SaveEmbeddedResourceToFile("PngDog");
// pngCatPath = SaveEmbeddedResourceToFile("PngCat");
// }
// private static void DeletePerfTestFileConstants()
// {
// File.Delete(jpegDogPath);
// File.Delete(jpegCatPath);
// File.Delete(pngDogPath);
// File.Delete(pngCatPath);
// }
// private static void WriteTestHeader(int numRuns)
// {
// Console.WriteLine("");
// Console.WriteLine("~~~~~~~~~~~ {0} Runs ~~~~~~~~~~~", numRuns);
// Console.WriteLine("");
// streamwriter.WriteLine("");
// streamwriter.WriteLine("~~~~~~~~~~~ {0} Runs ~~~~~~~~~~~", numRuns);
// streamwriter.WriteLine("");
// }
// private static void WriteCurrentTest(string currentTest, int numRuns)
// {
// Console.WriteLine(currentTest + "{0}", numRuns);
// streamwriter.WriteLine(currentTest + "{0}", numRuns);
// }
// private static void WriteStopWatch(Stopwatch sw, string currentTest)
// {
// TimeSpan elapsedSecs = (sw.Elapsed);
// Console.WriteLine(elapsedSecs);
// Console.WriteLine("");
// streamwriter.WriteLine("Elapsed time for " + currentTest + ": " + elapsedSecs);
// streamwriter.WriteLine("");
// sw.Reset();
// }
// private static void LoadFileJpegPerfTest(int numRuns)
// {
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("LoadFileJpegTest :" + i);
// stopwatchSingleThread.Start();
// Image img = Jpg.Load(jpegCatPath);
// stopwatchSingleThread.Stop();
// img.ReleaseStruct();
// }
// }
// private static void LoadFilePngPerfTest(int numRuns)
// {
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// {
// Console.WriteLine("LoadFilePngTest :" + i);
// }
// stopwatchSingleThread.Start();
// Image img = Png.Load(pngCatPath);
// stopwatchSingleThread.Stop();
// img.ReleaseStruct();
// }
// }
// //FIX Write
// private static void WriteFileJpegPerfTest(int numRuns)
// {
// //string dir = Path.GetTempPath();
// Image _thisjpgdog = Jpg.Load(jpegDogPath);
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// {
// Console.WriteLine("WriteJpegTest :" + i);
// }
// stopwatchSingleThread.Start();
// Jpg.Write(_thisjpgdog, Path.ChangeExtension(Path.GetTempFileName(), ".jpg"));
// stopwatchSingleThread.Stop();
// }
// _thisjpgdog.ReleaseStruct();
// }
// //fix write
// private static void WriteFilePngPerfTest(int numRuns)
// {
// Image _thispngdog = Png.Load(pngDogPath);
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("WritePngTest :" + i);
// stopwatchSingleThread.Start();
// Png.Write(_thispngdog, Path.ChangeExtension(Path.GetTempFileName(), ".png"));
// stopwatchSingleThread.Stop();
// }
// _thispngdog.ReleaseStruct();
// }
// private static void ResizeJpegPerfTest(int numRuns)
// {
// Image _thisjpgcat = Jpg.Load(jpegCatPath);
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("ResizeJpegTest :" + i);
// stopwatchSingleThread.Start();
// Image img = _thisjpgcat.Resize(100, 100);
// stopwatchSingleThread.Stop();
// img.ReleaseStruct();
// }
// _thisjpgcat.ReleaseStruct();
// }
// private static void ResizePngPerfTest(int numRuns)
// {
// Image _thispngcat = Png.Load(pngCatPath);
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("ResizePngTest :" + i);
// stopwatchSingleThread.Start();
// Image img = _thispngcat.Resize(100, 100);
// stopwatchSingleThread.Stop();
// img.ReleaseStruct();
// }
// _thispngcat.ReleaseStruct();
// }
// private static void ChangeAlphaJpegPerfTest(int numRuns)
// {
// Image _thisjpgcat = Jpg.Load(jpegCatPath);
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("ChangeAlphaJpegTest :" + i);
// stopwatchSingleThread.Start();
// _thisjpgcat.SetAlphaPercentage(0.5);
// stopwatchSingleThread.Stop();
// }
// _thisjpgcat.ReleaseStruct();
// }
// private static void ChangeAlphaPngPerfTest(int numRuns)
// {
// Image _thispngcat = Png.Load(pngCatPath);
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("ChangeAlphaPngTest :" + i);
// stopwatchSingleThread.Start();
// _thispngcat.SetAlphaPercentage(0.5);
// stopwatchSingleThread.Stop();
// }
// _thispngcat.ReleaseStruct();
// }
// private static void DrawJpegOverJpegPerfTest(int numRuns)
// {
// Image _thisjpgcat = Jpg.Load(jpegCatPath);
// Image _thisjpgdog = Jpg.Load(jpegDogPath);
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("DrawJpegOverJpegTest :" + i);
// stopwatchSingleThread.Start();
// _thisjpgdog.Draw(_thisjpgcat, 10, 10);
// stopwatchSingleThread.Stop();
// }
// _thisjpgcat.ReleaseStruct();
// _thisjpgdog.ReleaseStruct();
// }
// private static void DrawPngOverPngPerfTest(int numRuns)
// {
// Image _thispngcat = Png.Load(pngCatPath);
// Image _thispngdog = Png.Load(pngDogPath);
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("DrawPngOverPngTest :" + i);
// stopwatchSingleThread.Start();
// _thispngdog.Draw(_thispngcat, 10, 10);
// stopwatchSingleThread.Stop();
// }
// _thispngcat.ReleaseStruct();
// _thispngdog.ReleaseStruct();
// }
// private static void DrawJpegOverPngPerfTest(int numRuns)
// {
// Image _thisjpgcat = Jpg.Load(jpegCatPath);
// Image _thispngdog = Png.Load(pngDogPath);
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("DrawJpegOverPngTest :" + i);
// stopwatchSingleThread.Start();
// _thispngdog.Draw(_thisjpgcat, 10, 10);
// stopwatchSingleThread.Stop();
// }
// _thisjpgcat.ReleaseStruct();
// _thispngdog.ReleaseStruct();
// }
// private static void DrawPngOverJpegPerfTest(int numRuns)
// {
// Image _thisjpgdog = Jpg.Load(jpegDogPath);
// Image _thispngcat = Png.Load(pngCatPath);
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("DrawPngOverJpegTest :" + i);
// stopwatchSingleThread.Start();
// _thisjpgdog.Draw(_thispngcat, 10, 10);
// stopwatchSingleThread.Stop();
// }
// _thisjpgdog.ReleaseStruct();
// _thispngcat.ReleaseStruct();
// }
// private static void LoadStreamJpegPerfTest(int numRuns)
// {
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("LoadStreamJpegTest :" + i);
// using (FileStream filestream = new FileStream(jpegCatPath, FileMode.Open, FileAccess.Read, FileShare.Read))
// {
// stopwatchSingleThread.Start();
// Image img = Jpg.Load(filestream);
// stopwatchSingleThread.Stop();
// img.ReleaseStruct();
// //filestream.Dispose();
// }
// }
// }
// private static void LoadStreamPngPerfTest(int numRuns)
// {
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("LoadStreamPngTest :" + i);
// //fixed stream by giving acces to multiple threads?
// using (FileStream filestream = new FileStream(pngCatPath, FileMode.Open, FileAccess.Read, FileShare.Read))
// {
// stopwatchSingleThread.Start();
// Image img = Png.Load(filestream);
// stopwatchSingleThread.Stop();
// img.ReleaseStruct();
// //filestream.Dispose();
// }
// }
// }
// private static void WriteStreamJpegPerfTest(int numRuns)
// {
// Image _thisjpgcat = Jpg.Load(jpegCatPath);
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("WriteJpegTest :" + i);
// using (MemoryStream stream = new MemoryStream())
// {
// stopwatchSingleThread.Start();
// Jpg.Write(_thisjpgcat, stream);
// stopwatchSingleThread.Stop();
// }
// }
// _thisjpgcat.ReleaseStruct();
// }
// private static void WriteStreamPngPerfTest(int numRuns)
// {
// Image _thispngcat = Jpg.Load(pngCatPath);
// for (int i = 0; i < numRuns; i++)
// {
// //make sure it's going
// if (i % 100 == 0)
// Console.WriteLine("WritePngTest :" + i);
// using (MemoryStream stream = new MemoryStream())
// {
// stopwatchSingleThread.Start();
// Png.Write(_thispngcat, stream);
// stopwatchSingleThread.Stop();
// }
// }
// _thispngcat.ReleaseStruct();
// }
//#endif
//}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Internal.Interop;
using Internal.Threading.Tasks;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Runtime.WindowsRuntime.Internal;
using System.Threading;
using Windows.Foundation;
namespace System.Threading.Tasks
{
/// <summary>Provides a bridge between IAsyncOperation* and Task.</summary>
/// <typeparam name="TResult">Specifies the type of the result of the asynchronous operation.</typeparam>
/// <typeparam name="TProgress">Specifies the type of progress notification data.</typeparam>
internal sealed class AsyncInfoToTaskBridge<TResult> : TaskCompletionSource<TResult>
{
/// <summary>The CancellationToken associated with this operation.</summary>
private readonly CancellationToken _ct;
/// <summary>A registration for cancellation that needs to be disposed of when the operation completes.</summary>
private CancellationTokenRegistration _ctr;
/// <summary>A flag set to true as soon as the completion callback begins to execute.</summary>
private bool _completing;
internal AsyncInfoToTaskBridge(CancellationToken cancellationToken)
{
if (AsyncCausalitySupport.LoggingOn)
AsyncCausalitySupport.TraceOperationCreation(this.Task, "WinRT Operation as Task");
AsyncCausalitySupport.AddToActiveTasks(this.Task);
_ct = cancellationToken;
}
/// <summary>The synchronization object to use for protecting the state of this bridge.</summary>
private object StateLock
{
get { return this; } // "this" isn't available publicly, so we can safely use it as a syncobj
}
/// <summary>Registers the async operation for cancellation.</summary>
/// <param name="asyncInfo">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
internal void RegisterForCancellation(IAsyncInfo asyncInfo)
{
Debug.Assert(asyncInfo != null);
try
{
if (_ct.CanBeCanceled && !_completing)
{ // benign race on m_completing... it's ok if it's not up-to-date.
var ctr = _ct.Register(ai => ((IAsyncInfo)ai).Cancel(), asyncInfo); // delegate cached by compiler
// The operation may already be completing by this time, in which case
// we might need to dispose of our new cancellation registration here.
bool disposeOfCtr = false;
lock (StateLock)
{
if (_completing) disposeOfCtr = true;
else _ctr = ctr; // under lock to avoid torn writes
}
if (disposeOfCtr)
ctr.TryDeregister();
}
}
catch (Exception ex)
{
// We do not want exceptions propagating out of the AsTask / GetAwaiter calls, as the
// Completed handler will instead store the exception into the returned Task.
// Such exceptions should cause the Completed handler to be invoked synchronously and thus the Task should already be completed.
if (!base.Task.IsFaulted)
{
Debug.Assert(false, String.Format("Expected base task to already be faulted but found it in state {0}", base.Task.Status));
base.TrySetException(ex);
}
}
}
/// <summary>Bridge to Completed handler on IAsyncAction.</summary>
internal void CompleteFromAsyncAction(IAsyncAction asyncInfo, AsyncStatus asyncStatus)
{
Complete(asyncInfo, null, asyncStatus);
}
/// <summary>Bridge to Completed handler on IAsyncActionWithProgress{TProgress}.</summary>
internal void CompleteFromAsyncActionWithProgress<TProgress>(IAsyncActionWithProgress<TProgress> asyncInfo, AsyncStatus asyncStatus)
{
Complete(asyncInfo, null, asyncStatus);
}
/// <summary>Bridge to Completed handler on IAsyncOperation{TResult}.</summary>
internal void CompleteFromAsyncOperation(IAsyncOperation<TResult> asyncInfo, AsyncStatus asyncStatus)
{
Complete(asyncInfo, ai => ((IAsyncOperation<TResult>)ai).GetResults(), asyncStatus); // delegate cached by compiler
}
/// <summary>Bridge to Completed handler on IAsyncOperationWithProgress{TResult,TProgress}.</summary>
internal void CompleteFromAsyncOperationWithProgress<TProgress>(IAsyncOperationWithProgress<TResult, TProgress> asyncInfo, AsyncStatus asyncStatus)
{
// delegate cached by compiler:
Complete(asyncInfo, ai => ((IAsyncOperationWithProgress<TResult, TProgress>)ai).GetResults(), asyncStatus);
}
/// <summary>Completes the task from the completed asynchronous operation.</summary>
/// <param name="asyncInfo">The asynchronous operation.</param>
/// <param name="getResultsFunction">A function used to retrieve the TResult from the async operation; may be null.</param>
/// <param name="asyncStatus">The status of the asynchronous operation.</param>
private void Complete(IAsyncInfo asyncInfo, Func<IAsyncInfo, TResult> getResultsFunction, AsyncStatus asyncStatus)
{
if (asyncInfo == null)
throw new ArgumentNullException(nameof(asyncInfo));
Contract.EndContractBlock();
AsyncCausalitySupport.RemoveFromActiveTasks(this.Task);
try
{
Debug.Assert(asyncInfo.Status == asyncStatus,
"asyncInfo.Status does not match asyncStatus; are we dealing with a faulty IAsyncInfo implementation?");
// Assuming a correct underlying implementation, the task should not have been
// completed yet. If it is completed, we shouldn't try to do any further work
// with the operation or the task, as something is horked.
bool taskAlreadyCompleted = Task.IsCompleted;
Debug.Assert(!taskAlreadyCompleted, "Expected the task to not yet be completed.");
if (taskAlreadyCompleted)
throw new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
// Clean up our registration with the cancellation token, noting that we're now in the process of cleaning up.
CancellationTokenRegistration ctr;
lock (StateLock)
{
_completing = true;
ctr = _ctr; // under lock to avoid torn reads
_ctr = default(CancellationTokenRegistration);
}
ctr.TryDeregister(); // It's ok if we end up unregistering a not-initialized registration; it'll just be a nop.
try
{
// Find out how the async operation completed. It must be in a terminal state.
bool terminalState = asyncStatus == AsyncStatus.Completed
|| asyncStatus == AsyncStatus.Canceled
|| asyncStatus == AsyncStatus.Error;
Debug.Assert(terminalState, "The async operation should be in a terminal state.");
if (!terminalState)
throw new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
// Retrieve the completion data from the IAsyncInfo.
TResult result = default(TResult);
Exception error = null;
if (asyncStatus == AsyncStatus.Error)
{
error = asyncInfo.ErrorCode;
// Defend against a faulty IAsyncInfo implementation:
if (error == null)
{
Debug.Assert(false, "IAsyncInfo.Status == Error, but ErrorCode returns a null Exception (implying S_OK).");
error = new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
}
else
{
error = asyncInfo.ErrorCode.AttachRestrictedErrorInfo();
}
}
else if (asyncStatus == AsyncStatus.Completed && getResultsFunction != null)
{
try
{
result = getResultsFunction(asyncInfo);
}
catch (Exception resultsEx)
{
// According to the WinRT team, this can happen in some egde cases, such as marshalling errors in GetResults.
error = resultsEx;
asyncStatus = AsyncStatus.Error;
}
}
// Nothing to retrieve for a canceled operation or for a completed operation with no result.
// Complete the task based on the previously retrieved results:
bool success = false;
switch (asyncStatus)
{
case AsyncStatus.Completed:
if (AsyncCausalitySupport.LoggingOn)
AsyncCausalitySupport.TraceOperationCompletedSuccess(this.Task);
success = base.TrySetResult(result);
break;
case AsyncStatus.Error:
Debug.Assert(error != null, "The error should have been retrieved previously.");
success = base.TrySetException(error);
break;
case AsyncStatus.Canceled:
success = base.TrySetCanceled(_ct.IsCancellationRequested ? _ct : new CancellationToken(true));
break;
}
Debug.Assert(success, "Expected the outcome to be successfully transfered to the task.");
}
catch (Exception exc)
{
// This really shouldn't happen, but could in a variety of misuse cases
// such as a faulty underlying IAsyncInfo implementation.
Debug.Assert(false, string.Format("Unexpected exception in Complete: {0}", exc.ToString()));
if (AsyncCausalitySupport.LoggingOn)
AsyncCausalitySupport.TraceOperationCompletedError(this.Task);
// For these cases, store the exception into the task so that it makes its way
// back to the caller. Only if something went horribly wrong and we can't store the exception
// do we allow it to be propagated out to the invoker of the Completed handler.
if (!base.TrySetException(exc))
{
Debug.Assert(false, "The task was already completed and thus the exception couldn't be stored.");
throw;
}
}
}
finally
{
// We may be called on an STA thread which we don't own, so make sure that the RCW is released right
// away. Otherwise, if we leave it up to the finalizer, the apartment may already be gone.
if (Marshal.IsComObject(asyncInfo))
Marshal.ReleaseComObject(asyncInfo);
}
} // private void Complete(..)
} // class AsyncInfoToTaskBridge<TResult, TProgress>
} // namespace
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.MetaData;
using Microsoft.Zelig.MetaData.Normalized;
using Microsoft.Zelig.Runtime.TypeSystem;
public sealed partial class ByteCodeConverter
{
//
// State
//
private int m_currentInstructionOffset;
private Expression[] m_activeStackModel;
//
// Constructor Methods
//
private TypeRepresentation ProcessInstruction_GetTypeFromActionType( Instruction instr ,
TypeRepresentation tdRef )
{
WellKnownTypes wkt = m_typeSystem.WellKnownTypes;
switch(instr.Operator.ActionType)
{
case Instruction.OpcodeActionType.I1 : return wkt.System_SByte;
case Instruction.OpcodeActionType.U1 : return wkt.System_Byte;
case Instruction.OpcodeActionType.I2 : return wkt.System_Int16;
case Instruction.OpcodeActionType.U2 : return wkt.System_UInt16;
case Instruction.OpcodeActionType.I4 : return wkt.System_Int32;
case Instruction.OpcodeActionType.U4 : return wkt.System_UInt32;
case Instruction.OpcodeActionType.I8 : return wkt.System_Int64;
case Instruction.OpcodeActionType.U8 : return wkt.System_UInt64;
case Instruction.OpcodeActionType.I : return wkt.System_IntPtr;
case Instruction.OpcodeActionType.U : return wkt.System_UIntPtr;
case Instruction.OpcodeActionType.R4 : return wkt.System_Single;
case Instruction.OpcodeActionType.R8 : return wkt.System_Double;
case Instruction.OpcodeActionType.R : return wkt.System_Double;
case Instruction.OpcodeActionType.String: return wkt.System_String;
case Instruction.OpcodeActionType.Reference:
{
return tdRef;
}
case Instruction.OpcodeActionType.Token:
{
return this.CurrentArgumentAsType;
}
default:
{
throw IncorrectEncodingException.Create( "Invalid OpcodeActionType {0} for {1}", instr.Operator.ActionType, instr );
}
}
}
private Expression ProcessInstruction_GetTypeOfActionTarget( Instruction instr ,
out TypeRepresentation tdTarget ,
out FieldRepresentation fdTarget )
{
Expression ex;
switch(instr.Operator.ActionTarget)
{
case Instruction.OpcodeActionTarget.Local:
ex = m_locals[this.CurrentArgumentAsInt32];
break;
case Instruction.OpcodeActionTarget.Argument:
ex = m_arguments[m_variable_arguments_offset + this.CurrentArgumentAsInt32];
break;
case Instruction.OpcodeActionTarget.Null:
ex = CreateNewNullPointer( m_typeSystem.WellKnownTypes.System_Object );
break;
case Instruction.OpcodeActionTarget.Constant:
ex = CreateNewConstant( m_typeSystem.GetTypeOfValue( this.CurrentArgument ), this.CurrentArgument );
break;
case Instruction.OpcodeActionTarget.Field:
case Instruction.OpcodeActionTarget.StaticField:
{
fdTarget = this.CurrentArgumentAsField;
tdTarget = fdTarget.FieldType;
return null;
}
case Instruction.OpcodeActionTarget.String:
ex = CreateNewConstant( m_typeSystem.WellKnownTypes.System_String, this.CurrentArgument );
break;
case Instruction.OpcodeActionTarget.Token:
{
object o = this.CurrentArgument;
if(o is TypeRepresentation ||
o is FieldRepresentation ||
o is MethodRepresentation )
{
ex = m_typeSystem.CreateRuntimeHandle( o );
break;
}
throw TypeConsistencyErrorException.Create( "Unknown token {0}", o );
}
default:
{
throw IncorrectEncodingException.Create( "Invalid OpcodeActionTarget {0} for {1}", instr.Operator.ActionTarget, instr );
}
}
fdTarget = null;
tdTarget = ex.Type;
return ex;
}
//--//
private TypeRepresentation ProcessInstruction_ExtractAddressType( Instruction instr ,
Expression exAddr ,
TypeRepresentation tdFormal )
{
if(tdFormal == null)
{
TypeRepresentation td = exAddr.Type;
TypeRepresentation tdActual;
if(td is PointerTypeRepresentation)
{
tdActual = td.UnderlyingType;
}
else if(td is BoxedValueTypeRepresentation)
{
tdActual = td.UnderlyingType;
}
else if(td.StackEquivalentType == StackEquivalentType.NativeInt)
{
tdActual = m_typeSystem.WellKnownTypes.System_IntPtr;
}
else
{
throw TypeConsistencyErrorException.Create( "Expecting pointer type, got {0}", td );
}
tdFormal = ProcessInstruction_GetTypeFromActionType( instr, tdActual );
//
// TODO: Need to distinguish between safe and unsafe code. For safe code, the check should be performed.
//
//// if(m_typeSystem.CanBeAssignedFrom( tdFormal, tdActual ) == false)
//// {
//// throw TypeConsistencyErrorException.Create( "Expecting pointer type {0}, got {1}", tdFormal, tdActual );
//// }
}
return tdFormal;
}
private Operator ProcessInstruction_LoadIndirect( Instruction instr ,
Expression exAddr ,
TypeRepresentation tdFormal )
{
TypeRepresentation td = ProcessInstruction_ExtractAddressType( instr, exAddr, tdFormal );
VariableExpression exRes = CreateNewTemporary( td );
ModifyStackModel( 1, exRes );
return LoadIndirectOperator.New( instr.DebugInfo, td, exRes, exAddr, null, 0, false, true );
}
private Operator ProcessInstruction_StoreIndirect( Instruction instr ,
Expression exAddr ,
Expression exValue ,
TypeRepresentation tdFormal )
{
TypeRepresentation td = ProcessInstruction_ExtractAddressType( instr, exAddr, tdFormal );
if(CanBeAssignedFromEvaluationStack( td, exValue ) == false)
{
throw TypeConsistencyErrorException.Create( "Expecting value of type {0}, got {1}", td, exValue.Type );
}
PopStackModel( 2 );
return StoreIndirectOperator.New( instr.DebugInfo, td, exAddr, exValue, null, 0, true );
}
//--//--//--//--//--//--//--//--//--//
internal int CurrentInstructionOffset
{
get
{
return m_currentInstructionOffset;
}
set
{
m_currentInstructionOffset = value;
}
}
internal object CurrentArgument
{
get
{
return m_byteCodeArguments[m_currentInstructionOffset];
}
}
internal int CurrentArgumentAsInt32
{
get
{
return (int)CurrentArgument;
}
}
internal TypeRepresentation CurrentArgumentAsType
{
get
{
return (TypeRepresentation)CurrentArgument;
}
}
internal FieldRepresentation CurrentArgumentAsField
{
get
{
return (FieldRepresentation)CurrentArgument;
}
}
internal MethodRepresentation CurrentArgumentAsMethod
{
get
{
return (MethodRepresentation)CurrentArgument;
}
}
internal BasicBlock GetBasicBlockFromInstruction( int offset )
{
if(offset < 0 || offset >= m_instructionToByteCodeBlock.Length)
{
return null;
}
return m_instructionToByteCodeBlock[offset].BasicBlock;
}
//--//
internal void ModifyStackModel( int slotsToPop ,
Expression slotToPush )
{
Expression[] stackModel = m_activeStackModel;
int newLen = stackModel.Length - slotsToPop;
if(slotToPush != null) newLen += 1;
Expression[] res = new Expression[newLen];
for(int i = 0; i < newLen; i++)
{
if(slotToPush != null)
{
res[i] = slotToPush; slotToPush = null;
}
else
{
res[i] = stackModel[slotsToPop++];
}
}
m_activeStackModel = res;
}
internal void PushStackModel( Expression slot )
{
ModifyStackModel( 0, slot );
}
internal void PopStackModel( int slots )
{
ModifyStackModel( slots, null );
}
internal void EmptyStackModel()
{
m_activeStackModel = Expression.SharedEmptyArray;
}
internal Expression GetArgumentFromStack( int pos ,
int tot )
{
pos = tot - 1 - pos;
CHECKS.ASSERT( pos >= 0 , "Evaluation stack underflow in {0}", m_md );
CHECKS.ASSERT( pos < m_activeStackModel.Length, "Evaluation stack overflow in {0}" , m_md );
return m_activeStackModel[pos];
}
//--//--//--//--//--//--//--//--//--//
private bool CanBeAssignedFromEvaluationStack( TypeRepresentation dst ,
Expression src )
{
if(src.CanBeNull == CanBeNull.Yes)
{
if(dst is ReferenceTypeRepresentation)
{
return true;
}
if(dst is PointerTypeRepresentation)
{
return true;
}
}
return dst.CanBeAssignedFrom( ExpandForEvaluationStack( src.Type ), null );
}
private TypeRepresentation ExpandForEvaluationStack( TypeRepresentation td )
{
if(td is EnumerationTypeRepresentation)
{
td = td.UnderlyingType;
}
if(td is ScalarTypeRepresentation)
{
switch(td.BuiltInType)
{
case TypeRepresentation.BuiltInTypes.BOOLEAN:
case TypeRepresentation.BuiltInTypes.I1:
case TypeRepresentation.BuiltInTypes.U1:
case TypeRepresentation.BuiltInTypes.I2:
case TypeRepresentation.BuiltInTypes.U2:
case TypeRepresentation.BuiltInTypes.CHAR:
case TypeRepresentation.BuiltInTypes.U4:
return m_typeSystem.WellKnownTypes.System_Int32;
}
}
return td;
}
private ConstantExpression CreateNewNullPointer( TypeRepresentation td )
{
return m_typeSystem.CreateNullPointer( td );
}
private ConstantExpression CreateNewConstant( TypeRepresentation td ,
object value )
{
return m_typeSystem.CreateConstant( td, value );
}
private TemporaryVariableExpression CreateNewTemporary( TypeRepresentation td )
{
td = ExpandForEvaluationStack( td );
return m_cfg.AllocateTemporary( td, null );
}
private void AddOperator( Operator op )
{
m_currentBasicBlock.AddOperator( op );
}
private void AddControl( ControlOperator op )
{
m_currentBasicBlock.FlowControl = op;
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCROPS
{
using System;
using System.Collections.Generic;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// This class is designed to verify the response buffer formats of Permission ROPs.
/// </summary>
[TestClass]
public class S08_PermissionROPs : TestSuiteBase
{
#region Class Initialization and Cleanup
/// <summary>
/// Class initialize.
/// </summary>
/// <param name="testContext">The session context handle</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Class cleanup.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test Cases
/// <summary>
/// This method tests the ROP buffers of RopGetPermission and RopModifyPermission.
/// </summary>
[TestCategory("MSOXCROPS"), TestMethod()]
public void MSOXCROPS_S08_TC01_TestRopGetAndModifyPermissions()
{
this.CheckTransportIsSupported();
this.cropsAdapter.RpcConnect(
Common.GetConfigurationPropertyValue("SutComputerName", this.Site),
ConnectionType.PrivateMailboxServer,
Common.GetConfigurationPropertyValue("UserEssdn", this.Site),
Common.GetConfigurationPropertyValue("Domain", this.Site),
Common.GetConfigurationPropertyValue("AdminUserName", this.Site),
Common.GetConfigurationPropertyValue("PassWord", this.Site));
// Step 1: Preparations-Open folder and create a subfolder, then get it's handle.
#region Common operations
RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle);
uint folderHandle = GetFolderObjectHandle(ref logonResponse);
#endregion
// Step 2: Construct RopGetPermissionsTable request.
#region RopGetPermissionsTable request
RopGetPermissionsTableRequest getPermissionsTableRequest;
getPermissionsTableRequest.RopId = (byte)RopId.RopGetPermissionsTable;
getPermissionsTableRequest.LogonId = TestSuiteBase.LogonId;
getPermissionsTableRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
getPermissionsTableRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1;
getPermissionsTableRequest.TableFlags = (byte)PermTableFlags.IncludeFreeBusy;
#endregion
// Step 3: Construct RopSetColumns request.
#region RopSetColumns request
// Call CreatePermissionPropertyTags method to create Permission PropertyTags.
PropertyTag[] propertyTags = this.CreatePermissionPropertyTags();
RopSetColumnsRequest setColumnsRequest;
setColumnsRequest.RopId = (byte)RopId.RopSetColumns;
setColumnsRequest.LogonId = TestSuiteBase.LogonId;
setColumnsRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex1;
setColumnsRequest.PropertyTagCount = (ushort)propertyTags.Length;
setColumnsRequest.PropertyTags = propertyTags;
setColumnsRequest.SetColumnsFlags = (byte)AsynchronousFlags.None;
#endregion
// Step 4: Construct RopQueryRows request.
#region RopQueryRows request
RopQueryRowsRequest queryRowsRequest;
queryRowsRequest.RopId = (byte)RopId.RopQueryRows;
queryRowsRequest.LogonId = TestSuiteBase.LogonId;
queryRowsRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex1;
queryRowsRequest.QueryRowsFlags = (byte)QueryRowsFlags.Advance;
// TRUE: read the table forwards.
queryRowsRequest.ForwardRead = TestSuiteBase.NonZero;
// Maximum number of rows to be returned
queryRowsRequest.RowCount = TestSuiteBase.RowCount;
#endregion
// Step 5: Send the Multiple ROPs request and verify the success response.
#region Multiple ROPs
List<ISerializable> requests = new List<ISerializable>();
List<IDeserializable> ropResponses = new List<IDeserializable>();
List<uint> handleList = new List<uint>
{
folderHandle,
TestSuiteBase.DefaultFolderHandle
};
requests.Add(getPermissionsTableRequest);
requests.Add(setColumnsRequest);
requests.Add(queryRowsRequest);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 5: Begin to send the Multiple ROPs request.");
// Send the Multiple ROPs request and verify the success response.
this.responseSOHs = cropsAdapter.ProcessMutipleRops(
requests,
handleList,
ref ropResponses,
ref this.rawData,
RopResponseType.SuccessResponse);
RopGetPermissionsTableResponse getPermissionsTableResponse = (RopGetPermissionsTableResponse)ropResponses[0];
RopSetColumnsResponse setColumnsResponse = (RopSetColumnsResponse)ropResponses[1];
RopQueryRowsResponse queryRowsResponse = (RopQueryRowsResponse)ropResponses[2];
// Send the RopModifyPermissions request and verify response.
#region RopModifyPermissions request
RopModifyPermissionsRequest modifyPermissionsRequest;
PermissionData[] permissionsDataArray = this.GetPermissionDataArray();
modifyPermissionsRequest.RopId = (byte)RopId.RopModifyPermissions;
modifyPermissionsRequest.LogonId = TestSuiteBase.LogonId;
modifyPermissionsRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0;
modifyPermissionsRequest.ModifyFlags = (byte)ModifyFlags.IncludeFreeBusy;
modifyPermissionsRequest.ModifyCount = (ushort)permissionsDataArray.Length;
modifyPermissionsRequest.PermissionsData = permissionsDataArray;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Step 5: Begin to send the RopModifyPermissions request.");
this.responseSOHs = cropsAdapter.ProcessSingleRop(
modifyPermissionsRequest,
folderHandle,
ref this.response,
ref this.rawData,
RopResponseType.SuccessResponse);
RopModifyPermissionsResponse modifyPermissionsResponse = (RopModifyPermissionsResponse)response;
#endregion
bool isRopsSuccess = (getPermissionsTableResponse.ReturnValue == TestSuiteBase.SuccessReturnValue)
&& (setColumnsResponse.ReturnValue == TestSuiteBase.SuccessReturnValue)
&& (queryRowsResponse.ReturnValue == TestSuiteBase.SuccessReturnValue)
&& (modifyPermissionsResponse.ReturnValue == TestSuiteBase.SuccessReturnValue);
Site.Assert.IsTrue(isRopsSuccess, "If ROP succeeds, the ReturnValue of its response is 0 (success)");
#endregion
}
#endregion
#region Common methods
/// <summary>
/// Create Permission PropertyTags
/// </summary>
/// <returns>Return propertyTag array</returns>
private PropertyTag[] CreatePermissionPropertyTags()
{
// The following sample tags is from MS-OXCPERM 4.1
PropertyTag[] propertyTags = new PropertyTag[4];
// PidTagMemberId
propertyTags[0] = this.propertyDictionary[PropertyNames.PidTagMemberId];
// PidTagMemberName
propertyTags[1] = this.propertyDictionary[PropertyNames.PidTagMemberName];
// PidTagMemberRights
propertyTags[2] = this.propertyDictionary[PropertyNames.PidTagMemberRights];
// PidTagEntryId
propertyTags[3] = this.propertyDictionary[PropertyNames.PidTagEntryId];
return propertyTags;
}
/// <summary>
/// Get GetPermissionData Array for modify permissions
/// </summary>
/// <returns>Return GetPermissionData array</returns>
private PermissionData[] GetPermissionDataArray()
{
// Get PropertyValues
TaggedPropertyValue taggedPropertyValue = new TaggedPropertyValue();
TaggedPropertyValue[] propertyValues = new TaggedPropertyValue[2];
// PidTagMemberId
taggedPropertyValue.PropertyTag.PropertyId = this.propertyDictionary[PropertyNames.PidTagMemberId].PropertyId;
taggedPropertyValue.PropertyTag.PropertyType = this.propertyDictionary[PropertyNames.PidTagMemberId].PropertyType;
// Anonymous Client: The server MUST use the permissions specified in PidTagMemberRights for
// any anonymous users that have not been authenticated with user credentials.
taggedPropertyValue.Value = BitConverter.GetBytes(TestSuiteBase.TaggedPropertyValueForPidTagMemberId);
propertyValues[0] = taggedPropertyValue;
// PidTagMemberRights
taggedPropertyValue = new TaggedPropertyValue
{
PropertyTag =
{
PropertyId = this.propertyDictionary[PropertyNames.PidTagMemberRights].PropertyId,
PropertyType = this.propertyDictionary[PropertyNames.PidTagMemberRights].PropertyType
},
Value = BitConverter.GetBytes(TestSuiteBase.TaggedPropertyValueForPidTagMemberRights)
};
// CreateSubFolder
propertyValues[1] = taggedPropertyValue;
PermissionData[] permissionsDataArray = new PermissionData[1];
permissionsDataArray[0].PermissionDataFlags = (byte)PermissionDataFlags.ModifyRow;
permissionsDataArray[0].PropertyValueCount = (ushort)propertyValues.Length;
permissionsDataArray[0].PropertyValues = propertyValues;
return permissionsDataArray;
}
#endregion
}
}
| |
using Pathfinding;
using System.Collections.Generic;
using Pathfinding.Serialization;
using UnityEngine;
namespace Pathfinding {
/** Base class for GridNode and LevelGridNode */
public abstract class GridNodeBase : GraphNode {
protected GridNodeBase (AstarPath astar) : base (astar) {
}
protected int nodeInGridIndex;
/** The index of the node in the grid.
* This is x + z*graph.width (+ y*graph.width*graph.depth if this is a LayerGridGraph)
* So you can get the X and Z indices using
* \code
* int index = node.NodeInGridIndex;
* int x = index % graph.width;
* int z = index / graph.width;
* // where graph is GridNode.GetGridGraph (node.graphIndex), i.e the graph the nodes are contained in.
* \endcode
*/
public int NodeInGridIndex { get { return nodeInGridIndex;} set { nodeInGridIndex = value; }}
}
public class GridNode : GridNodeBase {
public GridNode (AstarPath astar) : base (astar) {
}
private static GridGraph[] _gridGraphs = new GridGraph[0];
public static GridGraph GetGridGraph (uint graphIndex) { return _gridGraphs[(int)graphIndex]; }
public GraphNode[] connections;
public uint[] connectionCosts;
public static void SetGridGraph (int graphIndex, GridGraph graph) {
if (_gridGraphs.Length <= graphIndex) {
var gg = new GridGraph[graphIndex+1];
for (int i=0;i<_gridGraphs.Length;i++) gg[i] = _gridGraphs[i];
_gridGraphs = gg;
}
_gridGraphs[graphIndex] = graph;
}
protected ushort gridFlags;
/** Internal use only */
internal ushort InternalGridFlags {
get { return gridFlags; }
set { gridFlags = value; }
}
const int GridFlagsConnectionOffset = 0;
const int GridFlagsConnectionBit0 = 1 << GridFlagsConnectionOffset;
const int GridFlagsConnectionMask = 0xFF << GridFlagsConnectionOffset;
const int GridFlagsWalkableErosionOffset = 8;
const int GridFlagsWalkableErosionMask = 1 << GridFlagsWalkableErosionOffset;
const int GridFlagsWalkableTmpOffset = 9;
const int GridFlagsWalkableTmpMask = 1 << GridFlagsWalkableTmpOffset;
const int GridFlagsEdgeNodeOffset = 10;
const int GridFlagsEdgeNodeMask = 1 << GridFlagsEdgeNodeOffset;
/** Returns true if the node has a connection in the specified direction.
* The dir parameter corresponds to directions in the grid as:
\code
[0] = -Y
[1] = +X
[2] = +Y
[3] = -X
[4] = -Y+X
[5] = +Y+X
[6] = +Y-X
[7] = -Y-X
\endcode
* \see SetConnectionInternal
*/
public bool GetConnectionInternal (int dir) {
return (gridFlags >> dir & GridFlagsConnectionBit0) != 0;
}
/** Enables or disables a connection in a specified direction on the graph.
* \see GetConnectionInternal
*/
public void SetConnectionInternal (int dir, bool value) {
unchecked { gridFlags = (ushort)(gridFlags & ~((ushort)1 << GridFlagsConnectionOffset << dir) | (value ? (ushort)1 : (ushort)0) << GridFlagsConnectionOffset << dir); }
}
/** Disables all grid connections from this node.
* \note Other nodes might still be able to get to this node. Therefore it is recommended to also disable the relevant connections on adjacent nodes.
*/
public void ResetConnectionsInternal () {
unchecked {
gridFlags = (ushort)(gridFlags & ~GridFlagsConnectionMask);
}
}
public bool EdgeNode {
get {
return (gridFlags & GridFlagsEdgeNodeMask) != 0;
}
set {
unchecked { gridFlags = (ushort)(gridFlags & ~GridFlagsEdgeNodeMask | (value ? GridFlagsEdgeNodeMask : 0)); }
}
}
/** Stores walkability before erosion is applied.
* Used by graph updating.
*/
public bool WalkableErosion {
get {
return (gridFlags & GridFlagsWalkableErosionMask) != 0;
}
set {
unchecked { gridFlags = (ushort)(gridFlags & ~GridFlagsWalkableErosionMask | (value ? (ushort)GridFlagsWalkableErosionMask : (ushort)0)); }
}
}
/** Temporary variable used by graph updating */
public bool TmpWalkable {
get {
return (gridFlags & GridFlagsWalkableTmpMask) != 0;
}
set {
unchecked { gridFlags = (ushort)(gridFlags & ~GridFlagsWalkableTmpMask | (value ? (ushort)GridFlagsWalkableTmpMask : (ushort)0)); }
}
}
public override void ClearConnections (bool alsoReverse) {
if (alsoReverse) {
GridGraph gg = GetGridGraph (GraphIndex);
for (int i=0;i<8;i++) {
GridNode other = gg.GetNodeConnection (this,i);
if (other != null) {
//Remove reverse connection
other.SetConnectionInternal(i < 4 ? ((i + 2) % 4) : (((5-2) % 4) + 4),false);
}
}
}
ResetConnectionsInternal ();
if ( alsoReverse ) {
if ( connections != null ) for (int i=0;i<connections.Length;i++) connections[i].RemoveConnection ( this );
}
connections = null;
connectionCosts = null;
}
public override void GetConnections (GraphNodeDelegate del)
{
GridGraph gg = GetGridGraph (GraphIndex);
int[] neighbourOffsets = gg.neighbourOffsets;
GridNode[] nodes = gg.nodes;
for (int i=0;i<8;i++) {
if (GetConnectionInternal(i)) {
GridNode other = nodes[nodeInGridIndex + neighbourOffsets[i]];
if (other != null) del (other);
}
}
if ( connections != null ) for (int i=0;i<connections.Length;i++) del(connections[i]);
}
public override bool GetPortal (GraphNode other, List<Vector3> left, List<Vector3> right, bool backwards)
{
if (backwards) return true;
GridGraph gg = GetGridGraph (GraphIndex);
int[] neighbourOffsets = gg.neighbourOffsets;
GridNode[] nodes = gg.nodes;
for (int i=0;i<4;i++) {
if (GetConnectionInternal(i) && other == nodes[nodeInGridIndex + neighbourOffsets[i]]) {
Vector3 middle = ((Vector3)(position + other.position))*0.5f;
Vector3 cross = Vector3.Cross (gg.collision.up, (Vector3)(other.position-position));
cross.Normalize();
cross *= gg.nodeSize*0.5f;
left.Add (middle - cross);
right.Add (middle + cross);
return true;
}
}
for (int i=4;i<8;i++) {
if (GetConnectionInternal(i) && other == nodes[nodeInGridIndex + neighbourOffsets[i]]) {
bool rClear = false;
bool lClear = false;
if (GetConnectionInternal(i-4)) {
GridNode n2 = nodes[nodeInGridIndex + neighbourOffsets[i-4]];
if (n2.Walkable && n2.GetConnectionInternal((i-4+1)%4)) {
rClear = true;
}
}
if (GetConnectionInternal((i-4+1)%4)) {
GridNode n2 = nodes[nodeInGridIndex + neighbourOffsets[(i-4+1)%4]];
if (n2.Walkable && n2.GetConnectionInternal(i-4)) {
lClear = true;
}
}
Vector3 middle = ((Vector3)(position + other.position))*0.5f;
Vector3 cross = Vector3.Cross (gg.collision.up, (Vector3)(other.position-position));
cross.Normalize();
cross *= gg.nodeSize*1.4142f;
left.Add (middle - (lClear ? cross : Vector3.zero));
right.Add (middle + (rClear ? cross : Vector3.zero));
return true;
}
}
return false;
}
public override void FloodFill (Stack<GraphNode> stack, uint region) {
GridGraph gg = GetGridGraph (GraphIndex);
int[] neighbourOffsets = gg.neighbourOffsets;
GridNode[] nodes = gg.nodes;
for (int i=0;i<8;i++) {
if (GetConnectionInternal(i)) {
GridNode other = nodes[nodeInGridIndex + neighbourOffsets[i]];
if (other != null && other.Area != region) {
other.Area = region;
stack.Push (other);
}
}
}
if ( connections != null ) for (int i=0;i<connections.Length;i++) {
GraphNode other = connections[i];
if (other.Area != region) {
other.Area = region;
stack.Push (other);
}
}
}
/** Add a connection from this node to the specified node.
* If the connection already exists, the cost will simply be updated and
* no extra connection added.
*
* \note Only adds a one-way connection. Consider calling the same function on the other node
* to get a two-way connection.
*/
public override void AddConnection (GraphNode node, uint cost) {
if (connections != null) {
for (int i=0;i<connections.Length;i++) {
if (connections[i] == node) {
connectionCosts[i] = cost;
return;
}
}
}
int connLength = connections != null ? connections.Length : 0;
var newconns = new GraphNode[connLength+1];
var newconncosts = new uint[connLength+1];
for (int i=0;i<connLength;i++) {
newconns[i] = connections[i];
newconncosts[i] = connectionCosts[i];
}
newconns[connLength] = node;
newconncosts[connLength] = cost;
connections = newconns;
connectionCosts = newconncosts;
}
/** Removes any connection from this node to the specified node.
* If no such connection exists, nothing will be done.
*
* \note This only removes the connection from this node to the other node.
* You may want to call the same function on the other node to remove its eventual connection
* to this node.
*/
public override void RemoveConnection (GraphNode node) {
if (connections == null) return;
for (int i=0;i<connections.Length;i++) {
if (connections[i] == node) {
int connLength = connections.Length;
var newconns = new GraphNode[connLength-1];
var newconncosts = new uint[connLength-1];
for (int j=0;j<i;j++) {
newconns[j] = connections[j];
newconncosts[j] = connectionCosts[j];
}
for (int j=i+1;j<connLength;j++) {
newconns[j-1] = connections[j];
newconncosts[j-1] = connectionCosts[j];
}
connections = newconns;
connectionCosts = newconncosts;
return;
}
}
}
public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
GridGraph gg = GetGridGraph (GraphIndex);
int[] neighbourOffsets = gg.neighbourOffsets;
GridNode[] nodes = gg.nodes;
UpdateG (path,pathNode);
handler.PushNode (pathNode);
ushort pid = handler.PathID;
for (int i=0;i<8;i++) {
if (GetConnectionInternal(i)) {
GridNode other = nodes[nodeInGridIndex + neighbourOffsets[i]];
PathNode otherPN = handler.GetPathNode (other);
if (otherPN.parent == pathNode && otherPN.pathID == pid) other.UpdateRecursiveG (path, otherPN,handler);
}
}
if ( connections != null ) for (int i=0;i<connections.Length;i++) {
GraphNode other = connections[i];
PathNode otherPN = handler.GetPathNode (other);
if (otherPN.parent == pathNode && otherPN.pathID == pid) other.UpdateRecursiveG (path, otherPN,handler);
}
}
public override void Open (Path path, PathNode pathNode, PathHandler handler) {
GridGraph gg = GetGridGraph (GraphIndex);
ushort pid = handler.PathID;
{
int[] neighbourOffsets = gg.neighbourOffsets;
uint[] neighbourCosts = gg.neighbourCosts;
GridNode[] nodes = gg.nodes;
for (int i=0;i<8;i++) {
if (GetConnectionInternal(i)) {
GridNode other = nodes[nodeInGridIndex + neighbourOffsets[i]];
if (!path.CanTraverse (other)) continue;
PathNode otherPN = handler.GetPathNode (other);
uint tmpCost = neighbourCosts[i];
if (otherPN.pathID != pid) {
otherPN.parent = pathNode;
otherPN.pathID = pid;
otherPN.cost = tmpCost;
otherPN.H = path.CalculateHScore (other);
other.UpdateG (path, otherPN);
//Debug.Log ("G " + otherPN.G + " F " + otherPN.F);
handler.PushNode (otherPN);
//Debug.DrawRay ((Vector3)otherPN.node.Position, Vector3.up,Color.blue);
} else {
// Sorry for the huge number of #ifs
//If not we can test if the path from the current node to this one is a better one then the one already used
#if ASTAR_NO_TRAVERSAL_COST
if (pathNode.G+tmpCost < otherPN.G)
#else
if (pathNode.G+tmpCost+path.GetTraversalCost(other) < otherPN.G)
#endif
{
//Debug.Log ("Path better from " + NodeIndex + " to " + otherPN.node.NodeIndex + " " + (pathNode.G+tmpCost+path.GetTraversalCost(other)) + " < " + otherPN.G);
otherPN.cost = tmpCost;
otherPN.parent = pathNode;
other.UpdateRecursiveG (path,otherPN, handler);
//Or if the path from this node ("other") to the current ("current") is better
}
#if ASTAR_NO_TRAVERSAL_COST
else if (otherPN.G+tmpCost < pathNode.G)
#else
else if (otherPN.G+tmpCost+path.GetTraversalCost (this) < pathNode.G)
#endif
{
//Debug.Log ("Path better from " + otherPN.node.NodeIndex + " to " + NodeIndex + " " + (otherPN.G+tmpCost+path.GetTraversalCost (this)) + " < " + pathNode.G);
pathNode.parent = otherPN;
pathNode.cost = tmpCost;
UpdateRecursiveG(path, pathNode, handler);
}
}
}
}
}
if (connections != null) for (int i=0;i<connections.Length;i++) {
GraphNode other = connections[i];
if (!path.CanTraverse (other)) continue;
PathNode otherPN = handler.GetPathNode (other);
uint tmpCost = connectionCosts[i];
if (otherPN.pathID != pid) {
otherPN.parent = pathNode;
otherPN.pathID = pid;
otherPN.cost = tmpCost;
otherPN.H = path.CalculateHScore (other);
other.UpdateG (path, otherPN);
//Debug.Log ("G " + otherPN.G + " F " + otherPN.F);
handler.PushNode (otherPN);
//Debug.DrawRay ((Vector3)otherPN.node.Position, Vector3.up,Color.blue);
} else {
// Sorry for the huge number of #ifs
//If not we can test if the path from the current node to this one is a better one then the one already used
#if ASTAR_NO_TRAVERSAL_COST
if (pathNode.G+tmpCost < otherPN.G)
#else
if (pathNode.G+tmpCost+path.GetTraversalCost(other) < otherPN.G)
#endif
{
//Debug.Log ("Path better from " + NodeIndex + " to " + otherPN.node.NodeIndex + " " + (pathNode.G+tmpCost+path.GetTraversalCost(other)) + " < " + otherPN.G);
otherPN.cost = tmpCost;
otherPN.parent = pathNode;
other.UpdateRecursiveG (path,otherPN, handler);
//Or if the path from this node ("other") to the current ("current") is better
}
#if ASTAR_NO_TRAVERSAL_COST
else if (otherPN.G+tmpCost < pathNode.G && other.ContainsConnection (this))
#else
else if (otherPN.G+tmpCost+path.GetTraversalCost (this) < pathNode.G && other.ContainsConnection (this))
#endif
{
//Debug.Log ("Path better from " + otherPN.node.NodeIndex + " to " + NodeIndex + " " + (otherPN.G+tmpCost+path.GetTraversalCost (this)) + " < " + pathNode.G);
pathNode.parent = otherPN;
pathNode.cost = tmpCost;
UpdateRecursiveG(path, pathNode, handler);
}
}
}
}
public override void SerializeNode (GraphSerializationContext ctx) {
base.SerializeNode (ctx);
ctx.writer.Write (position.x);
ctx.writer.Write (position.y);
ctx.writer.Write (position.z);
ctx.writer.Write (gridFlags);
}
public override void DeserializeNode (GraphSerializationContext ctx)
{
base.DeserializeNode (ctx);
position = new Int3(ctx.reader.ReadInt32(), ctx.reader.ReadInt32(), ctx.reader.ReadInt32());
gridFlags = ctx.reader.ReadUInt16();
}
}
}
| |
/*
* 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 log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Monitoring;
using OpenSim.Services.Interfaces;
using OpenSim.Server.Base;
using OpenMetaverse;
namespace OpenSim.Services.Connectors
{
public class XInventoryServicesConnector : BaseServiceConnector, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Number of requests made to the remote inventory service.
/// </summary>
public int RequestsMade { get; private set; }
private string m_ServerURI = String.Empty;
private object m_Lock = new object();
public XInventoryServicesConnector()
{
}
public XInventoryServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public XInventoryServicesConnector(IConfigSource source)
: base(source, "InventoryService")
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig assetConfig = source.Configs["InventoryService"];
if (assetConfig == null)
{
m_log.Error("[INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini");
throw new Exception("Inventory connector init error");
}
string serviceURI = assetConfig.GetString("InventoryServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[INVENTORY CONNECTOR]: No Server URI named in section InventoryService");
throw new Exception("Inventory connector init error");
}
m_ServerURI = serviceURI;
StatsManager.RegisterStat(
new Stat(
"RequestsMade",
"Requests made",
"Number of requests made to the remove inventory service",
"requests",
"inventory",
serviceURI,
StatType.Pull,
MeasuresOfInterest.AverageChangeOverTime,
s => s.Value = RequestsMade,
StatVerbosity.Debug));
}
private bool CheckReturn(Dictionary<string, object> ret)
{
if (ret == null)
return false;
if (ret.Count == 0)
return false;
if (ret.ContainsKey("RESULT"))
{
if (ret["RESULT"] is string)
{
bool result;
if (bool.TryParse((string)ret["RESULT"], out result))
return result;
return false;
}
}
return true;
}
public bool CreateUserInventory(UUID principalID)
{
Dictionary<string,object> ret = MakeRequest("CREATEUSERINVENTORY",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() }
});
return CheckReturn(ret);
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID principalID)
{
Dictionary<string,object> ret = MakeRequest("GETINVENTORYSKELETON",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() }
});
if (!CheckReturn(ret))
return null;
Dictionary<string, object> folders = (Dictionary<string, object>)ret["FOLDERS"];
List<InventoryFolderBase> fldrs = new List<InventoryFolderBase>();
try
{
foreach (Object o in folders.Values)
fldrs.Add(BuildFolder((Dictionary<string, object>)o));
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception unwrapping folder list: ", e);
}
return fldrs;
}
public InventoryFolderBase GetRootFolder(UUID principalID)
{
Dictionary<string,object> ret = MakeRequest("GETROOTFOLDER",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() }
});
if (!CheckReturn(ret))
return null;
return BuildFolder((Dictionary<string, object>)ret["folder"]);
}
public InventoryFolderBase GetFolderForType(UUID principalID, AssetType type)
{
Dictionary<string,object> ret = MakeRequest("GETFOLDERFORTYPE",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "TYPE", ((int)type).ToString() }
});
if (!CheckReturn(ret))
return null;
return BuildFolder((Dictionary<string, object>)ret["folder"]);
}
public InventoryCollection GetFolderContent(UUID principalID, UUID folderID)
{
InventoryCollection inventory = new InventoryCollection();
inventory.Folders = new List<InventoryFolderBase>();
inventory.Items = new List<InventoryItemBase>();
inventory.UserID = principalID;
try
{
Dictionary<string,object> ret = MakeRequest("GETFOLDERCONTENT",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "FOLDER", folderID.ToString() }
});
if (!CheckReturn(ret))
return null;
Dictionary<string,object> folders =
(Dictionary<string,object>)ret["FOLDERS"];
Dictionary<string,object> items =
(Dictionary<string,object>)ret["ITEMS"];
foreach (Object o in folders.Values) // getting the values directly, we don't care about the keys folder_i
inventory.Folders.Add(BuildFolder((Dictionary<string, object>)o));
foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i
inventory.Items.Add(BuildItem((Dictionary<string, object>)o));
}
catch (Exception e)
{
m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: Exception in GetFolderContent: {0}", e.Message);
}
return inventory;
}
public List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID)
{
Dictionary<string,object> ret = MakeRequest("GETFOLDERITEMS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "FOLDER", folderID.ToString() }
});
if (!CheckReturn(ret))
return null;
Dictionary<string, object> items = (Dictionary<string, object>)ret["ITEMS"];
List<InventoryItemBase> fitems = new List<InventoryItemBase>();
foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i
fitems.Add(BuildItem((Dictionary<string, object>)o));
return fitems;
}
public bool AddFolder(InventoryFolderBase folder)
{
Dictionary<string,object> ret = MakeRequest("ADDFOLDER",
new Dictionary<string,object> {
{ "ParentID", folder.ParentID.ToString() },
{ "Type", folder.Type.ToString() },
{ "Version", folder.Version.ToString() },
{ "Name", folder.Name.ToString() },
{ "Owner", folder.Owner.ToString() },
{ "ID", folder.ID.ToString() }
});
return CheckReturn(ret);
}
public bool UpdateFolder(InventoryFolderBase folder)
{
Dictionary<string,object> ret = MakeRequest("UPDATEFOLDER",
new Dictionary<string,object> {
{ "ParentID", folder.ParentID.ToString() },
{ "Type", folder.Type.ToString() },
{ "Version", folder.Version.ToString() },
{ "Name", folder.Name.ToString() },
{ "Owner", folder.Owner.ToString() },
{ "ID", folder.ID.ToString() }
});
return CheckReturn(ret);
}
public bool MoveFolder(InventoryFolderBase folder)
{
Dictionary<string,object> ret = MakeRequest("MOVEFOLDER",
new Dictionary<string,object> {
{ "ParentID", folder.ParentID.ToString() },
{ "ID", folder.ID.ToString() },
{ "PRINCIPAL", folder.Owner.ToString() }
});
return CheckReturn(ret);
}
public bool DeleteFolders(UUID principalID, List<UUID> folderIDs)
{
List<string> slist = new List<string>();
foreach (UUID f in folderIDs)
slist.Add(f.ToString());
Dictionary<string,object> ret = MakeRequest("DELETEFOLDERS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "FOLDERS", slist }
});
return CheckReturn(ret);
}
public bool PurgeFolder(InventoryFolderBase folder)
{
Dictionary<string,object> ret = MakeRequest("PURGEFOLDER",
new Dictionary<string,object> {
{ "ID", folder.ID.ToString() }
});
return CheckReturn(ret);
}
public bool AddItem(InventoryItemBase item)
{
if (item.CreatorData == null)
item.CreatorData = String.Empty;
Dictionary<string,object> ret = MakeRequest("ADDITEM",
new Dictionary<string,object> {
{ "AssetID", item.AssetID.ToString() },
{ "AssetType", item.AssetType.ToString() },
{ "Name", item.Name.ToString() },
{ "Owner", item.Owner.ToString() },
{ "ID", item.ID.ToString() },
{ "InvType", item.InvType.ToString() },
{ "Folder", item.Folder.ToString() },
{ "CreatorId", item.CreatorId.ToString() },
{ "CreatorData", item.CreatorData.ToString() },
{ "Description", item.Description.ToString() },
{ "NextPermissions", item.NextPermissions.ToString() },
{ "CurrentPermissions", item.CurrentPermissions.ToString() },
{ "BasePermissions", item.BasePermissions.ToString() },
{ "EveryOnePermissions", item.EveryOnePermissions.ToString() },
{ "GroupPermissions", item.GroupPermissions.ToString() },
{ "GroupID", item.GroupID.ToString() },
{ "GroupOwned", item.GroupOwned.ToString() },
{ "SalePrice", item.SalePrice.ToString() },
{ "SaleType", item.SaleType.ToString() },
{ "Flags", item.Flags.ToString() },
{ "CreationDate", item.CreationDate.ToString() }
});
return CheckReturn(ret);
}
public bool UpdateItem(InventoryItemBase item)
{
if (item.CreatorData == null)
item.CreatorData = String.Empty;
Dictionary<string,object> ret = MakeRequest("UPDATEITEM",
new Dictionary<string,object> {
{ "AssetID", item.AssetID.ToString() },
{ "AssetType", item.AssetType.ToString() },
{ "Name", item.Name.ToString() },
{ "Owner", item.Owner.ToString() },
{ "ID", item.ID.ToString() },
{ "InvType", item.InvType.ToString() },
{ "Folder", item.Folder.ToString() },
{ "CreatorId", item.CreatorId.ToString() },
{ "CreatorData", item.CreatorData.ToString() },
{ "Description", item.Description.ToString() },
{ "NextPermissions", item.NextPermissions.ToString() },
{ "CurrentPermissions", item.CurrentPermissions.ToString() },
{ "BasePermissions", item.BasePermissions.ToString() },
{ "EveryOnePermissions", item.EveryOnePermissions.ToString() },
{ "GroupPermissions", item.GroupPermissions.ToString() },
{ "GroupID", item.GroupID.ToString() },
{ "GroupOwned", item.GroupOwned.ToString() },
{ "SalePrice", item.SalePrice.ToString() },
{ "SaleType", item.SaleType.ToString() },
{ "Flags", item.Flags.ToString() },
{ "CreationDate", item.CreationDate.ToString() }
});
return CheckReturn(ret);
}
public bool MoveItems(UUID principalID, List<InventoryItemBase> items)
{
List<string> idlist = new List<string>();
List<string> destlist = new List<string>();
foreach (InventoryItemBase item in items)
{
idlist.Add(item.ID.ToString());
destlist.Add(item.Folder.ToString());
}
Dictionary<string,object> ret = MakeRequest("MOVEITEMS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "IDLIST", idlist },
{ "DESTLIST", destlist }
});
return CheckReturn(ret);
}
public bool DeleteItems(UUID principalID, List<UUID> itemIDs)
{
List<string> slist = new List<string>();
foreach (UUID f in itemIDs)
slist.Add(f.ToString());
Dictionary<string,object> ret = MakeRequest("DELETEITEMS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "ITEMS", slist }
});
return CheckReturn(ret);
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
try
{
Dictionary<string, object> ret = MakeRequest("GETITEM",
new Dictionary<string, object> {
{ "ID", item.ID.ToString() }
});
if (!CheckReturn(ret))
return null;
return BuildItem((Dictionary<string, object>)ret["item"]);
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception in GetItem: ", e);
}
return null;
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
try
{
Dictionary<string, object> ret = MakeRequest("GETFOLDER",
new Dictionary<string, object> {
{ "ID", folder.ID.ToString() }
});
if (!CheckReturn(ret))
return null;
return BuildFolder((Dictionary<string, object>)ret["folder"]);
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception in GetFolder: ", e);
}
return null;
}
public List<InventoryItemBase> GetActiveGestures(UUID principalID)
{
Dictionary<string,object> ret = MakeRequest("GETACTIVEGESTURES",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() }
});
if (!CheckReturn(ret))
return null;
List<InventoryItemBase> items = new List<InventoryItemBase>();
foreach (Object o in ((Dictionary<string,object>)ret["ITEMS"]).Values)
items.Add(BuildItem((Dictionary<string, object>)o));
return items;
}
public int GetAssetPermissions(UUID principalID, UUID assetID)
{
Dictionary<string,object> ret = MakeRequest("GETASSETPERMISSIONS",
new Dictionary<string,object> {
{ "PRINCIPAL", principalID.ToString() },
{ "ASSET", assetID.ToString() }
});
// We cannot use CheckReturn() here because valid values for RESULT are "false" (in the case of request failure) or an int
if (ret == null)
return 0;
if (ret.ContainsKey("RESULT"))
{
if (ret["RESULT"] is string)
{
int intResult;
if (int.TryParse ((string)ret["RESULT"], out intResult))
return intResult;
}
}
return 0;
}
public bool HasInventoryForUser(UUID principalID)
{
return false;
}
// Helpers
//
private Dictionary<string,object> MakeRequest(string method,
Dictionary<string,object> sendData)
{
// Add "METHOD" as the first key in the dictionary. This ensures that it will be
// visible even when using partial logging ("debug http all 5").
Dictionary<string, object> temp = sendData;
sendData = new Dictionary<string,object>{ { "METHOD", method } };
foreach (KeyValuePair<string, object> kvp in temp)
sendData.Add(kvp.Key, kvp.Value);
RequestsMade++;
string reply = string.Empty;
lock (m_Lock)
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/xinventory",
ServerUtils.BuildQueryString(sendData), m_Auth);
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(
reply);
return replyData;
}
private InventoryFolderBase BuildFolder(Dictionary<string,object> data)
{
InventoryFolderBase folder = new InventoryFolderBase();
try
{
folder.ParentID = new UUID(data["ParentID"].ToString());
folder.Type = short.Parse(data["Type"].ToString());
folder.Version = ushort.Parse(data["Version"].ToString());
folder.Name = data["Name"].ToString();
folder.Owner = new UUID(data["Owner"].ToString());
folder.ID = new UUID(data["ID"].ToString());
}
catch (Exception e)
{
m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception building folder: ", e);
}
return folder;
}
private InventoryItemBase BuildItem(Dictionary<string,object> data)
{
InventoryItemBase item = new InventoryItemBase();
try
{
item.AssetID = new UUID(data["AssetID"].ToString());
item.AssetType = int.Parse(data["AssetType"].ToString());
item.Name = data["Name"].ToString();
item.Owner = new UUID(data["Owner"].ToString());
item.ID = new UUID(data["ID"].ToString());
item.InvType = int.Parse(data["InvType"].ToString());
item.Folder = new UUID(data["Folder"].ToString());
item.CreatorId = data["CreatorId"].ToString();
if (data.ContainsKey("CreatorData"))
item.CreatorData = data["CreatorData"].ToString();
else
item.CreatorData = String.Empty;
item.Description = data["Description"].ToString();
item.NextPermissions = uint.Parse(data["NextPermissions"].ToString());
item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString());
item.BasePermissions = uint.Parse(data["BasePermissions"].ToString());
item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString());
item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString());
item.GroupID = new UUID(data["GroupID"].ToString());
item.GroupOwned = bool.Parse(data["GroupOwned"].ToString());
item.SalePrice = int.Parse(data["SalePrice"].ToString());
item.SaleType = byte.Parse(data["SaleType"].ToString());
item.Flags = uint.Parse(data["Flags"].ToString());
item.CreationDate = int.Parse(data["CreationDate"].ToString());
}
catch (Exception e)
{
m_log.Error("[XINVENTORY CONNECTOR]: Exception building item: ", e);
}
return item;
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.SimpleWorkflow.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SimpleWorkflow.Model.Internal.MarshallTransformations
{
/// <summary>
/// List Closed Workflow Executions Request Marshaller
/// </summary>
internal class ListClosedWorkflowExecutionsRequestMarshaller : IMarshaller<IRequest, ListClosedWorkflowExecutionsRequest>
{
public IRequest Marshall(ListClosedWorkflowExecutionsRequest listClosedWorkflowExecutionsRequest)
{
IRequest request = new DefaultRequest(listClosedWorkflowExecutionsRequest, "AmazonSimpleWorkflow");
string target = "SimpleWorkflowService.ListClosedWorkflowExecutions";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.0";
string uriResourcePath = "";
if (uriResourcePath.Contains("?"))
{
string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));
foreach (string s in queryString.Split('&', ';'))
{
string[] nameValuePair = s.Split('=');
if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
{
request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
}
else
{
request.Parameters.Add(nameValuePair[0], null);
}
}
}
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter())
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
if (listClosedWorkflowExecutionsRequest != null && listClosedWorkflowExecutionsRequest.IsSetDomain())
{
writer.WritePropertyName("domain");
writer.Write(listClosedWorkflowExecutionsRequest.Domain);
}
if (listClosedWorkflowExecutionsRequest != null)
{
ExecutionTimeFilter startTimeFilter = listClosedWorkflowExecutionsRequest.StartTimeFilter;
if (startTimeFilter != null)
{
writer.WritePropertyName("startTimeFilter");
writer.WriteObjectStart();
if (startTimeFilter != null && startTimeFilter.IsSetOldestDate())
{
writer.WritePropertyName("oldestDate");
writer.Write(startTimeFilter.OldestDate);
}
if (startTimeFilter != null && startTimeFilter.IsSetLatestDate())
{
writer.WritePropertyName("latestDate");
writer.Write(startTimeFilter.LatestDate);
}
writer.WriteObjectEnd();
}
}
if (listClosedWorkflowExecutionsRequest != null)
{
ExecutionTimeFilter closeTimeFilter = listClosedWorkflowExecutionsRequest.CloseTimeFilter;
if (closeTimeFilter != null)
{
writer.WritePropertyName("closeTimeFilter");
writer.WriteObjectStart();
if (closeTimeFilter != null && closeTimeFilter.IsSetOldestDate())
{
writer.WritePropertyName("oldestDate");
writer.Write(closeTimeFilter.OldestDate);
}
if (closeTimeFilter != null && closeTimeFilter.IsSetLatestDate())
{
writer.WritePropertyName("latestDate");
writer.Write(closeTimeFilter.LatestDate);
}
writer.WriteObjectEnd();
}
}
if (listClosedWorkflowExecutionsRequest != null)
{
WorkflowExecutionFilter executionFilter = listClosedWorkflowExecutionsRequest.ExecutionFilter;
if (executionFilter != null)
{
writer.WritePropertyName("executionFilter");
writer.WriteObjectStart();
if (executionFilter != null && executionFilter.IsSetWorkflowId())
{
writer.WritePropertyName("workflowId");
writer.Write(executionFilter.WorkflowId);
}
writer.WriteObjectEnd();
}
}
if (listClosedWorkflowExecutionsRequest != null)
{
CloseStatusFilter closeStatusFilter = listClosedWorkflowExecutionsRequest.CloseStatusFilter;
if (closeStatusFilter != null)
{
writer.WritePropertyName("closeStatusFilter");
writer.WriteObjectStart();
if (closeStatusFilter != null && closeStatusFilter.IsSetStatus())
{
writer.WritePropertyName("status");
writer.Write(closeStatusFilter.Status);
}
writer.WriteObjectEnd();
}
}
if (listClosedWorkflowExecutionsRequest != null)
{
WorkflowTypeFilter typeFilter = listClosedWorkflowExecutionsRequest.TypeFilter;
if (typeFilter != null)
{
writer.WritePropertyName("typeFilter");
writer.WriteObjectStart();
if (typeFilter != null && typeFilter.IsSetName())
{
writer.WritePropertyName("name");
writer.Write(typeFilter.Name);
}
if (typeFilter != null && typeFilter.IsSetVersion())
{
writer.WritePropertyName("version");
writer.Write(typeFilter.Version);
}
writer.WriteObjectEnd();
}
}
if (listClosedWorkflowExecutionsRequest != null)
{
TagFilter tagFilter = listClosedWorkflowExecutionsRequest.TagFilter;
if (tagFilter != null)
{
writer.WritePropertyName("tagFilter");
writer.WriteObjectStart();
if (tagFilter != null && tagFilter.IsSetTag())
{
writer.WritePropertyName("tag");
writer.Write(tagFilter.Tag);
}
writer.WriteObjectEnd();
}
}
if (listClosedWorkflowExecutionsRequest != null && listClosedWorkflowExecutionsRequest.IsSetNextPageToken())
{
writer.WritePropertyName("nextPageToken");
writer.Write(listClosedWorkflowExecutionsRequest.NextPageToken);
}
if (listClosedWorkflowExecutionsRequest != null && listClosedWorkflowExecutionsRequest.IsSetMaximumPageSize())
{
writer.WritePropertyName("maximumPageSize");
writer.Write(listClosedWorkflowExecutionsRequest.MaximumPageSize);
}
if (listClosedWorkflowExecutionsRequest != null && listClosedWorkflowExecutionsRequest.IsSetReverseOrder())
{
writer.WritePropertyName("reverseOrder");
writer.Write(listClosedWorkflowExecutionsRequest.ReverseOrder);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using HANDLE = System.IntPtr;
using HWND = System.IntPtr;
namespace LythumOSL.Core.Win32
{
public struct NETRESOURCE
{
public int dwScope;
public int dwType;
public int dwDisplayType;
public int dwUsage;
public string lpLocalName;
public string lpRemoteName;
public string lpComment;
public string lpProvider;
}
public struct USER_INFO_3
{
public int Name;
public int Password;
public int PasswordAge;
public int Privilege;
public int HomeDir;
public int Comment;
public int Flags;
public int ScriptPath;
public int AuthFlags;
public int FullName;
public int UserComment;
public int Parms;
public int Workstations;
public int LastLogon;
public int LastLogoff;
public int AcctExpires;
public int MaxStorage;
public int UnitsPerWeek;
public int LogonHours;
public int BadPwCount;
public int NumLogons;
public int LogonServer;
public int CountryCode;
public int CodePage;
public int UserID;
public int PrimaryGroupID;
public int Profile;
public int HomeDirDrive;
public int PasswordExpired;
}
public struct GROUP_INFO_2
{
public int Name;
public int Comment;
public int GroupID;
public int Attributes;
}
public struct LOCALGROUP_MEMBERS_INFO_0
{
public int pSID;
}
public struct LOCALGROUP_MEMBERS_INFO_1
{
public int pSID;
public g_netSID_NAME_USE eUsage;
public int psName;
}
public struct WKSTA_INFO_102
{
public int wki102_platform_id;
public int wki102_computername;
public int wki102_langroup;
public int wki102_ver_major;
public int wki102_ver_minor;
public int wki102_lanroot;
public int wki102_logged_on_users;
}
public struct WKSTA_USER_INFO_1
{
public int wkui1_username;
public int wkui1_logon_domain;
public int wkui1_oth_domains;
public int wkui1_logon_server;
}
public enum g_netSID_NAME_USE
{
SidTypeUser = 1,
SidTypeGroup = 2,
SidTypeDomain = 3,
SidTypeAlias = 4,
SidTypeWellKnownGroup = 5,
SidTypeDeletedAccount = 6,
SidTypeInvalid = 7,
SidTypeUnknown = 8,
}
public abstract class Mpr
{
[DllImport("mpr")] public static extern int WNetAddConnection(string lpszNetPath, string lpszPassword, string lpszLocalName);
[DllImport("mpr")] public static extern int WNetAddConnection2(ref NETRESOURCE lpNetResource, string lpPassword, string lpUserName, int dwFlags);
[DllImport("mpr")] public static extern int WNetCancelConnection(string lpszName, int bForce);
[DllImport("mpr")] public static extern int WNetCancelConnection2(string lpName, int dwFlags, int fForce);
[DllImport("mpr")] public static extern int WNetCloseEnum(HANDLE hEnum);
[DllImport("mpr")] public static extern int WNetConnectionDialog(HWND hwnd, int dwType);
[DllImport("mpr")] public static extern int WNetDisconnectDialog(HWND hwnd, int dwType);
[DllImport("mpr")] public static extern int WNetEnumResource(HANDLE hEnum, ref int lpcCount, ref NETRESOURCE lpBuffer, ref int lpBufferSize);
[DllImport("mpr")] public static extern int WNetGetConnection(string lpszLocalName, string lpszRemoteName, int cbRemoteName);
[DllImport("mpr")] public static extern int WNetGetLastError(int lpError, StringBuilder lpErrorBuf, int nErrorBufSize, string lpNameBuf, int nNameBufSize);
[DllImport("mpr")] public static extern int WNetGetUser(string lpName, StringBuilder lpUserName, ref int lpnLength);
[DllImport("mpr")] public static extern int WNetOpenEnum(int dwScope, int dwType, int dwUsage, ref NETRESOURCE lpNetResource, ref int lphEnum);
}
public abstract class NetApi
{
[DllImport("Netapi32")] public static extern int NetApiBufferFree(int lpBuffer);
[DllImport("Netapi32")] public static extern int NetRemoteTOD(IntPtr yServer, int pBuffer);
[DllImport("Netapi32")] public static extern int NetUserChangePassword(IntPtr Domain, IntPtr User, Byte OldPass, Byte NewPass);
[DllImport("Netapi32")] public static extern int NetUserGetGroups(IntPtr lpServer, Byte UserName, int Level, ref int lpBuffer, int PrefMaxLen, ref int lpEntriesRead, ref int lpTotalEntries);
[DllImport("Netapi32")] public static extern int NetUserGetInfo(IntPtr lpServer, Byte UserName, int Level, ref int lpBuffer);
[DllImport("Netapi32")] public static extern int NetUserGetLocalGroups(IntPtr lpServer, Byte UserName, int Level, int Flags, ref int lpBuffer, int MaxLen, ref int lpEntriesRead, ref int lpTotalEntries);
[DllImport("Netapi32")] public static extern int NetWkstaGetInfo(IntPtr lpServer, int Level, IntPtr lpBuffer);
[DllImport("Netapi32")] public static extern int NetWkstaUserGetInfo(IntPtr reserved, int Level, IntPtr lpBuffer);
[DllImport("netapi32")] public static extern int NetUserAdd(IntPtr lpServer, int Level, ref USER_INFO_3 lpUser, ref int lpError);
[DllImport("netapi32")] public static extern int NetLocalGroupDelMembers(int psServer, int psLocalGroup, int lLevel, ref LOCALGROUP_MEMBERS_INFO_0 uMember, int lMemberCount);
[DllImport("netapi32")] public static extern int NetLocalGroupGetMembers(int psServer, int psLocalGroup, int lLevel, int pBuffer, int lMaxLength, int plEntriesRead, int plTotalEntries, int phResume);
public const int CNLEN = 15;
public const int CONNECT_UPDATE_PROFILE = 0x1;
public const int FILTER_INTERDOMAIN_TRUST_ACCOUNT = 0x8;
public const int FILTER_NORMAL_ACCOUNT = 0x2;
public const int FILTER_PROXY_ACCOUNT = 0x4;
public const int FILTER_SERVER_TRUST_ACCOUNT = 0x20;
public const int FILTER_TEMP_DUPLICATE_ACCOUNT = 0x1;
public const int FILTER_WORKSTATION_TRUST_ACCOUNT = 0x10;
public const int GNLEN = UNLEN;
public const int LG_INCLUDE_INDIRECT = 0x1;
public const int LM20_PWLEN = 14;
public const int MAXCOMMENTSZ = 256;
public const int NERR_BASE = 2100;
public const int NERR_GroupExists = (NERR_BASE + 123);
public const int NERR_InvalidComputer = (NERR_BASE + 251);
public const int NERR_NotPrimary = (NERR_BASE + 126);
public const int NERR_PasswordTooShort = (NERR_BASE + 145);
public const int NERR_Success = 0;
public const int NERR_UserExists = (NERR_BASE + 124);
public const int PWLEN = 256;
public const int RESOURCEDISPLAYTYPE_DOMAIN = 0x1;
public const int RESOURCEDISPLAYTYPE_FILE = 0x4;
public const int RESOURCEDISPLAYTYPE_GENERIC = 0x0;
public const int RESOURCEDISPLAYTYPE_GROUP = 0x5;
public const int RESOURCEDISPLAYTYPE_SERVER = 0x2;
public const int RESOURCEDISPLAYTYPE_SHARE = 0x3;
public const int RESOURCETYPE_ANY = 0x0;
public const int RESOURCETYPE_DISK = 0x1;
public const int RESOURCETYPE_PRINT = 0x2;
public const int RESOURCETYPE_UNKNOWN = 0xFFFF;
public const int RESOURCEUSAGE_ALL = 0x0;
public const int RESOURCEUSAGE_CONNECTABLE = 0x1;
public const int RESOURCEUSAGE_CONTAINER = 0x2;
public const int RESOURCEUSAGE_RESERVED = unchecked((int)0x80000000);
public const int RESOURCE_CONNECTED = 0x1;
public const int RESOURCE_ENUM_ALL = 0xFFFF;
public const int RESOURCE_GLOBALNET = 0x2;
public const int RESOURCE_PUBLICNET = 0x2;
public const int RESOURCE_REMEMBERED = 0x3;
public const int TIMEQ_FOREVER = -1;
public const int UF_ACCOUNTDISABLE = 0x2;
public const int UF_HOMEDIR_REQUIRED = 0x8;
public const int UF_LOCKOUT = 0x10;
public const int UF_PASSWD_CANT_CHANGE = 0x40;
public const int UF_PASSWD_NOTREQD = 0x20;
public const int UF_SCRIPT = 0x1;
public const int UNITS_PER_DAY = 24;
public const int UNITS_PER_WEEK = UNITS_PER_DAY * 7;
public const int UNLEN = 256;
public const int USER_MAXSTORAGE_UNLIMITED = -1;
public const int USER_NO_LOGOFF = -1;
public const int USER_PRIV_ADMIN = 2;
public const int USER_PRIV_GUEST = 0;
public const int USER_PRIV_MASK = 3;
public const int USER_PRIV_USER = 1;
public const int WN_ACCESS_DENIED = ERROR.ERROR_ACCESS_DENIED;
public const int WN_ALREADY_CONNECTED = ERROR.ERROR_ALREADY_ASSIGNED;
public const int WN_BAD_LOCALNAME = ERROR.ERROR_BAD_DEVICE;
public const int WN_BAD_NETNAME = ERROR.ERROR_BAD_NET_NAME;
public const int WN_BAD_PASSWORD = ERROR.ERROR_INVALID_PASSWORD;
public const int WN_BAD_POINTER = ERROR.ERROR_INVALID_ADDRESS;
public const int WN_BAD_PROFILE = ERROR.ERROR_BAD_PROFILE;
public const int WN_BAD_PROVIDER = ERROR.ERROR_BAD_PROVIDER;
public const int WN_BAD_USER = ERROR.ERROR_BAD_USERNAME;
public const int WN_BAD_VALUE = ERROR.ERROR_INVALID_PARAMETER;
public const int WN_CANNOT_OPEN_PROFILE = ERROR.ERROR_CANNOT_OPEN_PROFILE;
public const int WN_CONNECTION_CLOSED = ERROR.ERROR_CONNECTION_UNAVAIL;
public const int WN_DEVICE_ERROR = ERROR.ERROR_GEN_FAILURE;
public const int WN_DEVICE_IN_USE = ERROR.ERROR_DEVICE_IN_USE;
public const int WN_EXTENDED_ERROR = ERROR.ERROR_EXTENDED_ERROR;
public const int WN_FUNCTION_BUSY = ERROR.ERROR_BUSY;
public const int WN_MORE_DATA = ERROR.ERROR_MORE_DATA;
public const int WN_NET_ERROR = ERROR.ERROR_UNEXP_NET_ERR;
public const int WN_NOT_CONNECTED = ERROR.ERROR_NOT_CONNECTED;
public const int WN_NOT_SUPPORTED = ERROR.ERROR_NOT_SUPPORTED;
public const int WN_NO_NETWORK = ERROR.ERROR_NO_NETWORK;
public const int WN_NO_NET_OR_BAD_PATH = ERROR.ERROR_NO_NET_OR_BAD_PATH;
public const int WN_OPEN_FILES = ERROR.ERROR_OPEN_FILES;
public const int WN_OUT_OF_MEMORY = ERROR.ERROR_NOT_ENOUGH_MEMORY;
public const int WN_SUCCESS = ERROR.NO_ERROR;
public const int WN_WINDOWS_ERROR = ERROR.ERROR_UNEXP_NET_ERR;
}
}
| |
using System;
using System.Collections;
using System.Reflection;
using XmlRpcLight.Attributes;
using XmlRpcLight.DataTypes;
using XmlRpcLight.Enums;
namespace XmlRpcLight {
public class XmlRpcServiceInfo
{
public static XmlRpcServiceInfo CreateServiceInfo(Type type)
{
XmlRpcServiceInfo svcInfo = new XmlRpcServiceInfo();
// extract service info
XmlRpcServiceAttribute svcAttr = (XmlRpcServiceAttribute)
Attribute.GetCustomAttribute(type, typeof(XmlRpcServiceAttribute));
if (svcAttr != null && svcAttr.Description != "")
svcInfo.doc = svcAttr.Description;
if (svcAttr != null && svcAttr.Name != "")
svcInfo.Name = svcAttr.Name;
else
svcInfo.Name = type.Name;
// extract method info
Hashtable methods = new Hashtable();
foreach (Type itf in type.GetInterfaces())
{
XmlRpcServiceAttribute itfAttr = (XmlRpcServiceAttribute)
Attribute.GetCustomAttribute(itf, typeof(XmlRpcServiceAttribute));
if (itfAttr != null)
svcInfo.doc = itfAttr.Description;
#if (!COMPACT_FRAMEWORK)
InterfaceMapping imap = type.GetInterfaceMap(itf);
foreach (MethodInfo mi in imap.InterfaceMethods)
{
ExtractMethodInfo(methods, mi, itf);
}
#else
foreach (MethodInfo mi in itf.GetMethods())
{
ExtractMethodInfo(methods, mi, itf);
}
#endif
}
foreach (MethodInfo mi in type.GetMethods())
{
ArrayList mthds = new ArrayList();
mthds.Add(mi);
MethodInfo curMi = mi;
while (true)
{
MethodInfo baseMi = curMi.GetBaseDefinition();
if (baseMi.DeclaringType == curMi.DeclaringType)
break;
mthds.Insert(0, baseMi);
curMi = baseMi;
}
foreach (MethodInfo mthd in mthds)
{
ExtractMethodInfo(methods, mthd, type);
}
}
svcInfo.methodInfos = new XmlRpcMethodInfo[methods.Count];
methods.Values.CopyTo(svcInfo.methodInfos, 0);
Array.Sort(svcInfo.methodInfos);
return svcInfo;
}
static void ExtractMethodInfo(Hashtable methods, MethodInfo mi, Type type)
{
XmlRpcMethodAttribute attr = (XmlRpcMethodAttribute)
Attribute.GetCustomAttribute(mi,
typeof(XmlRpcMethodAttribute));
if (attr == null)
return;
XmlRpcMethodInfo mthdInfo = new XmlRpcMethodInfo();
mthdInfo.MethodInfo = mi;
mthdInfo.XmlRpcName = GetXmlRpcMethodName(mi);
mthdInfo.MiName = mi.Name;
mthdInfo.Doc = attr.Description;
mthdInfo.IsHidden = attr.IntrospectionMethod | attr.Hidden;
// extract parameters information
ArrayList parmList = new ArrayList();
ParameterInfo[] parms = mi.GetParameters();
foreach (ParameterInfo parm in parms)
{
XmlRpcParameterInfo parmInfo = new XmlRpcParameterInfo();
parmInfo.Name = parm.Name;
parmInfo.Type = parm.ParameterType;
parmInfo.XmlRpcType = GetXmlRpcTypeString(parm.ParameterType);
// retrieve optional attributed info
parmInfo.Doc = "";
XmlRpcParameterAttribute pattr = (XmlRpcParameterAttribute)
Attribute.GetCustomAttribute(parm,
typeof(XmlRpcParameterAttribute));
if (pattr != null)
{
parmInfo.Doc = pattr.Description;
parmInfo.XmlRpcName = pattr.Name;
}
parmInfo.IsParams = Attribute.IsDefined(parm,
typeof(ParamArrayAttribute));
parmList.Add(parmInfo);
}
mthdInfo.Parameters = (XmlRpcParameterInfo[])
parmList.ToArray(typeof(XmlRpcParameterInfo));
// extract return type information
mthdInfo.ReturnType = mi.ReturnType;
mthdInfo.ReturnXmlRpcType = GetXmlRpcTypeString(mi.ReturnType);
object[] orattrs = mi.ReturnTypeCustomAttributes.GetCustomAttributes(
typeof(XmlRpcReturnValueAttribute), false);
if (orattrs.Length > 0)
{
mthdInfo.ReturnDoc = ((XmlRpcReturnValueAttribute)orattrs[0]).Description;
}
if (methods[mthdInfo.XmlRpcName] != null)
{
throw new XmlRpcDupXmlRpcMethodNames(String.Format("Method "
+ "{0} in type {1} has duplicate XmlRpc method name {2}",
mi.Name, type.Name, mthdInfo.XmlRpcName));
}
else
methods.Add(mthdInfo.XmlRpcName, mthdInfo);
}
public MethodInfo GetMethodInfo(string xmlRpcMethodName)
{
foreach (XmlRpcMethodInfo xmi in methodInfos)
{
if (xmlRpcMethodName == xmi.XmlRpcName)
{
return xmi.MethodInfo;
}
}
return null;
}
static bool IsVisibleXmlRpcMethod(MethodInfo mi)
{
bool ret = false;
Attribute attr = Attribute.GetCustomAttribute(mi,
typeof(XmlRpcMethodAttribute));
if (attr != null)
{
XmlRpcMethodAttribute mattr = (XmlRpcMethodAttribute)attr;
ret = !(mattr.Hidden || mattr.IntrospectionMethod == true);
}
return ret;
}
public static string GetXmlRpcMethodName(MethodInfo mi)
{
XmlRpcMethodAttribute attr = (XmlRpcMethodAttribute)
Attribute.GetCustomAttribute(mi,
typeof(XmlRpcMethodAttribute));
if (attr != null
&& attr.Method != null
&& attr.Method != "")
{
return attr.Method;
}
else
{
return mi.Name;
}
}
public string GetMethodName(string XmlRpcMethodName)
{
foreach (XmlRpcMethodInfo methodInfo in methodInfos)
{
if (methodInfo.XmlRpcName == XmlRpcMethodName)
return methodInfo.MiName;
}
return null;
}
public String Doc
{
get { return doc; }
set { doc = value; }
}
public String Name
{
get { return name; }
set { name = value; }
}
public XmlRpcMethodInfo[] Methods
{
get { return methodInfos; }
}
public XmlRpcMethodInfo GetMethod(
String methodName)
{
foreach (XmlRpcMethodInfo mthdInfo in methodInfos)
{
if (mthdInfo.XmlRpcName == methodName)
return mthdInfo;
}
return null;
}
private XmlRpcServiceInfo()
{
}
public static XmlRpcType GetXmlRpcType(Type t)
{
return GetXmlRpcType(t, new Stack());
}
private static XmlRpcType GetXmlRpcType(Type t, Stack typeStack)
{
XmlRpcType ret;
if (t == typeof(Int32))
ret = XmlRpcType.tInt32;
else if (t == typeof(XmlRpcInt))
ret = XmlRpcType.tInt32;
else if (t == typeof(Int64))
ret = XmlRpcType.tInt64;
else if (t == typeof(Boolean))
ret = XmlRpcType.tBoolean;
else if (t == typeof(XmlRpcBoolean))
ret = XmlRpcType.tBoolean;
else if (t == typeof(String))
ret = XmlRpcType.tString;
else if (t == typeof(Double))
ret = XmlRpcType.tDouble;
else if (t == typeof(XmlRpcDouble))
ret = XmlRpcType.tDouble;
else if (t == typeof(DateTime))
ret = XmlRpcType.tDateTime;
else if (t == typeof(XmlRpcDateTime))
ret = XmlRpcType.tDateTime;
else if (t == typeof(byte[]))
ret = XmlRpcType.tBase64;
else if (t == typeof(XmlRpcStruct))
{
ret = XmlRpcType.tHashtable;
}
else if (t == typeof(Array))
ret = XmlRpcType.tArray;
else if (t.IsArray)
{
#if (!COMPACT_FRAMEWORK)
Type elemType = t.GetElementType();
if (elemType != typeof(Object)
&& GetXmlRpcType(elemType, typeStack) == XmlRpcType.tInvalid)
{
ret = XmlRpcType.tInvalid;
}
else
{
if (t.GetArrayRank() == 1) // single dim array
ret = XmlRpcType.tArray;
else
ret = XmlRpcType.tMultiDimArray;
}
#else
//!! check types of array elements if not Object[]
Type elemType = null;
string[] checkSingleDim = Regex.Split(t.FullName, "\\[\\]$");
if (checkSingleDim.Length > 1) // single dim array
{
elemType = Type.GetType(checkSingleDim[0]);
ret = XmlRpcType.tArray;
}
else
{
string[] checkMultiDim = Regex.Split(t.FullName, "\\[,[,]*\\]$");
if (checkMultiDim.Length > 1)
{
elemType = Type.GetType(checkMultiDim[0]);
ret = XmlRpcType.tMultiDimArray;
}
else
ret = XmlRpcType.tInvalid;
}
if (elemType != null)
{
if (elemType != typeof(Object)
&& GetXmlRpcType(elemType, typeStack) == XmlRpcType.tInvalid)
{
ret = XmlRpcType.tInvalid;
}
}
#endif
}
#if !FX1_0
else if (t == typeof(int?))
ret = XmlRpcType.tInt32;
else if (t == typeof(long?))
ret = XmlRpcType.tInt64;
else if (t == typeof(Boolean?))
ret = XmlRpcType.tBoolean;
else if (t == typeof(Double?))
ret = XmlRpcType.tDouble;
else if (t == typeof(DateTime?))
ret = XmlRpcType.tDateTime;
#endif
else if (t == typeof(void))
{
ret = XmlRpcType.tVoid;
}
else if ((t.IsValueType && !t.IsPrimitive && !t.IsEnum)
|| t.IsClass)
{
// if type is struct or class its only valid for XML-RPC mapping if all
// its members have a valid mapping or are of type object which
// maps to any XML-RPC type
MemberInfo[] mis = t.GetMembers();
foreach (MemberInfo mi in mis)
{
if (mi.MemberType == MemberTypes.Field)
{
FieldInfo fi = (FieldInfo)mi;
if (typeStack.Contains(fi.FieldType))
continue;
try
{
typeStack.Push(fi.FieldType);
if ((fi.FieldType != typeof(Object)
&& GetXmlRpcType(fi.FieldType, typeStack) == XmlRpcType.tInvalid))
{
return XmlRpcType.tInvalid;
}
}
finally
{
typeStack.Pop();
}
}
else if (mi.MemberType == MemberTypes.Property)
{
PropertyInfo pi = (PropertyInfo)mi;
if (typeStack.Contains(pi.PropertyType))
continue;
try
{
typeStack.Push(pi.PropertyType);
if ((pi.PropertyType != typeof(Object)
&& GetXmlRpcType(pi.PropertyType, typeStack) == XmlRpcType.tInvalid))
{
return XmlRpcType.tInvalid;
}
}
finally
{
typeStack.Pop();
}
}
}
ret = XmlRpcType.tStruct;
}
else
ret = XmlRpcType.tInvalid;
return ret;
}
static public string GetXmlRpcTypeString(Type t)
{
XmlRpcType rpcType = GetXmlRpcType(t);
return GetXmlRpcTypeString(rpcType);
}
static public string GetXmlRpcTypeString(XmlRpcType t)
{
string ret = null;
if (t == XmlRpcType.tInt32)
ret = "integer";
else if (t == XmlRpcType.tInt64)
ret = "i8";
else if (t == XmlRpcType.tBoolean)
ret = "boolean";
else if (t == XmlRpcType.tString)
ret = "string";
else if (t == XmlRpcType.tDouble)
ret = "double";
else if (t == XmlRpcType.tDateTime)
ret = "dateTime";
else if (t == XmlRpcType.tBase64)
ret = "base64";
else if (t == XmlRpcType.tStruct)
ret = "struct";
else if (t == XmlRpcType.tHashtable)
ret = "struct";
else if (t == XmlRpcType.tArray)
ret = "array";
else if (t == XmlRpcType.tMultiDimArray)
ret = "array";
else if (t == XmlRpcType.tVoid)
ret = "void";
else
ret = null;
return ret;
}
XmlRpcMethodInfo[] methodInfos;
String doc;
string name;
}
}
| |
// ArrayList.cs
// Script#/Libraries/CoreLib
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace System.Collections {
// NOTE: Keep in sync with Array and List
/// <summary>
/// Equivalent to the Array type in Javascript.
/// </summary>
[ScriptIgnoreNamespace]
[ScriptImport]
[ScriptName("Array")]
public sealed class ArrayList : IEnumerable {
public ArrayList() {
}
public ArrayList(int capacity) {
}
public ArrayList(params object[] items) {
}
[ScriptField]
[ScriptName("length")]
public int Count {
get {
return 0;
}
}
[ScriptField]
public object this[int index] {
get {
return null;
}
set {
}
}
[ScriptName("push")]
public void Add(object item) {
}
[ScriptName("push")]
public void AddRange(params object[] items) {
}
public void Clear() {
}
public ArrayList Concat(params object[] objects) {
return null;
}
public bool Contains(object item) {
return false;
}
public bool Every(ArrayFilterCallback filterCallback) {
return false;
}
public bool Every(ArrayItemFilterCallback itemFilterCallback) {
return false;
}
public Array Filter(ArrayFilterCallback filterCallback) {
return null;
}
public Array Filter(ArrayItemFilterCallback itemFilterCallback) {
return null;
}
public void ForEach(ArrayCallback callback) {
}
public void ForEach(ArrayItemCallback itemCallback) {
}
public IEnumerator GetEnumerator() {
return null;
}
public Array GetRange(int index) {
return null;
}
public Array GetRange(int index, int count) {
return null;
}
public int IndexOf(object item) {
return 0;
}
public int IndexOf(object item, int startIndex) {
return 0;
}
public void Insert(int index, object item) {
}
public void InsertRange(int index, params object[] items) {
}
public string Join() {
return null;
}
public string Join(string delimiter) {
return null;
}
public int LastIndexOf(object item) {
return 0;
}
public int LastIndexOf(object item, int fromIndex) {
return 0;
}
public Array Map(ArrayMapCallback mapCallback) {
return null;
}
public Array Map(ArrayItemMapCallback mapItemCallback) {
return null;
}
public static ArrayList Parse(string s) {
return null;
}
public object Reduce(ArrayReduceCallback callback) {
return null;
}
public object Reduce(ArrayReduceCallback callback, object initialValue) {
return null;
}
public object Reduce(ArrayItemReduceCallback callback) {
return null;
}
public object Reduce(ArrayItemReduceCallback callback, object initialValue) {
return null;
}
public object ReduceRight(ArrayReduceCallback callback) {
return null;
}
public object ReduceRight(ArrayReduceCallback callback, object initialValue) {
return null;
}
public object ReduceRight(ArrayItemReduceCallback callback) {
return null;
}
public object ReduceRight(ArrayItemReduceCallback callback, object initialValue) {
return null;
}
[ScriptAlias("ss.remove")]
public bool Remove(object item) {
return false;
}
public void RemoveAt(int index) {
}
public Array RemoveRange(int index, int count) {
return null;
}
public void Reverse() {
}
public object Shift() {
return null;
}
public Array Slice(int start) {
return null;
}
public Array Slice(int start, int end) {
return null;
}
public bool Some(ArrayFilterCallback filterCallback) {
return false;
}
public bool Some(ArrayItemFilterCallback itemFilterCallback) {
return false;
}
public void Sort() {
}
public void Sort(CompareCallback compareCallback) {
}
public void Splice(int start, int deleteCount) {
}
public void Splice(int start, int deleteCount, params object[] itemsToInsert) {
}
public void Unshift(params object[] items) {
}
public static implicit operator Array(ArrayList list) {
return null;
}
public static implicit operator object[](ArrayList list) {
return null;
}
public static implicit operator List<object>(ArrayList list) {
return null;
}
public static explicit operator ArrayList(object[] array) {
return null;
}
}
}
| |
// Public domain by Christopher Diggins
// See: http://research.microsoft.com/Users/luca/Papers/BasicTypechecking.pdf
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace Cat
{
public class Pair<T>
{
public T First;
public T Second;
public Pair(T first, T second)
{
First = first;
Second = second;
}
}
public class VarNameList : List<String>
{
public new void Add(string s)
{
if (Contains(s))
return;
base.Add(s);
}
public void Add(Var v)
{
Add(v.ToString());
}
public bool Contains(Var v)
{
return base.Contains(v.ToString());
}
public new void AddRange(IEnumerable<string> strings)
{
foreach (string s in strings)
Add(s);
}
public override string ToString()
{
string ret = "";
foreach (string s in this)
ret += s + ";";
return ret;
}
}
public class VarNameMap : Dictionary<string, string>
{
public bool AreVarsEqual(Var x, Var y)
{
string s = x.ToString();
if (ContainsKey(s))
return this[s].Equals(y.ToString());
else
{
Add(s, y.ToString());
return true;
}
}
}
public class VarList : List<Var>
{
public VarList(VarList x)
: base(x)
{ }
public VarList(IEnumerable<Var> x)
: base(x)
{ }
public VarList()
{ }
public new void Add(Var v)
{
if (!Contains(v))
base.Add(v);
}
public new void AddRange(IEnumerable<Var> list)
{
foreach (Var v in list)
this.Add(v);
}
public override string ToString()
{
string ret = "";
foreach (Var v in this)
ret += v.ToString() + ";";
return ret;
}
}
public abstract class Constraint
{
public virtual IEnumerable<Constraint> GetSubConstraints()
{
yield return this;
}
public bool EqualsVar(string s)
{
if (!(this is Var))
return false;
return ToString().Equals(s);
}
public VarNameList GetAllVarNames()
{
VarNameList vars = new VarNameList();
foreach (Constraint c in GetSubConstraints())
if (c is Var)
vars.Add(c as Var);
return vars;
}
public VarList GetAllVars()
{
VarList vars = new VarList();
foreach (Constraint c in GetSubConstraints())
if (c is Var)
vars.Add(c as Var);
return vars;
}
public abstract Constraint Clone();
public abstract bool Equals(Constraint c, VarNameMap vars);
}
public abstract class Var : Constraint
{
protected string m;
public Var(string s)
{
m = s;
}
public override string ToString()
{
return m;
}
public void Rename(string s)
{
m = s;
}
public override bool Equals(Constraint c, VarNameMap vars)
{
if (!(c is Var))
return false;
return vars.AreVarsEqual(this, c as Var);
}
}
public class ScalarVar : Var
{
public ScalarVar(string s)
: base(s)
{
}
public override Constraint Clone()
{
return new ScalarVar(m);
}
}
public class VectorVar : Var
{
public VectorVar(string s)
: base(s)
{
}
public override Constraint Clone()
{
return new VectorVar(m);
}
}
public class Constant : Constraint
{
string m;
public Constant(string s)
{
m = s;
}
public override string ToString()
{
return m;
}
public override Constraint Clone()
{
return new Constant(m);
}
public override bool Equals(Constraint c, VarNameMap vars)
{
if (!(c is Constant))
return false;
return ToString().Equals(c.ToString());
}
}
public class RecursiveRelation : Constraint
{
public RecursiveRelation()
{
}
public override Constraint Clone()
{
return this;
}
public override bool Equals(Constraint c, VarNameMap vars)
{
return c is RecursiveRelation;
}
}
public class Relation : Constraint
{
Vector mLeft;
Vector mRight;
VarNameList mGenerics;
Relation mParent = null;
VarNameList mChildNonGenerics = new VarNameList();
public Relation(Vector left, Vector right)
{
mLeft = left;
mRight = right;
}
public void UnrollRecursiveRelations()
{
foreach (Relation r in GetChildRelations())
r.UnrollRecursiveRelations();
for (int i=0; i < GetLeft().GetCount(); ++i)
if (GetLeft().GetConstraint(i) is RecursiveRelation)
GetLeft().ReplaceConstraint(i, Clone());
for (int i=0; i < GetRight().GetCount(); ++i)
if (GetRight().GetConstraint(i) is RecursiveRelation)
GetRight().ReplaceConstraint(i, Clone());
}
private bool CanRollupRelation(Constraint child)
{
VarNameMap map = new VarNameMap();
if (!(child is Relation))
return false;
Relation childRel = child as Relation;
int n = GetLeft().GetCount();
if (n != childRel.GetLeft().GetCount())
return false;
for (int i = 0; i < n; ++i)
{
Constraint tmp = GetLeft(i);
Constraint childTmp = childRel.GetLeft(i);
if (tmp != child)
{
if (!tmp.Equals(childTmp, map))
return false;
}
else
{
if (!(childTmp is RecursiveRelation))
return false;
}
}
n = GetRight().GetCount();
if (n != childRel.GetRight().GetCount())
return false;
for (int i = 0; i < n; ++i)
{
Constraint tmp = GetRight(i);
Constraint childTmp = childRel.GetRight(i);
if (tmp != child)
{
if (!tmp.Equals(childTmp, map))
return false;
}
else
{
if (!(childTmp is RecursiveRelation))
return false;
}
}
return true;
}
/// <summary>
/// We want to compact any recursive relations as much as possible, for example:
/// ('A ('A self -> 'B) -> 'B) should become ('A self -> 'B)
/// This process is called rolling up the recursion.
/// This way we can compare the relations to see if they are the same.
/// </summary>
public void RollupRecursiveRelations()
{
foreach (Relation r in GetChildRelations())
r.RollupRecursiveRelations();
for (int i = 0; i < GetLeft().GetCount(); ++i)
if (CanRollupRelation(GetLeft().GetConstraint(i)))
GetLeft().ReplaceConstraint(i, new RecursiveRelation());
for (int i = 0; i < GetRight().GetCount(); ++i)
if (CanRollupRelation(GetRight().GetConstraint(i)))
GetRight().ReplaceConstraint(i, new RecursiveRelation());
}
public Vector GetLeft()
{
return mLeft;
}
public Vector GetRight()
{
return mRight;
}
public Constraint GetLeft(int n)
{
return mLeft.GetConstraint(n);
}
public Constraint GetRight(int n)
{
return mRight.GetConstraint(n);
}
public override string ToString()
{
return mLeft.ToString() + "->" + mRight.ToString();
}
public IEnumerable<Relation> GetChildRelations()
{
foreach (Constraint c in GetChildConstraints())
if (c is Relation)
yield return c as Relation;
}
public IEnumerable<Constraint> GetChildConstraints()
{
foreach (Constraint c in mLeft)
{
Trace.Assert(!(c is Vector));
yield return c;
}
foreach (Constraint c in mRight)
{
Trace.Assert(!(c is Vector));
yield return c;
}
}
public override IEnumerable<Constraint> GetSubConstraints()
{
foreach (Constraint c in mLeft.GetSubConstraints())
yield return c;
foreach (Constraint c in mRight.GetSubConstraints())
yield return c;
}
/// <summary>
/// This has to be called after all of their parent pointers have been set.
/// </summary>
public void ComputeGenericVars()
{
Trace.Assert(mChildNonGenerics != null);
Trace.Assert(mGenerics == null);
mGenerics = new VarNameList();
foreach (Constraint c in GetSubConstraints())
{
if (c is Var)
{
Var v = c as Var;
if (!IsNonGenericVar(v))
mGenerics.Add(v);
}
}
}
public bool IsNonGenericVar(Var v)
{
if (mParent == null)
return false;
if (mParent.mChildNonGenerics.Contains(v))
return true;
return mParent.IsNonGenericVar(v);
}
public bool IsSubRelation(Relation r)
{
foreach (Constraint c in GetSubConstraints())
if (c == r)
return true;
return false;
}
public VarNameList GetGenericVars()
{
ComputeGenericVars();
return mGenerics;
}
public override Constraint Clone()
{
return new Relation(mLeft.Clone() as Vector, mRight.Clone() as Vector);
}
public VarNameList GetNonGenericsForChildren()
{
return mChildNonGenerics;
}
public void SetParent(Relation parent)
{
Trace.Assert(mParent == null);
mParent = parent;
}
public Relation GetParent()
{
return mParent;
}
public override bool Equals(Constraint c, VarNameMap vars)
{
if (!(c is Relation))
return false;
Relation r = c as Relation;
return mLeft.Equals(r.mLeft, vars) && mRight.Equals(r.mRight, vars);
}
public static bool AreRelationsEqual(Relation r1, Relation r2)
{
return r1.Equals(r2, new VarNameMap());
}
}
public class Vector : Constraint
{
List<Constraint> mList;
public Vector(IEnumerable<Constraint> list)
{
mList = new List<Constraint>(list);
}
public Vector(List<Constraint> list)
{
mList = list;
}
public Vector()
{
mList = new List<Constraint>();
}
public Constraint GetFirst()
{
return mList[0];
}
public int IndexOf(Constraint c)
{
return mList.IndexOf(c);
}
public Vector GetRest()
{
return new Vector(mList.GetRange(1, mList.Count - 1));
}
public override string ToString()
{
string ret = "(";
for (int i = mList.Count - 1; i >= 0; --i)
{
if (i < mList.Count - 1) ret += " ";
ret += mList[i].ToString();
}
ret += ")";
return ret;
}
public bool IsEmpty()
{
return mList.Count == 0;
}
public int GetCount()
{
return mList.Count;
}
public override IEnumerable<Constraint> GetSubConstraints()
{
foreach (Constraint c in mList)
foreach (Constraint d in c.GetSubConstraints())
yield return d;
}
public int GetSubConstraintCount()
{
int ret = 0;
foreach (Constraint c in GetSubConstraints())
{
// artificial check to remove unused variable warning.
if (c != null) ++ret;
}
return ret;
}
public void Add(Constraint c)
{
if (c is Vector)
{
Vector vec = c as Vector;
foreach (Constraint child in vec)
mList.Add(child);
}
else
{
mList.Add(c);
}
}
public IEnumerator<Constraint> GetEnumerator()
{
return mList.GetEnumerator();
}
public void Insert(int n, Constraint constraint)
{
mList.Insert(n, constraint);
}
public override Constraint Clone()
{
List<Constraint> tmp = new List<Constraint>();
foreach (Constraint c in this)
tmp.Add(c.Clone());
return new Vector(tmp);
}
public Constraint GetConstraint(int i)
{
return mList[i];
}
public void ReplaceConstraint(int i, Constraint constraint)
{
mList[i] = constraint;
}
public override bool Equals(Constraint c, VarNameMap vars)
{
if (!(c is Vector))
return false;
Vector v = c as Vector;
int n = v.GetCount();
if (n != GetCount())
return false;
for (int i = 0; i < n; ++i)
{
Constraint c1 = GetConstraint(i);
Constraint c2 = v.GetConstraint(i);
if (!c1.Equals(c2, vars))
return false;
}
return true;
}
}
public class ConstraintList : List<Constraint>
{
Constraint mUnifier;
public ConstraintList(IEnumerable<Constraint> a)
: base(a)
{ }
public ConstraintList()
: base()
{ }
public override string ToString()
{
string ret = "";
for (int i = 0; i < Count; ++i)
{
if (i > 0) ret += " = ";
ret += this[i].ToString();
}
if (mUnifier != null)
ret += "; unifier = " + mUnifier.ToString();
return ret;
}
public Vector ChooseBetterVectorUnifier(Vector v1, Vector v2)
{
if (v1.GetCount() > v2.GetCount())
{
return v1;
}
else if (v1.GetCount() < v2.GetCount())
{
return v2;
}
else if (v1.GetSubConstraintCount() >= v2.GetSubConstraintCount())
{
return v1;
}
else
{
return v2;
}
}
public Constraint ChooseBetterUnifier(Constraint c1, Constraint c2)
{
Trace.Assert(c1 != null);
Trace.Assert(c2 != null);
Trace.Assert(c1 != c2);
if (c1 is RecursiveRelation)
{
return c1;
}
else if (c2 is RecursiveRelation)
{
return c2;
}
else if (c1 is Var)
{
return c2;
}
else if (c2 is Var)
{
return c1;
}
else if (c1 is Constant)
{
return c1;
}
else if (c2 is Constant)
{
return c2;
}
else if ((c1 is Vector) && (c2 is Vector))
{
return ChooseBetterVectorUnifier(c1 as Vector, c2 as Vector);
}
else
{
return c1;
}
}
public void ComputeUnifier()
{
if (Count == 0)
throw new Exception("Can not compute unifier for an empty list");
mUnifier = this[0];
for (int i = 1; i < Count; ++i)
mUnifier = ChooseBetterUnifier(mUnifier, this[i]);
}
public Constraint GetUnifier()
{
if (mUnifier == null)
throw new Exception("Unifier hasn't been computed yet");
return mUnifier;
}
public bool ContainsVar(string s)
{
foreach (Constraint c in this)
if (c.EqualsVar(s))
return true;
return false;
}
}
}
| |
/*
* 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.Diagnostics;
using System.Linq;
using System.Text;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework.Monitoring.Interfaces;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Collects sim statistics which aren't already being collected for the linden viewer's statistics pane
/// </summary>
public class SimExtraStatsCollector : BaseStatsCollector
{
// private long assetsInCache;
// private long texturesInCache;
// private long assetCacheMemoryUsage;
// private long textureCacheMemoryUsage;
// private TimeSpan assetRequestTimeAfterCacheMiss;
// private long blockedMissingTextureRequests;
// private long assetServiceRequestFailures;
// private long inventoryServiceRetrievalFailures;
private volatile float timeDilation;
private volatile float simFps;
private volatile float physicsFps;
private volatile float agentUpdates;
private volatile float rootAgents;
private volatile float childAgents;
private volatile float totalPrims;
private volatile float activePrims;
private volatile float totalFrameTime;
private volatile float netFrameTime;
private volatile float physicsFrameTime;
private volatile float otherFrameTime;
private volatile float imageFrameTime;
private volatile float inPacketsPerSecond;
private volatile float outPacketsPerSecond;
private volatile float unackedBytes;
private volatile float agentFrameTime;
private volatile float pendingDownloads;
private volatile float pendingUploads;
private volatile float activeScripts;
private volatile float scriptLinesPerSecond;
private volatile float m_frameDilation;
private volatile float m_usersLoggingIn;
private volatile float m_totalGeoPrims;
private volatile float m_totalMeshes;
private volatile float m_inUseThreads;
// /// <summary>
// /// These statistics are being collected by push rather than pull. Pull would be simpler, but I had the
// /// notion of providing some flow statistics (which pull wouldn't give us). Though admittedly these
// /// haven't yet been implemented...
// /// </summary>
// public long AssetsInCache { get { return assetsInCache; } }
//
// /// <value>
// /// Currently unused
// /// </value>
// public long TexturesInCache { get { return texturesInCache; } }
//
// /// <value>
// /// Currently misleading since we can't currently subtract removed asset memory usage without a performance hit
// /// </value>
// public long AssetCacheMemoryUsage { get { return assetCacheMemoryUsage; } }
//
// /// <value>
// /// Currently unused
// /// </value>
// public long TextureCacheMemoryUsage { get { return textureCacheMemoryUsage; } }
public float TimeDilation { get { return timeDilation; } }
public float SimFps { get { return simFps; } }
public float PhysicsFps { get { return physicsFps; } }
public float AgentUpdates { get { return agentUpdates; } }
public float RootAgents { get { return rootAgents; } }
public float ChildAgents { get { return childAgents; } }
public float TotalPrims { get { return totalPrims; } }
public float ActivePrims { get { return activePrims; } }
public float TotalFrameTime { get { return totalFrameTime; } }
public float NetFrameTime { get { return netFrameTime; } }
public float PhysicsFrameTime { get { return physicsFrameTime; } }
public float OtherFrameTime { get { return otherFrameTime; } }
public float ImageFrameTime { get { return imageFrameTime; } }
public float InPacketsPerSecond { get { return inPacketsPerSecond; } }
public float OutPacketsPerSecond { get { return outPacketsPerSecond; } }
public float UnackedBytes { get { return unackedBytes; } }
public float AgentFrameTime { get { return agentFrameTime; } }
public float PendingDownloads { get { return pendingDownloads; } }
public float PendingUploads { get { return pendingUploads; } }
public float ActiveScripts { get { return activeScripts; } }
public float ScriptLinesPerSecond { get { return scriptLinesPerSecond; } }
// /// <summary>
// /// This is the time it took for the last asset request made in response to a cache miss.
// /// </summary>
// public TimeSpan AssetRequestTimeAfterCacheMiss { get { return assetRequestTimeAfterCacheMiss; } }
//
// /// <summary>
// /// Number of persistent requests for missing textures we have started blocking from clients. To some extent
// /// this is just a temporary statistic to keep this problem in view - the root cause of this lies either
// /// in a mishandling of the reply protocol, related to avatar appearance or may even originate in graphics
// /// driver bugs on clients (though this seems less likely).
// /// </summary>
// public long BlockedMissingTextureRequests { get { return blockedMissingTextureRequests; } }
//
// /// <summary>
// /// Record the number of times that an asset request has failed. Failures are effectively exceptions, such as
// /// request timeouts. If an asset service replies that a particular asset cannot be found, this is not counted
// /// as a failure
// /// </summary>
// public long AssetServiceRequestFailures { get { return assetServiceRequestFailures; } }
/// <summary>
/// Number of known failures to retrieve avatar inventory from the inventory service. This does not
/// cover situations where the inventory service accepts the request but never returns any data, since
/// we do not yet timeout this situation.
/// </summary>
/// <remarks>Commented out because we do not cache inventory at this point</remarks>
// public long InventoryServiceRetrievalFailures { get { return inventoryServiceRetrievalFailures; } }
/// <summary>
/// Retrieve the total frame time (in ms) of the last frame
/// </summary>
//public float TotalFrameTime { get { return totalFrameTime; } }
/// <summary>
/// Retrieve the physics update component (in ms) of the last frame
/// </summary>
//public float PhysicsFrameTime { get { return physicsFrameTime; } }
/// <summary>
/// Retain a dictionary of all packet queues stats reporters
/// </summary>
private IDictionary<UUID, PacketQueueStatsCollector> packetQueueStatsCollectors
= new Dictionary<UUID, PacketQueueStatsCollector>();
// public void AddAsset(AssetBase asset)
// {
// assetsInCache++;
// //assetCacheMemoryUsage += asset.Data.Length;
// }
//
// public void RemoveAsset(UUID uuid)
// {
// assetsInCache--;
// }
//
// public void AddTexture(AssetBase image)
// {
// if (image.Data != null)
// {
// texturesInCache++;
//
// // This could have been a pull stat, though there was originally a nebulous idea to measure flow rates
// textureCacheMemoryUsage += image.Data.Length;
// }
// }
//
// /// <summary>
// /// Signal that the asset cache has been cleared.
// /// </summary>
// public void ClearAssetCacheStatistics()
// {
// assetsInCache = 0;
// assetCacheMemoryUsage = 0;
// texturesInCache = 0;
// textureCacheMemoryUsage = 0;
// }
//
// public void AddAssetRequestTimeAfterCacheMiss(TimeSpan ts)
// {
// assetRequestTimeAfterCacheMiss = ts;
// }
//
// public void AddBlockedMissingTextureRequest()
// {
// blockedMissingTextureRequests++;
// }
//
// public void AddAssetServiceRequestFailure()
// {
// assetServiceRequestFailures++;
// }
// public void AddInventoryServiceRetrievalFailure()
// {
// inventoryServiceRetrievalFailures++;
// }
/// <summary>
/// Register as a packet queue stats provider
/// </summary>
/// <param name="uuid">An agent UUID</param>
/// <param name="provider"></param>
public void RegisterPacketQueueStatsProvider(UUID uuid, IPullStatsProvider provider)
{
lock (packetQueueStatsCollectors)
{
// FIXME: If the region service is providing more than one region, then the child and root agent
// queues are wrongly replacing each other here.
packetQueueStatsCollectors[uuid] = new PacketQueueStatsCollector(provider);
}
}
/// <summary>
/// Deregister a packet queue stats provider
/// </summary>
/// <param name="uuid">An agent UUID</param>
public void DeregisterPacketQueueStatsProvider(UUID uuid)
{
lock (packetQueueStatsCollectors)
{
packetQueueStatsCollectors.Remove(uuid);
}
}
/// <summary>
/// This is the method on which the classic sim stats reporter (which collects stats for
/// client purposes) sends information to listeners.
/// </summary>
/// <param name="pack"></param>
public void ReceiveClassicSimStatsPacket(SimStats stats)
{
// FIXME: SimStats shouldn't allow an arbitrary stat packing order (which is inherited from the original
// SimStatsPacket that was being used).
// For an unknown reason the original designers decided not to
// include the spare MS statistic inside of this class, this is
// located inside the StatsBlock at location 21, thus it is skipped
timeDilation = stats.StatsBlock[0].StatValue;
simFps = stats.StatsBlock[1].StatValue;
physicsFps = stats.StatsBlock[2].StatValue;
agentUpdates = stats.StatsBlock[3].StatValue;
rootAgents = stats.StatsBlock[4].StatValue;
childAgents = stats.StatsBlock[5].StatValue;
totalPrims = stats.StatsBlock[6].StatValue;
activePrims = stats.StatsBlock[7].StatValue;
totalFrameTime = stats.StatsBlock[8].StatValue;
netFrameTime = stats.StatsBlock[9].StatValue;
physicsFrameTime = stats.StatsBlock[10].StatValue;
otherFrameTime = stats.StatsBlock[11].StatValue;
imageFrameTime = stats.StatsBlock[12].StatValue;
inPacketsPerSecond = stats.StatsBlock[13].StatValue;
outPacketsPerSecond = stats.StatsBlock[14].StatValue;
unackedBytes = stats.StatsBlock[15].StatValue;
agentFrameTime = stats.StatsBlock[16].StatValue;
pendingDownloads = stats.StatsBlock[17].StatValue;
pendingUploads = stats.StatsBlock[18].StatValue;
activeScripts = stats.StatsBlock[19].StatValue;
scriptLinesPerSecond = stats.StatsBlock[20].StatValue;
m_frameDilation = stats.StatsBlock[22].StatValue;
m_usersLoggingIn = stats.StatsBlock[23].StatValue;
m_totalGeoPrims = stats.StatsBlock[24].StatValue;
m_totalMeshes = stats.StatsBlock[25].StatValue;
m_inUseThreads = stats.StatsBlock[26].StatValue;
}
/// <summary>
/// Report back collected statistical information.
/// </summary>
/// <returns></returns>
public override string Report()
{
StringBuilder sb = new StringBuilder(Environment.NewLine);
// sb.Append("ASSET STATISTICS");
// sb.Append(Environment.NewLine);
/*
sb.Append(
string.Format(
@"Asset cache contains {0,6} non-texture assets using {1,10} K
Texture cache contains {2,6} texture assets using {3,10} K
Latest asset request time after cache miss: {4}s
Blocked client requests for missing textures: {5}
Asset service request failures: {6}"+ Environment.NewLine,
AssetsInCache, Math.Round(AssetCacheMemoryUsage / 1024.0),
TexturesInCache, Math.Round(TextureCacheMemoryUsage / 1024.0),
assetRequestTimeAfterCacheMiss.Milliseconds / 1000.0,
BlockedMissingTextureRequests,
AssetServiceRequestFailures));
*/
/*
sb.Append(
string.Format(
@"Asset cache contains {0,6} assets
Latest asset request time after cache miss: {1}s
Blocked client requests for missing textures: {2}
Asset service request failures: {3}" + Environment.NewLine,
AssetsInCache,
assetRequestTimeAfterCacheMiss.Milliseconds / 1000.0,
BlockedMissingTextureRequests,
AssetServiceRequestFailures));
*/
sb.Append(Environment.NewLine);
sb.Append("CONNECTION STATISTICS");
sb.Append(Environment.NewLine);
List<Stat> stats = StatsManager.GetStatsFromEachContainer("clientstack", "ClientLogoutsDueToNoReceives");
sb.AppendFormat(
"Client logouts due to no data receive timeout: {0}\n\n",
stats != null ? stats.Sum(s => s.Value).ToString() : "unknown");
// sb.Append(Environment.NewLine);
// sb.Append("INVENTORY STATISTICS");
// sb.Append(Environment.NewLine);
// sb.Append(
// string.Format(
// "Initial inventory caching failures: {0}" + Environment.NewLine,
// InventoryServiceRetrievalFailures));
sb.Append(Environment.NewLine);
sb.Append("SAMPLE FRAME STATISTICS");
sb.Append(Environment.NewLine);
sb.Append("Dilatn SimFPS PhyFPS AgntUp RootAg ChldAg Prims AtvPrm AtvScr ScrLPS");
sb.Append(Environment.NewLine);
sb.Append(
string.Format(
"{0,6:0.00} {1,6:0} {2,6:0.0} {3,6:0.0} {4,6:0} {5,6:0} {6,6:0} {7,6:0} {8,6:0} {9,6:0}",
timeDilation, simFps, physicsFps, agentUpdates, rootAgents,
childAgents, totalPrims, activePrims, activeScripts, scriptLinesPerSecond));
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
// There is no script frame time currently because we don't yet collect it
sb.Append("PktsIn PktOut PendDl PendUl UnackB TotlFt NetFt PhysFt OthrFt AgntFt ImgsFt");
sb.Append(Environment.NewLine);
sb.Append(
string.Format(
"{0,6:0} {1,6:0} {2,6:0} {3,6:0} {4,6:0} {5,6:0.0} {6,6:0.0} {7,6:0.0} {8,6:0.0} {9,6:0.0} {10,6:0.0}\n\n",
inPacketsPerSecond, outPacketsPerSecond, pendingDownloads, pendingUploads, unackedBytes, totalFrameTime,
netFrameTime, physicsFrameTime, otherFrameTime, agentFrameTime, imageFrameTime));
/* 20130319 RA: For the moment, disable the dump of 'scene' catagory as they are mostly output by
* the two formatted printouts above.
SortedDictionary<string, SortedDictionary<string, Stat>> sceneStats;
if (StatsManager.TryGetStats("scene", out sceneStats))
{
foreach (KeyValuePair<string, SortedDictionary<string, Stat>> kvp in sceneStats)
{
foreach (Stat stat in kvp.Value.Values)
{
if (stat.Verbosity == StatVerbosity.Info)
{
sb.AppendFormat("{0} ({1}): {2}{3}\n", stat.Name, stat.Container, stat.Value, stat.UnitName);
}
}
}
}
*/
/*
sb.Append(Environment.NewLine);
sb.Append("PACKET QUEUE STATISTICS");
sb.Append(Environment.NewLine);
sb.Append("Agent UUID ");
sb.Append(
string.Format(
" {0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7}",
"Send", "In", "Out", "Resend", "Land", "Wind", "Cloud", "Task", "Texture", "Asset"));
sb.Append(Environment.NewLine);
foreach (UUID key in packetQueueStatsCollectors.Keys)
{
sb.Append(string.Format("{0}: ", key));
sb.Append(packetQueueStatsCollectors[key].Report());
sb.Append(Environment.NewLine);
}
*/
sb.Append(base.Report());
return sb.ToString();
}
/// <summary>
/// Report back collected statistical information as json serialization.
/// </summary>
/// <returns></returns>
public override string XReport(string uptime, string version)
{
return OSDParser.SerializeJsonString(OReport(uptime, version));
}
/// <summary>
/// Report back collected statistical information as an OSDMap
/// </summary>
/// <returns></returns>
public override OSDMap OReport(string uptime, string version)
{
// Get the amount of physical memory, allocated with the instance of this program, in kilobytes;
// the working set is the set of memory pages currently visible to this program in physical RAM
// memory and includes both shared (e.g. system libraries) and private data
double memUsage = Process.GetCurrentProcess().WorkingSet64 / 1024.0;
// Get the number of threads from the system that are currently
// running
int numberThreadsRunning = 0;
foreach (ProcessThread currentThread in
Process.GetCurrentProcess().Threads)
{
// A known issue with the current process .Threads property is
// that it can return null threads, thus don't count those as
// running threads and prevent the program function from failing
if (currentThread != null &&
currentThread.ThreadState == ThreadState.Running)
{
numberThreadsRunning++;
}
}
OSDMap args = new OSDMap(30);
// args["AssetsInCache"] = OSD.FromString (String.Format ("{0:0.##}", AssetsInCache));
// args["TimeAfterCacheMiss"] = OSD.FromString (String.Format ("{0:0.##}",
// assetRequestTimeAfterCacheMiss.Milliseconds / 1000.0));
// args["BlockedMissingTextureRequests"] = OSD.FromString (String.Format ("{0:0.##}",
// BlockedMissingTextureRequests));
// args["AssetServiceRequestFailures"] = OSD.FromString (String.Format ("{0:0.##}",
// AssetServiceRequestFailures));
// args["abnormalClientThreadTerminations"] = OSD.FromString (String.Format ("{0:0.##}",
// abnormalClientThreadTerminations));
// args["InventoryServiceRetrievalFailures"] = OSD.FromString (String.Format ("{0:0.##}",
// InventoryServiceRetrievalFailures));
args["Dilatn"] = OSD.FromString (String.Format ("{0:0.##}", timeDilation));
args["SimFPS"] = OSD.FromString (String.Format ("{0:0.##}", simFps));
args["PhyFPS"] = OSD.FromString (String.Format ("{0:0.##}", physicsFps));
args["AgntUp"] = OSD.FromString (String.Format ("{0:0.##}", agentUpdates));
args["RootAg"] = OSD.FromString (String.Format ("{0:0.##}", rootAgents));
args["ChldAg"] = OSD.FromString (String.Format ("{0:0.##}", childAgents));
args["Prims"] = OSD.FromString (String.Format ("{0:0.##}", totalPrims));
args["AtvPrm"] = OSD.FromString (String.Format ("{0:0.##}", activePrims));
args["AtvScr"] = OSD.FromString (String.Format ("{0:0.##}", activeScripts));
args["ScrLPS"] = OSD.FromString (String.Format ("{0:0.##}", scriptLinesPerSecond));
args["PktsIn"] = OSD.FromString (String.Format ("{0:0.##}", inPacketsPerSecond));
args["PktOut"] = OSD.FromString (String.Format ("{0:0.##}", outPacketsPerSecond));
args["PendDl"] = OSD.FromString (String.Format ("{0:0.##}", pendingDownloads));
args["PendUl"] = OSD.FromString (String.Format ("{0:0.##}", pendingUploads));
args["UnackB"] = OSD.FromString (String.Format ("{0:0.##}", unackedBytes));
args["TotlFt"] = OSD.FromString (String.Format ("{0:0.##}", totalFrameTime));
args["NetFt"] = OSD.FromString (String.Format ("{0:0.##}", netFrameTime));
args["PhysFt"] = OSD.FromString (String.Format ("{0:0.##}", physicsFrameTime));
args["OthrFt"] = OSD.FromString (String.Format ("{0:0.##}", otherFrameTime));
args["AgntFt"] = OSD.FromString (String.Format ("{0:0.##}", agentFrameTime));
args["ImgsFt"] = OSD.FromString (String.Format ("{0:0.##}", imageFrameTime));
args["Memory"] = OSD.FromString (base.XReport (uptime, version));
args["Uptime"] = OSD.FromString (uptime);
args["Version"] = OSD.FromString (version);
args["FrameDilatn"] = OSD.FromString(String.Format("{0:0.##}", m_frameDilation));
args["Logging in Users"] = OSD.FromString(String.Format("{0:0.##}",
m_usersLoggingIn));
args["GeoPrims"] = OSD.FromString(String.Format("{0:0.##}",
m_totalGeoPrims));
args["Mesh Objects"] = OSD.FromString(String.Format("{0:0.##}",
m_totalMeshes));
args["XEngine Thread Count"] = OSD.FromString(String.Format("{0:0.##}",
m_inUseThreads));
args["Util Thread Count"] = OSD.FromString(String.Format("{0:0.##}",
Util.GetSmartThreadPoolInfo().InUseThreads));
args["System Thread Count"] = OSD.FromString(String.Format(
"{0:0.##}", numberThreadsRunning));
args["ProcMem"] = OSD.FromString(String.Format("{0:#,###,###.##}",
memUsage));
return args;
}
}
/// <summary>
/// Pull packet queue stats from packet queues and report
/// </summary>
public class PacketQueueStatsCollector : IStatsCollector
{
private IPullStatsProvider m_statsProvider;
public PacketQueueStatsCollector(IPullStatsProvider provider)
{
m_statsProvider = provider;
}
/// <summary>
/// Report back collected statistical information.
/// </summary>
/// <returns></returns>
public string Report()
{
return m_statsProvider.GetStats();
}
public string XReport(string uptime, string version)
{
return "";
}
public OSDMap OReport(string uptime, string version)
{
OSDMap ret = new OSDMap();
return ret;
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Scott Wilson <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: XmlFileErrorLog.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Xml;
using System.Collections;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses XML files stored on
/// disk as its backing store.
/// </summary>
public class XmlFileErrorLog : ErrorLog
{
private readonly string _logPath;
/// <summary>
/// Initializes a new instance of the <see cref="XmlFileErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public XmlFileErrorLog(IDictionary config)
{
string logPath = Mask.NullString(config["logPath"] as string);
if (logPath.Length == 0)
{
//
// For compatibility reasons with older version of this
// implementation, we also try "LogPath".
//
logPath = Mask.NullString(config["LogPath"] as string);
if (logPath.Length == 0)
throw new ApplicationException("Log path is missing for the XML file-based error log.");
}
#if !NET_1_1 && !NET_1_0
if (logPath.StartsWith("~/"))
logPath = MapPath(logPath);
#endif
_logPath = logPath;
}
#if !NET_1_1 && !NET_1_0
/// <remarks>
/// This method is excluded from inlining so that if
/// HostingEnvironment does not need JIT-ing if it is not implicated
/// by the caller.
/// </remarks>
[ MethodImpl(MethodImplOptions.NoInlining) ]
private static string MapPath(string path)
{
return System.Web.Hosting.HostingEnvironment.MapPath(path);
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="XmlFileErrorLog"/> class
/// to use a specific path to store/load XML files.
/// </summary>
public XmlFileErrorLog(string logPath)
{
_logPath = logPath;
}
/// <summary>
/// Gets the path to where the log is stored.
/// </summary>
public virtual string LogPath
{
get { return Mask.NullString(_logPath); }
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "XML File-Based Error Log"; }
}
/// <summary>
/// Logs an error to the database.
/// </summary>
/// <remarks>
/// Logs an error as a single XML file stored in a folder. XML files are named with a
/// sortable date and a unique identifier. Currently the XML files are stored indefinately.
/// As they are stored as files, they may be managed using standard scheduled jobs.
/// </remarks>
public override string Log(Error error)
{
string logPath = LogPath;
if (!Directory.Exists(logPath))
Directory.CreateDirectory(logPath);
string errorId = Guid.NewGuid().ToString();
DateTime timeStamp = (error.Time > DateTime.MinValue ? error.Time : DateTime.Now);
string fileName = string.Format(CultureInfo.InvariantCulture,
@"error-{0:yyyy-MM-ddHHmmssZ}-{1}.xml",
/* 0 */ timeStamp.ToUniversalTime(),
/* 1 */ errorId);
string path = Path.Combine(logPath, fileName);
XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8);
try
{
writer.Formatting = Formatting.Indented;
writer.WriteStartElement("error");
writer.WriteAttributeString("errorId", errorId);
ErrorXml.Encode(error, writer);
writer.WriteEndElement();
writer.Flush();
}
finally
{
writer.Close();
}
return errorId;
}
internal override void Delete(Guid id)
{
throw new NotImplementedException();
}
public override int GetErrors(int pageIndex, int pageSize, string filter, IList errorEntryList)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns a page of errors from the folder in descending order
/// of logged time as defined by the sortable filenames.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
/* Get all files in directory */
string logPath = LogPath;
DirectoryInfo dir = new DirectoryInfo(logPath);
if (!dir.Exists)
return 0;
FileSystemInfo[] infos = dir.GetFiles("error-*.xml");
if (infos.Length < 1)
return 0;
string[] files = new string[infos.Length];
int count = 0;
/* Get files that are not marked with system and hidden attributes */
foreach (FileSystemInfo info in infos)
{
if (IsUserFile(info.Attributes))
files[count++] = Path.Combine(logPath, info.Name);
}
InvariantStringArray.Sort(files, 0, count);
Array.Reverse(files, 0, count);
if (errorEntryList != null)
{
/* Find the proper page */
int firstIndex = pageIndex * pageSize;
int lastIndex = (firstIndex + pageSize < count) ? firstIndex + pageSize : count;
/* Open them up and rehydrate the list */
for (int i = firstIndex; i < lastIndex; i++)
{
XmlTextReader reader = new XmlTextReader(files[i]);
try
{
while (reader.IsStartElement("error"))
{
string id = reader.GetAttribute("errorId");
Error error = ErrorXml.Decode(reader);
errorEntryList.Add(new ErrorLogEntry(this, id, error));
}
}
finally
{
reader.Close();
}
}
}
/* Return how many are total */
return count;
}
/// <summary>
/// Returns the specified error from the filesystem, or throws an exception if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
try
{
/* Make sure the identifier is a valid GUID */
id = (new Guid(id)).ToString();
}
catch (FormatException e)
{
throw new ArgumentException(e.Message, id, e);
}
/* Get the file folder list - should only return one ever */
DirectoryInfo dir = new DirectoryInfo(LogPath);
FileInfo[] files = dir.GetFiles(string.Format("error-*-{0}.xml", id));
if (files.Length < 1)
return null;
FileInfo file = files[0];
if (!IsUserFile(file.Attributes))
return null;
XmlTextReader reader = new XmlTextReader(file.FullName);
try
{
Error error = ErrorXml.Decode(reader);
return new ErrorLogEntry(this, id, error);
}
finally
{
reader.Close();
}
}
private static bool IsUserFile(FileAttributes attributes)
{
return 0 == (attributes & (FileAttributes.Directory |
FileAttributes.Hidden |
FileAttributes.System));
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET //
// Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See license-pdn.txt for full licensing and attribution details. //
// //
// Ported to Pinta by: Krzysztof Marecki <[email protected]> //
/////////////////////////////////////////////////////////////////////////////////
// Additional code:
//
// LevelsDialog.cs
//
// Author:
// Krzysztof Marecki <[email protected]>
//
// Copyright (c) 2010 Krzysztof Marecki
//
// 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 Mono.Unix;
using Cairo;
using Pinta.Core;
using Pinta.Gui.Widgets;
namespace Pinta.Effects
{
public partial class LevelsDialog : Gtk.Dialog
{
private bool[] mask;
public LevelsData EffectData { get; private set; }
public LevelsDialog (LevelsData effectData) : base (Catalog.GetString ("Levels Adjustment"),
PintaCore.Chrome.MainWindow, DialogFlags.Modal)
{
this.Build ();
EffectData = effectData;
mask = new bool[] {true, true, true};
this.HasSeparator = false;
//hack allowing adding hbox with rgb checkboxes into dialog action area
VBox.Remove (hboxBottom);
foreach (Widget widget in hboxBottom)
{
hboxBottom.Remove (widget);
if (widget == buttonOk)
{
AddActionWidget (widget, ResponseType.Ok);
}
else
{
AddActionWidget (widget, ResponseType.None);
}
}
UpdateInputHistogram ();
Reset ();
UpdateLevels ();
checkRed.Toggled += HandleCheckRedToggled;
checkGreen.Toggled += HandleCheckGreenToggled;
checkBlue.Toggled += HandleCheckBlueToggled;
buttonReset.Clicked += HandleButtonResetClicked;
buttonAuto.Clicked += HandleButtonAutoClicked;
buttonCancel.Clicked += HandleButtonCancelClicked;
buttonOk.Clicked += HandleButtonOkClicked;
spinInLow.ValueChanged += HandleSpinInLowValueChanged;
spinInHigh.ValueChanged += HandleSpinInHighValueChanged;
spinOutLow.ValueChanged += HandleSpinOutLowValueChanged;
spinOutGamma.ValueChanged += HandleSpinOutGammaValueChanged;
spinOutHigh.ValueChanged += HandleSpinOutHighValueChanged;
gradientInput.ValueChanged += HandleGradientInputValueChanged;
gradientOutput.ValueChanged += HandleGradientOutputValueChanged;
gradientInput.ButtonReleaseEvent += HandleGradientButtonReleaseEvent;
gradientOutput.ButtonReleaseEvent += HandleGradientButtonReleaseEvent;
gradientInput.ButtonPressEvent += HandleGradientButtonPressEvent;
gradientOutput.ButtonPressEvent += HandleGradientButtonPressEvent;
colorpanelInLow.ButtonPressEvent += HandleColorPanelButtonPressEvent;
colorpanelInHigh.ButtonPressEvent += HandleColorPanelButtonPressEvent;
colorpanelOutLow.ButtonPressEvent += HandleColorPanelButtonPressEvent;
colorpanelOutHigh.ButtonPressEvent += HandleColorPanelButtonPressEvent;
if (Gtk.Global.AlternativeDialogButtonOrder (this.Screen)) {
hboxBottom.ReorderChild (buttonCancel, 0);
}
buttonOk.CanDefault = true;
DefaultResponse = ResponseType.Ok;
spinInLow.ActivatesDefault = true;
spinInHigh.ActivatesDefault = true;
spinOutGamma.ActivatesDefault = true;
spinOutLow.ActivatesDefault = true;
spinOutHigh.ActivatesDefault = true;
}
private UnaryPixelOps.Level Levels {
get {
if (EffectData == null)
throw new InvalidOperationException ("Effect data not set on levels dialog.");
return EffectData.Levels;
}
set {
if (value == null)
throw new ArgumentNullException ();
EffectData.Levels = value;
}
}
private void UpdateLivePreview ()
{
if (EffectData != null)
EffectData.FirePropertyChanged ("Levels");
}
private void UpdateInputHistogram ()
{
ImageSurface surface = PintaCore.Layers.CurrentLayer.Surface;
Gdk.Rectangle rect = PintaCore.Workspace.ActiveDocument.Selection.SelectionPath.GetBounds ();
histogramInput.Histogram.UpdateHistogram (surface, rect);
UpdateOutputHistogram ();
}
private void UpdateOutputHistogram ()
{
histogramOutput.Histogram.SetFromLeveledHistogram(histogramInput.Histogram, Levels);
}
private void Reset ()
{
histogramOutput.ResetHistogram ();
spinInLow.Value = 0;
spinInHigh.Value = 255;
spinOutLow.Value = 0;
spinOutGamma.Value = 1.0;
spinOutHigh.Value = 255;
}
private void HandleButtonResetClicked (object sender, EventArgs e)
{
Reset ();
}
private void UpdateFromLevelsOp ()
{
disable_updating = true;
spinInHigh.Value = MaskAvg (Levels.ColorInHigh);
spinInLow.Value = MaskAvg (Levels.ColorInLow);
float gamma = MaskGamma ();
int lo = MaskAvg (Levels.ColorOutLow);
int hi = MaskAvg (Levels.ColorOutHigh);
spinOutHigh.Value = hi;
spinOutGamma.Value = gamma;
spinOutLow.Value = lo;
disable_updating = false;
}
private void HandleButtonAutoClicked (object sender, EventArgs e)
{
Levels = histogramInput.Histogram.MakeLevelsAuto ();
UpdateFromLevelsOp ();
UpdateLevels ();
}
private void HandleSpinInLowValueChanged (object sender, EventArgs e)
{
gradientInput.SetValue (0, spinInLow.ValueAsInt);
}
private void HandleSpinInHighValueChanged (object sender, EventArgs e)
{
gradientInput.SetValue (1, spinInHigh.ValueAsInt);
}
private void HandleSpinOutLowValueChanged (object sender, EventArgs e)
{
gradientOutput.SetValue (0, spinOutLow.ValueAsInt);
}
private int FromGammaValue ()
{
int lo = gradientOutput.GetValue (0);
int hi = gradientOutput.GetValue (2);
int med = (int)(lo + (hi - lo) * Math.Pow (0.5, spinOutGamma.Value));
return med;
}
private void HandleSpinOutGammaValueChanged (object sender, EventArgs e)
{
gradientOutput.SetValue (1, FromGammaValue ());
}
private void HandleSpinOutHighValueChanged (object sender, EventArgs e)
{
gradientOutput.SetValue (2, spinOutHigh.ValueAsInt);
}
private int MaskAvg(ColorBgra before)
{
int count = 0, total = 0;
for (int c = 0; c < 3; c++) {
if (mask [c]) {
total += before [c];
count++;
}
}
if (count > 0) {
return total / count;
}
else {
return 0;
}
}
private ColorBgra UpdateByMask (ColorBgra before, byte val)
{
ColorBgra after = before;
int average = -1, oldaverage = -1;
if (!(mask [0] || mask [1] || mask [2])) {
return before;
}
do {
float factor;
oldaverage = average;
average = MaskAvg (after);
if (average == 0) {
break;
}
factor = (float)val / average;
for (int c = 0; c < 3; c++) {
if (mask [c]) {
after [c] = (byte)Utility.ClampToByte (after [c] * factor);
}
}
} while (average != val && oldaverage != average);
while (average != val) {
average = MaskAvg (after);
int diff = val - average;
for (int c = 0; c < 3; c++) {
if (mask [c]) {
after [c] = (byte)Utility.ClampToByte(after [c] + diff);
}
}
}
after.A = 255;
return after;
}
private float MaskGamma ()
{
int count = 0;
float total = 0;
for (int c = 0; c < 3; c++) {
if (mask [c]) {
total += Levels.GetGamma (c);
count++;
}
}
if (count > 0) {
return total / count;
} else {
return 1;
}
}
private void UpdateGammaByMask (float val)
{
float average = -1;
if (!(mask [0] || mask [1] || mask [2]))
return;
do {
average = MaskGamma ();
float factor = val / average;
for (int c = 0; c < 3; c++) {
if (mask [c]) {
Levels.SetGamma (c, factor * Levels.GetGamma (c));
}
}
} while (Math.Abs (val - average) > 0.001);
}
private Color GetOutMidColor ()
{
return Levels.Apply (histogramInput.Histogram.GetMeanColor ()).ToCairoColor ();
}
//hack to avoid reccurent invocation of UpdateLevels
private bool disable_updating;
//when user moves triangles inside gradient widget,
//we don't want to redraw histogram each time Levels values change.
//maximum number of skipped updates
private const int max_skip = 5;
//skipped updates counter
private int skip_counter = max_skip;
private bool button_down = false;
private void UpdateLevels ()
{
if(disable_updating)
return;
disable_updating = true;
if(skip_counter == max_skip || !button_down) {
Levels.ColorOutHigh = UpdateByMask (Levels.ColorOutHigh, (byte)spinOutHigh.Value);
Levels.ColorOutLow = UpdateByMask (Levels.ColorOutLow, (byte)spinOutLow.Value);
UpdateGammaByMask ((float) spinOutGamma.Value);
Levels.ColorInHigh = UpdateByMask (Levels.ColorInHigh, (byte)spinInHigh.Value);
Levels.ColorInLow = UpdateByMask (Levels.ColorInLow, (byte)spinInLow.Value);
colorpanelInLow.SetCairoColor (Levels.ColorInLow.ToCairoColor ());
colorpanelInHigh.SetCairoColor (Levels.ColorInHigh.ToCairoColor ());
colorpanelOutLow.SetCairoColor (Levels.ColorOutLow.ToCairoColor ());
colorpanelOutMid.SetCairoColor (GetOutMidColor ());
colorpanelOutHigh.SetCairoColor (Levels.ColorOutHigh.ToCairoColor ());
UpdateOutputHistogram ();
skip_counter = 0;
} else
skip_counter++;
GdkWindow.Invalidate ();
disable_updating = false;
UpdateLivePreview ();
}
private void HandleGradientButtonPressEvent (object o, ButtonPressEventArgs args)
{
button_down = true;
}
private void HandleGradientButtonReleaseEvent (object o, ButtonReleaseEventArgs args)
{
button_down = false;
if (skip_counter != 0)
UpdateLevels ();
}
private void HandleGradientInputValueChanged (object sender, IndexEventArgs e)
{
int val = gradientInput.GetValue (e.Index);
if (e.Index == 0)
spinInLow.Value = val;
else
spinInHigh.Value = val;
UpdateLevels ();
}
private void HandleGradientOutputValueChanged (object sender, IndexEventArgs e)
{
if (gradientOutput.ValueIndex != -1 && gradientOutput.ValueIndex != e.Index)
return;
int val = gradientOutput.GetValue (e.Index);
int hi = gradientOutput.GetValue (2);
int lo = gradientOutput.GetValue (0);
int med = FromGammaValue ();
switch (e.Index) {
case 0 :
spinOutLow.Value = val;
gradientOutput.SetValue (1, med);
break;
case 1 :
med = gradientOutput.GetValue (1);
spinOutGamma.Value = Utility.Clamp(1 / Math.Log (0.5, (float)(med - lo) / (float)(hi - lo)), 0.1, 10.0);
break;
case 2 :
spinOutHigh.Value = val;
gradientOutput.SetValue (1, med);
break;
}
UpdateLevels ();
}
private void MaskChanged ()
{
ColorBgra max = ColorBgra.Black;
max.Bgra |= mask[0] ? (uint)0xFF0000 : 0;
max.Bgra |= mask[1] ? (uint)0xFF00 : 0;
max.Bgra |= mask[2] ? (uint)0xFF : 0;
Color maxcolor = max.ToCairoColor ();
gradientInput.MaxColor = maxcolor;
gradientOutput.MaxColor = maxcolor;
for (int i = 0; i < 3; i++) {
histogramInput.SetSelected (i, mask[i]);
histogramOutput.SetSelected (i, mask[i]);
}
GdkWindow.Invalidate ();
}
private void HandleCheckRedToggled (object sender, EventArgs e)
{
mask [0] = checkRed.Active;
MaskChanged();
}
private void HandleCheckGreenToggled (object sender, EventArgs e)
{
mask [1] = checkGreen.Active;
MaskChanged ();
}
private void HandleCheckBlueToggled (object sender, EventArgs e)
{
mask [2] = checkBlue.Active;
MaskChanged ();
}
private void HandleButtonOkClicked (object sender, EventArgs e)
{
Respond (ResponseType.Ok);
}
private void HandleButtonCancelClicked (object sender, EventArgs e)
{
Respond (ResponseType.Cancel);
}
private void HandleColorPanelButtonPressEvent (object sender, ButtonPressEventArgs args)
{
if (args.Event.Type != Gdk.EventType.TwoButtonPress)
return;
Gtk.ColorSelectionDialog csd = new Gtk.ColorSelectionDialog ("Choose Color");
ColorPanelWidget panel = (ColorPanelWidget)sender;
csd.ColorSelection.PreviousColor = panel.CairoColor.ToGdkColor ();
csd.ColorSelection.CurrentColor = panel.CairoColor.ToGdkColor ();
csd.ColorSelection.CurrentAlpha = panel.CairoColor.GdkColorAlpha ();
int response = csd.Run ();
if (response == (int)Gtk.ResponseType.Ok) {
ColorBgra col = csd.ColorSelection.CurrentColor.ToBgraColor ();
if (panel == colorpanelInLow) {
Levels.ColorInLow = col;
} else if (panel == colorpanelInHigh) {
Levels.ColorInHigh = col;
} else if (panel == colorpanelOutLow) {
Levels.ColorOutLow = col;
// } else if (panel == colorpanelOutMid) {
// ColorBgra lo = Levels.ColorInLow;
// ColorBgra md = histogramInput.Histogram.GetMeanColor();
// ColorBgra hi = Levels.ColorInHigh;
// ColorBgra out_lo = Levels.ColorOutLow;
// ColorBgra out_hi = Levels.ColorOutHigh;
//
// for (int i = 0; i < 3; i++) {
// double logA = (col[i] - out_lo[i]) / (out_hi[i] - out_lo[i]);
// double logBase = (md[i] - lo[i]) / (hi[i] - lo[i]);
// double logVal = (logBase == 1.0) ? 0.0 : Math.Log (logA, logBase);
//
// Levels.SetGamma(i, (float)Utility.Clamp (logVal, 0.1, 10.0));
// }
} else if (panel == colorpanelOutHigh) {
Levels.ColorOutHigh = col;
}
}
csd.Destroy ();
UpdateFromLevelsOp ();
UpdateLevels ();
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSLF.Model;
using NPOI.HSLF.record.*;
using NPOI.HSLF.usermodel.SlideShow;
/**
* Header / Footer Settings.
*
* You can Get these on slides, or across all notes
*
* @author Yegor Kozlov
*/
public class HeadersFooters {
private HeadersFootersContainer _Container;
private bool _newRecord;
private SlideShow _ppt;
private Sheet _sheet;
private bool _ppt2007;
public HeadersFooters(HeadersFootersContainer rec, SlideShow ppt, bool newRecord, bool IsPpt2007){
_Container = rec;
_newRecord = newRecord;
_ppt = ppt;
_ppt2007 = isPpt2007;
}
public HeadersFooters(HeadersFootersContainer rec, Sheet sheet, bool newRecord, bool IsPpt2007){
_Container = rec;
_newRecord = newRecord;
_sheet = sheet;
_ppt2007 = isPpt2007;
}
/**
* Headers's text
*
* @return Headers's text
*/
public String GetHeaderText(){
CString cs = _Container == null ? null : _Container.GetHeaderAtom();
return GetPlaceholderText(OEPlaceholderAtom.MasterHeader, cs);
}
/**
* Sets headers's text
*
* @param text headers's text
*/
public void SetHeaderText(String text){
if(_newRecord) attach();
SetHeaderVisible(true);
CString cs = _Container.GetHeaderAtom();
if(cs == null) cs = _Container.AddHeaderAtom();
cs.SetText(text);
}
/**
* Footer's text
*
* @return Footer's text
*/
public String GetFooterText(){
CString cs = _Container == null ? null : _Container.GetFooterAtom();
return GetPlaceholderText(OEPlaceholderAtom.MasterFooter, cs);
}
/**
* Sets footers's text
*
* @param text footers's text
*/
public void SetFootersText(String text){
if(_newRecord) attach();
SetFooterVisible(true);
CString cs = _Container.GetFooterAtom();
if(cs == null) cs = _Container.AddFooterAtom();
cs.SetText(text);
}
/**
* This is the date that the user wants in the footers, instead of today's date.
*
* @return custom user date
*/
public String GetDateTimeText(){
CString cs = _Container == null ? null : _Container.GetUserDateAtom();
return GetPlaceholderText(OEPlaceholderAtom.MasterDate, cs);
}
/**
* Sets custom user date to be displayed instead of today's date.
*
* @param text custom user date
*/
public void SetDateTimeText(String text){
if(_newRecord) attach();
SetUserDateVisible(true);
SetDateTimeVisible(true);
CString cs = _Container.GetUserDateAtom();
if(cs == null) cs = _Container.AddUserDateAtom();
cs.SetText(text);
}
/**
* whether the footer text is displayed.
*/
public bool IsFooterVisible(){
return isVisible(HeadersFootersAtom.fHasFooter, OEPlaceholderAtom.MasterFooter);
}
/**
* whether the footer text is displayed.
*/
public void SetFooterVisible(bool flag){
if(_newRecord) attach();
_Container.GetHeadersFootersAtom().SetFlag(HeadersFootersAtom.fHasFooter, flag);
}
/**
* whether the header text is displayed.
*/
public bool IsHeaderVisible(){
return isVisible(HeadersFootersAtom.fHasHeader, OEPlaceholderAtom.MasterHeader);
}
/**
* whether the header text is displayed.
*/
public void SetHeaderVisible(bool flag){
if(_newRecord) attach();
_Container.GetHeadersFootersAtom().SetFlag(HeadersFootersAtom.fHasHeader, flag);
}
/**
* whether the date is displayed in the footer.
*/
public bool IsDateTimeVisible(){
return isVisible(HeadersFootersAtom.fHasDate, OEPlaceholderAtom.MasterDate);
}
/**
* whether the date is displayed in the footer.
*/
public void SetDateTimeVisible(bool flag){
if(_newRecord) attach();
_Container.GetHeadersFootersAtom().SetFlag(HeadersFootersAtom.fHasDate, flag);
}
/**
* whether the custom user date is used instead of today's date.
*/
public bool IsUserDateVisible(){
return isVisible(HeadersFootersAtom.fHasUserDate, OEPlaceholderAtom.MasterDate);
}
/**
* whether the date is displayed in the footer.
*/
public void SetUserDateVisible(bool flag){
if(_newRecord) attach();
_Container.GetHeadersFootersAtom().SetFlag(HeadersFootersAtom.fHasUserDate, flag);
}
/**
* whether the slide number is displayed in the footer.
*/
public bool IsSlideNumberVisible(){
return isVisible(HeadersFootersAtom.fHasSlideNumber, OEPlaceholderAtom.MasterSlideNumber);
}
/**
* whether the slide number is displayed in the footer.
*/
public void SetSlideNumberVisible(bool flag){
if(_newRecord) attach();
_Container.GetHeadersFootersAtom().SetFlag(HeadersFootersAtom.fHasSlideNumber, flag);
}
/**
* An integer that specifies the format ID to be used to style the datetime.
*
* @return an integer that specifies the format ID to be used to style the datetime.
*/
public int GetDateTimeFormat(){
return _Container.GetHeadersFootersAtom().GetFormatId();
}
/**
* An integer that specifies the format ID to be used to style the datetime.
*
* @param formatId an integer that specifies the format ID to be used to style the datetime.
*/
public void SetDateTimeFormat(int formatId){
if(_newRecord) attach();
_Container.GetHeadersFootersAtom().SetFormatId(formatId);
}
/**
* Attach this HeadersFootersContainer to the parent Document record
*/
private void attach(){
Document doc = _ppt.GetDocumentRecord();
Record[] ch = doc.GetChildRecords();
Record lst = null;
for (int i=0; i < ch.Length; i++){
if(ch[i].GetRecordType() == RecordTypes.List.typeID){
lst = ch[i];
break;
}
}
doc.AddChildAfter(_Container, lst);
_newRecord = false;
}
private bool IsVisible(int flag, int placeholderId){
bool visible;
if(_ppt2007){
Sheet master = _sheet != null ? _sheet : _ppt.GetSlidesMasters()[0];
TextShape placeholder = master.GetPlaceholder(placeholderId);
visible = placeholder != null && placeholder.GetText() != null;
} else {
visible = _Container.GetHeadersFootersAtom().GetFlag(flag);
}
return visible;
}
private String GetPlaceholderText(int placeholderId, CString cs){
String text = null;
if(_ppt2007){
Sheet master = _sheet != null ? _sheet : _ppt.GetSlidesMasters()[0];
TextShape placeholder = master.GetPlaceholder(placeholderId);
if(placeholder != null) text = placeholder.GetText();
//default text in master placeholders is not visible
if("*".Equals(text)) text = null;
} else {
text = cs == null ? null : cs.GetText();
}
return text;
}
}
| |
/* ====================================================================
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 NPOI.SS.UserModel;
using NPOI.XSSF.Model;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.Util;
using System;
using NPOI.SS.Formula.PTG;
using NPOI.SS.Formula;
using NPOI.SS;
using NPOI.Util;
using NPOI.SS.Formula.Eval;
using System.Globalization;
namespace NPOI.XSSF.UserModel
{
/**
* High level representation of a cell in a row of a spreadsheet.
* <p>
* Cells can be numeric, formula-based or string-based (text). The cell type
* specifies this. String cells cannot conatin numbers and numeric cells cannot
* contain strings (at least according to our model). Client apps should do the
* conversions themselves. Formula cells have the formula string, as well as
* the formula result, which can be numeric or string.
* </p>
* <p>
* Cells should have their number (0 based) before being Added to a row. Only
* cells that have values should be Added.
* </p>
*/
public class XSSFCell : ICell
{
private static String FALSE_AS_STRING = "0";
private static String TRUE_AS_STRING = "1";
/**
* the xml bean Containing information about the cell's location, value,
* data type, formatting, and formula
*/
private CT_Cell _cell;
/**
* the XSSFRow this cell belongs to
*/
private XSSFRow _row;
/**
* 0-based column index
*/
private int _cellNum;
/**
* Table of strings shared across this workbook.
* If two cells contain the same string, then the cell value is the same index into SharedStringsTable
*/
private SharedStringsTable _sharedStringSource;
/**
* Table of cell styles shared across all cells in a workbook.
*/
private StylesTable _stylesSource;
/**
* Construct a XSSFCell.
*
* @param row the parent row.
* @param cell the xml bean Containing information about the cell.
*/
public XSSFCell(XSSFRow row, CT_Cell cell)
{
_cell = cell;
_row = row;
if (cell.r != null)
{
_cellNum = new CellReference(cell.r).Col;
}
else
{
int prevNum = row.LastCellNum;
if (prevNum != -1)
{
_cellNum = (row as XSSFRow).GetCell(prevNum - 1, MissingCellPolicy.RETURN_NULL_AND_BLANK).ColumnIndex + 1;
}
}
_sharedStringSource = ((XSSFWorkbook)row.Sheet.Workbook).GetSharedStringSource();
_stylesSource = ((XSSFWorkbook)row.Sheet.Workbook).GetStylesSource();
}
/// <summary>
/// Copy cell value, formula and style, from srcCell per cell copy policy
/// If srcCell is null, clears the cell value and cell style per cell copy policy
///
/// This does not shift references in formulas. Use {@link XSSFRowShifter} to shift references in formulas.
/// </summary>
/// <param name="srcCell">The cell to take value, formula and style from</param>
/// <param name="policy">The policy for copying the information, see {@link CellCopyPolicy}</param>
/// <exception cref="ArgumentException">if copy cell style and srcCell is from a different workbook</exception>
public void CopyCellFrom(ICell srcCell, CellCopyPolicy policy)
{
// Copy cell value (cell type is updated implicitly)
if (policy.IsCopyCellValue)
{
if (srcCell != null)
{
CellType copyCellType = srcCell.CellType;
if (copyCellType == CellType.Formula && !policy.IsCopyCellFormula)
{
// Copy formula result as value
// FIXME: Cached value may be stale
copyCellType = srcCell.CachedFormulaResultType;
}
switch (copyCellType)
{
case CellType.Boolean:
SetCellValue(srcCell.BooleanCellValue);
break;
case CellType.Error:
SetCellErrorValue(srcCell.ErrorCellValue);
break;
case CellType.Formula:
SetCellFormula(srcCell.CellFormula);
break;
case CellType.Numeric:
// DataFormat is not copied unless policy.isCopyCellStyle is true
if (DateUtil.IsCellDateFormatted(srcCell))
{
SetCellValue(srcCell.DateCellValue);
}
else
{
SetCellValue(srcCell.NumericCellValue);
}
break;
case CellType.String:
SetCellValue(srcCell.StringCellValue);
break;
case CellType.Blank:
SetBlank();
break;
default:
throw new ArgumentException("Invalid cell type " + srcCell.CellType);
}
}
else
{ //srcCell is null
SetBlank();
}
}
// Copy CellStyle
if (policy.IsCopyCellStyle)
{
if (srcCell != null)
{
CellStyle = (srcCell.CellStyle);
}
else
{
// clear cell style
CellStyle = (null);
}
}
if (policy.IsMergeHyperlink)
{
// if srcCell doesn't have a hyperlink and destCell has a hyperlink, don't clear destCell's hyperlink
IHyperlink srcHyperlink = srcCell.Hyperlink;
if (srcHyperlink != null)
{
Hyperlink = new XSSFHyperlink(srcHyperlink);
}
}
else if (policy.IsCopyHyperlink)
{
// overwrite the hyperlink at dest cell with srcCell's hyperlink
// if srcCell doesn't have a hyperlink, clear the hyperlink (if one exists) at destCell
IHyperlink srcHyperlink = srcCell.Hyperlink;
if (srcHyperlink == null)
{
Hyperlink = (null);
}
else
{
Hyperlink = new XSSFHyperlink(srcHyperlink);
}
}
}
/**
* @return table of strings shared across this workbook
*/
protected SharedStringsTable GetSharedStringSource()
{
return _sharedStringSource;
}
/**
* @return table of cell styles shared across this workbook
*/
protected StylesTable GetStylesSource()
{
return _stylesSource;
}
/**
* Returns the sheet this cell belongs to
*
* @return the sheet this cell belongs to
*/
public ISheet Sheet
{
get
{
return _row.Sheet;
}
}
/**
* Returns the row this cell belongs to
*
* @return the row this cell belongs to
*/
public IRow Row
{
get
{
return _row;
}
}
/**
* Get the value of the cell as a bool.
* <p>
* For strings, numbers, and errors, we throw an exception. For blank cells we return a false.
* </p>
* @return the value of the cell as a bool
* @throws InvalidOperationException if the cell type returned by {@link #CellType}
* is not CellType.Boolean, CellType.Blank or CellType.Formula
*/
public bool BooleanCellValue
{
get
{
CellType cellType = CellType;
switch (cellType)
{
case CellType.Blank:
return false;
case CellType.Boolean:
return _cell.IsSetV() && TRUE_AS_STRING.Equals(_cell.v);
case CellType.Formula:
//YK: should throw an exception if requesting bool value from a non-bool formula
return _cell.IsSetV() && TRUE_AS_STRING.Equals(_cell.v);
default:
throw TypeMismatch(CellType.Boolean, cellType, false);
}
}
}
/**
* Set a bool value for the cell
*
* @param value the bool value to Set this cell to. For formulas we'll Set the
* precalculated value, for bools we'll Set its value. For other types we
* will change the cell to a bool cell and Set its value.
*/
public void SetCellValue(bool value)
{
_cell.t = (ST_CellType.b);
_cell.v = (value ? TRUE_AS_STRING : FALSE_AS_STRING);
}
/**
* Get the value of the cell as a number.
* <p>
* For strings we throw an exception. For blank cells we return a 0.
* For formulas or error cells we return the precalculated value;
* </p>
* @return the value of the cell as a number
* @throws InvalidOperationException if the cell type returned by {@link #CellType} is CellType.String
* @exception NumberFormatException if the cell value isn't a parsable <code>double</code>.
* @see DataFormatter for turning this number into a string similar to that which Excel would render this number as.
*/
public double NumericCellValue
{
get
{
CellType cellType = CellType;
switch (cellType)
{
case CellType.Blank:
return 0.0;
case CellType.Formula:
case CellType.Numeric:
if (_cell.IsSetV())
{
if (string.IsNullOrEmpty(_cell.v))
return 0.0;
try
{
return Double.Parse(_cell.v, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw TypeMismatch(CellType.Numeric, CellType.String, false);
}
}
else
{
return 0.0;
}
default:
throw TypeMismatch(CellType.Numeric, cellType, false);
}
}
}
/**
* Set a numeric value for the cell
*
* @param value the numeric value to Set this cell to. For formulas we'll Set the
* precalculated value, for numerics we'll Set its value. For other types we
* will change the cell to a numeric cell and Set its value.
*/
public void SetCellValue(double value)
{
if (Double.IsInfinity(value))
{
// Excel does not support positive/negative infInities,
// rather, it gives a #DIV/0! error in these cases.
_cell.t = (ST_CellType.e);
_cell.v = (FormulaError.DIV0.String);
}
else if (Double.IsNaN(value))
{
// Excel does not support Not-a-Number (NaN),
// instead it immediately generates an #NUM! error.
_cell.t = (ST_CellType.e);
_cell.v = (FormulaError.NUM.String);
}
else
{
_cell.t = (ST_CellType.n);
_cell.v = (value.ToString(CultureInfo.InvariantCulture));
}
}
/**
* Get the value of the cell as a string
* <p>
* For numeric cells we throw an exception. For blank cells we return an empty string.
* For formulaCells that are not string Formulas, we throw an exception
* </p>
* @return the value of the cell as a string
*/
public String StringCellValue
{
get
{
return this.RichStringCellValue.String;
}
}
/**
* Get the value of the cell as a XSSFRichTextString
* <p>
* For numeric cells we throw an exception. For blank cells we return an empty string.
* For formula cells we return the pre-calculated value if a string, otherwise an exception
* </p>
* @return the value of the cell as a XSSFRichTextString
*/
public IRichTextString RichStringCellValue
{
get
{
CellType cellType = CellType;
XSSFRichTextString rt;
switch (cellType)
{
case CellType.Blank:
rt = new XSSFRichTextString("");
break;
case CellType.String:
if (_cell.t == ST_CellType.inlineStr)
{
if (_cell.IsSetIs())
{
//string is expressed directly in the cell defInition instead of implementing the shared string table.
rt = new XSSFRichTextString(_cell.@is);
}
else if (_cell.IsSetV())
{
//cached result of a formula
rt = new XSSFRichTextString(_cell.v);
}
else
{
rt = new XSSFRichTextString("");
}
}
else if (_cell.t == ST_CellType.str)
{
//cached formula value
rt = new XSSFRichTextString(_cell.IsSetV() ? _cell.v : "");
}
else
{
if (_cell.IsSetV())
{
int idx = Int32.Parse(_cell.v);
rt = new XSSFRichTextString(_sharedStringSource.GetEntryAt(idx));
}
else
{
rt = new XSSFRichTextString("");
}
}
break;
case CellType.Formula:
CheckFormulaCachedValueType(CellType.String, GetBaseCellType(false));
rt = new XSSFRichTextString(_cell.IsSetV() ? _cell.v : "");
break;
default:
throw TypeMismatch(CellType.String, cellType, false);
}
rt.SetStylesTableReference(_stylesSource);
return rt;
}
}
private static void CheckFormulaCachedValueType(CellType expectedTypeCode, CellType cachedValueType)
{
if (cachedValueType != expectedTypeCode)
{
throw TypeMismatch(expectedTypeCode, cachedValueType, true);
}
}
/**
* Set a string value for the cell.
*
* @param str value to Set the cell to. For formulas we'll Set the formula
* cached string result, for String cells we'll Set its value. For other types we will
* change the cell to a string cell and Set its value.
* If value is null then we will change the cell to a Blank cell.
*/
public void SetCellValue(String str)
{
SetCellValue(str == null ? null : new XSSFRichTextString(str));
}
/**
* Set a string value for the cell.
*
* @param str value to Set the cell to. For formulas we'll Set the 'pre-Evaluated result string,
* for String cells we'll Set its value. For other types we will
* change the cell to a string cell and Set its value.
* If value is null then we will change the cell to a Blank cell.
*/
public void SetCellValue(IRichTextString str)
{
if (str == null || str.String == null)
{
SetCellType(CellType.Blank);
return;
}
if (str.Length > SpreadsheetVersion.EXCEL2007.MaxTextLength)
{
throw new ArgumentException("The maximum length of cell contents (text) is 32,767 characters");
}
CellType cellType = CellType;
switch (cellType)
{
case CellType.Formula:
_cell.v = (str.String);
_cell.t= (ST_CellType.str);
break;
default:
if (_cell.t == ST_CellType.inlineStr)
{
//set the 'pre-Evaluated result
_cell.v = str.String;
}
else
{
_cell.t = ST_CellType.s;
XSSFRichTextString rt = (XSSFRichTextString)str;
rt.SetStylesTableReference(_stylesSource);
int sRef = _sharedStringSource.AddEntry(rt.GetCTRst());
_cell.v=sRef.ToString();
}
break;
}
}
/// <summary>
/// Return a formula for the cell, for example, <code>SUM(C4:E4)</code>
/// </summary>
public String CellFormula
{
get
{
// existing behavior - create a new XSSFEvaluationWorkbook for every call
return GetCellFormula(null);
}
set
{
SetCellFormula(value);
}
}
/**
* package/hierarchy use only - reuse an existing evaluation workbook if available for caching
*
* @param fpb evaluation workbook for reuse, if available, or null to create a new one as needed
* @return a formula for the cell
* @throws InvalidOperationException if the cell type returned by {@link #getCellType()} is not CELL_TYPE_FORMULA
*/
protected internal String GetCellFormula(XSSFEvaluationWorkbook fpb)
{
CellType cellType = CellType;
if (cellType != CellType.Formula)
throw TypeMismatch(CellType.Formula, cellType, false);
CT_CellFormula f = _cell.f;
if (IsPartOfArrayFormulaGroup && f == null)
{
XSSFCell cell = ((XSSFSheet)Sheet).GetFirstCellInArrayFormula(this);
return cell.GetCellFormula(fpb);
}
if (f.t == ST_CellFormulaType.shared)
{
//return ConvertSharedFormula((int)f.si);
return ConvertSharedFormula((int)f.si, fpb == null ? XSSFEvaluationWorkbook.Create(Sheet.Workbook) : fpb);
}
return f.Value;
}
/// <summary>
/// Creates a non shared formula from the shared formula counterpart
/// </summary>
/// <param name="si">Shared Group Index</param>
/// <param name="fpb"></param>
/// <returns>non shared formula created for the given shared formula and this cell</returns>
private String ConvertSharedFormula(int si, XSSFEvaluationWorkbook fpb)
{
XSSFSheet sheet = (XSSFSheet)Sheet;
CT_CellFormula f = sheet.GetSharedFormula(si);
if (f == null) throw new InvalidOperationException(
"Master cell of a shared formula with sid=" + si + " was not found");
String sharedFormula = f.Value;
//Range of cells which the shared formula applies to
String sharedFormulaRange = f.@ref;
CellRangeAddress ref1 = CellRangeAddress.ValueOf(sharedFormulaRange);
int sheetIndex = sheet.Workbook.GetSheetIndex(sheet);
SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL2007);
Ptg[] ptgs = FormulaParser.Parse(sharedFormula, fpb, FormulaType.Cell, sheetIndex, RowIndex);
Ptg[] fmla = sf.ConvertSharedFormulas(ptgs,
RowIndex - ref1.FirstRow, ColumnIndex - ref1.FirstColumn);
return FormulaRenderer.ToFormulaString(fpb, fmla);
}
/**
* Sets formula for this cell.
* <p>
* Note, this method only Sets the formula string and does not calculate the formula value.
* To Set the precalculated value use {@link #setCellValue(double)} or {@link #setCellValue(String)}
* </p>
*
* @param formula the formula to Set, e.g. <code>"SUM(C4:E4)"</code>.
* If the argument is <code>null</code> then the current formula is Removed.
* @throws NPOI.ss.formula.FormulaParseException if the formula has incorrect syntax or is otherwise invalid
* @throws InvalidOperationException if the operation is not allowed, for example,
* when the cell is a part of a multi-cell array formula
*/
public void SetCellFormula(String formula)
{
if (IsPartOfArrayFormulaGroup)
{
NotifyArrayFormulaChanging();
}
SetFormula(formula, FormulaType.Cell);
}
internal void SetCellArrayFormula(String formula, CellRangeAddress range)
{
SetFormula(formula, FormulaType.Array);
CT_CellFormula cellFormula = _cell.f;
cellFormula.t = (ST_CellFormulaType.array);
cellFormula.@ref = (range.FormatAsString());
}
private void SetFormula(String formula, FormulaType formulaType)
{
IWorkbook wb = _row.Sheet.Workbook;
if (formula == null)
{
((XSSFWorkbook)wb).OnDeleteFormula(this);
if (_cell.IsSetF()) _cell.unsetF();
return;
}
IFormulaParsingWorkbook fpb = XSSFEvaluationWorkbook.Create(wb);
//validate through the FormulaParser
FormulaParser.Parse(formula, fpb, formulaType, wb.GetSheetIndex(this.Sheet), RowIndex);
CT_CellFormula f = new CT_CellFormula();
f.Value = formula;
_cell.f= (f);
if (_cell.IsSetV()) _cell.unsetV();
}
/// <summary>
/// Returns zero-based column index of this cell
/// </summary>
public int ColumnIndex
{
get
{
return this._cellNum;
}
}
/// <summary>
/// Returns zero-based row index of a row in the sheet that contains this cell
/// </summary>
public int RowIndex
{
get
{
return _row.RowNum;
}
}
/// <summary>
/// Returns an A1 style reference to the location of this cell
/// </summary>
/// <returns>A1 style reference to the location of this cell</returns>
public String GetReference()
{
String ref1 = _cell.r;
if (ref1 == null)
{
return new CellAddress(this).FormatAsString();
}
return ref1;
}
public CellAddress Address
{
get
{
return new CellAddress(this);
}
}
/// <summary>
/// Return the cell's style.
/// </summary>
public ICellStyle CellStyle
{
get
{
XSSFCellStyle style = null;
if ((null != _stylesSource) && (_stylesSource.NumCellStyles > 0))
{
long idx = _cell.IsSetS() ? _cell.s : 0;
style = _stylesSource.GetStyleAt((int)idx);
}
return style;
}
set
{
if (value == null)
{
if (_cell.IsSetS()) _cell.unsetS();
}
else
{
XSSFCellStyle xStyle = (XSSFCellStyle)value;
xStyle.VerifyBelongsToStylesSource(_stylesSource);
long idx = _stylesSource.PutStyle(xStyle);
_cell.s = (uint)idx;
}
}
}
private bool IsFormulaCell
{
get
{
if (_cell.f != null || ((XSSFSheet)Sheet).IsCellInArrayFormulaContext(this))
{
return true;
}
return false;
}
}
/// <summary>
/// Return the cell type.
/// </summary>
public CellType CellType
{
get
{
if (IsFormulaCell)
{
return CellType.Formula;
}
return GetBaseCellType(true);
}
}
/// <summary>
/// Only valid for formula cells
/// </summary>
public CellType CachedFormulaResultType
{
get
{
if (!IsFormulaCell)
{
throw new InvalidOperationException("Only formula cells have cached results");
}
return GetBaseCellType(false);
}
}
/// <summary>
/// Detect cell type based on the "t" attribute of the CT_Cell bean
/// </summary>
/// <param name="blankCells"></param>
/// <returns></returns>
private CellType GetBaseCellType(bool blankCells)
{
switch (_cell.t)
{
case ST_CellType.b:
return CellType.Boolean;
case ST_CellType.n:
if (!_cell.IsSetV() && blankCells)
{
// ooxml does have a separate cell type of 'blank'. A blank cell Gets encoded as
// (either not present or) a numeric cell with no value Set.
// The formula Evaluator (and perhaps other clients of this interface) needs to
// distinguish blank values which sometimes Get translated into zero and sometimes
// empty string, depending on context
return CellType.Blank;
}
return CellType.Numeric;
case ST_CellType.e:
return CellType.Error;
case ST_CellType.s: // String is in shared strings
case ST_CellType.inlineStr: // String is inline in cell
case ST_CellType.str:
return CellType.String;
default:
throw new InvalidOperationException("Illegal cell type: " + this._cell.t);
}
}
/// <summary>
/// Get the value of the cell as a date.
/// </summary>
public DateTime DateCellValue
{
get
{
if (CellType == CellType.Blank)
{
return DateTime.MinValue;
}
double value = NumericCellValue;
bool date1904 = Sheet.Workbook.IsDate1904();
return DateUtil.GetJavaDate(value, date1904);
}
}
public void SetCellValue(DateTime? value)
{
if (value == null)
{
SetCellType(CellType.Blank);
return;
}
SetCellValue(value.Value);
}
/// <summary>
/// Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as a date.
/// </summary>
/// <param name="value">the date value to Set this cell to. For formulas we'll set the precalculated value,
/// for numerics we'll Set its value. For other types we will change the cell to a numeric cell and Set its value. </param>
public void SetCellValue(DateTime value)
{
bool date1904 = Sheet.Workbook.IsDate1904();
SetCellValue(DateUtil.GetExcelDate(value, date1904));
}
/// <summary>
/// Returns the error message, such as #VALUE!
/// </summary>
public String ErrorCellString
{
get
{
CellType cellType = GetBaseCellType(true);
if (cellType != CellType.Error) throw TypeMismatch(CellType.Error, cellType, false);
return _cell.v;
}
}
/// <summary>
/// Get the value of the cell as an error code.
/// For strings, numbers, and bools, we throw an exception.
/// For blank cells we return a 0.
/// </summary>
public byte ErrorCellValue
{
get
{
String code = this.ErrorCellString;
if (code == null)
{
return 0;
}
return FormulaError.ForString(code).Code;
}
}
public void SetCellErrorValue(byte errorCode)
{
FormulaError error = FormulaError.ForInt(errorCode);
SetCellErrorValue(error);
}
/// <summary>
/// Set a error value for the cell
/// </summary>
/// <param name="error">the error value to Set this cell to.
/// For formulas we'll Set the precalculated value , for errors we'll set
/// its value. For other types we will change the cell to an error cell and Set its value.
/// </param>
public void SetCellErrorValue(FormulaError error)
{
_cell.t = (ST_CellType.e);
_cell.v = (error.String);
}
/// <summary>
/// Sets this cell as the active cell for the worksheet.
/// </summary>
public void SetAsActiveCell()
{
Sheet.ActiveCell = Address;
}
/// <summary>
/// Blanks this cell. Blank cells have no formula or value but may have styling.
/// This method erases all the data previously associated with this cell.
/// </summary>
private void SetBlank()
{
CT_Cell blank = new CT_Cell();
blank.r = (_cell.r);
if (_cell.IsSetS()) blank.s=(_cell.s);
_cell.Set(blank);
}
/// <summary>
/// Sets column index of this cell
/// </summary>
/// <param name="num"></param>
internal void SetCellNum(int num)
{
CheckBounds(num);
_cellNum = num;
String ref1 = new CellReference(RowIndex, ColumnIndex).FormatAsString();
_cell.r = (ref1);
}
/// <summary>
/// Set the cells type (numeric, formula or string)
/// </summary>
/// <param name="cellType"></param>
public void SetCellType(CellType cellType)
{
CellType prevType = CellType;
if (IsPartOfArrayFormulaGroup)
{
NotifyArrayFormulaChanging();
}
if (prevType == CellType.Formula && cellType != CellType.Formula)
{
((XSSFWorkbook)Sheet.Workbook).OnDeleteFormula(this);
}
switch (cellType)
{
case CellType.Blank:
SetBlank();
break;
case CellType.Boolean:
String newVal = ConvertCellValueToBoolean() ? TRUE_AS_STRING : FALSE_AS_STRING;
_cell.t= (ST_CellType.b);
_cell.v= (newVal);
break;
case CellType.Numeric:
_cell.t = (ST_CellType.n);
break;
case CellType.Error:
_cell.t = (ST_CellType.e);
break;
case CellType.String:
if (prevType != CellType.String)
{
String str = ConvertCellValueToString();
XSSFRichTextString rt = new XSSFRichTextString(str);
rt.SetStylesTableReference(_stylesSource);
int sRef = _sharedStringSource.AddEntry(rt.GetCTRst());
_cell.v= sRef.ToString();
}
_cell.t= (ST_CellType.s);
break;
case CellType.Formula:
if (!_cell.IsSetF())
{
CT_CellFormula f = new CT_CellFormula();
f.Value = "0";
_cell.f = (f);
if (_cell.IsSetT()) _cell.unsetT();
}
break;
default:
throw new ArgumentException("Illegal cell type: " + cellType);
}
if (cellType != CellType.Formula && _cell.IsSetF())
{
_cell.unsetF();
}
}
/// <summary>
/// Returns a string representation of the cell
/// </summary>
/// <returns>Formula cells return the formula string, rather than the formula result.
/// Dates are displayed in dd-MMM-yyyy format
/// Errors are displayed as #ERR<errIdx>
/// </returns>
public override String ToString()
{
switch (CellType)
{
case CellType.Blank:
return "";
case CellType.Boolean:
return BooleanCellValue ? "TRUE" : "FALSE";
case CellType.Error:
return ErrorEval.GetText(ErrorCellValue);
case CellType.Formula:
return CellFormula;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(this))
{
FormatBase sdf = new SimpleDateFormat("dd-MMM-yyyy");
return sdf.Format(DateCellValue, CultureInfo.CurrentCulture);
}
return NumericCellValue.ToString();
case CellType.String:
return RichStringCellValue.ToString();
default:
return "Unknown Cell Type: " + CellType;
}
}
/**
* Returns the raw, underlying ooxml value for the cell
* <p>
* If the cell Contains a string, then this value is an index into
* the shared string table, pointing to the actual string value. Otherwise,
* the value of the cell is expressed directly in this element. Cells Containing formulas express
* the last calculated result of the formula in this element.
* </p>
*
* @return the raw cell value as Contained in the underlying CT_Cell bean,
* <code>null</code> for blank cells.
*/
public String GetRawValue()
{
return _cell.v;
}
/// <summary>
/// Used to help format error messages
/// </summary>
/// <param name="cellTypeCode"></param>
/// <returns></returns>
private static String GetCellTypeName(CellType cellTypeCode)
{
switch (cellTypeCode)
{
case CellType.Blank: return "blank";
case CellType.String: return "text";
case CellType.Boolean: return "bool";
case CellType.Error: return "error";
case CellType.Numeric: return "numeric";
case CellType.Formula: return "formula";
}
return "#unknown cell type (" + cellTypeCode + ")#";
}
/**
* Used to help format error messages
*/
private static Exception TypeMismatch(CellType expectedTypeCode, CellType actualTypeCode, bool isFormulaCell)
{
String msg = "Cannot get a "
+ GetCellTypeName(expectedTypeCode) + " value from a "
+ GetCellTypeName(actualTypeCode) + " " + (isFormulaCell ? "formula " : "") + "cell";
return new InvalidOperationException(msg);
}
/**
* @throws RuntimeException if the bounds are exceeded.
*/
private static void CheckBounds(int cellIndex)
{
SpreadsheetVersion v = SpreadsheetVersion.EXCEL2007;
int maxcol = SpreadsheetVersion.EXCEL2007.LastColumnIndex;
if (cellIndex < 0 || cellIndex > maxcol)
{
throw new ArgumentException("Invalid column index (" + cellIndex
+ "). Allowable column range for " + v.ToString() + " is (0.."
+ maxcol + ") or ('A'..'" + v.LastColumnName + "')");
}
}
/// <summary>
/// Returns cell comment associated with this cell
/// </summary>
public IComment CellComment
{
get
{
return Sheet.GetCellComment(new CellAddress(this));
}
set
{
if (value == null)
{
RemoveCellComment();
return;
}
value.SetAddress(RowIndex, ColumnIndex);
}
}
/// <summary>
/// Removes the comment for this cell, if there is one.
/// </summary>
public void RemoveCellComment() {
IComment comment = this.CellComment;
if (comment != null)
{
CellAddress ref1 = new CellAddress(GetReference());
XSSFSheet sh = (XSSFSheet)Sheet;
sh.GetCommentsTable(false).RemoveComment(ref1);
sh.GetVMLDrawing(false).RemoveCommentShape(RowIndex, ColumnIndex);
}
}
/// <summary>
/// Get or set hyperlink associated with this cell
/// If the supplied hyperlink is null on setting, the hyperlink for this cell will be removed.
/// </summary>
public IHyperlink Hyperlink
{
get
{
return ((XSSFSheet)Sheet).GetHyperlink(_row.RowNum, _cellNum);
}
set
{
if (value == null)
{
RemoveHyperlink();
return;
}
XSSFHyperlink link = (XSSFHyperlink)value;
// Assign to us
link.SetCellReference(new CellReference(_row.RowNum, _cellNum).FormatAsString());
// Add to the lists
((XSSFSheet)Sheet).AddHyperlink(link);
}
}
/**
* Removes the hyperlink for this cell, if there is one.
*/
public void RemoveHyperlink()
{
((XSSFSheet)Sheet).RemoveHyperlink(_row.RowNum, _cellNum);
}
/**
* Returns the xml bean containing information about the cell's location (reference), value,
* data type, formatting, and formula
*
* @return the xml bean containing information about this cell
*/
internal CT_Cell GetCTCell()
{
return _cell;
}
/**
* Chooses a new bool value for the cell when its type is changing.<p/>
*
* Usually the caller is calling SetCellType() with the intention of calling
* SetCellValue(bool) straight afterwards. This method only exists to give
* the cell a somewhat reasonable value until the SetCellValue() call (if at all).
* TODO - perhaps a method like SetCellTypeAndValue(int, Object) should be introduced to avoid this
*/
private bool ConvertCellValueToBoolean()
{
CellType cellType = CellType;
if (cellType == CellType.Formula)
{
cellType = GetBaseCellType(false);
}
switch (cellType)
{
case CellType.Boolean:
return TRUE_AS_STRING.Equals(_cell.v);
case CellType.String:
int sstIndex = Int32.Parse(_cell.v);
XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.GetEntryAt(sstIndex));
String text = rt.String;
return Boolean.Parse(text);
case CellType.Numeric:
return Double.Parse(_cell.v, CultureInfo.InvariantCulture) != 0;
case CellType.Error:
case CellType.Blank:
return false;
}
throw new RuntimeException("Unexpected cell type (" + cellType + ")");
}
private String ConvertCellValueToString()
{
CellType cellType = CellType;
switch (cellType)
{
case CellType.Blank:
return "";
case CellType.Boolean:
return TRUE_AS_STRING.Equals(_cell.v) ? "TRUE" : "FALSE";
case CellType.String:
int sstIndex = Int32.Parse(_cell.v);
XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.GetEntryAt(sstIndex));
return rt.String;
case CellType.Numeric:
case CellType.Error:
return _cell.v;
case CellType.Formula:
// should really Evaluate, but HSSFCell can't call HSSFFormulaEvaluator
// just use cached formula result instead
break;
default:
throw new InvalidOperationException("Unexpected cell type (" + cellType + ")");
}
cellType = GetBaseCellType(false);
String textValue = _cell.v;
switch (cellType)
{
case CellType.Boolean:
if (TRUE_AS_STRING.Equals(textValue))
{
return "TRUE";
}
if (FALSE_AS_STRING.Equals(textValue))
{
return "FALSE";
}
throw new InvalidOperationException("Unexpected bool cached formula value '"
+ textValue + "'.");
case CellType.String:
case CellType.Numeric:
case CellType.Error:
return textValue;
}
throw new InvalidOperationException("Unexpected formula result type (" + cellType + ")");
}
public CellRangeAddress ArrayFormulaRange
{
get
{
XSSFCell cell = ((XSSFSheet)Sheet).GetFirstCellInArrayFormula(this);
if (cell == null)
{
throw new InvalidOperationException("Cell " + GetReference()
+ " is not part of an array formula.");
}
String formulaRef = cell._cell.f.@ref;
return CellRangeAddress.ValueOf(formulaRef);
}
}
public bool IsPartOfArrayFormulaGroup
{
get
{
return ((XSSFSheet)Sheet).IsCellInArrayFormulaContext(this);
}
}
/**
* The purpose of this method is to validate the cell state prior to modification
*
* @see #NotifyArrayFormulaChanging()
*/
internal void NotifyArrayFormulaChanging(String msg)
{
if (IsPartOfArrayFormulaGroup)
{
CellRangeAddress cra = this.ArrayFormulaRange;
if (cra.NumberOfCells > 1)
{
throw new InvalidOperationException(msg);
}
//un-register the Single-cell array formula from the parent XSSFSheet
Row.Sheet.RemoveArrayFormula(this);
}
}
/// <summary>
/// Called when this cell is modified.The purpose of this method is to validate the cell state prior to modification.
/// </summary>
/// <exception cref="InvalidOperationException">if modification is not allowed</exception>
internal void NotifyArrayFormulaChanging()
{
CellReference ref1 = new CellReference(this);
String msg = "Cell " + ref1.FormatAsString() + " is part of a multi-cell array formula. " +
"You cannot change part of an array.";
NotifyArrayFormulaChanging(msg);
}
#region ICell Members
public bool IsMergedCell
{
get {
return this.Sheet.IsMergedRegion(new CellRangeAddress(this.RowIndex, this.RowIndex, this.ColumnIndex, this.ColumnIndex));
}
}
#endregion
public ICell CopyCellTo(int targetIndex)
{
return CellUtil.CopyCell(this.Row, this.ColumnIndex, targetIndex);
}
public CellType GetCachedFormulaResultTypeEnum()
{
throw new NotImplementedException();
}
}
}
| |
// CRC32.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2011 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// Last Saved: <2011-August-02 18:25:54>
//
// ------------------------------------------------------------------
//
// This module defines the CRC32 class, which can do the CRC32 algorithm, using
// arbitrary starting polynomials, and bit reversal. The bit reversal is what
// distinguishes this CRC-32 used in BZip2 from the CRC-32 that is used in PKZIP
// files, or GZIP files. This class does both.
//
// ------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using Interop = System.Runtime.InteropServices;
namespace Dune.Compression.Zlib
{
/// <summary>
/// Computes a CRC-32. The CRC-32 algorithm is parameterized - you
/// can set the polynomial and enable or disable bit
/// reversal. This can be used for GZIP, BZip2, or ZIP.
/// </summary>
/// <remarks>
/// This type is used internally by DotNetZip; it is generally not used
/// directly by applications wishing to create, read, or manipulate zip
/// archive files.
/// </remarks>
[Guid("ebc25cf6-9120-4283-b972-0e5520d0000C")]
[Interop.ComVisible(true)]
#if !NETCF
[Interop.ClassInterface(Interop.ClassInterfaceType.AutoDispatch)]
#endif
public class CRC32
{
/// <summary>
/// Indicates the total number of bytes applied to the CRC.
/// </summary>
public Int64 TotalBytesRead
{
get
{
return _TotalBytesRead;
}
}
/// <summary>
/// Indicates the current CRC for all blocks slurped in.
/// </summary>
public Int32 Crc32Result
{
get
{
return unchecked((Int32)(~_register));
}
}
/// <summary>
/// Returns the CRC32 for the specified stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32(System.IO.Stream input)
{
return GetCrc32AndCopy(input, null);
}
/// <summary>
/// Returns the CRC32 for the specified stream, and writes the input into the
/// output stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <param name="output">The stream into which to deflate the input</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output)
{
if (input == null)
throw new Exception("The input stream must not be null.");
unchecked
{
byte[] buffer = new byte[BUFFER_SIZE];
int readSize = BUFFER_SIZE;
_TotalBytesRead = 0;
int count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
_TotalBytesRead += count;
while (count > 0)
{
SlurpBlock(buffer, 0, count);
count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
_TotalBytesRead += count;
}
return (Int32)(~_register);
}
}
/// <summary>
/// Get the CRC32 for the given (word,byte) combo. This is a
/// computation defined by PKzip for PKZIP 2.0 (weak) encryption.
/// </summary>
/// <param name="W">The word to start with.</param>
/// <param name="B">The byte to combine it with.</param>
/// <returns>The CRC-ized result.</returns>
public Int32 ComputeCrc32(Int32 W, byte B)
{
return _InternalComputeCrc32((UInt32)W, B);
}
internal Int32 _InternalComputeCrc32(UInt32 W, byte B)
{
return (Int32)(crc32Table[(W ^ B) & 0xFF] ^ (W >> 8));
}
/// <summary>
/// Update the value for the running CRC32 using the given block of bytes.
/// This is useful when using the CRC32() class in a Stream.
/// </summary>
/// <param name="block">block of bytes to slurp</param>
/// <param name="offset">starting point in the block</param>
/// <param name="count">how many bytes within the block to slurp</param>
public void SlurpBlock(byte[] block, int offset, int count)
{
if (block == null)
throw new Exception("The data buffer must not be null.");
// bzip algorithm
for (int i = 0; i < count; i++)
{
int x = offset + i;
byte b = block[x];
if (this.reverseBits)
{
UInt32 temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[temp];
}
else
{
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[temp];
}
}
_TotalBytesRead += count;
}
/// <summary>
/// Process one byte in the CRC.
/// </summary>
/// <param name = "b">the byte to include into the CRC . </param>
public void UpdateCRC(byte b)
{
if (this.reverseBits)
{
UInt32 temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[temp];
}
else
{
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[temp];
}
}
/// <summary>
/// Process a run of N identical bytes into the CRC.
/// </summary>
/// <remarks>
/// <para>
/// This method serves as an optimization for updating the CRC when a
/// run of identical bytes is found. Rather than passing in a buffer of
/// length n, containing all identical bytes b, this method accepts the
/// byte value and the length of the (virtual) buffer - the length of
/// the run.
/// </para>
/// </remarks>
/// <param name = "b">the byte to include into the CRC. </param>
/// <param name = "n">the number of times that byte should be repeated. </param>
public void UpdateCRC(byte b, int n)
{
while (n-- > 0)
{
if (this.reverseBits)
{
uint temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[(temp >= 0)
? temp
: (temp + 256)];
}
else
{
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[(temp >= 0)
? temp
: (temp + 256)];
}
}
}
private static uint ReverseBits(uint data)
{
unchecked
{
uint ret = data;
ret = (ret & 0x55555555) << 1 | (ret >> 1) & 0x55555555;
ret = (ret & 0x33333333) << 2 | (ret >> 2) & 0x33333333;
ret = (ret & 0x0F0F0F0F) << 4 | (ret >> 4) & 0x0F0F0F0F;
ret = (ret << 24) | ((ret & 0xFF00) << 8) | ((ret >> 8) & 0xFF00) | (ret >> 24);
return ret;
}
}
private static byte ReverseBits(byte data)
{
unchecked
{
uint u = (uint)data * 0x00020202;
uint m = 0x01044010;
uint s = u & m;
uint t = (u << 2) & (m << 1);
return (byte)((0x01001001 * (s + t)) >> 24);
}
}
private void GenerateLookupTable()
{
crc32Table = new UInt32[256];
unchecked
{
UInt32 dwCrc;
byte i = 0;
do
{
dwCrc = i;
for (byte j = 8; j > 0; j--)
{
if ((dwCrc & 1) == 1)
{
dwCrc = (dwCrc >> 1) ^ dwPolynomial;
}
else
{
dwCrc >>= 1;
}
}
if (reverseBits)
{
crc32Table[ReverseBits(i)] = ReverseBits(dwCrc);
}
else
{
crc32Table[i] = dwCrc;
}
i++;
} while (i!=0);
}
#if VERBOSE
Console.WriteLine();
Console.WriteLine("private static readonly UInt32[] crc32Table = {");
for (int i = 0; i < crc32Table.Length; i+=4)
{
Console.Write(" ");
for (int j=0; j < 4; j++)
{
Console.Write(" 0x{0:X8}U,", crc32Table[i+j]);
}
Console.WriteLine();
}
Console.WriteLine("};");
Console.WriteLine();
#endif
}
private uint gf2_matrix_times(uint[] matrix, uint vec)
{
uint sum = 0;
int i=0;
while (vec != 0)
{
if ((vec & 0x01)== 0x01)
sum ^= matrix[i];
vec >>= 1;
i++;
}
return sum;
}
private void gf2_matrix_square(uint[] square, uint[] mat)
{
for (int i = 0; i < 32; i++)
square[i] = gf2_matrix_times(mat, mat[i]);
}
/// <summary>
/// Combines the given CRC32 value with the current running total.
/// </summary>
/// <remarks>
/// This is useful when using a divide-and-conquer approach to
/// calculating a CRC. Multiple threads can each calculate a
/// CRC32 on a segment of the data, and then combine the
/// individual CRC32 values at the end.
/// </remarks>
/// <param name="crc">the crc value to be combined with this one</param>
/// <param name="length">the length of data the CRC value was calculated on</param>
public void Combine(int crc, int length)
{
uint[] even = new uint[32]; // even-power-of-two zeros operator
uint[] odd = new uint[32]; // odd-power-of-two zeros operator
if (length == 0)
return;
uint crc1= ~_register;
uint crc2= (uint) crc;
// put operator for one zero bit in odd
odd[0] = this.dwPolynomial; // the CRC-32 polynomial
uint row = 1;
for (int i = 1; i < 32; i++)
{
odd[i] = row;
row <<= 1;
}
// put operator for two zero bits in even
gf2_matrix_square(even, odd);
// put operator for four zero bits in odd
gf2_matrix_square(odd, even);
uint len2 = (uint) length;
// apply len2 zeros to crc1 (first square will put the operator for one
// zero byte, eight zero bits, in even)
do {
// apply zeros operator for this bit of len2
gf2_matrix_square(even, odd);
if ((len2 & 1)== 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
if (len2 == 0)
break;
// another iteration of the loop with odd and even swapped
gf2_matrix_square(odd, even);
if ((len2 & 1)==1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
} while (len2 != 0);
crc1 ^= crc2;
_register= ~crc1;
//return (int) crc1;
return;
}
/// <summary>
/// Create an instance of the CRC32 class using the default settings: no
/// bit reversal, and a polynomial of 0xEDB88320.
/// </summary>
public CRC32() : this(false)
{
}
/// <summary>
/// Create an instance of the CRC32 class, specifying whether to reverse
/// data bits or not.
/// </summary>
/// <param name='reverseBits'>
/// specify true if the instance should reverse data bits.
/// </param>
/// <remarks>
/// <para>
/// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you
/// want a CRC32 with compatibility with BZip2, you should pass true
/// here. In the CRC-32 used by GZIP and PKZIP, the bits are not
/// reversed; Therefore if you want a CRC32 with compatibility with
/// those, you should pass false.
/// </para>
/// </remarks>
public CRC32(bool reverseBits) :
this( unchecked((int)0xEDB88320), reverseBits)
{
}
/// <summary>
/// Create an instance of the CRC32 class, specifying the polynomial and
/// whether to reverse data bits or not.
/// </summary>
/// <param name='polynomial'>
/// The polynomial to use for the CRC, expressed in the reversed (LSB)
/// format: the highest ordered bit in the polynomial value is the
/// coefficient of the 0th power; the second-highest order bit is the
/// coefficient of the 1 power, and so on. Expressed this way, the
/// polynomial for the CRC-32C used in IEEE 802.3, is 0xEDB88320.
/// </param>
/// <param name='reverseBits'>
/// specify true if the instance should reverse data bits.
/// </param>
///
/// <remarks>
/// <para>
/// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you
/// want a CRC32 with compatibility with BZip2, you should pass true
/// here for the <c>reverseBits</c> parameter. In the CRC-32 used by
/// GZIP and PKZIP, the bits are not reversed; Therefore if you want a
/// CRC32 with compatibility with those, you should pass false for the
/// <c>reverseBits</c> parameter.
/// </para>
/// </remarks>
public CRC32(int polynomial, bool reverseBits)
{
this.reverseBits = reverseBits;
this.dwPolynomial = (uint) polynomial;
this.GenerateLookupTable();
}
/// <summary>
/// Reset the CRC-32 class - clear the CRC "remainder register."
/// </summary>
/// <remarks>
/// <para>
/// Use this when employing a single instance of this class to compute
/// multiple, distinct CRCs on multiple, distinct data blocks.
/// </para>
/// </remarks>
public void Reset()
{
_register = 0xFFFFFFFFU;
}
// private member vars
private UInt32 dwPolynomial;
private Int64 _TotalBytesRead;
private bool reverseBits;
private UInt32[] crc32Table;
private const int BUFFER_SIZE = 8192;
private UInt32 _register = 0xFFFFFFFFU;
}
/// <summary>
/// A Stream that calculates a CRC32 (a checksum) on all bytes read,
/// or on all bytes written.
/// </summary>
///
/// <remarks>
/// <para>
/// This class can be used to verify the CRC of a ZipEntry when
/// reading from a stream, or to calculate a CRC when writing to a
/// stream. The stream should be used to either read, or write, but
/// not both. If you intermix reads and writes, the results are not
/// defined.
/// </para>
///
/// <para>
/// This class is intended primarily for use internally by the
/// DotNetZip library.
/// </para>
/// </remarks>
public class CrcCalculatorStream : System.IO.Stream, System.IDisposable
{
private static readonly Int64 UnsetLengthLimit = -99;
internal System.IO.Stream _innerStream;
private CRC32 _Crc32;
private Int64 _lengthLimit = -99;
private bool _leaveOpen;
/// <summary>
/// The default constructor.
/// </summary>
/// <remarks>
/// <para>
/// Instances returned from this constructor will leave the underlying
/// stream open upon Close(). The stream uses the default CRC32
/// algorithm, which implies a polynomial of 0xEDB88320.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
public CrcCalculatorStream(System.IO.Stream stream)
: this(true, CrcCalculatorStream.UnsetLengthLimit, stream, null)
{
}
/// <summary>
/// The constructor allows the caller to specify how to handle the
/// underlying stream at close.
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the default CRC32 algorithm, which implies a
/// polynomial of 0xEDB88320.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param>
public CrcCalculatorStream(System.IO.Stream stream, bool leaveOpen)
: this(leaveOpen, CrcCalculatorStream.UnsetLengthLimit, stream, null)
{
}
/// <summary>
/// A constructor allowing the specification of the length of the stream
/// to read.
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the default CRC32 algorithm, which implies a
/// polynomial of 0xEDB88320.
/// </para>
/// <para>
/// Instances returned from this constructor will leave the underlying
/// stream open upon Close().
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length)
: this(true, length, stream, null)
{
if (length < 0)
throw new ArgumentException("length");
}
/// <summary>
/// A constructor allowing the specification of the length of the stream
/// to read, as well as whether to keep the underlying stream open upon
/// Close().
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the default CRC32 algorithm, which implies a
/// polynomial of 0xEDB88320.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen)
: this(leaveOpen, length, stream, null)
{
if (length < 0)
throw new ArgumentException("length");
}
/// <summary>
/// A constructor allowing the specification of the length of the stream
/// to read, as well as whether to keep the underlying stream open upon
/// Close(), and the CRC32 instance to use.
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the specified CRC32 instance, which allows the
/// application to specify how the CRC gets calculated.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param>
/// <param name="crc32">the CRC32 instance to use to calculate the CRC32</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen,
CRC32 crc32)
: this(leaveOpen, length, stream, crc32)
{
if (length < 0)
throw new ArgumentException("length");
}
// This ctor is private - no validation is done here. This is to allow the use
// of a (specific) negative value for the _lengthLimit, to indicate that there
// is no length set. So we validate the length limit in those ctors that use an
// explicit param, otherwise we don't validate, because it could be our special
// value.
private CrcCalculatorStream
(bool leaveOpen, Int64 length, System.IO.Stream stream, CRC32 crc32)
: base()
{
_innerStream = stream;
_Crc32 = crc32 ?? new CRC32();
_lengthLimit = length;
_leaveOpen = leaveOpen;
}
/// <summary>
/// Gets the total number of bytes run through the CRC32 calculator.
/// </summary>
///
/// <remarks>
/// This is either the total number of bytes read, or the total number of
/// bytes written, depending on the direction of this stream.
/// </remarks>
public Int64 TotalBytesSlurped
{
get { return _Crc32.TotalBytesRead; }
}
/// <summary>
/// Provides the current CRC for all blocks slurped in.
/// </summary>
/// <remarks>
/// <para>
/// The running total of the CRC is kept as data is written or read
/// through the stream. read this property after all reads or writes to
/// get an accurate CRC for the entire stream.
/// </para>
/// </remarks>
public Int32 Crc
{
get { return _Crc32.Crc32Result; }
}
/// <summary>
/// Indicates whether the underlying stream will be left open when the
/// <c>CrcCalculatorStream</c> is Closed.
/// </summary>
/// <remarks>
/// <para>
/// Set this at any point before calling <see cref="Close()"/>.
/// </para>
/// </remarks>
public bool LeaveOpen
{
get { return _leaveOpen; }
set { _leaveOpen = value; }
}
/// <summary>
/// Read from the stream
/// </summary>
/// <param name="buffer">the buffer to read</param>
/// <param name="offset">the offset at which to start</param>
/// <param name="count">the number of bytes to read</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
int bytesToRead = count;
// Need to limit the # of bytes returned, if the stream is intended to have
// a definite length. This is especially useful when returning a stream for
// the uncompressed data directly to the application. The app won't
// necessarily read only the UncompressedSize number of bytes. For example
// wrapping the stream returned from OpenReader() into a StreadReader() and
// calling ReadToEnd() on it, We can "over-read" the zip data and get a
// corrupt string. The length limits that, prevents that problem.
if (_lengthLimit != CrcCalculatorStream.UnsetLengthLimit)
{
if (_Crc32.TotalBytesRead >= _lengthLimit) return 0; // EOF
Int64 bytesRemaining = _lengthLimit - _Crc32.TotalBytesRead;
if (bytesRemaining < count) bytesToRead = (int)bytesRemaining;
}
int n = _innerStream.Read(buffer, offset, bytesToRead);
if (n > 0) _Crc32.SlurpBlock(buffer, offset, n);
return n;
}
/// <summary>
/// Write to the stream.
/// </summary>
/// <param name="buffer">the buffer from which to write</param>
/// <param name="offset">the offset at which to start writing</param>
/// <param name="count">the number of bytes to write</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (count > 0) _Crc32.SlurpBlock(buffer, offset, count);
_innerStream.Write(buffer, offset, count);
}
/// <summary>
/// Indicates whether the stream supports reading.
/// </summary>
public override bool CanRead
{
get { return _innerStream.CanRead; }
}
/// <summary>
/// Indicates whether the stream supports seeking.
/// </summary>
/// <remarks>
/// <para>
/// Always returns false.
/// </para>
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream supports writing.
/// </summary>
public override bool CanWrite
{
get { return _innerStream.CanWrite; }
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
_innerStream.Flush();
}
/// <summary>
/// Returns the length of the underlying stream.
/// </summary>
public override long Length
{
get
{
if (_lengthLimit == CrcCalculatorStream.UnsetLengthLimit)
return _innerStream.Length;
else return _lengthLimit;
}
}
/// <summary>
/// The getter for this property returns the total bytes read.
/// If you use the setter, it will throw
/// <see cref="NotSupportedException"/>.
/// </summary>
public override long Position
{
get { return _Crc32.TotalBytesRead; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Seeking is not supported on this stream. This method always throws
/// <see cref="NotSupportedException"/>
/// </summary>
/// <param name="offset">N/A</param>
/// <param name="origin">N/A</param>
/// <returns>N/A</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// This method always throws
/// <see cref="NotSupportedException"/>
/// </summary>
/// <param name="value">N/A</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
Close();
}
/// <summary>
/// Closes the stream.
/// </summary>
public override void Close()
{
base.Close();
if (!_leaveOpen)
_innerStream.Close();
}
}
}
| |
using EpisodeInformer.Core.Rss;
using EpisodeInformer.Data;
using EpisodeInformer.LocalClasses;
using EpisodeInformer.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace EpisodeInformer
{
public partial class frmFeedManager : Form
{
private IContainer components = (IContainer)null;
private Label label1;
private ComboBox cmbURL;
private TextBox txtVer;
private TextBox txtDescrip;
private TextBox txtTitle;
private Label label4;
private Label label3;
private Label label2;
private Button btnNew;
private LinkLabel lnkLEDIT;
private LinkLabel lnkLDELETE;
private Button btnClose;
private Panel panel1;
private Panel panel2;
private Panel panel3;
private List<RssFeed> feeds;
protected override void Dispose(bool disposing)
{
if (disposing && this.components != null)
this.components.Dispose();
base.Dispose(disposing);
}
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmFeedManager));
this.lnkLEDIT = new System.Windows.Forms.LinkLabel();
this.lnkLDELETE = new System.Windows.Forms.LinkLabel();
this.cmbURL = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.txtVer = new System.Windows.Forms.TextBox();
this.txtDescrip = new System.Windows.Forms.TextBox();
this.txtTitle = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.btnClose = new System.Windows.Forms.Button();
this.btnNew = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.panel3 = new System.Windows.Forms.Panel();
this.chkSelected = new System.Windows.Forms.CheckBox();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.panel3.SuspendLayout();
this.SuspendLayout();
//
// lnkLEDIT
//
this.lnkLEDIT.AutoSize = true;
this.lnkLEDIT.BackColor = System.Drawing.Color.Transparent;
this.lnkLEDIT.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lnkLEDIT.Location = new System.Drawing.Point(249, 41);
this.lnkLEDIT.Name = "lnkLEDIT";
this.lnkLEDIT.Size = new System.Drawing.Size(27, 15);
this.lnkLEDIT.TabIndex = 3;
this.lnkLEDIT.TabStop = true;
this.lnkLEDIT.Text = "Edit";
this.lnkLEDIT.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkLEDIT_LinkClicked);
//
// lnkLDELETE
//
this.lnkLDELETE.AutoSize = true;
this.lnkLDELETE.BackColor = System.Drawing.Color.Transparent;
this.lnkLDELETE.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lnkLDELETE.Location = new System.Drawing.Point(285, 41);
this.lnkLDELETE.Name = "lnkLDELETE";
this.lnkLDELETE.Size = new System.Drawing.Size(40, 15);
this.lnkLDELETE.TabIndex = 2;
this.lnkLDELETE.TabStop = true;
this.lnkLDELETE.Text = "Delete";
this.lnkLDELETE.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkLDELETE_LinkClicked);
//
// cmbURL
//
this.cmbURL.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmbURL.FormattingEnabled = true;
this.cmbURL.Location = new System.Drawing.Point(44, 13);
this.cmbURL.Name = "cmbURL";
this.cmbURL.Size = new System.Drawing.Size(286, 23);
this.cmbURL.TabIndex = 1;
this.cmbURL.SelectedIndexChanged += new System.EventHandler(this.cmbURL_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(9, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(28, 15);
this.label1.TabIndex = 0;
this.label1.Text = "URL";
//
// txtVer
//
this.txtVer.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtVer.Location = new System.Drawing.Point(73, 74);
this.txtVer.Name = "txtVer";
this.txtVer.ReadOnly = true;
this.txtVer.Size = new System.Drawing.Size(100, 23);
this.txtVer.TabIndex = 5;
this.txtVer.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// txtDescrip
//
this.txtDescrip.AcceptsReturn = true;
this.txtDescrip.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtDescrip.Location = new System.Drawing.Point(73, 40);
this.txtDescrip.Name = "txtDescrip";
this.txtDescrip.ReadOnly = true;
this.txtDescrip.Size = new System.Drawing.Size(255, 23);
this.txtDescrip.TabIndex = 4;
//
// txtTitle
//
this.txtTitle.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtTitle.Location = new System.Drawing.Point(73, 4);
this.txtTitle.Name = "txtTitle";
this.txtTitle.ReadOnly = true;
this.txtTitle.Size = new System.Drawing.Size(255, 23);
this.txtTitle.TabIndex = 3;
//
// label4
//
this.label4.AutoSize = true;
this.label4.BackColor = System.Drawing.Color.Transparent;
this.label4.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(7, 77);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(46, 15);
this.label4.TabIndex = 2;
this.label4.Text = "Version";
//
// label3
//
this.label3.AutoSize = true;
this.label3.BackColor = System.Drawing.Color.Transparent;
this.label3.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(7, 43);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(67, 15);
this.label3.TabIndex = 1;
this.label3.Text = "Description";
//
// label2
//
this.label2.AutoSize = true;
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(7, 7);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(30, 15);
this.label2.TabIndex = 0;
this.label2.Text = "Title";
//
// btnClose
//
this.btnClose.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnClose.Location = new System.Drawing.Point(254, 8);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(75, 23);
this.btnClose.TabIndex = 1;
this.btnClose.Text = "&Close";
this.btnClose.UseVisualStyleBackColor = true;
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// btnNew
//
this.btnNew.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNew.Location = new System.Drawing.Point(11, 8);
this.btnNew.Name = "btnNew";
this.btnNew.Size = new System.Drawing.Size(75, 23);
this.btnNew.TabIndex = 0;
this.btnNew.Text = "&New";
this.btnNew.UseVisualStyleBackColor = true;
this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
//
// panel1
//
this.panel1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("panel1.BackgroundImage")));
this.panel1.Controls.Add(this.lnkLEDIT);
this.panel1.Controls.Add(this.cmbURL);
this.panel1.Controls.Add(this.lnkLDELETE);
this.panel1.Controls.Add(this.label1);
this.panel1.Location = new System.Drawing.Point(12, 12);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(347, 66);
this.panel1.TabIndex = 3;
//
// panel2
//
this.panel2.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("panel2.BackgroundImage")));
this.panel2.Controls.Add(this.chkSelected);
this.panel2.Controls.Add(this.txtVer);
this.panel2.Controls.Add(this.txtDescrip);
this.panel2.Controls.Add(this.label2);
this.panel2.Controls.Add(this.txtTitle);
this.panel2.Controls.Add(this.label3);
this.panel2.Controls.Add(this.label4);
this.panel2.Location = new System.Drawing.Point(14, 98);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(344, 104);
this.panel2.TabIndex = 4;
//
// panel3
//
this.panel3.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("panel3.BackgroundImage")));
this.panel3.Controls.Add(this.btnClose);
this.panel3.Controls.Add(this.btnNew);
this.panel3.Location = new System.Drawing.Point(15, 217);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(343, 41);
this.panel3.TabIndex = 5;
//
// chkSelected
//
this.chkSelected.AutoSize = true;
this.chkSelected.Enabled = false;
this.chkSelected.Location = new System.Drawing.Point(179, 77);
this.chkSelected.Name = "chkSelected";
this.chkSelected.Size = new System.Drawing.Size(111, 17);
this.chkSelected.TabIndex = 7;
this.chkSelected.Text = "Use for Download";
this.chkSelected.UseVisualStyleBackColor = true;
//
// frmFeedManager
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = global::EpisodeInformer.Properties.Resources.back;
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.ClientSize = new System.Drawing.Size(374, 271);
this.Controls.Add(this.panel3);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "frmFeedManager";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Feed Manager";
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.panel3.ResumeLayout(false);
this.ResumeLayout(false);
}
private CheckBox chkSelected;
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using GitTools.Testing;
using GitVersion;
using GitVersion.Extensions;
using GitVersion.Model.Configuration;
using GitVersion.VersionCalculation;
using GitVersionCore.Tests.Helpers;
using LibGit2Sharp;
using NUnit.Framework;
namespace GitVersionCore.Tests.IntegrationTests
{
public class MainlineDevelopmentMode : TestBase
{
private readonly Config config = new Config
{
VersioningMode = VersioningMode.Mainline
};
[Test]
public void MergedFeatureBranchesToMasterImpliesRelease()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("2");
fixture.AssertFullSemver("1.0.1-foo.1", config);
fixture.MakeACommit("2.1");
fixture.AssertFullSemver("1.0.1-foo.2", config);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.0.1", config);
fixture.BranchTo("feature/foo2", "foo2");
fixture.MakeACommit("3 +semver: minor");
fixture.AssertFullSemver("1.1.0-foo2.1", config);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo2");
fixture.AssertFullSemver("1.1.0", config);
fixture.BranchTo("feature/foo3", "foo3");
fixture.MakeACommit("4");
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo3");
fixture.SequenceDiagram.NoteOver("Merge message contains '+semver: minor'", "master");
var commit = fixture.Repository.Head.Tip;
// Put semver increment in merge message
fixture.Repository.Commit(commit.Message + " +semver: minor", commit.Author, commit.Committer, new CommitOptions
{
AmendPreviousCommit = true
});
fixture.AssertFullSemver("1.2.0", config);
fixture.BranchTo("feature/foo4", "foo4");
fixture.MakeACommit("5 +semver: major");
fixture.AssertFullSemver("2.0.0-foo4.1", config);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo4");
fixture.AssertFullSemver("2.0.0", config);
// We should evaluate any commits not included in merge commit calculations for direct commit/push or squash to merge commits
fixture.MakeACommit("6 +semver: major");
fixture.AssertFullSemver("3.0.0", config);
fixture.MakeACommit("7 +semver: minor");
fixture.AssertFullSemver("3.1.0", config);
fixture.MakeACommit("8");
fixture.AssertFullSemver("3.1.1", config);
// Finally verify that the merge commits still function properly
fixture.BranchTo("feature/foo5", "foo5");
fixture.MakeACommit("9 +semver: minor");
fixture.AssertFullSemver("3.2.0-foo5.1", config);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo5");
fixture.AssertFullSemver("3.2.0", config);
// One more direct commit for good measure
fixture.MakeACommit("10 +semver: minor");
fixture.AssertFullSemver("3.3.0", config);
// And we can commit without bumping semver
fixture.MakeACommit("11 +semver: none");
fixture.AssertFullSemver("3.3.0", config);
Console.WriteLine(fixture.SequenceDiagram.GetDiagram());
}
[Test]
public void VerifyPullRequestsActLikeContinuousDelivery()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.1", config);
fixture.BranchTo("feature/foo", "foo");
fixture.AssertFullSemver("1.0.2-foo.0", config);
fixture.MakeACommit();
fixture.MakeACommit();
fixture.Repository.CreatePullRequestRef("feature/foo", "master", normalise: true, prNumber: 8);
fixture.AssertFullSemver("1.0.2-PullRequest0008.3", config);
}
[Test]
public void SupportBranches()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit(); // 1.0.1
fixture.MakeACommit(); // 1.0.2
fixture.AssertFullSemver("1.0.2", config);
fixture.BranchTo("support/1.0", "support10");
fixture.AssertFullSemver("1.0.3", config);
// Move master on
fixture.Checkout("master");
fixture.MakeACommit("+semver: major"); // 2.0.0 (on master)
fixture.AssertFullSemver("2.0.0", config);
// Continue on support/1.0
fixture.Checkout("support/1.0");
fixture.MakeACommit(); // 1.0.4
fixture.MakeACommit(); // 1.0.5
fixture.AssertFullSemver("1.0.5", config);
fixture.BranchTo("feature/foo", "foo");
fixture.AssertFullSemver("1.0.5-foo.0", config);
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.5-foo.1", config);
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.5-foo.2", config);
fixture.Repository.CreatePullRequestRef("feature/foo", "support/1.0", normalise: true, prNumber: 7);
fixture.AssertFullSemver("1.0.5-PullRequest0007.3", config);
}
[Test]
public void VerifyForwardMerge()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit(); // 1.0.1
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.2-foo.1", config);
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.2-foo.2", config);
fixture.Checkout("master");
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.2", config);
fixture.Checkout("feature/foo");
// This may seem surprising, but this happens because we branched off mainline
// and incremented. Mainline has then moved on. We do not follow mainline
// in feature branches, you need to merge mainline in to get the mainline version
fixture.AssertFullSemver("1.0.2-foo.2", config);
fixture.MergeNoFF("master");
fixture.AssertFullSemver("1.0.3-foo.3", config);
}
[Test]
public void VerifySupportForwardMerge()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit(); // 1.0.1
fixture.BranchTo("support/1.0", "support10");
fixture.MakeACommit();
fixture.MakeACommit();
fixture.Checkout("master");
fixture.MakeACommit("+semver: minor");
fixture.AssertFullSemver("1.1.0", config);
fixture.MergeNoFF("support/1.0");
fixture.AssertFullSemver("1.1.1", config);
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.2", config);
fixture.Checkout("support/1.0");
fixture.AssertFullSemver("1.0.4", config);
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit();
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.4-foo.2", config); // TODO This probably should be 1.0.5
}
[Test]
public void VerifyDevelopTracksMasterVersion()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit();
// branching increments the version
fixture.BranchTo("develop");
fixture.AssertFullSemver("1.1.0-alpha.0", config);
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.0-alpha.1", config);
// merging develop into master increments minor version on master
fixture.Checkout("master");
fixture.MergeNoFF("develop");
fixture.AssertFullSemver("1.1.0", config);
// a commit on develop before the merge still has the same version number
fixture.Checkout("develop");
fixture.AssertFullSemver("1.1.0-alpha.1", config);
// moving on to further work on develop tracks master's version from the merge
fixture.MakeACommit();
fixture.AssertFullSemver("1.2.0-alpha.1", config);
// adding a commit to master increments patch
fixture.Checkout("master");
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.1", config);
// adding a commit to master doesn't change develop's version
fixture.Checkout("develop");
fixture.AssertFullSemver("1.2.0-alpha.1", config);
}
[Test]
public void VerifyDevelopFeatureTracksMasterVersion()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit();
// branching increments the version
fixture.BranchTo("develop");
fixture.AssertFullSemver("1.1.0-alpha.0", config);
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.0-alpha.1", config);
// merging develop into master increments minor version on master
fixture.Checkout("master");
fixture.MergeNoFF("develop");
fixture.AssertFullSemver("1.1.0", config);
// a commit on develop before the merge still has the same version number
fixture.Checkout("develop");
fixture.AssertFullSemver("1.1.0-alpha.1", config);
// a branch from develop before the merge tracks the pre-merge version from master
// (note: the commit on develop looks like a commit to this branch, thus the .1)
fixture.BranchTo("feature/foo");
fixture.AssertFullSemver("1.0.2-foo.1", config);
// further work on the branch tracks the merged version from master
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.1-foo.1", config);
// adding a commit to master increments patch
fixture.Checkout("master");
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.1", config);
// adding a commit to master doesn't change the feature's version
fixture.Checkout("feature/foo");
fixture.AssertFullSemver("1.1.1-foo.1", config);
// merging the feature to develop increments develop
fixture.Checkout("develop");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.2.0-alpha.2", config);
}
[Test]
public void VerifyMergingMasterToFeatureDoesNotCauseBranchCommitsToIncrementVersion()
{
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit("first in master");
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("first in foo");
fixture.Checkout("master");
fixture.MakeACommit("second in master");
fixture.Checkout("feature/foo");
fixture.MergeNoFF("master");
fixture.MakeACommit("second in foo");
fixture.Checkout("master");
fixture.MakeATaggedCommit("1.0.0");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.0.1", config);
}
[Test]
public void VerifyMergingMasterToFeatureDoesNotStopMasterCommitsIncrementingVersion()
{
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit("first in master");
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("first in foo");
fixture.Checkout("master");
fixture.MakeATaggedCommit("1.0.0");
fixture.MakeACommit("third in master");
fixture.Checkout("feature/foo");
fixture.MergeNoFF("master");
fixture.MakeACommit("second in foo");
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.0.2", config);
}
[Test]
public void VerifyIssue1154CanForwardMergeMasterToFeatureBranch()
{
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit();
fixture.BranchTo("feature/branch2");
fixture.BranchTo("feature/branch1");
fixture.MakeACommit();
fixture.MakeACommit();
fixture.Checkout("master");
fixture.MergeNoFF("feature/branch1");
fixture.AssertFullSemver("0.1.1", config);
fixture.Checkout("feature/branch2");
fixture.MakeACommit();
fixture.MakeACommit();
fixture.MakeACommit();
fixture.MergeNoFF("master");
fixture.AssertFullSemver("0.1.2-branch2.4", config);
}
[Test]
public void VerifyMergingMasterIntoAFeatureBranchWorksWithMultipleBranches()
{
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit("first in master");
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("first in foo");
fixture.BranchTo("feature/bar", "bar");
fixture.MakeACommit("first in bar");
fixture.Checkout("master");
fixture.MakeACommit("second in master");
fixture.Checkout("feature/foo");
fixture.MergeNoFF("master");
fixture.MakeACommit("second in foo");
fixture.Checkout("feature/bar");
fixture.MergeNoFF("master");
fixture.MakeACommit("second in bar");
fixture.Checkout("master");
fixture.MakeATaggedCommit("1.0.0");
fixture.MergeNoFF("feature/foo");
fixture.MergeNoFF("feature/bar");
fixture.AssertFullSemver("1.0.2", config);
}
[Test]
public void MergingFeatureBranchThatIncrementsMinorNumberIncrementsMinorVersionOfMaster()
{
var currentConfig = new Config
{
VersioningMode = VersioningMode.Mainline,
Branches = new Dictionary<string, BranchConfig>
{
{
"feature", new BranchConfig
{
VersioningMode = VersioningMode.ContinuousDeployment,
Increment = IncrementStrategy.Minor
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit("first in master");
fixture.MakeATaggedCommit("1.0.0");
fixture.AssertFullSemver("1.0.0", currentConfig);
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("first in foo");
fixture.MakeACommit("second in foo");
fixture.AssertFullSemver("1.1.0-foo.2", currentConfig);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.1.0", currentConfig);
}
[Test]
public void VerifyIncrementConfigIsHonoured()
{
var minorIncrementConfig = new Config
{
VersioningMode = VersioningMode.Mainline,
Increment = IncrementStrategy.Minor,
Branches = new Dictionary<string, BranchConfig>
{
{
"master",
new BranchConfig
{
Increment = IncrementStrategy.Minor,
Name = "master",
Regex = "master"
}
},
{
"feature",
new BranchConfig
{
Increment = IncrementStrategy.Minor,
Name = "feature",
Regex = "features?[/-]"
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit("1");
fixture.MakeATaggedCommit("1.0.0");
fixture.BranchTo("feature/foo", "foo");
fixture.MakeACommit("2");
fixture.AssertFullSemver("1.1.0-foo.1", minorIncrementConfig);
fixture.MakeACommit("2.1");
fixture.AssertFullSemver("1.1.0-foo.2", minorIncrementConfig);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo");
fixture.AssertFullSemver("1.1.0", minorIncrementConfig);
fixture.BranchTo("feature/foo2", "foo2");
fixture.MakeACommit("3 +semver: patch");
fixture.AssertFullSemver("1.1.1-foo2.1", minorIncrementConfig);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo2");
fixture.AssertFullSemver("1.1.1", minorIncrementConfig);
fixture.BranchTo("feature/foo3", "foo3");
fixture.MakeACommit("4");
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo3");
fixture.SequenceDiagram.NoteOver("Merge message contains '+semver: patch'", "master");
var commit = fixture.Repository.Head.Tip;
// Put semver increment in merge message
fixture.Repository.Commit(commit.Message + " +semver: patch", commit.Author, commit.Committer, new CommitOptions
{
AmendPreviousCommit = true
});
fixture.AssertFullSemver("1.1.2", minorIncrementConfig);
fixture.BranchTo("feature/foo4", "foo4");
fixture.MakeACommit("5 +semver: major");
fixture.AssertFullSemver("2.0.0-foo4.1", minorIncrementConfig);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo4");
fixture.AssertFullSemver("2.0.0", config);
// We should evaluate any commits not included in merge commit calculations for direct commit/push or squash to merge commits
fixture.MakeACommit("6 +semver: major");
fixture.AssertFullSemver("3.0.0", minorIncrementConfig);
fixture.MakeACommit("7");
fixture.AssertFullSemver("3.1.0", minorIncrementConfig);
fixture.MakeACommit("8 +semver: patch");
fixture.AssertFullSemver("3.1.1", minorIncrementConfig);
// Finally verify that the merge commits still function properly
fixture.BranchTo("feature/foo5", "foo5");
fixture.MakeACommit("9 +semver: patch");
fixture.AssertFullSemver("3.1.2-foo5.1", minorIncrementConfig);
fixture.Checkout("master");
fixture.MergeNoFF("feature/foo5");
fixture.AssertFullSemver("3.1.2", minorIncrementConfig);
// One more direct commit for good measure
fixture.MakeACommit("10 +semver: patch");
fixture.AssertFullSemver("3.1.3", minorIncrementConfig);
// And we can commit without bumping semver
fixture.MakeACommit("11 +semver: none");
fixture.AssertFullSemver("3.1.3", minorIncrementConfig);
Console.WriteLine(fixture.SequenceDiagram.GetDiagram());
}
}
internal static class CommitExtensions
{
public static void MakeACommit(this RepositoryFixtureBase fixture, string commitMsg)
{
fixture.Repository.MakeACommit(commitMsg);
var diagramBuilder = (StringBuilder)typeof(SequenceDiagram)
.GetField("_diagramBuilder", BindingFlags.Instance | BindingFlags.NonPublic)
?.GetValue(fixture.SequenceDiagram);
string GetParticipant(string participant) =>
(string)typeof(SequenceDiagram).GetMethod("GetParticipant", BindingFlags.Instance | BindingFlags.NonPublic)
?.Invoke(fixture.SequenceDiagram, new object[]
{
participant
});
diagramBuilder.AppendLineFormat("{0} -> {0}: Commit '{1}'", GetParticipant(fixture.Repository.Head.FriendlyName),
commitMsg);
}
}
}
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System;
using System.Collections.Generic;
using Voxalia.ClientGame.GraphicsSystems;
using Voxalia.Shared;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
using Voxalia.ClientGame.OtherSystems;
using Voxalia.Shared.Collision;
using Voxalia.ClientGame.EntitySystem;
namespace Voxalia.ClientGame.WorldSystem
{
public partial class Chunk
{
public VBO _VBO = null;
public List<KeyValuePair<Vector3i, Material>> Lits = new List<KeyValuePair<Vector3i, Material>>();
public bool Edited = true;
public int Plant_VAO = -1;
public int Plant_VBO_Pos = -1;
public int Plant_VBO_Ind = -1;
public int Plant_VBO_Col = -1;
public int Plant_VBO_Tcs = -1;
public int Plant_C;
public List<Entity> CreatedEnts = new List<Entity>();
public bool CreateVBO()
{
List<KeyValuePair<Vector3i, Material>> tLits = new List<KeyValuePair<Vector3i, Material>>();
if (CSize == CHUNK_SIZE)
{
List<Entity> cents = new List<Entity>();
for (int x = 0; x < CHUNK_SIZE; x++)
{
for (int y = 0; y < CHUNK_SIZE; y++)
{
for (int z = 0; z < CHUNK_SIZE; z++)
{
BlockInternal bi = GetBlockAt(x, y, z);
if (bi.Material.GetLightEmitRange() > 0.01)
{
tLits.Add(new KeyValuePair<Vector3i, Material>(new Vector3i(x, y, z), bi.Material));
}
MaterialSpawnType mst = bi.Material.GetSpawnType();
if (mst == MaterialSpawnType.FIRE)
{
cents.Add(new FireEntity(WorldPosition.ToLocation() * Chunk.CHUNK_SIZE + new Location(x, y, z - 1), null, OwningRegion));
}
}
}
}
OwningRegion.TheClient.Schedule.ScheduleSyncTask(() =>
{
foreach (Entity e in CreatedEnts)
{
OwningRegion.Despawn(e);
}
CreatedEnts = cents;
foreach (Entity e in cents)
{
OwningRegion.SpawnEntity(e);
}
});
}
Lits = tLits;
return OwningRegion.NeedToRender(this);
}
public void CalcSkyLight(Chunk above)
{
if (CSize != CHUNK_SIZE)
{
for (int x = 0; x < CSize; x++)
{
for (int y = 0; y < CSize; y++)
{
for (int z = 0; z < CSize; z++)
{
BlocksInternal[BlockIndex(x, y, z)].BlockLocalData = 255;
}
}
}
return;
}
for (int x = 0; x < CHUNK_SIZE; x++)
{
for (int y = 0; y < CHUNK_SIZE; y++)
{
byte light = (above != null && above.CSize == CHUNK_SIZE) ? above.GetBlockAt(x, y, 0).BlockLocalData : (byte)255;
for (int z = CHUNK_SIZE - 1; z >= 0; z--)
{
if (light > 0)
{
BlockInternal bi = GetBlockAt(x, y, z);
double transc = Colors.AlphaForByte(bi.BlockPaint);
if (bi.Material.IsOpaque())
{
light = (byte)(light * (1.0 - (BlockShapeRegistry.BSD[bi.BlockData].LightDamage * transc)));
}
else
{
light = (byte)(light * (1.0 - (bi.Material.GetLightDamage() * transc)));
}
}
BlocksInternal[BlockIndex(x, y, z)].BlockLocalData = light;
}
}
}
}
/// <summary>
/// Internal region call only.
/// </summary>
public void MakeVBONow()
{
if (SucceededBy != null)
{
SucceededBy.MakeVBONow();
return;
}
Chunk c_zp = OwningRegion.GetChunk(WorldPosition + new Vector3i(0, 0, 1));
Chunk c_zm = OwningRegion.GetChunk(WorldPosition + new Vector3i(0, 0, -1));
Chunk c_yp = OwningRegion.GetChunk(WorldPosition + new Vector3i(0, 1, 0));
Chunk c_ym = OwningRegion.GetChunk(WorldPosition + new Vector3i(0, -1, 0));
Chunk c_xp = OwningRegion.GetChunk(WorldPosition + new Vector3i(1, 0, 0));
Chunk c_xm = OwningRegion.GetChunk(WorldPosition + new Vector3i(-1, 0, 0));
Chunk c_zpxp = OwningRegion.GetChunk(WorldPosition + new Vector3i(0, 1, 1));
Chunk c_zpxm = OwningRegion.GetChunk(WorldPosition + new Vector3i(0, -1, 1));
Chunk c_zpyp = OwningRegion.GetChunk(WorldPosition + new Vector3i(1, 0, 1));
Chunk c_zpym = OwningRegion.GetChunk(WorldPosition + new Vector3i(-1, 0, 1));
List<Chunk> potentials = new List<Chunk>();
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
for (int z = -1; z <= 1; z++)
{
Chunk tch = OwningRegion.GetChunk(WorldPosition + new Vector3i(x, y, z));
if (tch != null)
{
potentials.Add(tch);
}
}
}
}
bool plants = PosMultiplier == 1 && OwningRegion.TheClient.CVars.r_plants.ValueB;
bool shaped = OwningRegion.TheClient.CVars.r_noblockshapes.ValueB;
Action a = () => VBOHInternal(c_zp, c_zm, c_yp, c_ym, c_xp, c_xm, c_zpxp, c_zpxm, c_zpyp, c_zpym, potentials, plants, shaped);
if (rendering != null)
{
ASyncScheduleItem item = OwningRegion.TheClient.Schedule.AddASyncTask(a);
rendering = rendering.ReplaceOrFollowWith(item);
}
else
{
rendering = OwningRegion.TheClient.Schedule.StartASyncTask(a);
}
}
public ASyncScheduleItem rendering = null;
public static Vector3i[] dirs = new Vector3i[] { new Vector3i(1, 0, 0), new Vector3i(0, 1, 0), new Vector3i(0, 0, 1), new Vector3i(1, 1, 0), new Vector3i(0, 1, 1), new Vector3i(1, 0, 1),
new Vector3i(-1, 1, 0), new Vector3i(0, -1, 1), new Vector3i(-1, 0, 1), new Vector3i(1, 1, 1), new Vector3i(-1, 1, 1), new Vector3i(1, -1, 1), new Vector3i(1, 1, -1), new Vector3i(-1, -1, 1),
new Vector3i(-1, 1, -1), new Vector3i(1, -1, -1) };
BlockInternal GetLODRelative(Chunk c, int x, int y, int z)
{
if (c.PosMultiplier == PosMultiplier)
{
return c.GetBlockAt(x, y, z);
}
if (c.PosMultiplier > PosMultiplier)
{
return new BlockInternal((ushort)Material.STONE, 0, 0, 0);
}
for (int bx = 0; bx < PosMultiplier; bx++)
{
for (int by = 0; by < PosMultiplier; by++)
{
for (int bz = 0; bz < PosMultiplier; bz++)
{
if (!c.GetBlockAt(x * PosMultiplier + bx, y * PosMultiplier + bx, z * PosMultiplier + bz).IsOpaque())
{
return BlockInternal.AIR;
}
}
}
}
return new BlockInternal((ushort)Material.STONE, 0, 0, 0);
}
void VBOHInternal(Chunk c_zp, Chunk c_zm, Chunk c_yp, Chunk c_ym, Chunk c_xp, Chunk c_xm, Chunk c_zpxp, Chunk c_zpxm, Chunk c_zpyp, Chunk c_zpym, List<Chunk> potentials, bool plants, bool shaped)
{
try
{
ChunkRenderHelper rh;
rh = new ChunkRenderHelper();
BlockInternal t_air = new BlockInternal((ushort)Material.AIR, 0, 0, 255);
List<Vector3> poses = new List<Vector3>();
List<Vector4> colorses = new List<Vector4>();
List<Vector2> tcses = new List<Vector2>();
Vector3d wp = ClientUtilities.ConvertD(WorldPosition.ToLocation()) * CHUNK_SIZE;
for (int x = 0; x < CSize; x++)
{
for (int y = 0; y < CSize; y++)
{
for (int z = 0; z < CSize; z++)
{
BlockInternal c = GetBlockAt(x, y, z);
if (c.Material.RendersAtAll())
{
BlockInternal zp = z + 1 < CSize ? GetBlockAt(x, y, z + 1) : (c_zp == null ? t_air : GetLODRelative(c_zp, x, y, z + 1 - CSize));
BlockInternal zm = z > 0 ? GetBlockAt(x, y, z - 1) : (c_zm == null ? t_air : GetLODRelative(c_zm, x, y, z - 1 + CSize));
BlockInternal yp = y + 1 < CSize ? GetBlockAt(x, y + 1, z) : (c_yp == null ? t_air : GetLODRelative(c_yp, x, y + 1 - CSize, z));
BlockInternal ym = y > 0 ? GetBlockAt(x, y - 1, z) : (c_ym == null ? t_air : GetLODRelative(c_ym, x, y - 1 + CSize, z));
BlockInternal xp = x + 1 < CSize ? GetBlockAt(x + 1, y, z) : (c_xp == null ? t_air : GetLODRelative(c_xp, x + 1 - CSize, y, z));
BlockInternal xm = x > 0 ? GetBlockAt(x - 1, y, z) : (c_xm == null ? t_air : GetLODRelative(c_xm, x - 1 + CSize, y, z));
bool rAS = !((Material)c.BlockMaterial).GetCanRenderAgainstSelf();
bool pMatters = !c.IsOpaque();
bool zps = (zp.DamageData == 0) && (zp.IsOpaque() || (rAS && (zp.BlockMaterial == c.BlockMaterial && (pMatters || zp.BlockPaint == c.BlockPaint)))) && BlockShapeRegistry.BSD[shaped ? 0 : zp.BlockData].OccupiesBOTTOM();
bool zms = (zm.DamageData == 0) && (zm.IsOpaque() || (rAS && (zm.BlockMaterial == c.BlockMaterial && (pMatters || zm.BlockPaint == c.BlockPaint)))) && BlockShapeRegistry.BSD[shaped ? 0 : zm.BlockData].OccupiesTOP();
bool xps = (xp.DamageData == 0) && (xp.IsOpaque() || (rAS && (xp.BlockMaterial == c.BlockMaterial && (pMatters || xp.BlockPaint == c.BlockPaint)))) && BlockShapeRegistry.BSD[shaped ? 0 : xp.BlockData].OccupiesXM();
bool xms = (xm.DamageData == 0) && (xm.IsOpaque() || (rAS && (xm.BlockMaterial == c.BlockMaterial && (pMatters || xm.BlockPaint == c.BlockPaint)))) && BlockShapeRegistry.BSD[shaped ? 0 : xm.BlockData].OccupiesXP();
bool yps = (yp.DamageData == 0) && (yp.IsOpaque() || (rAS && (yp.BlockMaterial == c.BlockMaterial && (pMatters || yp.BlockPaint == c.BlockPaint)))) && BlockShapeRegistry.BSD[shaped ? 0 : yp.BlockData].OccupiesYM();
bool yms = (ym.DamageData == 0) && (ym.IsOpaque() || (rAS && (ym.BlockMaterial == c.BlockMaterial && (pMatters || ym.BlockPaint == c.BlockPaint)))) && BlockShapeRegistry.BSD[shaped ? 0 : ym.BlockData].OccupiesYP();
if (zps && zms && xps && xms && yps && yms)
{
continue;
}
BlockInternal zpyp;
BlockInternal zpym;
BlockInternal zpxp;
BlockInternal zpxm;
if (z + 1 >= CSize)
{
zpyp = y + 1 < CSize ? (c_zp == null ? t_air : GetLODRelative(c_zp, x, y + 1, z + 1 - CSize)) : (c_zpyp == null ? t_air : GetLODRelative(c_zpyp, x, y + 1 - CSize, z + 1 - CSize));
zpym = y > 0 ? (c_zp == null ? t_air : GetLODRelative(c_zp, x, y - 1, z + 1 - CSize)) : (c_zpym == null ? t_air : GetLODRelative(c_zpym, x, y - 1 + CSize, z + 1 - CSize));
zpxp = x + 1 < CSize ? (c_zp == null ? t_air : GetLODRelative(c_zp, x + 1, y, z + 1 - CSize)) : (c_zpxp == null ? t_air : GetLODRelative(c_zpxp, x + 1 - CSize, y, z + 1 - CSize));
zpxm = x > 0 ? (c_zp == null ? t_air : GetLODRelative(c_zp, x - 1, y, z + 1 - CSize)) : (c_zpxm == null ? t_air : GetLODRelative(c_zpxm, x - 1 + CSize, y, z + 1 - CSize));
}
else
{
zpyp = y + 1 < CSize ? GetBlockAt(x, y + 1, z + 1) : (c_yp == null ? t_air : GetLODRelative(c_yp, x, y + 1 - CSize, z + 1));
zpym = y > 0 ? GetBlockAt(x, y - 1, z + 1) : (c_ym == null ? t_air : GetLODRelative(c_ym, x, y - 1 + CSize, z + 1));
zpxp = x + 1 < CSize ? GetBlockAt(x + 1, y, z + 1) : (c_xp == null ? t_air : GetLODRelative(c_xp, x + 1 - CSize, y, z + 1));
zpxm = x > 0 ? GetBlockAt(x - 1, y, z + 1) : (c_xm == null ? t_air : GetLODRelative(c_xm, x - 1 + CSize, y, z + 1));
}
int index_bssd = (xps ? 1 : 0) | (xms ? 2 : 0) | (yps ? 4 : 0) | (yms ? 8 : 0) | (zps ? 16 : 0) | (zms ? 32 : 0);
List<BEPUutilities.Vector3> vecsi = BlockShapeRegistry.BSD[shaped ? 0 : c.BlockData].Damaged[shaped ? 0 : c.DamageData].BSSD.Verts[index_bssd];
List<BEPUutilities.Vector3> normsi = BlockShapeRegistry.BSD[shaped ? 0 : c.BlockData].Damaged[shaped ? 0 : c.DamageData].BSSD.Norms[index_bssd];
BEPUutilities.Vector3[] tci = BlockShapeRegistry.BSD[shaped ? 0 : c.BlockData].Damaged[shaped ? 0 : c.DamageData].GetTCoordsQuick(index_bssd, c.Material);
KeyValuePair<List<BEPUutilities.Vector4>, List<BEPUutilities.Vector4>> ths = !c.BlockShareTex ? default(KeyValuePair<List<BEPUutilities.Vector4>, List<BEPUutilities.Vector4>>) :
BlockShapeRegistry.BSD[shaped ? 0 : c.BlockData].GetStretchData(new BEPUutilities.Vector3(x, y, z), vecsi, xp, xm, yp, ym, zp, zm, xps, xms, yps, yms, zps, zms);
for (int i = 0; i < vecsi.Count; i++)
{
Vector3 vt = new Vector3((float)(x + vecsi[i].X) * PosMultiplier, (float)(y + vecsi[i].Y) * PosMultiplier, (float)(z + vecsi[i].Z) * PosMultiplier);
rh.Vertices.Add(vt);
Vector3 nt = new Vector3((float)normsi[i].X, (float)normsi[i].Y, (float)normsi[i].Z);
rh.Norms.Add(nt);
rh.TCoords.Add(new Vector3((float)tci[i].X, (float)tci[i].Y, (float)tci[i].Z));
byte reldat = 255;
if (nt.X > 0.6)
{
reldat = zpxp.BlockLocalData;
}
else if (nt.X < -0.6)
{
reldat = zpxm.BlockLocalData;
}
else if (nt.Y > 0.6)
{
reldat = zpyp.BlockLocalData;
}
else if (nt.Y < -0.6)
{
reldat = zpym.BlockLocalData;
}
else if (nt.Z < 0)
{
reldat = c.BlockLocalData;
}
else
{
reldat = zp.BlockLocalData;
}
Location lcol = OwningRegion.GetLightAmountForSkyValue(ClientUtilities.Convert(vt) + WorldPosition.ToLocation() * CHUNK_SIZE, ClientUtilities.Convert(nt), potentials, reldat / 255f);
rh.Cols.Add(new Vector4((float)lcol.X, (float)lcol.Y, (float)lcol.Z, 1));
rh.TCols.Add(OwningRegion.TheClient.Rendering.AdaptColor(wp + ClientUtilities.ConvertToD(vt), Colors.ForByte(c.BlockPaint)));
if (ths.Key != null)
{
rh.THVs.Add(new Vector4((float)ths.Key[i].X, (float)ths.Key[i].Y, (float)ths.Key[i].Z, (float)ths.Key[i].W));
rh.THWs.Add(new Vector4((float)ths.Value[i].X, (float)ths.Value[i].Y, (float)ths.Value[i].Z, (float)ths.Value[i].W));
}
else
{
rh.THVs.Add(Vector4.Zero);
rh.THWs.Add(Vector4.Zero);
}
}
if (!c.IsOpaque() && BlockShapeRegistry.BSD[shaped ? 0 : c.BlockData].BackTextureAllowed)
{
int tf = rh.Cols.Count - vecsi.Count;
for (int i = vecsi.Count - 1; i >= 0; i--)
{
Vector3 vt = new Vector3((float)(x + vecsi[i].X) * PosMultiplier, (float)(y + vecsi[i].Y) * PosMultiplier, (float)(z + vecsi[i].Z) * PosMultiplier);
rh.Vertices.Add(vt);
int tx = tf + i;
rh.Cols.Add(rh.Cols[tx]);
rh.TCols.Add(rh.TCols[tx]);
rh.Norms.Add(new Vector3((float)-normsi[i].X, (float)-normsi[i].Y, (float)-normsi[i].Z));
rh.TCoords.Add(new Vector3((float)tci[i].X, (float)tci[i].Y, (float)tci[i].Z));
if (ths.Key != null)
{
rh.THVs.Add(new Vector4((float)ths.Key[i].X, (float)ths.Key[i].Y, (float)ths.Key[i].Z, (float)ths.Key[i].W));
rh.THWs.Add(new Vector4((float)ths.Value[i].X, (float)ths.Value[i].Y, (float)ths.Value[i].Z, (float)ths.Value[i].W));
}
else
{
rh.THVs.Add(Vector4.Zero);
rh.THWs.Add(Vector4.Zero);
}
}
}
if (plants && c.Material.GetPlant() != null && !zp.Material.IsOpaque() && zp.Material.GetSolidity() == MaterialSolidity.NONSOLID)
{
Location skylight = OwningRegion.GetLightAmountForSkyValue(new Location(WorldPosition.X * Chunk.CHUNK_SIZE + x + 0.5, WorldPosition.Y * Chunk.CHUNK_SIZE + y + 0.5,
WorldPosition.Z * Chunk.CHUNK_SIZE + z + 1.0), Location.UnitZ, potentials, zp.BlockLocalData / 255f);
for (int plx = 1; plx < 4; plx++)
{
for (int ply = 0; ply < 3; ply++)
{
BEPUutilities.RayHit rayhit;
if (!BlockShapeRegistry.BSD[c.BlockData].Coll.RayCast(new BEPUutilities.Ray(new BEPUutilities.Vector3(0.3333f * plx, 0.3333f * ply, 3), new BEPUutilities.Vector3(0, 0, -1)), 5, out rayhit))
{
rayhit.Location = new BEPUutilities.Vector3(0.33333 * plx + 0.01, 0.33333 * ply + 0.01, 1.0);
}
poses.Add(new Vector3(x + (float)rayhit.Location.X, y + (float)rayhit.Location.Y, z + (float)rayhit.Location.Z));
colorses.Add(new Vector4((float)skylight.X, (float)skylight.Y, (float)skylight.Z, 1.0f));
tcses.Add(new Vector2(1, OwningRegion.TheClient.GrassMatSet[(int)c.Material])); // TODO: 1 -> custom per-mat scaling!
}
}
}
}
}
}
}
for (int i = 0; i < rh.Vertices.Count; i += 3)
{
Vector3 v1 = rh.Vertices[i];
Vector3 dv1 = rh.Vertices[i + 1] - v1;
Vector3 dv2 = rh.Vertices[i + 2] - v1;
Vector3 t1 = rh.TCoords[i];
Vector3 dt1 = rh.TCoords[i + 1] - t1;
Vector3 dt2 = rh.TCoords[i + 2] - t1;
Vector3 tangent = (dv1 * dt2.Y - dv2 * dt1.Y) / (dt1.X * dt2.Y - dt1.Y * dt2.X);
//Vector3 normal = rh.Norms[i];
//tangent = (tangent - normal * Vector3.Dot(normal, tangent)).Normalized(); // TODO: Necessity of this correction?
rh.Tangs.Add(tangent);
rh.Tangs.Add(tangent);
rh.Tangs.Add(tangent);
}
if (rh.Vertices.Count == 0)
{
if (_VBO != null)
{
VBO tV = _VBO;
if (OwningRegion.TheClient.vbos.Count < MAX_VBOS_REMEMBERED)
{
OwningRegion.TheClient.vbos.Push(tV);
}
else
{
OwningRegion.TheClient.Schedule.ScheduleSyncTask(() =>
{
tV.Destroy();
});
}
}
IsAir = true;
_VBO = null;
OwningRegion.DoneRendering(this);
return;
}
uint[] inds = new uint[rh.Vertices.Count];
for (uint i = 0; i < rh.Vertices.Count; i++)
{
inds[i] = i;
}
VBO tVBO;
if (!OwningRegion.TheClient.vbos.TryPop(out tVBO))
{
tVBO = new VBO();
}
tVBO.indices = inds;
tVBO.Vertices = rh.Vertices;
tVBO.Normals = rh.Norms;
tVBO.TexCoords = rh.TCoords;
tVBO.Colors = rh.Cols;
tVBO.TCOLs = rh.TCols;
tVBO.THVs = rh.THVs;
tVBO.THWs = rh.THWs;
tVBO.Tangents = rh.Tangs;
tVBO.BoneWeights = null;
tVBO.BoneIDs = null;
tVBO.BoneWeights2 = null;
tVBO.BoneIDs2 = null;
tVBO.oldvert();
Vector3[] posset = poses.ToArray();
Vector4[] colorset = colorses.ToArray();
Vector2[] texcoordsset = tcses.ToArray();
uint[] posind = new uint[posset.Length];
for (uint i = 0; i < posind.Length; i++)
{
posind[i] = i;
}
OwningRegion.TheClient.Schedule.ScheduleSyncTask(() =>
{
VBO tV = _VBO;
if (tV != null)
{
if (OwningRegion.TheClient.vbos.Count < MAX_VBOS_REMEMBERED)
{
OwningRegion.TheClient.vbos.Push(tV);
}
else
{
tV.Destroy();
}
}
_VBO = tVBO;
tVBO.GenerateOrUpdate();
tVBO.CleanLists();
DestroyPlants();
Plant_VAO = GL.GenVertexArray();
Plant_VBO_Ind = GL.GenBuffer();
Plant_VBO_Pos = GL.GenBuffer();
Plant_VBO_Col = GL.GenBuffer();
Plant_VBO_Tcs = GL.GenBuffer();
Plant_C = posind.Length;
GL.BindBuffer(BufferTarget.ArrayBuffer, Plant_VBO_Pos);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(posset.Length * OpenTK.Vector3.SizeInBytes), posset, BufferUsageHint.StaticDraw);
GL.BindBuffer(BufferTarget.ArrayBuffer, Plant_VBO_Tcs);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(texcoordsset.Length * OpenTK.Vector2.SizeInBytes), texcoordsset, BufferUsageHint.StaticDraw);
GL.BindBuffer(BufferTarget.ArrayBuffer, Plant_VBO_Col);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(colorset.Length * OpenTK.Vector4.SizeInBytes), colorset, BufferUsageHint.StaticDraw);
GL.BindBuffer(BufferTarget.ElementArrayBuffer, Plant_VBO_Ind);
GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(posind.Length * sizeof(uint)), posind, BufferUsageHint.StaticDraw);
GL.BindVertexArray(Plant_VAO);
GL.BindBuffer(BufferTarget.ArrayBuffer, Plant_VBO_Pos);
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, 0);
GL.EnableVertexAttribArray(0);
GL.BindBuffer(BufferTarget.ArrayBuffer, Plant_VBO_Tcs);
GL.VertexAttribPointer(2, 2, VertexAttribPointerType.Float, false, 0, 0);
GL.EnableVertexAttribArray(2);
GL.BindBuffer(BufferTarget.ArrayBuffer, Plant_VBO_Col);
GL.VertexAttribPointer(4, 4, VertexAttribPointerType.Float, false, 0, 0);
GL.EnableVertexAttribArray(4);
GL.BindBuffer(BufferTarget.ElementArrayBuffer, Plant_VBO_Ind);
GL.BindVertexArray(0);
OnRendered?.Invoke();
});
OwningRegion.DoneRendering(this);
}
catch (Exception ex)
{
SysConsole.Output(OutputType.ERROR, "Generating ChunkVBO...: " + ex.ToString());
OwningRegion.DoneRendering(this);
}
}
public const int MAX_VBOS_REMEMBERED = 40; // TODO: Is this number good? Should this functionality exist at all?
public bool IsAir = false;
public void Render()
{
if (_VBO != null && _VBO.generated)
{
Matrix4d mat = Matrix4d.CreateTranslation(ClientUtilities.ConvertD(WorldPosition.ToLocation() * CHUNK_SIZE));
OwningRegion.TheClient.MainWorldView.SetMatrix(2, mat);
_VBO.Render(OwningRegion.TheClient.RenderTextures);
}
}
public Chunk SucceededBy = null;
public Action OnRendered = null;
}
public class ChunkRenderHelper
{
const int CSize = Chunk.CHUNK_SIZE;
public ChunkRenderHelper()
{
Vertices = new List<Vector3>(CSize * CSize * CSize);
TCoords = new List<Vector3>(CSize * CSize * CSize);
Norms = new List<Vector3>(CSize * CSize * CSize);
Cols = new List<Vector4>(CSize * CSize * CSize);
TCols = new List<Vector4>(CSize * CSize * CSize);
THVs = new List<Vector4>(CSize * CSize * CSize);
THWs = new List<Vector4>(CSize * CSize * CSize);
Tangs = new List<Vector3>(CSize * CSize * CSize);
}
public List<Vector3> Vertices;
public List<Vector3> TCoords;
public List<Vector3> Norms;
public List<Vector4> Cols;
public List<Vector4> TCols;
public List<Vector4> THVs;
public List<Vector4> THWs;
public List<Vector3> Tangs;
}
}
| |
/*
Copyright(c) 2009, Stefan Simek
Copyright(c) 2016, Vladyslav Taranov
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
#if FEAT_IKVM
using IKVM.Reflection;
using IKVM.Reflection.Emit;
using Type = IKVM.Reflection.Type;
using MissingMethodException = System.MissingMethodException;
using MissingMemberException = System.MissingMemberException;
using DefaultMemberAttribute = System.Reflection.DefaultMemberAttribute;
using Attribute = IKVM.Reflection.CustomAttributeData;
using BindingFlags = IKVM.Reflection.BindingFlags;
#else
using System.Reflection;
using System.Reflection.Emit;
#endif
namespace TriAxis.RunSharp
{
public interface IDelayedDefinition
{
void EndDefinition();
}
public interface IDelayedCompletion
{
void Complete();
}
#if !PHONE8
public class TypeGen : MemberGenBase<TypeGen>, ITypeInfoProvider, ICodeGenBasicContext
{
class InterfaceImplEntry
{
public InterfaceImplEntry(IMemberInfo interfaceMethod)
{
InterfaceMethod = interfaceMethod;
}
public bool Match(MethodGen candidate)
{
return candidate.Name == InterfaceMethod.Name &&
candidate.ReturnType == InterfaceMethod.ReturnType &&
ArrayUtils.Equals(candidate.ParameterTypes, InterfaceMethod.ParameterTypes);
}
public IMemberInfo InterfaceMethod { get; }
public Type InterfaceType => InterfaceMethod.Member.DeclaringType;
public MethodGen BoundMethod { get; set; }
public bool IsBound => BoundMethod != null;
public void Bind(MethodGen implementation)
{
BoundMethod = implementation;
}
}
readonly AssemblyGen _owner;
public ExpressionFactory ExpressionFactory => _owner.ExpressionFactory;
public StaticFactory StaticFactory => _owner.StaticFactory;
Type[] _interfaces;
readonly ITypeMapper _typeMapper;
Type _type;
MethodGen _commonCtor;
ConstructorGen _staticCtor;
readonly List<IDelayedDefinition> _definitionQueue = new List<IDelayedDefinition>();
readonly List<IDelayedCompletion> _completionQueue = new List<IDelayedCompletion>();
readonly List<TypeGen> _nestedTypes = new List<TypeGen>();
readonly List<InterfaceImplEntry> _implementations = new List<InterfaceImplEntry>();
readonly List<IMemberInfo> _constructors = new List<IMemberInfo>();
readonly List<IMemberInfo> _fields = new List<IMemberInfo>();
readonly List<IMemberInfo> _properties = new List<IMemberInfo>();
readonly List<IMemberInfo> _events = new List<IMemberInfo>();
readonly List<IMemberInfo> _methods = new List<IMemberInfo>();
List<AttributeGen> _customAttributes = new List<AttributeGen>();
string _indexerName;
internal AssemblyBuilder AssemblyBuilder => _owner.AssemblyBuilder;
internal TypeBuilder TypeBuilder { get; }
internal Type BaseType { get; }
public string Name { get; }
internal TypeGen(AssemblyGen owner, string name, TypeAttributes attrs, Type baseType, Type[] interfaces, ITypeMapper typeMapper)
: base(typeMapper)
{
_owner = owner;
Name = name;
BaseType = baseType;
_interfaces = interfaces;
_typeMapper = typeMapper;
TypeBuilder = owner.ModuleBuilder.DefineType(name, attrs, baseType, interfaces);
owner.AddType(this);
ScanMethodsToImplement(interfaces);
typeMapper.TypeInfo.RegisterProvider(TypeBuilder, this);
ResetAttrs();
}
internal TypeGen(TypeGen owner, string name, TypeAttributes attrs, Type baseType, Type[] interfaces, ITypeMapper typeMapper)
: base(typeMapper)
{
_owner = owner._owner;
Name = name;
BaseType = baseType;
_interfaces = interfaces;
_typeMapper = typeMapper;
TypeBuilder = owner.TypeBuilder.DefineNestedType(name, attrs, baseType, interfaces);
owner._nestedTypes.Add(this);
ScanMethodsToImplement(interfaces);
typeMapper.TypeInfo.RegisterProvider(TypeBuilder, this);
}
void ScanMethodsToImplement(Type[] interfaces)
{
if (interfaces == null)
return;
foreach (Type t in interfaces)
{
foreach (Type @interface in _typeMapper.TypeInfo.SearchInterfaces(t))
{
foreach (IMemberInfo mi in _typeMapper.TypeInfo.GetMethods(@interface))
_implementations.Add(new InterfaceImplEntry(mi));
}
}
}
internal MethodAttributes PreprocessAttributes(MethodGen mg, MethodAttributes attrs)
{
bool requireVirtual = false;
foreach (InterfaceImplEntry implEntry in _implementations)
{
if (!implEntry.IsBound && implEntry.Match(mg))
{
implEntry.Bind(mg);
requireVirtual = true;
}
}
if (requireVirtual && ((attrs & MethodAttributes.Virtual) == 0))
// create an exclusive VTable entry for the method
attrs |= MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final;
return attrs;
}
internal void RegisterForCompletion(ICodeGenContext routine)
{
_definitionQueue.Add(routine);
_completionQueue.Add(routine);
}
internal void RegisterForCompletion(IDelayedCompletion completion)
{
_completionQueue.Add(completion);
}
#region Modifiers
MethodAttributes _mthVis, _mthFlags, _mthVirt;
FieldAttributes _fldVis, _fldFlags;
TypeAttributes _typeVis, _typeFlags, _typeVirt;
MethodImplAttributes _implFlags;
void SetVisibility(MethodAttributes mthVis, FieldAttributes fldVis, TypeAttributes typeVis)
{
if (_mthVis != 0)
throw new InvalidOperationException(Properties.Messages.ErrMultiVisibility);
_mthVis = mthVis;
_fldVis = fldVis;
_typeVis = typeVis;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Public { get { SetVisibility(MethodAttributes.Public, FieldAttributes.Public, TypeAttributes.NestedPublic); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Private { get { SetVisibility(MethodAttributes.Private, FieldAttributes.Private, TypeAttributes.NestedPrivate); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Protected { get { SetVisibility(MethodAttributes.Family, FieldAttributes.Family, TypeAttributes.NestedFamily); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Internal { get { SetVisibility(MethodAttributes.Assembly, FieldAttributes.Assembly, TypeAttributes.NestedAssembly); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen ProtectedOrInternal { get { SetVisibility(MethodAttributes.FamORAssem, FieldAttributes.FamORAssem, TypeAttributes.NestedFamORAssem); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen ProtectedAndInternal { get { SetVisibility(MethodAttributes.FamANDAssem, FieldAttributes.FamANDAssem, TypeAttributes.NestedFamANDAssem); return this; } }
void SetVirtual(MethodAttributes mthVirt, TypeAttributes typeVirt)
{
if (_mthVirt != 0)
throw new InvalidOperationException(Properties.Messages.ErrMultiVTable);
_mthVirt = mthVirt;
_typeVirt = typeVirt;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Sealed { get { SetVirtual(MethodAttributes.Virtual | MethodAttributes.Final, TypeAttributes.Sealed); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Virtual { get { SetVirtual(MethodAttributes.Virtual | MethodAttributes.NewSlot, 0); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Override { get { SetVirtual(MethodAttributes.Virtual, 0); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Abstract { get { SetVirtual(MethodAttributes.Virtual | MethodAttributes.Abstract, TypeAttributes.Abstract); return this; } }
void SetFlag(MethodAttributes mthFlag, FieldAttributes fldFlag, TypeAttributes typeFlag)
{
if ((_mthFlags & mthFlag) != 0 ||
(_fldFlags & fldFlag) != 0 ||
(_typeFlags & typeFlag) != 0)
throw new InvalidOperationException(string.Format(null, Properties.Messages.ErrMultiAttribute, mthFlag));
_mthFlags |= mthFlag;
_fldFlags |= fldFlag;
_typeFlags |= typeFlag;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen Static { get { SetFlag(MethodAttributes.Static, FieldAttributes.Static, TypeAttributes.Sealed | TypeAttributes.Abstract); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen ReadOnly { get { SetFlag(0, FieldAttributes.InitOnly, 0); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public TypeGen NoBeforeFieldInit { get { SetFlag(0, 0, TypeAttributes.BeforeFieldInit); return this; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal TypeGen RuntimeImpl { get { _implFlags |= MethodImplAttributes.Runtime | MethodImplAttributes.Managed; return this; } }
void ResetAttrs()
{
if (TypeBuilder.IsInterface)
{
_mthVis = MethodAttributes.Public;
_mthVirt = MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Abstract;
_mthFlags = 0;
}
else
_mthVis = _mthVirt = _mthFlags = 0;
_fldVis = _fldFlags = 0;
_typeVis = _typeVirt = _typeFlags = 0;
_implFlags = 0;
}
#endregion
#region Custom Attributes
public override TypeGen Attribute(AttributeType type)
{
BeginAttribute(type);
return this;
}
public override TypeGen Attribute(AttributeType type, params object[] args)
{
BeginAttribute(type, args);
return this;
}
public override AttributeGen<TypeGen> BeginAttribute(AttributeType type)
{
return BeginAttribute(type, EmptyArray<object>.Instance);
}
public override AttributeGen<TypeGen> BeginAttribute(AttributeType type, params object[] args)
{
AttributeTargets target = AttributeTargets.Class;
if (BaseType == null)
target = AttributeTargets.Interface;
else if (BaseType == TypeMapper.MapType(typeof(ValueType)))
target = AttributeTargets.Struct;
else
target = AttributeTargets.Class;
return AttributeGen<TypeGen>.CreateAndAdd(this, ref _customAttributes, target, type, args, TypeMapper);
}
#endregion
#region Members
public MethodGen CommonConstructor()
{
if (TypeBuilder.IsValueType)
throw new InvalidOperationException(Properties.Messages.ErrStructNoDefaultCtor);
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoCtor);
if (_commonCtor == null)
{
_commonCtor = new MethodGen(this, "$$ctor", 0, TypeMapper.MapType(typeof(void)), 0).LockSignature();
}
return _commonCtor;
}
public ConstructorGen Constructor()
{
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoCtor);
ConstructorGen cg = new ConstructorGen(this, _mthVis, _implFlags);
ResetAttrs();
return cg;
}
public ConstructorGen StaticConstructor()
{
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoCtor);
if (_staticCtor == null)
{
_staticCtor = new ConstructorGen(this, MethodAttributes.Static, 0).LockSignature();
}
return _staticCtor;
}
#if FEAT_IKVM
public FieldGen Field(System.Type type, string name)
{
return Field(TypeMapper.MapType(type), name);
}
#endif
public FieldGen Field(Type type, string name)
{
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoField);
if (_fldVis == 0)
_fldVis |= FieldAttributes.Private;
FieldGen fld = new FieldGen(this, name, type, _fldVis | _fldFlags);
_fields.Add(fld);
ResetAttrs();
return fld;
}
#if FEAT_IKVM
public FieldGen Field(System.Type type, string name, Operand initialValue)
{
return Field(TypeMapper.MapType(type), name, initialValue);
}
#endif
public FieldGen Field(Type type, string name, Operand initialValue)
{
FieldGen fld = Field(type, name);
CodeGen initCode = fld.IsStatic ? StaticConstructor().GetCode(): CommonConstructor().GetCode();
initCode.Assign(fld, initialValue);
return fld;
}
#if FEAT_IKVM
public PropertyGen Property(System.Type type, string name)
{
return Property(TypeMapper.MapType(type), name);
}
#endif
public PropertyGen Property(Type type, string name)
{
if (_mthVis == 0)
_mthVis |= MethodAttributes.Private;
if (TypeBuilder.IsInterface)
_mthVirt |= MethodAttributes.Virtual | MethodAttributes.Abstract;
PropertyGen pg = new PropertyGen(this, _mthVis | _mthVirt | _mthFlags, type, name);
_properties.Add(pg);
ResetAttrs();
return pg;
}
#if FEAT_IKVM
public PropertyGen Indexer(System.Type type)
{
return Indexer(TypeMapper.MapType(type));
}
#endif
public PropertyGen Indexer(Type type)
{
return Indexer(type, "Item");
}
#if FEAT_IKVM
public PropertyGen Indexer(System.Type type, string name)
{
return Indexer(TypeMapper.MapType(type), name);
}
#endif
public PropertyGen Indexer(Type type, string name)
{
if (_indexerName != null && _indexerName != name)
throw new InvalidOperationException(Properties.Messages.ErrAmbiguousIndexerName);
PropertyGen pg = Property(type, name);
_indexerName = name;
return pg;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "It is invalid to use anything else than a Field as a base for SimpleProperty")]
public PropertyGen SimpleProperty(FieldGen field, string name)
{
if ((object)field == null)
throw new ArgumentNullException(nameof(field));
PropertyGen pg = Property(field.GetReturnType(_typeMapper), name);
pg.Getter().GetCode().Return(field);
pg.Setter().GetCode().Assign(field, pg.Setter().GetCode().PropertyValue());
return pg;
}
#if FEAT_IKVM
public EventGen Event(System.Type handlerType, string name)
{
return Event(TypeMapper.MapType(handlerType), name);
}
#endif
public EventGen Event(Type handlerType, string name)
{
return CustomEvent(handlerType, name).WithStandardImplementation();
}
#if FEAT_IKVM
public EventGen CustomEvent(System.Type handlerType, string name)
{
return CustomEvent(TypeMapper.MapType(handlerType), name);
}
#endif
public EventGen CustomEvent(Type handlerType, string name)
{
EventGen eg = new EventGen(this, name, handlerType, _mthVis | _mthVirt | _mthFlags);
_events.Add(eg);
ResetAttrs();
return eg;
}
#if FEAT_IKVM
public MethodGen Method(System.Type returnType, string name)
{
return Method(TypeMapper.MapType(returnType), name);
}
#endif
public MethodGen Method(Type returnType, string name)
{
if (_mthVis == 0)
_mthVis |= MethodAttributes.Private;
if (TypeBuilder.IsInterface)
_mthVirt |= MethodAttributes.Virtual | MethodAttributes.Abstract;
MethodGen mg = new MethodGen(this, name, _mthVis | _mthVirt | _mthFlags, returnType, _implFlags);
ResetAttrs();
return mg;
}
#if FEAT_IKVM
public MethodGen ImplicitConversionFrom(System.Type fromType)
{
return ImplicitConversionFrom(TypeMapper.MapType(fromType));
}
#endif
public MethodGen ImplicitConversionFrom(Type fromType)
{
return ImplicitConversionFrom(fromType, "value");
}
#if FEAT_IKVM
public MethodGen ImplicitConversionFrom(System.Type fromType, string parameterName)
{
return ImplicitConversionFrom(TypeMapper.MapType(fromType), parameterName);
}
#endif
public MethodGen ImplicitConversionFrom(Type fromType, string parameterName)
{
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoConversion);
ResetAttrs();
_mthFlags = MethodAttributes.SpecialName | MethodAttributes.Static;
_mthVis = MethodAttributes.Public;
return Method(TypeBuilder, "op_Implicit").Parameter(fromType, parameterName);
}
#if FEAT_IKVM
public MethodGen ImplicitConversionTo(System.Type toType)
{
return ImplicitConversionTo(TypeMapper.MapType(toType));
}
#endif
public MethodGen ImplicitConversionTo(Type toType)
{
return ImplicitConversionTo(toType, "value");
}
#if FEAT_IKVM
public MethodGen ImplicitConversionTo(System.Type toType, string parameterName)
{
return ImplicitConversionTo(TypeMapper.MapType(toType), parameterName);
}
#endif
public MethodGen ImplicitConversionTo(Type toType, string parameterName)
{
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoConversion);
ResetAttrs();
_mthFlags = MethodAttributes.SpecialName | MethodAttributes.Static;
_mthVis = MethodAttributes.Public;
return Method(toType, "op_Implicit").Parameter(TypeBuilder, parameterName);
}
#if FEAT_IKVM
public MethodGen ExplicitConversionFrom(System.Type fromType)
{
return ExplicitConversionFrom(TypeMapper.MapType(fromType));
}
#endif
public MethodGen ExplicitConversionFrom(Type fromType)
{
return ExplicitConversionFrom(fromType, "value");
}
#if FEAT_IKVM
public MethodGen ExplicitConversionFrom(System.Type fromType, string parameterName)
{
return ExplicitConversionFrom(TypeMapper.MapType(fromType), parameterName);
}
#endif
public MethodGen ExplicitConversionFrom(Type fromType, string parameterName)
{
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoConversion);
ResetAttrs();
_mthFlags = MethodAttributes.SpecialName | MethodAttributes.Static;
_mthVis = MethodAttributes.Public;
return Method(TypeBuilder, "op_Explicit").Parameter(fromType, parameterName);
}
#if FEAT_IKVM
public MethodGen ExplicitConversionTo(System.Type toType)
{
return ExplicitConversionTo(TypeMapper.MapType(toType));
}
#endif
public MethodGen ExplicitConversionTo(Type toType)
{
return ExplicitConversionTo(toType, "value");
}
#if FEAT_IKVM
public MethodGen ExplicitConversionTo(System.Type toType, string parameterName)
{
return ExplicitConversionTo(TypeMapper.MapType(toType), parameterName);
}
#endif
public MethodGen ExplicitConversionTo(Type toType, string parameterName)
{
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoConversion);
ResetAttrs();
_mthFlags = MethodAttributes.SpecialName | MethodAttributes.Static;
_mthVis = MethodAttributes.Public;
return Method(toType, "op_Explicit").Parameter(TypeBuilder, parameterName);
}
#if FEAT_IKVM
public MethodGen Operator(Operator op, System.Type returnType, System.Type operandType)
{
return Operator(op, TypeMapper.MapType(returnType), TypeMapper.MapType(operandType));
}
#endif
public MethodGen Operator(Operator op, Type returnType, Type operandType)
{
return Operator(op, returnType, operandType, "operand");
}
#if FEAT_IKVM
public MethodGen Operator(Operator op, System.Type returnType, System.Type operandType, string operandName)
{
return Operator(op, TypeMapper.MapType(returnType), TypeMapper.MapType(operandType), operandName);
}
public MethodGen Operator(Operator op, Type returnType, System.Type operandType, string operandName)
{
return Operator(op, returnType, TypeMapper.MapType(operandType), operandName);
}
public MethodGen Operator(Operator op, System.Type returnType, Type operandType, string operandName)
{
return Operator(op, TypeMapper.MapType(returnType), operandType, operandName);
}
#endif
public MethodGen Operator(Operator op, Type returnType, Type operandType, string operandName)
{
if (op == null)
throw new ArgumentNullException(nameof(op));
ResetAttrs();
_mthFlags = MethodAttributes.SpecialName | MethodAttributes.Static;
_mthVis = MethodAttributes.Public;
return Method(returnType, "op_" + op.MethodName).Parameter(operandType, operandName);
}
#if FEAT_IKVM
public MethodGen Operator(Operator op, System.Type returnType, System.Type leftType, System.Type rightType)
{
return Operator(op, TypeMapper.MapType(returnType), TypeMapper.MapType(leftType), TypeMapper.MapType(rightType));
}
#endif
public MethodGen Operator(Operator op, Type returnType, Type leftType, Type rightType)
{
return Operator(op, returnType, leftType, "left", rightType, "right");
}
#if FEAT_IKVM
public MethodGen Operator(Operator op, System.Type returnType, System.Type leftType, string leftName, System.Type rightType, string rightName)
{
return Operator(op, TypeMapper.MapType(returnType), TypeMapper.MapType(leftType), leftName, TypeMapper.MapType(rightType), rightName);
}
#endif
public MethodGen Operator(Operator op, Type returnType, Type leftType, string leftName, Type rightType, string rightName)
{
if (op == null)
throw new ArgumentNullException(nameof(op));
ResetAttrs();
_mthFlags = MethodAttributes.SpecialName | MethodAttributes.Static;
_mthVis = MethodAttributes.Public;
return Method(returnType, "op_" + op.MethodName)
.Parameter(leftType, leftName)
.Parameter(rightType, rightName)
;
}
public TypeGen Class(string name)
{
return Class(name, TypeMapper.MapType(typeof(object)), Type.EmptyTypes);
}
#if FEAT_IKVM
public TypeGen Class(string name, System.Type baseType)
{
return Class(name, TypeMapper.MapType(baseType));
}
#endif
public TypeGen Class(string name, Type baseType)
{
return Class(name, baseType, Type.EmptyTypes);
}
#if FEAT_IKVM
public TypeGen Class(string name, System.Type baseType, params Type[] interfaces)
{
return Class(name, TypeMapper.MapType(baseType), interfaces);
}
#endif
public TypeGen Class(string name, Type baseType, params Type[] interfaces)
{
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoNested);
if (_typeVis == 0)
_typeVis |= TypeAttributes.NestedPrivate;
TypeGen tg = new TypeGen(this, name, (_typeVis | _typeVirt | _typeFlags | TypeAttributes.Class) ^ TypeAttributes.BeforeFieldInit, baseType, interfaces, _typeMapper);
ResetAttrs();
return tg;
}
public TypeGen Struct(string name)
{
return Struct(name, Type.EmptyTypes);
}
public TypeGen Struct(string name, params Type[] interfaces)
{
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoNested);
if (_typeVis == 0)
_typeVis |= TypeAttributes.NestedPrivate;
TypeGen tg = new TypeGen(this, name, (_typeVis | _typeVirt | _typeFlags | TypeAttributes.Sealed | TypeAttributes.SequentialLayout) ^ TypeAttributes.BeforeFieldInit, TypeMapper.MapType(typeof(ValueType)), interfaces, _typeMapper);
ResetAttrs();
return tg;
}
#if FEAT_IKVM
public DelegateGen Delegate(System.Type returnType, string name)
{
return Delegate(TypeMapper.MapType(returnType), name);
}
#endif
public DelegateGen Delegate(Type returnType, string name)
{
DelegateGen dg = new DelegateGen(this, name, returnType, (_typeVis | _typeVirt | _typeFlags | TypeAttributes.Class | TypeAttributes.Sealed) ^ TypeAttributes.BeforeFieldInit);
ResetAttrs();
return dg;
}
#endregion
#region Interface implementations
void DefineMethodOverride(MethodGen methodBody, MethodInfo methodDeclaration)
{
foreach (InterfaceImplEntry iie in _implementations)
{
if (iie.InterfaceMethod.Member == methodDeclaration
&& iie.InterfaceType == methodDeclaration.DeclaringType)
{
iie.Bind(methodBody);
return;
}
}
}
#if FEAT_IKVM
public MethodGen MethodImplementation(System.Type interfaceType, System.Type returnType, string name)
{
return MethodImplementation(TypeMapper.MapType(interfaceType), TypeMapper.MapType(returnType), name);
}
public MethodGen MethodImplementation(System.Type interfaceType, Type returnType, string name)
{
return MethodImplementation(TypeMapper.MapType(interfaceType), returnType, name);
}
public MethodGen MethodImplementation(Type interfaceType, System.Type returnType, string name)
{
return MethodImplementation(interfaceType, TypeMapper.MapType(returnType), name);
}
#endif
public MethodGen MethodImplementation(Type interfaceType, Type returnType, string name)
{
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoExplicitImpl);
MethodGen mg = new MethodGen(this, name,
MethodAttributes.Private | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final,
returnType, 0);
mg.ImplementedInterface = interfaceType;
return mg;
}
#if FEAT_IKVM
public PropertyGen PropertyImplementation(System.Type interfaceType, System.Type type, string name)
{
return PropertyImplementation(TypeMapper.MapType(interfaceType), TypeMapper.MapType(type), name);
}
#endif
public PropertyGen PropertyImplementation(Type interfaceType, Type type, string name)
{
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoExplicitImpl);
PropertyGen pg = new PropertyGen(this,
MethodAttributes.Private | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final,
type, name);
pg.ImplementedInterface = interfaceType;
return pg;
}
#if FEAT_IKVM
public EventGen EventImplementation(System.Type interfaceType, System.Type eventHandlerType, string name)
{
return EventImplementation(TypeMapper.MapType(interfaceType), TypeMapper.MapType(eventHandlerType), name);
}
#endif
public EventGen EventImplementation(Type interfaceType, Type eventHandlerType, string name)
{
if (TypeBuilder.IsInterface)
throw new InvalidOperationException(Properties.Messages.ErrInterfaceNoExplicitImpl);
EventGen eg = new EventGen(this, name, eventHandlerType,
MethodAttributes.Private | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final);
eg.ImplementedInterface = interfaceType;
return eg;
}
#endregion
public Type GetCompletedType()
{
return GetCompletedType(false);
}
public Type GetCompletedType(bool completeIfNeeded)
{
if (_type != null)
return _type;
if (completeIfNeeded)
{
Complete();
return _type;
}
throw new InvalidOperationException(Properties.Messages.ErrTypeNotCompleted);
}
public bool IsCompleted => _type != null;
void FlushDefinitionQueue()
{
// cannot use foreach, because it is possible that new objects
// will be appended while completing the existing ones
for (int i = 0; i < _definitionQueue.Count; i++)
{
_definitionQueue[i].EndDefinition();
}
_definitionQueue.Clear();
}
void FlushCompletionQueue()
{
// cannot use foreach, because it is possible that new objects
// will be appended while completing the existing ones
for (int i = 0; i < _completionQueue.Count; i++)
{
_completionQueue[i].Complete();
}
_completionQueue.Clear();
}
public void Complete()
{
if (_type != null)
return;
if (TypeBuilder.IsValueType)
{
if (_fields.Count == 0 && _properties.Count == 0)
{
// otherwise "Value class has neither fields nor size parameter."
Private.ReadOnly.Field(_typeMapper.MapType(typeof(int)), "_____");
}
}
foreach (TypeGen nested in _nestedTypes)
nested.Complete();
// ensure creation of default constructor
EnsureDefaultConstructor();
FlushDefinitionQueue();
FlushCompletionQueue();
// implement all interfaces
foreach (InterfaceImplEntry iie in _implementations)
{
if (!iie.IsBound)
throw new NotImplementedException(string.Format(null, Properties.Messages.ErrInterfaceNotImplemented,
iie.InterfaceType, iie.InterfaceMethod.Member));
TypeBuilder.DefineMethodOverride(iie.BoundMethod.GetMethodBuilder(), (MethodInfo) iie.InterfaceMethod.Member);
}
// set indexer name
if (_indexerName != null)
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(
TypeMapper.MapType(typeof(DefaultMemberAttribute)).GetConstructor(new Type[] { TypeMapper.MapType(typeof(string)) }),
new object[] { _indexerName });
TypeBuilder.SetCustomAttribute(cab);
}
AttributeGen.ApplyList(ref _customAttributes, TypeBuilder.SetCustomAttribute);
_type = TypeBuilder.CreateType();
_typeMapper.TypeInfo.UnregisterProvider(TypeBuilder);
}
public static implicit operator Type(TypeGen tg)
{
if (tg == null)
return null;
if (tg._type != null)
return tg._type;
return tg.TypeBuilder;
}
public override string ToString()
{
return TypeBuilder.FullName;
}
void EnsureDefaultConstructor()
{
if (_constructors.Count == 0 && TypeBuilder.IsClass)
{
// create default constructor
ResetAttrs();
Public.Constructor().LockSignature();
}
}
#region Member registration
internal void Register(ConstructorGen constructor)
{
if (constructor.IsStatic)
return;
if (constructor.ParameterCount == 0 && TypeBuilder.IsValueType)
throw new InvalidOperationException(Properties.Messages.ErrStructNoDefaultCtor);
_constructors.Add(constructor);
}
internal void Register(MethodGen method)
{
#if !SILVERLIGHT
if (_owner.AssemblyBuilder.EntryPoint == null && method.Name == "Main" && method.IsStatic &&
(
method.ParameterCount == 0 ||
(method.ParameterCount == 1 &&
method.ParameterTypes[0] == TypeMapper.MapType(typeof(string[])))))
{
_owner.AssemblyBuilder.SetEntryPoint(method.GetMethodBuilder());
}
#endif
// match explicit interface implementations
if (method.ImplementedInterface != null)
{
foreach (IMemberInfo mi in _typeMapper.TypeInfo.Filter(_typeMapper.TypeInfo.GetMethods(method.ImplementedInterface), method.Name, false, false, true))
{
if (ArrayUtils.Equals(mi.ParameterTypes, method.ParameterTypes))
{
DefineMethodOverride(method, (MethodInfo)mi.Member);
return;
}
}
throw new MissingMethodException(Properties.Messages.ErrMissingMethod);
}
_methods.Add(method);
}
#endregion
#region ITypeInfoProvider implementation
IEnumerable<IMemberInfo> ITypeInfoProvider.GetConstructors()
{
EnsureDefaultConstructor();
FlushDefinitionQueue();
return _constructors;
}
IEnumerable<IMemberInfo> ITypeInfoProvider.GetFields()
{
FlushDefinitionQueue();
return _fields;
}
IEnumerable<IMemberInfo> ITypeInfoProvider.GetProperties()
{
FlushDefinitionQueue();
return _properties;
}
IEnumerable<IMemberInfo> ITypeInfoProvider.GetEvents()
{
FlushDefinitionQueue();
return _events;
}
IEnumerable<IMemberInfo> ITypeInfoProvider.GetMethods()
{
FlushDefinitionQueue();
return _methods;
}
string ITypeInfoProvider.DefaultMember => _indexerName;
#endregion
}
#endif
}
| |
//
// Controls sample in C#
//
using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using System.Drawing;
namespace MonoCatalog {
public partial class ControlsViewController : UITableViewController {
//
// This datasource describes how the UITableView should render the
// contents. We have a number of sections determined by the
// samples in our container class, and 2 rows per section:
//
// Row 0: the actual styled button
// Row 1: the text information about the button
//
class DataSource : UITableViewDataSource {
ControlsViewController cvc;
static NSString kDisplayCell_ID = new NSString ("DisplayCellID");
static NSString kSourceCell_ID = new NSString ("SourceCellID");
public DataSource (ControlsViewController cvc)
{
this.cvc = cvc;
}
public override int NumberOfSections (UITableView tableView)
{
return cvc.samples.Length;
}
public override string TitleForHeader (UITableView tableView, int section)
{
return cvc.samples [section].Title;
}
public override int RowsInSection (UITableView tableView, int section)
{
return 2;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell;
if (indexPath.Row == 0){
cell = tableView.DequeueReusableCell (kDisplayCell_ID);
if (cell == null){
cell = new UITableViewCell (UITableViewCellStyle.Default, kDisplayCell_ID);
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
} else {
// The cell is being recycled, remove the old content
UIView viewToRemove = cell.ContentView.ViewWithTag (kViewTag);
if (viewToRemove != null)
viewToRemove.RemoveFromSuperview ();
}
cell.TextLabel.Text = cvc.samples [indexPath.Section].Label;
cell.ContentView.AddSubview (cvc.samples [indexPath.Section].Control);
} else {
cell = tableView.DequeueReusableCell (kSourceCell_ID);
if (cell == null){
// Construct the cell with reusability (the second argument is not null)
cell = new UITableViewCell (UITableViewCellStyle.Default, kSourceCell_ID);
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
var label = cell.TextLabel;
label.Opaque = false;
label.TextAlignment = UITextAlignment.Center;
label.TextColor = UIColor.Gray;
label.Lines = 2;
label.HighlightedTextColor = UIColor.Black;
label.Font = UIFont.SystemFontOfSize (12f);
}
cell.TextLabel.Text = cvc.samples [indexPath.Section].Source;
}
return cell;
}
}
class TableDelegate : UITableViewDelegate {
public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
{
// First row is always 50 pixes, second row 38
return indexPath.Row == 0 ? 50f : 38f;
}
}
// Load our definition from the NIB file
public ControlsViewController () : base ("ControlsViewController", null)
{
}
// For tagging our embedded controls at cell recylce time.
const int kViewTag = 1;
UIControl SwitchControl ()
{
var sw = new UISwitch (new RectangleF (198f, 12f, 94f, 27f)){
BackgroundColor = UIColor.Clear,
Tag = kViewTag
};
sw.ValueChanged += delegate {
// The enum variant causes a full-aot crash
Console.WriteLine ("New state: {0}", (int) sw.State);
};
return sw;
}
UIControl SliderControl ()
{
var slider = new UISlider (new RectangleF (174f, 12f, 120f, 7f)){
BackgroundColor = UIColor.Clear,
MinValue = 0f,
MaxValue = 100f,
Continuous = true,
Value = 50f,
Tag = kViewTag
};
slider.ValueChanged += delegate {
Console.WriteLine ("New value {0}", slider.Value);
};
return slider;
}
UIControl CustomSliderControl ()
{
var cslider = new UISlider (new RectangleF (174f, 12f, 120f, 7f)){
BackgroundColor = UIColor.Clear,
MinValue = 0f,
MaxValue = 100f,
Continuous = true,
Value = 50f,
Tag = kViewTag
};
var left = UIImage.FromFile ("images/orangeslide.png");
left = left.StretchableImage (10, 0);
var right = UIImage.FromFile ("images/yellowslide.png");
right = right.StretchableImage (10, 0);
cslider.SetThumbImage (UIImage.FromFile ("images/slider_ball.png"), UIControlState.Normal);
cslider.SetMinTrackImage (left, UIControlState.Normal);
cslider.SetMaxTrackImage (right, UIControlState.Normal);
cslider.ValueChanged += delegate {
Console.WriteLine ("New value {0}", cslider.Value);
};
return cslider;
}
UIControl PageControl ()
{
var page = new UIPageControl (new RectangleF (120f, 14f, 178f, 20f)){
BackgroundColor = UIColor.Gray,
Pages = 10,
Tag = kViewTag
};
page.TouchUpInside += delegate {
Console.WriteLine ("Current page: {0}", page.CurrentPage);
};
return page;
}
UIView ProgressIndicator ()
{
var pind = new UIActivityIndicatorView (new RectangleF (265f, 12f, 40f, 40f)){
ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray,
AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin |
UIViewAutoresizing.FlexibleRightMargin |
UIViewAutoresizing.FlexibleTopMargin |
UIViewAutoresizing.FlexibleBottomMargin,
Tag = kViewTag
};
pind.StartAnimating ();
pind.SizeToFit ();
return pind;
}
UIView ProgressBar ()
{
return new UIProgressView (new RectangleF (126f, 20f, 160f, 24f)){
Style = UIProgressViewStyle.Default,
Progress = 0.5f,
Tag = kViewTag
};
}
struct ControlSample {
public string Title, Label, Source;
public UIView Control;
public ControlSample (string t, string l, string s, UIView c)
{
Title = t;
Label = l;
Source = s;
Control = c;
}
}
ControlSample [] samples;
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
Title = "Controls";
samples = new ControlSample [] {
new ControlSample ("UISwitch", "Standard Switch", "controls.cs: SwitchControl ()", SwitchControl ()),
new ControlSample ("UISlider", "Standard Slider", "controls.cs: SliderControl ()", SliderControl ()),
new ControlSample ("UISlider", "Customized Slider", "controls.cs: CustomSliderControl ()", CustomSliderControl ()),
new ControlSample ("UIPageControl", "Ten Pages", "controls.cs: PageControl ()", PageControl ()),
new ControlSample ("UIActivityIndicatorView", "Style Gray", "controls.cs: ProgressIndicator ()", ProgressIndicator ()),
new ControlSample ("UIProgressView", "Style Default", "controls.cs: ProgressBar ()", ProgressBar ()),
};
TableView.DataSource = new DataSource (this);
TableView.Delegate = new TableDelegate ();
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExpressRouteCircuitAuthorizationsOperations operations.
/// </summary>
public partial interface IExpressRouteCircuitAuthorizationsOperations
{
/// <summary>
/// Deletes the specified authorization from the specified express
/// route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates an authorization in the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified authorization from the specified express
/// route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates an authorization in the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//
// OracleParameter.cs
//
// Part of the Mono class libraries at
// mcs/class/System.Data.OracleClient/System.Data.OracleClient
//
// Assembly: System.Data.OracleClient.dll
// Namespace: System.Data.OracleClient
//
// Authors:
// Tim Coleman <[email protected]>
// Daniel Moragn <[email protected]>
//
// Copyright (C) Tim Coleman , 2003
// Copyright (C) Daniel Morgan, 2005
//
// Licensed under the MIT/X11 License.
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient.Oci;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Data.OracleClient {
[TypeConverter (typeof(OracleParameter.OracleParameterConverter))]
public sealed class OracleParameter : MarshalByRefObject, IDbDataParameter, IDataParameter, ICloneable
{
#region Fields
string name;
OracleType oracleType = OracleType.VarChar;
OciDataType ociType;
int size;
ParameterDirection direction = ParameterDirection.Input;
bool isNullable;
byte precision;
byte scale;
string srcColumn;
DataRowVersion srcVersion;
DbType dbType = DbType.AnsiString;
int offset = 0;
bool sizeSet = false;
object value = null;
OciLobLocator lobLocator = null; // only if Blob or Clob
OracleParameterCollection container = null;
OciBindHandle bindHandle;
#endregion // Fields
#region Constructors
// constructor for cloning the object
internal OracleParameter (OracleParameter value) {
this.name = value.name;
this.oracleType = value.oracleType;
this.ociType = value.ociType;
this.size = value.size;
this.direction = value.direction;
this.isNullable = value.isNullable;
this.precision = value.precision;
this.scale = value.scale;
this.srcColumn = value.srcColumn;
this.srcVersion = value.srcVersion;
this.dbType = value.dbType;
this.offset = value.offset;
this.sizeSet = value.sizeSet;
this.value = value.value;
this.lobLocator = value.lobLocator;
}
public OracleParameter ()
: this (String.Empty, OracleType.VarChar, 0, ParameterDirection.Input, false, 0, 0, String.Empty, DataRowVersion.Current, null)
{
}
public OracleParameter (string name, object value)
{
this.name = name;
this.value = value;
SourceVersion = DataRowVersion.Current;
InferOracleType (value);
}
public OracleParameter (string name, OracleType dataType)
: this (name, dataType, 0, ParameterDirection.Input, false, 0, 0, String.Empty, DataRowVersion.Current, null)
{
}
public OracleParameter (string name, OracleType dataType, int size)
: this (name, dataType, size, ParameterDirection.Input, false, 0, 0, String.Empty, DataRowVersion.Current, null)
{
}
public OracleParameter (string name, OracleType dataType, int size, string srcColumn)
: this (name, dataType, size, ParameterDirection.Input, false, 0, 0, srcColumn, DataRowVersion.Current, null)
{
}
public OracleParameter (string name, OracleType dataType, int size, ParameterDirection direction, bool isNullable, byte precision, byte scale, string srcColumn, DataRowVersion srcVersion, object value)
{
this.name = name;
this.size = size;
this.value = value;
OracleType = dataType;
Direction = direction;
SourceColumn = srcColumn;
SourceVersion = srcVersion;
}
#endregion // Constructors
#region Properties
internal OracleParameterCollection Container {
get { return container; }
set { container = value; }
}
[Browsable (false)]
[RefreshProperties (RefreshProperties.All)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public DbType DbType {
get { return dbType; }
set { SetDbType (value); }
}
[DefaultValue (ParameterDirection.Input)]
[RefreshProperties (RefreshProperties.All)]
public ParameterDirection Direction {
get { return direction; }
set { direction = value; }
}
[Browsable (false)]
[DesignOnly (true)]
[DefaultValue (false)]
[EditorBrowsable (EditorBrowsableState.Never)]
public bool IsNullable {
get { return isNullable; }
set { isNullable = value; }
}
[DefaultValue (0)]
[Browsable (false)]
public int Offset {
get { return offset; }
set { offset = value; }
}
[DefaultValue (OracleType.VarChar)]
[RefreshProperties (RefreshProperties.All)]
public OracleType OracleType {
get { return oracleType; }
set { SetOracleType (value); }
}
[DefaultValue ("")]
public string ParameterName {
get { return name; }
set { name = value; }
}
[DefaultValue (0)]
public byte Precision {
get { return precision; }
set { /* NO EFFECT*/ }
}
[DefaultValue (0)]
public byte Scale {
get { return scale; }
set { /* NO EFFECT*/ }
}
[DefaultValue (0)]
public int Size {
get { return size; }
set {
sizeSet = true;
size = value;
}
}
[DefaultValue ("")]
public string SourceColumn {
get { return srcColumn; }
set { srcColumn = value; }
}
[DefaultValue (DataRowVersion.Current)]
public DataRowVersion SourceVersion {
get { return srcVersion; }
set { srcVersion = value; }
}
[DefaultValue (null)]
[RefreshProperties (RefreshProperties.All)]
[TypeConverter (typeof(StringConverter))]
public object Value {
get { return this.value; }
set { this.value = value; }
}
#endregion // Properties
#region Methods
private void AssertSizeIsSet ()
{
if (!sizeSet)
throw new Exception ("Size must be set.");
}
internal void Bind (OciStatementHandle statement, OracleConnection connection)
{
if (bindHandle == null)
bindHandle = new OciBindHandle ((OciHandle) statement);
IntPtr tmpHandle = bindHandle.Handle;
if (Direction != ParameterDirection.Input)
AssertSizeIsSet ();
if (!sizeSet)
size = InferSize ();
byte[] bytes = null;
int status = 0;
int indicator = 0;
OciDataType bindType = ociType;
IntPtr bindValue = IntPtr.Zero;
int bindSize = size;
int rsize = 0;
if (value == DBNull.Value) {
indicator = 0;
bindType = OciDataType.VarChar2;
bindSize = 0;
}
else {
// TODO: do other data types and oracle data types
// should I be using IConvertible to convert?
if (oracleType == OracleType.DateTime) {
string oraDateFormat = connection.GetSessionDateFormat ();
string sysDateFormat = OracleDateTime.ConvertOracleDateFormatToSystemDateTime (oraDateFormat);
string sDate = "";
DateTime dt = DateTime.MinValue;
if (value is String) {
sDate = (string) value;
dt = DateTime.Parse (sDate);
}
else if (value is DateTime)
dt = (DateTime) value;
else if (value is OracleString) {
sDate = (string) value;
dt = DateTime.Parse (sDate);
}
else if (value is OracleDateTime) {
OracleDateTime odt = (OracleDateTime) value;
dt = (DateTime) odt.Value;
}
else
throw new NotImplementedException (); // ?
sDate = dt.ToString (sysDateFormat);
rsize = 0;
// Get size of buffer
OciCalls.OCIUnicodeToCharSet (statement.Parent, null, sDate, out rsize);
// Fill buffer
bytes = new byte[rsize];
OciCalls.OCIUnicodeToCharSet (statement.Parent, bytes, sDate, out rsize);
bindType = OciDataType.VarChar2;
//bindValue = Marshal.StringToHGlobalAnsi (sDate);
bindSize = sDate.Length;
}
else if (oracleType == OracleType.Blob) {
bytes = (byte[]) value;
bindType = OciDataType.LongRaw;
bindSize = bytes.Length;
}
else if (oracleType == OracleType.Clob) {
string v = (string) value;
rsize = 0;
// Get size of buffer
OciCalls.OCIUnicodeToCharSet (statement.Parent, null, v, out rsize);
// Fill buffer
bytes = new byte[rsize];
OciCalls.OCIUnicodeToCharSet (statement.Parent, bytes, v, out rsize);
bindType = OciDataType.Long;
bindSize = bytes.Length;
}
else if (oracleType == OracleType.Raw) {
byte[] val = value as byte[];
bindValue = Marshal.AllocHGlobal (val.Length);
Marshal.Copy (val, 0, bindValue, val.Length);
bindSize = val.Length;
}
else {
string svalue = value.ToString ();
rsize = 0;
// Get size of buffer
OciCalls.OCIUnicodeToCharSet (statement.Parent, null, svalue, out rsize);
// Fill buffer
bytes = new byte[rsize];
OciCalls.OCIUnicodeToCharSet (statement.Parent, bytes, svalue, out rsize);
//bindValue = Marshal.StringToHGlobalAnsi (value.ToString ());
bindType = OciDataType.VarChar2;
bindSize = value.ToString ().Length;
}
}
if (bytes != null) {
status = OciCalls.OCIBindByNameBytes (statement,
out tmpHandle,
connection.ErrorHandle,
ParameterName,
ParameterName.Length,
bytes,
bindSize,
bindType,
indicator,
IntPtr.Zero,
IntPtr.Zero,
0,
IntPtr.Zero,
0);
}
else {
status = OciCalls.OCIBindByName (statement,
out tmpHandle,
connection.ErrorHandle,
ParameterName,
ParameterName.Length,
bindValue,
bindSize,
bindType,
indicator,
IntPtr.Zero,
IntPtr.Zero,
0,
IntPtr.Zero,
0);
}
if (status != 0) {
OciErrorInfo info = connection.ErrorHandle.HandleError ();
throw new OracleException (info.ErrorCode, info.ErrorMessage);
}
bindHandle.SetHandle (tmpHandle);
}
object ICloneable.Clone ()
{
return new OracleParameter(this);
}
private void InferOracleType (object value)
{
Type type = value.GetType ();
string exception = String.Format ("The parameter data type of {0} is invalid.", type.Name);
switch (type.FullName) {
case "System.Int64":
SetOracleType (OracleType.Number);
break;
case "System.Boolean":
case "System.Byte":
SetOracleType (OracleType.Byte);
break;
case "System.String":
SetOracleType (OracleType.VarChar);
break;
case "System.DateTime":
SetOracleType (OracleType.DateTime);
break;
case "System.Decimal":
SetOracleType (OracleType.Number);
//scale = ((decimal) value).Scale;
break;
case "System.Double":
SetOracleType (OracleType.Double);
break;
case "System.Byte[]":
case "System.Guid":
SetOracleType (OracleType.Raw);
break;
case "System.Int32":
SetOracleType (OracleType.Int32);
break;
case "System.Single":
SetOracleType (OracleType.Float);
break;
case "System.Int16":
SetOracleType (OracleType.Int16);
break;
default:
throw new ArgumentException (exception);
}
}
[MonoTODO ("different size depending on type.")]
private int InferSize ()
{
return value.ToString ().Length;
}
private void SetDbType (DbType type)
{
string exception = String.Format ("No mapping exists from DbType {0} to a known OracleType.", type);
switch (type) {
case DbType.AnsiString:
oracleType = OracleType.VarChar;
ociType = OciDataType.VarChar;
break;
case DbType.AnsiStringFixedLength:
oracleType = OracleType.Char;
ociType = OciDataType.Char;
break;
case DbType.Binary:
case DbType.Guid:
oracleType = OracleType.Raw;
ociType = OciDataType.Raw;
break;
case DbType.Boolean:
case DbType.Byte:
oracleType = OracleType.Byte;
ociType = OciDataType.Integer;
break;
case DbType.Currency:
case DbType.Decimal:
case DbType.Int64:
oracleType = OracleType.Number;
ociType = OciDataType.Number;
break;
case DbType.Date:
case DbType.DateTime:
case DbType.Time:
oracleType = OracleType.DateTime;
ociType = OciDataType.Char;
break;
case DbType.Double:
oracleType = OracleType.Double;
ociType = OciDataType.Float;
break;
case DbType.Int16:
oracleType = OracleType.Int16;
ociType = OciDataType.Integer;
break;
case DbType.Int32:
oracleType = OracleType.Int32;
ociType = OciDataType.Integer;
break;
case DbType.Object:
oracleType = OracleType.Blob;
ociType = OciDataType.Blob;
break;
case DbType.Single:
oracleType = OracleType.Float;
ociType = OciDataType.Float;
break;
case DbType.String:
oracleType = OracleType.NVarChar;
ociType = OciDataType.VarChar;
break;
case DbType.StringFixedLength:
oracleType = OracleType.NChar;
ociType = OciDataType.Char;
break;
default:
throw new ArgumentException (exception);
}
dbType = type;
}
private void SetOracleType (OracleType type)
{
string exception = String.Format ("No mapping exists from OracleType {0} to a known DbType.", type);
switch (type) {
case OracleType.BFile:
case OracleType.Blob:
case OracleType.LongRaw:
case OracleType.Raw:
dbType = DbType.Binary;
ociType = OciDataType.Raw;
break;
case OracleType.Byte:
dbType = DbType.Byte;
ociType = OciDataType.Integer;
break;
case OracleType.Char:
dbType = DbType.AnsiStringFixedLength;
ociType = OciDataType.Char;
break;
case OracleType.Clob:
case OracleType.LongVarChar:
case OracleType.RowId:
case OracleType.VarChar:
dbType = DbType.AnsiString;
ociType = OciDataType.VarChar;
break;
case OracleType.Cursor:
case OracleType.IntervalDayToSecond:
dbType = DbType.Object;
ociType = OciDataType.Blob;
break;
case OracleType.DateTime:
case OracleType.Timestamp:
case OracleType.TimestampLocal:
case OracleType.TimestampWithTZ:
dbType = DbType.DateTime;
ociType = OciDataType.Char;
break;
case OracleType.Double:
dbType = DbType.Double;
ociType = OciDataType.Float;
break;
case OracleType.Float:
dbType = DbType.Single;
ociType = OciDataType.Float;
break;
case OracleType.Int16:
dbType = DbType.Int16;
ociType = OciDataType.Integer;
break;
case OracleType.Int32:
case OracleType.IntervalYearToMonth:
dbType = DbType.Int32;
ociType = OciDataType.Integer;
break;
case OracleType.NChar:
dbType = DbType.StringFixedLength;
ociType = OciDataType.Char;
break;
case OracleType.NClob:
case OracleType.NVarChar:
dbType = DbType.String;
ociType = OciDataType.VarChar;
break;
case OracleType.Number:
dbType = DbType.VarNumeric;
ociType = OciDataType.Number;
break;
case OracleType.SByte:
dbType = DbType.SByte;
ociType = OciDataType.Integer;
break;
case OracleType.UInt16:
dbType = DbType.UInt16;
ociType = OciDataType.Integer;
break;
case OracleType.UInt32:
dbType = DbType.UInt32;
ociType = OciDataType.Integer;
break;
default:
throw new ArgumentException (exception);
}
oracleType = type;
}
public override string ToString ()
{
return ParameterName;
}
#endregion // Methods
internal sealed class OracleParameterConverter : ExpandableObjectConverter
{
public OracleParameterConverter ()
{
}
[MonoTODO]
public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException ();
}
}
}
}
| |
// 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.
using Firebase.Firestore;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Firebase.Sample.Firestore {
public sealed class InvalidArgumentsTestCase {
public string name;
public Action<UIHandlerAutomated> action;
}
// Tests that passing invalid input to SWIG-wrapped functions results in a C# exception instead
// of a crash.
public sealed class InvalidArgumentsTest {
public static InvalidArgumentsTestCase[] TestCases {
get {
return new InvalidArgumentsTestCase[] {
new InvalidArgumentsTestCase { name = "CollectionReference_AddAsync_NullDocumentData",
action = CollectionReference_AddAsync_NullDocumentData },
new InvalidArgumentsTestCase {
name = "CollectionReference_AddAsync_DocumentDataWithEmptyKey",
action = CollectionReference_AddAsync_DocumentDataWithEmptyKey
},
new InvalidArgumentsTestCase {
name = "CollectionReference_AddAsync_InvalidDocumentDataType",
action = CollectionReference_AddAsync_InvalidDocumentDataType
},
new InvalidArgumentsTestCase { name = "CollectionReference_Document_NullStringPath",
action = CollectionReference_Document_NullStringPath },
new InvalidArgumentsTestCase { name = "CollectionReference_Document_EmptyStringPath",
action = CollectionReference_Document_EmptyStringPath },
new InvalidArgumentsTestCase {
name = "CollectionReference_Document_EvenNumberOfPathSegments",
action = CollectionReference_Document_EvenNumberOfPathSegments
},
new InvalidArgumentsTestCase { name = "DocumentReference_Collection_NullStringPath",
action = DocumentReference_Collection_NullStringPath },
new InvalidArgumentsTestCase { name = "DocumentReference_Collection_EmptyStringPath",
action = DocumentReference_Collection_EmptyStringPath },
new InvalidArgumentsTestCase {
name = "DocumentReference_Collection_EvenNumberOfPathSegments",
action = DocumentReference_Collection_EvenNumberOfPathSegments
},
new InvalidArgumentsTestCase { name = "DocumentReference_Listen_1Arg_NullCallback",
action = DocumentReference_Listen_1Arg_NullCallback },
new InvalidArgumentsTestCase { name = "DocumentReference_Listen_2Args_NullCallback",
action = DocumentReference_Listen_2Args_NullCallback },
new InvalidArgumentsTestCase { name = "DocumentReference_SetAsync_NullDocumentData",
action = DocumentReference_SetAsync_NullDocumentData },
new InvalidArgumentsTestCase {
name = "DocumentReference_SetAsync_DocumentDataWithEmptyKey",
action = DocumentReference_SetAsync_DocumentDataWithEmptyKey
},
new InvalidArgumentsTestCase {
name = "DocumentReference_SetAsync_InvalidDocumentDataType",
action = DocumentReference_SetAsync_InvalidDocumentDataType
},
new InvalidArgumentsTestCase {
name = "DocumentReference_UpdateAsync_NullStringKeyedDictionary",
action = DocumentReference_UpdateAsync_NullStringKeyedDictionary
},
new InvalidArgumentsTestCase {
name = "DocumentReference_UpdateAsync_EmptyStringKeyedDictionary",
action = DocumentReference_UpdateAsync_EmptyStringKeyedDictionary
},
new InvalidArgumentsTestCase {
name = "DocumentReference_UpdateAsync_StringKeyedDictionaryWithEmptyKey",
action = DocumentReference_UpdateAsync_StringKeyedDictionaryWithEmptyKey
},
new InvalidArgumentsTestCase { name = "DocumentReference_UpdateAsync_NullStringField",
action = DocumentReference_UpdateAsync_NullStringField },
new InvalidArgumentsTestCase { name = "DocumentReference_UpdateAsync_EmptyStringField",
action = DocumentReference_UpdateAsync_EmptyStringField },
new InvalidArgumentsTestCase {
name = "DocumentReference_UpdateAsync_NullFieldPathKeyedDictionary",
action = DocumentReference_UpdateAsync_NullFieldPathKeyedDictionary
},
new InvalidArgumentsTestCase {
name = "DocumentReference_UpdateAsync_EmptyFieldPathKeyedDictionary",
action = DocumentReference_UpdateAsync_EmptyFieldPathKeyedDictionary
},
new InvalidArgumentsTestCase { name = "DocumentSnapshot_ContainsField_NullStringPath",
action = DocumentSnapshot_ContainsField_NullStringPath },
new InvalidArgumentsTestCase { name = "DocumentSnapshot_ContainsField_EmptyStringPath",
action = DocumentSnapshot_ContainsField_EmptyStringPath },
new InvalidArgumentsTestCase { name = "DocumentSnapshot_ContainsField_NullFieldPath",
action = DocumentSnapshot_ContainsField_NullFieldPath },
new InvalidArgumentsTestCase { name = "DocumentSnapshot_GetValue_NullStringPath",
action = DocumentSnapshot_GetValue_NullStringPath },
new InvalidArgumentsTestCase { name = "DocumentSnapshot_GetValue_EmptyStringPath",
action = DocumentSnapshot_GetValue_EmptyStringPath },
new InvalidArgumentsTestCase { name = "DocumentSnapshot_GetValue_NullFieldPath",
action = DocumentSnapshot_GetValue_NullFieldPath },
new InvalidArgumentsTestCase { name = "DocumentSnapshot_TryGetValue_NullStringPath",
action = DocumentSnapshot_TryGetValue_NullStringPath },
new InvalidArgumentsTestCase { name = "DocumentSnapshot_TryGetValue_EmptyStringPath",
action = DocumentSnapshot_TryGetValue_EmptyStringPath },
new InvalidArgumentsTestCase { name = "DocumentSnapshot_TryGetValue_NullFieldPath",
action = DocumentSnapshot_TryGetValue_NullFieldPath },
new InvalidArgumentsTestCase { name = "FieldPath_Constructor_NullStringArray",
action = FieldPath_Constructor_NullStringArray },
new InvalidArgumentsTestCase { name = "FieldPath_Constructor_StringArrayWithNullElement",
action =
FieldPath_Constructor_StringArrayWithNullElement },
new InvalidArgumentsTestCase { name = "FieldPath_Constructor_EmptyStringArray",
action = FieldPath_Constructor_EmptyStringArray },
new InvalidArgumentsTestCase { name = "FieldPath_Constructor_StringArrayWithEmptyString",
action =
FieldPath_Constructor_StringArrayWithEmptyString },
new InvalidArgumentsTestCase { name = "FieldValue_ArrayRemove_NullArray",
action = FieldValue_ArrayRemove_NullArray },
new InvalidArgumentsTestCase { name = "FieldValue_ArrayUnion_NullArray",
action = FieldValue_ArrayUnion_NullArray },
new InvalidArgumentsTestCase { name = "FirebaseFirestore_GetInstance_Null",
action = FirebaseFirestore_GetInstance_Null },
new InvalidArgumentsTestCase { name = "FirebaseFirestore_GetInstance_DisposedApp",
action = FirebaseFirestore_GetInstance_DisposedApp },
new InvalidArgumentsTestCase { name = "FirebaseFirestore_Collection_NullStringPath",
action = FirebaseFirestore_Collection_NullStringPath },
new InvalidArgumentsTestCase { name = "FirebaseFirestore_Collection_EmptyStringPath",
action = FirebaseFirestore_Collection_EmptyStringPath },
new InvalidArgumentsTestCase {
name = "FirebaseFirestore_Collection_EvenNumberOfPathSegments",
action = FirebaseFirestore_Collection_EvenNumberOfPathSegments
},
new InvalidArgumentsTestCase {
name = "FirebaseFirestore_CollectionGroup_NullCollectionId",
action = FirebaseFirestore_CollectionGroup_NullCollectionId
},
new InvalidArgumentsTestCase {
name = "FirebaseFirestore_CollectionGroup_EmptyCollectionId",
action = FirebaseFirestore_CollectionGroup_EmptyCollectionId
},
new InvalidArgumentsTestCase {
name = "FirebaseFirestore_CollectionGroup_CollectionIdContainsSlash",
action = FirebaseFirestore_CollectionGroup_CollectionIdContainsSlash
},
new InvalidArgumentsTestCase { name = "FirebaseFirestore_Document_NullStringPath",
action = FirebaseFirestore_Document_NullStringPath },
new InvalidArgumentsTestCase { name = "FirebaseFirestore_Document_EmptyStringPath",
action = FirebaseFirestore_Document_EmptyStringPath },
new InvalidArgumentsTestCase {
name = "FirebaseFirestore_Document_OddNumberOfPathSegments",
action = FirebaseFirestore_Document_OddNumberOfPathSegments
},
new InvalidArgumentsTestCase {
name = "FirebaseFirestore_ListenForSnapshotsInSync_NullCallback",
action = FirebaseFirestore_ListenForSnapshotsInSync_NullCallback
},
new InvalidArgumentsTestCase {
name = "FirebaseFirestore_RunTransactionAsync_WithoutTypeParameter_NullCallback",
action = FirebaseFirestore_RunTransactionAsync_WithoutTypeParameter_NullCallback
},
new InvalidArgumentsTestCase {
name = "FirebaseFirestore_RunTransactionAsync_WithTypeParameter_NullCallback",
action = FirebaseFirestore_RunTransactionAsync_WithTypeParameter_NullCallback
},
new InvalidArgumentsTestCase { name = "FirebaseFirestoreSettings_Host_Null",
action = FirebaseFirestoreSettings_Host_Null },
new InvalidArgumentsTestCase { name = "FirebaseFirestoreSettings_Host_EmptyString",
action = FirebaseFirestoreSettings_Host_EmptyString },
new InvalidArgumentsTestCase { name = "Query_EndAt_NullDocumentSnapshot",
action = Query_EndAt_NullDocumentSnapshot },
new InvalidArgumentsTestCase { name = "Query_EndAt_NullArray",
action = Query_EndAt_NullArray },
new InvalidArgumentsTestCase { name = "Query_EndAt_ArrayWithNullElement",
action = Query_EndAt_ArrayWithNullElement },
new InvalidArgumentsTestCase { name = "Query_EndBefore_NullDocumentSnapshot",
action = Query_EndBefore_NullDocumentSnapshot },
new InvalidArgumentsTestCase { name = "Query_EndBefore_NullArray",
action = Query_EndBefore_NullArray },
new InvalidArgumentsTestCase { name = "Query_Limit_0", action = Query_Limit_0 },
new InvalidArgumentsTestCase { name = "Query_Limit_Negative1",
action = Query_Limit_Negative1 },
new InvalidArgumentsTestCase { name = "Query_LimitToLast_0",
action = Query_LimitToLast_0 },
new InvalidArgumentsTestCase { name = "Query_LimitToLast_Negative1",
action = Query_LimitToLast_Negative1 },
new InvalidArgumentsTestCase { name = "Query_OrderBy_NullPathString",
action = Query_OrderBy_NullPathString },
new InvalidArgumentsTestCase { name = "Query_OrderBy_EmptyPathString",
action = Query_OrderBy_EmptyPathString },
new InvalidArgumentsTestCase { name = "Query_OrderBy_NullFieldPath",
action = Query_OrderBy_NullFieldPath },
new InvalidArgumentsTestCase { name = "Query_OrderByDescending_NullPathString",
action = Query_OrderByDescending_NullPathString },
new InvalidArgumentsTestCase { name = "Query_OrderByDescending_EmptyPathString",
action = Query_OrderByDescending_EmptyPathString },
new InvalidArgumentsTestCase { name = "Query_OrderByDescending_NullFieldPath",
action = Query_OrderByDescending_NullFieldPath },
new InvalidArgumentsTestCase { name = "Query_StartAfter_NullDocumentSnapshot",
action = Query_StartAfter_NullDocumentSnapshot },
new InvalidArgumentsTestCase { name = "Query_StartAfter_NullArray",
action = Query_StartAfter_NullArray },
new InvalidArgumentsTestCase { name = "Query_StartAt_NullDocumentSnapshot",
action = Query_StartAt_NullDocumentSnapshot },
new InvalidArgumentsTestCase { name = "Query_StartAt_NullArray",
action = Query_StartAt_NullArray },
new InvalidArgumentsTestCase { name = "Query_StartAt_ArrayWithNullElement",
action = Query_StartAt_ArrayWithNullElement },
new InvalidArgumentsTestCase { name = "Query_WhereArrayContains_NullFieldPath",
action = Query_WhereArrayContains_NullFieldPath },
new InvalidArgumentsTestCase { name = "Query_WhereArrayContains_NullPathString",
action = Query_WhereArrayContains_NullPathString },
new InvalidArgumentsTestCase { name = "Query_WhereArrayContains_EmptyPathString",
action = Query_WhereArrayContains_EmptyPathString },
new InvalidArgumentsTestCase { name = "Query_WhereArrayContainsAny_NullFieldPath",
action = Query_WhereArrayContainsAny_NullFieldPath },
new InvalidArgumentsTestCase {
name = "Query_WhereArrayContainsAny_NonNullFieldPath_NullValues",
action = Query_WhereArrayContainsAny_NonNullFieldPath_NullValues
},
new InvalidArgumentsTestCase { name = "Query_WhereArrayContainsAny_NullPathString",
action = Query_WhereArrayContainsAny_NullPathString },
new InvalidArgumentsTestCase { name = "Query_WhereArrayContainsAny_EmptyPathString",
action = Query_WhereArrayContainsAny_EmptyPathString },
new InvalidArgumentsTestCase {
name = "Query_WhereArrayContainsAny_NonNullPathString_NullValues",
action = Query_WhereArrayContainsAny_NonNullPathString_NullValues
},
new InvalidArgumentsTestCase { name = "Query_WhereEqualTo_NullPathString",
action = Query_WhereEqualTo_NullPathString },
new InvalidArgumentsTestCase { name = "Query_WhereEqualTo_EmptyPathString",
action = Query_WhereEqualTo_EmptyPathString },
new InvalidArgumentsTestCase { name = "Query_WhereEqualTo_NullFieldPath",
action = Query_WhereEqualTo_NullFieldPath },
new InvalidArgumentsTestCase { name = "Query_WhereGreaterThan_NullPathString",
action = Query_WhereGreaterThan_NullPathString },
new InvalidArgumentsTestCase { name = "Query_WhereGreaterThan_EmptyPathString",
action = Query_WhereGreaterThan_EmptyPathString },
new InvalidArgumentsTestCase { name = "Query_WhereGreaterThan_NullFieldPath",
action = Query_WhereGreaterThan_NullFieldPath },
new InvalidArgumentsTestCase { name = "Query_WhereGreaterThanOrEqualTo_NullPathString",
action = Query_WhereGreaterThanOrEqualTo_NullPathString },
new InvalidArgumentsTestCase { name = "Query_WhereGreaterThanOrEqualTo_EmptyPathString",
action = Query_WhereGreaterThanOrEqualTo_EmptyPathString },
new InvalidArgumentsTestCase { name = "Query_WhereGreaterThanOrEqualTo_NullFieldPath",
action = Query_WhereGreaterThanOrEqualTo_NullFieldPath },
new InvalidArgumentsTestCase { name = "Query_WhereIn_NullFieldPath",
action = Query_WhereIn_NullFieldPath },
new InvalidArgumentsTestCase { name = "Query_WhereIn_NonNullFieldPath_NullValues",
action = Query_WhereIn_NonNullFieldPath_NullValues },
new InvalidArgumentsTestCase { name = "Query_WhereIn_NullPathString",
action = Query_WhereIn_NullPathString },
new InvalidArgumentsTestCase { name = "Query_WhereIn_EmptyPathString",
action = Query_WhereIn_EmptyPathString },
new InvalidArgumentsTestCase { name = "Query_WhereIn_NonNullPathString_NullValues",
action = Query_WhereIn_NonNullPathString_NullValues },
new InvalidArgumentsTestCase { name = "Query_WhereLessThan_NullPathString",
action = Query_WhereLessThan_NullPathString },
new InvalidArgumentsTestCase { name = "Query_WhereLessThan_EmptyPathString",
action = Query_WhereLessThan_EmptyPathString },
new InvalidArgumentsTestCase { name = "Query_WhereLessThan_NullFieldPath",
action = Query_WhereLessThan_NullFieldPath },
new InvalidArgumentsTestCase { name = "Query_WhereLessThanOrEqualTo_NullPathString",
action = Query_WhereLessThanOrEqualTo_NullPathString },
new InvalidArgumentsTestCase { name = "Query_WhereLessThanOrEqualTo_EmptyPathString",
action = Query_WhereLessThanOrEqualTo_EmptyPathString },
new InvalidArgumentsTestCase { name = "Query_WhereLessThanOrEqualTo_NullFieldPath",
action = Query_WhereLessThanOrEqualTo_NullFieldPath },
new InvalidArgumentsTestCase { name = "Query_WhereNotEqualTo_NullPathString",
action = Query_WhereNotEqualTo_NullPathString },
new InvalidArgumentsTestCase { name = "Query_WhereNotEqualTo_EmptyPathString",
action = Query_WhereNotEqualTo_EmptyPathString },
new InvalidArgumentsTestCase { name = "Query_WhereNotEqualTo_NullFieldPath",
action = Query_WhereNotEqualTo_NullFieldPath },
new InvalidArgumentsTestCase { name = "Query_WhereNotIn_NullFieldPath",
action = Query_WhereNotIn_NullFieldPath },
new InvalidArgumentsTestCase { name = "Query_WhereNotIn_NonNullFieldPath_NullValues",
action = Query_WhereNotIn_NonNullFieldPath_NullValues },
new InvalidArgumentsTestCase { name = "Query_WhereNotIn_NullPathString",
action = Query_WhereNotIn_NullPathString },
new InvalidArgumentsTestCase { name = "Query_WhereNotIn_EmptyPathString",
action = Query_WhereNotIn_EmptyPathString },
new InvalidArgumentsTestCase { name = "Query_WhereNotIn_NonNullPathString_NullValues",
action = Query_WhereNotIn_NonNullPathString_NullValues },
new InvalidArgumentsTestCase { name = "Transaction_Delete_NullDocumentReference",
action = Transaction_Delete_NullDocumentReference },
new InvalidArgumentsTestCase {
name = "Transaction_GetSnapshotAsync_NullDocumentReference",
action = Transaction_GetSnapshotAsync_NullDocumentReference
},
new InvalidArgumentsTestCase { name = "Transaction_Set_NullDocumentReference",
action = Transaction_Set_NullDocumentReference },
new InvalidArgumentsTestCase { name = "Transaction_Set_NullDocumentData",
action = Transaction_Set_NullDocumentData },
new InvalidArgumentsTestCase { name = "Transaction_Set_DocumentDataWithEmptyKey",
action = Transaction_Set_DocumentDataWithEmptyKey },
new InvalidArgumentsTestCase { name = "Transaction_Set_InvalidDocumentDataType",
action = Transaction_Set_InvalidDocumentDataType },
new InvalidArgumentsTestCase {
name = "Transaction_Update_NullDocumentReference_NonNullStringKeyDictionary",
action = Transaction_Update_NullDocumentReference_NonNullStringKeyDictionary
},
new InvalidArgumentsTestCase {
name = "Transaction_Update_NonNullDocumentReference_NullStringKeyDictionary",
action = Transaction_Update_NonNullDocumentReference_NullStringKeyDictionary
},
new InvalidArgumentsTestCase {
name = "Transaction_Update_NonNullDocumentReference_EmptyStringKeyDictionary",
action = Transaction_Update_NonNullDocumentReference_EmptyStringKeyDictionary
},
new InvalidArgumentsTestCase {
name = "Transaction_Update_NonNullDocumentReference_StringKeyDictionaryWithEmptyKey",
action = Transaction_Update_NonNullDocumentReference_StringKeyDictionaryWithEmptyKey
},
new InvalidArgumentsTestCase {
name = "Transaction_Update_NullDocumentReference_NonNullFieldString",
action = Transaction_Update_NullDocumentReference_NonNullFieldString
},
new InvalidArgumentsTestCase {
name = "Transaction_Update_NonNullDocumentReference_NullFieldString",
action = Transaction_Update_NonNullDocumentReference_NullFieldString
},
new InvalidArgumentsTestCase {
name = "Transaction_Update_NullDocumentReference_NonNullFieldPathKeyDictionary",
action = Transaction_Update_NullDocumentReference_NonNullFieldPathKeyDictionary
},
new InvalidArgumentsTestCase {
name = "Transaction_Update_NonNullDocumentReference_NullFieldPathKeyDictionary",
action = Transaction_Update_NonNullDocumentReference_NullFieldPathKeyDictionary
},
new InvalidArgumentsTestCase {
name = "Transaction_Update_NonNullDocumentReference_EmptyFieldPathKeyDictionary",
action = Transaction_Update_NonNullDocumentReference_EmptyFieldPathKeyDictionary
},
new InvalidArgumentsTestCase { name = "WriteBatch_Delete_NullDocumentReference",
action = WriteBatch_Delete_NullDocumentReference },
new InvalidArgumentsTestCase { name = "WriteBatch_Set_NullDocumentReference",
action = WriteBatch_Set_NullDocumentReference },
new InvalidArgumentsTestCase { name = "WriteBatch_Set_NullDocumentData",
action = WriteBatch_Set_NullDocumentData },
new InvalidArgumentsTestCase { name = "WriteBatch_Set_DocumentDataWithEmptyKey",
action = WriteBatch_Set_DocumentDataWithEmptyKey },
new InvalidArgumentsTestCase { name = "WriteBatch_Set_InvalidDocumentDataType",
action = WriteBatch_Set_InvalidDocumentDataType },
new InvalidArgumentsTestCase {
name = "WriteBatch_Update_NullDocumentReference_NonNullStringKeyDictionary",
action = WriteBatch_Update_NullDocumentReference_NonNullStringKeyDictionary
},
new InvalidArgumentsTestCase {
name = "WriteBatch_Update_NonNullDocumentReference_NullStringKeyDictionary",
action = WriteBatch_Update_NonNullDocumentReference_NullStringKeyDictionary
},
new InvalidArgumentsTestCase {
name = "WriteBatch_Update_NonNullDocumentReference_EmptyStringKeyDictionary",
action = WriteBatch_Update_NonNullDocumentReference_EmptyStringKeyDictionary
},
new InvalidArgumentsTestCase {
name = "WriteBatch_Update_NonNullDocumentReference_StringKeyDictionaryWithEmptyKey",
action = WriteBatch_Update_NonNullDocumentReference_StringKeyDictionaryWithEmptyKey
},
new InvalidArgumentsTestCase {
name = "WriteBatch_Update_NullDocumentReference_NonNullFieldString",
action = WriteBatch_Update_NullDocumentReference_NonNullFieldString
},
new InvalidArgumentsTestCase {
name = "WriteBatch_Update_NonNullDocumentReference_NullFieldString",
action = WriteBatch_Update_NonNullDocumentReference_NullFieldString
},
new InvalidArgumentsTestCase {
name = "WriteBatch_Update_NullDocumentReference_NonNullFieldPathKeyDictionary",
action = WriteBatch_Update_NullDocumentReference_NonNullFieldPathKeyDictionary
},
new InvalidArgumentsTestCase {
name = "WriteBatch_Update_NonNullDocumentReference_NullFieldPathKeyDictionary",
action = WriteBatch_Update_NonNullDocumentReference_NullFieldPathKeyDictionary
},
new InvalidArgumentsTestCase {
name = "WriteBatch_Update_NonNullDocumentReference_EmptyFieldPathKeyDictionary",
action = WriteBatch_Update_NonNullDocumentReference_EmptyFieldPathKeyDictionary
},
new InvalidArgumentsTestCase { name = "FirebaseFirestore_LoadBundleAsync_NullBundle",
action = FirebaseFirestore_LoadBundleAsync_NullBundle },
new InvalidArgumentsTestCase {
name = "FirebaseFirestore_LoadBundleAsync_NonNullBundle_NullHandler",
action = FirebaseFirestore_LoadBundleAsync_NonNullBundle_NullHandler
},
new InvalidArgumentsTestCase {
name = "FirebaseFirestore_GetNamedQueryAsync_NullQueryName",
action = FirebaseFirestore_GetNamedQueryAsync_NullQueryName
},
};
}
}
private static void CollectionReference_AddAsync_NullDocumentData(UIHandlerAutomated handler) {
CollectionReference collection = handler.db.Collection("a");
handler.AssertException(typeof(ArgumentNullException), () => collection.AddAsync(null));
}
private static void CollectionReference_AddAsync_DocumentDataWithEmptyKey(
UIHandlerAutomated handler) {
CollectionReference collection = handler.db.Collection("a");
handler.AssertTaskFaults(collection.AddAsync(new Dictionary<string, object> { { "", 42 } }));
}
private static void CollectionReference_AddAsync_InvalidDocumentDataType(
UIHandlerAutomated handler) {
CollectionReference collection = handler.db.Collection("a");
handler.AssertException(typeof(ArgumentException), () => collection.AddAsync(42));
}
private static void CollectionReference_Document_NullStringPath(UIHandlerAutomated handler) {
CollectionReference collection = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException), () => collection.Document(null));
}
private static void CollectionReference_Document_EmptyStringPath(UIHandlerAutomated handler) {
CollectionReference collection = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => collection.Document(""));
}
private static void CollectionReference_Document_EvenNumberOfPathSegments(
UIHandlerAutomated handler) {
CollectionReference collection = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => collection.Document("b/c"));
}
private static void DocumentReference_Collection_NullStringPath(UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentNullException), () => doc.Collection(null));
}
private static void DocumentReference_Collection_EmptyStringPath(UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentException), () => doc.Collection(""));
}
private static void DocumentReference_Collection_EvenNumberOfPathSegments(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentException), () => doc.Collection("a/b"));
}
private static void DocumentReference_Listen_1Arg_NullCallback(UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentNullException), () => doc.Listen(null));
}
private static void DocumentReference_Listen_2Args_NullCallback(UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentNullException),
() => doc.Listen(MetadataChanges.Include, null));
}
private static void DocumentReference_SetAsync_NullDocumentData(UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentNullException), () => doc.SetAsync(null, null));
}
private static void DocumentReference_SetAsync_DocumentDataWithEmptyKey(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertTaskFaults(doc.SetAsync(new Dictionary<string, object> { { "", 42 } }, null));
}
private static void DocumentReference_SetAsync_InvalidDocumentDataType(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentException), () => doc.SetAsync(42, null));
}
private static void DocumentReference_UpdateAsync_NullStringKeyedDictionary(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentNullException),
() => doc.UpdateAsync((IDictionary<string, object>)null));
}
private static void DocumentReference_UpdateAsync_EmptyStringKeyedDictionary(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertTaskSucceeds(doc.SetAsync(handler.TestData(), null));
handler.AssertTaskSucceeds(doc.UpdateAsync(new Dictionary<string, object>()));
}
private static void DocumentReference_UpdateAsync_StringKeyedDictionaryWithEmptyKey(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertTaskSucceeds(doc.SetAsync(handler.TestData(), null));
handler.AssertTaskFaults(doc.UpdateAsync(new Dictionary<string, object> { { "", 42 } }));
}
private static void DocumentReference_UpdateAsync_NullStringField(UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentNullException), () => doc.UpdateAsync(null, 42));
}
private static void DocumentReference_UpdateAsync_EmptyStringField(UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertTaskSucceeds(doc.SetAsync(handler.TestData(), null));
handler.AssertTaskFaults(doc.UpdateAsync("", 42));
}
private static void DocumentReference_UpdateAsync_NullFieldPathKeyedDictionary(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentNullException),
() => doc.UpdateAsync((IDictionary<FieldPath, object>)null));
}
private static void DocumentReference_UpdateAsync_EmptyFieldPathKeyedDictionary(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertTaskSucceeds(doc.SetAsync(handler.TestData(), null));
handler.AssertTaskSucceeds(doc.UpdateAsync(new Dictionary<FieldPath, object>()));
}
private static void DocumentSnapshot_ContainsField_NullStringPath(UIHandlerAutomated handler) {
RunWithTestDocumentSnapshot(handler, snapshot => {
handler.AssertException(typeof(ArgumentNullException),
() => snapshot.ContainsField((string)null));
});
}
private static void DocumentSnapshot_ContainsField_EmptyStringPath(UIHandlerAutomated handler) {
RunWithTestDocumentSnapshot(handler, snapshot => {
handler.AssertException(typeof(ArgumentException), () => snapshot.ContainsField(""));
});
}
private static void DocumentSnapshot_ContainsField_NullFieldPath(UIHandlerAutomated handler) {
RunWithTestDocumentSnapshot(handler, snapshot => {
handler.AssertException(typeof(ArgumentNullException),
() => snapshot.ContainsField((FieldPath)null));
});
}
private static void DocumentSnapshot_GetValue_NullStringPath(UIHandlerAutomated handler) {
RunWithTestDocumentSnapshot(handler, snapshot => {
handler.AssertException(
typeof(ArgumentNullException),
() => snapshot.GetValue<object>((string)null, ServerTimestampBehavior.None));
});
}
private static void DocumentSnapshot_GetValue_EmptyStringPath(UIHandlerAutomated handler) {
RunWithTestDocumentSnapshot(handler, snapshot => {
handler.AssertException(typeof(ArgumentException),
() => snapshot.GetValue<object>("", ServerTimestampBehavior.None));
});
}
private static void DocumentSnapshot_GetValue_NullFieldPath(UIHandlerAutomated handler) {
RunWithTestDocumentSnapshot(handler, snapshot => {
handler.AssertException(
typeof(ArgumentNullException),
() => snapshot.GetValue<object>((FieldPath)null, ServerTimestampBehavior.None));
});
}
private static void DocumentSnapshot_TryGetValue_NullStringPath(UIHandlerAutomated handler) {
RunWithTestDocumentSnapshot(handler, snapshot => {
object value = null;
handler.AssertException(
typeof(ArgumentNullException),
() => snapshot.TryGetValue((string)null, out value, ServerTimestampBehavior.None));
});
}
private static void DocumentSnapshot_TryGetValue_EmptyStringPath(UIHandlerAutomated handler) {
RunWithTestDocumentSnapshot(handler, snapshot => {
object value = null;
handler.AssertException(
typeof(ArgumentException),
() => snapshot.TryGetValue("", out value, ServerTimestampBehavior.None));
});
}
private static void DocumentSnapshot_TryGetValue_NullFieldPath(UIHandlerAutomated handler) {
RunWithTestDocumentSnapshot(handler, snapshot => {
object value = null;
handler.AssertException(
typeof(ArgumentNullException),
() => snapshot.TryGetValue((FieldPath)null, out value, ServerTimestampBehavior.None));
});
}
private static void FieldPath_Constructor_NullStringArray(UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException), () => new FieldPath(null));
}
private static void FieldPath_Constructor_StringArrayWithNullElement(
UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentException),
() => new FieldPath(new string[] { null }));
}
private static void FieldPath_Constructor_EmptyStringArray(UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentException), () => new FieldPath(new string[0]));
}
private static void FieldPath_Constructor_StringArrayWithEmptyString(
UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentException), () => new FieldPath(new string[] { "" }));
}
private static void FieldValue_ArrayRemove_NullArray(UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException), () => FieldValue.ArrayRemove(null));
}
private static void FieldValue_ArrayUnion_NullArray(UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException), () => FieldValue.ArrayUnion(null));
}
private static void FirebaseFirestore_GetInstance_Null(UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException),
() => FirebaseFirestore.GetInstance(null));
}
private static void FirebaseFirestore_GetInstance_DisposedApp(UIHandlerAutomated handler) {
FirebaseApp disposedApp =
FirebaseApp.Create(handler.db.App.Options, "test-getinstance-disposedapp");
disposedApp.Dispose();
handler.AssertException(typeof(ArgumentException),
() => FirebaseFirestore.GetInstance(disposedApp));
}
private static void FirebaseFirestore_Collection_NullStringPath(UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException), () => handler.db.Collection(null));
}
private static void FirebaseFirestore_Collection_EmptyStringPath(UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentException), () => handler.db.Collection(""));
}
private static void FirebaseFirestore_Collection_EvenNumberOfPathSegments(
UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentException), () => handler.db.Collection("a/b"));
}
private static void FirebaseFirestore_CollectionGroup_NullCollectionId(
UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException),
() => handler.db.CollectionGroup(null));
}
private static void FirebaseFirestore_CollectionGroup_EmptyCollectionId(
UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentException), () => handler.db.CollectionGroup(""));
}
private static void FirebaseFirestore_CollectionGroup_CollectionIdContainsSlash(
UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentException), () => handler.db.CollectionGroup("a/b"));
}
private static void FirebaseFirestore_Document_NullStringPath(UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException), () => handler.db.Document(null));
}
private static void FirebaseFirestore_Document_EmptyStringPath(UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentException), () => handler.db.Document(""));
}
private static void FirebaseFirestore_Document_OddNumberOfPathSegments(
UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentException), () => handler.db.Document("a/b/c"));
}
private static void FirebaseFirestore_ListenForSnapshotsInSync_NullCallback(
UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException),
() => handler.db.ListenForSnapshotsInSync(null));
}
private static void FirebaseFirestore_RunTransactionAsync_WithoutTypeParameter_NullCallback(
UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException),
() => handler.db.RunTransactionAsync(null));
}
private static void FirebaseFirestore_RunTransactionAsync_WithTypeParameter_NullCallback(
UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException),
() => handler.db.RunTransactionAsync<object>(null));
}
private static void FirebaseFirestoreSettings_Host_Null(UIHandlerAutomated handler) {
FirebaseFirestoreSettings settings = handler.db.Settings;
handler.AssertException(typeof(ArgumentNullException), () => settings.Host = null);
}
private static void FirebaseFirestoreSettings_Host_EmptyString(UIHandlerAutomated handler) {
FirebaseFirestoreSettings settings = handler.db.Settings;
handler.AssertException(typeof(ArgumentException), () => settings.Host = "");
}
private static void Query_EndAt_NullDocumentSnapshot(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.EndAt((DocumentSnapshot)null));
}
private static void Query_EndAt_NullArray(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException), () => query.EndAt((object[])null));
}
private static void Query_EndAt_ArrayWithNullElement(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => query.EndAt(new object[] { null }));
}
private static void Query_EndBefore_NullDocumentSnapshot(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.EndBefore((DocumentSnapshot)null));
}
private static void Query_EndBefore_NullArray(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException), () => query.EndBefore((object[])null));
}
private static void Query_Limit_0(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => query.Limit(0));
}
private static void Query_Limit_Negative1(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => query.Limit(-1));
}
private static void Query_LimitToLast_0(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => query.LimitToLast(0));
}
private static void Query_LimitToLast_Negative1(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => query.LimitToLast(-1));
}
private static void Query_OrderBy_NullPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException), () => query.OrderBy((string)null));
}
private static void Query_OrderBy_EmptyPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => query.OrderBy(""));
}
private static void Query_OrderBy_NullFieldPath(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException), () => query.OrderBy((FieldPath)null));
}
private static void Query_OrderByDescending_NullPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.OrderByDescending((string)null));
}
private static void Query_OrderByDescending_EmptyPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => query.OrderByDescending(""));
}
private static void Query_OrderByDescending_NullFieldPath(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.OrderByDescending((FieldPath)null));
}
private static void Query_StartAfter_NullDocumentSnapshot(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.StartAfter((DocumentSnapshot)null));
}
private static void Query_StartAfter_NullArray(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.StartAfter((object[])null));
}
private static void Query_StartAt_NullDocumentSnapshot(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.StartAt((DocumentSnapshot)null));
}
private static void Query_StartAt_NullArray(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException), () => query.StartAt((object[])null));
}
private static void Query_StartAt_ArrayWithNullElement(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException),
() => query.StartAt(new object[] { null }));
}
private static void Query_WhereArrayContains_NullFieldPath(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereArrayContains((FieldPath)null, ""));
}
private static void Query_WhereArrayContains_NullPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereArrayContains((string)null, ""));
}
private static void Query_WhereArrayContains_EmptyPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => query.WhereArrayContains("", 42));
}
private static void Query_WhereArrayContainsAny_NullFieldPath(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
List<object> values = new List<object> { "" };
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereArrayContainsAny((FieldPath)null, values));
}
private static void Query_WhereArrayContainsAny_NonNullFieldPath_NullValues(
UIHandlerAutomated handler) {
Query query = handler.TestCollection();
FieldPath fieldPath = new FieldPath(new string[] { "a", "b" });
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereArrayContainsAny(fieldPath, null));
}
private static void Query_WhereArrayContainsAny_NullPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
List<object> values = new List<object> { "" };
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereArrayContainsAny((string)null, values));
}
private static void Query_WhereArrayContainsAny_EmptyPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
List<object> values = new List<object> { "" };
handler.AssertException(typeof(ArgumentException),
() => query.WhereArrayContainsAny("", values));
}
private static void Query_WhereArrayContainsAny_NonNullPathString_NullValues(
UIHandlerAutomated handler) {
Query query = handler.TestCollection();
string pathString = "a/b";
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereArrayContainsAny(pathString, null));
}
private static void Query_WhereEqualTo_NullPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereEqualTo((string)null, 42));
}
private static void Query_WhereEqualTo_EmptyPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => query.WhereEqualTo("", 42));
}
private static void Query_WhereEqualTo_NullFieldPath(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereEqualTo((FieldPath)null, 42));
}
private static void Query_WhereGreaterThan_NullPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereGreaterThan((string)null, 42));
}
private static void Query_WhereGreaterThan_EmptyPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => query.WhereGreaterThan("", 42));
}
private static void Query_WhereGreaterThan_NullFieldPath(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereGreaterThan((FieldPath)null, 42));
}
private static void Query_WhereGreaterThanOrEqualTo_NullPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereGreaterThanOrEqualTo((string)null, 42));
}
private static void Query_WhereGreaterThanOrEqualTo_EmptyPathString(
UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException),
() => query.WhereGreaterThanOrEqualTo("", 42));
}
private static void Query_WhereGreaterThanOrEqualTo_NullFieldPath(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereGreaterThanOrEqualTo((FieldPath)null, 42));
}
private static void Query_WhereIn_NullFieldPath(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
List<object> values = new List<object> { 42 };
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereIn((FieldPath)null, values));
}
private static void Query_WhereIn_NonNullFieldPath_NullValues(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
FieldPath fieldPath = new FieldPath(new string[] { "a", "b" });
handler.AssertException(typeof(ArgumentNullException), () => query.WhereIn(fieldPath, null));
}
private static void Query_WhereIn_NullPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
List<object> values = new List<object> { 42 };
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereIn((string)null, values));
}
private static void Query_WhereIn_EmptyPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
List<object> values = new List<object> { 42 };
handler.AssertException(typeof(ArgumentException), () => query.WhereIn("", values));
}
private static void Query_WhereIn_NonNullPathString_NullValues(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
string fieldPath = "a/b";
handler.AssertException(typeof(ArgumentNullException), () => query.WhereIn(fieldPath, null));
}
private static void Query_WhereLessThan_NullPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereLessThan((string)null, 42));
}
private static void Query_WhereLessThan_EmptyPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => query.WhereLessThan("", 42));
}
private static void Query_WhereLessThan_NullFieldPath(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereLessThan((FieldPath)null, 42));
}
private static void Query_WhereLessThanOrEqualTo_NullPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereLessThanOrEqualTo((string)null, 42));
}
private static void Query_WhereLessThanOrEqualTo_EmptyPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException),
() => query.WhereLessThanOrEqualTo("", 42));
}
private static void Query_WhereLessThanOrEqualTo_NullFieldPath(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereLessThanOrEqualTo((FieldPath)null, 42));
}
private static void Query_WhereNotEqualTo_NullPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereNotEqualTo((string)null, 42));
}
private static void Query_WhereNotEqualTo_EmptyPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentException), () => query.WhereNotEqualTo("", 42));
}
private static void Query_WhereNotEqualTo_NullFieldPath(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereNotEqualTo((FieldPath)null, 42));
}
private static void Query_WhereNotIn_NullFieldPath(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
List<object> values = new List<object> { 42 };
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereNotIn((FieldPath)null, values));
}
private static void Query_WhereNotIn_NonNullFieldPath_NullValues(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
FieldPath fieldPath = new FieldPath(new string[] { "a", "b" });
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereNotIn(fieldPath, null));
}
private static void Query_WhereNotIn_NullPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
List<object> values = new List<object> { 42 };
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereNotIn((string)null, values));
}
private static void Query_WhereNotIn_EmptyPathString(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
List<object> values = new List<object> { 42 };
handler.AssertException(typeof(ArgumentException), () => query.WhereNotIn("", values));
}
private static void Query_WhereNotIn_NonNullPathString_NullValues(UIHandlerAutomated handler) {
Query query = handler.TestCollection();
string fieldPath = "a/b";
handler.AssertException(typeof(ArgumentNullException),
() => query.WhereNotIn(fieldPath, null));
}
private static void Transaction_Delete_NullDocumentReference(UIHandlerAutomated handler) {
RunWithTransaction(handler, transaction => {
handler.AssertException(typeof(ArgumentNullException), () => transaction.Delete(null));
});
}
private static void Transaction_GetSnapshotAsync_NullDocumentReference(
UIHandlerAutomated handler) {
RunWithTransaction(handler, transaction => {
handler.AssertException(typeof(ArgumentNullException),
() => transaction.GetSnapshotAsync(null));
});
}
private static void Transaction_Set_NullDocumentReference(UIHandlerAutomated handler) {
object documentData = handler.TestData();
RunWithTransaction(handler, transaction => {
handler.AssertException(typeof(ArgumentNullException),
() => transaction.Set(null, documentData, null));
});
}
private static void Transaction_Set_NullDocumentData(UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
RunWithTransaction(handler, transaction => {
handler.AssertException(typeof(ArgumentNullException),
() => transaction.Set(doc, null, null));
});
}
private static void Transaction_Set_DocumentDataWithEmptyKey(UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
RunWithTransaction(handler, transaction => {
handler.AssertException(
typeof(ArgumentException),
() => transaction.Set(doc, new Dictionary<string, object> { { "", 42 } }, null));
});
}
private static void Transaction_Set_InvalidDocumentDataType(UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
RunWithTransaction(handler, transaction => {
handler.AssertException(typeof(ArgumentException), () => transaction.Set(doc, 42, null));
});
}
private static void Transaction_Update_NullDocumentReference_NonNullStringKeyDictionary(
UIHandlerAutomated handler) {
RunWithTransaction(handler, transaction => {
handler.AssertException(
typeof(ArgumentNullException),
() => transaction.Update(null, new Dictionary<string, object> { { "key", 42 } }));
});
}
private static void Transaction_Update_NonNullDocumentReference_NullStringKeyDictionary(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
RunWithTransaction(handler, transaction => {
handler.AssertException(typeof(ArgumentNullException),
() => transaction.Update(doc, (IDictionary<string, object>)null));
});
}
private static void Transaction_Update_NonNullDocumentReference_EmptyStringKeyDictionary(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertTaskSucceeds(doc.SetAsync(handler.TestData(), null));
handler.AssertTaskSucceeds(handler.db.RunTransactionAsync(transaction => {
return transaction.GetSnapshotAsync(doc).ContinueWith(
snapshot => { transaction.Update(doc, new Dictionary<string, object>()); });
}));
}
private static void Transaction_Update_NonNullDocumentReference_StringKeyDictionaryWithEmptyKey(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
RunWithTransaction(handler, transaction => {
handler.AssertException(
typeof(ArgumentException),
() => transaction.Update(doc, new Dictionary<string, object> { { "", 42 } }));
});
}
private static void Transaction_Update_NullDocumentReference_NonNullFieldString(
UIHandlerAutomated handler) {
RunWithTransaction(handler, transaction => {
handler.AssertException(typeof(ArgumentNullException),
() => transaction.Update(null, "fieldName", 42));
});
}
private static void Transaction_Update_NonNullDocumentReference_NullFieldString(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
RunWithTransaction(handler, transaction => {
handler.AssertException(typeof(ArgumentNullException),
() => transaction.Update(doc, (string)null, 42));
});
}
private static void Transaction_Update_NullDocumentReference_NonNullFieldPathKeyDictionary(
UIHandlerAutomated handler) {
var nonNullFieldPathKeyDictionary =
new Dictionary<FieldPath, object> { { new FieldPath(new string[] { "a", "b" }), 42 } };
RunWithTransaction(handler, transaction => {
handler.AssertException(typeof(ArgumentNullException),
() => transaction.Update(null, nonNullFieldPathKeyDictionary));
});
}
private static void Transaction_Update_NonNullDocumentReference_NullFieldPathKeyDictionary(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
RunWithTransaction(handler, transaction => {
handler.AssertException(
typeof(ArgumentNullException),
() => transaction.Update(doc, (IDictionary<FieldPath, object>)null));
});
}
private static void Transaction_Update_NonNullDocumentReference_EmptyFieldPathKeyDictionary(
UIHandlerAutomated handler) {
DocumentReference doc = handler.TestDocument();
handler.AssertTaskSucceeds(doc.SetAsync(handler.TestData(), null));
handler.AssertTaskSucceeds(handler.db.RunTransactionAsync(transaction => {
return transaction.GetSnapshotAsync(doc).ContinueWith(
snapshot => { transaction.Update(doc, new Dictionary<FieldPath, object>()); });
}));
}
private static void WriteBatch_Delete_NullDocumentReference(UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
handler.AssertException(typeof(ArgumentNullException), () => writeBatch.Delete(null));
}
private static void WriteBatch_Set_NullDocumentReference(UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
var nonNullDocumentData = handler.TestData();
handler.AssertException(typeof(ArgumentNullException),
() => writeBatch.Set(null, nonNullDocumentData, null));
}
private static void WriteBatch_Set_NullDocumentData(UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentNullException), () => writeBatch.Set(doc, null, null));
}
private static void WriteBatch_Set_DocumentDataWithEmptyKey(UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
DocumentReference doc = handler.TestDocument();
handler.AssertException(
typeof(ArgumentException),
() => writeBatch.Set(doc, new Dictionary<string, object> { { "", 42 } }, null));
}
private static void WriteBatch_Set_InvalidDocumentDataType(UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentException), () => writeBatch.Set(doc, 42, null));
}
private static void WriteBatch_Update_NullDocumentReference_NonNullStringKeyDictionary(
UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
handler.AssertException(
typeof(ArgumentNullException),
() => writeBatch.Update(null, new Dictionary<string, object> { { "key", 42 } }));
}
private static void WriteBatch_Update_NonNullDocumentReference_NullStringKeyDictionary(
UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentNullException),
() => writeBatch.Update(doc, (IDictionary<string, object>)null));
}
private static void WriteBatch_Update_NonNullDocumentReference_EmptyStringKeyDictionary(
UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
DocumentReference doc = handler.TestDocument();
handler.AssertTaskSucceeds(doc.SetAsync(handler.TestData(), null));
writeBatch.Update(doc, new Dictionary<string, object>());
handler.AssertTaskSucceeds(writeBatch.CommitAsync());
}
private static void WriteBatch_Update_NonNullDocumentReference_StringKeyDictionaryWithEmptyKey(
UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
DocumentReference doc = handler.TestDocument();
handler.AssertException(
typeof(ArgumentException),
() => writeBatch.Update(doc, new Dictionary<string, object> { { "", 42 } }));
}
private static void WriteBatch_Update_NullDocumentReference_NonNullFieldString(
UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
handler.AssertException(typeof(ArgumentNullException),
() => writeBatch.Update(null, "fieldName", 42));
}
private static void WriteBatch_Update_NonNullDocumentReference_NullFieldString(
UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentNullException),
() => writeBatch.Update(doc, (string)null, 42));
}
private static void WriteBatch_Update_NullDocumentReference_NonNullFieldPathKeyDictionary(
UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
var nonNullFieldPathKeyDictionary =
new Dictionary<FieldPath, object> { { new FieldPath(new string[] { "a", "b" }), 42 } };
handler.AssertException(typeof(ArgumentNullException),
() => writeBatch.Update(null, nonNullFieldPathKeyDictionary));
}
private static void WriteBatch_Update_NonNullDocumentReference_NullFieldPathKeyDictionary(
UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
DocumentReference doc = handler.TestDocument();
handler.AssertException(typeof(ArgumentNullException),
() => writeBatch.Update(doc, (IDictionary<FieldPath, object>)null));
}
private static void WriteBatch_Update_NonNullDocumentReference_EmptyFieldPathKeyDictionary(
UIHandlerAutomated handler) {
WriteBatch writeBatch = handler.db.StartBatch();
DocumentReference doc = handler.TestDocument();
handler.AssertTaskSucceeds(doc.SetAsync(handler.TestData(), null));
writeBatch.Update(doc, new Dictionary<FieldPath, object>());
handler.AssertTaskSucceeds(writeBatch.CommitAsync());
}
private static void FirebaseFirestore_LoadBundleAsync_NullBundle(UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException),
() => handler.db.LoadBundleAsync(null as string));
handler.AssertException(
typeof(ArgumentNullException),
() => handler.db.LoadBundleAsync(null as string, (sender, progress) => {}));
handler.AssertException(typeof(ArgumentNullException),
() => handler.db.LoadBundleAsync(null as byte[]));
handler.AssertException(
typeof(ArgumentNullException),
() => handler.db.LoadBundleAsync(null as byte[], (sender, progress) => {}));
}
private static void FirebaseFirestore_LoadBundleAsync_NonNullBundle_NullHandler(
UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException),
() => handler.db.LoadBundleAsync("", null));
handler.AssertException(typeof(ArgumentNullException),
() => handler.db.LoadBundleAsync(new byte[] {}, null));
}
private static void FirebaseFirestore_GetNamedQueryAsync_NullQueryName(
UIHandlerAutomated handler) {
handler.AssertException(typeof(ArgumentNullException),
() => handler.db.GetNamedQueryAsync(null));
}
/**
* Starts a transaction and invokes the given action with the `Transaction` object synchronously
* in the calling thread. This enables the caller to use standard asserts since any exceptions
* they throw will be thrown in the calling thread's context and bubble up to the test runner.
*/
private static void RunWithTransaction(UIHandlerAutomated handler, Action<Transaction> action) {
var taskCompletionSource = new TaskCompletionSource<object>();
Transaction capturedTransaction = null;
Task transactionTask = handler.db.RunTransactionAsync(lambdaTransaction => {
Interlocked.Exchange(ref capturedTransaction, lambdaTransaction);
return taskCompletionSource.Task;
});
try {
Transaction transaction = null;
while (true) {
transaction = Interlocked.Exchange(ref capturedTransaction, null);
if (transaction != null) {
break;
}
}
action(transaction);
} finally { taskCompletionSource.SetResult(null); }
handler.AssertTaskSucceeds(transactionTask);
}
/**
* Creates a `DocumentSnapshot` then invokes the given action with it synchronously in the
* calling thread. This enables the caller to use standard asserts since any exceptions
* they throw will be thrown in the calling thread's context and bubble up to the test runner.
*/
private static void RunWithTestDocumentSnapshot(UIHandlerAutomated handler,
Action<DocumentSnapshot> action) {
DocumentReference doc = handler.TestDocument();
doc.SetAsync(handler.TestData());
Task<DocumentSnapshot> task = doc.GetSnapshotAsync(Source.Cache);
handler.AssertTaskSucceeds(task);
DocumentSnapshot snapshot = task.Result;
action(snapshot);
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
//# define debug_output
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using MLifter.DAL.Interfaces;
namespace MLifter.DAL.Tools
{
/// <summary>
/// Class which implements a caching mechanism.
/// </summary>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public class Cache : Dictionary<ObjectIdentifier, object>
{
/// <summary>
/// Default timespan for a cache value to expire.
/// </summary>
public static TimeSpan DefaultValidationTime = new TimeSpan(0, 1, 0);
/// <summary>
/// Default timespan for a settings cache to expire.
/// </summary>
public static TimeSpan DefaultSettingsValidationTime = new TimeSpan(0, 10, 0);
/// <summary>
/// Default timespan for a statistics cache to expire.
/// </summary>
public static TimeSpan DefaultStatisticValidationTime = new TimeSpan(23, 59, 59);
private Thread cleanupThread;
private System.Timers.Timer cleanupTimer = new System.Timers.Timer();
private Dictionary<CacheObject, Dictionary<int, DateTime>> deathTimeList = new Dictionary<CacheObject, Dictionary<int, DateTime>>();
/// <summary>
/// Gets or sets a value indicating whether the caches auto clean up is enabled.
/// </summary>
/// <value><c>true</c> if auto clean up is enabled; otherwise, <c>false</c>.</value>
/// <remarks>Documented by Dev05, 2008-08-01</remarks>
public bool AutoCleanUp
{
get { return cleanupTimer.Enabled; }
set { cleanupTimer.Enabled = value; }
}
/// <summary>
/// Gets or sets the clean up interval in minutes.
/// </summary>
/// <value>The clean up interval.</value>
/// <remarks>Documented by Dev05, 2008-08-01</remarks>
public int CleanUpInterval
{
get { return Convert.ToInt32(cleanupTimer.Interval / 60000); }
set
{
if (value > 0)
cleanupTimer.Interval = value * 60000;
else
throw new ArgumentException("Interval must be greater than zero!");
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Cache"/> class.
/// </summary>
/// <param name="autoCleanUp">if set to <c>true</c> auto clean up is enabled.</param>
/// <remarks>Documented by Dev05, 2008-08-01</remarks>
public Cache(bool autoCleanUp)
{
PrepareDeathtimeList();
cleanupTimer.Elapsed += new System.Timers.ElapsedEventHandler(cleanupTimer_Elapsed);
GC.KeepAlive(cleanupTimer);
CleanUpInterval = 1;
AutoCleanUp = autoCleanUp;
}
/// <summary>
/// Initializes a new instance of the <see cref="Cache"/> class. Auto clean up will be enabled automatically!
/// </summary>
/// <param name="cleanUpInterval">The clean up interval in minutes.</param>
/// <remarks>Documented by Dev05, 2008-08-01</remarks>
public Cache(int cleanUpInterval)
{
PrepareDeathtimeList();
cleanupTimer.Elapsed += new System.Timers.ElapsedEventHandler(cleanupTimer_Elapsed);
GC.KeepAlive(cleanupTimer);
CleanUpInterval = cleanUpInterval;
AutoCleanUp = true;
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="Cache"/> is reclaimed by garbage collection.
/// </summary>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
~Cache()
{
cleanupTimer.Enabled = false;
if (cleanupThread != null && cleanupThread.IsAlive)
cleanupThread.Abort();
}
private void PrepareDeathtimeList()
{
foreach (CacheObject cacheObject in Enum.GetValues(typeof(CacheObject)))
deathTimeList.Add(cacheObject, new Dictionary<int, DateTime>());
}
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified key.
/// </summary>
/// <value></value>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public new object this[ObjectIdentifier key]
{
get
{
lock (deathTimeList)
{
if (!base.ContainsKey(key) || deathTimeList[key.Type][key.Id] <= DateTime.Now)
{
Uncache(key);
return null;
}
else
{
#if DEBUG && debug_output
Debug.WriteLine("Returning from cache: " + key.Type.ToString() + " " + key.Id.ToString());
#endif
return base[key];
}
}
}
set
{
lock (deathTimeList)
{
AddObjectToDeathTimeList(ObjectLifetimeIdentifier.Create(key.Type, key.Id));
this[key] = value;
}
}
}
/// <summary>
/// Sets the <see cref="System.Object"/> with the specified key.
/// </summary>
/// <value></value>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public object this[ObjectLifetimeIdentifier key]
{
set
{
lock (deathTimeList)
{
AddObjectToDeathTimeList(key);
base[key.Identifier] = value;
}
}
}
private void AddObjectToDeathTimeList(ObjectLifetimeIdentifier oli)
{
deathTimeList[oli.Identifier.Type][oli.Identifier.Id] = oli.DeathTime;
}
private string cleanupLocker = string.Empty;
void cleanupTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
lock (cleanupLocker)
{
if (cleanupThread == null)
{
cleanupThread = new Thread(new ThreadStart(CleanUpLauncher));
cleanupThread.Name = "Cache Cleanup Thread";
cleanupThread.CurrentCulture = Thread.CurrentThread.CurrentCulture;
cleanupThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
cleanupThread.IsBackground = true;
cleanupThread.Priority = ThreadPriority.Lowest;
cleanupThread.Start();
}
}
}
private void CleanUpLauncher()
{
CleanUp();
cleanupThread = null;
}
/// <summary>
/// Cleans the cache from outdated items.
/// </summary>
/// <remarks>Documented by Dev05, 2008-08-04</remarks>
public void CleanUp()
{
List<ObjectIdentifier> deathObjects = new List<ObjectIdentifier>();
lock (deathTimeList)
{
int count = 0;
int totalCount = 0;
foreach (KeyValuePair<CacheObject, Dictionary<int, DateTime>> dic in deathTimeList)
{
totalCount += dic.Value.Count;
foreach (KeyValuePair<int, DateTime> pair in dic.Value)
if (pair.Value < DateTime.Now)
deathObjects.Add(ObjectLifetimeIdentifier.GetIdentifier(dic.Key, pair.Key));
count++;
#if DEBUG && debug_output
Debug.WriteLine(string.Format("Cache cleanup scanned {0}/{1}. Totaly listed: {2}", count, deathTimeList.Count, totalCount));
#endif
Monitor.Wait(deathTimeList, 10);
}
}
deathObjects.ForEach(oi => Uncache(oi));
GC.Collect(); //request garbage collection
#if DEBUG && debug_output
Debug.WriteLine("Cache cleanup finished.");
#endif
}
/// <summary>
/// Begins to uncache the given item asyncron.
/// </summary>
/// <param name="identifier">The identifier.</param>
/// <remarks>Documented by Dev05, 2008-08-04</remarks>
public void BeginUncache(ObjectIdentifier identifier)
{
Thread uncache = new Thread(new ParameterizedThreadStart(BeginUncache));
uncache.CurrentCulture = Thread.CurrentThread.CurrentCulture;
uncache.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
uncache.Start(identifier);
}
private void BeginUncache(object identifier)
{
Uncache((ObjectIdentifier)identifier);
}
/// <summary>
/// Uncaches the specified item.
/// </summary>
/// <param name="identifier">The identifier.</param>
/// <remarks>Documented by Dev05, 2008-08-04</remarks>
public void Uncache(ObjectIdentifier identifier)
{
lock (deathTimeList)
{
if (!base.ContainsKey(identifier))
return;
#if DEBUG && debug_output
Debug.WriteLine("Removing from cache: " + identifier.Type.ToString() + " " + identifier.Id.ToString());
#endif
deathTimeList[identifier.Type].Remove(identifier.Id);
base.Remove(identifier);
}
}
/// <summary>
/// Removes all items from the cache.
/// </summary>
/// <remarks>Documented by Dev05, 2008-09-15</remarks>
public new void Clear()
{
lock (deathTimeList)
{
base.Clear();
foreach (KeyValuePair<CacheObject, Dictionary<int, DateTime>> dic in deathTimeList)
{
dic.Value.Clear();
}
}
}
}
/// <summary>
/// Identifier of an object.
/// </summary>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public struct ObjectIdentifier
{
/// <summary>
/// The id of the object.
/// </summary>
public int Id;
/// <summary>
/// The object type.
/// </summary>
public CacheObject Type;
}
/// <summary>
/// Lifetime identifier of an object.
/// </summary>
/// <remarks>Documented by Dev03, 2008-11-27</remarks>
public class ObjectLifetimeIdentifier
{
/// <summary>
/// The identifier of the object.
/// </summary>
public ObjectIdentifier Identifier;
/// <summary>
/// The time were the object is removed from cache.
/// </summary>
public DateTime DeathTime;
private ObjectLifetimeIdentifier(CacheObject type, int id)
{
Identifier = new ObjectIdentifier();
Identifier.Id = id;
Identifier.Type = type;
DeathTime = DateTime.Now.Add(Cache.DefaultValidationTime);
}
/// <summary>
/// Creates the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="id">The id.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2009-02-09</remarks>
public static ObjectLifetimeIdentifier Create(CacheObject type, int id)
{
return new ObjectLifetimeIdentifier(type, id);
}
private ObjectLifetimeIdentifier(CacheObject type, int id, DateTime deathTime)
{
Identifier = new ObjectIdentifier();
Identifier.Id = id;
Identifier.Type = type;
DeathTime = deathTime;
}
/// <summary>
/// Creates the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="id">The id.</param>
/// <param name="deathTime">The death time.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2009-02-09</remarks>
public static ObjectLifetimeIdentifier Create(CacheObject type, int id, DateTime deathTime)
{
return new ObjectLifetimeIdentifier(type, id, deathTime);
}
private ObjectLifetimeIdentifier(CacheObject type, int id, TimeSpan lifetime)
{
Identifier = new ObjectIdentifier();
Identifier.Id = id;
Identifier.Type = type;
DeathTime = DateTime.Now + lifetime;
}
/// <summary>
/// Creates the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="id">The id.</param>
/// <param name="lifetime">The lifetime.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2009-02-09</remarks>
public static ObjectLifetimeIdentifier Create(CacheObject type, int id, TimeSpan lifetime)
{
return new ObjectLifetimeIdentifier(type, id, lifetime);
}
/// <summary>
/// Gets the identifier.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="id">The id.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2009-02-09</remarks>
public static ObjectIdentifier GetIdentifier(CacheObject type, int id)
{
ObjectIdentifier idf = new ObjectIdentifier();
idf.Id = id;
idf.Type = type;
return idf;
}
/// <summary>
/// Gets the cache object.
/// </summary>
/// <param name="side">The side.</param>
/// <param name="type">The type.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2009-02-09</remarks>
public static CacheObject GetCacheObject(Side side, WordType type)
{
switch (side)
{
case Side.Question:
switch (type)
{
case WordType.Word:
return CacheObject.QuestionWords;
case WordType.Sentence:
return CacheObject.QuestionExampleWords;
case WordType.Distractor:
return CacheObject.QuestionDistractorWords;
}
break;
case Side.Answer:
switch (type)
{
case WordType.Word:
return CacheObject.AnswerWords;
case WordType.Sentence:
return CacheObject.AnswerExampleWords;
case WordType.Distractor:
return CacheObject.AnswerDistractorWords;
}
break;
}
return CacheObject.Word;
}
}
/// <summary>
/// Definition of the CacheObject
/// </summary>
/// <remarks>Documented by Dev08, 2008-10-15</remarks>
public enum CacheObject
{
/// <summary>
/// ChaptersList
/// </summary>
ChaptersList,
/// <summary>
/// ChapterTitle
/// </summary>
ChapterTitle,
/// <summary>
/// ChapterDescription
/// </summary>
ChapterDescription,
/// <summary>
/// Setting of the chapter
/// </summary>
ChapterSetting,
/// <summary>
/// Word
/// </summary>
Word,
/// <summary>
/// QuestionWords
/// </summary>
QuestionWords,
/// <summary>
/// QuestionExampleWords
/// </summary>
QuestionExampleWords,
/// <summary>
/// QuestionDistractorWords
/// </summary>
QuestionDistractorWords,
/// <summary>
/// AnswerWords
/// </summary>
AnswerWords,
/// <summary>
/// AnswerExampleWords
/// </summary>
AnswerExampleWords,
/// <summary>
/// AnswerDistractorWords
/// </summary>
AnswerDistractorWords,
/// <summary>
/// CardChapterList
/// </summary>
CardChapterList,
/// <summary>
/// CardsList
/// </summary>
CardsList,
/// <summary>
/// Setting of the card
/// </summary>
CardSetting,
/// <summary>
/// CardIdsList
/// </summary>
CardIdsList,
/// <summary>
/// LearningModuleTitle
/// </summary>
LearningModuleTitle,
/// <summary>
/// LearningModuleAuthor
/// </summary>
LearningModuleAuthor,
/// <summary>
/// DefaultLearningModuleSettings
/// </summary>
DefaultLearningModuleSettings,
/// <summary>
/// AllowedLearningModuleSettings
/// </summary>
AllowedLearningModuleSettings,
/// <summary>
/// UserLearningModuleSettings
/// </summary>
UserLearningModuleSettings,
/// <summary>
/// Database version
/// </summary>
DataBaseVersion,
/// <summary>
/// Supported data layer versions
/// </summary>
SupportedDataLayerVersions,
/// <summary>
/// Database supports list authentication
/// </summary>
ListAuthentication,
/// <summary>
/// Database supports forms authentication
/// </summary>
FormsAuthentication,
/// <summary>
/// Database supports local directory authentication
/// </summary>
LocalDirectoryAuthentication,
/// <summary>
/// Local directory type authentication
/// </summary>
LocalDirectoryType,
/// <summary>
/// Local directory server
/// </summary>
LdapServer,
/// <summary>
/// Local directory server port
/// </summary>
LdapPort,
/// <summary>
/// Local directory username
/// </summary>
LdapUser,
/// <summary>
/// Local directory user password
/// </summary>
LdapPassword,
/// <summary>
/// Local directory context
/// </summary>
LdapContext,
/// <summary>
/// Use SSL for local directory connection
/// </summary>
LdapUseSsl,
/// <summary>
/// UserList
/// </summary>
UserList,
/// <summary>
/// CardState
/// </summary>
CardState,
/// <summary>
/// CurrentBoxSizes
/// </summary>
CurrentBoxSizes,
/// <summary>
/// BoxSizes
/// </summary>
BoxSizes,
/// <summary>
/// MaximalBoxSizes
/// </summary>
MaximalBoxSizes,
/// <summary>
/// DefaultBoxSizes
/// </summary>
DefaultBoxSizes,
/// <summary>
/// CardMedia
/// </summary>
CardMedia,
/// <summary>
/// MediaProperties
/// </summary>
MediaProperties,
/// <summary>
/// SettingsAutoPlayAudio
/// </summary>
SettingsAutoPlayAudio,
/// <summary>
/// SettingsCaseSensetive
/// </summary>
SettingsCaseSensetive,
/// <summary>
/// SettingsCaseSensetive
/// </summary>
SettingsIgnoreAccentChars,
/// <summary>
/// SettingsConfirmDemote
/// </summary>
SettingsConfirmDemote,
/// <summary>
/// SettingsEnableCommentary
/// </summary>
SettingsEnableCommentary,
/// <summary>
/// SettingsCorrectOnTheFly
/// </summary>
SettingsCorrectOnTheFly,
/// <summary>
/// SettingsEnableTimer
/// </summary>
SettingsEnableTimer,
/// <summary>
/// SettingsSynonymGradingsFk
/// </summary>
SettingsSynonymGradingsFk,
/// <summary>
/// SettingsTypeGradingsFk
/// </summary>
SettingsTypeGradingsFk,
/// <summary>
/// SettingsMultipleChoiceOptionsFk
/// </summary>
SettingsMultipleChoiceOptionsFk,
/// <summary>
/// SettingsQueryDirectionsFk
/// </summary>
SettingsQueryDirectionsFk,
/// <summary>
/// SettingsQueryTypesFk
/// </summary>
SettingsQueryTypesFk,
/// <summary>
/// SettingsRandomPool
/// </summary>
SettingsRandomPool,
/// <summary>
/// SettingsSelfAssessment
/// </summary>
SettingsSelfAssessment,
/// <summary>
/// SettingsShowImages
/// </summary>
SettingsShowImages,
/// <summary>
/// SettingsStripchars
/// </summary>
SettingsStripchars,
/// <summary>
/// SettingsQuestionCulture
/// </summary>
SettingsQuestionCulture,
/// <summary>
/// SettingsAnswerCulture
/// </summary>
SettingsAnswerCulture,
/// <summary>
/// SettingsQuestionCaption
/// </summary>
SettingsQuestionCaption,
/// <summary>
/// SettingsAnswerCaption
/// </summary>
SettingsAnswerCaption,
/// <summary>
/// SettingsLogoFk
/// </summary>
SettingsLogoFk,
/// <summary>
/// SettingsQuestionStylesheetFk
/// </summary>
SettingsQuestionStylesheetFk,
/// <summary>
/// SettingsAnswerStylesheetFk
/// </summary>
SettingsAnswerStylesheetFk,
/// <summary>
/// SettingsAutoBoxsize
/// </summary>
SettingsAutoBoxsize,
/// <summary>
/// SettingsPoolEmptyMessageShown
/// </summary>
SettingsPoolEmptyMessageShown,
/// <summary>
///
/// </summary>
SettingsShowStatistics,
/// <summary>
///
/// </summary>
SettingsSkipCorrectAnswers,
/// <summary>
///
/// </summary>
SettingsSnoozeOptionsFk,
/// <summary>
///
/// </summary>
SettingsUseLearningModuleStylesheet,
/// <summary>
///
/// </summary>
SettingsCardStyleFk,
/// <summary>
///
/// </summary>
SettingsBoxesFk,
/// <summary>
///
/// </summary>
SettingsIsCached,
/// <summary>
///
/// </summary>
SettingsSnoozeOptionsId,
/// <summary>
///
/// </summary>
SettingsSnoozeCardsEnabled,
/// <summary>
///
/// </summary>
SettingsSnoozeRightsEnabled,
/// <summary>
///
/// </summary>
SettingsSnoozeTimeEnabled,
/// <summary>
///
/// </summary>
SettingsSnoozeCards,
/// <summary>
///
/// </summary>
SettingsSnoozeHigh,
/// <summary>
///
/// </summary>
SettingsSnoozeLow,
/// <summary>
///
/// </summary>
SettingsSnoozeMode,
/// <summary>
///
/// </summary>
SettingsSnoozeRights,
/// <summary>
///
/// </summary>
SettingsSnoozeTime,
/// <summary>
///
/// </summary>
SettingsBoxSizeId,
/// <summary>
///
/// </summary>
SettingsBox1Size,
/// <summary>
///
/// </summary>
SettingsBox2Size,
/// <summary>
///
/// </summary>
SettingsBox3Size,
/// <summary>
///
/// </summary>
SettingsBox4Size,
/// <summary>
///
/// </summary>
SettingsBox5Size,
/// <summary>
///
/// </summary>
SettingsBox6Size,
/// <summary>
///
/// </summary>
SettingsBox7Size,
/// <summary>
///
/// </summary>
SettingsBox8Size,
/// <summary>
///
/// </summary>
SettingsBox9Size,
/// <summary>
///
/// </summary>
SettingsStyleSheetsId,
/// <summary>
///
/// </summary>
SettingsStyleSheetsQuestionValue,
/// <summary>
///
/// </summary>
SettingsStyleSheetsAnswerValue,
/// <summary>
///
/// </summary>
SettingsCardStyleValue,
/// <summary>
///
/// </summary>
SettingsTypeGradingsId,
/// <summary>
///
/// </summary>
SettingsTypeGradingsAllCorrect,
/// <summary>
///
/// </summary>
SettingsTypeGradingsHalfCorrect,
/// <summary>
///
/// </summary>
SettingsTypeGradingsNoneCorrect,
/// <summary>
///
/// </summary>
SettingsTypeGradingsPrompt,
/// <summary>
///
/// </summary>
SettingsMultipleChoiceOptionsId,
/// <summary>
///
/// </summary>
SettingsMultipleChoiceOptionsAllowMultipleCorrectAnswers,
/// <summary>
///
/// </summary>
SettingsMultipleChoiceOptionsAllowRandomDistractors,
/// <summary>
///
/// </summary>
SettingsMultipleChoiceOptionsMaxCorrectAnswers,
/// <summary>
///
/// </summary>
SettingsMultipleChoiceOptionsNumberOfChoices,
/// <summary>
///
/// </summary>
SettingsQueryTypesId,
/// <summary>
///
/// </summary>
SettingsQueryTypesImageRecognition,
/// <summary>
///
/// </summary>
SettingsQueryTypesListeningComprehension,
/// <summary>
///
/// </summary>
SettingsQueryTypesMultipleChoice,
/// <summary>
///
/// </summary>
SettingsQueryTypesSentence,
/// <summary>
///
/// </summary>
SettingsQueryTypesWord,
/// <summary>
///
/// </summary>
SettingsSynonymGradingsId,
/// <summary>
///
/// </summary>
SettingsSynonymGradingsAllKnown,
/// <summary>
///
/// </summary>
SettingsSynonymGradingsHalfKnown,
/// <summary>
///
/// </summary>
SettingsSynonymGradingsOneKnown,
/// <summary>
///
/// </summary>
SettingsSynonymGradingsFirstKnown,
/// <summary>
///
/// </summary>
SettingsSynonymGradingsPrompt,
/// <summary>
///
/// </summary>
SettingsQueryDirectionsId,
/// <summary>
///
/// </summary>
SettingsQueryDirectionsQuestion2Answer,
/// <summary>
///
/// </summary>
SettingsQueryDirectionsAnswer2Question,
/// <summary>
///
/// </summary>
SettingsQueryDirectionsMixed,
/// <summary>
/// contains a Dictionary(key,value) full of Sounds
/// </summary>
SettingsCommentarySounds,
/// <summary>
///
/// </summary>
SettingsSelectedLearnChapterList,
/// <summary>
///
/// </summary>
StatisticWrongCards,
/// <summary>
///
/// </summary>
StatisticCorrectCards,
/// <summary>
///
/// </summary>
StatisticContentOfBoxes,
/// <summary>
///
/// </summary>
StatisticStartTime,
/// <summary>
///
/// </summary>
StatisticEndTime,
/// <summary>
///
/// </summary>
StatisticsLearnSessions,
/// <summary>
///
/// </summary>
Score,
/// <summary>
/// SessionAlive
/// </summary>
SessionAlive,
/// <summary>
/// CardCacheInitialized
/// </summary>
CardCacheInitialized
}
/// <summary>
/// A simple conversation function. (a nullable extension of Convert.ToSomething() )
/// </summary>
/// <remarks>Documented by Dev08, 2008-10-24</remarks>
public class DbValueConverter
{
/// <summary>
/// Converts the specified value.
/// </summary>
/// <typeparam name="T">The type to convert to.</typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2008-10-27</remarks>
public static T? Convert<T>(object value) where T : struct
{
if (typeof(Enum).IsAssignableFrom(typeof(T)))
return (value == null || value is DBNull) ? (T?)null : (T?)Enum.Parse(typeof(T), value.ToString());
else
return (value == null || value is DBNull) ? (T?)null : (T?)System.Convert.ChangeType(value, typeof(T));
}
/// <summary>
/// Converts the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
/// <remarks>Documented by Dev05, 2008-10-27</remarks>
public static string Convert(object value)
{
return (value == null || value is DBNull) ? string.Empty : value.ToString();
}
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using TheArtOfDev.HtmlRenderer.Adapters;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using TheArtOfDev.HtmlRenderer.Core.Dom;
using TheArtOfDev.HtmlRenderer.Core.Entities;
using TheArtOfDev.HtmlRenderer.Core.Utils;
namespace TheArtOfDev.HtmlRenderer.Core.Handlers
{
/// <summary>
/// Handler for text selection in the html.
/// </summary>
internal sealed class SelectionHandler : IDisposable
{
#region Fields and Consts
/// <summary>
/// the root of the handled html tree
/// </summary>
private readonly CssBox _root;
/// <summary>
/// handler for showing context menu on right click
/// </summary>
private readonly ContextMenuHandler _contextMenuHandler;
/// <summary>
/// the mouse location when selection started used to ignore small selections
/// </summary>
private RPoint _selectionStartPoint;
/// <summary>
/// the starting word of html selection<br/>
/// where the user started the selection, if the selection is backwards then it will be the last selected word.
/// </summary>
private CssRect _selectionStart;
/// <summary>
/// the ending word of html selection<br/>
/// where the user ended the selection, if the selection is backwards then it will be the first selected word.
/// </summary>
private CssRect _selectionEnd;
/// <summary>
/// the selection start index if the first selected word is partially selected (-1 if not selected or fully selected)
/// </summary>
private int _selectionStartIndex = -1;
/// <summary>
/// the selection end index if the last selected word is partially selected (-1 if not selected or fully selected)
/// </summary>
private int _selectionEndIndex = -1;
/// <summary>
/// the selection start offset if the first selected word is partially selected (-1 if not selected or fully selected)
/// </summary>
private double _selectionStartOffset = -1;
/// <summary>
/// the selection end offset if the last selected word is partially selected (-1 if not selected or fully selected)
/// </summary>
private double _selectionEndOffset = -1;
/// <summary>
/// is the selection goes backward in the html, the starting word comes after the ending word in DFS traversing.<br/>
/// </summary>
private bool _backwardSelection;
/// <summary>
/// used to ignore mouse up after selection
/// </summary>
private bool _inSelection;
/// <summary>
/// current selection process is after double click (full word selection)
/// </summary>
private bool _isDoubleClickSelect;
/// <summary>
/// used to know if selection is in the control or started outside so it needs to be ignored
/// </summary>
private bool _mouseDownInControl;
/// <summary>
/// used to handle drag & drop
/// </summary>
private bool _mouseDownOnSelectedWord;
/// <summary>
/// is the cursor on the control has been changed by the selection handler
/// </summary>
private bool _cursorChanged;
/// <summary>
/// used to know if double click selection is requested
/// </summary>
private DateTime _lastMouseDown;
/// <summary>
/// used to know if drag & drop was already started not to execute the same operation over
/// </summary>
private object _dragDropData;
#endregion
/// <summary>
/// Init.
/// </summary>
/// <param name="root">the root of the handled html tree</param>
public SelectionHandler(CssBox root)
{
ArgChecker.AssertArgNotNull(root, "root");
_root = root;
_contextMenuHandler = new ContextMenuHandler(this, root.HtmlContainer);
}
/// <summary>
/// Select all the words in the html.
/// </summary>
/// <param name="control">the control hosting the html to invalidate</param>
public void SelectAll(RControl control)
{
if (_root.HtmlContainer.IsSelectionEnabled)
{
ClearSelection();
SelectAllWords(_root);
control.Invalidate();
}
}
/// <summary>
/// Select the word at the given location if found.
/// </summary>
/// <param name="control">the control hosting the html to invalidate</param>
/// <param name="loc">the location to select word at</param>
public void SelectWord(RControl control, RPoint loc)
{
if (_root.HtmlContainer.IsSelectionEnabled)
{
var word = DomUtils.GetCssBoxWord(_root, loc);
if (word != null)
{
word.Selection = this;
_selectionStartPoint = loc;
_selectionStart = _selectionEnd = word;
control.Invalidate();
}
}
}
/// <summary>
/// Handle mouse down to handle selection.
/// </summary>
/// <param name="parent">the control hosting the html to invalidate</param>
/// <param name="loc">the location of the mouse on the html</param>
/// <param name="isMouseInContainer"> </param>
public void HandleMouseDown(RControl parent, RPoint loc, bool isMouseInContainer)
{
bool clear = !isMouseInContainer;
if (isMouseInContainer)
{
_mouseDownInControl = true;
_isDoubleClickSelect = (DateTime.Now - _lastMouseDown).TotalMilliseconds < 400;
_lastMouseDown = DateTime.Now;
_mouseDownOnSelectedWord = false;
if (_root.HtmlContainer.IsSelectionEnabled && parent.LeftMouseButton)
{
var word = DomUtils.GetCssBoxWord(_root, loc);
if (word != null && word.Selected)
{
_mouseDownOnSelectedWord = true;
}
else
{
clear = true;
}
}
else if (parent.RightMouseButton)
{
var rect = DomUtils.GetCssBoxWord(_root, loc);
var link = DomUtils.GetLinkBox(_root, loc);
if (_root.HtmlContainer.IsContextMenuEnabled)
{
_contextMenuHandler.ShowContextMenu(parent, rect, link);
}
clear = rect == null || !rect.Selected;
}
}
if (clear)
{
ClearSelection();
parent.Invalidate();
}
}
/// <summary>
/// Handle mouse up to handle selection and link click.
/// </summary>
/// <param name="parent">the control hosting the html to invalidate</param>
/// <param name="leftMouseButton">is the left mouse button has been released</param>
/// <returns>is the mouse up should be ignored</returns>
public bool HandleMouseUp(RControl parent, bool leftMouseButton)
{
bool ignore = false;
_mouseDownInControl = false;
if (_root.HtmlContainer.IsSelectionEnabled)
{
ignore = _inSelection;
if (!_inSelection && leftMouseButton && _mouseDownOnSelectedWord)
{
ClearSelection();
parent.Invalidate();
}
_mouseDownOnSelectedWord = false;
_inSelection = false;
}
ignore = ignore || (DateTime.Now - _lastMouseDown > TimeSpan.FromSeconds(1));
return ignore;
}
/// <summary>
/// Handle mouse move to handle hover cursor and text selection.
/// </summary>
/// <param name="parent">the control hosting the html to set cursor and invalidate</param>
/// <param name="loc">the location of the mouse on the html</param>
public void HandleMouseMove(RControl parent, RPoint loc)
{
if (_root.HtmlContainer.IsSelectionEnabled && _mouseDownInControl && parent.LeftMouseButton)
{
if (_mouseDownOnSelectedWord)
{
// make sure not to start drag-drop on click but when it actually moves as it fucks mouse-up
if ((DateTime.Now - _lastMouseDown).TotalMilliseconds > 200)
StartDragDrop(parent);
}
else
{
HandleSelection(parent, loc, !_isDoubleClickSelect);
_inSelection = _selectionStart != null && _selectionEnd != null && (_selectionStart != _selectionEnd || _selectionStartIndex != _selectionEndIndex);
}
}
else
{
// Handle mouse hover over the html to change the cursor depending if hovering word, link of other.
var link = DomUtils.GetLinkBox(_root, loc);
if (link != null)
{
_cursorChanged = true;
parent.SetCursorHand();
}
else if (_root.HtmlContainer.IsSelectionEnabled)
{
var word = DomUtils.GetCssBoxWord(_root, loc);
_cursorChanged = word != null && !word.IsImage && !(word.Selected && (word.SelectedStartIndex < 0 || word.Left + word.SelectedStartOffset <= loc.X) && (word.SelectedEndOffset < 0 || word.Left + word.SelectedEndOffset >= loc.X));
if (_cursorChanged)
parent.SetCursorIBeam();
else
parent.SetCursorDefault();
}
else if (_cursorChanged)
{
parent.SetCursorDefault();
}
}
}
/// <summary>
/// On mouse leave change the cursor back to default.
/// </summary>
/// <param name="parent">the control hosting the html to set cursor and invalidate</param>
public void HandleMouseLeave(RControl parent)
{
if (_cursorChanged)
{
_cursorChanged = false;
parent.SetCursorDefault();
}
}
/// <summary>
/// Copy the currently selected html segment to clipboard.<br/>
/// Copy rich html text and plain text.
/// </summary>
public void CopySelectedHtml()
{
if (_root.HtmlContainer.IsSelectionEnabled)
{
var html = DomUtils.GenerateHtml(_root, HtmlGenerationStyle.Inline, true);
var plainText = DomUtils.GetSelectedPlainText(_root);
if (!string.IsNullOrEmpty(plainText))
_root.HtmlContainer.Adapter.SetToClipboard(html, plainText);
}
}
/// <summary>
/// Get the currently selected text segment in the html.<br/>
/// </summary>
public string GetSelectedText()
{
return _root.HtmlContainer.IsSelectionEnabled ? DomUtils.GetSelectedPlainText(_root) : null;
}
/// <summary>
/// Copy the currently selected html segment with style.<br/>
/// </summary>
public string GetSelectedHtml()
{
return _root.HtmlContainer.IsSelectionEnabled ? DomUtils.GenerateHtml(_root, HtmlGenerationStyle.Inline, true) : null;
}
/// <summary>
/// The selection start index if the first selected word is partially selected (-1 if not selected or fully selected)<br/>
/// if the given word is not starting or ending selection word -1 is returned as full word selection is in place.
/// </summary>
/// <remarks>
/// Handles backward selecting by returning the selection end data instead of start.
/// </remarks>
/// <param name="word">the word to return the selection start index for</param>
/// <returns>data value or -1 if not applicable</returns>
public int GetSelectingStartIndex(CssRect word)
{
return word == (_backwardSelection ? _selectionEnd : _selectionStart) ? (_backwardSelection ? _selectionEndIndex : _selectionStartIndex) : -1;
}
/// <summary>
/// The selection end index if the last selected word is partially selected (-1 if not selected or fully selected)<br/>
/// if the given word is not starting or ending selection word -1 is returned as full word selection is in place.
/// </summary>
/// <remarks>
/// Handles backward selecting by returning the selection end data instead of start.
/// </remarks>
/// <param name="word">the word to return the selection end index for</param>
public int GetSelectedEndIndexOffset(CssRect word)
{
return word == (_backwardSelection ? _selectionStart : _selectionEnd) ? (_backwardSelection ? _selectionStartIndex : _selectionEndIndex) : -1;
}
/// <summary>
/// The selection start offset if the first selected word is partially selected (-1 if not selected or fully selected)<br/>
/// if the given word is not starting or ending selection word -1 is returned as full word selection is in place.
/// </summary>
/// <remarks>
/// Handles backward selecting by returning the selection end data instead of start.
/// </remarks>
/// <param name="word">the word to return the selection start offset for</param>
public double GetSelectedStartOffset(CssRect word)
{
return word == (_backwardSelection ? _selectionEnd : _selectionStart) ? (_backwardSelection ? _selectionEndOffset : _selectionStartOffset) : -1;
}
/// <summary>
/// The selection end offset if the last selected word is partially selected (-1 if not selected or fully selected)<br/>
/// if the given word is not starting or ending selection word -1 is returned as full word selection is in place.
/// </summary>
/// <remarks>
/// Handles backward selecting by returning the selection end data instead of start.
/// </remarks>
/// <param name="word">the word to return the selection end offset for</param>
public double GetSelectedEndOffset(CssRect word)
{
return word == (_backwardSelection ? _selectionStart : _selectionEnd) ? (_backwardSelection ? _selectionStartOffset : _selectionEndOffset) : -1;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
_contextMenuHandler.Dispose();
}
#region Private methods
/// <summary>
/// Handle html text selection by mouse move over the html with left mouse button pressed.<br/>
/// Calculate the words in the selected range and set their selected property.
/// </summary>
/// <param name="control">the control hosting the html to invalidate</param>
/// <param name="loc">the mouse location</param>
/// <param name="allowPartialSelect">true - partial word selection allowed, false - only full words selection</param>
private void HandleSelection(RControl control, RPoint loc, bool allowPartialSelect)
{
// get the line under the mouse or nearest from the top
var lineBox = DomUtils.GetCssLineBox(_root, loc);
if (lineBox != null)
{
// get the word under the mouse
var word = DomUtils.GetCssBoxWord(lineBox, loc);
// if no word found under the mouse use the last or the first word in the line
if (word == null && lineBox.Words.Count > 0)
{
if (loc.Y > lineBox.LineBottom)
{
// under the line
word = lineBox.Words[lineBox.Words.Count - 1];
}
else if (loc.X < lineBox.Words[0].Left)
{
// before the line
word = lineBox.Words[0];
}
else if (loc.X > lineBox.Words[lineBox.Words.Count - 1].Right)
{
// at the end of the line
word = lineBox.Words[lineBox.Words.Count - 1];
}
}
// if there is matching word
if (word != null)
{
if (_selectionStart == null)
{
// on start set the selection start word
_selectionStartPoint = loc;
_selectionStart = word;
if (allowPartialSelect)
CalculateWordCharIndexAndOffset(control, word, loc, true);
}
// always set selection end word
_selectionEnd = word;
if (allowPartialSelect)
CalculateWordCharIndexAndOffset(control, word, loc, false);
ClearSelection(_root);
if (CheckNonEmptySelection(loc, allowPartialSelect))
{
CheckSelectionDirection();
SelectWordsInRange(_root, _backwardSelection ? _selectionEnd : _selectionStart, _backwardSelection ? _selectionStart : _selectionEnd);
}
else
{
_selectionEnd = null;
}
_cursorChanged = true;
control.SetCursorIBeam();
control.Invalidate();
}
}
}
/// <summary>
/// Clear the current selection.
/// </summary>
private void ClearSelection()
{
// clear drag and drop
_dragDropData = null;
ClearSelection(_root);
_selectionStartOffset = -1;
_selectionStartIndex = -1;
_selectionEndOffset = -1;
_selectionEndIndex = -1;
_selectionStartPoint = RPoint.Empty;
_selectionStart = null;
_selectionEnd = null;
}
/// <summary>
/// Clear the selection from all the words in the css box recursively.
/// </summary>
/// <param name="box">the css box to selectionStart clear at</param>
private static void ClearSelection(CssBox box)
{
foreach (var word in box.Words)
{
word.Selection = null;
}
foreach (var childBox in box.Boxes)
{
ClearSelection(childBox);
}
}
/// <summary>
/// Start drag & drop operation on the currently selected html segment.
/// </summary>
/// <param name="control">the control to start the drag & drop on</param>
private void StartDragDrop(RControl control)
{
if (_dragDropData == null)
{
var html = DomUtils.GenerateHtml(_root, HtmlGenerationStyle.Inline, true);
var plainText = DomUtils.GetSelectedPlainText(_root);
_dragDropData = control.Adapter.GetClipboardDataObject(html, plainText);
}
control.DoDragDropCopy(_dragDropData);
}
/// <summary>
/// Select all the words that are under <paramref name="box"/> DOM hierarchy.<br/>
/// </summary>
/// <param name="box">the box to start select all at</param>
public void SelectAllWords(CssBox box)
{
foreach (var word in box.Words)
{
word.Selection = this;
}
foreach (var childBox in box.Boxes)
{
SelectAllWords(childBox);
}
}
/// <summary>
/// Check if the current selection is non empty, has some selection data.
/// </summary>
/// <param name="loc"></param>
/// <param name="allowPartialSelect">true - partial word selection allowed, false - only full words selection</param>
/// <returns>true - is non empty selection, false - empty selection</returns>
private bool CheckNonEmptySelection(RPoint loc, bool allowPartialSelect)
{
// full word selection is never empty
if (!allowPartialSelect)
return true;
// if end selection location is near starting location then the selection is empty
if (Math.Abs(_selectionStartPoint.X - loc.X) <= 1 && Math.Abs(_selectionStartPoint.Y - loc.Y) < 5)
return false;
// selection is empty if on same word and same index
return _selectionStart != _selectionEnd || _selectionStartIndex != _selectionEndIndex;
}
/// <summary>
/// Select all the words that are between <paramref name="selectionStart"/> word and <paramref name="selectionEnd"/> word in the DOM hierarchy.<br/>
/// </summary>
/// <param name="root">the root of the DOM sub-tree the selection is in</param>
/// <param name="selectionStart">selection start word limit</param>
/// <param name="selectionEnd">selection end word limit</param>
private void SelectWordsInRange(CssBox root, CssRect selectionStart, CssRect selectionEnd)
{
bool inSelection = false;
SelectWordsInRange(root, selectionStart, selectionEnd, ref inSelection);
}
/// <summary>
/// Select all the words that are between <paramref name="selectionStart"/> word and <paramref name="selectionEnd"/> word in the DOM hierarchy.
/// </summary>
/// <param name="box">the current traversal node</param>
/// <param name="selectionStart">selection start word limit</param>
/// <param name="selectionEnd">selection end word limit</param>
/// <param name="inSelection">used to know the traversal is currently in selected range</param>
/// <returns></returns>
private bool SelectWordsInRange(CssBox box, CssRect selectionStart, CssRect selectionEnd, ref bool inSelection)
{
foreach (var boxWord in box.Words)
{
if (!inSelection && boxWord == selectionStart)
{
inSelection = true;
}
if (inSelection)
{
boxWord.Selection = this;
if (selectionStart == selectionEnd || boxWord == selectionEnd)
{
return true;
}
}
}
foreach (var childBox in box.Boxes)
{
if (SelectWordsInRange(childBox, selectionStart, selectionEnd, ref inSelection))
{
return true;
}
}
return false;
}
/// <summary>
/// Calculate the character index and offset by characters for the given word and given offset.<br/>
/// <seealso cref="CalculateWordCharIndexAndOffset(RControl,HtmlRenderer.Core.Dom.CssRect,RPoint,bool)"/>.
/// </summary>
/// <param name="control">used to create graphics to measure string</param>
/// <param name="word">the word to calculate its index and offset</param>
/// <param name="loc">the location to calculate for</param>
/// <param name="selectionStart">to set the starting or ending char and offset data</param>
private void CalculateWordCharIndexAndOffset(RControl control, CssRect word, RPoint loc, bool selectionStart)
{
int selectionIndex;
double selectionOffset;
CalculateWordCharIndexAndOffset(control, word, loc, selectionStart, out selectionIndex, out selectionOffset);
if (selectionStart)
{
_selectionStartIndex = selectionIndex;
_selectionStartOffset = selectionOffset;
}
else
{
_selectionEndIndex = selectionIndex;
_selectionEndOffset = selectionOffset;
}
}
/// <summary>
/// Calculate the character index and offset by characters for the given word and given offset.<br/>
/// If the location is below the word line then set the selection to the end.<br/>
/// If the location is to the right of the word then set the selection to the end.<br/>
/// If the offset is to the left of the word set the selection to the beginning.<br/>
/// Otherwise calculate the width of each substring to find the char the location is on.
/// </summary>
/// <param name="control">used to create graphics to measure string</param>
/// <param name="word">the word to calculate its index and offset</param>
/// <param name="loc">the location to calculate for</param>
/// <param name="inclusive">is to include the first character in the calculation</param>
/// <param name="selectionIndex">return the index of the char under the location</param>
/// <param name="selectionOffset">return the offset of the char under the location</param>
private static void CalculateWordCharIndexAndOffset(RControl control, CssRect word, RPoint loc, bool inclusive, out int selectionIndex, out double selectionOffset)
{
selectionIndex = 0;
selectionOffset = 0f;
var offset = loc.X - word.Left;
if (word.Text == null)
{
// not a text word - set full selection
selectionIndex = -1;
selectionOffset = -1;
}
else if (offset > word.Width - word.OwnerBox.ActualWordSpacing || loc.Y > DomUtils.GetCssLineBoxByWord(word).LineBottom)
{
// mouse under the line, to the right of the word - set to the end of the word
selectionIndex = word.Text.Length;
selectionOffset = word.Width;
}
else if (offset > 0)
{
// calculate partial word selection
int charFit;
double charFitWidth;
var maxWidth = offset + (inclusive ? 0 : 1.5f * word.LeftGlyphPadding);
control.MeasureString(word.Text, word.OwnerBox.ActualFont, maxWidth, out charFit, out charFitWidth);
selectionIndex = charFit;
selectionOffset = charFitWidth;
}
}
/// <summary>
/// Check if the selection direction is forward or backward.<br/>
/// Is the selection start word is before the selection end word in DFS traversal.
/// </summary>
private void CheckSelectionDirection()
{
if (_selectionStart == _selectionEnd)
{
_backwardSelection = _selectionStartIndex > _selectionEndIndex;
}
else if (DomUtils.GetCssLineBoxByWord(_selectionStart) == DomUtils.GetCssLineBoxByWord(_selectionEnd))
{
_backwardSelection = _selectionStart.Left > _selectionEnd.Left;
}
else
{
_backwardSelection = _selectionStart.Top >= _selectionEnd.Bottom;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Threading;
namespace System.Configuration.Internal
{
internal class WriteFileContext
{
private const int SavingTimeout = 10000; // 10 seconds
private const int SavingRetryInterval = 100; // 100 milliseconds
private readonly string _templateFilename;
private IO.Internal.TempFileCollection _tempFiles;
internal WriteFileContext(string filename, string templateFilename)
{
string directoryname = UrlPath.GetDirectoryOrRootName(filename);
_templateFilename = templateFilename;
_tempFiles = new IO.Internal.TempFileCollection(directoryname);
try
{
TempNewFilename = _tempFiles.AddExtension("newcfg");
}
catch
{
((IDisposable)_tempFiles).Dispose();
_tempFiles = null;
throw;
}
}
internal string TempNewFilename { get; }
// Cleanup the WriteFileContext object based on either success
// or failure
//
// Note: The current algorithm guarantess
// 1) The file we are saving to will always be present
// on the file system (ie. there will be no window
// during saving in which there won't be a file there)
// 2) It will always be available for reading from a
// client and it will be complete and accurate.
//
// ... This means that writing is a bit more complicated, and may
// have to be retried (because of reading lock), but I don't see
// anyway to get around this given 1 and 2.
internal void Complete(string filename, bool success)
{
try
{
if (!success) return;
if (File.Exists(filename))
{
// Test that we can write to the file
ValidateWriteAccess(filename);
// Copy Attributes from original
DuplicateFileAttributes(filename, TempNewFilename);
}
else
{
if (_templateFilename != null)
{
// Copy Acl from template file
DuplicateTemplateAttributes(_templateFilename, TempNewFilename);
}
}
ReplaceFile(TempNewFilename, filename);
// Don't delete, since we just moved it.
_tempFiles.KeepFiles = true;
}
finally
{
((IDisposable)_tempFiles).Dispose();
_tempFiles = null;
}
}
// Copy all the files attributes that we care about from the source
// file to the destination file
private void DuplicateFileAttributes(string source, string destination)
{
DateTime creationTime;
// Copy File Attributes, ie. Hidden, Readonly, etc.
FileAttributes attributes = File.GetAttributes(source);
File.SetAttributes(destination, attributes);
// Copy Creation Time
creationTime = File.GetCreationTimeUtc(source);
File.SetCreationTimeUtc(destination, creationTime);
// Copy ACL's
DuplicateTemplateAttributes(source, destination);
}
// Copy over all the attributes you would want copied from a template file.
// As of right now this is just acl's
private void DuplicateTemplateAttributes(string source, string destination)
{
FileAttributes fileAttributes = File.GetAttributes(source);
File.SetAttributes(destination, fileAttributes);
}
// Validate that we can write to the file. This will enforce the ACL's
// on the file. Since we do our moving of files to replace, this is
// nice to ensure we are not by-passing some security permission
// that someone set (although that could bypass this via move themselves)
//
// Note: 1) This is really just a nice to have, since with directory permissions
// they could do the same thing we are doing
//
// 2) We are depending on the current behavior that if the file is locked
// and we can not open it, that we will get an UnauthorizedAccessException
// and not the IOException.
private void ValidateWriteAccess(string filename)
{
FileStream fs = null;
try
{
// Try to open file for write access
fs = new FileStream(filename,
FileMode.Open,
FileAccess.Write,
FileShare.ReadWrite);
}
catch (IOException)
{
// Someone else was using the file. Since we did not get
// the unauthorizedAccessException we have access to the file
}
finally
{
fs?.Close();
}
}
/// <summary>
/// Replace one file with another, retrying if locked.
/// </summary>
private void ReplaceFile(string source, string target)
{
bool writeSucceeded;
int duration = 0;
writeSucceeded = AttemptMove(source, target);
// The file may be open for read, if it is then
// lets try again because maybe they will finish
// soon, and we will be able to replace
while (!writeSucceeded &&
(duration < SavingTimeout) &&
File.Exists(target) &&
!FileIsWriteLocked(target))
{
Thread.Sleep(SavingRetryInterval);
duration += SavingRetryInterval;
writeSucceeded = AttemptMove(source, target);
}
if (!writeSucceeded)
{
throw new ConfigurationErrorsException(string.Format(SR.Config_write_failed, target));
}
}
// Attempt to move a file from one location to another, overwriting if needed
private bool AttemptMove(string source, string target)
{
try
{
if (File.Exists(target))
{
File.Replace(source, target, null);
}
else
{
File.Move(source, target);
}
return true;
}
catch
{
return false;
}
}
private static bool FileIsWriteLocked(string fileName)
{
Stream fileStream = null;
if (!File.Exists(fileName))
{
// It can't be locked if it doesn't exist
return false;
}
try
{
// Try to open for shared reading
fileStream = new FileStream(fileName,
FileMode.Open,
FileAccess.Read,
FileShare.Read | FileShare.Delete);
// If we can open it for shared reading, it is not write locked
return false;
}
catch
{
return true;
}
finally
{
fileStream?.Close();
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal abstract partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax> : IIntroduceVariableService
where TService : AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
where TExpressionSyntax : SyntaxNode
where TTypeSyntax : TExpressionSyntax
where TTypeDeclarationSyntax : SyntaxNode
where TQueryExpressionSyntax : TExpressionSyntax
{
protected abstract bool IsInNonFirstQueryClause(TExpressionSyntax expression);
protected abstract bool IsInFieldInitializer(TExpressionSyntax expression);
protected abstract bool IsInParameterInitializer(TExpressionSyntax expression);
protected abstract bool IsInConstructorInitializer(TExpressionSyntax expression);
protected abstract bool IsInAttributeArgumentInitializer(TExpressionSyntax expression);
protected abstract IEnumerable<SyntaxNode> GetContainingExecutableBlocks(TExpressionSyntax expression);
protected abstract IList<bool> GetInsertionIndices(TTypeDeclarationSyntax destination, CancellationToken cancellationToken);
protected abstract bool CanIntroduceVariableFor(TExpressionSyntax expression);
protected abstract bool CanReplace(TExpressionSyntax expression);
protected abstract Task<Document> IntroduceQueryLocalAsync(SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, CancellationToken cancellationToken);
protected abstract Task<Document> IntroduceLocalAsync(SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, bool isConstant, CancellationToken cancellationToken);
protected abstract Task<Tuple<Document, SyntaxNode, int>> IntroduceFieldAsync(SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, bool isConstant, CancellationToken cancellationToken);
protected virtual bool BlockOverlapsHiddenPosition(SyntaxNode block, CancellationToken cancellationToken)
{
return block.OverlapsHiddenPosition(cancellationToken);
}
public async Task<IIntroduceVariableResult> IntroduceVariableAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_IntroduceVariable, cancellationToken))
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var state = State.Generate((TService)this, semanticDocument, textSpan, cancellationToken);
if (state == null)
{
return IntroduceVariableResult.Failure;
}
var actions = await CreateActionsAsync(state, cancellationToken).ConfigureAwait(false);
if (actions.Count == 0)
{
return IntroduceVariableResult.Failure;
}
return new IntroduceVariableResult(new CodeRefactoring(null, actions));
}
}
private async Task<List<CodeAction>> CreateActionsAsync(State state, CancellationToken cancellationToken)
{
var actions = new List<CodeAction>();
if (state.InQueryContext)
{
actions.Add(CreateAction(state, allOccurrences: false, isConstant: false, isLocal: false, isQueryLocal: true));
actions.Add(CreateAction(state, allOccurrences: true, isConstant: false, isLocal: false, isQueryLocal: true));
}
else if (state.InParameterContext)
{
actions.Add(CreateAction(state, allOccurrences: false, isConstant: true, isLocal: false, isQueryLocal: false));
actions.Add(CreateAction(state, allOccurrences: true, isConstant: true, isLocal: false, isQueryLocal: false));
}
else if (state.InFieldContext)
{
actions.Add(CreateAction(state, allOccurrences: false, isConstant: state.IsConstant, isLocal: false, isQueryLocal: false));
actions.Add(CreateAction(state, allOccurrences: true, isConstant: state.IsConstant, isLocal: false, isQueryLocal: false));
}
else if (state.InConstructorInitializerContext)
{
actions.Add(CreateAction(state, allOccurrences: false, isConstant: state.IsConstant, isLocal: false, isQueryLocal: false));
actions.Add(CreateAction(state, allOccurrences: true, isConstant: state.IsConstant, isLocal: false, isQueryLocal: false));
}
else if (state.InAttributeContext)
{
actions.Add(CreateAction(state, allOccurrences: false, isConstant: true, isLocal: false, isQueryLocal: false));
actions.Add(CreateAction(state, allOccurrences: true, isConstant: true, isLocal: false, isQueryLocal: false));
}
else if (state.InBlockContext)
{
if (state.IsConstant &&
!state.GetSemanticMap(cancellationToken).AllReferencedSymbols.OfType<ILocalSymbol>().Any() &&
!state.GetSemanticMap(cancellationToken).AllReferencedSymbols.OfType<IParameterSymbol>().Any())
{
// If something is a constant, and it doesn't access any other locals constants,
// then we prefer to offer to generate a constant field instead of a constant
// local.
var action1 = CreateAction(state, allOccurrences: false, isConstant: true, isLocal: false, isQueryLocal: false);
if (await CanGenerateIntoContainerAsync(state, action1, cancellationToken).ConfigureAwait(false))
{
actions.Add(action1);
}
var action2 = CreateAction(state, allOccurrences: true, isConstant: true, isLocal: false, isQueryLocal: false);
if (await CanGenerateIntoContainerAsync(state, action2, cancellationToken).ConfigureAwait(false))
{
actions.Add(action2);
}
}
var blocks = this.GetContainingExecutableBlocks(state.Expression);
var block = blocks.FirstOrDefault();
if (!BlockOverlapsHiddenPosition(block, cancellationToken))
{
actions.Add(CreateAction(state, allOccurrences: false, isConstant: state.IsConstant, isLocal: true, isQueryLocal: false));
if (blocks.All(b => !BlockOverlapsHiddenPosition(b, cancellationToken)))
{
actions.Add(CreateAction(state, allOccurrences: true, isConstant: state.IsConstant, isLocal: true, isQueryLocal: false));
}
}
}
return actions;
}
private async Task<bool> CanGenerateIntoContainerAsync(State state, CodeAction action, CancellationToken cancellationToken)
{
var result = await this.IntroduceFieldAsync(
state.Document, state.Expression,
allOccurrences: false, isConstant: state.IsConstant, cancellationToken: cancellationToken).ConfigureAwait(false);
SyntaxNode destination = result.Item2;
int insertionIndex = result.Item3;
if (!destination.OverlapsHiddenPosition(cancellationToken))
{
return true;
}
if (destination is TTypeDeclarationSyntax)
{
var insertionIndices = this.GetInsertionIndices((TTypeDeclarationSyntax)destination, cancellationToken);
if (insertionIndices != null &&
insertionIndices.Count > insertionIndex &&
insertionIndices[insertionIndex])
{
return true;
}
}
return false;
}
private CodeAction CreateAction(State state, bool allOccurrences, bool isConstant, bool isLocal, bool isQueryLocal)
{
if (allOccurrences)
{
return new IntroduceVariableAllOccurrenceCodeAction((TService)this, state.Document, state.Expression, allOccurrences, isConstant, isLocal, isQueryLocal);
}
return new IntroduceVariableCodeAction((TService)this, state.Document, state.Expression, allOccurrences, isConstant, isLocal, isQueryLocal);
}
protected static SyntaxToken GenerateUniqueFieldName(
SemanticDocument document,
TExpressionSyntax expression,
bool isConstant,
CancellationToken cancellationToken)
{
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var semanticFacts = document.Project.LanguageServices.GetService<ISemanticFactsService>();
var semanticModel = document.SemanticModel;
var baseName = semanticFacts.GenerateNameForExpression(semanticModel, expression, isConstant);
// A field can't conflict with any existing member names.
var declaringType = semanticModel.GetEnclosingNamedType(expression.SpanStart, cancellationToken);
var reservedNames = declaringType.GetMembers().Select(m => m.Name);
return syntaxFacts.ToIdentifierToken(
NameGenerator.EnsureUniqueness(baseName, reservedNames, syntaxFacts.IsCaseSensitive));
}
protected static SyntaxToken GenerateUniqueLocalName(
SemanticDocument document,
TExpressionSyntax expression,
bool isConstant,
CancellationToken cancellationToken)
{
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var semanticFacts = document.Project.LanguageServices.GetService<ISemanticFactsService>();
var semanticModel = document.SemanticModel;
var baseName = semanticFacts.GenerateNameForExpression(semanticModel, expression, capitalize: isConstant);
var reservedNames = semanticModel.LookupSymbols(expression.SpanStart).Select(s => s.Name);
return syntaxFacts.ToIdentifierToken(
NameGenerator.EnsureUniqueness(baseName, reservedNames, syntaxFacts.IsCaseSensitive));
}
protected ISet<TExpressionSyntax> FindMatches(
SemanticDocument originalDocument,
TExpressionSyntax expressionInOriginal,
SemanticDocument currentDocument,
SyntaxNode withinNodeInCurrent,
bool allOccurrences,
CancellationToken cancellationToken)
{
var syntaxFacts = currentDocument.Project.LanguageServices.GetService<ISyntaxFactsService>();
var originalSemanticModel = originalDocument.SemanticModel;
var currentSemanticModel = currentDocument.SemanticModel;
var result = new HashSet<TExpressionSyntax>();
var matches = from nodeInCurrent in withinNodeInCurrent.DescendantNodesAndSelf().OfType<TExpressionSyntax>()
where NodeMatchesExpression(originalSemanticModel, currentSemanticModel, syntaxFacts, expressionInOriginal, nodeInCurrent, allOccurrences, cancellationToken)
select nodeInCurrent;
result.AddRange(matches.OfType<TExpressionSyntax>());
return result;
}
private bool NodeMatchesExpression(
SemanticModel originalSemanticModel,
SemanticModel currentSemanticModel,
ISyntaxFactsService syntaxFacts,
TExpressionSyntax expressionInOriginal,
TExpressionSyntax nodeInCurrent,
bool allOccurrences,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (nodeInCurrent == expressionInOriginal)
{
return true;
}
else
{
if (allOccurrences &&
this.CanReplace(nodeInCurrent))
{
return SemanticEquivalence.AreSemanticallyEquivalent(
originalSemanticModel, currentSemanticModel, expressionInOriginal, nodeInCurrent);
}
}
return false;
}
protected TNode Rewrite<TNode>(
SemanticDocument originalDocument,
TExpressionSyntax expressionInOriginal,
TExpressionSyntax variableName,
SemanticDocument currentDocument,
TNode withinNodeInCurrent,
bool allOccurrences,
CancellationToken cancellationToken)
where TNode : SyntaxNode
{
var syntaxFacts = originalDocument.Project.LanguageServices.GetService<ISyntaxFactsService>();
var matches = FindMatches(originalDocument, expressionInOriginal, currentDocument, withinNodeInCurrent, allOccurrences, cancellationToken);
// Parenthesize the variable, and go and replace anything we find with it.
// NOTE: we do not want elastic trivia as we want to just replace the existing code
// as is, while preserving the trivia there. We do not want to update it.
var replacement = syntaxFacts.Parenthesize(variableName, includeElasticTrivia: false)
.WithAdditionalAnnotations(Formatter.Annotation);
return RewriteCore(withinNodeInCurrent, replacement, matches);
}
protected abstract TNode RewriteCore<TNode>(
TNode node,
SyntaxNode replacementNode,
ISet<TExpressionSyntax> matches)
where TNode : SyntaxNode;
protected static ITypeSymbol GetTypeSymbol(
SemanticDocument document,
TExpressionSyntax expression,
CancellationToken cancellationToken,
bool objectAsDefault = true)
{
var semanticModel = document.SemanticModel;
var typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken);
if (typeInfo.Type != null)
{
return typeInfo.Type;
}
if (typeInfo.ConvertedType != null)
{
return typeInfo.ConvertedType;
}
if (objectAsDefault)
{
return semanticModel.Compilation.GetSpecialType(SpecialType.System_Object);
}
return null;
}
protected static IEnumerable<IParameterSymbol> GetAnonymousMethodParameters(
SemanticDocument document, TExpressionSyntax expression, CancellationToken cancellationToken)
{
var semanticModel = document.SemanticModel;
var semanticMap = semanticModel.GetSemanticMap(expression, cancellationToken);
var anonymousMethodParameters = semanticMap.AllReferencedSymbols
.OfType<IParameterSymbol>()
.Where(p => p.ContainingSymbol.IsAnonymousFunction());
return anonymousMethodParameters;
}
}
}
| |
/*
* Copyright 2012-2021 The Pkcs11Interop Project
*
* 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <[email protected]>
*/
using System;
using System.IO;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI41;
using NUnit.Framework;
using NativeULong = System.UInt32;
// Note: Code in this file is maintained manually.
namespace Net.Pkcs11Interop.Tests.LowLevelAPI41
{
/// <summary>
/// C_SignEncryptUpdate and C_DecryptVerifyUpdate tests.
/// </summary>
[TestFixture()]
public class _24_SignEncryptAndDecryptVerifyTest
{
/// <summary>
/// Basic C_SignEncryptUpdate and C_DecryptVerifyUpdate test.
/// </summary>
[Test()]
public void _01_BasicSignEncryptAndDecryptVerifyTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
{
rv = pkcs11Library.C_Initialize(Settings.InitArgs41);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate asymetric key pair
NativeULong pubKeyId = CK.CK_INVALID_HANDLE;
NativeULong privKeyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKeyPair(pkcs11Library, session, ref pubKeyId, ref privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify signing mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM signingMechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS);
// Generate symetric key
NativeULong keyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKey(pkcs11Library, session, ref keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate random initialization vector
byte[] iv = new byte[8];
rv = pkcs11Library.C_GenerateRandom(session, iv, ConvertUtils.UInt32FromInt32(iv.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify encryption mechanism with initialization vector as parameter.
// Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory.
CK_MECHANISM encryptionMechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv);
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Passw0rd");
byte[] signature = null;
byte[] encryptedData = null;
byte[] decryptedData = null;
// Multipart signing and encryption function C_SignEncryptUpdate can be used i.e. for signing and encryption of streamed data
using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream())
{
// Initialize signing operation
rv = pkcs11Library.C_SignInit(session, ref signingMechanism, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Initialize encryption operation
rv = pkcs11Library.C_EncryptInit(session, ref encryptionMechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for source data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
// Prepare buffer for encrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] encryptedPart = new byte[8];
NativeULong encryptedPartLen = ConvertUtils.UInt32FromInt32(encryptedPart.Length);
// Read input stream with source data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
{
// Process each individual source data part
encryptedPartLen = ConvertUtils.UInt32FromInt32(encryptedPart.Length);
rv = pkcs11Library.C_SignEncryptUpdate(session, part, ConvertUtils.UInt32FromInt32(bytesRead), encryptedPart, ref encryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append encrypted data part to the output stream
outputStream.Write(encryptedPart, 0, ConvertUtils.UInt32ToInt32(encryptedPartLen));
}
// Get the length of signature in first call
NativeULong signatureLen = 0;
rv = pkcs11Library.C_SignFinal(session, null, ref signatureLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(signatureLen > 0);
// Allocate array for signature
signature = new byte[signatureLen];
// Get signature in second call
rv = pkcs11Library.C_SignFinal(session, signature, ref signatureLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Get the length of last encrypted data part in first call
byte[] lastEncryptedPart = null;
NativeULong lastEncryptedPartLen = 0;
rv = pkcs11Library.C_EncryptFinal(session, null, ref lastEncryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Allocate array for the last encrypted data part
lastEncryptedPart = new byte[lastEncryptedPartLen];
// Get the last encrypted data part in second call
rv = pkcs11Library.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append the last encrypted data part to the output stream
outputStream.Write(lastEncryptedPart, 0, ConvertUtils.UInt32ToInt32(lastEncryptedPartLen));
// Read whole output stream to the byte array so we can compare results more easily
encryptedData = outputStream.ToArray();
}
// Do something interesting with signature and encrypted data
// Multipart decryption and verification function C_DecryptVerifyUpdate can be used i.e. for decryption and signature verification of streamed data
using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream())
{
// Initialize decryption operation
rv = pkcs11Library.C_DecryptInit(session, ref encryptionMechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Initialize verification operation
rv = pkcs11Library.C_VerifyInit(session, ref signingMechanism, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for encrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] encryptedPart = new byte[8];
// Prepare buffer for decrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
NativeULong partLen = ConvertUtils.UInt32FromInt32(part.Length);
// Read input stream with encrypted data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(encryptedPart, 0, encryptedPart.Length)) > 0)
{
// Process each individual encrypted data part
partLen = ConvertUtils.UInt32FromInt32(part.Length);
rv = pkcs11Library.C_DecryptVerifyUpdate(session, encryptedPart, ConvertUtils.UInt32FromInt32(bytesRead), part, ref partLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append decrypted data part to the output stream
outputStream.Write(part, 0, ConvertUtils.UInt32ToInt32(partLen));
}
// Get the length of last decrypted data part in first call
byte[] lastPart = null;
NativeULong lastPartLen = 0;
rv = pkcs11Library.C_DecryptFinal(session, null, ref lastPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Allocate array for the last decrypted data part
lastPart = new byte[lastPartLen];
// Get the last decrypted data part in second call
rv = pkcs11Library.C_DecryptFinal(session, lastPart, ref lastPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append the last decrypted data part to the output stream
outputStream.Write(lastPart, 0, ConvertUtils.UInt32ToInt32(lastPartLen));
// Read whole output stream to the byte array so we can compare results more easily
decryptedData = outputStream.ToArray();
// Verify signature
rv = pkcs11Library.C_VerifyFinal(session, signature, ConvertUtils.UInt32FromInt32(signature.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Do something interesting with decrypted data and verification result
Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData));
// In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case)
UnmanagedMemory.Free(ref encryptionMechanism.Parameter);
encryptionMechanism.ParameterLen = 0;
rv = pkcs11Library.C_DestroyObject(session, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_DestroyObject(session, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_DestroyObject(session, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| |
using System;
using System.Diagnostics;
using StandardColor = System.Drawing.Color;
namespace Discord
{
/// <summary>
/// Represents a color used in Discord.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public struct Color
{
/// <summary> Gets the default user color value. </summary>
public static readonly Color Default = new Color(0);
/// <summary> Gets the teal color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/1ABC9C">1ABC9C</see>.</returns>
public static readonly Color Teal = new Color(0x1ABC9C);
/// <summary> Gets the dark teal color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/11806A">11806A</see>.</returns>
public static readonly Color DarkTeal = new Color(0x11806A);
/// <summary> Gets the green color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/2ECC71">2ECC71</see>.</returns>
public static readonly Color Green = new Color(0x2ECC71);
/// <summary> Gets the dark green color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/1F8B4C">1F8B4C</see>.</returns>
public static readonly Color DarkGreen = new Color(0x1F8B4C);
/// <summary> Gets the blue color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/3498DB">3498DB</see>.</returns>
public static readonly Color Blue = new Color(0x3498DB);
/// <summary> Gets the dark blue color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/206694">206694</see>.</returns>
public static readonly Color DarkBlue = new Color(0x206694);
/// <summary> Gets the purple color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/9B59B6">9B59B6</see>.</returns>
public static readonly Color Purple = new Color(0x9B59B6);
/// <summary> Gets the dark purple color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/71368A">71368A</see>.</returns>
public static readonly Color DarkPurple = new Color(0x71368A);
/// <summary> Gets the magenta color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/E91E63">E91E63</see>.</returns>
public static readonly Color Magenta = new Color(0xE91E63);
/// <summary> Gets the dark magenta color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/AD1457">AD1457</see>.</returns>
public static readonly Color DarkMagenta = new Color(0xAD1457);
/// <summary> Gets the gold color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/F1C40F">F1C40F</see>.</returns>
public static readonly Color Gold = new Color(0xF1C40F);
/// <summary> Gets the light orange color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/C27C0E">C27C0E</see>.</returns>
public static readonly Color LightOrange = new Color(0xC27C0E);
/// <summary> Gets the orange color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/E67E22">E67E22</see>.</returns>
public static readonly Color Orange = new Color(0xE67E22);
/// <summary> Gets the dark orange color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/A84300">A84300</see>.</returns>
public static readonly Color DarkOrange = new Color(0xA84300);
/// <summary> Gets the red color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/E74C3C">E74C3C</see>.</returns>
public static readonly Color Red = new Color(0xE74C3C);
/// <summary> Gets the dark red color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/992D22">992D22</see>.</returns>
public static readonly Color DarkRed = new Color(0x992D22);
/// <summary> Gets the light grey color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/979C9F">979C9F</see>.</returns>
public static readonly Color LightGrey = new Color(0x979C9F);
/// <summary> Gets the lighter grey color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/95A5A6">95A5A6</see>.</returns>
public static readonly Color LighterGrey = new Color(0x95A5A6);
/// <summary> Gets the dark grey color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/607D8B">607D8B</see>.</returns>
public static readonly Color DarkGrey = new Color(0x607D8B);
/// <summary> Gets the darker grey color value. </summary>
/// <returns> A color struct with the hex value of <see href="http://www.color-hex.com/color/546E7A">546E7A</see>.</returns>
public static readonly Color DarkerGrey = new Color(0x546E7A);
/// <summary> Gets the encoded value for this color. </summary>
/// <remarks>
/// This value is encoded as an unsigned integer value. The most-significant 8 bits contain the red value,
/// the middle 8 bits contain the green value, and the least-significant 8 bits contain the blue value.
/// </remarks>
public uint RawValue { get; }
/// <summary> Gets the red component for this color. </summary>
public byte R => (byte)(RawValue >> 16);
/// <summary> Gets the green component for this color. </summary>
public byte G => (byte)(RawValue >> 8);
/// <summary> Gets the blue component for this color. </summary>
public byte B => (byte)(RawValue);
/// <summary>
/// Initializes a <see cref="Color"/> struct with the given raw value.
/// </summary>
/// <example>
/// The following will create a color that has a hex value of
/// <see href="http://www.color-hex.com/color/607d8b">#607D8B</see>.
/// <code language="cs">
/// Color darkGrey = new Color(0x607D8B);
/// </code>
/// </example>
/// <param name="rawValue">The raw value of the color (e.g. <c>0x607D8B</c>).</param>
public Color(uint rawValue)
{
RawValue = rawValue;
}
/// <summary>
/// Initializes a <see cref="Color" /> struct with the given RGB bytes.
/// </summary>
/// <example>
/// The following will create a color that has a value of
/// <see href="http://www.color-hex.com/color/607d8b">#607D8B</see>.
/// <code language="cs">
/// Color darkGrey = new Color((byte)0b_01100000, (byte)0b_01111101, (byte)0b_10001011);
/// </code>
/// </example>
/// <param name="r">The byte that represents the red color.</param>
/// <param name="g">The byte that represents the green color.</param>
/// <param name="b">The byte that represents the blue color.</param>
public Color(byte r, byte g, byte b)
{
RawValue =
((uint)r << 16) |
((uint)g << 8) |
(uint)b;
}
/// <summary>
/// Initializes a <see cref="Color"/> struct with the given RGB value.
/// </summary>
/// <example>
/// The following will create a color that has a value of
/// <see href="http://www.color-hex.com/color/607d8b">#607D8B</see>.
/// <code language="cs">
/// Color darkGrey = new Color(96, 125, 139);
/// </code>
/// </example>
/// <param name="r">The value that represents the red color. Must be within 0~255.</param>
/// <param name="g">The value that represents the green color. Must be within 0~255.</param>
/// <param name="b">The value that represents the blue color. Must be within 0~255.</param>
/// <exception cref="ArgumentOutOfRangeException">The argument value is not between 0 to 255.</exception>
public Color(int r, int g, int b)
{
if (r < 0 || r > 255)
throw new ArgumentOutOfRangeException(nameof(r), "Value must be within [0,255].");
if (g < 0 || g > 255)
throw new ArgumentOutOfRangeException(nameof(g), "Value must be within [0,255].");
if (b < 0 || b > 255)
throw new ArgumentOutOfRangeException(nameof(b), "Value must be within [0,255].");
RawValue =
((uint)r << 16) |
((uint)g << 8) |
(uint)b;
}
/// <summary>
/// Initializes a <see cref="Color"/> struct with the given RGB float value.
/// </summary>
/// <example>
/// The following will create a color that has a value of
/// <see href="http://www.color-hex.com/color/607c8c">#607c8c</see>.
/// <code language="cs">
/// Color darkGrey = new Color(0.38f, 0.49f, 0.55f);
/// </code>
/// </example>
/// <param name="r">The value that represents the red color. Must be within 0~1.</param>
/// <param name="g">The value that represents the green color. Must be within 0~1.</param>
/// <param name="b">The value that represents the blue color. Must be within 0~1.</param>
/// <exception cref="ArgumentOutOfRangeException">The argument value is not between 0 to 1.</exception>
public Color(float r, float g, float b)
{
if (r < 0.0f || r > 1.0f)
throw new ArgumentOutOfRangeException(nameof(r), "Value must be within [0,1].");
if (g < 0.0f || g > 1.0f)
throw new ArgumentOutOfRangeException(nameof(g), "Value must be within [0,1].");
if (b < 0.0f || b > 1.0f)
throw new ArgumentOutOfRangeException(nameof(b), "Value must be within [0,1].");
RawValue =
((uint)(r * 255.0f) << 16) |
((uint)(g * 255.0f) << 8) |
(uint)(b * 255.0f);
}
public static bool operator ==(Color lhs, Color rhs)
=> lhs.RawValue == rhs.RawValue;
public static bool operator !=(Color lhs, Color rhs)
=> lhs.RawValue != rhs.RawValue;
public override bool Equals(object obj)
=> (obj is Color c && RawValue == c.RawValue);
public override int GetHashCode() => RawValue.GetHashCode();
public static implicit operator StandardColor(Color color) =>
StandardColor.FromArgb((int)color.RawValue);
public static explicit operator Color(StandardColor color) =>
new Color((uint)color.ToArgb() << 8 >> 8);
/// <summary>
/// Gets the hexadecimal representation of the color (e.g. <c>#000ccc</c>).
/// </summary>
/// <returns>
/// A hexadecimal string of the color.
/// </returns>
public override string ToString() =>
string.Format("#{0:X6}", RawValue);
private string DebuggerDisplay =>
string.Format("#{0:X6} ({0})", RawValue);
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: UnsafeNativeMethods
**
============================================================*/
namespace Microsoft.Win32 {
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Configuration.Assemblies;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Security.Principal;
using System.Runtime.Serialization;
using System.Threading;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Diagnostics.Eventing;
using System.Diagnostics.Eventing.Reader;
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class UnsafeNativeMethods {
internal const String KERNEL32 = "kernel32.dll";
internal const String ADVAPI32 = "advapi32.dll";
internal const String WEVTAPI = "wevtapi.dll";
internal static readonly IntPtr NULL = IntPtr.Zero;
//
// Win32 IO
//
internal const int CREDUI_MAX_USERNAME_LENGTH = 513;
// WinError.h codes:
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_PATH_NOT_FOUND = 0x3;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
// Can occurs when filled buffers are trying to flush to disk, but disk IOs are not fast enough.
// This happens when the disk is slow and event traffic is heavy.
// Eventually, there are no more free (empty) buffers and the event is dropped.
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int ERROR_INVALID_DRIVE = 0xF;
internal const int ERROR_NO_MORE_FILES = 0x12;
internal const int ERROR_NOT_READY = 0x15;
internal const int ERROR_BAD_LENGTH = 0x18;
internal const int ERROR_SHARING_VIOLATION = 0x20;
internal const int ERROR_LOCK_VIOLATION = 0x21; // 33
internal const int ERROR_HANDLE_EOF = 0x26; // 38
internal const int ERROR_FILE_EXISTS = 0x50;
internal const int ERROR_INVALID_PARAMETER = 0x57; // 87
internal const int ERROR_BROKEN_PIPE = 0x6D; // 109
internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; // 122
internal const int ERROR_INVALID_NAME = 0x7B;
internal const int ERROR_BAD_PATHNAME = 0xA1;
internal const int ERROR_ALREADY_EXISTS = 0xB7;
internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long
internal const int ERROR_PIPE_BUSY = 0xE7; // 231
internal const int ERROR_NO_DATA = 0xE8; // 232
internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9; // 233
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_NO_MORE_ITEMS = 0x103; // 259
internal const int ERROR_PIPE_CONNECTED = 0x217; // 535
internal const int ERROR_PIPE_LISTENING = 0x218; // 536
internal const int ERROR_OPERATION_ABORTED = 0x3E3; // 995; For IO Cancellation
internal const int ERROR_IO_PENDING = 0x3E5; // 997
internal const int ERROR_NOT_FOUND = 0x490; // 1168
// The event size is larger than the allowed maximum (64k - header).
internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216; // 534
internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 0x717; // 1815
// Event log specific codes:
internal const int ERROR_EVT_MESSAGE_NOT_FOUND = 15027;
internal const int ERROR_EVT_MESSAGE_ID_NOT_FOUND = 15028;
internal const int ERROR_EVT_UNRESOLVED_VALUE_INSERT = 15029;
internal const int ERROR_EVT_UNRESOLVED_PARAMETER_INSERT = 15030;
internal const int ERROR_EVT_MAX_INSERTS_REACHED = 15031;
internal const int ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND = 15033;
internal const int ERROR_MUI_FILE_NOT_FOUND = 15100;
internal const int SECURITY_SQOS_PRESENT = 0x00100000;
internal const int SECURITY_ANONYMOUS = 0 << 16;
internal const int SECURITY_IDENTIFICATION = 1 << 16;
internal const int SECURITY_IMPERSONATION = 2 << 16;
internal const int SECURITY_DELEGATION = 3 << 16;
internal const int GENERIC_READ = unchecked((int)0x80000000);
internal const int GENERIC_WRITE = 0x40000000;
internal const int STD_INPUT_HANDLE = -10;
internal const int STD_OUTPUT_HANDLE = -11;
internal const int STD_ERROR_HANDLE = -12;
internal const int DUPLICATE_SAME_ACCESS = 0x00000002;
internal const int PIPE_ACCESS_INBOUND = 1;
internal const int PIPE_ACCESS_OUTBOUND = 2;
internal const int PIPE_ACCESS_DUPLEX = 3;
internal const int PIPE_TYPE_BYTE = 0;
internal const int PIPE_TYPE_MESSAGE = 4;
internal const int PIPE_READMODE_BYTE = 0;
internal const int PIPE_READMODE_MESSAGE = 2;
internal const int PIPE_UNLIMITED_INSTANCES = 255;
internal const int FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000;
internal const int FILE_SHARE_READ = 0x00000001;
internal const int FILE_SHARE_WRITE = 0x00000002;
internal const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
internal const int FILE_FLAG_OVERLAPPED = 0x40000000;
internal const int OPEN_EXISTING = 3;
// From WinBase.h
internal const int FILE_TYPE_DISK = 0x0001;
internal const int FILE_TYPE_CHAR = 0x0002;
internal const int FILE_TYPE_PIPE = 0x0003;
// Memory mapped file constants
internal const int MEM_COMMIT = 0x1000;
internal const int MEM_RESERVE = 0x2000;
internal const int INVALID_FILE_SIZE = -1;
internal const int PAGE_READWRITE = 0x04;
internal const int PAGE_READONLY = 0x02;
internal const int PAGE_WRITECOPY = 0x08;
internal const int PAGE_EXECUTE_READ = 0x20;
internal const int PAGE_EXECUTE_READWRITE = 0x40;
internal const int FILE_MAP_COPY = 0x0001;
internal const int FILE_MAP_WRITE = 0x0002;
internal const int FILE_MAP_READ = 0x0004;
internal const int FILE_MAP_EXECUTE = 0x0020;
[StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES {
internal int nLength;
[SecurityCritical]
internal unsafe byte* pSecurityDescriptor;
internal int bInheritHandle;
}
[DllImport(KERNEL32)]
[SecurityCritical]
internal static extern int GetFileType(SafeFileHandle handle);
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
internal static unsafe extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite,
out int numBytesWritten, NativeOverlapped* lpOverlapped);
// Disallow access to all non-file devices from methods that take
// a String. This disallows DOS devices like "con:", "com1:",
// "lpt1:", etc. Use this to avoid security problems, like allowing
// a web client asking a server for "http://server/com1.aspx" and
// then causing a worker process to hang.
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
private static extern SafeFileHandle CreateFile(String lpFileName,
int dwDesiredAccess, System.IO.FileShare dwShareMode,
SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
int dwFlagsAndAttributes, IntPtr hTemplateFile);
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
[SecurityCritical]
internal static SafeFileHandle SafeCreateFile(String lpFileName,
int dwDesiredAccess, System.IO.FileShare dwShareMode,
SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
int dwFlagsAndAttributes, IntPtr hTemplateFile) {
SafeFileHandle handle = CreateFile(lpFileName, dwDesiredAccess, dwShareMode,
securityAttrs, dwCreationDisposition,
dwFlagsAndAttributes, hTemplateFile);
if (!handle.IsInvalid) {
int fileType = UnsafeNativeMethods.GetFileType(handle);
if (fileType != UnsafeNativeMethods.FILE_TYPE_DISK) {
handle.Dispose();
throw new NotSupportedException(SR.GetString(SR.NotSupported_IONonFileDevices));
}
}
return handle;
}
// From WinBase.h
internal const int SEM_FAILCRITICALERRORS = 1;
[DllImport(KERNEL32, SetLastError = false)]
[ResourceExposure(ResourceScope.Process)]
[SecurityCritical]
internal static extern int SetErrorMode(int newMode);
[DllImport(KERNEL32, SetLastError = true, EntryPoint = "SetFilePointer")]
[ResourceExposure(ResourceScope.None)]
[SecurityCritical]
private unsafe static extern int SetFilePointerWin32(SafeFileHandle handle, int lo, int* hi, int origin);
[ResourceExposure(ResourceScope.None)]
[SecurityCritical]
internal unsafe static long SetFilePointer(SafeFileHandle handle, long offset, System.IO.SeekOrigin origin, out int hr) {
hr = 0;
int lo = (int)offset;
int hi = (int)(offset >> 32);
lo = SetFilePointerWin32(handle, lo, &hi, (int)origin);
if (lo == -1 && ((hr = Marshal.GetLastWin32Error()) != 0))
return -1;
return (long)(((ulong)((uint)hi)) << 32) | ((uint)lo);
}
//
// ErrorCode & format
//
// Use this to translate error codes like the above into HRESULTs like
// 0x80070006 for ERROR_INVALID_HANDLE
internal static int MakeHRFromErrorCode(int errorCode) {
return unchecked(((int)0x80070000) | errorCode);
}
// for win32 error message formatting
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
[DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = false)]
[SecurityCritical]
internal static extern int FormatMessage(int dwFlags, IntPtr lpSource,
int dwMessageId, int dwLanguageId, StringBuilder lpBuffer,
int nSize, IntPtr va_list_arguments);
// Gets an error message for a Win32 error code.
[SecurityCritical]
internal static String GetMessage(int errorCode) {
StringBuilder sb = new StringBuilder(512);
int result = UnsafeNativeMethods.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
UnsafeNativeMethods.NULL, errorCode, 0, sb, sb.Capacity, UnsafeNativeMethods.NULL);
if (result != 0) {
// result is the # of characters copied to the StringBuilder on NT,
// but on Win9x, it appears to be the number of MBCS buffer.
// Just give up and return the String as-is...
String s = sb.ToString();
return s;
}
else {
return "UnknownError_Num " + errorCode;
}
}
//
// SafeLibraryHandle
//
[DllImport(KERNEL32, CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
[ResourceExposure(ResourceScope.Machine)]
[SecurityCritical]
internal static extern SafeLibraryHandle LoadLibraryEx(string libFilename, IntPtr reserved, int flags);
[DllImport(KERNEL32, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SecurityCritical]
internal static extern bool FreeLibrary(IntPtr hModule);
//
// Pipe
//
[DllImport(KERNEL32, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
[SecurityCritical]
internal static extern bool CloseHandle(IntPtr handle);
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
internal static extern IntPtr GetCurrentProcess();
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DuplicateHandle(IntPtr hSourceProcessHandle,
SafePipeHandle hSourceHandle, IntPtr hTargetProcessHandle, out SafePipeHandle lpTargetHandle,
uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);
[DllImport(KERNEL32)]
[SecurityCritical]
internal static extern int GetFileType(SafePipeHandle handle);
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CreatePipe(out SafePipeHandle hReadPipe,
out SafePipeHandle hWritePipe, SECURITY_ATTRIBUTES lpPipeAttributes, int nSize);
[DllImport(KERNEL32, EntryPoint="CreateFile", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
[SecurityCritical]
internal static extern SafePipeHandle CreateNamedPipeClient(String lpFileName,
int dwDesiredAccess, System.IO.FileShare dwShareMode,
UnsafeNativeMethods.SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
unsafe internal static extern bool ConnectNamedPipe(SafePipeHandle handle, NativeOverlapped* overlapped);
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ConnectNamedPipe(SafePipeHandle handle, IntPtr overlapped);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WaitNamedPipe(String name, int timeout);
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, out int lpState,
IntPtr lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout,
IntPtr lpUserName, int nMaxUserNameSize);
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, IntPtr lpState,
out int lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout,
IntPtr lpUserName, int nMaxUserNameSize);
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, IntPtr lpState,
IntPtr lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout,
StringBuilder lpUserName, int nMaxUserNameSize);
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe,
out int lpFlags,
IntPtr lpOutBufferSize,
IntPtr lpInBufferSize,
IntPtr lpMaxInstances
);
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe,
IntPtr lpFlags,
out int lpOutBufferSize,
IntPtr lpInBufferSize,
IntPtr lpMaxInstances
);
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe,
IntPtr lpFlags,
IntPtr lpOutBufferSize,
out int lpInBufferSize,
IntPtr lpMaxInstances
);
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static unsafe extern bool SetNamedPipeHandleState(
SafePipeHandle hNamedPipe,
int* lpMode,
IntPtr lpMaxCollectionCount,
IntPtr lpCollectDataTimeout
);
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DisconnectNamedPipe(SafePipeHandle hNamedPipe);
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FlushFileBuffers(SafePipeHandle hNamedPipe);
[DllImport(ADVAPI32, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern bool RevertToSelf();
[DllImport(ADVAPI32, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern bool ImpersonateNamedPipeClient(SafePipeHandle hNamedPipe);
[DllImport(KERNEL32, SetLastError = true, BestFitMapping = false, CharSet = CharSet.Auto)]
[SecurityCritical]
internal static extern SafePipeHandle CreateNamedPipe(string pipeName,
int openMode, int pipeMode, int maxInstances,
int outBufferSize, int inBufferSize, int defaultTimeout,
SECURITY_ATTRIBUTES securityAttributes);
// Note there are two different ReadFile prototypes - this is to use
// the type system to force you to not trip across a "feature" in
// Win32's async IO support. You can't do the following three things
// simultaneously: overlapped IO, free the memory for the overlapped
// struct in a callback (or an EndRead method called by that callback),
// and pass in an address for the numBytesRead parameter.
// <STRIP> See Windows Bug 105512 for details. -- </STRIP>
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
unsafe internal static extern int ReadFile(SafePipeHandle handle, byte* bytes, int numBytesToRead,
IntPtr numBytesRead_mustBeZero, NativeOverlapped* overlapped);
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
unsafe internal static extern int ReadFile(SafePipeHandle handle, byte* bytes, int numBytesToRead,
out int numBytesRead, IntPtr mustBeZero);
// Note there are two different WriteFile prototypes - this is to use
// the type system to force you to not trip across a "feature" in
// Win32's async IO support. You can't do the following three things
// simultaneously: overlapped IO, free the memory for the overlapped
// struct in a callback (or an EndWrite method called by that callback),
// and pass in an address for the numBytesRead parameter.
// <STRIP> See Windows Bug 105512 for details. -- </STRIP>
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
internal static unsafe extern int WriteFile(SafePipeHandle handle, byte* bytes, int numBytesToWrite,
IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped);
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
internal static unsafe extern int WriteFile(SafePipeHandle handle, byte* bytes, int numBytesToWrite,
out int numBytesWritten, IntPtr mustBeZero);
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
internal static extern bool SetEndOfFile(IntPtr hNamedPipe);
//
// ETW Methods
//
//
// Callback
//
#pragma warning disable 618 // Ssytem.Core still uses SecurityRuleSet.Level1
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
internal unsafe delegate void EtwEnableCallback(
[In] ref Guid sourceId,
[In] int isEnabled,
[In] byte level,
[In] long matchAnyKeywords,
[In] long matchAllKeywords,
[In] void* filterData,
[In] void* callbackContext
);
//
// Registration APIs
//
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventRegister(
[In] ref Guid providerId,
[In]EtwEnableCallback enableCallback,
[In]void* callbackContext,
[In][Out]ref long registrationHandle
);
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern int EventUnregister([In] long registrationHandle);
//
// Control (Is Enabled) APIs
//
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern int EventEnabled([In] long registrationHandle, [In] ref System.Diagnostics.Eventing.EventDescriptor eventDescriptor);
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventProviderEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern int EventProviderEnabled([In] long registrationHandle, [In] byte level, [In] long keywords);
//
// Writing (Publishing/Logging) APIs
//
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventWrite(
[In] long registrationHandle,
[In] ref EventDescriptor eventDescriptor,
[In] uint userDataCount,
[In] void* userData
);
//
// Writing (Publishing/Logging) APIs
//
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventWrite(
[In] long registrationHandle,
[In] EventDescriptor* eventDescriptor,
[In] uint userDataCount,
[In] void* userData
);
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteTransfer", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventWriteTransfer(
[In] long registrationHandle,
[In] ref EventDescriptor eventDescriptor,
[In] Guid* activityId,
[In] Guid* relatedActivityId,
[In] uint userDataCount,
[In] void* userData
);
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventWriteString(
[In] long registrationHandle,
[In] byte level,
[In] long keywords,
[In] char* message
);
//
// ActivityId Control APIs
//
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventActivityIdControl([In] int ControlCode, [In][Out] ref Guid ActivityId);
// Native PERFLIB V2 Provider APIs.
//
[StructLayout(LayoutKind.Explicit, Size = 40)]
internal struct PerfCounterSetInfoStruct { // PERF_COUNTERSET_INFO structure defined in perflib.h
[FieldOffset(0)] internal Guid CounterSetGuid;
[FieldOffset(16)] internal Guid ProviderGuid;
[FieldOffset(32)] internal uint NumCounters;
[FieldOffset(36)] internal uint InstanceType;
}
[StructLayout(LayoutKind.Explicit, Size = 32)]
internal struct PerfCounterInfoStruct { // PERF_COUNTER_INFO structure defined in perflib.h
[FieldOffset(0)] internal uint CounterId;
[FieldOffset(4)] internal uint CounterType;
[FieldOffset(8)] internal Int64 Attrib;
[FieldOffset(16)] internal uint Size;
[FieldOffset(20)] internal uint DetailLevel;
[FieldOffset(24)] internal uint Scale;
[FieldOffset(28)] internal uint Offset;
}
[StructLayout(LayoutKind.Explicit, Size = 32)]
internal struct PerfCounterSetInstanceStruct { // PERF_COUNTERSET_INSTANCE structure defined in perflib.h
[FieldOffset(0)] internal Guid CounterSetGuid;
[FieldOffset(16)] internal uint dwSize;
[FieldOffset(20)] internal uint InstanceId;
[FieldOffset(24)] internal uint InstanceNameOffset;
[FieldOffset(28)] internal uint InstanceNameSize;
}
#pragma warning disable 618 // Ssytem.Core still uses SecurityRuleSet.Level1
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
internal unsafe delegate uint PERFLIBREQUEST(
[In] uint RequestCode,
[In] void * Buffer,
[In] uint BufferSize
);
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "PerfStartProvider", CharSet = CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint PerfStartProvider(
[In] ref Guid ProviderGuid,
[In] PERFLIBREQUEST ControlCallback,
[Out] out SafePerfProviderHandle phProvider
);
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "PerfStopProvider", CharSet = CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint PerfStopProvider(
[In] IntPtr hProvider
);
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "PerfSetCounterSetInfo", CharSet = CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint PerfSetCounterSetInfo(
[In] SafePerfProviderHandle hProvider,
[In][Out] PerfCounterSetInfoStruct * pTemplate,
[In] uint dwTemplateSize
);
[DllImport(ADVAPI32, SetLastError = true, ExactSpelling = true, EntryPoint = "PerfCreateInstance", CharSet = CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe PerfCounterSetInstanceStruct* PerfCreateInstance(
[In] SafePerfProviderHandle hProvider,
[In] ref Guid CounterSetGuid,
[In] String szInstanceName,
[In] uint dwInstance
);
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "PerfDeleteInstance", CharSet = CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint PerfDeleteInstance(
[In] SafePerfProviderHandle hProvider,
[In] PerfCounterSetInstanceStruct * InstanceBlock
);
[DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "PerfSetCounterRefValue", CharSet = CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint PerfSetCounterRefValue(
[In] SafePerfProviderHandle hProvider,
[In] PerfCounterSetInstanceStruct * pInstance,
[In] uint CounterId,
[In] void * lpAddr
);
//
// EventLog
//
[Flags]
internal enum EvtQueryFlags {
EvtQueryChannelPath = 0x1,
EvtQueryFilePath = 0x2,
EvtQueryForwardDirection = 0x100,
EvtQueryReverseDirection = 0x200,
EvtQueryTolerateQueryErrors = 0x1000
}
[Flags]
internal enum EvtSubscribeFlags {
EvtSubscribeToFutureEvents = 1,
EvtSubscribeStartAtOldestRecord = 2,
EvtSubscribeStartAfterBookmark = 3,
EvtSubscribeTolerateQueryErrors = 0x1000,
EvtSubscribeStrict = 0x10000
}
/// <summary>
/// Evt Variant types
/// </summary>
internal enum EvtVariantType {
EvtVarTypeNull = 0,
EvtVarTypeString = 1,
EvtVarTypeAnsiString = 2,
EvtVarTypeSByte = 3,
EvtVarTypeByte = 4,
EvtVarTypeInt16 = 5,
EvtVarTypeUInt16 = 6,
EvtVarTypeInt32 = 7,
EvtVarTypeUInt32 = 8,
EvtVarTypeInt64 = 9,
EvtVarTypeUInt64 = 10,
EvtVarTypeSingle = 11,
EvtVarTypeDouble = 12,
EvtVarTypeBoolean = 13,
EvtVarTypeBinary = 14,
EvtVarTypeGuid = 15,
EvtVarTypeSizeT = 16,
EvtVarTypeFileTime = 17,
EvtVarTypeSysTime = 18,
EvtVarTypeSid = 19,
EvtVarTypeHexInt32 = 20,
EvtVarTypeHexInt64 = 21,
// these types used internally
EvtVarTypeEvtHandle = 32,
EvtVarTypeEvtXml = 35,
//Array = 128
EvtVarTypeStringArray = 129,
EvtVarTypeUInt32Array = 136
}
internal enum EvtMasks {
EVT_VARIANT_TYPE_MASK = 0x7f,
EVT_VARIANT_TYPE_ARRAY = 128
}
[StructLayout(LayoutKind.Sequential)]
internal struct SystemTime {
[MarshalAs(UnmanagedType.U2)]
public short Year;
[MarshalAs(UnmanagedType.U2)]
public short Month;
[MarshalAs(UnmanagedType.U2)]
public short DayOfWeek;
[MarshalAs(UnmanagedType.U2)]
public short Day;
[MarshalAs(UnmanagedType.U2)]
public short Hour;
[MarshalAs(UnmanagedType.U2)]
public short Minute;
[MarshalAs(UnmanagedType.U2)]
public short Second;
[MarshalAs(UnmanagedType.U2)]
public short Milliseconds;
}
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)]
#pragma warning disable 618 // Ssytem.Core still uses SecurityRuleSet.Level1
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
internal struct EvtVariant {
[FieldOffset(0)]
public UInt32 UInteger;
[FieldOffset(0)]
public Int32 Integer;
[FieldOffset(0)]
public byte UInt8;
[FieldOffset(0)]
public short Short;
[FieldOffset(0)]
public ushort UShort;
[FieldOffset(0)]
public UInt32 Bool;
[FieldOffset(0)]
public Byte ByteVal;
[FieldOffset(0)]
public byte SByte;
[FieldOffset(0)]
public UInt64 ULong;
[FieldOffset(0)]
public Int64 Long;
[FieldOffset(0)]
public Single Single;
[FieldOffset(0)]
public Double Double;
[FieldOffset(0)]
public IntPtr StringVal;
[FieldOffset(0)]
public IntPtr AnsiString;
[FieldOffset(0)]
public IntPtr SidVal;
[FieldOffset(0)]
public IntPtr Binary;
[FieldOffset(0)]
public IntPtr Reference;
[FieldOffset(0)]
public IntPtr Handle;
[FieldOffset(0)]
public IntPtr GuidReference;
[FieldOffset(0)]
public UInt64 FileTime;
[FieldOffset(0)]
public IntPtr SystemTime;
[FieldOffset(0)]
public IntPtr SizeT;
[FieldOffset(8)]
public UInt32 Count; // number of elements (not length) in bytes.
[FieldOffset(12)]
public UInt32 Type;
}
internal enum EvtEventPropertyId {
EvtEventQueryIDs = 0,
EvtEventPath = 1
}
/// <summary>
/// The query flags to get information about query
/// </summary>
internal enum EvtQueryPropertyId {
EvtQueryNames = 0, //String; //Variant will be array of EvtVarTypeString
EvtQueryStatuses = 1 //UInt32; //Variant will be Array of EvtVarTypeUInt32
}
/// <summary>
/// Publisher Metadata properties
/// </summary>
internal enum EvtPublisherMetadataPropertyId {
EvtPublisherMetadataPublisherGuid = 0, // EvtVarTypeGuid
EvtPublisherMetadataResourceFilePath = 1, // EvtVarTypeString
EvtPublisherMetadataParameterFilePath = 2, // EvtVarTypeString
EvtPublisherMetadataMessageFilePath = 3, // EvtVarTypeString
EvtPublisherMetadataHelpLink = 4, // EvtVarTypeString
EvtPublisherMetadataPublisherMessageID = 5, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferences = 6, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataChannelReferencePath = 7, // EvtVarTypeString
EvtPublisherMetadataChannelReferenceIndex = 8, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferenceID = 9, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferenceFlags = 10, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferenceMessageID = 11, // EvtVarTypeUInt32
EvtPublisherMetadataLevels = 12, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataLevelName = 13, // EvtVarTypeString
EvtPublisherMetadataLevelValue = 14, // EvtVarTypeUInt32
EvtPublisherMetadataLevelMessageID = 15, // EvtVarTypeUInt32
EvtPublisherMetadataTasks = 16, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataTaskName = 17, // EvtVarTypeString
EvtPublisherMetadataTaskEventGuid = 18, // EvtVarTypeGuid
EvtPublisherMetadataTaskValue = 19, // EvtVarTypeUInt32
EvtPublisherMetadataTaskMessageID = 20, // EvtVarTypeUInt32
EvtPublisherMetadataOpcodes = 21, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataOpcodeName = 22, // EvtVarTypeString
EvtPublisherMetadataOpcodeValue = 23, // EvtVarTypeUInt32
EvtPublisherMetadataOpcodeMessageID = 24, // EvtVarTypeUInt32
EvtPublisherMetadataKeywords = 25, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataKeywordName = 26, // EvtVarTypeString
EvtPublisherMetadataKeywordValue = 27, // EvtVarTypeUInt64
EvtPublisherMetadataKeywordMessageID = 28//, // EvtVarTypeUInt32
//EvtPublisherMetadataPropertyIdEND
}
internal enum EvtChannelReferenceFlags {
EvtChannelReferenceImported = 1
}
internal enum EvtEventMetadataPropertyId {
EventMetadataEventID, // EvtVarTypeUInt32
EventMetadataEventVersion, // EvtVarTypeUInt32
EventMetadataEventChannel, // EvtVarTypeUInt32
EventMetadataEventLevel, // EvtVarTypeUInt32
EventMetadataEventOpcode, // EvtVarTypeUInt32
EventMetadataEventTask, // EvtVarTypeUInt32
EventMetadataEventKeyword, // EvtVarTypeUInt64
EventMetadataEventMessageID,// EvtVarTypeUInt32
EventMetadataEventTemplate // EvtVarTypeString
//EvtEventMetadataPropertyIdEND
}
//CHANNEL CONFIGURATION
internal enum EvtChannelConfigPropertyId {
EvtChannelConfigEnabled = 0, // EvtVarTypeBoolean
EvtChannelConfigIsolation, // EvtVarTypeUInt32, EVT_CHANNEL_ISOLATION_TYPE
EvtChannelConfigType, // EvtVarTypeUInt32, EVT_CHANNEL_TYPE
EvtChannelConfigOwningPublisher, // EvtVarTypeString
EvtChannelConfigClassicEventlog, // EvtVarTypeBoolean
EvtChannelConfigAccess, // EvtVarTypeString
EvtChannelLoggingConfigRetention, // EvtVarTypeBoolean
EvtChannelLoggingConfigAutoBackup, // EvtVarTypeBoolean
EvtChannelLoggingConfigMaxSize, // EvtVarTypeUInt64
EvtChannelLoggingConfigLogFilePath, // EvtVarTypeString
EvtChannelPublishingConfigLevel, // EvtVarTypeUInt32
EvtChannelPublishingConfigKeywords, // EvtVarTypeUInt64
EvtChannelPublishingConfigControlGuid, // EvtVarTypeGuid
EvtChannelPublishingConfigBufferSize, // EvtVarTypeUInt32
EvtChannelPublishingConfigMinBuffers, // EvtVarTypeUInt32
EvtChannelPublishingConfigMaxBuffers, // EvtVarTypeUInt32
EvtChannelPublishingConfigLatency, // EvtVarTypeUInt32
EvtChannelPublishingConfigClockType, // EvtVarTypeUInt32, EVT_CHANNEL_CLOCK_TYPE
EvtChannelPublishingConfigSidType, // EvtVarTypeUInt32, EVT_CHANNEL_SID_TYPE
EvtChannelPublisherList, // EvtVarTypeString | EVT_VARIANT_TYPE_ARRAY
EvtChannelConfigPropertyIdEND
}
//LOG INFORMATION
internal enum EvtLogPropertyId {
EvtLogCreationTime = 0, // EvtVarTypeFileTime
EvtLogLastAccessTime, // EvtVarTypeFileTime
EvtLogLastWriteTime, // EvtVarTypeFileTime
EvtLogFileSize, // EvtVarTypeUInt64
EvtLogAttributes, // EvtVarTypeUInt32
EvtLogNumberOfLogRecords, // EvtVarTypeUInt64
EvtLogOldestRecordNumber, // EvtVarTypeUInt64
EvtLogFull, // EvtVarTypeBoolean
}
internal enum EvtExportLogFlags {
EvtExportLogChannelPath = 1,
EvtExportLogFilePath = 2,
EvtExportLogTolerateQueryErrors = 0x1000
}
//RENDERING
internal enum EvtRenderContextFlags {
EvtRenderContextValues = 0, // Render specific properties
EvtRenderContextSystem = 1, // Render all system properties (System)
EvtRenderContextUser = 2 // Render all user properties (User/EventData)
}
internal enum EvtRenderFlags {
EvtRenderEventValues = 0, // Variants
EvtRenderEventXml = 1, // XML
EvtRenderBookmark = 2 // Bookmark
}
internal enum EvtFormatMessageFlags {
EvtFormatMessageEvent = 1,
EvtFormatMessageLevel = 2,
EvtFormatMessageTask = 3,
EvtFormatMessageOpcode = 4,
EvtFormatMessageKeyword = 5,
EvtFormatMessageChannel = 6,
EvtFormatMessageProvider = 7,
EvtFormatMessageId = 8,
EvtFormatMessageXml = 9
}
internal enum EvtSystemPropertyId {
EvtSystemProviderName = 0, // EvtVarTypeString
EvtSystemProviderGuid, // EvtVarTypeGuid
EvtSystemEventID, // EvtVarTypeUInt16
EvtSystemQualifiers, // EvtVarTypeUInt16
EvtSystemLevel, // EvtVarTypeUInt8
EvtSystemTask, // EvtVarTypeUInt16
EvtSystemOpcode, // EvtVarTypeUInt8
EvtSystemKeywords, // EvtVarTypeHexInt64
EvtSystemTimeCreated, // EvtVarTypeFileTime
EvtSystemEventRecordId, // EvtVarTypeUInt64
EvtSystemActivityID, // EvtVarTypeGuid
EvtSystemRelatedActivityID, // EvtVarTypeGuid
EvtSystemProcessID, // EvtVarTypeUInt32
EvtSystemThreadID, // EvtVarTypeUInt32
EvtSystemChannel, // EvtVarTypeString
EvtSystemComputer, // EvtVarTypeString
EvtSystemUserID, // EvtVarTypeSid
EvtSystemVersion, // EvtVarTypeUInt8
EvtSystemPropertyIdEND
}
//SESSION
internal enum EvtLoginClass {
EvtRpcLogin = 1
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct EvtRpcLogin {
[MarshalAs(UnmanagedType.LPWStr)]
public string Server;
[MarshalAs(UnmanagedType.LPWStr)]
public string User;
[MarshalAs(UnmanagedType.LPWStr)]
public string Domain;
[SecurityCritical]
public CoTaskMemUnicodeSafeHandle Password;
public int Flags;
}
//SEEK
[Flags]
internal enum EvtSeekFlags {
EvtSeekRelativeToFirst = 1,
EvtSeekRelativeToLast = 2,
EvtSeekRelativeToCurrent = 3,
EvtSeekRelativeToBookmark = 4,
EvtSeekOriginMask = 7,
EvtSeekStrict = 0x10000
}
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtQuery(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]string path,
[MarshalAs(UnmanagedType.LPWStr)]string query,
int flags);
//SEEK
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtSeek(
EventLogHandle resultSet,
long position,
EventLogHandle bookmark,
int timeout,
[MarshalAs(UnmanagedType.I4)]EvtSeekFlags flags
);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtSubscribe(
EventLogHandle session,
SafeWaitHandle signalEvent,
[MarshalAs(UnmanagedType.LPWStr)]string path,
[MarshalAs(UnmanagedType.LPWStr)]string query,
EventLogHandle bookmark,
IntPtr context,
IntPtr callback,
int flags);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtNext(
EventLogHandle queryHandle,
int eventSize,
[MarshalAs(UnmanagedType.LPArray)] IntPtr[] events,
int timeout,
int flags,
ref int returned);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtCancel(EventLogHandle handle);
[DllImport(WEVTAPI)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtClose(IntPtr handle);
/*
[DllImport(WEVTAPI, EntryPoint = "EvtClose", SetLastError = true)]
public static extern bool EvtClose(
IntPtr eventHandle
);
*/
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetEventInfo(
EventLogHandle eventHandle,
//int propertyId
[MarshalAs(UnmanagedType.I4)]EvtEventPropertyId propertyId,
int bufferSize,
IntPtr bufferPtr,
out int bufferUsed
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetQueryInfo(
EventLogHandle queryHandle,
[MarshalAs(UnmanagedType.I4)]EvtQueryPropertyId propertyId,
int bufferSize,
IntPtr buffer,
ref int bufferRequired
);
//PUBLISHER METADATA
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenPublisherMetadata(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string publisherId,
[MarshalAs(UnmanagedType.LPWStr)] string logFilePath,
int locale,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetPublisherMetadataProperty(
EventLogHandle publisherMetadataHandle,
[MarshalAs(UnmanagedType.I4)] EvtPublisherMetadataPropertyId propertyId,
int flags,
int publisherMetadataPropertyBufferSize,
IntPtr publisherMetadataPropertyBuffer,
out int publisherMetadataPropertyBufferUsed
);
//NEW
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetObjectArraySize(
EventLogHandle objectArray,
out int objectArraySize
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetObjectArrayProperty(
EventLogHandle objectArray,
int propertyId,
int arrayIndex,
int flags,
int propertyValueBufferSize,
IntPtr propertyValueBuffer,
out int propertyValueBufferUsed
);
//NEW 2
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenEventMetadataEnum(
EventLogHandle publisherMetadata,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
//public static extern IntPtr EvtNextEventMetadata(
internal static extern EventLogHandle EvtNextEventMetadata(
EventLogHandle eventMetadataEnum,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetEventMetadataProperty(
EventLogHandle eventMetadata,
[MarshalAs(UnmanagedType.I4)] EvtEventMetadataPropertyId propertyId,
int flags,
int eventMetadataPropertyBufferSize,
IntPtr eventMetadataPropertyBuffer,
out int eventMetadataPropertyBufferUsed
);
//Channel Configuration Native Api
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenChannelEnum(
EventLogHandle session,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtNextChannelPath(
EventLogHandle channelEnum,
int channelPathBufferSize,
//StringBuilder channelPathBuffer,
[Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder channelPathBuffer,
out int channelPathBufferUsed
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenPublisherEnum(
EventLogHandle session,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtNextPublisherId(
EventLogHandle publisherEnum,
int publisherIdBufferSize,
[Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder publisherIdBuffer,
out int publisherIdBufferUsed
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenChannelConfig(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]String channelPath,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtSaveChannelConfig(
EventLogHandle channelConfig,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtSetChannelConfigProperty(
EventLogHandle channelConfig,
[MarshalAs(UnmanagedType.I4)]EvtChannelConfigPropertyId propertyId,
int flags,
ref EvtVariant propertyValue
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetChannelConfigProperty(
EventLogHandle channelConfig,
[MarshalAs(UnmanagedType.I4)]EvtChannelConfigPropertyId propertyId,
int flags,
int propertyValueBufferSize,
IntPtr propertyValueBuffer,
out int propertyValueBufferUsed
);
//Log Information Native Api
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string path,
[MarshalAs(UnmanagedType.I4)]PathType flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetLogInfo(
EventLogHandle log,
[MarshalAs(UnmanagedType.I4)]EvtLogPropertyId propertyId,
int propertyValueBufferSize,
IntPtr propertyValueBuffer,
out int propertyValueBufferUsed
);
//LOG MANIPULATION
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtExportLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]string channelPath,
[MarshalAs(UnmanagedType.LPWStr)]string query,
[MarshalAs(UnmanagedType.LPWStr)]string targetFilePath,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtArchiveExportedLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]string logFilePath,
int locale,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtClearLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]string channelPath,
[MarshalAs(UnmanagedType.LPWStr)]string targetFilePath,
int flags
);
//RENDERING
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtCreateRenderContext(
Int32 valuePathsCount,
[MarshalAs(UnmanagedType.LPArray,ArraySubType = UnmanagedType.LPWStr)]
String[] valuePaths,
[MarshalAs(UnmanagedType.I4)]EvtRenderContextFlags flags
);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtRender(
EventLogHandle context,
EventLogHandle eventHandle,
EvtRenderFlags flags,
int buffSize,
[Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder buffer,
out int buffUsed,
out int propCount
);
[DllImport(WEVTAPI, EntryPoint = "EvtRender", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtRender(
EventLogHandle context,
EventLogHandle eventHandle,
EvtRenderFlags flags,
int buffSize,
IntPtr buffer,
out int buffUsed,
out int propCount
);
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)]
internal struct EvtStringVariant {
[MarshalAs(UnmanagedType.LPWStr),FieldOffset(0)]
public string StringVal;
[FieldOffset(8)]
public UInt32 Count;
[FieldOffset(12)]
public UInt32 Type;
};
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtFormatMessage(
EventLogHandle publisherMetadataHandle,
EventLogHandle eventHandle,
uint messageId,
int valueCount,
EvtStringVariant [] values,
[MarshalAs(UnmanagedType.I4)]EvtFormatMessageFlags flags,
int bufferSize,
[Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder buffer,
out int bufferUsed
);
[DllImport(WEVTAPI, EntryPoint = "EvtFormatMessage", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtFormatMessageBuffer(
EventLogHandle publisherMetadataHandle,
EventLogHandle eventHandle,
uint messageId,
int valueCount,
IntPtr values,
[MarshalAs(UnmanagedType.I4)]EvtFormatMessageFlags flags,
int bufferSize,
IntPtr buffer,
out int bufferUsed
);
//SESSION
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenSession(
[MarshalAs(UnmanagedType.I4)]EvtLoginClass loginClass,
ref EvtRpcLogin login,
int timeout,
int flags
);
//BOOKMARK
[DllImport(WEVTAPI, EntryPoint = "EvtCreateBookmark", CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtCreateBookmark(
[MarshalAs(UnmanagedType.LPWStr)] string bookmarkXml
);
[DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtUpdateBookmark(
EventLogHandle bookmark,
EventLogHandle eventHandle
);
//
// EventLog
//
//
// Memory Mapped File
//
[StructLayout(LayoutKind.Sequential)]
#pragma warning disable 618 // Ssytem.Core still uses SecurityRuleSet.Level1
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
internal unsafe struct MEMORY_BASIC_INFORMATION {
internal void* BaseAddress;
internal void* AllocationBase;
internal uint AllocationProtect;
internal UIntPtr RegionSize;
internal uint State;
internal uint Protect;
internal uint Type;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SYSTEM_INFO {
internal int dwOemId; // This is a union of a DWORD and a struct containing 2 WORDs.
internal int dwPageSize;
internal IntPtr lpMinimumApplicationAddress;
internal IntPtr lpMaximumApplicationAddress;
internal IntPtr dwActiveProcessorMask;
internal int dwNumberOfProcessors;
internal int dwProcessorType;
internal int dwAllocationGranularity;
internal short wProcessorLevel;
internal short wProcessorRevision;
}
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
internal static extern void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
[DllImport(KERNEL32, ExactSpelling = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
internal static extern int GetFileSize(
SafeMemoryMappedFileHandle hFile,
out int highSize
);
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
unsafe internal static extern IntPtr VirtualQuery(
SafeMemoryMappedViewHandle address,
ref MEMORY_BASIC_INFORMATION buffer,
IntPtr sizeOfBuffer
);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
[SecurityCritical]
internal static extern SafeMemoryMappedFileHandle CreateFileMapping(
SafeFileHandle hFile,
SECURITY_ATTRIBUTES lpAttributes,
int fProtect,
int dwMaximumSizeHigh,
int dwMaximumSizeLow,
String lpName
);
[DllImport(KERNEL32, ExactSpelling = true, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
unsafe internal static extern bool FlushViewOfFile(
byte* lpBaseAddress,
IntPtr dwNumberOfBytesToFlush
);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
[SecurityCritical]
internal static extern SafeMemoryMappedFileHandle OpenFileMapping(
int dwDesiredAccess,
[MarshalAs(UnmanagedType.Bool)]
bool bInheritHandle,
string lpName
);
[DllImport(KERNEL32, SetLastError = true, ExactSpelling = true)]
[SecurityCritical]
internal static extern SafeMemoryMappedViewHandle MapViewOfFile(
SafeMemoryMappedFileHandle handle,
int dwDesiredAccess,
uint dwFileOffsetHigh,
uint dwFileOffsetLow,
UIntPtr dwNumberOfBytesToMap
);
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
unsafe internal static extern IntPtr VirtualAlloc(
SafeMemoryMappedViewHandle address,
UIntPtr numBytes,
int commitOrReserve,
int pageProtectionMode
);
[SecurityCritical]
internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer)
{
lpBuffer.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
return GlobalMemoryStatusExNative(ref lpBuffer);
}
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, EntryPoint = "GlobalMemoryStatusEx")]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GlobalMemoryStatusExNative([In, Out] ref MEMORYSTATUSEX lpBuffer);
[DllImport(KERNEL32, SetLastError = true)]
[SecurityCritical]
internal static unsafe extern bool CancelIoEx(SafeHandle handle, NativeOverlapped* lpOverlapped);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct MEMORYSTATUSEX {
internal uint dwLength;
internal uint dwMemoryLoad;
internal ulong ullTotalPhys;
internal ulong ullAvailPhys;
internal ulong ullTotalPageFile;
internal ulong ullAvailPageFile;
internal ulong ullTotalVirtual;
internal ulong ullAvailVirtual;
internal ulong ullAvailExtendedVirtual;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="CustomerUserAccessServiceClient"/> instances.</summary>
public sealed partial class CustomerUserAccessServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CustomerUserAccessServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CustomerUserAccessServiceSettings"/>.</returns>
public static CustomerUserAccessServiceSettings GetDefault() => new CustomerUserAccessServiceSettings();
/// <summary>
/// Constructs a new <see cref="CustomerUserAccessServiceSettings"/> object with default settings.
/// </summary>
public CustomerUserAccessServiceSettings()
{
}
private CustomerUserAccessServiceSettings(CustomerUserAccessServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetCustomerUserAccessSettings = existing.GetCustomerUserAccessSettings;
MutateCustomerUserAccessSettings = existing.MutateCustomerUserAccessSettings;
OnCopy(existing);
}
partial void OnCopy(CustomerUserAccessServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerUserAccessServiceClient.GetCustomerUserAccess</c> and
/// <c>CustomerUserAccessServiceClient.GetCustomerUserAccessAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetCustomerUserAccessSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerUserAccessServiceClient.MutateCustomerUserAccess</c> and
/// <c>CustomerUserAccessServiceClient.MutateCustomerUserAccessAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateCustomerUserAccessSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CustomerUserAccessServiceSettings"/> object.</returns>
public CustomerUserAccessServiceSettings Clone() => new CustomerUserAccessServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CustomerUserAccessServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class CustomerUserAccessServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerUserAccessServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CustomerUserAccessServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CustomerUserAccessServiceClientBuilder()
{
UseJwtAccessWithScopes = CustomerUserAccessServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CustomerUserAccessServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerUserAccessServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CustomerUserAccessServiceClient Build()
{
CustomerUserAccessServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CustomerUserAccessServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CustomerUserAccessServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CustomerUserAccessServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CustomerUserAccessServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CustomerUserAccessServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CustomerUserAccessServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CustomerUserAccessServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CustomerUserAccessServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerUserAccessServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CustomerUserAccessService client wrapper, for convenient use.</summary>
/// <remarks>
/// This service manages the permissions of a user on a given customer.
/// </remarks>
public abstract partial class CustomerUserAccessServiceClient
{
/// <summary>
/// The default endpoint for the CustomerUserAccessService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CustomerUserAccessService scopes.</summary>
/// <remarks>
/// The default CustomerUserAccessService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CustomerUserAccessServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CustomerUserAccessServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CustomerUserAccessServiceClient"/>.</returns>
public static stt::Task<CustomerUserAccessServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CustomerUserAccessServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CustomerUserAccessServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CustomerUserAccessServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CustomerUserAccessServiceClient"/>.</returns>
public static CustomerUserAccessServiceClient Create() => new CustomerUserAccessServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CustomerUserAccessServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CustomerUserAccessServiceSettings"/>.</param>
/// <returns>The created <see cref="CustomerUserAccessServiceClient"/>.</returns>
internal static CustomerUserAccessServiceClient Create(grpccore::CallInvoker callInvoker, CustomerUserAccessServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CustomerUserAccessService.CustomerUserAccessServiceClient grpcClient = new CustomerUserAccessService.CustomerUserAccessServiceClient(callInvoker);
return new CustomerUserAccessServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CustomerUserAccessService client</summary>
public virtual CustomerUserAccessService.CustomerUserAccessServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerUserAccess GetCustomerUserAccess(GetCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerUserAccess> GetCustomerUserAccessAsync(GetCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerUserAccess> GetCustomerUserAccessAsync(GetCustomerUserAccessRequest request, st::CancellationToken cancellationToken) =>
GetCustomerUserAccessAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the customer user access.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerUserAccess GetCustomerUserAccess(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerUserAccess(new GetCustomerUserAccessRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the customer user access.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerUserAccess> GetCustomerUserAccessAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerUserAccessAsync(new GetCustomerUserAccessRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the customer user access.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerUserAccess> GetCustomerUserAccessAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetCustomerUserAccessAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the customer user access.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerUserAccess GetCustomerUserAccess(gagvr::CustomerUserAccessName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerUserAccess(new GetCustomerUserAccessRequest
{
ResourceNameAsCustomerUserAccessName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the customer user access.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerUserAccess> GetCustomerUserAccessAsync(gagvr::CustomerUserAccessName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerUserAccessAsync(new GetCustomerUserAccessRequest
{
ResourceNameAsCustomerUserAccessName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the customer user access.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerUserAccess> GetCustomerUserAccessAsync(gagvr::CustomerUserAccessName resourceName, st::CancellationToken cancellationToken) =>
GetCustomerUserAccessAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerUserAccessResponse MutateCustomerUserAccess(MutateCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerUserAccessResponse> MutateCustomerUserAccessAsync(MutateCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerUserAccessResponse> MutateCustomerUserAccessAsync(MutateCustomerUserAccessRequest request, st::CancellationToken cancellationToken) =>
MutateCustomerUserAccessAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer being modified.
/// </param>
/// <param name="operation">
/// Required. The operation to perform on the customer
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerUserAccessResponse MutateCustomerUserAccess(string customerId, CustomerUserAccessOperation operation, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerUserAccess(new MutateCustomerUserAccessRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)),
}, callSettings);
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer being modified.
/// </param>
/// <param name="operation">
/// Required. The operation to perform on the customer
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerUserAccessResponse> MutateCustomerUserAccessAsync(string customerId, CustomerUserAccessOperation operation, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerUserAccessAsync(new MutateCustomerUserAccessRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)),
}, callSettings);
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer being modified.
/// </param>
/// <param name="operation">
/// Required. The operation to perform on the customer
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerUserAccessResponse> MutateCustomerUserAccessAsync(string customerId, CustomerUserAccessOperation operation, st::CancellationToken cancellationToken) =>
MutateCustomerUserAccessAsync(customerId, operation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CustomerUserAccessService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// This service manages the permissions of a user on a given customer.
/// </remarks>
public sealed partial class CustomerUserAccessServiceClientImpl : CustomerUserAccessServiceClient
{
private readonly gaxgrpc::ApiCall<GetCustomerUserAccessRequest, gagvr::CustomerUserAccess> _callGetCustomerUserAccess;
private readonly gaxgrpc::ApiCall<MutateCustomerUserAccessRequest, MutateCustomerUserAccessResponse> _callMutateCustomerUserAccess;
/// <summary>
/// Constructs a client wrapper for the CustomerUserAccessService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="CustomerUserAccessServiceSettings"/> used within this client.
/// </param>
public CustomerUserAccessServiceClientImpl(CustomerUserAccessService.CustomerUserAccessServiceClient grpcClient, CustomerUserAccessServiceSettings settings)
{
GrpcClient = grpcClient;
CustomerUserAccessServiceSettings effectiveSettings = settings ?? CustomerUserAccessServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetCustomerUserAccess = clientHelper.BuildApiCall<GetCustomerUserAccessRequest, gagvr::CustomerUserAccess>(grpcClient.GetCustomerUserAccessAsync, grpcClient.GetCustomerUserAccess, effectiveSettings.GetCustomerUserAccessSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetCustomerUserAccess);
Modify_GetCustomerUserAccessApiCall(ref _callGetCustomerUserAccess);
_callMutateCustomerUserAccess = clientHelper.BuildApiCall<MutateCustomerUserAccessRequest, MutateCustomerUserAccessResponse>(grpcClient.MutateCustomerUserAccessAsync, grpcClient.MutateCustomerUserAccess, effectiveSettings.MutateCustomerUserAccessSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCustomerUserAccess);
Modify_MutateCustomerUserAccessApiCall(ref _callMutateCustomerUserAccess);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetCustomerUserAccessApiCall(ref gaxgrpc::ApiCall<GetCustomerUserAccessRequest, gagvr::CustomerUserAccess> call);
partial void Modify_MutateCustomerUserAccessApiCall(ref gaxgrpc::ApiCall<MutateCustomerUserAccessRequest, MutateCustomerUserAccessResponse> call);
partial void OnConstruction(CustomerUserAccessService.CustomerUserAccessServiceClient grpcClient, CustomerUserAccessServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CustomerUserAccessService client</summary>
public override CustomerUserAccessService.CustomerUserAccessServiceClient GrpcClient { get; }
partial void Modify_GetCustomerUserAccessRequest(ref GetCustomerUserAccessRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateCustomerUserAccessRequest(ref MutateCustomerUserAccessRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::CustomerUserAccess GetCustomerUserAccess(GetCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerUserAccessRequest(ref request, ref callSettings);
return _callGetCustomerUserAccess.Sync(request, callSettings);
}
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::CustomerUserAccess> GetCustomerUserAccessAsync(GetCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerUserAccessRequest(ref request, ref callSettings);
return _callGetCustomerUserAccess.Async(request, callSettings);
}
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateCustomerUserAccessResponse MutateCustomerUserAccess(MutateCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerUserAccessRequest(ref request, ref callSettings);
return _callMutateCustomerUserAccess.Sync(request, callSettings);
}
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateCustomerUserAccessResponse> MutateCustomerUserAccessAsync(MutateCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerUserAccessRequest(ref request, ref callSettings);
return _callMutateCustomerUserAccess.Async(request, callSettings);
}
}
}
| |
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.
Portions copyright 2007 ThoughtWorks, 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.Collections;
using System.Runtime.InteropServices;
using IEWrapper;
using mshtml;
namespace WebDriver
{
[Guid("F9072BAE-29BC-4505-8DB5-2A32BD00AC68")]
[ClassInterface(ClassInterfaceType.None)]
public class WrappedWebElement : WebElement
{
private readonly IeWrapper parent;
private readonly IHTMLElement node;
internal WrappedWebElement(IeWrapper parent, IHTMLDOMNode node)
{
this.parent = parent;
this.node = (IHTMLElement) node;
}
public string Text
{
get { return node.innerText; }
}
public string GetAttribute(string name)
{
string lookFor = (name.ToLower() == "class" ? "className" : name);
object attribute = node.getAttribute(lookFor, 0);
if (attribute == null)
{
return "";
}
Nullable<Boolean> b = attribute as Nullable<Boolean>;
if (b != null)
{
return b.ToString().ToLower();
}
// This is a nasty hack. We don't know what the type is. Look at the "name" and make a guess
if ("System.__ComObject".Equals(attribute.GetType().FullName)) {
switch (lookFor.ToLower())
{
case "style":
return GetStyleValue();
default:
return "";
}
}
return attribute.ToString();
}
private string GetStyleValue()
{
IHTMLStyle style = node.style;
return style == null || style.cssText == null ? "" : style.cssText.ToLower();
}
public void SetAttribute(string name, object value)
{
node.setAttribute(name, value, 0);
}
public bool Toggle()
{
Click();
return Selected;
}
public bool Selected {
get {
if (node is IHTMLOptionElement)
return ((IHTMLOptionElement) node).selected;
if (IsCheckBox())
return NullSafeAttributeEquality("checked", "true");
return false;
}
}
public void SetSelected()
{
if (IsCheckBox())
{
if (!Selected)
Click();
SetAttribute("checked", true);
}
else if (node is IHTMLOptionElement)
((IHTMLOptionElement)node).selected = true;
else
throw new UnsupportedOperationException("Unable to select element. Tag name is: " + node.tagName);
}
public bool Enabled
{
get {
return !NullSafeAttributeEquality("disabled", "true");
}
}
private bool IsCheckBox()
{
return
node.tagName.ToLower().Equals("input") &&
GetAttribute("type").Equals("checkbox");
}
public void Click() {
object refObj = null;
IHTMLDocument4 document = node.document as IHTMLDocument4;
IHTMLElement3 element = (IHTMLElement3) node;
IHTMLEventObj eventObject = document.CreateEventObject(ref refObj);
object eventRef = eventObject;
element.FireEvent("onMouseDown", ref eventRef);
element.FireEvent("onMouseUp", ref eventRef);
node.click();
parent.WaitForLoadToComplete();
}
public void Submit()
{
if (node is IHTMLFormElement)
{
((IHTMLFormElement) node).submit();
}
else if (node is IHTMLInputElement)
{
string type = GetAttribute("type");
if (type != null && ("submit".Equals(type.ToLower()) || "image".Equals(type.ToLower())))
{
Click();
}
else
{
((IHTMLInputElement)node).form.submit();
}
}
else
{
IHTMLFormElement form = FindParentForm();
if (form == null)
throw new NoSuchElementException("Unable to find the containing form");
form.submit();
}
parent.WaitForLoadToComplete();
}
public string Value
{
get { return GetAttribute("value"); }
set
{
if (isTextInputElement(node))
{
Type(value);
}
else
{
throw new UnsupportedOperationException("You may only set the value of elements that are input elements");
}
}
}
private bool isTextInputElement(IHTMLElement element)
{
return element is IHTMLInputElement || element is IHTMLTextAreaElement;
}
private void Type(string value)
{
object refObj = null;
IHTMLDocument4 document = node.document as IHTMLDocument4;
IHTMLElement3 element = (IHTMLElement3) node;
string val = "";
foreach (char c in value)
{
IHTMLEventObj eventObject = document.CreateEventObject(ref refObj);
eventObject.keyCode = c;
object eventRef = eventObject;
val += c;
element.FireEvent("onKeyDown", ref eventRef);
element.FireEvent("onKeyPress", ref eventRef);
node.setAttribute("value", val, 0);
element.FireEvent("onKeyUp", ref eventRef);
}
}
public ArrayList GetChildrenOfType(string tagName)
{
ArrayList children = new ArrayList();
IEnumerator allChildren = ((IHTMLElement2) node).getElementsByTagName(tagName).GetEnumerator();
while (allChildren.MoveNext())
{
IHTMLDOMNode child = (IHTMLDOMNode) allChildren.Current;
children.Add(new WrappedWebElement(parent, child));
}
return children;
}
private bool NullSafeAttributeEquality(string attributeName, string valueWhenTrue) {
string value = GetAttribute(attributeName);
return value != null && valueWhenTrue.Equals(value.ToLower());
}
private IHTMLFormElement FindParentForm() {
IHTMLElement current = node;
while (!(current == null || current is IHTMLFormElement))
{
current = current.parentElement;
}
return (IHTMLFormElement) current;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// This source file is marked up so that it can be built both as part of the BCL and as part of the fx tree
// as well. Since the security annotation process is different between the two trees, SecurityCritical
// attributes appear directly in this file, instead of being marked up by the BCL annotator tool.
//
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.Contracts;
namespace System.Security.Cryptography {
/// <summary>
/// Native interop with CAPI. Native code definitions can be found in wincrypt.h
/// </summary>
internal static class CapiNative {
/// <summary>
/// Class fields for CAPI algorithm identifiers
/// </summary>
internal enum AlgorithmClass
{
Any = (0 << 13), // ALG_CLASS_ANY
Signature = (1 << 13), // ALG_CLASS_SIGNATURE
Hash = (4 << 13), // ALG_CLASS_HASH
KeyExchange = (5 << 13), // ALG_CLASS_KEY_EXCHANGE
}
/// <summary>
/// Type identifier fields for CAPI algorithm identifiers
/// </summary>
internal enum AlgorithmType
{
Any = (0 << 9), // ALG_TYPE_ANY
Rsa = (2 << 9), // ALG_TYPE_RSA
}
/// <summary>
/// Sub identifiers for CAPI algorithm identifiers
/// </summary>
internal enum AlgorithmSubId
{
Any = 0, // ALG_SID_ANY
RsaAny = 0, // ALG_SID_RSA_ANY
Sha1 = 4, // ALG_SID_SHA1
Sha256 = 12, // ALG_SID_SHA_256
Sha384 = 13, // ALG_SID_SHA_384
Sha512 = 14, // ALG_SID_SHA_512
}
/// <summary>
/// CAPI algorithm identifiers
/// </summary>
internal enum AlgorithmID
{
None = 0,
RsaSign = (AlgorithmClass.Signature | AlgorithmType.Rsa | AlgorithmSubId.RsaAny), // CALG_RSA_SIGN
RsaKeyExchange = (AlgorithmClass.KeyExchange | AlgorithmType.Rsa | AlgorithmSubId.RsaAny), // CALG_RSA_KEYX
Sha1 = (AlgorithmClass.Hash | AlgorithmType.Any | AlgorithmSubId.Sha1), // CALG_SHA1
Sha256 = (AlgorithmClass.Hash | AlgorithmType.Any | AlgorithmSubId.Sha256), // CALG_SHA_256
Sha384 = (AlgorithmClass.Hash | AlgorithmType.Any | AlgorithmSubId.Sha384), // CALG_SHA_384
Sha512 = (AlgorithmClass.Hash | AlgorithmType.Any | AlgorithmSubId.Sha512), // CALG_SHA_512
}
/// <summary>
/// Flags for the CryptAcquireContext API
/// </summary>
[Flags]
internal enum CryptAcquireContextFlags {
None = 0x00000000,
NewKeyset = 0x00000008, // CRYPT_NEWKEYSET
DeleteKeyset = 0x00000010, // CRYPT_DELETEKEYSET
MachineKeyset = 0x00000020, // CRYPT_MACHINE_KEYSET
Silent = 0x00000040, // CRYPT_SILENT
VerifyContext = unchecked((int)0xF0000000) // CRYPT_VERIFYCONTEXT
}
/// <summary>
/// Error codes returned by CAPI
/// </summary>
internal enum ErrorCode {
Ok = 0x00000000,
MoreData = 0x000000ea, // ERROR_MORE_DATA
BadHash = unchecked((int)0x80090002), // NTE_BAD_HASH
BadData = unchecked((int)0x80090005), // NTE_BAD_DATA
BadSignature = unchecked((int)0x80090006), // NTE_BAD_SIGNATURE
NoKey = unchecked((int)0x8009000d) // NTE_NO_KEY
}
/// <summary>
/// Properties of CAPI hash objects
/// </summary>
internal enum HashProperty {
None = 0,
HashValue = 0x0002, // HP_HASHVAL
HashSize = 0x0004, // HP_HASHSIZE
}
/// <summary>
/// Flags for the CryptGenKey API
/// </summary>
[Flags]
internal enum KeyGenerationFlags {
None = 0x00000000,
Exportable = 0x00000001, // CRYPT_EXPORTABLE
UserProtected = 0x00000002, // CRYPT_USER_PROTECTED
Archivable = 0x00004000 // CRYPT_ARCHIVABLE
}
/// <summary>
/// Properties that can be read or set on a key
/// </summary>
internal enum KeyProperty {
None = 0,
AlgorithmID = 7, // KP_ALGID
KeyLength = 9 // KP_KEYLEN
}
/// <summary>
/// Key numbers for identifying specific keys within a single container
/// </summary>
internal enum KeySpec {
KeyExchange = 1, // AT_KEYEXCHANGE
Signature = 2 // AT_SIGNATURE
}
/// <summary>
/// Well-known names of crypto service providers
/// </summary>
internal static class ProviderNames {
// MS_ENHANCED_PROV
internal const string MicrosoftEnhanced = "Microsoft Enhanced Cryptographic Provider v1.0";
}
/// <summary>
/// Provider type accessed in a crypto service provider. These provide the set of algorithms
/// available to use for an application.
/// </summary>
internal enum ProviderType {
RsaFull = 1 // PROV_RSA_FULL
}
[System.Security.SecurityCritical]
internal static class UnsafeNativeMethods {
/// <summary>
/// Open a crypto service provider, if a key container is specified KeyContainerPermission
/// should be demanded.
/// </summary>
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptAcquireContext([Out] out SafeCspHandle phProv,
string pszContainer,
string pszProvider,
ProviderType dwProvType,
CryptAcquireContextFlags dwFlags);
/// <summary>
/// Create an object to hash data with
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptCreateHash(SafeCspHandle hProv,
AlgorithmID Algid,
IntPtr hKey, // SafeCspKeyHandle
int dwFlags,
[Out] out SafeCspHashHandle phHash);
/// <summary>
/// Create a new key in the given key container
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptGenKey(SafeCspHandle hProv,
int Algid,
uint dwFlags,
[Out] out SafeCspKeyHandle phKey);
/// <summary>
/// Fill a buffer with randomly generated data
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptGenRandom(SafeCspHandle hProv,
int dwLen,
[In, Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbBuffer);
/// <summary>
/// Fill a buffer with randomly generated data
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern unsafe bool CryptGenRandom(SafeCspHandle hProv,
int dwLen,
byte* pbBuffer);
/// <summary>
/// Read the value of a property from a hash object
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptGetHashParam(SafeCspHashHandle hHash,
HashProperty dwParam,
[In, Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbData,
[In, Out] ref int pdwDataLen,
int dwFlags);
/// <summary>
/// Read the value of a property from a key
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptGetKeyParam(SafeCspKeyHandle hKey,
KeyProperty dwParam,
[In, Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbData,
[In, Out] ref int pdwDataLen,
int dwFlags);
/// <summary>
/// Import a key blob into a CSP
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptImportKey(SafeCspHandle hProv,
[In, MarshalAs(UnmanagedType.LPArray)] byte[] pbData,
int pdwDataLen,
IntPtr hPubKey, // SafeCspKeyHandle
KeyGenerationFlags dwFlags,
[Out] out SafeCspKeyHandle phKey);
/// <summary>
/// Set the value of a property on a hash object
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptSetHashParam(SafeCspHashHandle hHash,
HashProperty dwParam,
[In, MarshalAs(UnmanagedType.LPArray)] byte[] pbData,
int dwFlags);
/// <summary>
/// Verify the a digital signature
/// </summary>
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptVerifySignature(SafeCspHashHandle hHash,
[In, MarshalAs(UnmanagedType.LPArray)] byte[] pbSignature,
int dwSigLen,
SafeCspKeyHandle hPubKey,
string sDescription,
int dwFlags);
}
/// <summary>
/// Acquire a handle to a crypto service provider and optionally a key container
/// </summary>
[SecurityCritical]
internal static SafeCspHandle AcquireCsp(string keyContainer,
string providerName,
ProviderType providerType,
CryptAcquireContextFlags flags) {
Contract.Assert(keyContainer == null, "Key containers are not supported");
// Specifying both verify context (for an ephemeral key) and machine keyset (for a persisted machine key)
// does not make sense. Additionally, Widows is beginning to lock down against uses of MACHINE_KEYSET
// (for instance in the app container), even if verify context is present. Therefore, if we're using
// an ephemeral key, strip out MACHINE_KEYSET from the flags.
if (((flags & CryptAcquireContextFlags.VerifyContext) == CryptAcquireContextFlags.VerifyContext) &&
((flags & CryptAcquireContextFlags.MachineKeyset) == CryptAcquireContextFlags.MachineKeyset)) {
flags &= ~CryptAcquireContextFlags.MachineKeyset;
}
SafeCspHandle cspHandle = null;
if (!UnsafeNativeMethods.CryptAcquireContext(out cspHandle,
keyContainer,
providerName,
providerType,
flags)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return cspHandle;
}
/// <summary>
/// Create a CSP hash object for the specified hash algorithm
/// </summary>
[SecurityCritical]
internal static SafeCspHashHandle CreateHashAlgorithm(SafeCspHandle cspHandle, AlgorithmID algorithm) {
Contract.Assert(cspHandle != null && !cspHandle.IsInvalid, "cspHandle != null && !cspHandle.IsInvalid");
Contract.Assert(((AlgorithmClass)algorithm & AlgorithmClass.Hash) == AlgorithmClass.Hash, "Invalid hash algorithm");
SafeCspHashHandle hashHandle = null;
if (!UnsafeNativeMethods.CryptCreateHash(cspHandle, algorithm, IntPtr.Zero, 0, out hashHandle)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return hashHandle;
}
/// <summary>
/// Fill a buffer with random data generated by the CSP
/// </summary>
[SecurityCritical]
internal static void GenerateRandomBytes(SafeCspHandle cspHandle, byte[] buffer) {
Contract.Assert(cspHandle != null && !cspHandle.IsInvalid, "cspHandle != null && !cspHandle.IsInvalid");
Contract.Assert(buffer != null && buffer.Length > 0, "buffer != null && buffer.Length > 0");
if (!UnsafeNativeMethods.CryptGenRandom(cspHandle, buffer.Length, buffer)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
}
/// <summary>
/// Fill part of a buffer with random data generated by the CSP
/// </summary>
[SecurityCritical]
internal static unsafe void GenerateRandomBytes(SafeCspHandle cspHandle, byte[] buffer, int offset, int count)
{
Contract.Assert(cspHandle != null && !cspHandle.IsInvalid, "cspHandle != null && !cspHandle.IsInvalid");
Contract.Assert(buffer != null && buffer.Length > 0, "buffer != null && buffer.Length > 0");
Contract.Assert(offset >= 0 && count > 0, "offset >= 0 && count > 0");
Contract.Assert(buffer.Length >= offset + count, "buffer.Length >= offset + count");
fixed (byte* pBuffer = &buffer[offset])
{
if (!UnsafeNativeMethods.CryptGenRandom(cspHandle, count, pBuffer))
{
throw new CryptographicException(Marshal.GetLastWin32Error());
}
}
}
/// <summary>
/// Get a DWORD sized property of a hash object
/// </summary>
[SecurityCritical]
internal static int GetHashPropertyInt32(SafeCspHashHandle hashHandle, HashProperty property) {
byte[] rawProperty = GetHashProperty(hashHandle, property);
Contract.Assert(rawProperty.Length == sizeof(int) || rawProperty.Length == 0, "Unexpected property size");
return rawProperty.Length == sizeof(int) ? BitConverter.ToInt32(rawProperty, 0) : 0;
}
/// <summary>
/// Get an arbitrary property of a hash object
/// </summary>
[SecurityCritical]
internal static byte[] GetHashProperty(SafeCspHashHandle hashHandle, HashProperty property) {
Contract.Assert(hashHandle != null && !hashHandle.IsInvalid, "keyHandle != null && !keyHandle.IsInvalid");
int bufferSize = 0;
byte[] buffer = null;
// Figure out how big of a buffer we need to hold the property
if (!UnsafeNativeMethods.CryptGetHashParam(hashHandle, property, buffer, ref bufferSize, 0)) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode != (int)ErrorCode.MoreData) {
throw new CryptographicException(errorCode);
}
}
// Now get the property bytes directly
buffer = new byte[bufferSize];
if (!UnsafeNativeMethods.CryptGetHashParam(hashHandle, property, buffer, ref bufferSize, 0)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return buffer;
}
/// <summary>
/// Get a DWORD sized property of a key stored in a CSP
/// </summary>
[SecurityCritical]
internal static int GetKeyPropertyInt32(SafeCspKeyHandle keyHandle, KeyProperty property) {
byte[] rawProperty = GetKeyProperty(keyHandle, property);
Contract.Assert(rawProperty.Length == sizeof(int) || rawProperty.Length == 0, "Unexpected property size");
return rawProperty.Length == sizeof(int) ? BitConverter.ToInt32(rawProperty, 0) : 0;
}
/// <summary>
/// Get an arbitrary property of a key stored in a CSP
/// </summary>
[SecurityCritical]
internal static byte[] GetKeyProperty(SafeCspKeyHandle keyHandle, KeyProperty property) {
Contract.Assert(keyHandle != null && !keyHandle.IsInvalid, "keyHandle != null && !keyHandle.IsInvalid");
int bufferSize = 0;
byte[] buffer = null;
// Figure out how big of a buffer we need to hold the property
if (!UnsafeNativeMethods.CryptGetKeyParam(keyHandle, property, buffer, ref bufferSize, 0)) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode != (int)ErrorCode.MoreData) {
throw new CryptographicException(errorCode);
}
}
// Now get the property bytes directly
buffer = new byte[bufferSize];
if (!UnsafeNativeMethods.CryptGetKeyParam(keyHandle, property, buffer, ref bufferSize, 0)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return buffer;
}
/// <summary>
/// Set an arbitrary property on a hash object
/// </summary>
[SecurityCritical]
internal static void SetHashProperty(SafeCspHashHandle hashHandle,
HashProperty property,
byte[] value) {
Contract.Assert(hashHandle != null && !hashHandle.IsInvalid, "hashHandle != null && !hashHandle.IsInvalid");
if (!UnsafeNativeMethods.CryptSetHashParam(hashHandle, property, value, 0)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
}
/// <summary>
/// Verify that the digital signature created with the specified hash and asymmetric algorithm
/// is valid for the given hash value.
/// </summary>
[SecurityCritical]
internal static bool VerifySignature(SafeCspHandle cspHandle,
SafeCspKeyHandle keyHandle,
AlgorithmID signatureAlgorithm,
AlgorithmID hashAlgorithm,
byte[] hashValue,
byte[] signature) {
Contract.Assert(cspHandle != null && !cspHandle.IsInvalid, "cspHandle != null && !cspHandle.IsInvalid");
Contract.Assert(keyHandle != null && !keyHandle.IsInvalid, "keyHandle != null && !keyHandle.IsInvalid");
Contract.Assert(((AlgorithmClass)signatureAlgorithm & AlgorithmClass.Signature) == AlgorithmClass.Signature, "Invalid signature algorithm");
Contract.Assert(((AlgorithmClass)hashAlgorithm & AlgorithmClass.Hash) == AlgorithmClass.Hash, "Invalid hash algorithm");
Contract.Assert(hashValue != null, "hashValue != null");
Contract.Assert(signature != null, "signature != null");
// CAPI and the CLR have inverse byte orders for signatures, so we need to reverse before verifying
byte[] signatureValue = new byte[signature.Length];
Array.Copy(signature, signatureValue, signatureValue.Length);
Array.Reverse(signatureValue);
using (SafeCspHashHandle hashHandle = CreateHashAlgorithm(cspHandle, hashAlgorithm)) {
// Make sure the hash value is the correct size and import it into the CSP
if (hashValue.Length != GetHashPropertyInt32(hashHandle, HashProperty.HashSize)) {
throw new CryptographicException((int)ErrorCode.BadHash);
}
SetHashProperty(hashHandle, HashProperty.HashValue, hashValue);
// Do the signature verification. A TRUE result means that the signature was valid. A FALSE
// result either means an invalid signature or some other error, so we need to check the last
// error to see which occurred.
if (UnsafeNativeMethods.CryptVerifySignature(hashHandle,
signatureValue,
signatureValue.Length,
keyHandle,
null,
0)) {
return true;
}
else {
int error = Marshal.GetLastWin32Error();
if (error != (int)ErrorCode.BadSignature) {
throw new CryptographicException(error);
}
return false;
}
}
}
}
/// <summary>
/// SafeHandle representing a native HCRYPTPROV on Windows, or representing all state associated with
/// loading a CSSM CSP on the Mac. The HCRYPTPROV SafeHandle usage is straightforward, however CSSM
/// usage is slightly different.
///
/// For CSSM we hold three pieces of state:
/// * m_initializedCssm - a flag indicating that CSSM_Init() was successfully called
/// * m_cspModuleGuid - the module GUID of the CSP we loaded, if that CSP was successfully loaded
/// * handle - handle resulting from attaching to the CSP
///
/// We need to keep all three pieces of state, since we need to teardown in a specific order. If
/// these pieces of state were in seperate SafeHandles we could not guarantee their order of
/// finalization.
/// </summary>
[SecurityCritical]
internal sealed class SafeCspHandle : SafeHandleZeroOrMinusOneIsInvalid {
private SafeCspHandle() : base(true) {
}
[DllImport("advapi32")]
#if FEATURE_CORECLR || FEATURE_CER
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif // FEATURE_CORECLR || FEATURE_CER
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool CryptReleaseContext(IntPtr hProv, int dwFlags);
/// <summary>
/// Clean up the safe handle's resources.
///
/// On Windows the cleanup is a straightforward release of the HCRYPTPROV handle. However, on
/// the Mac, CSSM requires that we release resources in the following order:
///
/// 1. Detach from the CSP
/// 2. Unload the CSP
/// 3. Terminate CSSM
///
/// Both the unload and terminate operations are ref-counted by CSSM, so it is safe to do these
/// even if other handles are open on the CSP or other CSSM objects are in use.
/// </summary>
[SecurityCritical]
protected override bool ReleaseHandle() {
return CryptReleaseContext(handle, 0);
}
}
/// <summary>
/// SafeHandle representing a native HCRYPTHASH
/// </summary>
[SecurityCritical]
internal sealed class SafeCspHashHandle : SafeHandleZeroOrMinusOneIsInvalid {
private SafeCspHashHandle() : base(true) {
}
[DllImport("advapi32")]
#if FEATURE_CORECLR || FEATURE_CER
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif // FEATURE_CORECLR || FEATURE_CER
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool CryptDestroyHash(IntPtr hKey);
[SecurityCritical]
protected override bool ReleaseHandle() {
return CryptDestroyHash(handle);
}
}
/// <summary>
/// SafeHandle representing a native HCRYPTKEY on Windows.
///
/// On the Mac, we generate our keys by hand, so they are really just CSSM_KEY structures along with
/// the associated data blobs. Because of this, the only resource that needs to be released when the
/// key is freed is the memory associated with the key blob.
///
/// However, in order for a SafeCspKeyHandle to marshal as a CSSM_KEY_PTR, as one would expect, the
/// handle value on the Mac is actually a pointer to the CSSM_KEY. We maintain a seperate m_data
/// pointer which is the buffer holding the actual key data.
///
/// Both of these details add a further invarient that on the Mac a SafeCspKeyHandle may never be an
/// [out] parameter from an API. This is because we always expect that we control the memory buffer
/// that the CSSM_KEY resides in and that we don't have to call CSSM_FreeKey on the data.
///
/// Keeping this in a SafeHandle rather than just marshaling the key structure direclty buys us a
/// level of abstraction, in that if we ever do need to work with keys that require a CSSM_FreeKey
/// call, we can continue to use the same key handle object. It also means that keys are represented
/// by the same type on both Windows and Mac, so that consumers of the CapiNative layer don't have
/// to know the difference between the two.
/// </summary>
[SecurityCritical]
internal sealed class SafeCspKeyHandle : SafeHandleZeroOrMinusOneIsInvalid {
internal SafeCspKeyHandle() : base(true) {
}
[DllImport("advapi32")]
#if FEATURE_CORECLR || FEATURE_CER
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif // FEATURE_CORECLR || FEATURE_CER
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool CryptDestroyKey(IntPtr hKey);
[SecurityCritical]
protected override bool ReleaseHandle() {
return CryptDestroyKey(handle);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementByte7()
{
var test = new VectorGetAndWithElement__GetAndWithElementByte7();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementByte7
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 7, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Byte[] values = new Byte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetByte();
}
Vector64<Byte> value = Vector64.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
Byte result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Byte.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Byte insertedValue = TestLibrary.Generator.GetByte();
try
{
Vector64<Byte> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Byte.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 7, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Byte[] values = new Byte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetByte();
}
Vector64<Byte> value = Vector64.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector64)
.GetMethod(nameof(Vector64.GetElement))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((Byte)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Byte.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Byte insertedValue = TestLibrary.Generator.GetByte();
try
{
object result2 = typeof(Vector64)
.GetMethod(nameof(Vector64.WithElement))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector64<Byte>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Byte.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(7 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(7 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(7 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(7 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(Byte result, Byte[] values, [CallerMemberName] string method = "")
{
if (result != values[7])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector64<Byte.GetElement(7): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector64<Byte> result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "")
{
Byte[] resultElements = new Byte[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(Byte[] result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 7) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[7] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Byte.WithElement(7): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding.WindowsStore;
#if UNITY_WINRT && !UNITY_EDITOR
//using MarkerMetro.Unity.WinLegacy.IO;
//using MarkerMetro.Unity.WinLegacy.Reflection;
#endif
namespace Pathfinding {
[System.Serializable]
/** Stores the navigation graphs for the A* Pathfinding System.
* \ingroup relevant
*
* An instance of this class is assigned to AstarPath.data, from it you can access all graphs loaded through the #graphs variable.\n
* This class also handles a lot of the high level serialization.
*/
public class AstarData {
/** Shortcut to AstarPath.active */
public static AstarPath active {
get {
return AstarPath.active;
}
}
#region Fields
/** Shortcut to the first NavMeshGraph.
* Updated at scanning time
*/
public NavMeshGraph navmesh { get; private set; }
#if !ASTAR_NO_GRID_GRAPH
/** Shortcut to the first GridGraph.
* Updated at scanning time
*/
public GridGraph gridGraph { get; private set; }
/** Shortcut to the first LayerGridGraph.
* Updated at scanning time.
* \astarpro
*/
public LayerGridGraph layerGridGraph { get; private set; }
#endif
#if !ASTAR_NO_POINT_GRAPH
/** Shortcut to the first PointGraph.
* Updated at scanning time
*/
public PointGraph pointGraph { get; private set; }
#endif
/** Shortcut to the first RecastGraph.
* Updated at scanning time.
* \astarpro
*/
public RecastGraph recastGraph { get; private set; }
/** All supported graph types.
* Populated through reflection search
*/
public System.Type[] graphTypes { get; private set; }
#if ASTAR_FAST_NO_EXCEPTIONS || UNITY_WINRT || UNITY_WEBGL
/** Graph types to use when building with Fast But No Exceptions for iPhone.
* If you add any custom graph types, you need to add them to this hard-coded list.
*/
public static readonly System.Type[] DefaultGraphTypes = new System.Type[] {
#if !ASTAR_NO_GRID_GRAPH
typeof(GridGraph),
#endif
#if !ASTAR_NO_POINT_GRAPH
typeof(PointGraph),
#endif
typeof(NavMeshGraph),
typeof(RecastGraph),
typeof(LayerGridGraph)
};
#endif
/** All graphs this instance holds.
* This will be filled only after deserialization has completed.
* May contain null entries if graph have been removed.
*/
[System.NonSerialized]
public NavGraph[] graphs = new NavGraph[0];
//Serialization Settings
/** Serialized data for all graphs and settings.
* Stored as a base64 encoded string because otherwise Unity's Undo system would sometimes corrupt the byte data (because it only stores deltas).
*
* This can be accessed as a byte array from the #data property.
*
* \since 3.6.1
*/
[SerializeField]
string dataString;
/** Data from versions from before 3.6.1.
* Used for handling upgrades
* \since 3.6.1
*/
[SerializeField]
[UnityEngine.Serialization.FormerlySerializedAs("data")]
private byte[] upgradeData;
/** Serialized data for all graphs and settings */
private byte[] data {
get {
// Handle upgrading from earlier versions than 3.6.1
if (upgradeData != null && upgradeData.Length > 0) {
data = upgradeData;
upgradeData = null;
}
return dataString != null ? System.Convert.FromBase64String(dataString) : null;
}
set {
dataString = value != null ? System.Convert.ToBase64String(value) : null;
}
}
/** Serialized data for cached startup.
* If set, on start the graphs will be deserialized from this file.
*/
public TextAsset file_cachedStartup;
/** Serialized data for cached startup.
*
* \deprecated Deprecated since 3.6, AstarData.file_cachedStartup is now used instead
*/
public byte[] data_cachedStartup;
/** Should graph-data be cached.
* Caching the startup means saving the whole graphs - not only the settings - to a file (#file_cachedStartup) which can
* be loaded when the game starts. This is usually much faster than scanning the graphs when the game starts. This is configured from the editor under the "Save & Load" tab.
*
* \see \ref save-load-graphs
*/
[SerializeField]
public bool cacheStartup;
//End Serialization Settings
List<bool> graphStructureLocked = new List<bool>();
#endregion
public byte[] GetData () {
return data;
}
public void SetData (byte[] data) {
this.data = data;
}
/** Loads the graphs from memory, will load cached graphs if any exists */
public void Awake () {
graphs = new NavGraph[0];
if (cacheStartup && file_cachedStartup != null) {
LoadFromCache();
} else {
DeserializeGraphs();
}
}
/** Prevent the graph structure from changing during the time this lock is held.
* This prevents graphs from being added or removed and also prevents graphs from being serialized or deserialized.
* This is used when e.g an async scan is happening to ensure that for example a graph that is being scanned is not destroyed.
*
* Each call to this method *must* be paired with exactly one call to #UnlockGraphStructure.
* The calls may be nested.
*/
internal void LockGraphStructure (bool allowAddingGraphs = false) {
graphStructureLocked.Add(allowAddingGraphs);
}
/** Allows the graph structure to change again.
* \see #LockGraphStructure
*/
internal void UnlockGraphStructure () {
if (graphStructureLocked.Count == 0) throw new System.InvalidOperationException();
graphStructureLocked.RemoveAt(graphStructureLocked.Count - 1);
}
PathProcessor.GraphUpdateLock AssertSafe (bool onlyAddingGraph = false) {
if (graphStructureLocked.Count > 0) {
bool allowAdding = true;
for (int i = 0; i < graphStructureLocked.Count; i++) allowAdding &= graphStructureLocked[i];
if (!(onlyAddingGraph && allowAdding)) throw new System.InvalidOperationException("Graphs cannot be added, removed or serialized while the graph structure is locked. This is the case when a graph is currently being scanned and when executing graph updates and work items.\nHowever as a special case, graphs can be added inside work items.");
}
// Pause the pathfinding threads
var graphLock = active.PausePathfinding();
if (!active.IsInsideWorkItem) {
// Make sure all graph updates and other callbacks are done
// Only do this if this code is not being called from a work item itself as that would cause a recursive wait that could never complete.
// There are some valid cases when this can happen. For example it may be necessary to add a new graph inside a work item.
active.FlushWorkItems();
// Paths that are already calculated and waiting to be returned to the Seeker component need to be
// processed immediately as their results usually depend on graphs that currently exist. If this was
// not done then after destroying a graph one could get a path result with destroyed nodes in it.
active.pathReturnQueue.ReturnPaths(false);
}
return graphLock;
}
/** Updates shortcuts to the first graph of different types.
* Hard coding references to some graph types is not really a good thing imo. I want to keep it dynamic and flexible.
* But these references ease the use of the system, so I decided to keep them.
*/
public void UpdateShortcuts () {
navmesh = (NavMeshGraph)FindGraphOfType(typeof(NavMeshGraph));
#if !ASTAR_NO_GRID_GRAPH
gridGraph = (GridGraph)FindGraphOfType(typeof(GridGraph));
layerGridGraph = (LayerGridGraph)FindGraphOfType(typeof(LayerGridGraph));
#endif
#if !ASTAR_NO_POINT_GRAPH
pointGraph = (PointGraph)FindGraphOfType(typeof(PointGraph));
#endif
recastGraph = (RecastGraph)FindGraphOfType(typeof(RecastGraph));
}
/** Load from data from #file_cachedStartup */
public void LoadFromCache () {
var graphLock = AssertSafe();
if (file_cachedStartup != null) {
var bytes = file_cachedStartup.bytes;
DeserializeGraphs(bytes);
GraphModifier.TriggerEvent(GraphModifier.EventType.PostCacheLoad);
} else {
Debug.LogError("Can't load from cache since the cache is empty");
}
graphLock.Release();
}
#region Serialization
/** Serializes all graphs settings to a byte array.
* \see DeserializeGraphs(byte[])
*/
public byte[] SerializeGraphs () {
return SerializeGraphs(Pathfinding.Serialization.SerializeSettings.Settings);
}
/** Serializes all graphs settings and optionally node data to a byte array.
* \see DeserializeGraphs(byte[])
* \see Pathfinding.Serialization.SerializeSettings
*/
public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings) {
uint checksum;
return SerializeGraphs(settings, out checksum);
}
/** Main serializer function.
* Serializes all graphs to a byte array
* A similar function exists in the AstarPathEditor.cs script to save additional info */
public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings, out uint checksum) {
var graphLock = AssertSafe();
var sr = new Pathfinding.Serialization.AstarSerializer(this, settings);
sr.OpenSerialize();
sr.SerializeGraphs(graphs);
sr.SerializeExtraInfo();
byte[] bytes = sr.CloseSerialize();
checksum = sr.GetChecksum();
#if ASTARDEBUG
Debug.Log("Got a whole bunch of data, "+bytes.Length+" bytes");
#endif
graphLock.Release();
return bytes;
}
/** Deserializes graphs from #data */
public void DeserializeGraphs () {
if (data != null) {
DeserializeGraphs(data);
}
}
/** Destroys all graphs and sets graphs to null */
void ClearGraphs () {
if (graphs == null) return;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] != null) {
((IGraphInternals)graphs[i]).OnDestroy();
graphs[i].active = null;
}
}
graphs = null;
UpdateShortcuts();
}
public void OnDestroy () {
ClearGraphs();
}
/** Deserializes graphs from the specified byte array.
* An error will be logged if deserialization fails.
*/
public void DeserializeGraphs (byte[] bytes) {
var graphLock = AssertSafe();
ClearGraphs();
DeserializeGraphsAdditive(bytes);
graphLock.Release();
}
/** Deserializes graphs from the specified byte array additively.
* An error will be logged if deserialization fails.
* This function will add loaded graphs to the current ones.
*/
public void DeserializeGraphsAdditive (byte[] bytes) {
var graphLock = AssertSafe();
try {
if (bytes != null) {
var sr = new Pathfinding.Serialization.AstarSerializer(this);
if (sr.OpenDeserialize(bytes)) {
DeserializeGraphsPartAdditive(sr);
sr.CloseDeserialize();
} else {
Debug.Log("Invalid data file (cannot read zip).\nThe data is either corrupt or it was saved using a 3.0.x or earlier version of the system");
}
} else {
throw new System.ArgumentNullException("bytes");
}
active.VerifyIntegrity();
} catch (System.Exception e) {
Debug.LogError("Caught exception while deserializing data.\n"+e);
graphs = new NavGraph[0];
}
UpdateShortcuts();
graphLock.Release();
}
/** Helper function for deserializing graphs */
void DeserializeGraphsPartAdditive (Pathfinding.Serialization.AstarSerializer sr) {
if (graphs == null) graphs = new NavGraph[0];
var gr = new List<NavGraph>(graphs);
// Set an offset so that the deserializer will load
// the graphs with the correct graph indexes
sr.SetGraphIndexOffset(gr.Count);
gr.AddRange(sr.DeserializeGraphs());
graphs = gr.ToArray();
sr.DeserializeEditorSettingsCompatibility();
sr.DeserializeExtraInfo();
//Assign correct graph indices.
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] == null) continue;
graphs[i].GetNodes(node => node.GraphIndex = (uint)i);
}
for (int i = 0; i < graphs.Length; i++) {
for (int j = i+1; j < graphs.Length; j++) {
if (graphs[i] != null && graphs[j] != null && graphs[i].guid == graphs[j].guid) {
Debug.LogWarning("Guid Conflict when importing graphs additively. Imported graph will get a new Guid.\nThis message is (relatively) harmless.");
graphs[i].guid = Pathfinding.Util.Guid.NewGuid();
break;
}
}
}
sr.PostDeserialization();
}
#endregion
/** Find all graph types supported in this build.
* Using reflection, the assembly is searched for types which inherit from NavGraph. */
public void FindGraphTypes () {
#if !ASTAR_FAST_NO_EXCEPTIONS && !UNITY_WINRT && !UNITY_WEBGL
var assembly = WindowsStoreCompatibility.GetTypeInfo(typeof(AstarPath)).Assembly;
System.Type[] types = assembly.GetTypes();
var graphList = new List<System.Type>();
foreach (System.Type type in types) {
#if NETFX_CORE && !UNITY_EDITOR
System.Type baseType = type.GetTypeInfo().BaseType;
#else
System.Type baseType = type.BaseType;
#endif
while (baseType != null) {
if (System.Type.Equals(baseType, typeof(NavGraph))) {
graphList.Add(type);
break;
}
#if NETFX_CORE && !UNITY_EDITOR
baseType = baseType.GetTypeInfo().BaseType;
#else
baseType = baseType.BaseType;
#endif
}
}
graphTypes = graphList.ToArray();
#if ASTARDEBUG
Debug.Log("Found "+graphTypes.Length+" graph types");
#endif
#else
graphTypes = DefaultGraphTypes;
#endif
}
#region GraphCreation
/**
* \returns A System.Type which matches the specified \a type string. If no mathing graph type was found, null is returned
*
* \deprecated
*/
[System.Obsolete("If really necessary. Use System.Type.GetType instead.")]
public System.Type GetGraphType (string type) {
for (int i = 0; i < graphTypes.Length; i++) {
if (graphTypes[i].Name == type) {
return graphTypes[i];
}
}
return null;
}
/** Creates a new instance of a graph of type \a type. If no matching graph type was found, an error is logged and null is returned
* \returns The created graph
* \see #CreateGraph(System.Type)
*
* \deprecated
*/
[System.Obsolete("Use CreateGraph(System.Type) instead")]
public NavGraph CreateGraph (string type) {
Debug.Log("Creating Graph of type '"+type+"'");
for (int i = 0; i < graphTypes.Length; i++) {
if (graphTypes[i].Name == type) {
return CreateGraph(graphTypes[i]);
}
}
Debug.LogError("Graph type ("+type+") wasn't found");
return null;
}
/** Creates a new graph instance of type \a type
* \see #CreateGraph(string)
*/
internal NavGraph CreateGraph (System.Type type) {
var graph = System.Activator.CreateInstance(type) as NavGraph;
graph.active = active;
return graph;
}
/** Adds a graph of type \a type to the #graphs array
*
* \deprecated
*/
[System.Obsolete("Use AddGraph(System.Type) instead")]
public NavGraph AddGraph (string type) {
NavGraph graph = null;
for (int i = 0; i < graphTypes.Length; i++) {
if (graphTypes[i].Name == type) {
graph = CreateGraph(graphTypes[i]);
}
}
if (graph == null) {
Debug.LogError("No NavGraph of type '"+type+"' could be found");
return null;
}
AddGraph(graph);
return graph;
}
/** Adds a graph of type \a type to the #graphs array */
public NavGraph AddGraph (System.Type type) {
NavGraph graph = null;
for (int i = 0; i < graphTypes.Length; i++) {
if (System.Type.Equals(graphTypes[i], type)) {
graph = CreateGraph(graphTypes[i]);
}
}
if (graph == null) {
Debug.LogError("No NavGraph of type '"+type+"' could be found, "+graphTypes.Length+" graph types are avaliable");
return null;
}
AddGraph(graph);
return graph;
}
/** Adds the specified graph to the #graphs array */
void AddGraph (NavGraph graph) {
// Make sure to not interfere with pathfinding
var graphLock = AssertSafe(true);
// Try to fill in an empty position
bool foundEmpty = false;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] == null) {
graphs[i] = graph;
graph.graphIndex = (uint)i;
foundEmpty = true;
break;
}
}
if (!foundEmpty) {
if (graphs != null && graphs.Length >= GraphNode.MaxGraphIndex) {
throw new System.Exception("Graph Count Limit Reached. You cannot have more than " + GraphNode.MaxGraphIndex + " graphs.");
}
// Add a new entry to the list
var graphList = new List<NavGraph>(graphs ?? new NavGraph[0]);
graphList.Add(graph);
graphs = graphList.ToArray();
graph.graphIndex = (uint)(graphs.Length-1);
}
UpdateShortcuts();
graph.active = active;
graphLock.Release();
}
/** Removes the specified graph from the #graphs array and Destroys it in a safe manner.
* To avoid changing graph indices for the other graphs, the graph is simply nulled in the array instead
* of actually removing it from the array.
* The empty position will be reused if a new graph is added.
*
* \returns True if the graph was sucessfully removed (i.e it did exist in the #graphs array). False otherwise.
*
* \version Changed in 3.2.5 to call SafeOnDestroy before removing
* and nulling it in the array instead of removing the element completely in the #graphs array.
*/
public bool RemoveGraph (NavGraph graph) {
// Make sure the pathfinding threads are stopped
// If we don't wait until pathfinding that is potentially running on
// this graph right now we could end up with NullReferenceExceptions
var graphLock = AssertSafe();
((IGraphInternals)graph).OnDestroy();
graph.active = null;
int i = System.Array.IndexOf(graphs, graph);
if (i != -1) graphs[i] = null;
UpdateShortcuts();
graphLock.Release();
return i != -1;
}
#endregion
#region GraphUtility
/** Returns the graph which contains the specified node.
* The graph must be in the #graphs array.
*
* \returns Returns the graph which contains the node. Null if the graph wasn't found
*/
public static NavGraph GetGraph (GraphNode node) {
if (node == null) return null;
AstarPath script = AstarPath.active;
if (script == null) return null;
AstarData data = script.data;
if (data == null || data.graphs == null) return null;
uint graphIndex = node.GraphIndex;
if (graphIndex >= data.graphs.Length) {
return null;
}
return data.graphs[(int)graphIndex];
}
/** Returns the first graph which satisfies the predicate. Returns null if no graph was found. */
public NavGraph FindGraph (System.Func<NavGraph, bool> predicate) {
if (graphs != null) {
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] != null && predicate(graphs[i])) {
return graphs[i];
}
}
}
return null;
}
/** Returns the first graph of type \a type found in the #graphs array. Returns null if no graph was found. */
public NavGraph FindGraphOfType (System.Type type) {
return FindGraph(graph => System.Type.Equals(graph.GetType(), type));
}
/** Returns the first graph which inherits from the type \a type. Returns null if no graph was found. */
public NavGraph FindGraphWhichInheritsFrom (System.Type type) {
return FindGraph(graph => WindowsStoreCompatibility.GetTypeInfo(type).IsAssignableFrom(WindowsStoreCompatibility.GetTypeInfo(graph.GetType())));
}
/** Loop through this function to get all graphs of type 'type'
* \code
* foreach (GridGraph graph in AstarPath.data.FindGraphsOfType (typeof(GridGraph))) {
* //Do something with the graph
* }
* \endcode
* \see AstarPath.RegisterSafeNodeUpdate */
public IEnumerable FindGraphsOfType (System.Type type) {
if (graphs == null) yield break;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] != null && System.Type.Equals(graphs[i].GetType(), type)) {
yield return graphs[i];
}
}
}
/** All graphs which implements the UpdateableGraph interface
* \code foreach (IUpdatableGraph graph in AstarPath.data.GetUpdateableGraphs ()) {
* //Do something with the graph
* } \endcode
* \see AstarPath.AddWorkItem
* \see Pathfinding.IUpdatableGraph */
public IEnumerable GetUpdateableGraphs () {
if (graphs == null) yield break;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] is IUpdatableGraph) {
yield return graphs[i];
}
}
}
/** All graphs which implements the UpdateableGraph interface
* \code foreach (IRaycastableGraph graph in AstarPath.data.GetRaycastableGraphs ()) {
* //Do something with the graph
* } \endcode
* \see Pathfinding.IRaycastableGraph
* \deprecated Deprecated because it is not used by the package internally and the use cases are few. Iterate through the #graphs array instead.
*/
[System.Obsolete("Obsolete because it is not used by the package internally and the use cases are few. Iterate through the graphs array instead.")]
public IEnumerable GetRaycastableGraphs () {
if (graphs == null) yield break;
for (int i = 0; i < graphs.Length; i++) {
if (graphs[i] is IRaycastableGraph) {
yield return graphs[i];
}
}
}
/** Gets the index of the NavGraph in the #graphs array */
public int GetGraphIndex (NavGraph graph) {
if (graph == null) throw new System.ArgumentNullException("graph");
var index = -1;
if (graphs != null) {
index = System.Array.IndexOf(graphs, graph);
if (index == -1) Debug.LogError("Graph doesn't exist");
}
return index;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowConcatAllSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System.Linq;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
using Akka.Streams.Dsl.Internal;
using Akka.TestKit;
using Reactive.Streams;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowConcatAllSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public FlowConcatAllSpec(ITestOutputHelper helper) : base(helper)
{
var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 2);
Materializer = ActorMaterializer.Create(Sys, settings);
}
private static readonly TestException TestException = new TestException("test");
[Fact]
public void ConcatAll_must_work_in_the_happy_case()
{
this.AssertAllStagesStopped(() =>
{
var s1 = Source.From(new[] {1, 2});
var s2 = Source.From(new int[] {});
var s3 = Source.From(new[] {3});
var s4 = Source.From(new[] {4, 5, 6});
var s5 = Source.From(new[] {7, 8, 9, 10});
var main = Source.From(new[] {s1, s2, s3, s4, s5});
var subscriber = this.CreateManualSubscriberProbe<int>();
main.ConcatMany(s => s).To(Sink.FromSubscriber(subscriber)).Run(Materializer);
var subscription = subscriber.ExpectSubscription();
subscription.Request(10);
for (var i = 1; i <= 10; i++)
subscriber.ExpectNext(i);
subscription.Request(1);
subscriber.ExpectComplete();
}, Materializer);
}
[Fact]
public void ConcatAll_must_work_together_with_SplitWhen()
{
var subscriber = this.CreateSubscriberProbe<int>();
var source = Source.From(Enumerable.Range(1, 10))
.SplitWhen(x => x%2 == 0)
.PrefixAndTail(0)
.Select(x => x.Item2)
.ConcatSubstream()
.ConcatMany(x => x);
((Source<int, NotUsed>) source).RunWith(Sink.FromSubscriber(subscriber), Materializer);
for (var i = 1; i <= 10; i++)
subscriber.RequestNext(i);
subscriber.Request(1);
subscriber.ExpectComplete();}
[Fact]
public void ConcatAll_must_on_OnError_on_master_stream_cancel_the_current_open_substream_and_signal_error()
{
this.AssertAllStagesStopped(() =>
{
var publisher = this.CreateManualPublisherProbe<Source<int, NotUsed>>();
var subscriber = this.CreateManualSubscriberProbe<int>();
Source.FromPublisher(publisher)
.ConcatMany(x => x)
.To(Sink.FromSubscriber(subscriber))
.Run(Materializer);
var upstream = publisher.ExpectSubscription();
var downstream = subscriber.ExpectSubscription();
downstream.Request(1000);
var substreamPublisher = this.CreateManualPublisherProbe<int>();
var substreamFlow = Source.FromPublisher(substreamPublisher);
upstream.ExpectRequest();
upstream.SendNext(substreamFlow);
var subUpstream = substreamPublisher.ExpectSubscription();
upstream.SendError(TestException);
subscriber.ExpectError().Should().Be(TestException);
subUpstream.ExpectCancellation();
}, Materializer);
}
[Fact]
public void ConcatAll_must_on_OnError_on_master_stream_cancel_the_currently_opening_substream_and_signal_error()
{
this.AssertAllStagesStopped(() =>
{
var publisher = this.CreateManualPublisherProbe<Source<int, NotUsed>>();
var subscriber = this.CreateManualSubscriberProbe<int>();
Source.FromPublisher(publisher)
.ConcatMany(x => x)
.To(Sink.FromSubscriber(subscriber))
.Run(Materializer);
var upstream = publisher.ExpectSubscription();
var downstream = subscriber.ExpectSubscription();
downstream.Request(1000);
var substreamPublisher = this.CreateManualPublisherProbe<int>(false);
var substreamFlow = Source.FromPublisher(substreamPublisher);
upstream.ExpectRequest();
upstream.SendNext(substreamFlow);
var subUpstream = substreamPublisher.ExpectSubscription();
upstream.SendError(TestException);
subUpstream.SendOnSubscribe();
subscriber.ExpectError().Should().Be(TestException);
subUpstream.ExpectCancellation();
}, Materializer);
}
[Fact]
public void ConcatAll_must_on_OnError_on_opening_substream_cancel_the_master_stream_and_signal_error()
{
this.AssertAllStagesStopped(() =>
{
var publisher = this.CreateManualPublisherProbe<Source<int, NotUsed>>();
var subscriber = this.CreateManualSubscriberProbe<int>();
Source.FromPublisher(publisher)
.ConcatMany<Source<int,NotUsed>,int,NotUsed>(x => { throw TestException; })
.To(Sink.FromSubscriber(subscriber))
.Run(Materializer);
var upstream = publisher.ExpectSubscription();
var downstream = subscriber.ExpectSubscription();
downstream.Request(1000);
var substreamPublisher = this.CreateManualPublisherProbe<int>();
var substreamFlow = Source.FromPublisher(substreamPublisher);
upstream.ExpectRequest();
upstream.SendNext(substreamFlow);
subscriber.ExpectError().Should().Be(TestException);
upstream.ExpectCancellation();
}, Materializer);
}
[Fact]
public void ConcatAll_must_on_OnError_on_open_substream_cancel_the_master_stream_and_signal_error()
{
this.AssertAllStagesStopped(() =>
{
var publisher = this.CreateManualPublisherProbe<Source<int, NotUsed>>();
var subscriber = this.CreateManualSubscriberProbe<int>();
Source.FromPublisher(publisher)
.ConcatMany(x => x)
.To(Sink.FromSubscriber(subscriber))
.Run(Materializer);
var upstream = publisher.ExpectSubscription();
var downstream = subscriber.ExpectSubscription();
downstream.Request(1000);
var substreamPublisher = this.CreateManualPublisherProbe<int>();
var substreamFlow = Source.FromPublisher(substreamPublisher);
upstream.ExpectRequest();
upstream.SendNext(substreamFlow);
var subUpstream = substreamPublisher.ExpectSubscription();
subUpstream.SendError(TestException);
subscriber.ExpectError().Should().Be(TestException);
upstream.ExpectCancellation();
}, Materializer);
}
[Fact]
public void ConcatAll_must_on_cancellation_cancel_the_current_open_substream_and_the_master_stream()
{
this.AssertAllStagesStopped(() =>
{
var publisher = this.CreateManualPublisherProbe<Source<int, NotUsed>>();
var subscriber = this.CreateManualSubscriberProbe<int>();
Source.FromPublisher(publisher)
.ConcatMany(x => x)
.To(Sink.FromSubscriber(subscriber))
.Run(Materializer);
var upstream = publisher.ExpectSubscription();
var downstream = subscriber.ExpectSubscription();
downstream.Request(1000);
var substreamPublisher = this.CreateManualPublisherProbe<int>();
var substreamFlow = Source.FromPublisher(substreamPublisher);
upstream.ExpectRequest();
upstream.SendNext(substreamFlow);
var subUpstream = substreamPublisher.ExpectSubscription();
downstream.Cancel();
subUpstream.ExpectCancellation();
upstream.ExpectCancellation();
}, Materializer);
}
[Fact]
public void ConcatAll_must_on_cancellation_cancel_the_currently_opening_substream_and_the_master_stream()
{
this.AssertAllStagesStopped(() =>
{
var publisher = this.CreateManualPublisherProbe<Source<int, NotUsed>>();
var subscriber = this.CreateManualSubscriberProbe<int>();
Source.FromPublisher(publisher)
.ConcatMany(x => x)
.To(Sink.FromSubscriber(subscriber))
.Run(Materializer);
var upstream = publisher.ExpectSubscription();
var downstream = subscriber.ExpectSubscription();
downstream.Request(1000);
var substreamPublisher = this.CreateManualPublisherProbe<int>(false);
var substreamFlow = Source.FromPublisher(substreamPublisher);
upstream.ExpectRequest();
upstream.SendNext(substreamFlow);
var subUpstream = substreamPublisher.ExpectSubscription();
downstream.Cancel();
subUpstream.SendOnSubscribe();
subUpstream.ExpectCancellation();
upstream.ExpectCancellation();
}, Materializer);
}
[Fact]
public void ConcatAll_must_pass_along_early_cancellation()
{
this.AssertAllStagesStopped(() =>
{
var up = this.CreateManualPublisherProbe<Source<int, NotUsed>>();
var down = this.CreateManualSubscriberProbe<int>();
var flowSubscriber = Source.AsSubscriber<Source<int, NotUsed>>()
.ConcatMany(x => x.MapMaterializedValue<ISubscriber<Source<int, NotUsed>>>(_ => null))
.To(Sink.FromSubscriber(down))
.Run(Materializer);
var downstream = down.ExpectSubscription();
downstream.Cancel();
up.Subscribe(flowSubscriber);
var upSub = up.ExpectSubscription();
upSub.ExpectCancellation();
}, Materializer);
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System;
using System.Text;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Search
{
/*
* 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 Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using OpenMode = Lucene.Net.Index.OpenMode;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class BaseTestRangeFilter : LuceneTestCase
{
public const bool F = false;
public const bool T = true;
/// <summary>
/// Collation interacts badly with hyphens -- collation produces different
/// ordering than Unicode code-point ordering -- so two indexes are created:
/// one which can't have negative random integers, for testing collated ranges,
/// and the other which can have negative random integers, for all other tests.
/// </summary>
internal class TestIndex
{
internal int maxR;
internal int minR;
internal bool allowNegativeRandomInts;
internal Directory index;
internal TestIndex(Random random, int minR, int maxR, bool allowNegativeRandomInts)
{
this.minR = minR;
this.maxR = maxR;
this.allowNegativeRandomInts = allowNegativeRandomInts;
index = NewDirectory(random);
}
}
internal static IndexReader signedIndexReader;
internal static IndexReader unsignedIndexReader;
internal static TestIndex signedIndexDir;
internal static TestIndex unsignedIndexDir;
internal static int minId = 0;
internal static int maxId;
internal static readonly int intLength = Convert.ToString(int.MaxValue).Length;
/// <summary>
/// a simple padding function that should work with any int
/// </summary>
public static string Pad(int n)
{
StringBuilder b = new StringBuilder(40);
string p = "0";
if (n < 0)
{
p = "-";
n = int.MaxValue + n + 1;
}
b.Append(p);
string s = Convert.ToString(n);
for (int i = s.Length; i <= intLength; i++)
{
b.Append("0");
}
b.Append(s);
return b.ToString();
}
/// <summary>
/// LUCENENET specific
/// Is non-static because <see cref="Build(Random, TestIndex)"/> is no
/// longer static.
/// </summary>
[OneTimeSetUp]
public override void BeforeClass() // LUCENENET specific: renamed from BeforeClassBaseTestRangeFilter() so we can override to control the order of execution
{
base.BeforeClass();
maxId = AtLeast(500);
signedIndexDir = new TestIndex(Random, int.MaxValue, int.MinValue, true);
unsignedIndexDir = new TestIndex(Random, int.MaxValue, 0, false);
signedIndexReader = Build(Random, signedIndexDir);
unsignedIndexReader = Build(Random, unsignedIndexDir);
}
[OneTimeTearDown]
public override void AfterClass() // LUCENENET specific: renamed from AfterClassBaseTestRangeFilter() so we can override to control the order of execution
{
signedIndexReader?.Dispose();
unsignedIndexReader?.Dispose();
signedIndexDir?.index?.Dispose();
unsignedIndexDir?.index?.Dispose();
signedIndexReader = null;
unsignedIndexReader = null;
signedIndexDir = null;
unsignedIndexDir = null;
base.AfterClass();
}
/// <summary>
/// LUCENENET specific
/// Passed in because NewStringField and NewIndexWriterConfig are no
/// longer static.
/// </summary>
private IndexReader Build(Random random, TestIndex index)
{
/* build an index */
Document doc = new Document();
Field idField = NewStringField(random, "id", "", Field.Store.YES);
Field randField = NewStringField(random, "rand", "", Field.Store.YES);
Field bodyField = NewStringField(random, "body", "", Field.Store.NO);
doc.Add(idField);
doc.Add(randField);
doc.Add(bodyField);
RandomIndexWriter writer = new RandomIndexWriter(random, index.index, NewIndexWriterConfig(random, TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetOpenMode(OpenMode.CREATE).SetMaxBufferedDocs(TestUtil.NextInt32(random, 50, 1000)).SetMergePolicy(NewLogMergePolicy()));
TestUtil.ReduceOpenFiles(writer.IndexWriter);
while (true)
{
int minCount = 0;
int maxCount = 0;
for (int d = minId; d <= maxId; d++)
{
idField.SetStringValue(Pad(d));
int r = index.allowNegativeRandomInts ? random.Next() : random.Next(int.MaxValue);
if (index.maxR < r)
{
index.maxR = r;
maxCount = 1;
}
else if (index.maxR == r)
{
maxCount++;
}
if (r < index.minR)
{
index.minR = r;
minCount = 1;
}
else if (r == index.minR)
{
minCount++;
}
randField.SetStringValue(Pad(r));
bodyField.SetStringValue("body");
writer.AddDocument(doc);
}
if (minCount == 1 && maxCount == 1)
{
// our subclasses rely on only 1 doc having the min or
// max, so, we loop until we satisfy that. it should be
// exceedingly rare (Yonik calculates 1 in ~429,000)
// times) that this loop requires more than one try:
IndexReader ir = writer.GetReader();
writer.Dispose();
return ir;
}
// try again
writer.DeleteAll();
}
}
[Test]
public virtual void TestPad()
{
int[] tests = new int[] { -9999999, -99560, -100, -3, -1, 0, 3, 9, 10, 1000, 999999999 };
for (int i = 0; i < tests.Length - 1; i++)
{
int a = tests[i];
int b = tests[i + 1];
string aa = Pad(a);
string bb = Pad(b);
string label = a + ":" + aa + " vs " + b + ":" + bb;
Assert.AreEqual(aa.Length, bb.Length, "i=" + i + ": length of " + label);
Assert.IsTrue(System.String.Compare(aa, bb, System.StringComparison.Ordinal) < 0, "i=" + i + ": compare less than " + label);
}
}
}
}
| |
// 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.IO;
using System.Net.Cache;
using System.Net.Http;
using System.Net.Test.Common;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Tests
{
public partial class HttpWebRequestTest : RemoteExecutorTestBase
{
private const string RequestBody = "This is data to POST.";
private readonly byte[] _requestBodyBytes = Encoding.UTF8.GetBytes(RequestBody);
private readonly NetworkCredential _explicitCredential = new NetworkCredential("user", "password", "domain");
private readonly ITestOutputHelper _output;
public static readonly object[][] EchoServers = System.Net.Test.Common.Configuration.Http.EchoServers;
public HttpWebRequestTest(ITestOutputHelper output)
{
_output = output;
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_VerifyDefaults_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Null(request.Accept);
Assert.True(request.AllowAutoRedirect);
Assert.False(request.AllowReadStreamBuffering);
Assert.True(request.AllowWriteStreamBuffering);
Assert.Null(request.ContentType);
Assert.Equal(350, request.ContinueTimeout);
Assert.NotNull(request.ClientCertificates);
Assert.Null(request.CookieContainer);
Assert.Null(request.Credentials);
Assert.False(request.HaveResponse);
Assert.NotNull(request.Headers);
Assert.True(request.KeepAlive);
Assert.Equal(0, request.Headers.Count);
Assert.Equal(HttpVersion.Version11, request.ProtocolVersion);
Assert.Equal("GET", request.Method);
Assert.Equal(HttpWebRequest.DefaultMaximumResponseHeadersLength, 64);
Assert.NotNull(HttpWebRequest.DefaultCachePolicy);
Assert.Equal(HttpWebRequest.DefaultCachePolicy.Level, RequestCacheLevel.BypassCache);
Assert.Equal(PlatformDetection.IsFullFramework ? 64 : 0, HttpWebRequest.DefaultMaximumErrorResponseLength);
Assert.NotNull(request.Proxy);
Assert.Equal(remoteServer, request.RequestUri);
Assert.True(request.SupportsCookieContainer);
Assert.Equal(100000, request.Timeout);
Assert.False(request.UseDefaultCredentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_CreateHttpWithString_ExpectNotNull(Uri remoteServer)
{
string remoteServerString = remoteServer.ToString();
HttpWebRequest request = WebRequest.CreateHttp(remoteServerString);
Assert.NotNull(request);
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_CreateHttpWithUri_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetValidValue_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
string acceptType = "*/*";
request.Accept = acceptType;
Assert.Equal(acceptType, request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetEmptyValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Accept = string.Empty;
Assert.Null(request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetNullValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Accept = null;
Assert.Null(request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowReadStreamBuffering_SetFalseThenGet_ExpectFalse(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowReadStreamBuffering = false;
Assert.False(request.AllowReadStreamBuffering);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "not supported on .NET Framework")]
[Theory, MemberData(nameof(EchoServers))]
public void AllowReadStreamBuffering_SetTrueThenGet_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowReadStreamBuffering = true;
Assert.True(request.AllowReadStreamBuffering);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ContentLength_Get_ExpectSameAsGetResponseStream(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (WebResponse response = await request.GetResponseAsync())
using (Stream myStream = response.GetResponseStream())
using (StreamReader sr = new StreamReader(myStream))
{
string strContent = sr.ReadToEnd();
long length = response.ContentLength;
Assert.Equal(strContent.Length, length);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentLength_SetNegativeOne_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.ContentLength = -1);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentLength_SetThenGetOne_Success(Uri remoteServer)
{
const int ContentLength = 1;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContentLength = ContentLength;
Assert.Equal(ContentLength, request.ContentLength);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentType_SetThenGet_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
string myContent = "application/x-www-form-urlencoded";
request.ContentType = myContent;
Assert.Equal(myContent, request.ContentType);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentType_SetThenGetEmptyValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContentType = string.Empty;
Assert.Null(request.ContentType);
}
[Fact]
public async Task Headers_SetAfterRequestSubmitted_ThrowsInvalidOperationException()
{
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
HttpWebRequest request = WebRequest.CreateHttp(uri);
Task<WebResponse> getResponse = request.GetResponseAsync();
await server.AcceptConnectionSendResponseAndCloseAsync();
using (WebResponse response = await getResponse)
{
Assert.Throws<InvalidOperationException>(() => request.AutomaticDecompression = DecompressionMethods.Deflate);
Assert.Throws<InvalidOperationException>(() => request.ContentLength = 255);
Assert.Throws<InvalidOperationException>(() => request.ContinueTimeout = 255);
Assert.Throws<InvalidOperationException>(() => request.Host = "localhost");
Assert.Throws<InvalidOperationException>(() => request.MaximumResponseHeadersLength = 255);
Assert.Throws<InvalidOperationException>(() => request.SendChunked = true);
Assert.Throws<InvalidOperationException>(() => request.Proxy = WebRequest.DefaultWebProxy);
Assert.Throws<InvalidOperationException>(() => request.Headers = null);
}
});
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumResponseHeadersLength_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.MaximumResponseHeadersLength = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumResponseHeadersLength_SetThenGetNegativeOne_Success(Uri remoteServer)
{
const int MaximumResponseHeaderLength = -1;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.MaximumResponseHeadersLength = MaximumResponseHeaderLength;
Assert.Equal(MaximumResponseHeaderLength, request.MaximumResponseHeadersLength);
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumAutomaticRedirections_SetZeroOrNegative_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.MaximumAutomaticRedirections = 0);
AssertExtensions.Throws<ArgumentException>("value", () => request.MaximumAutomaticRedirections = -1);
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumAutomaticRedirections_SetThenGetOne_Success(Uri remoteServer)
{
const int MaximumAutomaticRedirections = 1;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.MaximumAutomaticRedirections = MaximumAutomaticRedirections;
Assert.Equal(MaximumAutomaticRedirections, request.MaximumAutomaticRedirections);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetThenGetZero_ExpectZero(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueTimeout = 0;
Assert.Equal(0, request.ContinueTimeout);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetNegativeOne_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueTimeout = -1;
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.ContinueTimeout = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void Timeout_SetThenGetZero_ExpectZero(Uri remoteServer)
{
const int Timeout = 0;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Timeout = Timeout;
Assert.Equal(Timeout, request.Timeout);
}
[Theory, MemberData(nameof(EchoServers))]
public void Timeout_SetNegativeOne_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Timeout = -1;
}
[Theory, MemberData(nameof(EchoServers))]
public void Timeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.Timeout = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void TimeOut_SetThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Timeout = 100;
Assert.Equal(100, request.Timeout);
request.Timeout = Threading.Timeout.Infinite;
Assert.Equal(Threading.Timeout.Infinite, request.Timeout);
request.Timeout = int.MaxValue;
Assert.Equal(int.MaxValue, request.Timeout);
}
[ActiveIssue(22627)]
[Fact]
public async Task Timeout_SetTenMillisecondsOnLoopback_ThrowsWebException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Timeout = 10; // ms.
var sw = Stopwatch.StartNew();
WebException exception = Assert.Throws<WebException>(() => request.GetResponse());
sw.Stop();
Assert.InRange(sw.ElapsedMilliseconds, 1, 15 * 1000);
Assert.Equal(WebExceptionStatus.Timeout, exception.Status);
Assert.Equal(null, exception.InnerException);
Assert.Equal(null, exception.Response);
return Task.FromResult<object>(null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void Address_CtorAddress_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer, request.Address);
}
[Theory, MemberData(nameof(EchoServers))]
public void UserAgent_SetThenGetWindows_ValuesMatch(Uri remoteServer)
{
const string UserAgent = "Windows";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UserAgent = UserAgent;
Assert.Equal(UserAgent, request.UserAgent);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetNullValue_ThrowsArgumentNullException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentNullException>("value", null, () => request.Host = null);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetSlash_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", null, () => request.Host = "/localhost");
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetInvalidUri_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", null, () => request.Host = "NoUri+-*");
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetThenGetCustomUri_ValuesMatch(Uri remoteServer)
{
const string Host = "localhost";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Host = Host;
Assert.Equal(Host, request.Host);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetThenGetCustomUriWithPort_ValuesMatch(Uri remoteServer)
{
const string Host = "localhost:8080";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Host = Host;
Assert.Equal(Host, request.Host);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_GetDefaultHostSameAsAddress_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer.Host, request.Host);
}
[Theory]
[InlineData("https://microsoft.com:8080")]
public void Host_GetDefaultHostWithCustomPortSameAsAddress_ValuesMatch(string endpoint)
{
Uri endpointUri = new Uri(endpoint);
HttpWebRequest request = WebRequest.CreateHttp(endpointUri);
Assert.Equal(endpointUri.Host + ":" + endpointUri.Port, request.Host);
}
[Theory, MemberData(nameof(EchoServers))]
public void Pipelined_SetThenGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Pipelined = true;
Assert.True(request.Pipelined);
request.Pipelined = false;
Assert.False(request.Pipelined);
}
[Theory, MemberData(nameof(EchoServers))]
public void Referer_SetThenGetReferer_ValuesMatch(Uri remoteServer)
{
const string Referer = "Referer";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Referer = Referer;
Assert.Equal(Referer, request.Referer);
}
[Theory, MemberData(nameof(EchoServers))]
public void TransferEncoding_NullOrWhiteSpace_ValuesMatch(Uri remoteServer)
{
const string TransferEncoding = "xml";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.SendChunked = true;
request.TransferEncoding = TransferEncoding;
Assert.Equal(TransferEncoding, request.TransferEncoding);
request.TransferEncoding = null;
Assert.Equal(null, request.TransferEncoding);
}
[Theory, MemberData(nameof(EchoServers))]
public void TransferEncoding_SetChunked_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.TransferEncoding = "chunked");
}
[Theory, MemberData(nameof(EchoServers))]
public void TransferEncoding_SetWithSendChunkedFalse_ThrowsInvalidOperationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Throws<InvalidOperationException>(() => request.TransferEncoding = "xml");
}
[Theory, MemberData(nameof(EchoServers))]
public void KeepAlive_SetThenGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.KeepAlive = true;
Assert.True(request.KeepAlive);
request.KeepAlive = false;
Assert.False(request.KeepAlive);
}
[Theory]
[InlineData(null)]
[InlineData(false)]
[InlineData(true)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19225")]
public void KeepAlive_CorrectConnectionHeaderSent(bool? keepAlive)
{
HttpWebRequest request = WebRequest.CreateHttp(Test.Common.Configuration.Http.RemoteEchoServer);
if (keepAlive.HasValue)
{
request.KeepAlive = keepAlive.Value;
}
using (var response = (HttpWebResponse)request.GetResponse())
using (var body = new StreamReader(response.GetResponseStream()))
{
string content = body.ReadToEnd();
if (!keepAlive.HasValue || keepAlive.Value)
{
// Validate that the request doesn't contain Connection: "close", but we can't validate
// that it does contain Connection: "keep-alive", as that's optional as of HTTP 1.1.
Assert.DoesNotContain("\"Connection\": \"close\"", content, StringComparison.OrdinalIgnoreCase);
}
else
{
Assert.Contains("\"Connection\": \"close\"", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("\"Keep-Alive\"", content, StringComparison.OrdinalIgnoreCase);
}
}
}
[Theory, MemberData(nameof(EchoServers))]
public void AutomaticDecompression_SetAndGetDeflate_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AutomaticDecompression = DecompressionMethods.Deflate;
Assert.Equal(DecompressionMethods.Deflate, request.AutomaticDecompression);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowWriteStreamBuffering_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowWriteStreamBuffering = true;
Assert.True(request.AllowWriteStreamBuffering);
request.AllowWriteStreamBuffering = false;
Assert.False(request.AllowWriteStreamBuffering);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowAutoRedirect_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowAutoRedirect = true;
Assert.True(request.AllowAutoRedirect);
request.AllowAutoRedirect = false;
Assert.False(request.AllowAutoRedirect);
}
[Fact]
public void ConnectionGroupName_SetAndGetGroup_ValuesMatch()
{
// Note: In CoreFX changing this value will not have any effect on HTTP stack's behavior.
// For app-compat reasons we allow applications to alter and read the property.
HttpWebRequest request = WebRequest.CreateHttp("http://test");
Assert.Null(request.ConnectionGroupName);
request.ConnectionGroupName = "Group";
Assert.Equal("Group", request.ConnectionGroupName);
}
[Theory, MemberData(nameof(EchoServers))]
public void PreAuthenticate_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.PreAuthenticate = true;
Assert.True(request.PreAuthenticate);
request.PreAuthenticate = false;
Assert.False(request.PreAuthenticate);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19225")]
[Theory, MemberData(nameof(EchoServers))]
public void PreAuthenticate_SetAndGetBooleanResponse_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.PreAuthenticate = true;
using (var response = (HttpWebResponse)request.GetResponse())
{
Assert.True(request.PreAuthenticate);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void Connection_NullOrWhiteSpace_ValuesMatch(Uri remoteServer)
{
const string Connection = "connect";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Connection = Connection;
Assert.Equal(Connection, request.Connection);
request.Connection = null;
Assert.Equal(null, request.Connection);
}
[Theory, MemberData(nameof(EchoServers))]
public void Connection_SetKeepAliveAndClose_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.Connection = "keep-alive");
AssertExtensions.Throws<ArgumentException>("value", () => request.Connection = "close");
}
[Theory, MemberData(nameof(EchoServers))]
public void Expect_SetNullOrWhiteSpace_ValuesMatch(Uri remoteServer)
{
const string Expect = "101-go";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Expect = Expect;
Assert.Equal(Expect, request.Expect);
request.Expect = null;
Assert.Equal(null, request.Expect);
}
[Theory, MemberData(nameof(EchoServers))]
public void Expect_Set100Continue_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.Expect = "100-continue");
}
[Fact]
public void DefaultMaximumResponseHeadersLength_SetAndGetLength_ValuesMatch()
{
RemoteInvoke(() =>
{
int defaultMaximumResponseHeadersLength = HttpWebRequest.DefaultMaximumResponseHeadersLength;
const int NewDefaultMaximumResponseHeadersLength = 255;
try
{
HttpWebRequest.DefaultMaximumResponseHeadersLength = NewDefaultMaximumResponseHeadersLength;
Assert.Equal(NewDefaultMaximumResponseHeadersLength, HttpWebRequest.DefaultMaximumResponseHeadersLength);
}
finally
{
HttpWebRequest.DefaultMaximumResponseHeadersLength = defaultMaximumResponseHeadersLength;
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void DefaultMaximumErrorResponseLength_SetAndGetLength_ValuesMatch()
{
RemoteInvoke(() =>
{
int defaultMaximumErrorsResponseLength = HttpWebRequest.DefaultMaximumErrorResponseLength;
const int NewDefaultMaximumErrorsResponseLength = 255;
try
{
HttpWebRequest.DefaultMaximumErrorResponseLength = NewDefaultMaximumErrorsResponseLength;
Assert.Equal(NewDefaultMaximumErrorsResponseLength, HttpWebRequest.DefaultMaximumErrorResponseLength);
}
finally
{
HttpWebRequest.DefaultMaximumErrorResponseLength = defaultMaximumErrorsResponseLength;
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void DefaultCachePolicy_SetAndGetPolicyReload_ValuesMatch()
{
RemoteInvoke(() =>
{
RequestCachePolicy requestCachePolicy = HttpWebRequest.DefaultCachePolicy;
try
{
RequestCachePolicy newRequestCachePolicy = new RequestCachePolicy(RequestCacheLevel.Reload);
HttpWebRequest.DefaultCachePolicy = newRequestCachePolicy;
Assert.Equal(newRequestCachePolicy.Level, HttpWebRequest.DefaultCachePolicy.Level);
}
finally
{
HttpWebRequest.DefaultCachePolicy = requestCachePolicy;
}
return SuccessExitCode;
}).Dispose();
}
[Theory, MemberData(nameof(EchoServers))]
public void IfModifiedSince_SetMinDateAfterValidDate_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
DateTime newIfModifiedSince = new DateTime(2000, 1, 1);
request.IfModifiedSince = newIfModifiedSince;
Assert.Equal(newIfModifiedSince, request.IfModifiedSince);
DateTime ifModifiedSince = DateTime.MinValue;
request.IfModifiedSince = ifModifiedSince;
Assert.Equal(ifModifiedSince, request.IfModifiedSince);
}
[Theory, MemberData(nameof(EchoServers))]
public void Date_SetMinDateAfterValidDate_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
DateTime newDate = new DateTime(2000, 1, 1);
request.Date = newDate;
Assert.Equal(newDate, request.Date);
DateTime date = DateTime.MinValue;
request.Date = date;
Assert.Equal(date, request.Date);
}
[Theory, MemberData(nameof(EchoServers))]
public void SendChunked_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.SendChunked = true;
Assert.True(request.SendChunked);
request.SendChunked = false;
Assert.False(request.SendChunked);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueDelegate_SetNullDelegate_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueDelegate = null;
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueDelegate_SetDelegateThenGet_ValuesSame(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
HttpContinueDelegate continueDelegate = new HttpContinueDelegate((a, b) => { });
request.ContinueDelegate = continueDelegate;
Assert.Same(continueDelegate, request.ContinueDelegate);
}
[Theory, MemberData(nameof(EchoServers))]
public void ServicePoint_GetValue_ExpectedResult(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request.ServicePoint);
}
[Theory, MemberData(nameof(EchoServers))]
public void ServerCertificateValidationCallback_SetCallbackThenGet_ValuesSame(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
var serverCertificateVallidationCallback = new Security.RemoteCertificateValidationCallback((a, b, c, d) => true);
request.ServerCertificateValidationCallback = serverCertificateVallidationCallback;
Assert.Same(serverCertificateVallidationCallback, request.ServerCertificateValidationCallback);
}
[Theory, MemberData(nameof(EchoServers))]
public void ClientCertificates_SetNullX509_ThrowsArgumentNullException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentNullException>("value", () => request.ClientCertificates = null);
}
[Theory, MemberData(nameof(EchoServers))]
public void ClientCertificates_SetThenGetX509_ValuesSame(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
var certificateCollection = new System.Security.Cryptography.X509Certificates.X509CertificateCollection();
request.ClientCertificates = certificateCollection;
Assert.Same(certificateCollection, request.ClientCertificates);
}
[Theory, MemberData(nameof(EchoServers))]
public void ProtocolVersion_SetInvalidHttpVersion_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.ProtocolVersion = new Version());
}
[Theory, MemberData(nameof(EchoServers))]
public void ProtocolVersion_SetThenGetHttpVersions_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ProtocolVersion = HttpVersion.Version10;
Assert.Equal(HttpVersion.Version10, request.ProtocolVersion);
request.ProtocolVersion = HttpVersion.Version11;
Assert.Equal(HttpVersion.Version11, request.ProtocolVersion);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP does not allow HTTP/1.0 requests.")]
[OuterLoop]
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ProtocolVersion_SetThenSendRequest_CorrectHttpRequestVersionSent(bool isVersion10)
{
Version requestVersion = isVersion10 ? HttpVersion.Version10 : HttpVersion.Version11;
Version receivedRequestVersion = null;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.ProtocolVersion = requestVersion;
Task<WebResponse> getResponse = request.GetResponseAsync();
Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync();
using (HttpWebResponse response = (HttpWebResponse) await getResponse)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
List<string> receivedRequest = await serverTask;
string statusLine = receivedRequest[0];
if (statusLine.Contains("/1.0"))
{
receivedRequestVersion = HttpVersion.Version10;
}
else if (statusLine.Contains("/1.1"))
{
receivedRequestVersion = HttpVersion.Version11;
}
});
Assert.Equal(requestVersion, receivedRequestVersion);
}
[Fact]
public void ReadWriteTimeout_SetThenGet_ValuesMatch()
{
// Note: In CoreFX changing this value will not have any effect on HTTP stack's behavior.
// For app-compat reasons we allow applications to alter and read the property.
HttpWebRequest request = WebRequest.CreateHttp("http://test");
request.ReadWriteTimeout = 5;
Assert.Equal(5, request.ReadWriteTimeout);
}
[Fact]
public void ReadWriteTimeout_InfiniteValue_Ok()
{
HttpWebRequest request = WebRequest.CreateHttp("http://test");
request.ReadWriteTimeout = Timeout.Infinite;
}
[Fact]
public void ReadWriteTimeout_NegativeOrZeroValue_Fail()
{
HttpWebRequest request = WebRequest.CreateHttp("http://test");
Assert.Throws<ArgumentOutOfRangeException>(() => { request.ReadWriteTimeout = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { request.ReadWriteTimeout = -10; });
}
[Theory, MemberData(nameof(EchoServers))]
public void CookieContainer_SetThenGetContainer_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.CookieContainer = null;
var cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
Assert.Same(cookieContainer, request.CookieContainer);
}
[Theory, MemberData(nameof(EchoServers))]
public void Credentials_SetDefaultCredentialsThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = CredentialCache.DefaultCredentials;
Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void Credentials_SetExplicitCredentialsThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
Assert.Equal(_explicitCredential, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetTrue_CredentialsEqualsDefaultCredentials(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
request.UseDefaultCredentials = true;
Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetFalse_CredentialsNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
request.UseDefaultCredentials = false;
Assert.Equal(null, request.Credentials);
}
[OuterLoop]
[Theory]
[MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetGetResponse_ExpectSuccess(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UseDefaultCredentials = true;
WebResponse response = request.GetResponse();
response.Dispose();
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseGETVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseHEADVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Head.Method;
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseCONNECTVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = "CONNECT";
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
request.Abort();
WebException ex = Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null));
Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "no exception thrown on mono")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "no exception thrown on netfx")]
public void BeginGetRequestStream_CreatePostRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = "POST";
IAsyncResult asyncResult = request.BeginGetRequestStream(null, null);
Assert.Throws<InvalidOperationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreateRequestThenBeginGetResponsePrior_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
IAsyncResult asyncResult = request.BeginGetResponse(null, null);
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
public async Task BeginGetResponse_CreateRequestThenCallTwice_ThrowsInvalidOperationException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
IAsyncResult asyncResult = request.BeginGetResponse(null, null);
Assert.Throws<InvalidOperationException>(() => request.BeginGetResponse(null, null));
return Task.FromResult<object>(null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetResponse_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
request.Abort();
WebException ex = Assert.Throws<WebException>(() => request.BeginGetResponse(null, null));
Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status);
}
public async Task GetRequestStreamAsync_WriteAndDisposeRequestStreamThenOpenRequestStream_ThrowsArgumentException()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
AssertExtensions.Throws<ArgumentException>(null, () => new StreamReader(requestStream));
}
});
}
public async Task GetRequestStreamAsync_SetPOSTThenGet_ExpectNotNull()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
Assert.NotNull(requestStream);
}
});
}
public async Task GetResponseAsync_GetResponseStream_ExpectNotNull()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
using (WebResponse response = await request.GetResponseAsync())
{
Assert.NotNull(response.GetResponseStream());
}
});
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_GetResponseStream_ContainsHost(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Get.Method;
using (WebResponse response = await request.GetResponseAsync())
using (Stream myStream = response.GetResponseStream())
{
Assert.NotNull(myStream);
using (var sr = new StreamReader(myStream))
{
string strContent = sr.ReadToEnd();
Assert.True(strContent.Contains("\"Host\": \"" + System.Net.Test.Common.Configuration.Http.Host + "\""));
}
}
}
[OuterLoop]
[Theory, MemberData(nameof(EchoServers))]
public void CookieContainer_Count_Add(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
DateTime now = DateTime.UtcNow;
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(remoteServer, new Cookie("1", "cookie1"));
request.CookieContainer.Add(remoteServer, new Cookie("2", "cookie2"));
Assert.True(request.SupportsCookieContainer);
Assert.Equal(request.CookieContainer.GetCookies(remoteServer).Count, 2);
}
[Theory, MemberData(nameof(EchoServers))]
public void Range_Add_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AddRange(1, 5);
Assert.Equal(request.Headers["Range"], "bytes=1-5");
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_PostRequestStream_ContainsData(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
using (WebResponse response = await request.GetResponseAsync())
using (Stream myStream = response.GetResponseStream())
using (var sr = new StreamReader(myStream))
{
string strContent = sr.ReadToEnd();
Assert.True(strContent.Contains(RequestBody));
}
}
[Theory]
[MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_UseDefaultCredentials_ExpectSuccess(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UseDefaultCredentials = true;
var response = await request.GetResponseAsync();
response.Dispose();
}
[OuterLoop] // fails on networks with DNS servers that provide a dummy page for invalid addresses
[Fact]
public async Task GetResponseAsync_ServerNameNotInDns_ThrowsWebException()
{
string serverUrl = string.Format("http://www.{0}.com/", Guid.NewGuid().ToString());
HttpWebRequest request = WebRequest.CreateHttp(serverUrl);
WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync());
Assert.Equal(WebExceptionStatus.NameResolutionFailure, ex.Status);
}
public static object[][] StatusCodeServers = {
new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(false, 404) },
new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(true, 404) },
};
[Theory, MemberData(nameof(StatusCodeServers))]
public async Task GetResponseAsync_ResourceNotFound_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync());
Assert.Equal(WebExceptionStatus.ProtocolError, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task HaveResponse_GetResponseAsync_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (WebResponse response = await request.GetResponseAsync())
{
Assert.True(request.HaveResponse);
}
}
[Theory]
[MemberData(nameof(EchoServers))]
public async Task Headers_GetResponseHeaders_ContainsExpectedValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
string headersString = response.Headers.ToString();
string headersPartialContent = "Content-Type: application/json";
Assert.True(headersString.Contains(headersPartialContent));
}
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetThenGetToGET_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Get.Method;
Assert.Equal(HttpMethod.Get.Method, request.Method);
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetThenGetToPOST_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
Assert.Equal(HttpMethod.Post.Method, request.Method);
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetInvalidString_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.Method = null);
AssertExtensions.Throws<ArgumentException>("value", () => request.Method = string.Empty);
AssertExtensions.Throws<ArgumentException>("value", () => request.Method = "Method(2");
}
[Theory, MemberData(nameof(EchoServers))]
public void Proxy_GetDefault_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request.Proxy);
}
[Theory, MemberData(nameof(EchoServers))]
public void RequestUri_CreateHttpThenGet_ExpectSameUri(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer, request.RequestUri);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ResponseUri_GetResponseAsync_ExpectSameUri(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (WebResponse response = await request.GetResponseAsync())
{
Assert.Equal(remoteServer, response.ResponseUri);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void SupportsCookieContainer_GetDefault_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.True(request.SupportsCookieContainer);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SimpleScenario_UseGETVerb_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
string responseBody = sr.ReadToEnd();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SimpleScenario_UsePOSTVerb_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
string responseBody = sr.ReadToEnd();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ContentType_AddHeaderWithNoContent_SendRequest_HeaderGetsSent(Uri remoteServer)
{
const string ContentType = "text/plain; charset=utf-8";
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.ContentType = ContentType;
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
string responseBody = sr.ReadToEnd();
_output.WriteLine(responseBody);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(responseBody.Contains($"\"Content-Type\": \"{ContentType}\""));
}
}
[Theory, MemberData(nameof(EchoServers))]
public void MediaType_SetThenGet_ValuesMatch(Uri remoteServer)
{
const string MediaType = "text/plain";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.MediaType = MediaType;
Assert.Equal(MediaType, request.MediaType);
}
public async Task HttpWebRequest_EndGetRequestStreamContext_ExpectedValue()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
System.Net.TransportContext context;
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Method = "POST";
using (request.EndGetRequestStream(request.BeginGetRequestStream(null, null), out context))
{
if (PlatformDetection.IsFullFramework)
{
Assert.NotNull(context);
}
else
{
Assert.Null(context);
}
}
return Task.FromResult<object>(null);
});
}
[ActiveIssue(19083)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "dotnet/corefx #19083")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19083")]
[Fact]
public async Task Abort_BeginGetRequestStreamThenAbort_EndGetRequestStreamThrowsWebException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = "POST";
RequestState state = new RequestState();
state.Request = request;
request.BeginGetResponse(new AsyncCallback(RequestStreamCallback), state);
request.Abort();
Assert.Equal(1, state.RequestStreamCallbackCallCount);
WebException wex = state.SavedRequestStreamException as WebException;
Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status);
return Task.FromResult<object>(null);
});
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "ResponseCallback not called after Abort on mono")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "ResponseCallback not called after Abort on netfx")]
[Fact]
public async Task Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
RequestState state = new RequestState();
state.Request = request;
request.BeginGetResponse(new AsyncCallback(ResponseCallback), state);
request.Abort();
Assert.Equal(1, state.ResponseCallbackCallCount);
return Task.FromResult<object>(null);
});
}
[ActiveIssue(18800)]
[Fact]
public async Task Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
RequestState state = new RequestState();
state.Request = request;
request.BeginGetResponse(new AsyncCallback(ResponseCallback), state);
request.Abort();
WebException wex = state.SavedResponseException as WebException;
Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status);
return Task.FromResult<object>(null);
});
}
[Fact]
public async Task Abort_BeginGetResponseUsingNoCallbackThenAbort_Success()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.BeginGetResponse(null, null);
request.Abort();
return Task.FromResult<object>(null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_CreateRequestThenAbort_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Abort();
}
private void RequestStreamCallback(IAsyncResult asynchronousResult)
{
RequestState state = (RequestState)asynchronousResult.AsyncState;
state.RequestStreamCallbackCallCount++;
try
{
HttpWebRequest request = state.Request;
state.Response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream stream = request.EndGetRequestStream(asynchronousResult);
stream.Dispose();
}
catch (Exception ex)
{
state.SavedRequestStreamException = ex;
}
}
private void ResponseCallback(IAsyncResult asynchronousResult)
{
RequestState state = (RequestState)asynchronousResult.AsyncState;
state.ResponseCallbackCallCount++;
try
{
using (HttpWebResponse response = (HttpWebResponse)state.Request.EndGetResponse(asynchronousResult))
{
state.SavedResponseHeaders = response.Headers;
}
}
catch (Exception ex)
{
state.SavedResponseException = ex;
}
}
[Fact]
public void HttpWebRequest_Serialize_Fails()
{
using (MemoryStream fs = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
var hwr = HttpWebRequest.CreateHttp("http://localhost");
// .NET Framework throws
// System.Runtime.Serialization.SerializationException:
// Type 'System.Net.WebRequest+WebProxyWrapper' in Assembly 'System, Version=4.0.0.
// 0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
// While .NET Core throws
// System.Runtime.Serialization.SerializationException:
// Type 'System.Net.HttpWebRequest' in Assembly 'System.Net.Requests, Version=4.0.0.
// 0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
Assert.Throws<System.Runtime.Serialization.SerializationException>(() => formatter.Serialize(fs, hwr));
}
}
}
public class RequestState
{
public HttpWebRequest Request;
public HttpWebResponse Response;
public WebHeaderCollection SavedResponseHeaders;
public int RequestStreamCallbackCallCount;
public int ResponseCallbackCallCount;
public Exception SavedRequestStreamException;
public Exception SavedResponseException;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Cdn
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ProfilesOperations.
/// </summary>
public static partial class ProfilesOperationsExtensions
{
/// <summary>
/// Lists all of the CDN profiles within an Azure subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Profile> List(this IProfilesOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the CDN profiles within an Azure subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Profile>> ListAsync(this IProfilesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the CDN profiles within a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
public static IPage<Profile> ListByResourceGroup(this IProfilesOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the CDN profiles within a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Profile>> ListByResourceGroupAsync(this IProfilesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a CDN profile with the specified profile name under the specified
/// subscription and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
public static Profile Get(this IProfilesOperations operations, string resourceGroupName, string profileName)
{
return operations.GetAsync(resourceGroupName, profileName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a CDN profile with the specified profile name under the specified
/// subscription and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Profile> GetAsync(this IProfilesOperations operations, string resourceGroupName, string profileName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new CDN profile with a profile name under the specified
/// subscription and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='profile'>
/// Profile properties needed to create a new profile.
/// </param>
public static Profile Create(this IProfilesOperations operations, string resourceGroupName, string profileName, Profile profile)
{
return operations.CreateAsync(resourceGroupName, profileName, profile).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new CDN profile with a profile name under the specified
/// subscription and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='profile'>
/// Profile properties needed to create a new profile.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Profile> CreateAsync(this IProfilesOperations operations, string resourceGroupName, string profileName, Profile profile, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, profileName, profile, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing CDN profile with the specified profile name under the
/// specified subscription and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='tags'>
/// Profile tags
/// </param>
public static Profile Update(this IProfilesOperations operations, string resourceGroupName, string profileName, IDictionary<string, string> tags)
{
return operations.UpdateAsync(resourceGroupName, profileName, tags).GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing CDN profile with the specified profile name under the
/// specified subscription and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='tags'>
/// Profile tags
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Profile> UpdateAsync(this IProfilesOperations operations, string resourceGroupName, string profileName, IDictionary<string, string> tags, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, profileName, tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an existing CDN profile with the specified parameters. Deleting a
/// profile will result in the deletion of all of the sub-resources including
/// endpoints, origins and custom domains.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
public static void Delete(this IProfilesOperations operations, string resourceGroupName, string profileName)
{
operations.DeleteAsync(resourceGroupName, profileName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing CDN profile with the specified parameters. Deleting a
/// profile will result in the deletion of all of the sub-resources including
/// endpoints, origins and custom domains.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IProfilesOperations operations, string resourceGroupName, string profileName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, profileName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Generates a dynamic SSO URI used to sign in to the CDN supplemental portal.
/// Supplemnetal portal is used to configure advanced feature capabilities that
/// are not yet available in the Azure portal, such as core reports in a
/// standard profile; rules engine, advanced HTTP reports, and real-time stats
/// and alerts in a premium profile. The SSO URI changes approximately every 10
/// minutes.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
public static SsoUri GenerateSsoUri(this IProfilesOperations operations, string resourceGroupName, string profileName)
{
return operations.GenerateSsoUriAsync(resourceGroupName, profileName).GetAwaiter().GetResult();
}
/// <summary>
/// Generates a dynamic SSO URI used to sign in to the CDN supplemental portal.
/// Supplemnetal portal is used to configure advanced feature capabilities that
/// are not yet available in the Azure portal, such as core reports in a
/// standard profile; rules engine, advanced HTTP reports, and real-time stats
/// and alerts in a premium profile. The SSO URI changes approximately every 10
/// minutes.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SsoUri> GenerateSsoUriAsync(this IProfilesOperations operations, string resourceGroupName, string profileName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GenerateSsoUriWithHttpMessagesAsync(resourceGroupName, profileName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Checks the quota and actual usage of endpoints under the given CDN profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
public static IPage<ResourceUsage> ListResourceUsage(this IProfilesOperations operations, string resourceGroupName, string profileName)
{
return operations.ListResourceUsageAsync(resourceGroupName, profileName).GetAwaiter().GetResult();
}
/// <summary>
/// Checks the quota and actual usage of endpoints under the given CDN profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ResourceUsage>> ListResourceUsageAsync(this IProfilesOperations operations, string resourceGroupName, string profileName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListResourceUsageWithHttpMessagesAsync(resourceGroupName, profileName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new CDN profile with a profile name under the specified
/// subscription and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='profile'>
/// Profile properties needed to create a new profile.
/// </param>
public static Profile BeginCreate(this IProfilesOperations operations, string resourceGroupName, string profileName, Profile profile)
{
return operations.BeginCreateAsync(resourceGroupName, profileName, profile).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new CDN profile with a profile name under the specified
/// subscription and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='profile'>
/// Profile properties needed to create a new profile.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Profile> BeginCreateAsync(this IProfilesOperations operations, string resourceGroupName, string profileName, Profile profile, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, profileName, profile, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing CDN profile with the specified profile name under the
/// specified subscription and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='tags'>
/// Profile tags
/// </param>
public static Profile BeginUpdate(this IProfilesOperations operations, string resourceGroupName, string profileName, IDictionary<string, string> tags)
{
return operations.BeginUpdateAsync(resourceGroupName, profileName, tags).GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing CDN profile with the specified profile name under the
/// specified subscription and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='tags'>
/// Profile tags
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Profile> BeginUpdateAsync(this IProfilesOperations operations, string resourceGroupName, string profileName, IDictionary<string, string> tags, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, profileName, tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an existing CDN profile with the specified parameters. Deleting a
/// profile will result in the deletion of all of the sub-resources including
/// endpoints, origins and custom domains.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
public static void BeginDelete(this IProfilesOperations operations, string resourceGroupName, string profileName)
{
operations.BeginDeleteAsync(resourceGroupName, profileName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing CDN profile with the specified parameters. Deleting a
/// profile will result in the deletion of all of the sub-resources including
/// endpoints, origins and custom domains.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IProfilesOperations operations, string resourceGroupName, string profileName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, profileName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Lists all of the CDN profiles within an Azure subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Profile> ListNext(this IProfilesOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the CDN profiles within an Azure subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Profile>> ListNextAsync(this IProfilesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the CDN profiles within a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Profile> ListByResourceGroupNext(this IProfilesOperations operations, string nextPageLink)
{
return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the CDN profiles within a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Profile>> ListByResourceGroupNextAsync(this IProfilesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Checks the quota and actual usage of endpoints under the given CDN profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ResourceUsage> ListResourceUsageNext(this IProfilesOperations operations, string nextPageLink)
{
return operations.ListResourceUsageNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Checks the quota and actual usage of endpoints under the given CDN profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ResourceUsage>> ListResourceUsageNextAsync(this IProfilesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListResourceUsageNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
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 WebApiProxy.Api.Sample.Areas.HelpPage.ModelDescriptions;
using WebApiProxy.Api.Sample.Areas.HelpPage.Models;
namespace WebApiProxy.Api.Sample.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);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Timing;
using static Content.Shared.Cloning.SharedCloningPodComponent;
using static Robust.Client.UserInterface.Controls.BoxContainer;
namespace Content.Client.Cloning.UI
{
public sealed class CloningPodWindow : DefaultWindow
{
private Dictionary<int, string?> _scanManager;
private readonly BoxContainer _scanList;
public readonly Button CloneButton;
public readonly Button EjectButton;
private CloningScanButton? _selectedButton;
private readonly Label _progressLabel;
private readonly ProgressBar _cloningProgressBar;
private readonly Label _mindState;
private CloningPodBoundUserInterfaceState? _lastUpdate;
public int? SelectedScan;
public CloningPodWindow(Dictionary<int, string?> scanManager)
{
SetSize = MinSize = (250, 300);
_scanManager = scanManager;
Title = Loc.GetString("cloning-pod-window-title");
Contents.AddChild(new BoxContainer
{
Orientation = LayoutOrientation.Vertical,
Children =
{
new ScrollContainer
{
MinSize = new Vector2(200.0f, 0.0f),
VerticalExpand = true,
Children =
{
(_scanList = new BoxContainer
{
Orientation = LayoutOrientation.Vertical
})
}
},
new BoxContainer
{
Orientation = LayoutOrientation.Vertical,
Children =
{
(CloneButton = new Button
{
Text = Loc.GetString("cloning-pod-clone-button")
})
}
},
(_cloningProgressBar = new ProgressBar
{
MinSize = (200, 20),
MinValue = 0,
MaxValue = 120,
Page = 0,
Value = 0.5f,
Children =
{
(_progressLabel = new Label())
}
}),
(EjectButton = new Button
{
Text = Loc.GetString("cloning-pod-eject-body-button")
}),
new BoxContainer
{
Orientation = LayoutOrientation.Horizontal,
Children =
{
new Label()
{
Text = Loc.GetString($"{Loc.GetString("cloning-pod-neural-interface-label")} ")
},
(_mindState = new Label()
{
Text = Loc.GetString("cloning-pod-no-activity-text"),
FontColorOverride = Color.Red
}),
}
}
}
});
BuildCloneList();
}
public void Populate(CloningPodBoundUserInterfaceState state)
{
//Ignore useless updates or we can't interact with the UI
//TODO: come up with a better comparision, probably write a comparator because '.Equals' doesn't work
if (_lastUpdate == null || _lastUpdate.MindIdName.Count != state.MindIdName.Count)
{
_scanManager = state.MindIdName;
BuildCloneList();
}
_lastUpdate = state;
_cloningProgressBar.MaxValue = state.Maximum;
UpdateProgress();
_mindState.Text = Loc.GetString(state.MindPresent ? "cloning-pod-mind-present-text" : "cloning-pod-no-activity-text");
_mindState.FontColorOverride = state.MindPresent ? Color.LimeGreen : Color.Red;
}
protected override void FrameUpdate(FrameEventArgs args)
{
base.FrameUpdate(args);
UpdateProgress();
}
private void UpdateProgress()
{
if (_lastUpdate == null)
return;
float simulatedProgress = _lastUpdate.Progress;
if (_lastUpdate.Progressing)
{
TimeSpan sinceReference = IoCManager.Resolve<IGameTiming>().CurTime - _lastUpdate.ReferenceTime;
simulatedProgress += (float) sinceReference.TotalSeconds;
simulatedProgress = MathHelper.Clamp(simulatedProgress, 0f, _lastUpdate.Maximum);
}
var percentage = simulatedProgress / _cloningProgressBar.MaxValue * 100;
_progressLabel.Text = $"{percentage:0}%";
_cloningProgressBar.Value = simulatedProgress;
}
private void BuildCloneList()
{
_scanList.RemoveAllChildren();
_selectedButton = null;
foreach (var scan in _scanManager)
{
var button = new CloningScanButton
{
Scan = scan.Value ?? string.Empty,
Id = scan.Key
};
button.ActualButton.OnToggled += OnItemButtonToggled;
var entityLabelText = scan.Value;
button.EntityLabel.Text = entityLabelText;
if (scan.Key == SelectedScan)
{
_selectedButton = button;
_selectedButton.ActualButton.Pressed = true;
}
//TODO: replace with body's face
/*var tex = IconComponent.GetScanIcon(scan, resourceCache);
var rect = button.EntityTextureRect;
if (tex != null)
{
rect.Texture = tex.Default;
}
else
{
rect.Dispose();
}
rect.Dispose();
*/
_scanList.AddChild(button);
}
//TODO: set up sort
//_filteredScans.Sort((a, b) => string.Compare(a.ToString(), b.ToString(), StringComparison.Ordinal));
}
private void OnItemButtonToggled(BaseButton.ButtonToggledEventArgs args)
{
var item = (CloningScanButton) args.Button.Parent!;
if (_selectedButton == item)
{
_selectedButton = null;
SelectedScan = null;
return;
}
else if (_selectedButton != null)
{
_selectedButton.ActualButton.Pressed = false;
}
_selectedButton = null;
SelectedScan = null;
_selectedButton = item;
SelectedScan = item.Id;
}
[DebuggerDisplay("cloningbutton {" + nameof(Index) + "}")]
private sealed class CloningScanButton : Control
{
public string Scan { get; set; } = default!;
public int Id { get; set; }
public Button ActualButton { get; private set; }
public Label EntityLabel { get; private set; }
public TextureRect EntityTextureRect { get; private set; }
public int Index { get; set; }
public CloningScanButton()
{
AddChild(ActualButton = new Button
{
HorizontalExpand = true,
VerticalExpand = true,
ToggleMode = true,
});
AddChild(new BoxContainer
{
Orientation = LayoutOrientation.Horizontal,
Children =
{
(EntityTextureRect = new TextureRect
{
MinSize = (32, 32),
HorizontalAlignment = HAlignment.Center,
VerticalAlignment = VAlignment.Center,
Stretch = TextureRect.StretchMode.KeepAspectCentered,
CanShrink = true
}),
(EntityLabel = new Label
{
VerticalAlignment = VAlignment.Center,
HorizontalExpand = true,
Text = string.Empty,
ClipText = true
})
}
});
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ComponentModel;
using System.Runtime;
using System.ServiceModel.Channels;
using System.Text;
using System.Xml;
namespace System.ServiceModel
{
public abstract class HttpBindingBase : Binding, IBindingRuntimePreferences
{
// private BindingElements
private HttpTransportBindingElement _httpTransport;
private HttpsTransportBindingElement _httpsTransport;
private TextMessageEncodingBindingElement _textEncoding;
internal HttpBindingBase()
{
_httpTransport = new HttpTransportBindingElement();
_httpsTransport = new HttpsTransportBindingElement();
_textEncoding = new TextMessageEncodingBindingElement();
_textEncoding.MessageVersion = MessageVersion.Soap11;
_httpsTransport.WebSocketSettings = _httpTransport.WebSocketSettings;
}
[DefaultValue(HttpTransportDefaults.AllowCookies)]
public bool AllowCookies
{
get
{
return _httpTransport.AllowCookies;
}
set
{
_httpTransport.AllowCookies = value;
_httpsTransport.AllowCookies = value;
}
}
[DefaultValue(HttpTransportDefaults.HostNameComparisonMode)]
public HostNameComparisonMode HostNameComparisonMode
{
get
{
return _httpTransport.HostNameComparisonMode;
}
set
{
_httpTransport.HostNameComparisonMode = value;
_httpsTransport.HostNameComparisonMode = value;
}
}
[DefaultValue(TransportDefaults.MaxBufferSize)]
public int MaxBufferSize
{
get
{
return _httpTransport.MaxBufferSize;
}
set
{
_httpTransport.MaxBufferSize = value;
_httpsTransport.MaxBufferSize = value;
}
}
[DefaultValue(TransportDefaults.MaxBufferPoolSize)]
public long MaxBufferPoolSize
{
get
{
return _httpTransport.MaxBufferPoolSize;
}
set
{
_httpTransport.MaxBufferPoolSize = value;
_httpsTransport.MaxBufferPoolSize = value;
}
}
[DefaultValue(TransportDefaults.MaxReceivedMessageSize)]
public long MaxReceivedMessageSize
{
get
{
return _httpTransport.MaxReceivedMessageSize;
}
set
{
_httpTransport.MaxReceivedMessageSize = value;
_httpsTransport.MaxReceivedMessageSize = value;
}
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
return _textEncoding.ReaderQuotas;
}
set
{
if (value == null)
{
throw FxTrace.Exception.ArgumentNull("value");
}
value.CopyTo(_textEncoding.ReaderQuotas);
this.SetReaderQuotas(value);
}
}
public override string Scheme
{
get
{
return this.GetTransport().Scheme;
}
}
public EnvelopeVersion EnvelopeVersion
{
get { return this.GetEnvelopeVersion(); }
}
public Encoding TextEncoding
{
get
{
return _textEncoding.WriteEncoding;
}
set
{
_textEncoding.WriteEncoding = value;
}
}
[DefaultValue(HttpTransportDefaults.TransferMode)]
public TransferMode TransferMode
{
get
{
return _httpTransport.TransferMode;
}
set
{
_httpTransport.TransferMode = value;
_httpsTransport.TransferMode = value;
}
}
public bool UseDefaultWebProxy
{
get
{
return _httpTransport.UseDefaultWebProxy;
}
}
bool IBindingRuntimePreferences.ReceiveSynchronously
{
get { return false; }
}
internal TextMessageEncodingBindingElement TextMessageEncodingBindingElement
{
get
{
return _textEncoding;
}
}
internal abstract BasicHttpSecurity BasicHttpSecurity
{
get;
}
internal WebSocketTransportSettings InternalWebSocketSettings
{
get
{
return _httpTransport.WebSocketSettings;
}
}
internal static bool GetSecurityModeFromTransport(HttpTransportBindingElement http, HttpTransportSecurity transportSecurity, out UnifiedSecurityMode mode)
{
mode = UnifiedSecurityMode.None;
if (http == null)
{
return false;
}
Fx.Assert(http.AuthenticationScheme.IsSingleton(), "authenticationScheme used in an Http(s)ChannelFactory must be a singleton value.");
if (http is HttpsTransportBindingElement)
{
mode = UnifiedSecurityMode.Transport | UnifiedSecurityMode.TransportWithMessageCredential;
BasicHttpSecurity.EnableTransportSecurity((HttpsTransportBindingElement)http, transportSecurity);
}
else if (HttpTransportSecurity.IsDisabledTransportAuthentication(http))
{
mode = UnifiedSecurityMode.Message | UnifiedSecurityMode.None;
}
else if (!BasicHttpSecurity.IsEnabledTransportAuthentication(http, transportSecurity))
{
return false;
}
else
{
mode = UnifiedSecurityMode.TransportCredentialOnly;
}
return true;
}
internal TransportBindingElement GetTransport()
{
Fx.Assert(this.BasicHttpSecurity != null, "this.BasicHttpSecurity should not return null from a derived class.");
BasicHttpSecurity basicHttpSecurity = this.BasicHttpSecurity;
if (basicHttpSecurity.Mode == BasicHttpSecurityMode.Transport || basicHttpSecurity.Mode == BasicHttpSecurityMode.TransportWithMessageCredential)
{
basicHttpSecurity.EnableTransportSecurity(_httpsTransport);
return _httpsTransport;
}
else if (basicHttpSecurity.Mode == BasicHttpSecurityMode.TransportCredentialOnly)
{
basicHttpSecurity.EnableTransportAuthentication(_httpTransport);
return _httpTransport;
}
else
{
// ensure that there is no transport security
basicHttpSecurity.DisableTransportAuthentication(_httpTransport);
return _httpTransport;
}
}
internal abstract EnvelopeVersion GetEnvelopeVersion();
internal virtual void SetReaderQuotas(XmlDictionaryReaderQuotas readerQuotas)
{
}
// In the Win8 profile, some settings for the binding security are not supported.
internal virtual void CheckSettings()
{
BasicHttpSecurity security = this.BasicHttpSecurity;
if (security == null)
{
return;
}
BasicHttpSecurityMode mode = security.Mode;
if (mode == BasicHttpSecurityMode.None)
{
return;
}
else if (mode == BasicHttpSecurityMode.Message || mode == BasicHttpSecurityMode.TransportWithMessageCredential)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Mode", mode)));
}
// Transport.ClientCredentialType = Certificate or InheritedFromHost are not supported.
Fx.Assert(
(mode == BasicHttpSecurityMode.Transport) || (mode == BasicHttpSecurityMode.TransportCredentialOnly),
"Unexpected BasicHttpSecurityMode value: " + mode);
HttpTransportSecurity transport = security.Transport;
if ((transport != null) && ((transport.ClientCredentialType == HttpClientCredentialType.Certificate) || (transport.ClientCredentialType == HttpClientCredentialType.InheritedFromHost)))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Transport.ClientCredentialType", transport.ClientCredentialType)));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Security.Cryptography;
using System.Text;
namespace Mindscape.Raygun4Net.Storage
{
public class IsolatedRaygunOfflineStorage : IRaygunOfflineStorage
{
private string _folderNameHash = null;
private const string RaygunBaseDirectory = "Raygun";
private const string RaygunFileFormat = ".json";
private int _currentFileCounter = 0;
public bool Store(string message, string apiKey)
{
// Do not store invalid messages.
if (string.IsNullOrEmpty(message) || string.IsNullOrEmpty(apiKey))
{
return false;
}
using (var storage = GetIsolatedStorageScope())
{
// Get the directory within isolated storage to hold our data.
var localDirectory = GetLocalDirectory(apiKey);
if (string.IsNullOrEmpty(localDirectory))
{
return false;
}
// Create the destination if it's not there.
if (!EnsureDirectoryExists(storage, localDirectory))
{
return false;
}
var searchPattern = Path.Combine(localDirectory, $"*{RaygunFileFormat}");
var maxReports = Math.Min(RaygunSettings.Settings.MaxCrashReportsStoredOffline, RaygunSettings.MaxCrashReportsStoredOfflineHardLimit);
// We can only save the report if we have not reached the report count limit.
if (storage.GetFileNames(searchPattern).Length >= maxReports)
{
return false;
}
// Build up our file information.
var filename = GetUniqueAscendingJsonName();
var localFilePath = Path.Combine(localDirectory, filename);
// Write the contents to storage.
using (var stream = new IsolatedStorageFileStream(localFilePath, FileMode.OpenOrCreate, FileAccess.Write, storage))
{
using (var writer = new StreamWriter(stream, Encoding.Unicode))
{
writer.Write(message);
writer.Flush();
writer.Close();
}
}
}
return true;
}
private bool EnsureDirectoryExists(IsolatedStorageFile storage, string localDirectory)
{
bool success = true;
try
{
storage.CreateDirectory(localDirectory);
}
catch
{
success = false;
}
return success;
}
public IList<IRaygunFile> FetchAll(string apiKey)
{
var files = new List<IRaygunFile>();
if (string.IsNullOrEmpty(apiKey))
{
return files;
}
using (var storage = GetIsolatedStorageScope())
{
// Get the directory within isolated storage to hold our data.
var localDirectory = GetLocalDirectory(apiKey);
if (string.IsNullOrEmpty(localDirectory))
{
return files;
}
// We must ensure the local directory exists before we look for files..
if (!EnsureDirectoryExists(storage, localDirectory))
{
return files;
}
// Look for all the files within our working local directory.
var fileNames = storage.GetFileNames(Path.Combine(localDirectory, $"*{RaygunFileFormat}"));
// Take action on each file.
foreach (var name in fileNames)
{
var stream = new IsolatedStorageFileStream(Path.Combine(localDirectory, name), FileMode.Open, storage);
// Read the contents and put it into our own structure.
using (var reader = new StreamReader(stream))
{
string contents = reader.ReadToEnd();
files.Add(new RaygunFile()
{
Name = name,
Contents = contents
});
}
}
}
return files;
}
public bool Remove(string name, string apiKey)
{
// We cannot remove based on invalid params.
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(apiKey))
{
return false;
}
using (var storage = GetIsolatedStorageScope())
{
// Get a list of the current files in storage.
var localDirectory = GetLocalDirectory(apiKey);
if (string.IsNullOrEmpty(localDirectory))
{
return false;
}
var localFilePath = Path.Combine(localDirectory, name);
// We must ensure the local file exists before delete it.
if (storage.GetFileNames(localFilePath)?.Length == 0)
{
return false;
}
storage.DeleteFile(localFilePath);
return true;
}
}
private IsolatedStorageFile GetIsolatedStorageScope()
{
return AppDomain.CurrentDomain?.ActivationContext != null ?
IsolatedStorageFile.GetUserStoreForApplication() :
IsolatedStorageFile.GetUserStoreForAssembly();
}
private string GetLocalDirectory(string apiKey)
{
// Attempt to perform the hash operation once.
if (string.IsNullOrEmpty(_folderNameHash))
{
_folderNameHash = PerformHash(apiKey);
}
// If successful return the correct path.
return (_folderNameHash == null) ? null : Path.Combine(RaygunBaseDirectory, _folderNameHash);
}
private string PerformHash(string input)
{
// Use input string to calculate MD5 hash
using (var hasher = MD5.Create())
{
var inputBytes = Encoding.ASCII.GetBytes(input);
var hashBytes = hasher.ComputeHash(inputBytes);
// Convert the byte array to hexadecimal string
var builder = new StringBuilder();
foreach (var hashByte in hashBytes)
{
builder.Append(hashByte.ToString("X2"));
}
return builder.ToString();
}
}
private string GetUniqueAscendingJsonName()
{
return $"{DateTime.UtcNow.Ticks}-{_currentFileCounter++}-{Guid.NewGuid().ToString()}{RaygunFileFormat}";
}
}
}
| |
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Android.Content;
using Android.Content.PM;
using Android.Graphics;
using Android.OS;
using Android.Provider;
using MediaPicker.Forms.Plugin.Abstractions;
using MediaPicker.Forms.Plugin.Droid;
using Xamarin.Forms;
using Application = Android.App.Application;
[assembly: Dependency(typeof (MediaPickerImplementation))]
namespace MediaPicker.Forms.Plugin.Droid
{
/// <summary>
/// MediaPicker Implementation
/// </summary>
public class MediaPickerImplementation : IMediaPicker
{
private TaskCompletionSource<MediaFile> _completionSource;
private int _requestId;
/// <summary>
/// Initializes a new instance of the <see cref="MediaPicker" /> class.
/// </summary>
public MediaPickerImplementation()
{
IsPhotosSupported = true;
IsVideosSupported = true;
}
private static Context Context
{
get { return Application.Context; }
}
public byte[] ResizeImage(byte[] imageData, float width, float height)
{
// Load the bitmap
var originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length);
var resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int) width, (int) height, false);
using (var ms = new MemoryStream())
{
resizedImage.Compress(Bitmap.CompressFormat.Jpeg, 100, ms);
return ms.ToArray();
}
}
public Stream ResizeImage(Stream imageData, float width, float height)
{
// Load the bitmap
var originalImage = BitmapFactory.DecodeStream(imageData);
var resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int) width, (int) height, false);
using (var ms = new MemoryStream())
{
resizedImage.Compress(Bitmap.CompressFormat.Jpeg, 100, ms);
return ms;
}
}
/// <summary>
/// Gets a value indicating whether this instance is camera available.
/// </summary>
/// <value><c>true</c> if this instance is camera available; otherwise, <c>false</c>.</value>
public bool IsCameraAvailable
{
get
{
var isCameraAvailable = Context.PackageManager.HasSystemFeature(PackageManager.FeatureCamera);
if (Build.VERSION.SdkInt >= BuildVersionCodes.Gingerbread)
{
isCameraAvailable |= Context.PackageManager.HasSystemFeature(PackageManager.FeatureCameraFront);
}
return isCameraAvailable;
}
}
/// <summary>
/// Gets a value indicating whether this instance is photos supported.
/// </summary>
/// <value><c>true</c> if this instance is photos supported; otherwise, <c>false</c>.</value>
public bool IsPhotosSupported { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is videos supported.
/// </summary>
/// <value><c>true</c> if this instance is videos supported; otherwise, <c>false</c>.</value>
public bool IsVideosSupported { get; private set; }
/// <summary>
/// Select a picture from library.
/// </summary>
/// <param name="options">The storage options.</param>
/// <returns>Task with a return type of MediaFile.</returns>
/// <exception cref="System.NotSupportedException">Throws an exception if feature is not supported.</exception>
public Task<MediaFile> SelectPhotoAsync(CameraMediaStorageOptions options)
{
if (!IsCameraAvailable)
{
throw new NotSupportedException();
}
options.VerifyOptions();
return TakeMediaAsync("image/*", Intent.ActionPick, options);
}
/// <summary>
/// Takes the picture.
/// </summary>
/// <param name="options">The storage options.</param>
/// <returns>Task with a return type of MediaFile.</returns>
/// <exception cref="System.NotSupportedException">Throws an exception if feature is not supported.</exception>
public Task<MediaFile> TakePhotoAsync(CameraMediaStorageOptions options)
{
if (!IsCameraAvailable)
{
throw new NotSupportedException("Camera is not available.");
}
options.VerifyOptions();
return TakeMediaAsync("image/*", MediaStore.ActionImageCapture, options);
}
/// <summary>
/// Selects the video asynchronous.
/// </summary>
/// <param name="options">Video storage options.</param>
/// <returns>Task with a return type of MediaFile.</returns>
/// <exception cref="System.NotSupportedException">Throws an exception if feature is not supported.</exception>
public Task<MediaFile> SelectVideoAsync(VideoMediaStorageOptions options)
{
if (!IsCameraAvailable)
{
throw new NotSupportedException();
}
options.VerifyOptions();
return TakeMediaAsync("video/*", Intent.ActionPick, options);
}
/// <summary>
/// Takes the video asynchronous.
/// </summary>
/// <param name="options">The options.</param>
/// <returns>Task with a return type of MediaFile.</returns>
/// <exception cref="System.NotSupportedException">Throws an exception if feature is not supported.</exception>
public Task<MediaFile> TakeVideoAsync(VideoMediaStorageOptions options)
{
if (!IsCameraAvailable)
{
throw new NotSupportedException();
}
options.VerifyOptions();
return TakeMediaAsync("video/*", MediaStore.ActionVideoCapture, options);
}
/// <summary>
/// Gets or sets the event that fires when media has been selected.
/// </summary>
/// <value>The on photo selected.</value>
public EventHandler<MediaPickerArgs> OnMediaSelected { get; set; }
/// <summary>
/// Gets or sets the on error.
/// </summary>
/// <value>The on error.</value>
public EventHandler<MediaPickerErrorArgs> OnError { get; set; }
/// <summary>
/// Used for registration with dependency service
/// </summary>
public static void Init()
{
}
/// <summary>
/// Creates the media intent.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="type">The type of intent.</param>
/// <param name="action">The action.</param>
/// <param name="options">The options.</param>
/// <param name="tasked">if set to <c>true</c> [tasked].</param>
/// <returns>Intent to create media.</returns>
private Intent CreateMediaIntent(int id, string type, string action, MediaStorageOptions options,
bool tasked = true)
{
var pickerIntent = new Intent(Context, typeof (MediaPickerActivity));
pickerIntent.SetFlags(ActivityFlags.NewTask);
pickerIntent.PutExtra(MediaPickerActivity.ExtraId, id);
pickerIntent.PutExtra(MediaPickerActivity.ExtraType, type);
pickerIntent.PutExtra(MediaPickerActivity.ExtraAction, action);
pickerIntent.PutExtra(MediaPickerActivity.ExtraTasked, tasked);
if (options != null)
{
pickerIntent.PutExtra(MediaPickerActivity.ExtraPath, options.Directory);
pickerIntent.PutExtra(MediaStore.Images.ImageColumns.Title, options.Name);
if (options.MaxPixelDimension.HasValue)
pickerIntent.PutExtra(MediaPickerActivity.ExtraMaxPixelDimension, options.MaxPixelDimension.Value);
if (options.PercentQuality.HasValue)
pickerIntent.PutExtra(MediaPickerActivity.ExtraPercentQuality, options.PercentQuality.Value);
var vidOptions = options as VideoMediaStorageOptions;
if (vidOptions != null)
{
pickerIntent.PutExtra(MediaStore.ExtraDurationLimit, (int) vidOptions.DesiredLength.TotalSeconds);
pickerIntent.PutExtra(MediaStore.ExtraVideoQuality, (int) vidOptions.Quality);
}
}
return pickerIntent;
}
/// <summary>
/// Gets the request identifier.
/// </summary>
/// <returns>Request id as integer.</returns>
private int GetRequestId()
{
var id = _requestId;
if (_requestId == int.MaxValue)
{
_requestId = 0;
}
else
{
_requestId++;
}
return id;
}
/// <summary>
/// Takes the media asynchronous.
/// </summary>
/// <param name="type">The type of intent.</param>
/// <param name="action">The action.</param>
/// <param name="options">The options.</param>
/// <returns>Task with a return type of MediaFile.</returns>
/// <exception cref="System.InvalidOperationException">Only one operation can be active at a time.</exception>
private Task<MediaFile> TakeMediaAsync(string type, string action, MediaStorageOptions options)
{
var id = GetRequestId();
var ntcs = new TaskCompletionSource<MediaFile>(id);
if (Interlocked.CompareExchange(ref _completionSource, ntcs, null) != null)
{
throw new InvalidOperationException("Only one operation can be active at a time");
}
Context.StartActivity(CreateMediaIntent(id, type, action, options));
EventHandler<MediaPickedEventArgs> handler = null;
handler = (s, e) =>
{
var tcs = Interlocked.Exchange(ref _completionSource, null);
MediaPickerActivity.MediaPicked -= handler;
if (e.RequestId != id)
{
return;
}
if (e.Error != null)
{
tcs.SetException(e.Error);
}
else if (e.IsCanceled)
{
tcs.SetCanceled();
}
else
{
tcs.SetResult(e.Media);
}
};
MediaPickerActivity.MediaPicked += handler;
return ntcs.Task;
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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.Reflection;
using System.Text;
using Nini.Config;
using OpenMetaverse;
using System.Threading;
using log4net;
using OpenMetaverse.Imaging;
using CSJ2K;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Region.CoreModules.Agent.TextureSender;
namespace OpenSim.Region.CoreModules.Agent.TextureSender
{
public class CSJ2KDecoderModule : IRegionModule, IJ2KDecoder
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>Cache for decoded layer data</summary>
private J2KDecodeFileCache fCache;
/// <summary>List of client methods to notify of results of decode</summary>
private readonly Dictionary<UUID, List<DecodedCallback>> m_notifyList = new Dictionary<UUID, List<DecodedCallback>>();
/// <summary>Reference to a scene (doesn't matter which one as long as it can load the cache module)</summary>
private Scene m_scene;
#region IRegionModule
public CSJ2KDecoderModule()
{
}
public string Name { get { return "CSJ2KDecoderModule"; } }
public bool IsSharedModule { get { return true; } }
public void Initialise(Scene scene, IConfigSource source)
{
if (m_scene == null)
m_scene = scene;
bool useFileCache = false;
IConfig myConfig = source.Configs["J2KDecoder"];
if (myConfig != null)
{
if (myConfig.GetString("J2KDecoderModule", Name) != Name)
return;
useFileCache = myConfig.GetBoolean("J2KDecoderFileCacheEnabled", false);
}
else
{
m_log.DebugFormat("[J2K DECODER MODULE] No decoder specified, Using defaults");
}
m_log.DebugFormat("[J2K DECODER MODULE] Using {0} decoder. File Cache is {1}",
Name, (useFileCache ? "enabled" : "disabled"));
fCache = new J2KDecodeFileCache(useFileCache, J2KDecodeFileCache.CacheFolder);
scene.RegisterModuleInterface<IJ2KDecoder>(this);
}
public void PostInitialise()
{
}
public void Close()
{
}
#endregion IRegionModule
#region IJ2KDecoder
public void BeginDecode(UUID assetID, byte[] j2kData, DecodedCallback callback)
{
OpenJPEG.J2KLayerInfo[] result;
bool decodedSuccessfully = false;
lock (fCache)
{
decodedSuccessfully = fCache.TryLoadCacheForAsset(assetID, out result);
}
if (decodedSuccessfully)
{
callback(assetID, result);
return;
}
// Not cached, we need to decode it.
// Add to notify list and start decoding.
// Next request for this asset while it's decoding will only be added to the notify list
// once this is decoded, requests will be served from the cache and all clients in the notifylist will be updated
bool decode = false;
lock (m_notifyList)
{
if (m_notifyList.ContainsKey(assetID))
{
m_notifyList[assetID].Add(callback);
}
else
{
List<DecodedCallback> notifylist = new List<DecodedCallback>();
notifylist.Add(callback);
m_notifyList.Add(assetID, notifylist);
decode = true;
}
}
// Do Decode!
if (decode)
Decode(assetID, j2kData);
}
public bool Decode(UUID assetID, byte[] j2kData)
{
OpenJPEG.J2KLayerInfo[] layers;
return Decode(assetID, j2kData, out layers);
}
public bool Decode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers)
{
bool decodedSuccessfully = true;
lock (fCache)
{
decodedSuccessfully = fCache.TryLoadCacheForAsset(assetID, out layers);
}
if (!decodedSuccessfully)
decodedSuccessfully = DoJ2KDecode(assetID, j2kData, out layers);
// Notify Interested Parties
lock (m_notifyList)
{
if (m_notifyList.ContainsKey(assetID))
{
foreach (DecodedCallback d in m_notifyList[assetID])
{
if (d != null)
d.DynamicInvoke(assetID, layers);
}
m_notifyList.Remove(assetID);
}
}
return (decodedSuccessfully);
}
#endregion IJ2KDecoder
/// <summary>
/// Decode Jpeg2000 Asset Data
/// </summary>
/// <param name="assetID">UUID of Asset</param>
/// <param name="j2kData">JPEG2000 data</param>
/// <param name="layers">layer data</param>
/// <param name="components">number of components</param>
/// <returns>true if decode was successful. false otherwise.</returns>
private bool DoJ2KDecode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers)
{
bool decodedSuccessfully = true;
int DecodeTime = Environment.TickCount;
layers = new OpenJPEG.J2KLayerInfo[0]; // Dummy result for if it fails. Informs that there's only full quality
try
{
using (MemoryStream ms = new MemoryStream(j2kData))
{
List<int> layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(ms);
if (layerStarts != null && layerStarts.Count > 0)
{
layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count];
for (int i = 0; i < layerStarts.Count; i++)
{
OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo();
if (i == 0)
layer.Start = 0;
else
layer.Start = layerStarts[i];
if (i == layerStarts.Count - 1)
layer.End = j2kData.Length;
else
layer.End = layerStarts[i + 1] - 1;
layers[i] = layer;
}
}
}
}
catch (Exception ex)
{
m_log.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " + ex.Message);
decodedSuccessfully = false;
}
if (layers.Length == 0)
{
m_log.Warn("[J2KDecoderModule]: Failed to decode layer data for texture " + assetID + ", guessing sane defaults");
// Layer decoding completely failed. Guess at sane defaults for the layer boundaries
layers = CreateDefaultLayers(j2kData.Length);
decodedSuccessfully = false;
}
else
{
int elapsed = Environment.TickCount - DecodeTime;
if (elapsed >= 50)
m_log.InfoFormat("[J2KDecoderModule]: {0} Decode Time: {1}", elapsed, assetID);
// Cache Decoded layers
fCache.SaveCacheForAsset(assetID, layers);
}
return decodedSuccessfully;
}
private OpenJPEG.J2KLayerInfo[] CreateDefaultLayers(int j2kLength)
{
OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[5];
for (int i = 0; i < layers.Length; i++)
layers[i] = new OpenJPEG.J2KLayerInfo();
// These default layer sizes are based on a small sampling of real-world texture data
// with extra padding thrown in for good measure. This is a worst case fallback plan
// and may not gracefully handle all real world data
layers[0].Start = 0;
layers[1].Start = (int)((float)j2kLength * 0.02f);
layers[2].Start = (int)((float)j2kLength * 0.05f);
layers[3].Start = (int)((float)j2kLength * 0.20f);
layers[4].Start = (int)((float)j2kLength * 0.50f);
layers[0].End = layers[1].Start - 1;
layers[1].End = layers[2].Start - 1;
layers[2].End = layers[3].Start - 1;
layers[3].End = layers[4].Start - 1;
layers[4].End = j2kLength;
return layers;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel;
using Csla.Validation;
namespace Northwind.CSLA.Library
{
/// <summary>
/// CustomerCustomerCustomerDemos Generated by MyGeneration using the CSLA Object Mapping template
/// </summary>
[Serializable()]
[TypeConverter(typeof(CustomerCustomerCustomerDemosConverter))]
public partial class CustomerCustomerCustomerDemos : BusinessListBase<CustomerCustomerCustomerDemos, CustomerCustomerCustomerDemo>, ICustomTypeDescriptor, IVEHasBrokenRules
{
#region Business Methods
private string _ErrorMessage = string.Empty;
public string ErrorMessage
{
get { return _ErrorMessage; }
}
// Many To Many
public CustomerCustomerCustomerDemo this[CustomerDemographic myCustomerDemographic]
{
get
{
foreach (CustomerCustomerCustomerDemo customerCustomerDemo in this)
if (customerCustomerDemo.CustomerTypeID == myCustomerDemographic.CustomerTypeID)
return customerCustomerDemo;
return null;
}
}
public new System.Collections.Generic.IList<CustomerCustomerCustomerDemo> Items
{
get { return base.Items; }
}
public CustomerCustomerCustomerDemo GetItem(CustomerDemographic myCustomerDemographic)
{
foreach (CustomerCustomerCustomerDemo customerCustomerDemo in this)
if (customerCustomerDemo.CustomerTypeID == myCustomerDemographic.CustomerTypeID)
return customerCustomerDemo;
return null;
}
public CustomerCustomerCustomerDemo Add(CustomerDemographic myCustomerDemographic)// Many to Many with required fields
{
if (!Contains(myCustomerDemographic))
{
CustomerCustomerCustomerDemo customerCustomerDemo = CustomerCustomerCustomerDemo.New(myCustomerDemographic);
this.Add(customerCustomerDemo);
return customerCustomerDemo;
}
else
throw new InvalidOperationException("customerCustomerDemo already exists");
}
public void Remove(CustomerDemographic myCustomerDemographic)
{
foreach (CustomerCustomerCustomerDemo customerCustomerDemo in this)
{
if (customerCustomerDemo.CustomerTypeID == myCustomerDemographic.CustomerTypeID)
{
Remove(customerCustomerDemo);
break;
}
}
}
public bool Contains(CustomerDemographic myCustomerDemographic)
{
foreach (CustomerCustomerCustomerDemo customerCustomerDemo in this)
if (customerCustomerDemo.CustomerTypeID == myCustomerDemographic.CustomerTypeID)
return true;
return false;
}
public bool ContainsDeleted(CustomerDemographic myCustomerDemographic)
{
foreach (CustomerCustomerCustomerDemo customerCustomerDemo in DeletedList)
if (customerCustomerDemo.CustomerTypeID == myCustomerDemographic.CustomerTypeID)
return true;
return false;
}
#endregion
#region ValidationRules
public IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules=null;
foreach(CustomerCustomerCustomerDemo customerCustomerCustomerDemo in this)
if ((hasBrokenRules = customerCustomerCustomerDemo.HasBrokenRules) != null) return hasBrokenRules;
return hasBrokenRules;
}
}
public BrokenRulesCollection BrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null);
}
}
#endregion
#region Factory Methods
internal static CustomerCustomerCustomerDemos New()
{
return new CustomerCustomerCustomerDemos();
}
internal static CustomerCustomerCustomerDemos Get(SafeDataReader dr)
{
return new CustomerCustomerCustomerDemos(dr);
}
public static CustomerCustomerCustomerDemos GetByCustomerID(string customerID)
{
try
{
return DataPortal.Fetch<CustomerCustomerCustomerDemos>(new CustomerIDCriteria(customerID));
}
catch (Exception ex)
{
throw new DbCslaException("Error on CustomerCustomerCustomerDemos.GetByCustomerID", ex);
}
}
private CustomerCustomerCustomerDemos()
{
MarkAsChild();
}
internal CustomerCustomerCustomerDemos(SafeDataReader dr)
{
MarkAsChild();
Fetch(dr);
}
#endregion
#region Data Access Portal
// called to load data from the database
private void Fetch(SafeDataReader dr)
{
this.RaiseListChangedEvents = false;
while (dr.Read())
this.Add(CustomerCustomerCustomerDemo.Get(dr));
this.RaiseListChangedEvents = true;
}
[Serializable()]
private class CustomerIDCriteria
{
public CustomerIDCriteria(string customerID)
{
_CustomerID = customerID;
}
private string _CustomerID;
public string CustomerID
{
get { return _CustomerID; }
set { _CustomerID = value; }
}
}
private void DataPortal_Fetch(CustomerIDCriteria criteria)
{
this.RaiseListChangedEvents = false;
Database.LogInfo("CustomerCustomerCustomerDemos.DataPortal_FetchCustomerID", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "getCustomerCustomerDemosByCustomerID";
cm.Parameters.AddWithValue("@CustomerID", criteria.CustomerID);
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
while (dr.Read()) this.Add(new CustomerCustomerCustomerDemo(dr));
}
}
}
}
catch (Exception ex)
{
Database.LogException("CustomerCustomerCustomerDemos.DataPortal_FetchCustomerID", ex);
throw new DbCslaException("CustomerCustomerCustomerDemos.DataPortal_Fetch", ex);
}
this.RaiseListChangedEvents = true;
}
internal void Update(Customer customer)
{
this.RaiseListChangedEvents = false;
try
{
// update (thus deleting) any deleted child objects
foreach (CustomerCustomerCustomerDemo obj in DeletedList)
obj.Delete();// TODO: Should this be SQLDelete
// now that they are deleted, remove them from memory too
DeletedList.Clear();
// add/update any current child objects
foreach (CustomerCustomerCustomerDemo obj in this)
{
if (obj.IsNew)
obj.Insert(customer);
else
obj.Update(customer);
}
}
finally
{
this.RaiseListChangedEvents = true;
}
}
#endregion
#region ICustomTypeDescriptor impl
public String GetClassName()
{ return TypeDescriptor.GetClassName(this, true); }
public AttributeCollection GetAttributes()
{ return TypeDescriptor.GetAttributes(this, true); }
public String GetComponentName()
{ return TypeDescriptor.GetComponentName(this, true); }
public TypeConverter GetConverter()
{ return TypeDescriptor.GetConverter(this, true); }
public EventDescriptor GetDefaultEvent()
{ return TypeDescriptor.GetDefaultEvent(this, true); }
public PropertyDescriptor GetDefaultProperty()
{ return TypeDescriptor.GetDefaultProperty(this, true); }
public object GetEditor(Type editorBaseType)
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); }
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{ return TypeDescriptor.GetEvents(this, attributes, true); }
public EventDescriptorCollection GetEvents()
{ return TypeDescriptor.GetEvents(this, true); }
public object GetPropertyOwner(PropertyDescriptor pd)
{ return this; }
/// <summary>
/// Called to get the properties of this type. Returns properties with certain
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{
// Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list
for (int i = 0; i < this.Items.Count; i++)
{
// Create a property descriptor for the item and add to the property descriptor collection
CustomerCustomerCustomerDemosPropertyDescriptor pd = new CustomerCustomerCustomerDemosPropertyDescriptor(this, i);
pds.Add(pd);
}
// return the property descriptor collection
return pds;
}
#endregion
} // Class
#region Property Descriptor
/// <summary>
/// Summary description for CollectionPropertyDescriptor.
/// </summary>
public partial class CustomerCustomerCustomerDemosPropertyDescriptor : vlnListPropertyDescriptor
{
private CustomerCustomerCustomerDemo Item { get { return (CustomerCustomerCustomerDemo) _Item;} }
public CustomerCustomerCustomerDemosPropertyDescriptor(CustomerCustomerCustomerDemos collection, int index):base(collection, index){;}
}
#endregion
#region Converter
internal class CustomerCustomerCustomerDemosConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is CustomerCustomerCustomerDemos)
{
// Return department and department role separated by comma.
return ((CustomerCustomerCustomerDemos) value).Items.Count.ToString() + " CustomerCustomerDemos";
}
return base.ConvertTo(context, culture, value, destType);
}
}
#endregion
} // Namespace
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.HDInsight;
using Microsoft.Azure.Management.HDInsight.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.HDInsight
{
/// <summary>
/// The HDInsight Management Client.
/// </summary>
public partial class HDInsightManagementClient : ServiceClient<HDInsightManagementClient>, IHDInsightManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IClusterOperations _clusters;
/// <summary>
/// Contains all the cluster operations.
/// </summary>
public virtual IClusterOperations Clusters
{
get { return this._clusters; }
}
/// <summary>
/// Initializes a new instance of the HDInsightManagementClient class.
/// </summary>
public HDInsightManagementClient()
: base()
{
this._clusters = new ClusterOperations(this);
this._apiVersion = "2015-03-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the HDInsightManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public HDInsightManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the HDInsightManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public HDInsightManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the HDInsightManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public HDInsightManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._clusters = new ClusterOperations(this);
this._apiVersion = "2015-03-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the HDInsightManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public HDInsightManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the HDInsightManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public HDInsightManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// HDInsightManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of HDInsightManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<HDInsightManagementClient> client)
{
base.Clone(client);
if (client is HDInsightManagementClient)
{
HDInsightManagementClient clonedClient = ((HDInsightManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The azure async operation response.
/// </returns>
public async Task<OperationResource> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("User-Agent", "ARM SDK v1.0.7-preview");
httpRequest.Headers.Add("x-ms-version", "2015-03-01-preview");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResource result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OperationResource();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
AsyncOperationState statusInstance = ((AsyncOperationState)Enum.Parse(typeof(AsyncOperationState), ((string)statusValue), true));
result.State = statusInstance;
}
JToken errorValue = responseDoc["error"];
if (errorValue != null && errorValue.Type != JTokenType.Null)
{
ErrorInfo errorInstance = new ErrorInfo();
result.ErrorInfo = errorInstance;
JToken codeValue = errorValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = errorValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// LevelUpScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using RolePlayingGameData;
#endregion
namespace RolePlaying
{
/// <summary>
/// Displays all the players that have leveled up
/// </summary>
class LevelUpScreen : GameScreen
{
private int index;
private List<Player> leveledUpPlayers;
private List<Spell> spellList = new List<Spell>();
#region Graphics content
private Texture2D backTexture;
private Texture2D selectIconTexture;
private Texture2D portraitBackTexture;
private Texture2D headerTexture;
private Texture2D lineTexture;
private Texture2D scrollUpTexture;
private Texture2D scrollDownTexture;
private Texture2D fadeTexture;
private Color color;
private Color colorName = new Color(241, 173, 10);
private Color colorClass = new Color(207, 130, 42);
private Color colorText = new Color(76, 49, 8);
#endregion
#region Positions
private Vector2 backgroundPosition;
private Vector2 textPosition;
private Vector2 levelPosition;
private Vector2 iconPosition;
private Vector2 linePosition;
private Vector2 selectPosition;
private Vector2 selectIconPosition;
private Vector2 screenSize;
private Vector2 titlePosition;
private Vector2 scrollUpPosition;
private Vector2 scrollDownPosition;
private Vector2 spellUpgradePosition;
private Vector2 portraitPosition;
private Vector2 playerNamePosition;
private Vector2 playerLvlPosition;
private Vector2 playerClassPosition;
private Vector2 topLinePosition;
private Vector2 playerDamagePosition;
private Vector2 headerPosition;
private Vector2 backPosition;
private Rectangle fadeDest;
#endregion
#region Dialog Strings
private readonly string titleText = "Level Up";
private readonly string selectString = "Continue";
#endregion
#region Scrolling Text Navigation
private int startIndex;
private int endIndex;
private const int maxLines = 3;
private static readonly float lineSpacing = 74 * ScaledVector2.ScaleFactor;
#endregion
#region Initialization
/// <summary>
/// Constructs a new LevelUpScreen object.
/// </summary>
/// <param name="leveledUpPlayers"></param>
public LevelUpScreen(List<Player> leveledUpPlayers)
{
if ((leveledUpPlayers == null) || (leveledUpPlayers.Count <= 0))
{
throw new ArgumentNullException("leveledUpPlayers");
}
this.IsPopup = true;
this.leveledUpPlayers = leveledUpPlayers;
index = 0;
GetSpellList();
AudioManager.PushMusic("LevelUp",false);
this.Exiting += new EventHandler(LevelUpScreen_Exiting);
}
void LevelUpScreen_Exiting(object sender, EventArgs e)
{
AudioManager.PopMusic();
}
/// <summary>
/// Load the graphics content
/// </summary>
/// <param name="sprite">SpriteBatch</param>
/// <param name="screenWidth">Width of the screen</param>
/// <param name="screenHeight">Height of the screen</param>
public override void LoadContent()
{
ContentManager content = ScreenManager.Game.Content;
backTexture =
content.Load<Texture2D>(@"Textures\GameScreens\PopupScreen");
selectIconTexture =
content.Load<Texture2D>(@"Textures\Buttons\rpgbtn");
portraitBackTexture =
content.Load<Texture2D>(@"Textures\GameScreens\PlayerSelected");
headerTexture =
content.Load<Texture2D>(@"Textures\GameScreens\Caption");
lineTexture =
content.Load<Texture2D>(@"Textures\GameScreens\SeparationLine");
scrollUpTexture =
content.Load<Texture2D>(@"Textures\GameScreens\ScrollUp");
scrollDownTexture =
content.Load<Texture2D>(@"Textures\GameScreens\ScrollDown");
fadeTexture =
content.Load<Texture2D>(@"Textures\GameScreens\FadeScreen");
Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
backgroundPosition.X = (viewport.Width - backTexture.Width * ScaledVector2.DrawFactor ) / 2;
backgroundPosition.Y = (viewport.Height - backTexture.Height * ScaledVector2.DrawFactor) / 2;
screenSize = new Vector2(viewport.Width, viewport.Height);
fadeDest = new Rectangle(0, 0, viewport.Width, viewport.Height);
titlePosition.X = (screenSize.X -
Fonts.HeaderFont.MeasureString(titleText).X) / 2;
titlePosition.Y = backgroundPosition.Y + lineSpacing;
selectIconPosition.X = screenSize.X / 2 + 185 * ScaledVector2.ScaleFactor;
selectIconPosition.Y = backgroundPosition.Y + 520f * ScaledVector2.ScaleFactor;
selectPosition.X = selectIconPosition.X -
Fonts.ButtonNamesFont.MeasureString(selectString).X - 10f * ScaledVector2.ScaleFactor;
selectPosition.Y = selectIconPosition.Y;
portraitPosition = backgroundPosition + ScaledVector2.GetScaledVector(143f, 155f);
backPosition = backgroundPosition + ScaledVector2.GetScaledVector(140f, 120f);
playerNamePosition = backgroundPosition + ScaledVector2.GetScaledVector(220f, 130f);
playerClassPosition = backgroundPosition + ScaledVector2.GetScaledVector(220f, 155f);
playerLvlPosition = backgroundPosition + ScaledVector2.GetScaledVector(220f, 175f);
topLinePosition = backgroundPosition + ScaledVector2.GetScaledVector(380f, 160f);
textPosition = backgroundPosition + ScaledVector2.GetScaledVector(335f, 0);
levelPosition = backgroundPosition + ScaledVector2.GetScaledVector(540f, 320f);
iconPosition = backgroundPosition + ScaledVector2.GetScaledVector(155f, 303f);
linePosition = backgroundPosition + ScaledVector2.GetScaledVector(142f, 285f);
scrollUpPosition = backgroundPosition + ScaledVector2.GetScaledVector(810f, 300f);
scrollDownPosition = backgroundPosition + ScaledVector2.GetScaledVector(810f, 480f);
playerDamagePosition = backgroundPosition + ScaledVector2.GetScaledVector(560f, 130f);
spellUpgradePosition = backgroundPosition + ScaledVector2.GetScaledVector(380f, 250f);
headerPosition = backgroundPosition + ScaledVector2.GetScaledVector(120f, 248f);
}
#endregion
#region Updating
/// <summary>
/// Handles user input.
/// </summary>
public override void HandleInput()
{
bool okClicked = false;
if (InputManager.IsButtonClicked(new Rectangle(
(int)selectIconPosition.X, (int)selectIconPosition.Y,
(int)(selectIconTexture.Width * ScaledVector2.DrawFactor),
(int)(selectIconTexture.Height * ScaledVector2.DrawFactor))))
{
okClicked = true;
}
// exit without bothering to see the rest
if (InputManager.IsActionTriggered(InputManager.Action.Back))
{
ExitScreen();
}
// advance to the next player to have leveled up
else if (okClicked)
{
if (leveledUpPlayers.Count <= 0)
{
// no players at all
ExitScreen();
return;
}
if (index < leveledUpPlayers.Count - 1)
{
// move to the next player
index++;
GetSpellList();
}
else
{
// no more players
ExitScreen();
return;
}
}
// Scroll up
else if (InputManager.IsActionTriggered(InputManager.Action.CursorUp))
{
if (startIndex > 0)
{
startIndex--;
endIndex--;
}
}
// Scroll down
else if (InputManager.IsActionTriggered(InputManager.Action.CursorDown))
{
if (startIndex < spellList.Count - maxLines)
{
endIndex++;
startIndex++;
}
}
}
/// <summary>
/// Get the spell list
/// </summary>
private void GetSpellList()
{
spellList.Clear();
if ((leveledUpPlayers.Count > 0) &&
(leveledUpPlayers[index].CharacterLevel <=
leveledUpPlayers[index].CharacterClass.LevelEntries.Count))
{
List<Spell> newSpells =
leveledUpPlayers[index].CharacterClass.LevelEntries[
leveledUpPlayers[index].CharacterLevel - 1].Spells;
if ((newSpells == null) || (newSpells.Count <= 0))
{
startIndex = 0;
endIndex = 0;
}
else
{
spellList.AddRange(leveledUpPlayers[index].Spells);
spellList.RemoveAll(delegate(Spell spell)
{
return !newSpells.Exists(delegate(Spell newSpell)
{
return spell.AssetName == newSpell.AssetName;
});
});
startIndex = 0;
endIndex = Math.Min(maxLines, spellList.Count);
}
}
else
{
startIndex = 0;
endIndex = 0;
}
}
#endregion
#region Drawing
/// <summary>
/// Draw the screen.
/// </summary>
public override void Draw(GameTime gameTime)
{
Vector2 currentTextPosition = textPosition;
Vector2 currentIconPosition = iconPosition;
Vector2 currentLinePosition = linePosition;
Vector2 currentLevelPosition = levelPosition;
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
spriteBatch.Begin();
// Draw the fading screen
spriteBatch.Draw(fadeTexture, new Rectangle(0,0,
ScreenManager.GraphicsDevice.Viewport.Width,
ScreenManager.GraphicsDevice.Viewport.Height),Color.White);
// Draw the popup background
spriteBatch.Draw(backTexture, backgroundPosition, null,Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
// Draw the title
spriteBatch.DrawString(Fonts.HeaderFont, titleText, titlePosition,
Fonts.TitleColor);
DrawPlayerStats();
// Draw the spell upgrades caption
spriteBatch.Draw(headerTexture, headerPosition, null,Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
spriteBatch.DrawString(Fonts.PlayerNameFont, "Spell Upgrades",
spellUpgradePosition, colorClass);
// Draw the horizontal separating lines
for (int i = 0; i <= maxLines - 1; i++)
{
currentLinePosition.Y += lineSpacing;
spriteBatch.Draw(lineTexture, currentLinePosition,null, Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
}
// Draw the spell upgrade details
for (int i = startIndex; i < endIndex; i++)
{
// Draw the spell icon
spriteBatch.Draw(spellList[i].IconTexture, currentIconPosition,null,Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
// Draw the spell name
spriteBatch.DrawString(Fonts.GearInfoFont, spellList[i].Name,
currentTextPosition, Fonts.CountColor);
// Draw the spell level
spriteBatch.DrawString(Fonts.GearInfoFont, "Spell Level " +
spellList[i].Level.ToString(),
currentLevelPosition, Fonts.CountColor);
// Increment to next line position
currentTextPosition.Y += lineSpacing;
currentLevelPosition.Y += lineSpacing;
currentIconPosition.Y += lineSpacing;
}
// Draw the scroll bars
spriteBatch.Draw(scrollUpTexture, scrollUpPosition,null, Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
spriteBatch.Draw(scrollDownTexture, scrollDownPosition,null, Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
// Draw the select button and its corresponding text
spriteBatch.Draw(selectIconTexture, selectIconPosition,null, Color.White,0f,
Vector2.Zero,ScaledVector2.DrawFactor,SpriteEffects.None,0f);
Vector2 selectTextPosition = Fonts.GetCenterPositionInButton(Fonts.ButtonNamesFont, selectString,
new Rectangle((int)selectIconPosition.X, (int)selectIconPosition.Y,
selectIconTexture.Width, selectIconTexture.Height));
spriteBatch.DrawString(Fonts.ButtonNamesFont, selectString, selectTextPosition,Color.White);
spriteBatch.End();
}
/// <summary>
/// Draw the player stats here
/// </summary>
private void DrawPlayerStats()
{
Vector2 position = topLinePosition;
Vector2 posDamage = playerDamagePosition;
Player player = leveledUpPlayers[index];
int level = player.CharacterLevel;
CharacterLevelingStatistics levelingStatistics =
player.CharacterClass.LevelingStatistics;
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
// Draw the portrait
spriteBatch.Draw(portraitBackTexture, backPosition,null, Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
spriteBatch.Draw(player.ActivePortraitTexture, portraitPosition,null,Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
// Print the character name
spriteBatch.DrawString(Fonts.PlayerNameFont,
player.Name, playerNamePosition, colorName);
// Draw the Class Name
spriteBatch.DrawString(Fonts.PlayerNameFont,
player.CharacterClass.Name, playerClassPosition, colorClass);
// Draw the character level
spriteBatch.DrawString(Fonts.PlayerNameFont, "LEVEL: " +
level.ToString(), playerLvlPosition, Color.Gray);
// Draw the character Health Points
SetColor(levelingStatistics.LevelsPerHealthPointsIncrease == 0 ? 0 :
(level % levelingStatistics.LevelsPerHealthPointsIncrease) *
levelingStatistics.HealthPointsIncrease);
spriteBatch.DrawString(Fonts.PlayerStatisticsFont, "HP: " +
player.CurrentStatistics.HealthPoints + "/" +
player.CharacterStatistics.HealthPoints,
position, color);
// Draw the character Mana Points
position.Y += Fonts.GearInfoFont.LineSpacing;
SetColor(levelingStatistics.LevelsPerMagicPointsIncrease == 0 ? 0 :
(level % levelingStatistics.LevelsPerMagicPointsIncrease) *
levelingStatistics.MagicPointsIncrease);
spriteBatch.DrawString(Fonts.PlayerStatisticsFont, "MP: " +
player.CurrentStatistics.MagicPoints + "/" +
player.CharacterStatistics.MagicPoints,
position, color);
// Draw the physical offense
SetColor(levelingStatistics.LevelsPerPhysicalOffenseIncrease == 0 ? 0 :
(level % levelingStatistics.LevelsPerPhysicalOffenseIncrease) *
levelingStatistics.PhysicalOffenseIncrease);
spriteBatch.DrawString(Fonts.PlayerStatisticsFont, "PO: " +
player.CurrentStatistics.PhysicalOffense, posDamage, color);
// Draw the physical defense
posDamage.Y += Fonts.PlayerStatisticsFont.LineSpacing;
SetColor(levelingStatistics.LevelsPerPhysicalDefenseIncrease == 0 ? 0 :
(level % levelingStatistics.LevelsPerPhysicalDefenseIncrease) *
levelingStatistics.PhysicalDefenseIncrease);
spriteBatch.DrawString(Fonts.PlayerStatisticsFont, "PD: " +
player.CurrentStatistics.PhysicalDefense, posDamage, color);
// Draw the Magic offense
posDamage.Y += Fonts.PlayerStatisticsFont.LineSpacing;
SetColor(levelingStatistics.LevelsPerMagicalOffenseIncrease == 0 ? 0 :
(level % levelingStatistics.LevelsPerMagicalOffenseIncrease) *
levelingStatistics.MagicalOffenseIncrease);
spriteBatch.DrawString(Fonts.PlayerStatisticsFont, "MO: " +
player.CurrentStatistics.MagicalOffense, posDamage, color);
// Draw the Magical defense
posDamage.Y += Fonts.PlayerStatisticsFont.LineSpacing;
SetColor(levelingStatistics.LevelsPerMagicalDefenseIncrease == 0 ? 0 :
(level % levelingStatistics.LevelsPerMagicalDefenseIncrease) *
levelingStatistics.MagicalDefenseIncrease);
spriteBatch.DrawString(Fonts.PlayerStatisticsFont, "MD: " +
player.CurrentStatistics.MagicalDefense, posDamage, color);
}
/// <summary>
/// Set the current color based on whether the value has changed.
/// </summary>
/// <param name="change">State of levelled up values</param>
public void SetColor(int value)
{
if (value > 0)
{
color = Color.Green;
}
else if (value < 0)
{
color = Color.Red;
}
else
{
color = colorText;
}
}
#endregion
}
}
| |
/*
* OANDA v20 REST API
*
* The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more.
*
* OpenAPI spec version: 3.0.15
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace Oanda.RestV20.Model
{
/// <summary>
/// The representation of a Position for a single direction (long or short).
/// </summary>
[DataContract]
public partial class PositionSide : IEquatable<PositionSide>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="PositionSide" /> class.
/// </summary>
/// <param name="Units">Number of units in the position (negative value indicates short position, positive indicates long position)..</param>
/// <param name="AveragePrice">Volume-weighted average of the underlying Trade open prices for the Position..</param>
/// <param name="TradeIDs">List of the open Trade IDs which contribute to the open Position..</param>
/// <param name="Pl">Profit/loss realized by the PositionSide over the lifetime of the Account..</param>
/// <param name="UnrealizedPL">The unrealized profit/loss of all open Trades that contribute to this PositionSide..</param>
/// <param name="ResettablePL">Profit/loss realized by the PositionSide since the Account's resettablePL was last reset by the client..</param>
public PositionSide(string Units = default(string), string AveragePrice = default(string), List<string> TradeIDs = default(List<string>), string Pl = default(string), string UnrealizedPL = default(string), string ResettablePL = default(string))
{
this.Units = Units;
this.AveragePrice = AveragePrice;
this.TradeIDs = TradeIDs;
this.Pl = Pl;
this.UnrealizedPL = UnrealizedPL;
this.ResettablePL = ResettablePL;
}
/// <summary>
/// Number of units in the position (negative value indicates short position, positive indicates long position).
/// </summary>
/// <value>Number of units in the position (negative value indicates short position, positive indicates long position).</value>
[DataMember(Name="units", EmitDefaultValue=false)]
public string Units { get; set; }
/// <summary>
/// Volume-weighted average of the underlying Trade open prices for the Position.
/// </summary>
/// <value>Volume-weighted average of the underlying Trade open prices for the Position.</value>
[DataMember(Name="averagePrice", EmitDefaultValue=false)]
public string AveragePrice { get; set; }
/// <summary>
/// List of the open Trade IDs which contribute to the open Position.
/// </summary>
/// <value>List of the open Trade IDs which contribute to the open Position.</value>
[DataMember(Name="tradeIDs", EmitDefaultValue=false)]
public List<string> TradeIDs { get; set; }
/// <summary>
/// Profit/loss realized by the PositionSide over the lifetime of the Account.
/// </summary>
/// <value>Profit/loss realized by the PositionSide over the lifetime of the Account.</value>
[DataMember(Name="pl", EmitDefaultValue=false)]
public string Pl { get; set; }
/// <summary>
/// The unrealized profit/loss of all open Trades that contribute to this PositionSide.
/// </summary>
/// <value>The unrealized profit/loss of all open Trades that contribute to this PositionSide.</value>
[DataMember(Name="unrealizedPL", EmitDefaultValue=false)]
public string UnrealizedPL { get; set; }
/// <summary>
/// Profit/loss realized by the PositionSide since the Account's resettablePL was last reset by the client.
/// </summary>
/// <value>Profit/loss realized by the PositionSide since the Account's resettablePL was last reset by the client.</value>
[DataMember(Name="resettablePL", EmitDefaultValue=false)]
public string ResettablePL { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PositionSide {\n");
sb.Append(" Units: ").Append(Units).Append("\n");
sb.Append(" AveragePrice: ").Append(AveragePrice).Append("\n");
sb.Append(" TradeIDs: ").Append(TradeIDs).Append("\n");
sb.Append(" Pl: ").Append(Pl).Append("\n");
sb.Append(" UnrealizedPL: ").Append(UnrealizedPL).Append("\n");
sb.Append(" ResettablePL: ").Append(ResettablePL).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as PositionSide);
}
/// <summary>
/// Returns true if PositionSide instances are equal
/// </summary>
/// <param name="other">Instance of PositionSide to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PositionSide other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Units == other.Units ||
this.Units != null &&
this.Units.Equals(other.Units)
) &&
(
this.AveragePrice == other.AveragePrice ||
this.AveragePrice != null &&
this.AveragePrice.Equals(other.AveragePrice)
) &&
(
this.TradeIDs == other.TradeIDs ||
this.TradeIDs != null &&
this.TradeIDs.SequenceEqual(other.TradeIDs)
) &&
(
this.Pl == other.Pl ||
this.Pl != null &&
this.Pl.Equals(other.Pl)
) &&
(
this.UnrealizedPL == other.UnrealizedPL ||
this.UnrealizedPL != null &&
this.UnrealizedPL.Equals(other.UnrealizedPL)
) &&
(
this.ResettablePL == other.ResettablePL ||
this.ResettablePL != null &&
this.ResettablePL.Equals(other.ResettablePL)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Units != null)
hash = hash * 59 + this.Units.GetHashCode();
if (this.AveragePrice != null)
hash = hash * 59 + this.AveragePrice.GetHashCode();
if (this.TradeIDs != null)
hash = hash * 59 + this.TradeIDs.GetHashCode();
if (this.Pl != null)
hash = hash * 59 + this.Pl.GetHashCode();
if (this.UnrealizedPL != null)
hash = hash * 59 + this.UnrealizedPL.GetHashCode();
if (this.ResettablePL != null)
hash = hash * 59 + this.ResettablePL.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
#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
#if !(PORTABLE40 || NET20 || NET35|| PORTABLE)
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Newtonsoft.Json.Utilities
{
internal class ExpressionReflectionDelegateFactory : ReflectionDelegateFactory
{
private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory();
internal static ReflectionDelegateFactory Instance
{
get { return _instance; }
}
public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method)
{
ValidationUtils.ArgumentNotNull(method, "method");
Type type = typeof(object);
ParameterExpression targetParameterExpression = Expression.Parameter(type, "target");
ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args");
ParameterInfo[] parametersInfo = method.GetParameters();
Expression[] argsExpression = new Expression[parametersInfo.Length];
for (int i = 0; i < parametersInfo.Length; i++)
{
Expression indexExpression = Expression.Constant(i);
Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);
paramAccessorExpression = EnsureCastExpression(paramAccessorExpression, parametersInfo[i].ParameterType);
argsExpression[i] = paramAccessorExpression;
}
Expression callExpression;
if (method.IsConstructor)
{
callExpression = Expression.New((ConstructorInfo)method, argsExpression);
}
else if (method.IsStatic)
{
callExpression = Expression.Call((MethodInfo)method, argsExpression);
}
else
{
Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType);
callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression);
}
if (method is MethodInfo)
{
MethodInfo m = (MethodInfo)method;
if (m.ReturnType != typeof(void))
callExpression = EnsureCastExpression(callExpression, type);
else
callExpression = Expression.Block(callExpression, Expression.Constant(null));
}
else
{
callExpression = EnsureCastExpression(callExpression, type);
}
LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall<T, object>), callExpression, targetParameterExpression, argsParameterExpression);
MethodCall<T, object> compiled = (MethodCall<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Func<T> CreateDefaultConstructor<T>(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
// avoid error from expressions compiler because of abstract class
if (type.IsAbstract())
return () => (T)Activator.CreateInstance(type);
try
{
Type resultType = typeof(T);
Expression expression = Expression.New(type);
expression = EnsureCastExpression(expression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T>), expression);
Func<T> compiled = (Func<T>)lambdaExpression.Compile();
return compiled;
}
catch
{
// an error can be thrown if constructor is not valid on Win8
// will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag
return () => (T)Activator.CreateInstance(type);
}
}
public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
Type instanceType = typeof(T);
Type resultType = typeof(object);
ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance");
Expression resultExpression;
MethodInfo getMethod = propertyInfo.GetGetMethod(true);
if (getMethod.IsStatic)
{
resultExpression = Expression.MakeMemberAccess(null, propertyInfo);
}
else
{
Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType);
resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo);
}
resultExpression = EnsureCastExpression(resultExpression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T, object>), resultExpression, parameterExpression);
Func<T, object> compiled = (Func<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, "fieldInfo");
ParameterExpression sourceParameter = Expression.Parameter(typeof(T), "source");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
fieldExpression = EnsureCastExpression(fieldExpression, typeof(object));
Func<T, object> compiled = Expression.Lambda<Func<T, object>>(fieldExpression, sourceParameter).Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, "fieldInfo");
// use reflection for structs
// expression doesn't correctly set value
if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly)
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(fieldInfo);
ParameterExpression sourceParameterExpression = Expression.Parameter(typeof(T), "source");
ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object), "value");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
Expression valueExpression = EnsureCastExpression(valueParameterExpression, fieldExpression.Type);
BinaryExpression assignExpression = Expression.Assign(fieldExpression, valueExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), assignExpression, sourceParameterExpression, valueParameterExpression);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
// use reflection for structs
// expression doesn't correctly set value
if (propertyInfo.DeclaringType.IsValueType())
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(propertyInfo);
Type instanceType = typeof(T);
Type valueType = typeof(object);
ParameterExpression instanceParameter = Expression.Parameter(instanceType, "instance");
ParameterExpression valueParameter = Expression.Parameter(valueType, "value");
Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType);
MethodInfo setMethod = propertyInfo.GetSetMethod(true);
Expression setExpression;
if (setMethod.IsStatic)
{
setExpression = Expression.Call(setMethod, readValueParameter);
}
else
{
Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType);
setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter);
}
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), setExpression, instanceParameter, valueParameter);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
private Expression EnsureCastExpression(Expression expression, Type targetType)
{
Type expressionType = expression.Type;
// check if a cast or conversion is required
if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsAssignableFrom(expressionType)))
return expression;
return Expression.Convert(expression, targetType);
}
}
}
#endif
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudioTools.Navigation;
using Microsoft.VisualStudioTools.Project;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudioTools {
public abstract class CommonPackage : AsyncPackage, IOleComponent {
private uint _componentID;
private LibraryManager _libraryManager;
private IOleComponentManager _compMgr;
private UIThreadBase _uiThread;
private static readonly object _commandsLock = new object();
private static readonly Dictionary<Command, MenuCommand> _commands = new Dictionary<Command, MenuCommand>();
#region Language-specific abstracts
public abstract Type GetLibraryManagerType();
internal abstract LibraryManager CreateLibraryManager();
public abstract bool IsRecognizedFile(string filename);
// TODO:
// public abstract bool TryGetStartupFileAndDirectory(out string filename, out string dir);
#endregion
internal CommonPackage() {
#if DEBUG
AppDomain.CurrentDomain.UnhandledException += (sender, e) => {
if (e.IsTerminating) {
var ex = e.ExceptionObject as Exception;
if (ex is SEHException) {
return;
}
if (ex != null) {
Debug.Fail(
string.Format("An unhandled exception is about to terminate the process:\n\n{0}", ex.Message),
ex.ToString()
);
} else {
Debug.Fail(string.Format(
"An unhandled exception is about to terminate the process:\n\n{0}",
e.ExceptionObject
));
}
}
};
#endif
}
internal static Dictionary<Command, MenuCommand> Commands => _commands;
internal static object CommandsLock => _commandsLock;
protected override void Dispose(bool disposing) {
_uiThread.MustBeCalledFromUIThreadOrThrow();
try {
if (_componentID != 0) {
_compMgr.FRevokeComponent(_componentID);
_componentID = 0;
}
if (_libraryManager != null) {
_libraryManager.Dispose();
_libraryManager = null;
}
} finally {
base.Dispose(disposing);
}
}
private object CreateLibraryManager(IServiceContainer container, Type serviceType) {
if (GetLibraryManagerType() != serviceType) {
return null;
}
return _libraryManager = CreateLibraryManager();
}
internal void RegisterCommands(Guid cmdSet, params Command[] commands) {
_uiThread.MustBeCalledFromUIThreadOrThrow();
if (GetService(typeof(IMenuCommandService)) is OleMenuCommandService mcs) {
lock (_commandsLock) {
foreach (var command in commands) {
var beforeQueryStatus = command.BeforeQueryStatus;
CommandID toolwndCommandID = new CommandID(cmdSet, command.CommandId);
OleMenuCommand menuToolWin = new OleMenuCommand(command.DoCommand, toolwndCommandID);
if (beforeQueryStatus != null) {
menuToolWin.BeforeQueryStatus += beforeQueryStatus;
}
mcs.AddCommand(menuToolWin);
_commands[command] = menuToolWin;
}
}
}
}
internal void RegisterCommands(params MenuCommand[] commands) {
_uiThread.MustBeCalledFromUIThreadOrThrow();
if (GetService(typeof(IMenuCommandService)) is OleMenuCommandService mcs) {
foreach (var command in commands) {
mcs.AddCommand(command);
}
}
}
/// <summary>
/// Gets the current IWpfTextView that is the active document.
/// </summary>
/// <returns></returns>
public static IWpfTextView GetActiveTextView(System.IServiceProvider serviceProvider) {
var monitorSelection = (IVsMonitorSelection)serviceProvider.GetService(typeof(SVsShellMonitorSelection));
if (monitorSelection == null) {
return null;
}
if (ErrorHandler.Failed(monitorSelection.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out var curDocument))) {
// TODO: Report error
return null;
}
if (!(curDocument is IVsWindowFrame frame)) {
// TODO: Report error
return null;
}
if (ErrorHandler.Failed(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out var docView))) {
// TODO: Report error
return null;
}
#if DEV11_OR_LATER
if (docView is IVsDifferenceCodeWindow diffWindow && diffWindow.DifferenceViewer != null) {
switch (diffWindow.DifferenceViewer.ActiveViewType) {
case VisualStudio.Text.Differencing.DifferenceViewType.InlineView:
return diffWindow.DifferenceViewer.InlineView;
case VisualStudio.Text.Differencing.DifferenceViewType.LeftView:
return diffWindow.DifferenceViewer.LeftView;
case VisualStudio.Text.Differencing.DifferenceViewType.RightView:
return diffWindow.DifferenceViewer.RightView;
default:
return null;
}
}
#endif
if (docView is IVsCodeWindow window) {
if (ErrorHandler.Failed(window.GetPrimaryView(out var textView))) {
// TODO: Report error
return null;
}
var model = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
var adapterFactory = model.GetService<IVsEditorAdaptersFactoryService>();
var wpfTextView = adapterFactory.GetWpfTextView(textView);
return wpfTextView;
}
return null;
}
internal static CommonProjectNode GetStartupProject(System.IServiceProvider serviceProvider) {
var buildMgr = (IVsSolutionBuildManager)serviceProvider.GetService(typeof(IVsSolutionBuildManager));
if (buildMgr != null && ErrorHandler.Succeeded(buildMgr.get_StartupProject(out var hierarchy)) && hierarchy != null) {
return hierarchy.GetProject()?.GetCommonProject();
}
return null;
}
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) {
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
_uiThread = (UIThreadBase)GetService(typeof(UIThreadBase));
if (_uiThread == null) {
_uiThread = new UIThread(JoinableTaskFactory);
AddService<UIThreadBase>(_uiThread, true);
}
AddService(GetLibraryManagerType(), CreateLibraryManager, true);
var crinfo = new OLECRINFO {
cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO)),
grfcrf = (uint)_OLECRF.olecrfNeedIdleTime,
grfcadvf = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff,
uIdleTimeInterval = 0
};
_compMgr = (IOleComponentManager)GetService(typeof(SOleComponentManager));
ErrorHandler.ThrowOnFailure(_compMgr.FRegisterComponent(this, new[] { crinfo }, out _componentID));
await base.InitializeAsync(cancellationToken, progress);
}
protected override object GetService(Type serviceType)
=> serviceType == typeof(UIThreadBase) ? _uiThread : base.GetService(serviceType);
protected void AddService<T>(object service, bool promote)
=> ((IServiceContainer)this).AddService(typeof(T), service, promote);
protected void AddService<T>(ServiceCreatorCallback callback, bool promote)
=> ((IServiceContainer)this).AddService(typeof(T), callback, promote);
protected void AddService(Type serviceType, ServiceCreatorCallback callback, bool promote)
=> ((IServiceContainer)this).AddService(serviceType, callback, promote);
internal static void OpenWebBrowser(System.IServiceProvider serviceProvider, string url) {
// TODO: In a future VS 2017 release, SVsWebBrowsingService will have the ability
// to open in an external browser, and we may want to switch to using that, as it
// may be safer/better than Process.Start.
serviceProvider.GetUIThread().Invoke(() => {
try {
var uri = new Uri(url);
Process.Start(new ProcessStartInfo(uri.AbsoluteUri));
} catch (Exception ex) when (!ex.IsCriticalException()) {
Utilities.ShowMessageBox(
serviceProvider,
SR.GetString(SR.WebBrowseNavigateError, url, ex.Message),
null,
OLEMSGICON.OLEMSGICON_CRITICAL,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
);
}
});
}
internal static void OpenVsWebBrowser(System.IServiceProvider serviceProvider, string url) {
serviceProvider.GetUIThread().Invoke(() => {
var web = serviceProvider.GetService(typeof(SVsWebBrowsingService)) as IVsWebBrowsingService;
if (web == null) {
OpenWebBrowser(serviceProvider, url);
return;
}
try {
IVsWindowFrame frame;
ErrorHandler.ThrowOnFailure(web.Navigate(url, (uint)__VSWBNAVIGATEFLAGS.VSNWB_ForceNew, out frame));
frame.Show();
} catch (Exception ex) when (!ex.IsCriticalException()) {
Utilities.ShowMessageBox(
serviceProvider,
SR.GetString(SR.WebBrowseNavigateError, url, ex.Message),
null,
OLEMSGICON.OLEMSGICON_CRITICAL,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
);
}
});
}
#region IOleComponent Members
public int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked) => 1;
public int FDoIdle(uint grfidlef) {
var componentManager = _compMgr;
if (componentManager == null) {
return 0;
}
_libraryManager?.OnIdle(componentManager);
OnIdle?.Invoke(this, new ComponentManagerEventArgs(componentManager));
return 0;
}
internal event EventHandler<ComponentManagerEventArgs> OnIdle;
public int FPreTranslateMessage(MSG[] pMsg) => 0;
public int FQueryTerminate(int fPromptUser) => 1;
public int FReserved1(uint dwReserved, uint message, IntPtr wParam, IntPtr lParam) => 1;
public IntPtr HwndGetWindow(uint dwWhich, uint dwReserved) => IntPtr.Zero;
public void OnActivationChange(IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved) { }
public void OnAppActivate(int fActive, uint dwOtherThreadID) { }
public void OnEnterState(uint uStateID, int fEnter) { }
public void OnLoseActivation() { }
public void Terminate() { }
#endregion
}
internal sealed class ComponentManagerEventArgs : EventArgs {
public ComponentManagerEventArgs(IOleComponentManager compMgr) {
ComponentManager = compMgr;
}
public IOleComponentManager ComponentManager { get; }
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
namespace tk2dEditor.SpriteAnimationEditor
{
public enum AnimEditOperations
{
None = 0,
AllClipsChanged = 1, // the allClips list has changed
ClipContentChanged = 2, // the content of the clip has changed, only for the clipinspector & frame group inspector
ClipNameChanged = 4, // clips name has changed
NewClipCreated = 8, // the returned selectedClip is a newly created clip
};
// Inherit directly from this class
public class AnimOperator
{
protected AnimEditOperations operations = AnimEditOperations.None;
public AnimEditOperations AnimEditOperations { get { return operations; } }
public int sortId = 0;
// Sort id allows the operations to be sorted for draw = decide how it appears in the inspector
// Negative numbers are reserved for the system
public int SortId { get { return sortId; } }
// Insert menu item into "Create" menu
public virtual string[] AnimToolsMenu { get { return new string[0]; } }
// Called by system when one of the anim tools menu above is selected
// Return new selection if selection changed.
public virtual tk2dSpriteAnimationClip OnAnimMenu(string menuEntry, List<tk2dSpriteAnimationClip> allClips, tk2dSpriteAnimationClip selectedClip) { return selectedClip; }
// Drawn in the clip inspector GUI for the selected clip.
// Return true when data has changed.
public virtual bool OnClipInspectorGUI(tk2dSpriteAnimationClip selectedClip, List<ClipEditor.FrameGroup> frameGroups, TimelineEditor.State state) { return false; }
// Drawn in the frame group inspector GUI for the selected clip.
// Return true when data has changed.
public virtual bool OnFrameGroupInspectorGUI(tk2dSpriteAnimationClip selectedClip, List<ClipEditor.FrameGroup> frameGroups, TimelineEditor.State state ) { return false; }
}
public static class AnimOperatorUtil
{
public static ClipEditor.FrameGroup NewFrameGroup(List<ClipEditor.FrameGroup> frameGroups, int selectedFrameGroup)
{
ClipEditor.FrameGroup src = frameGroups[selectedFrameGroup];
ClipEditor.FrameGroup fg = new ClipEditor.FrameGroup();
fg.spriteCollection = src.spriteCollection;
fg.spriteId = src.spriteId;
tk2dSpriteAnimationFrame f = new tk2dSpriteAnimationFrame();
f.spriteCollection = fg.spriteCollection;
f.spriteId = fg.spriteId;
fg.frames.Add(f);
return fg;
}
public static string UniqueClipName(List<tk2dSpriteAnimationClip> allClips, string baseName)
{
bool found = false;
for (int i = 0; i < allClips.Count; ++i)
{
if (allClips[i].name == baseName)
{
found = true;
break;
}
}
if (!found) return baseName;
string uniqueName = baseName + " ";
int uniqueId = 1;
for (int i = 0; i < allClips.Count; ++i)
{
string uname = uniqueName + uniqueId.ToString();
if (allClips[i].name == uname)
{
uniqueId++;
i = -1;
continue;
}
}
uniqueName = uniqueName + uniqueId.ToString();
return uniqueName;
}
}
// Add a "Copy" option to the Animation menu
public class CopyAnimation : AnimOperator
{
public override string[] AnimToolsMenu { get { return new string[] { "Copy" }; } }
public override tk2dSpriteAnimationClip OnAnimMenu(string menuEntry, List<tk2dSpriteAnimationClip> allClips, tk2dSpriteAnimationClip selectedClip)
{
tk2dSpriteAnimationClip newClip = new tk2dSpriteAnimationClip();
newClip.CopyFrom(selectedClip);
newClip.name = AnimOperatorUtil.UniqueClipName( allClips, "Copy of " + selectedClip.name );
allClips.Add(newClip);
operations = AnimEditOperations.NewClipCreated | AnimEditOperations.AllClipsChanged;
return newClip;
}
}
// "Reverse frames"
public class ClipTools : AnimOperator
{
public ClipTools()
{
sortId = -1000;
}
bool textToggle = false;
string textNames = "";
public override bool OnClipInspectorGUI(tk2dSpriteAnimationClip selectedClip, List<ClipEditor.FrameGroup> frameGroups, TimelineEditor.State state )
{
GUILayout.BeginHorizontal();
bool changed = false;
if (GUILayout.Button("Reverse", EditorStyles.miniButton))
{
frameGroups.Reverse();
operations = AnimEditOperations.ClipContentChanged;
state.selectedFrame = (state.selectedFrame == -1) ? state.selectedFrame : (frameGroups.Count - 1 - state.selectedFrame);
changed = true;
}
GUIContent addTriggerContent = new GUIContent("Trigger", "You can also add a trigger by double clicking on the trigger area");
if (GUILayout.Button(addTriggerContent, EditorStyles.miniButton))
{
for (int i = 0; i < selectedClip.frames.Length; ++i)
{
if (!selectedClip.frames[i].triggerEvent)
{
selectedClip.frames[i].triggerEvent = true;
state.selectedTrigger = i;
break;
}
}
changed = true;
}
if (selectedClip.wrapMode != tk2dSpriteAnimationClip.WrapMode.Single)
{
bool newTextToggle = GUILayout.Toggle(textToggle, "Text", EditorStyles.miniButton);
if (newTextToggle != textToggle)
{
if (newTextToggle == true)
{
textNames = BuildTextSpriteList(frameGroups);
if (textNames.Length == 0) newTextToggle = false;
}
textToggle = newTextToggle;
}
}
GUILayout.EndHorizontal();
if (textToggle)
{
textNames = EditorGUILayout.TextArea(textNames, GUILayout.ExpandWidth(true));
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Process"))
{
if (ProcessSpriteImport(frameGroups, textNames))
{
textNames = "";
textToggle = false;
state.selectedFrame = -1;
changed = true;
GUIUtility.keyboardControl = 0;
}
}
GUILayout.EndHorizontal();
}
return changed;
}
string BuildTextSpriteList(List<ClipEditor.FrameGroup> frameGroups)
{
bool fromSameCollection = true;
bool areNamesValid = true;
tk2dSpriteCollectionData coll = null;
List<string> s = new List<string>();
foreach (ClipEditor.FrameGroup frameGroup in frameGroups)
{
tk2dSpriteDefinition def = frameGroup.spriteCollection.spriteDefinitions[frameGroup.spriteId];
if (coll == null) coll = frameGroup.spriteCollection;
if (coll != frameGroup.spriteCollection) fromSameCollection = false;
string spriteName = def.name;
if (spriteName.IndexOf(";") != -1) areNamesValid = false;
int frameCount = frameGroup.frames.Count;
s.Add( (frameCount == 1) ? (spriteName) : (spriteName + ";" + frameCount.ToString()) );
}
if (!fromSameCollection)
{
EditorUtility.DisplayDialog("Text importer failed", "Current animation clip contains sprites from multiple collections", "Ok");
return "";
}
if (!areNamesValid)
{
EditorUtility.DisplayDialog("Text importer failed", "Sprite names contain the ; character", "Ok");
return "";
}
string spriteList = "";
for (int i = 0; i < s.Count; ++i)
spriteList += s[i] + "\n";
return spriteList;
}
bool ProcessSpriteImport(List<ClipEditor.FrameGroup> frameGroups, string spriteNames)
{
tk2dSpriteCollectionData coll = frameGroups[0].spriteCollection;
// make new list
List<int> spriteIds = new List<int>();
List<int> frameCounts = new List<int>();
int lineNumber = 1;
string[] lines = spriteNames.Split('\n');
foreach (string line in lines)
{
if (line.Trim().Length != 0)
{
string spriteName = line;
int frameCount = 1;
int splitIndex = line.LastIndexOf(';');
if (splitIndex != -1)
{
spriteName = line.Substring(0, splitIndex);
string frameCountStr = line.Substring(splitIndex + 1, line.Length - 1 - splitIndex);
if (!System.Int32.TryParse(frameCountStr, out frameCount))
{
Debug.LogError("Parse error in line " + lineNumber.ToString());
return false;
}
frameCount = Mathf.Max(frameCount, 1);
}
int spriteId = coll.GetSpriteIdByName(spriteName, -1);
if (spriteId == -1)
{
Debug.LogError(string.Format("Unable to find sprite '{0}' in sprite collection", spriteName));
return false;
}
spriteIds.Add(spriteId);
frameCounts.Add(frameCount);
}
lineNumber++;
}
List<ClipEditor.FrameGroup> newFrameGroups = new List<ClipEditor.FrameGroup>();
for (int i = 0; i < spriteIds.Count; ++i)
{
if (i < frameGroups.Count && frameGroups[i].spriteId == spriteIds[i])
{
if (frameGroups[i].frames.Count != frameCounts[i])
frameGroups[i].SetFrameCount(frameCounts[i]);
newFrameGroups.Add(frameGroups[i]);
}
else
{
ClipEditor.FrameGroup fg = new ClipEditor.FrameGroup();
fg.spriteCollection = coll;
fg.spriteId = spriteIds[i];
fg.SetFrameCount(frameCounts[i]);
newFrameGroups.Add(fg);
}
}
frameGroups.Clear();
foreach (ClipEditor.FrameGroup fg in newFrameGroups)
frameGroups.Add(fg);
operations = AnimEditOperations.ClipContentChanged;
return true;
}
}
// "Delete frames"
public class DeleteFrames : AnimOperator
{
public DeleteFrames()
{
sortId = -50;
}
public override bool OnFrameGroupInspectorGUI(tk2dSpriteAnimationClip selectedClip, List<ClipEditor.FrameGroup> frameGroups, TimelineEditor.State state )
{
bool changed = false;
if (frameGroups.Count > 1)
{
GUILayout.Space(16);
if (GUILayout.Button("Delete", EditorStyles.miniButton))
{
frameGroups.RemoveAt(state.selectedFrame);
state.selectedFrame = -1;
changed = true;
}
GUILayout.BeginHorizontal();
if (GUILayout.Button("Delete <", EditorStyles.miniButton)) { frameGroups.RemoveRange(0, state.selectedFrame); changed = true; state.selectedFrame = 0; }
if (GUILayout.Button("Delete >", EditorStyles.miniButton)) { frameGroups.RemoveRange(state.selectedFrame + 1, frameGroups.Count - 1 - state.selectedFrame); changed = true; state.selectedFrame = frameGroups.Count - 1; }
GUILayout.EndHorizontal();
}
operations = changed ? AnimEditOperations.ClipContentChanged : AnimEditOperations.None;
return changed;
}
}
// "Insert frames"
public class InsertFrames : AnimOperator
{
public InsertFrames()
{
sortId = -100;
}
public override bool OnFrameGroupInspectorGUI(tk2dSpriteAnimationClip selectedClip, List<ClipEditor.FrameGroup> frameGroups, TimelineEditor.State state )
{
if (selectedClip.wrapMode == tk2dSpriteAnimationClip.WrapMode.Single)
return false;
bool changed = false;
GUILayout.BeginHorizontal();
if (GUILayout.Button("Insert <", EditorStyles.miniButton))
{
frameGroups.Insert(state.selectedFrame, AnimOperatorUtil.NewFrameGroup(frameGroups, state.selectedFrame));
state.selectedFrame++;
changed = true;
}
if (GUILayout.Button("Insert >", EditorStyles.miniButton))
{
frameGroups.Insert(state.selectedFrame + 1, AnimOperatorUtil.NewFrameGroup(frameGroups, state.selectedFrame));
changed = true;
}
GUILayout.EndHorizontal();
operations = changed ? AnimEditOperations.ClipContentChanged : AnimEditOperations.None;
return changed;
}
}
// "AutoFill frames"
public class AutoFillFrames : AnimOperator
{
public AutoFillFrames()
{
sortId = -110;
}
// Finds a sprite with the name and id
// matches "baseName" [ 0..9 ]* as id
// todo rewrite with regex
int GetFrameIndex(tk2dSpriteDefinition def, string baseName)
{
if (System.String.Compare(baseName, 0, def.name, 0, baseName.Length, true) == 0)
{
int thisFrameId = 0;
if (System.Int32.TryParse( def.name.Substring(baseName.Length), out thisFrameId ))
{
return thisFrameId;
}
}
return -1;
}
int FindFrameIndex(tk2dSpriteDefinition[] spriteDefs, string baseName, int frameId)
{
for (int j = 0; j < spriteDefs.Length; ++j)
{
if (GetFrameIndex(spriteDefs[j], baseName) == frameId)
return j;
}
return -1;
}
bool AutoFill(List<ClipEditor.FrameGroup> frameGroups, int selectedFrame, bool reverse)
{
ClipEditor.FrameGroup selectedFrameGroup = frameGroups[selectedFrame];
if (selectedFrameGroup.spriteCollection != null && selectedFrameGroup.spriteId >= 0 && selectedFrameGroup.spriteId < selectedFrameGroup.spriteCollection.inst.Count)
{
string na = selectedFrameGroup.spriteCollection.inst.spriteDefinitions[selectedFrameGroup.spriteId].name;
int numStartA = na.Length - 1;
if (na[numStartA] >= '0' && na[numStartA] <= '9')
{
while (numStartA > 0 && na[numStartA - 1] >= '0' && na[numStartA - 1] <= '9')
numStartA--;
string baseName = na.Substring(0, numStartA).ToLower();
int baseNo = System.Convert.ToInt32(na.Substring(numStartA));
int maxAllowedMissing = 10;
int allowedMissing = maxAllowedMissing;
List<int> pendingFrames = new List<int>();
int startOffset = reverse ? -1 : 1;
int frameInc = reverse ? -1 : 1;
for (int frameNo = baseNo + startOffset; frameNo >= 0 ; frameNo += frameInc)
{
int frameIdx = FindFrameIndex(selectedFrameGroup.spriteCollection.inst.spriteDefinitions, baseName, frameNo);
if (frameIdx == -1)
{
if (--allowedMissing <= 0)
break;
}
else
{
pendingFrames.Add(frameIdx);
allowedMissing = maxAllowedMissing; // reset
}
}
int numInserted = 0;
int insertIndex = selectedFrame + 1;
ClipEditor.FrameGroup nextFrameGroup = (insertIndex >= frameGroups.Count) ? null : frameGroups[insertIndex];
while (pendingFrames.Count > 0)
{
int frameToInsert = pendingFrames[0];
pendingFrames.RemoveAt(0);
if (nextFrameGroup != null &&
nextFrameGroup.spriteCollection == selectedFrameGroup.spriteCollection &&
nextFrameGroup.spriteId == frameToInsert)
break;
ClipEditor.FrameGroup fg = AnimOperatorUtil.NewFrameGroup(frameGroups, selectedFrame);
fg.spriteId = frameToInsert;
fg.Update();
frameGroups.Insert(insertIndex++, fg);
numInserted++;
}
return numInserted > 0;
}
}
return false;
}
public override bool OnFrameGroupInspectorGUI(tk2dSpriteAnimationClip selectedClip, List<ClipEditor.FrameGroup> frameGroups, TimelineEditor.State state)
{
if (selectedClip.wrapMode == tk2dSpriteAnimationClip.WrapMode.Single)
return false;
bool changed = false;
GUILayout.BeginHorizontal();
if (GUILayout.Button("Autofill 9..1", EditorStyles.miniButton) && AutoFill(frameGroups, state.selectedFrame, true)) { changed = true; }
if (GUILayout.Button("Autofill 1..9", EditorStyles.miniButton) && AutoFill(frameGroups, state.selectedFrame, false)) { changed = true; }
GUILayout.EndHorizontal();
operations = changed ? AnimEditOperations.ClipContentChanged : AnimEditOperations.None;
return changed;
}
}
}
| |
#nullable enable
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Configuration;
using BTCPayServer.Data;
using BTCPayServer.Lightning;
using BTCPayServer.Logging;
using BTCPayServer.Models;
using BTCPayServer.Models.StoreViewModels;
using BTCPayServer.Payments;
using BTCPayServer.Payments.Lightning;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
namespace BTCPayServer.Controllers
{
public partial class UIStoresController
{
private readonly ExternalServiceTypes[] _externalServiceTypes =
{
ExternalServiceTypes.Spark,
ExternalServiceTypes.RTL,
ExternalServiceTypes.ThunderHub
};
private readonly string[] _externalServiceNames =
{
"Lightning Terminal"
};
[HttpGet("{storeId}/lightning/{cryptoCode}")]
public async Task<IActionResult> Lightning(string storeId, string cryptoCode)
{
var store = HttpContext.GetStoreData();
if (store == null)
return NotFound();
var vm = new LightningViewModel
{
CryptoCode = cryptoCode,
StoreId = storeId
};
await SetExistingValues(store, vm);
if (vm.LightningNodeType == LightningNodeType.Internal)
{
var services = _externalServiceOptions.Value.ExternalServices.ToList()
.Where(service => _externalServiceTypes.Contains(service.Type))
.Select(service => new AdditionalServiceViewModel
{
DisplayName = service.DisplayName,
ServiceName = service.ServiceName,
CryptoCode = service.CryptoCode,
Type = service.Type.ToString()
})
.ToList();
// other services
foreach ((string key, Uri value) in _externalServiceOptions.Value.OtherExternalServices)
{
if (_externalServiceNames.Contains(key))
{
services.Add(new AdditionalServiceViewModel
{
DisplayName = key,
ServiceName = key,
Type = key.Replace(" ", ""),
Link = Request.GetAbsoluteUriNoPathBase(value).AbsoluteUri
});
}
}
vm.Services = services;
}
return View(vm);
}
[HttpGet("{storeId}/lightning/{cryptoCode}/setup")]
public async Task<IActionResult> SetupLightningNode(string storeId, string cryptoCode)
{
var store = HttpContext.GetStoreData();
if (store == null)
return NotFound();
var vm = new LightningNodeViewModel
{
CryptoCode = cryptoCode,
StoreId = storeId
};
await SetExistingValues(store, vm);
return View(vm);
}
[HttpPost("{storeId}/lightning/{cryptoCode}/setup")]
public async Task<IActionResult> SetupLightningNode(string storeId, LightningNodeViewModel vm, string command, string cryptoCode)
{
vm.CryptoCode = cryptoCode;
var store = HttpContext.GetStoreData();
if (store == null)
return NotFound();
vm.CanUseInternalNode = await CanUseInternalLightning();
if (vm.CryptoCode == null)
{
ModelState.AddModelError(nameof(vm.CryptoCode), "Invalid network");
return View(vm);
}
var network = _ExplorerProvider.GetNetwork(vm.CryptoCode);
var paymentMethodId = new PaymentMethodId(network.CryptoCode, PaymentTypes.LightningLike);
LightningSupportedPaymentMethod? paymentMethod = null;
if (vm.LightningNodeType == LightningNodeType.Internal)
{
if (!await CanUseInternalLightning())
{
ModelState.AddModelError(nameof(vm.ConnectionString), "You are not authorized to use the internal lightning node");
return View(vm);
}
paymentMethod = new LightningSupportedPaymentMethod
{
CryptoCode = paymentMethodId.CryptoCode
};
paymentMethod.SetInternalNode();
}
else
{
if (string.IsNullOrEmpty(vm.ConnectionString))
{
ModelState.AddModelError(nameof(vm.ConnectionString), "Please provide a connection string");
return View(vm);
}
if (!LightningConnectionString.TryParse(vm.ConnectionString, false, out var connectionString, out var error))
{
ModelState.AddModelError(nameof(vm.ConnectionString), $"Invalid URL ({error})");
return View(vm);
}
if (connectionString.ConnectionType == LightningConnectionType.LndGRPC)
{
ModelState.AddModelError(nameof(vm.ConnectionString), $"BTCPay does not support gRPC connections");
return View(vm);
}
if (!User.IsInRole(Roles.ServerAdmin) && !connectionString.IsSafe())
{
ModelState.AddModelError(nameof(vm.ConnectionString), "You are not a server admin, so the connection string should not contain 'cookiefilepath', 'macaroondirectorypath', 'macaroonfilepath', and should not point to a local ip or to a dns name ending with '.internal', '.local', '.lan' or '.'.");
return View(vm);
}
paymentMethod = new LightningSupportedPaymentMethod
{
CryptoCode = paymentMethodId.CryptoCode
};
paymentMethod.SetLightningUrl(connectionString);
}
switch (command)
{
case "save":
var lnurl = new PaymentMethodId(vm.CryptoCode, PaymentTypes.LNURLPay);
store.SetSupportedPaymentMethod(paymentMethodId, paymentMethod);
store.SetSupportedPaymentMethod(lnurl, new LNURLPaySupportedPaymentMethod()
{
CryptoCode = vm.CryptoCode,
UseBech32Scheme = true,
EnableForStandardInvoices = false,
LUD12Enabled = false
});
await _Repo.UpdateStore(store);
TempData[WellKnownTempData.SuccessMessage] = $"{network.CryptoCode} Lightning node updated.";
return RedirectToAction(nameof(LightningSettings), new { storeId, cryptoCode });
case "test":
var handler = _ServiceProvider.GetRequiredService<LightningLikePaymentHandler>();
try
{
var info = await handler.GetNodeInfo(paymentMethod, network, new InvoiceLogs(), Request.IsOnion(), true);
if (!vm.SkipPortTest)
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(20));
await handler.TestConnection(info.First(), cts.Token);
}
TempData[WellKnownTempData.SuccessMessage] = $"Connection to the Lightning node successful. Your node address: {info.First()}";
}
catch (Exception ex)
{
TempData[WellKnownTempData.ErrorMessage] = ex.Message;
return View(vm);
}
return View(vm);
default:
return View(vm);
}
}
[HttpGet("{storeId}/lightning/{cryptoCode}/settings")]
public async Task<IActionResult> LightningSettings(string storeId, string cryptoCode)
{
var store = HttpContext.GetStoreData();
if (store == null)
return NotFound();
var storeBlob = store.GetStoreBlob();
var excludeFilters = storeBlob.GetExcludedPaymentMethods();
var lightning = GetExistingLightningSupportedPaymentMethod(cryptoCode, store);
if (lightning == null)
{
TempData[WellKnownTempData.ErrorMessage] = $"You need to connect to a Lightning node before adjusting its settings.";
return RedirectToAction(nameof(SetupLightningNode), new { storeId, cryptoCode });
}
var vm = new LightningSettingsViewModel
{
CryptoCode = cryptoCode,
StoreId = storeId,
Enabled = !excludeFilters.Match(lightning.PaymentId),
LightningDescriptionTemplate = storeBlob.LightningDescriptionTemplate,
LightningAmountInSatoshi = storeBlob.LightningAmountInSatoshi,
LightningPrivateRouteHints = storeBlob.LightningPrivateRouteHints,
OnChainWithLnInvoiceFallback = storeBlob.OnChainWithLnInvoiceFallback
};
await SetExistingValues(store, vm);
if (lightning != null)
{
vm.DisableBolt11PaymentMethod = lightning.DisableBOLT11PaymentOption;
}
var lnurl = GetExistingLNURLSupportedPaymentMethod(vm.CryptoCode, store);
if (lnurl != null)
{
vm.LNURLEnabled = !store.GetStoreBlob().GetExcludedPaymentMethods().Match(lnurl.PaymentId);
vm.LNURLBech32Mode = lnurl.UseBech32Scheme;
vm.LNURLStandardInvoiceEnabled = lnurl.EnableForStandardInvoices;
vm.LUD12Enabled = lnurl.LUD12Enabled;
vm.DisableBolt11PaymentMethod =
vm.LNURLEnabled && vm.LNURLStandardInvoiceEnabled && vm.DisableBolt11PaymentMethod;
}
else
{
//disable by default for now
//vm.LNURLEnabled = !lnSet;
vm.DisableBolt11PaymentMethod = false;
}
return View(vm);
}
[HttpPost("{storeId}/lightning/{cryptoCode}/settings")]
public async Task<IActionResult> LightningSettings(LightningSettingsViewModel vm)
{
var store = HttpContext.GetStoreData();
if (store == null)
return NotFound();
if (vm.CryptoCode == null)
{
ModelState.AddModelError(nameof(vm.CryptoCode), "Invalid network");
return View(vm);
}
var network = _ExplorerProvider.GetNetwork(vm.CryptoCode);
var needUpdate = false;
var blob = store.GetStoreBlob();
blob.LightningDescriptionTemplate = vm.LightningDescriptionTemplate ?? string.Empty;
blob.LightningAmountInSatoshi = vm.LightningAmountInSatoshi;
blob.LightningPrivateRouteHints = vm.LightningPrivateRouteHints;
blob.OnChainWithLnInvoiceFallback = vm.OnChainWithLnInvoiceFallback;
var disableBolt11PaymentMethod =
vm.LNURLEnabled && vm.LNURLStandardInvoiceEnabled && vm.DisableBolt11PaymentMethod;
var lnurlId = new PaymentMethodId(vm.CryptoCode, PaymentTypes.LNURLPay);
blob.SetExcluded(lnurlId, !vm.LNURLEnabled);
var lightning = GetExistingLightningSupportedPaymentMethod(vm.CryptoCode, store);
// Going to mark "lightning" as non-null here assuming that if we are POSTing here it's because we have a Lightning Node set-up
if (lightning!.DisableBOLT11PaymentOption != disableBolt11PaymentMethod)
{
needUpdate = true;
lightning.DisableBOLT11PaymentOption = disableBolt11PaymentMethod;
store.SetSupportedPaymentMethod(lightning);
}
var lnurl = GetExistingLNURLSupportedPaymentMethod(vm.CryptoCode, store);
if (lnurl is null || (
lnurl.EnableForStandardInvoices != vm.LNURLStandardInvoiceEnabled ||
lnurl.UseBech32Scheme != vm.LNURLBech32Mode ||
lnurl.LUD12Enabled != vm.LUD12Enabled))
{
needUpdate = true;
}
store.SetSupportedPaymentMethod(new LNURLPaySupportedPaymentMethod
{
CryptoCode = vm.CryptoCode,
EnableForStandardInvoices = vm.LNURLStandardInvoiceEnabled,
UseBech32Scheme = vm.LNURLBech32Mode,
LUD12Enabled = vm.LUD12Enabled
});
if (store.SetStoreBlob(blob))
{
needUpdate = true;
}
if (needUpdate)
{
await _Repo.UpdateStore(store);
TempData[WellKnownTempData.SuccessMessage] = $"{network.CryptoCode} Lightning settings successfully updated.";
}
return RedirectToAction(nameof(LightningSettings), new { vm.StoreId, vm.CryptoCode });
}
[HttpPost("{storeId}/lightning/{cryptoCode}/status")]
public async Task<IActionResult> SetLightningNodeEnabled(string storeId, string cryptoCode, bool enabled)
{
var store = HttpContext.GetStoreData();
if (store == null)
return NotFound();
if (cryptoCode == null)
return NotFound();
var network = _ExplorerProvider.GetNetwork(cryptoCode);
var lightning = GetExistingLightningSupportedPaymentMethod(cryptoCode, store);
if (lightning == null)
return NotFound();
var paymentMethodId = new PaymentMethodId(network.CryptoCode, PaymentTypes.LightningLike);
var storeBlob = store.GetStoreBlob();
storeBlob.SetExcluded(paymentMethodId, !enabled);
if (!enabled)
{
storeBlob.SetExcluded(new PaymentMethodId(network.CryptoCode, PaymentTypes.LNURLPay), true);
}
store.SetStoreBlob(storeBlob);
await _Repo.UpdateStore(store);
TempData[WellKnownTempData.SuccessMessage] = $"{network.CryptoCode} Lightning payments are now {(enabled ? "enabled" : "disabled")} for this store.";
return RedirectToAction(nameof(LightningSettings), new { storeId, cryptoCode });
}
private async Task<bool> CanUseInternalLightning()
{
return User.IsInRole(Roles.ServerAdmin) || (await _settingsRepository.GetPolicies()).AllowLightningInternalNodeForAll;
}
private async Task SetExistingValues(StoreData store, LightningNodeViewModel vm)
{
vm.CanUseInternalNode = await CanUseInternalLightning();
var lightning = GetExistingLightningSupportedPaymentMethod(vm.CryptoCode, store);
if (lightning != null)
{
vm.LightningNodeType = lightning.IsInternalNode ? LightningNodeType.Internal : LightningNodeType.Custom;
vm.ConnectionString = lightning.GetDisplayableConnectionString();
}
else
{
vm.LightningNodeType = vm.CanUseInternalNode ? LightningNodeType.Internal : LightningNodeType.Custom;
}
}
private LightningSupportedPaymentMethod? GetExistingLightningSupportedPaymentMethod(string cryptoCode, StoreData store)
{
var id = new PaymentMethodId(cryptoCode, PaymentTypes.LightningLike);
var existing = store.GetSupportedPaymentMethods(_NetworkProvider)
.OfType<LightningSupportedPaymentMethod>()
.FirstOrDefault(d => d.PaymentId == id);
return existing;
}
private LNURLPaySupportedPaymentMethod? GetExistingLNURLSupportedPaymentMethod(string cryptoCode, StoreData store)
{
var id = new PaymentMethodId(cryptoCode, PaymentTypes.LNURLPay);
var existing = store.GetSupportedPaymentMethods(_NetworkProvider)
.OfType<LNURLPaySupportedPaymentMethod>()
.FirstOrDefault(d => d.PaymentId == id);
return existing;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
{
public class XmlDataContractSerializerOutputFormatterTest
{
[DataContract(Name = "DummyClass", Namespace = "")]
public class DummyClass
{
[DataMember]
public int SampleInt { get; set; }
}
[DataContract(Name = "SomeDummyClass", Namespace = "")]
public class SomeDummyClass : DummyClass
{
[DataMember]
public string SampleString { get; set; }
}
[DataContract(Name = "TestLevelOne", Namespace = "")]
public class TestLevelOne
{
[DataMember]
public int SampleInt { get; set; }
[DataMember]
public string sampleString;
}
[DataContract(Name = "TestLevelTwo", Namespace = "")]
public class TestLevelTwo
{
[DataMember]
public string SampleString { get; set; }
[DataMember]
public TestLevelOne TestOne { get; set; }
}
[DataContract(Name = "Child", Namespace = "")]
public class Child
{
[DataMember]
public int Id { get; set; }
[DataMember]
public Parent Parent { get; set; }
}
[DataContract(Name = "Parent", Namespace = "")]
public class Parent
{
[DataMember]
public string Name { get; set; }
[DataMember]
public List<Child> Children { get; set; }
}
public static IEnumerable<object[]> BasicTypeValues
{
get
{
yield return new object[] { "sampleString",
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">sampleString</string>" };
yield return new object[] { 5,
"<int xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">5</int>" };
yield return new object[] { 5.43,
"<double xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">5.43</double>" };
yield return new object[] { 'a',
"<char xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">97</char>" };
yield return new object[] { new DummyClass { SampleInt = 10 },
"<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<SampleInt>10</SampleInt></DummyClass>" };
yield return new object[] { new Dictionary<string, string>() { { "Hello", "World" } },
"<ArrayOfKeyValueOfstringstring xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\"><KeyValueOfstringstring>" +
"<Key>Hello</Key><Value>World</Value></KeyValueOfstringstring></ArrayOfKeyValueOfstringstring>" };
}
}
[ConditionalTheory]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
[MemberData(nameof(BasicTypeValues))]
public async Task WriteAsync_CanWriteBasicTypes(object input, string expectedOutput)
{
// Arrange
var formatter = new XmlDataContractSerializerOutputFormatter();
var outputFormatterContext = GetOutputFormatterContext(input, input.GetType());
// Act
await formatter.WriteAsync(outputFormatterContext);
// Assert
var body = outputFormatterContext.HttpContext.Response.Body;
body.Position = 0;
var content = new StreamReader(body).ReadToEnd();
XmlAssert.Equal(expectedOutput, content);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public void XmlDataContractSerializer_CachesSerializerForType()
{
// Arrange
var input = new DummyClass { SampleInt = 10 };
var formatter = new TestXmlDataContractSerializerOutputFormatter();
var context = GetOutputFormatterContext(input, typeof(DummyClass));
context.ContentType = new StringSegment("application/xml");
// Act
formatter.CanWriteResult(context);
formatter.CanWriteResult(context);
// Assert
Assert.Equal(1, formatter.createSerializerCalledCount);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public void DefaultConstructor_ExpectedWriterSettings_Created()
{
// Arrange and Act
var formatter = new XmlDataContractSerializerOutputFormatter();
// Assert
var writerSettings = formatter.WriterSettings;
Assert.NotNull(writerSettings);
Assert.True(writerSettings.OmitXmlDeclaration);
Assert.False(writerSettings.CloseOutput);
Assert.False(writerSettings.CheckCharacters);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task SuppliedWriterSettings_TakeAffect()
{
// Arrange
var writerSettings = FormattingUtilities.GetDefaultXmlWriterSettings();
writerSettings.OmitXmlDeclaration = false;
var sampleInput = new DummyClass { SampleInt = 10 };
var formatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
var formatter = new XmlDataContractSerializerOutputFormatter(writerSettings);
var expectedOutput = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<SampleInt>10</SampleInt></DummyClass>";
// Act
await formatter.WriteAsync(formatterContext);
// Assert
Assert.Same(writerSettings, formatter.WriterSettings);
var body = formatterContext.HttpContext.Response.Body;
body.Position = 0;
var content = new StreamReader(body).ReadToEnd();
XmlAssert.Equal(expectedOutput, content);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task WriteAsync_WritesSimpleTypes()
{
// Arrange
var expectedOutput =
"<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<SampleInt>10</SampleInt></DummyClass>";
var sampleInput = new DummyClass { SampleInt = 10 };
var formatter = new XmlDataContractSerializerOutputFormatter();
var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
// Act
await formatter.WriteAsync(outputFormatterContext);
// Assert
var body = outputFormatterContext.HttpContext.Response.Body;
body.Position = 0;
var content = new StreamReader(body).ReadToEnd();
XmlAssert.Equal(expectedOutput, content);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task WriteAsync_WritesComplexTypes()
{
// Arrange
var expectedOutput =
"<TestLevelTwo xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<SampleString>TestString</SampleString>" +
"<TestOne><SampleInt>10</SampleInt><sampleString>TestLevelOne string</sampleString>" +
"</TestOne></TestLevelTwo>";
var sampleInput = new TestLevelTwo
{
SampleString = "TestString",
TestOne = new TestLevelOne
{
SampleInt = 10,
sampleString = "TestLevelOne string"
}
};
var formatter = new XmlDataContractSerializerOutputFormatter();
var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
// Act
await formatter.WriteAsync(outputFormatterContext);
// Assert
var body = outputFormatterContext.HttpContext.Response.Body;
body.Position = 0;
var content = new StreamReader(body).ReadToEnd();
XmlAssert.Equal(expectedOutput, content);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task WriteAsync_WritesOnModifiedWriterSettings()
{
// Arrange
var expectedOutput =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<SampleInt>10</SampleInt></DummyClass>";
var sampleInput = new DummyClass { SampleInt = 10 };
var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
var formatter = new XmlDataContractSerializerOutputFormatter(
new XmlWriterSettings
{
OmitXmlDeclaration = false,
CloseOutput = false
});
// Act
await formatter.WriteAsync(outputFormatterContext);
// Assert
var body = outputFormatterContext.HttpContext.Response.Body;
body.Position = 0;
var content = new StreamReader(body).ReadToEnd();
XmlAssert.Equal(expectedOutput, content);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task WriteAsync_WritesUTF16Output()
{
// Arrange
var expectedOutput =
"<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
"<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<SampleInt>10</SampleInt></DummyClass>";
var sampleInput = new DummyClass { SampleInt = 10 };
var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType(),
"application/xml; charset=utf-16");
var formatter = new XmlDataContractSerializerOutputFormatter();
formatter.WriterSettings.OmitXmlDeclaration = false;
// Act
await formatter.WriteAsync(outputFormatterContext);
// Assert
var body = outputFormatterContext.HttpContext.Response.Body;
body.Position = 0;
var content = new StreamReader(
body,
new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true)).ReadToEnd();
XmlAssert.Equal(expectedOutput, content);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task WriteAsync_WritesIndentedOutput()
{
// Arrange
var expectedOutput =
"<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"\r\n <SampleInt>10</SampleInt>\r\n</DummyClass>";
var sampleInput = new DummyClass { SampleInt = 10 };
var formatter = new XmlDataContractSerializerOutputFormatter();
formatter.WriterSettings.Indent = true;
var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
// Act
await formatter.WriteAsync(outputFormatterContext);
// Assert
var body = outputFormatterContext.HttpContext.Response.Body;
body.Position = 0;
var content = new StreamReader(body).ReadToEnd();
XmlAssert.Equal(expectedOutput, content);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task WriteAsync_VerifyBodyIsNotClosedAfterOutputIsWritten()
{
// Arrange
var sampleInput = new DummyClass { SampleInt = 10 };
var formatter = new XmlDataContractSerializerOutputFormatter();
var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
// Act
await formatter.WriteAsync(outputFormatterContext);
// Assert
var body = outputFormatterContext.HttpContext.Response.Body;
Assert.True(body.CanRead);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task WriteAsync_DoesntFlushOutputStream()
{
// Arrange
var sampleInput = new DummyClass { SampleInt = 10 };
var formatter = new XmlDataContractSerializerOutputFormatter();
var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
var response = outputFormatterContext.HttpContext.Response;
response.Body = FlushReportingStream.GetThrowingStream();
// Act & Assert
await formatter.WriteAsync(outputFormatterContext);
}
public static IEnumerable<object[]> TypesForCanWriteResult
{
get
{
yield return new object[] { null, typeof(string), true };
yield return new object[] { null, null, false };
yield return new object[] { new DummyClass { SampleInt = 5 }, typeof(DummyClass), true };
yield return new object[] {
new Dictionary<string, string> { { "Hello", "world" } }, typeof(object), true };
yield return new object[] {
new Dictionary<string, string> { { "Hello", "world" } }, typeof(Dictionary<string,string>), true };
}
}
[ConditionalTheory]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
[MemberData(nameof(TypesForCanWriteResult))]
public void CanWriteResult_ReturnsExpectedValueForObjectType(object input, Type declaredType, bool expectedOutput)
{
// Arrange
var formatter = new XmlDataContractSerializerOutputFormatter();
var outputFormatterContext = GetOutputFormatterContext(input, declaredType);
outputFormatterContext.ContentType = new StringSegment("application/xml");
// Act
var result = formatter.CanWriteResult(outputFormatterContext);
// Assert
Assert.Equal(expectedOutput, result);
}
[ConditionalTheory]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
[InlineData("application/xml", false, "application/xml")]
[InlineData("application/xml", true, "application/xml")]
[InlineData("application/other", false, null)]
[InlineData("application/other", true, null)]
[InlineData("application/*", false, "application/xml")]
[InlineData("text/*", false, "text/xml")]
[InlineData("custom/*", false, null)]
[InlineData("application/xml;v=2", false, null)]
[InlineData("application/xml;v=2", true, null)]
[InlineData("application/some.entity+xml", false, null)]
[InlineData("application/some.entity+xml", true, "application/some.entity+xml")]
[InlineData("application/some.entity+xml;v=2", true, "application/some.entity+xml;v=2")]
[InlineData("application/some.entity+other", true, null)]
public void CanWriteResult_ReturnsExpectedValueForMediaType(
string mediaType,
bool isServerDefined,
string expectedResult)
{
// Arrange
var formatter = new XmlDataContractSerializerOutputFormatter();
var outputFormatterContext = GetOutputFormatterContext(new object(), typeof(object));
outputFormatterContext.ContentType = new StringSegment(mediaType);
outputFormatterContext.ContentTypeIsServerDefined = isServerDefined;
// Act
var actualCanWriteValue = formatter.CanWriteResult(outputFormatterContext);
// Assert
var expectedContentType = expectedResult ?? mediaType;
Assert.Equal(expectedResult != null, actualCanWriteValue);
Assert.Equal(new StringSegment(expectedContentType), outputFormatterContext.ContentType);
}
public static IEnumerable<object[]> TypesForGetSupportedContentTypes
{
get
{
yield return new object[] { typeof(DummyClass), "application/xml" };
yield return new object[] { typeof(object), "application/xml" };
yield return new object[] { null, null };
}
}
[ConditionalTheory]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
[MemberData(nameof(TypesForGetSupportedContentTypes))]
public void GetSupportedContentTypes_ReturnsSupportedTypes(Type type, object expectedOutput)
{
// Arrange
var formatter = new XmlDataContractSerializerOutputFormatter();
// Act
var result = formatter.GetSupportedContentTypes(
"application/xml",
type);
// Assert
if (expectedOutput != null)
{
Assert.Equal(expectedOutput, Assert.Single(result).ToString());
}
else
{
Assert.Equal(expectedOutput, result);
}
}
[Fact]
public async Task WriteAsync_ThrowsWhenNotConfiguredWithKnownTypes()
{
// Arrange
var sampleInput = new SomeDummyClass { SampleInt = 1, SampleString = "TestString" };
var formatter = new XmlDataContractSerializerOutputFormatter();
var outputFormatterContext = GetOutputFormatterContext(sampleInput, typeof(DummyClass));
// Act & Assert
await Assert.ThrowsAsync<SerializationException>(async () => await formatter.WriteAsync(outputFormatterContext));
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task WriteAsync_ThrowsWhenNotConfiguredWithPreserveReferences()
{
// Arrange
var child = new Child { Id = 1 };
var parent = new Parent { Name = "Parent", Children = new List<Child> { child } };
child.Parent = parent;
var formatter = new XmlDataContractSerializerOutputFormatter();
var outputFormatterContext = GetOutputFormatterContext(parent, parent.GetType());
// Act & Assert
await Assert.ThrowsAsync<SerializationException>(async () => await formatter.WriteAsync(outputFormatterContext));
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task WriteAsync_WritesWhenConfiguredWithRootName()
{
// Arrange
var sampleInt = 10;
var SubstituteRootName = "SomeOtherClass";
var SubstituteRootNamespace = "http://tempuri.org";
var InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
var expectedOutput = string.Format(
CultureInfo.InvariantCulture,
"<{0} xmlns:i=\"{2}\" xmlns=\"{1}\"><SampleInt xmlns=\"\">{3}</SampleInt></{0}>",
SubstituteRootName,
SubstituteRootNamespace,
InstanceNamespace,
sampleInt);
var sampleInput = new DummyClass { SampleInt = sampleInt };
var dictionary = new XmlDictionary();
var settings = new DataContractSerializerSettings
{
RootName = dictionary.Add(SubstituteRootName),
RootNamespace = dictionary.Add(SubstituteRootNamespace)
};
var formatter = new XmlDataContractSerializerOutputFormatter
{
SerializerSettings = settings
};
var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
// Act
await formatter.WriteAsync(outputFormatterContext);
// Assert
var body = outputFormatterContext.HttpContext.Response.Body;
body.Position = 0;
var content = new StreamReader(body).ReadToEnd();
XmlAssert.Equal(expectedOutput, content);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task WriteAsync_WritesWhenConfiguredWithKnownTypes()
{
// Arrange
var sampleInt = 10;
var sampleString = "TestString";
var KnownTypeName = "SomeDummyClass";
var InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
var expectedOutput = string.Format(
CultureInfo.InvariantCulture,
"<DummyClass xmlns:i=\"{1}\" xmlns=\"\" i:type=\"{0}\"><SampleInt>{2}</SampleInt>"
+ "<SampleString>{3}</SampleString></DummyClass>",
KnownTypeName,
InstanceNamespace,
sampleInt,
sampleString);
var sampleInput = new SomeDummyClass
{
SampleInt = sampleInt,
SampleString = sampleString
};
var settings = new DataContractSerializerSettings
{
KnownTypes = new[] { typeof(SomeDummyClass) }
};
var formatter = new XmlDataContractSerializerOutputFormatter
{
SerializerSettings = settings
};
var outputFormatterContext = GetOutputFormatterContext(sampleInput, typeof(DummyClass));
// Act
await formatter.WriteAsync(outputFormatterContext);
// Assert
var body = outputFormatterContext.HttpContext.Response.Body;
body.Position = 0;
var content = new StreamReader(body).ReadToEnd();
XmlAssert.Equal(expectedOutput, content);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task WriteAsync_WritesWhenConfiguredWithPreserveReferences()
{
// Arrange
var sampleId = 1;
var sampleName = "Parent";
var InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
var SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/";
var expectedOutput = string.Format(
CultureInfo.InvariantCulture,
"<Parent xmlns:i=\"{0}\" z:Id=\"{2}\" xmlns:z=\"{1}\">" +
"<Children z:Id=\"2\" z:Size=\"1\">" +
"<Child z:Id=\"3\"><Id>{2}</Id><Parent z:Ref=\"1\" i:nil=\"true\" />" +
"</Child></Children><Name z:Id=\"4\">{3}</Name></Parent>",
InstanceNamespace,
SerializationNamespace,
sampleId,
sampleName);
var child = new Child { Id = sampleId };
var parent = new Parent { Name = sampleName, Children = new List<Child> { child } };
child.Parent = parent;
var settings = new DataContractSerializerSettings
{
PreserveObjectReferences = true
};
var formatter = new XmlDataContractSerializerOutputFormatter
{
SerializerSettings = settings
};
var outputFormatterContext = GetOutputFormatterContext(parent, parent.GetType());
// Act
await formatter.WriteAsync(outputFormatterContext);
// Assert
var body = outputFormatterContext.HttpContext.Response.Body;
body.Position = 0;
var content = new StreamReader(body).ReadToEnd();
XmlAssert.Equal(expectedOutput, content);
}
public static TheoryData<XmlDataContractSerializerOutputFormatter, TestSink> LogsWhenUnableToCreateSerializerForTypeData
{
get
{
var sink1 = new TestSink();
var formatter1 = new XmlDataContractSerializerOutputFormatter(new TestLoggerFactory(sink1, enabled: true));
var sink2 = new TestSink();
var formatter2 = new XmlDataContractSerializerOutputFormatter(
new XmlWriterSettings(),
new TestLoggerFactory(sink2, enabled: true));
return new TheoryData<XmlDataContractSerializerOutputFormatter, TestSink>()
{
{ formatter1, sink1 },
{ formatter2, sink2}
};
}
}
[Theory]
[MemberData(nameof(LogsWhenUnableToCreateSerializerForTypeData))]
public void CannotCreateSerializer_LogsWarning(
XmlDataContractSerializerOutputFormatter formatter,
TestSink sink)
{
// Arrange
var outputFormatterContext = GetOutputFormatterContext(new Customer(10), typeof(Customer));
// Act
var result = formatter.CanWriteResult(outputFormatterContext);
// Assert
Assert.False(result);
var write = Assert.Single(sink.Writes);
Assert.Equal(LogLevel.Warning, write.LogLevel);
Assert.Equal($"An error occurred while trying to create a DataContractSerializer for the type '{typeof(Customer).FullName}'.",
write.State.ToString());
}
[Fact]
public void DoesNotThrow_OnNoLoggerAnd_WhenUnableToCreateSerializerForType()
{
// Arrange
var formatter = new XmlDataContractSerializerOutputFormatter(); // no logger is being supplied here on purpose
var outputFormatterContext = GetOutputFormatterContext(new Customer(10), typeof(Customer));
// Act
var canWriteResult = formatter.CanWriteResult(outputFormatterContext);
// Assert
Assert.False(canWriteResult);
}
public static TheoryData<bool, object, string> CanIndentOutputConditionallyData
{
get
{
var obj = new DummyClass { SampleInt = 10 };
var newLine = Environment.NewLine;
return new TheoryData<bool, object, string>()
{
{ true, obj, "<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
$"{newLine} <SampleInt>10</SampleInt>{newLine}</DummyClass>" },
{ false, obj, "<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<SampleInt>10</SampleInt></DummyClass>" }
};
}
}
[Theory]
[MemberData(nameof(CanIndentOutputConditionallyData))]
public async Task CanIndentOutputConditionally(bool indent, object input, string expectedOutput)
{
// Arrange
var formatter = new IndentingXmlDataContractSerializerOutputFormatter();
var outputFormatterContext = GetOutputFormatterContext(input, input.GetType());
outputFormatterContext.HttpContext.Request.QueryString = new QueryString("?indent=" + indent);
// Act
await formatter.WriteAsync(outputFormatterContext);
// Assert
var body = outputFormatterContext.HttpContext.Response.Body;
body.Position = 0;
var content = new StreamReader(body).ReadToEnd();
Assert.Equal(expectedOutput, content);
}
[Fact]
public async Task WriteResponseBodyAsync_AsyncEnumerableConnectionCloses()
{
// Arrange
var formatter = new XmlDataContractSerializerOutputFormatter();
var body = new MemoryStream();
var cts = new CancellationTokenSource();
var iterated = false;
var asyncEnumerable = AsyncEnumerableClosedConnection();
var outputFormatterContext = GetOutputFormatterContext(
asyncEnumerable,
asyncEnumerable.GetType());
outputFormatterContext.HttpContext.RequestAborted = cts.Token;
outputFormatterContext.HttpContext.Response.Body = body;
// Act
await formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.GetEncoding("utf-8"));
// Assert
Assert.Empty(body.ToArray());
Assert.False(iterated);
async IAsyncEnumerable<int> AsyncEnumerableClosedConnection([EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await Task.Yield();
cts.Cancel();
// MvcOptions.MaxIAsyncEnumerableBufferLimit is 8192. Pick some value larger than that.
foreach (var i in Enumerable.Range(0, 9000))
{
if (cancellationToken.IsCancellationRequested)
{
yield break;
}
iterated = true;
yield return i;
}
}
}
[Fact]
public async Task WriteResponseBodyAsync_AsyncEnumerable()
{
// Arrange
var formatter = new XmlDataContractSerializerOutputFormatter();
var body = new MemoryStream();
var asyncEnumerable = AsyncEnumerable();
var outputFormatterContext = GetOutputFormatterContext(
asyncEnumerable,
asyncEnumerable.GetType());
outputFormatterContext.HttpContext.Response.Body = body;
// Act
await formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.GetEncoding("utf-8"));
// Assert
Assert.Contains("<int>1</int><int>2</int>", Encoding.UTF8.GetString(body.ToArray()));
async IAsyncEnumerable<int> AsyncEnumerable()
{
await Task.Yield();
yield return 1;
yield return 2;
}
}
private OutputFormatterWriteContext GetOutputFormatterContext(
object outputValue,
Type outputType,
string contentType = "application/xml; charset=utf-8")
{
return new OutputFormatterWriteContext(
GetHttpContext(contentType),
new TestHttpResponseStreamWriterFactory().CreateWriter,
outputType,
outputValue);
}
private static HttpContext GetHttpContext(string contentType)
{
var httpContext = new DefaultHttpContext();
var request = httpContext.Request;
request.Headers["Accept-Charset"] = MediaTypeHeaderValue.Parse(contentType).Charset.ToString();
request.ContentType = contentType;
httpContext.Response.Body = new MemoryStream();
httpContext.RequestServices = new ServiceCollection()
.AddSingleton(Options.Create(new MvcOptions()))
.BuildServiceProvider();
return httpContext;
}
private class TestXmlDataContractSerializerOutputFormatter : XmlDataContractSerializerOutputFormatter
{
public int createSerializerCalledCount = 0;
protected override DataContractSerializer CreateSerializer(Type type)
{
createSerializerCalledCount++;
return base.CreateSerializer(type);
}
}
private class IndentingXmlDataContractSerializerOutputFormatter : XmlDataContractSerializerOutputFormatter
{
public override XmlWriter CreateXmlWriter(
OutputFormatterWriteContext context,
TextWriter writer,
XmlWriterSettings xmlWriterSettings)
{
var request = context.HttpContext.Request;
if (request.Query["indent"] == "True")
{
xmlWriterSettings.Indent = true;
}
return base.CreateXmlWriter(context, writer, xmlWriterSettings);
}
}
public class Customer
{
public Customer(int id)
{
}
public int MyProperty { get; set; }
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BackupStorageConfigsOperations operations.
/// </summary>
internal partial class BackupStorageConfigsOperations : IServiceOperations<RecoveryServicesClient>, IBackupStorageConfigsOperations
{
/// <summary>
/// Initializes a new instance of the BackupStorageConfigsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BackupStorageConfigsOperations(RecoveryServicesClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesClient
/// </summary>
public RecoveryServicesClient Client { get; private set; }
/// <summary>
/// Fetches resource storage config.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<BackupStorageConfig>> GetWithHttpMessagesAsync(string resourceGroupName, string vaultName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupstorageconfig/vaultstorageconfig").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<BackupStorageConfig>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BackupStorageConfig>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates vault storage model type.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='backupStorageConfig'>
/// Backup storage config.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string vaultName, BackupStorageConfig backupStorageConfig, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (backupStorageConfig == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "backupStorageConfig");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("backupStorageConfig", backupStorageConfig);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupstorageconfig/vaultstorageconfig").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(backupStorageConfig != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(backupStorageConfig, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OrchardCore.Environment.Cache;
using OrchardCore.Environment.Shell.Builders;
using OrchardCore.Environment.Shell.Models;
using OrchardCore.Modules;
namespace OrchardCore.Environment.Shell.Scope
{
/// <summary>
/// Custom 'IServiceScope' managing the shell state and the execution flow.
/// </summary>
public class ShellScope : IServiceScope
{
private static readonly AsyncLocal<ShellScopeHolder> _current = new AsyncLocal<ShellScopeHolder>();
private readonly IServiceScope _serviceScope;
private readonly Dictionary<object, object> _items = new Dictionary<object, object>();
private readonly List<Func<ShellScope, Task>> _beforeDispose = new List<Func<ShellScope, Task>>();
private readonly HashSet<string> _deferredSignals = new HashSet<string>();
private readonly List<Func<ShellScope, Task>> _deferredTasks = new List<Func<ShellScope, Task>>();
private readonly List<Func<ShellScope, Exception, Task>> _exceptionHandlers = new List<Func<ShellScope, Exception, Task>>();
private bool _serviceScopeOnly;
private bool _shellTerminated;
private bool _terminated;
private bool _disposed;
public ShellScope(ShellContext shellContext)
{
// Prevent the context from being disposed until the end of the scope
Interlocked.Increment(ref shellContext._refCount);
ShellContext = shellContext;
// The service provider is null if we try to create
// a scope on a disabled shell or already disposed.
if (shellContext.ServiceProvider == null)
{
// Keep the counter clean before failing.
Interlocked.Decrement(ref shellContext._refCount);
throw new ArgumentNullException(nameof(shellContext.ServiceProvider),
$"Can't resolve a scope on tenant: {shellContext.Settings.Name}");
}
_serviceScope = shellContext.ServiceProvider.CreateScope();
ServiceProvider = _serviceScope.ServiceProvider;
}
public ShellContext ShellContext { get; }
public IServiceProvider ServiceProvider { get; }
/// <summary>
/// Retrieve the 'ShellContext' of the current shell scope.
/// </summary>
public static ShellContext Context => Current?.ShellContext;
/// <summary>
/// Retrieve the 'IServiceProvider' of the current shell scope.
/// </summary>
public static IServiceProvider Services => Current?.ServiceProvider;
/// <summary>
/// Retrieve the current shell scope from the async flow.
/// </summary>
public static ShellScope Current => _current.Value?.Scope;
/// <summary>
/// Sets a shared item to the current shell scope.
/// </summary>
public static void Set(object key, object value)
{
if (Current != null)
{
Current._items[key] = value;
}
}
/// <summary>
/// Gets a shared item from the current shell scope.
/// </summary>
public static object Get(object key) => Current == null ? null : Current._items.TryGetValue(key, out var value) ? value : null;
/// <summary>
/// Gets a shared item of a given type from the current shell scope.
/// </summary>
public static T Get<T>(object key) => Current == null ? default : Current._items.TryGetValue(key, out var value) ? value is T item ? item : default : default;
/// <summary>
/// Gets (or creates) a shared item of a given type from the current shell scope.
/// </summary>
public static T GetOrCreate<T>(object key, Func<T> factory)
{
if (Current == null)
{
return factory();
}
if (!Current._items.TryGetValue(key, out var value) || !(value is T item))
{
Current._items[key] = item = factory();
}
return item;
}
/// <summary>
/// Gets (or creates) a shared item of a given type from the current shell scope.
/// </summary>
public static T GetOrCreate<T>(object key) where T : class, new()
{
if (Current == null)
{
return new T();
}
if (!Current._items.TryGetValue(key, out var value) || !(value is T item))
{
Current._items[key] = item = new T();
}
return item;
}
/// <summary>
/// Sets a shared feature to the current shell scope.
/// </summary>
public static void SetFeature<T>(T value) => Set(typeof(T), value);
/// <summary>
/// Gets a shared feature from the current shell scope.
/// </summary>
public static T GetFeature<T>() => Get<T>(typeof(T));
/// <summary>
/// Gets (or creates) a shared feature from the current shell scope.
/// </summary>
public static T GetOrCreateFeature<T>(Func<T> factory) => GetOrCreate(typeof(T), factory);
/// <summary>
/// Gets (or creates) a shared feature from the current shell scope.
/// </summary>
public static T GetOrCreateFeature<T>() where T : class, new() => GetOrCreate<T>(typeof(T));
/// <summary>
/// Creates a child scope from the current one.
/// </summary>
public static Task<ShellScope> CreateChildScopeAsync()
{
var shellHost = Services.GetRequiredService<IShellHost>();
return shellHost.GetScopeAsync(Context.Settings);
}
/// <summary>
/// Creates a child scope from the current one.
/// </summary>
public static Task<ShellScope> CreateChildScopeAsync(ShellSettings settings)
{
var shellHost = Services.GetRequiredService<IShellHost>();
return shellHost.GetScopeAsync(settings);
}
/// <summary>
/// Creates a child scope from the current one.
/// </summary>
public static Task<ShellScope> CreateChildScopeAsync(string tenant)
{
var shellHost = Services.GetRequiredService<IShellHost>();
return shellHost.GetScopeAsync(tenant);
}
/// <summary>
/// Execute a delegate using a child scope created from the current one.
/// </summary>
public static async Task UsingChildScopeAsync(Func<ShellScope, Task> execute, bool activateShell = true)
{
await (await CreateChildScopeAsync()).UsingAsync(execute, activateShell);
}
/// <summary>
/// Execute a delegate using a child scope created from the current one.
/// </summary>
public static async Task UsingChildScopeAsync(ShellSettings settings, Func<ShellScope, Task> execute, bool activateShell = true)
{
await (await CreateChildScopeAsync(settings)).UsingAsync(execute, activateShell);
}
/// <summary>
/// Execute a delegate using a child scope created from the current one.
/// </summary>
public static async Task UsingChildScopeAsync(string tenant, Func<ShellScope, Task> execute, bool activateShell = true)
{
await (await CreateChildScopeAsync(tenant)).UsingAsync(execute, activateShell);
}
/// <summary>
/// Start holding this shell scope along the async flow.
/// </summary>
public void StartAsyncFlow()
// Use an object indirection to hold the current scope in the 'AsyncLocal',
// so that it can be cleared in all execution contexts when it is cleared.
=> _current.Value = new ShellScopeHolder { Scope = this };
/// <summary>
/// Executes a delegate using this shell scope in an isolated async flow,
/// but only as a service scope without managing the shell state and
/// without invoking any tenant event.
/// </summary>
public Task UsingServiceScopeAsync(Func<ShellScope, Task> execute)
{
_serviceScopeOnly = true;
return UsingAsync(execute);
}
/// <summary>
/// Executes a delegate using this shell scope in an isolated async flow,
/// while managing the shell state and invoking tenant events.
/// </summary>
public async Task UsingAsync(Func<ShellScope, Task> execute, bool activateShell = true)
{
if (Current == this)
{
await execute(Current);
return;
}
using (this)
{
StartAsyncFlow();
try
{
try
{
if (activateShell)
{
await ActivateShellInternalAsync();
}
await execute(this);
}
finally
{
await TerminateShellInternalAsync();
}
}
catch (Exception e)
{
await HandleExceptionAsync(e);
throw;
}
finally
{
await BeforeDisposeAsync();
}
}
}
/// <summary>
/// Terminates a shell using this shell scope.
/// </summary>
internal async Task TerminateShellAsync()
{
using (this)
{
StartAsyncFlow();
await TerminateShellInternalAsync();
await BeforeDisposeAsync();
}
}
/// <summary>
/// Activate the shell, if not yet done, by calling the related tenant event handlers.
/// </summary>
internal async Task ActivateShellInternalAsync()
{
if (ShellContext.IsActivated)
{
return;
}
if (_serviceScopeOnly)
{
return;
}
// Try to acquire a lock before using a new scope, so that a next process gets the last committed data.
(var locker, var locked) = await ShellContext.TryAcquireShellActivateLockAsync();
if (!locked)
{
throw new TimeoutException($"Fails to acquire a lock before activating the tenant: {ShellContext.Settings.Name}");
}
await using var acquiredLock = locker;
// The tenant gets activated here.
if (!ShellContext.IsActivated)
{
await new ShellScope(ShellContext).UsingAsync(async scope =>
{
var tenantEvents = scope.ServiceProvider.GetServices<IModularTenantEvents>();
foreach (var tenantEvent in tenantEvents)
{
await tenantEvent.ActivatingAsync();
}
foreach (var tenantEvent in tenantEvents.Reverse())
{
await tenantEvent.ActivatedAsync();
}
}, activateShell: false);
ShellContext.IsActivated = true;
}
}
/// <summary>
/// Registers a delegate to be invoked when 'BeforeDisposeAsync()' is called on this scope.
/// </summary>
internal void BeforeDispose(Func<ShellScope, Task> callback) => _beforeDispose.Insert(0, callback);
/// <summary>
/// Adds a Signal (if not already present) to be sent just after 'BeforeDisposeAsync()'.
/// </summary>
internal void DeferredSignal(string key) => _deferredSignals.Add(key);
/// <summary>
/// Adds a Task to be executed in a new scope after 'BeforeDisposeAsync()'.
/// </summary>
internal void DeferredTask(Func<ShellScope, Task> task) => _deferredTasks.Add(task);
/// <summary>
/// Adds an handler to be invoked if an exception is thrown while executing in this shell scope.
/// </summary>
internal void ExceptionHandler(Func<ShellScope, Exception, Task> callback) => _exceptionHandlers.Add(callback);
/// <summary>
/// Registers a delegate to be invoked before the current shell scope will be disposed.
/// </summary>
public static void RegisterBeforeDispose(Func<ShellScope, Task> callback) => Current?.BeforeDispose(callback);
/// <summary>
/// Adds a Signal (if not already present) to be sent just before the current shell scope will be disposed.
/// </summary>
public static void AddDeferredSignal(string key) => Current?.DeferredSignal(key);
/// <summary>
/// Adds a Task to be executed in a new scope once the current shell scope has been disposed.
/// </summary>
public static void AddDeferredTask(Func<ShellScope, Task> task) => Current?.DeferredTask(task);
/// <summary>
/// Adds an handler to be invoked if an exception is thrown while executing in this shell scope.
/// </summary>
public static void AddExceptionHandler(Func<ShellScope, Exception, Task> handler) => Current?.ExceptionHandler(handler);
public async Task HandleExceptionAsync(Exception e)
{
foreach (var callback in _exceptionHandlers)
{
await callback(this, e);
}
}
internal async Task BeforeDisposeAsync()
{
foreach (var callback in _beforeDispose)
{
await callback(this);
}
if (_serviceScopeOnly)
{
return;
}
if (_deferredSignals.Any())
{
var signal = ShellContext.ServiceProvider.GetRequiredService<ISignal>();
foreach (var key in _deferredSignals)
{
await signal.SignalTokenAsync(key);
}
}
if (_deferredTasks.Any())
{
var shellHost = ShellContext.ServiceProvider.GetRequiredService<IShellHost>();
foreach (var task in _deferredTasks)
{
// Create a new scope (maybe based on a new shell) for each task.
ShellScope scope;
try
{
// May fail if a shell was released before being disabled.
scope = await shellHost.GetScopeAsync(ShellContext.Settings);
}
catch
{
// Fallback to a scope based on the current shell that is not yet disposed.
scope = new ShellScope(ShellContext);
}
// Use 'UsingAsync' in place of 'UsingServiceScopeAsync()' to allow a deferred task to
// trigger another one, but still prevent the shell to be activated in a deferred task.
await scope.UsingAsync(async scope =>
{
var logger = scope.ServiceProvider.GetService<ILogger<ShellScope>>();
try
{
await task(scope);
}
catch (Exception e)
{
logger?.LogError(e,
"Error while processing deferred task '{TaskName}' on tenant '{TenantName}'.",
task.GetType().FullName, ShellContext.Settings.Name);
await scope.HandleExceptionAsync(e);
}
},
activateShell: false);
}
}
}
/// <summary>
/// Terminates the shell, if released and in its last scope, by calling the related event handlers,
/// and specifies if the shell context should be disposed consequently to this scope being disposed.
/// </summary>
internal async Task TerminateShellInternalAsync()
{
if (_serviceScopeOnly)
{
return;
}
_terminated = true;
// If the shell context is released and in its last shell scope, according to the ref counter value,
// the terminate event handlers are called, and the shell will be disposed at the end of this scope.
// Check if the decremented value of the ref counter reached 0.
if (Interlocked.Decrement(ref ShellContext._refCount) == 0)
{
// A disabled shell still in use is released by its last scope.
if (ShellContext.Settings.State == TenantState.Disabled)
{
ShellContext.ReleaseFromLastScope();
}
if (!ShellContext._released)
{
return;
}
// If released after the counter reached 0, a new last scope may have been created.
if (Interlocked.CompareExchange(ref ShellContext._refCount, 0, 0) != 0)
{
return;
}
// If a new last scope reached this point, ensure that the shell is terminated once.
if (Interlocked.Exchange(ref ShellContext._terminated, 1) == 1)
{
return;
}
_shellTerminated = true;
var tenantEvents = _serviceScope.ServiceProvider.GetServices<IModularTenantEvents>();
foreach (var tenantEvent in tenantEvents)
{
await tenantEvent.TerminatingAsync();
}
foreach (var tenantEvent in tenantEvents.Reverse())
{
await tenantEvent.TerminatedAsync();
}
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_serviceScope.Dispose();
// Check if the shell has been terminated.
if (_shellTerminated)
{
ShellContext.Dispose();
}
if (!_terminated)
{
// Keep the counter clean if not yet decremented.
Interlocked.Decrement(ref ShellContext._refCount);
}
var holder = _current.Value;
if (holder != null)
{
// Clear the current scope that may be trapped in some execution contexts.
holder.Scope = null;
}
}
private class ShellScopeHolder
{
public ShellScope Scope;
}
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.