context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//#define TEST
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ICSimulator
{
public class Network
{
// dimensions
public int X, Y;
// every node has a router and a processor; not every processor is an application proc
public Router[] routers;
public Node[] nodes;
public List<Link> links;
public Workload workload;
public Golden golden;
public NodeMapping mapping;
public CmpCache cache;
public Router[] nodeRouters;
public Router[] connectRouters;
public Router[] switchRouters;
public Router[] bridgeRouters;
public Router[] L1bridgeRouters;
public Router[] L2bridgeRouters;
public Router[] L3bridgeRouters;
public Router[] L4bridgeRouters;
public Router[] nics;
public Router[] iris;
public bool[] endOfTraceBarrier;
public bool canRewind;
// Use to emulate M-to-1 traffic (i.e. ACK)
public int hotSpotNode;
public int hotSpotGenCount; // number of ACK generated which destines to the hot spot
public int [] hsReqPerNode; // hotspot node lock, set to true to ensure only one hotspot packet is generated from each node.
public int hsFlowID; // can be used to uniquely identify the mergable flow, including synchronization and ACKs.
// finish mode
public enum FinishMode { app, insn, packet, cycle, barrier };
FinishMode m_finish;
ulong m_finishCount;
public bool StopSynPktGen () {
if (Simulator.stats.generate_packet.Count >= (double)m_finishCount && finishMode == FinishMode.packet)
return true;
else
return false;
}
public FinishMode finishMode { get { return m_finish; } }
public double _cycle_netutil; // HACK -- controllers can use this.
public ulong _cycle_insns; // HACK -- controllers can use this.
public int Local_CW = 0;
public int Local_CCW = 1;
public int GL_CW = 2;
public int GL_CCW = 3;
public virtual int [] GetCWnext {get {return null;}}
public virtual int [] GetCCWnext {get {return null;}}
public Network(int dimX, int dimY)
{
X = dimX;
Y = dimY;
}
public void pickHotSpot ()
{
if ((hotSpotGenCount == Config.N - 1) || hotSpotNode == -1) {
hotSpotGenCount = 0;
hotSpotNode = Simulator.rand.Next (Config.N);
hsFlowID++;
for (int i = 0; i < Config.N; i++)
hsReqPerNode [i] = 0;
}
}
public bool endOfTraceAllDone()
{
if(canRewind == true)
return true;
for (int n = 0; n < Config.N; n++)
if(endOfTraceBarrier[n]==false)
return false;
canRewind = true;
return true;
}
// resetting all the barrier synchronously, set canRewind to false
// when the reset is done
public bool endOfTraceReset()
{
for (int n = 0; n < Config.N; n++)
if(endOfTraceBarrier[n]==true)
{
endOfTraceBarrier[n] = false;
return false;
}
canRewind = false;
return true;
}
public virtual void setup()
{
routers = new Router[Config.N];
nodes = new Node[Config.N];
links = new List<Link>();
cache = new CmpCache();
endOfTraceBarrier = new bool[Config.N];
hsReqPerNode = new int[Config.N];
canRewind = false;
hotSpotNode = -1;
hotSpotGenCount = 0;
hsFlowID = 0;
ParseFinish(Config.finish);
workload = new Workload(Config.traceFilenames);
mapping = new NodeMapping_AllCPU_SharedCache();
// create routers and nodes
for (int n = 0; n < Config.N; n++)
{
Coord c = new Coord(n);
nodes[n] = new Node(mapping, c);
routers[n] = MakeRouter(c);
nodes[n].setRouter(routers[n]);
routers[n].setNode(nodes[n]);
endOfTraceBarrier[n] = false;
hsReqPerNode [n] = 0;
#if DEBUG
Console.WriteLine ("*******This is Node {0} **********", n);
((Router_BLESS_MC)nodes [n].router).PrintMask ();
#endif
}
//Console.WriteLine ("Exit Normally!");
//System.Environment.Exit (1);
// create the Golden manager
golden = new Golden();
if (Config.RouterEvaluation)
return;
// connect the network with Links
for (int n = 0; n < Config.N; n++)
{
int x, y;
Coord.getXYfromID(n, out x, out y);
// inter-router links
for (int dir = 0; dir < 4; dir++)
{
// Clockwise 0->3 map to N->E->S->W
/* Coordinate Mapping (e.g. 16 nodes)
* (0,3) (1,3) ..... ||||| 3 7 ...
* ... ||||| 2 6 ...
* ... ||||| 1 5 ...
* (0,0) (1,0) ...... ||||| 0 4 ...
* */
int oppDir = (dir + 2) % 4; // direction from neighbor's perspective
// determine neighbor's coordinates
int x_, y_;
switch (dir)
{
case Simulator.DIR_UP: x_ = x; y_ = y + 1; break;
case Simulator.DIR_DOWN: x_ = x; y_ = y - 1; break;
case Simulator.DIR_RIGHT: x_ = x + 1; y_ = y; break;
case Simulator.DIR_LEFT: x_ = x - 1; y_ = y; break;
default: continue;
}
// If we are a torus, we manipulate x_ and y_
if(Config.torus)
{
if(x_ < 0)
x_ += X;
else if(x_ >= X)
x_ -= X;
if(y_ < 0)
y_ += Y;
else if(y_ >= Y)
y_ -= Y;
}
// mesh, not torus: detect edge
else if (x_ < 0 || x_ >= X || y_ < 0 || y_ >= Y)
{
if (Config.edge_loop)
{
Link edgeL = new Link(Config.router.linkLatency - 1);
links.Add(edgeL);
routers[Coord.getIDfromXY(x, y)].linkOut[dir] = edgeL;
routers[Coord.getIDfromXY(x, y)].linkIn[dir] = edgeL;
routers[Coord.getIDfromXY(x, y)].neighbors++;
routers[Coord.getIDfromXY(x, y)].neigh[dir] =
routers[Coord.getIDfromXY(x, y)];
}
continue;
}
// ensure no duplication by handling a link at the lexicographically
// first router
if (x_ < x || (x_ == x && y_ < y)) continue;
// Link param is *extra* latency (over the standard 1 cycle)
Link dirA = new Link(Config.router.linkLatency - 1);
Link dirB = new Link(Config.router.linkLatency - 1);
links.Add(dirA);
links.Add(dirB);
// link 'em up
routers[Coord.getIDfromXY(x, y)].linkOut[dir] = dirA;
routers[Coord.getIDfromXY(x_, y_)].linkIn[oppDir] = dirA;
routers[Coord.getIDfromXY(x, y)].linkIn[dir] = dirB;
routers[Coord.getIDfromXY(x_, y_)].linkOut[oppDir] = dirB;
routers[Coord.getIDfromXY(x, y)].neighbors++;
routers[Coord.getIDfromXY(x_, y_)].neighbors++;
routers[Coord.getIDfromXY(x, y)].neigh[dir] = routers[Coord.getIDfromXY(x_, y_)];
routers[Coord.getIDfromXY(x_, y_)].neigh[oppDir] = routers[Coord.getIDfromXY(x, y)];
if (Config.router.algorithm == RouterAlgorithm.DR_SCARAB)
{
for (int wireNr = 0; wireNr < Config.nack_nr; wireNr++)
{
Link nackA = new Link(Config.nack_linkLatency - 1);
Link nackB = new Link(Config.nack_linkLatency - 1);
links.Add(nackA);
links.Add(nackB);
((Router_SCARAB)routers[Coord.getIDfromXY(x, y)]).nackOut[dir * Config.nack_nr + wireNr] = nackA;
((Router_SCARAB)routers[Coord.getIDfromXY(x_, y_)]).nackIn[oppDir * Config.nack_nr + wireNr] = nackA;
((Router_SCARAB)routers[Coord.getIDfromXY(x, y)]).nackIn[dir * Config.nack_nr + wireNr] = nackB;
((Router_SCARAB)routers[Coord.getIDfromXY(x_, y_)]).nackOut[oppDir * Config.nack_nr + wireNr] = nackB;
}
}
}
}
// Just to verify the formed topology
//for ( int i=0; i<16; i++) {
// Console.WriteLine ("Router {0} has {1} neighbors", i, routers[i].neighbors);
//}
if (Config.torus)
for (int i = 0; i < Config.N; i++)
if (routers[i].neighbors < 4)
throw new Exception("torus construction not successful!");
}
// Pins specification for nodeRouters
public const int CW = 0; //clockwise
public const int CCW = 1; //counter clockwise
// Pins specification for connectRouters
public const int L0 = 0;
public const int L1 = 1;
public const int L2 = 2;
public const int L3 = 3;
public void setup_RingCluster_4()
{
nodeRouters = new Router_Node[Config.N];
connectRouters = new Router_Connect[6];
nodes = new Node[Config.N];
links = new List<Link>();
cache = new CmpCache();
ParseFinish(Config.finish);
workload = new Workload(Config.traceFilenames);
mapping = new NodeMapping_AllCPU_SharedCache();
// create routers and nodes
for (int n = 0; n < Config.N; n++)
{
Coord c = new Coord(n);
nodes[n] = new Node(mapping, c);
nodeRouters[n] = new Router_Node(c);
nodes[n].setRouter(nodeRouters[n]);
nodeRouters[n].setNode(nodes[n]);
}
for (int n = 0; n < 6; n++)
connectRouters[n] = new Router_Connect(n);
for (int n = 0; n < Config.N / 4; n++) // n is the cluster number
{
for (int i = 0; i < 4; i++) // for each node in the same cluster
{
if (n == 0 && i == 3 || n == 1 && i == 1 || n == 2 && i == 1 || n == 3 && i == 3)
{
Link dirA = new Link(0);
Link dirB = new Link(0);
links.Add(dirA);
links.Add(dirB);
int next = (i + 1 == 4)? n * 4 : n * 4 + i + 1;
nodeRouters[n * 4 + i].linkOut[CW] = dirA;
nodeRouters[next].linkIn[CW] = dirA;
nodeRouters[next].linkOut[CCW] = dirB;
nodeRouters[n * 4 + i].linkIn[CCW] = dirB;
}
}
}
for (int n = 0; n < 6; n++)
{
Link dirA = new Link(Config.router.linkLatency - 1);
Link dirB = new Link(Config.router.linkLatency - 1);
links.Add(dirA);
links.Add(dirB);
int[] node1 = new int[6] {1, 6, 11, 12, 0, 4};
nodeRouters[node1[n]].linkOut[CW] = dirA;
nodeRouters[node1[n]].linkIn[CCW] = dirB;
connectRouters[n].linkIn[L0] = dirA;
connectRouters[n].linkOut[L0] = dirB;
dirA = new Link(Config.router.linkLatency - 1);
dirB = new Link(Config.router.linkLatency - 1);
links.Add(dirA);
links.Add(dirB);
int[] node2 = new int[6] {2, 7, 8, 13, 1, 5};
nodeRouters[node2[n]].linkOut[CCW] = dirA;
nodeRouters[node2[n]].linkIn[CW] = dirB;
connectRouters[n].linkIn[L3] = dirA;
connectRouters[n].linkOut[L3] = dirB;
dirA = new Link(Config.router.linkLatency - 1);
dirB = new Link(Config.router.linkLatency - 1);
links.Add(dirA);
links.Add(dirB);
int[] node3 = new int[6] {4, 9, 14, 3, 15, 11};
nodeRouters[node3[n]].linkOut[CCW] = dirA;
nodeRouters[node3[n]].linkIn[CW] = dirB;
connectRouters[n].linkIn[L1] = dirA;
connectRouters[n].linkOut[L1] = dirB;
dirA = new Link(Config.router.linkLatency - 1);
dirB = new Link(Config.router.linkLatency - 1);
links.Add(dirA);
links.Add(dirB);
int[] node4 = new int[6] {7, 8, 13, 2, 14, 10};
nodeRouters[node4[n]].linkOut[CW] = dirA;
nodeRouters[node4[n]].linkIn[CCW] = dirB;
connectRouters[n].linkIn[L2] = dirA;
connectRouters[n].linkOut[L2] = dirB;
}
}
public void setup_TorusSingleRing()
{
nodeRouters = new Router_TorusRingNode[Config.N];
connectRouters = new Router_TorusRingConnect[8];
nodes = new Node[Config.N];
links = new List<Link>();
cache = new CmpCache();
ParseFinish(Config.finish);
workload = new Workload(Config.traceFilenames);
mapping = new NodeMapping_AllCPU_SharedCache();
for (int n = 0; n < Config.N; n++)
{
Coord c = new Coord(n);
nodes[n] = new Node(mapping, c);
nodeRouters[n] = new Router_TorusRingNode(c);
nodes[n].setRouter(nodeRouters[n]);
nodeRouters[n].setNode(nodes[n]);
}
for (int n = 0; n < 8; n++)
connectRouters[n] = new Router_TorusRingConnect(n);
int[] CW_Connect = new int[16] {7,0,6,1,3,1,2,0,2,5,3,4,6,4,7,5};
int[] CCW_Connect = new int[16] {1,7,0,6,0,3,1,2,4,2,5,3,5,6,4,7};
int[] dirCW = new int[16] {1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1};
int[] dirCCW = new int[16] {1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0};
for (int n = 0; n < Config.N; n++)
{
Link dirA = new Link(Config.router.linkLatency - 1);
Link dirB = new Link(Config.router.linkLatency - 1);
links.Add(dirA);
links.Add(dirB);
nodeRouters[n].linkOut[0] = dirA;
nodeRouters[n].linkIn[0] = dirB;
connectRouters[CW_Connect[n]].linkIn[dirCW[n]] = dirA;
connectRouters[CCW_Connect[n]].linkOut[dirCCW[n]] = dirB;
}
}
public virtual void doStep()
{
doStats();
// step the golden controller
golden.doStep();
// step the nodes
for (int n = 0; n < Config.N; n++)
nodes[n].doStep();
// step the network sim: first, routers
if (Config.RingClustered == false && Config.TorusSingleRing == false)
for (int n = 0; n < Config.N; n++)
routers[n].doStep();
else // RingClustered Topology dostep() OR TorusRing Topology
{
for (int n = 0; n < Config.N; n++)
nodeRouters[n].doStep();
for (int n = 0; n < 6; n++)
connectRouters[n].doStep();
}
// now, step each link
foreach (Link l in links)
l.doStep();
}
public void doStats()
{
/*
if (Simulator.CurrentRound % Config.subnet_reset_period == 0 && Simulator.CurrentRound > 0)
for (int i = 0; i < Config.sub_net; i++)
Simulator.stats.subnet_util[i].EndPeriod();
*/
int used_links = 0;
foreach (Link l in links)
if (l.Out != null)
used_links++;
this._cycle_netutil = (double)used_links / links.Count;
Simulator.stats.netutil.Add((double)used_links / links.Count);
this._cycle_insns = 0; // CPUs increment this each cycle -- we want a per-cycle sum
if (this is HR_Network && Config.N == 16)
{
int used_local = 0;
int used_global = 0;
for (int i = 0; i < Config.N; i++)
{
if (nodeRouters[i].linkIn[CW].Out != null) used_local ++;
if (nodeRouters[i].linkIn[CCW].Out != null) used_local ++;
if (switchRouters[i].linkIn[Local_CW].Out != null) used_local ++;
if (switchRouters[i].linkIn[Local_CCW].Out != null) used_local ++;
if (switchRouters[i].linkIn[GL_CW].Out != null) used_global ++;
if (switchRouters[i].linkIn[GL_CCW].Out != null) used_global ++;
}
Simulator.stats.local_net_util.Add((double)used_local / 64); // totally 32 slots in local rings
Simulator.stats.global_net_util.Add((double)used_global / 32); // totally 32 slots in global rings, but half are not visible
}
if (this is HR_4drop_Network || this is HR_8drop_Network || this is HR_16drop_Network)
{
int used_local = 0;
int used_global = 0;
for (int i = 0; i < Config.N; i++)
{
if (nodeRouters[i].linkIn[CW].Out != null) used_local ++;
if (nodeRouters[i].linkIn[CCW].Out != null) used_local ++;
}
int bridgeNum = (this is HR_8drop_Network) ? 8 : ((this is HR_4drop_Network)? 4 : ((this is HR_16drop_Network)? 16 : 0));
for (int i = 0; i < bridgeNum; i++)
{
if (bridgeRouters[i].LLinkIn[CW].Out != null) used_local ++;
if (bridgeRouters[i].LLinkIn[CCW].Out != null) used_local ++;
for (int j = 0; j < 2*Config.GlobalRingWidth; j++)
if (bridgeRouters[i].GLinkIn[j].Out != null)
{
if(i==0)
Simulator.stats.bridge0Count.Add();
if(i==1)
Simulator.stats.bridge1Count.Add();
if(i==2)
Simulator.stats.bridge2Count.Add();
if(i==3)
Simulator.stats.bridge3Count.Add();
if(i==4)
Simulator.stats.bridge4Count.Add();
if(i==5)
Simulator.stats.bridge5Count.Add();
if(i==6)
Simulator.stats.bridge6Count.Add();
if(i==7)
Simulator.stats.bridge7Count.Add();
used_global ++;
}
}
if (this is HR_4drop_Network)
{
Simulator.stats.local_net_util.Add((double)used_local / 40);
Simulator.stats.global_net_util.Add((double)used_global / 8 / Config.GlobalRingWidth); // totally 32 slots in global rings, but half are not visible
}
if (this is HR_8drop_Network)
{
Simulator.stats.local_net_util.Add((double)used_local / 48);
Simulator.stats.global_net_util.Add((double)used_global / 16 / Config.GlobalRingWidth);
}
if (this is HR_16drop_Network)
{
Simulator.stats.local_net_util.Add((double)used_local / 64);
Simulator.stats.global_net_util.Add((double)used_global / 32 / Config.GlobalRingWidth);
}
}
if (this is HR_8_8drop_Network)
{
int used_local = 0;
int used_g1 = 0;
int used_g2 = 0;
for (int i = 0; i < Config.N; i++)
{
if (nodeRouters[i].linkIn[CW].Out != null) used_local ++;
if (nodeRouters[i].linkIn[CCW].Out != null) used_local ++;
}
for (int i = 0; i < 32; i++)
{
if (L1bridgeRouters[i].LLinkIn[CW].Out != null) used_local ++;
if (L1bridgeRouters[i].LLinkIn[CCW].Out != null) used_local ++;
for (int j = 0; j < 2 * 2; j++)
if (L1bridgeRouters[i].GLinkIn[j].Out != null)
used_g1 ++;
}
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 2 * 2; j++)
if (L2bridgeRouters[i].LLinkIn[j].Out != null)
used_g1 ++;
for (int j = 0; j < 4 * 2; j++)
if (L2bridgeRouters[i].GLinkIn[j].Out != null)
used_g2 ++;
}
Simulator.stats.local_net_util.Add((double)used_local / 192);
Simulator.stats.g1_net_util.Add((double)used_g1 / 160);
Simulator.stats.g2_net_util.Add((double)used_g2 / 64);
}
}
public bool isFinished()
{
switch (m_finish)
{
case FinishMode.app:
int count = 0;
for (int i = 0; i < Config.N; i++)
if (nodes[i].Finished) count++;
return count == Config.N;
case FinishMode.cycle:
return Simulator.CurrentRound >= m_finishCount && ScoreBoard.ScoreBoardisClean();
case FinishMode.barrier:
return Simulator.CurrentBarrier >= (ulong)Config.barrier;
case FinishMode.packet:
return Simulator.stats.generate_packet.Count >= m_finishCount && ScoreBoard.ScoreBoardisClean() && (Simulator.stats.inject_flit.Count == Simulator.stats.eject_flit.Count);
}
throw new Exception("unknown finish mode");
}
public bool isLivelocked()
{
for (int i = 0; i < Config.N; i++)
if (nodes[i].Livelocked) return true;
return false;
}
public void ParseFinish(string finish)
{
// finish is "app", "insn <n>", "synth <n>", or "barrier <n>"
string[] parts = finish.Split(' ', '=');
if (parts [0] == "app")
m_finish = FinishMode.app;
else if (parts [0] == "cycle")
m_finish = FinishMode.cycle;
else if (parts [0] == "barrier")
m_finish = FinishMode.barrier;
else if (parts [0] == "packet")
m_finish = FinishMode.packet;
else
throw new Exception("unknown finish mode");
if (m_finish == FinishMode.app || m_finish == FinishMode.barrier)
m_finishCount = 0;
else
m_finishCount = UInt64.Parse(parts[1]);
}
public virtual void close()
{
if (Config.RingClustered == false)
for (int n = 0; n < Config.N; n++)
routers[n].close();
}
public void visitFlits(Flit.Visitor fv)
{
foreach (Link l in links)
l.visitFlits(fv);
foreach (Router r in routers)
r.visitFlits(fv);
foreach (Node n in nodes)
n.visitFlits(fv);
}
public delegate Flit FlitInjector();
public int injectFlits(int count, FlitInjector fi)
{
int i = 0;
for (; i < count; i++)
{
bool found = false;
foreach (Router r in routers)
if (r.canInjectFlit(null))
{
r.InjectFlit(fi());
found = true;
break;
}
if (!found)
return i;
}
return i;
}
public static Router MakeRouter(Coord c)
{
switch (Config.router.algorithm)
{
case RouterAlgorithm.DR_FLIT_SW_OF_MC:
return new Router_BLESS_MC (c);
case RouterAlgorithm.BLESS_BYPASS:
return new Router_BLESS_BYPASS(c);
case RouterAlgorithm.Router_MinBD:
return new Router_MinBD (c);
case RouterAlgorithm.DR_AFC:
return new Router_AFC(c);
case RouterAlgorithm.DR_FLIT_SWITCHED_CTLR:
return new Router_Flit_Ctlr(c);
case RouterAlgorithm.DR_FLIT_SWITCHED_OLDEST_FIRST:
return new Router_Flit_OldestFirst(c);
case RouterAlgorithm.DR_SCARAB:
return new Router_SCARAB(c);
case RouterAlgorithm.DR_FLIT_SWITCHED_GP:
return new Router_Flit_GP(c);
case RouterAlgorithm.DR_FLIT_SWITCHED_CALF:
return new Router_SortNet_GP(c);
case RouterAlgorithm.DR_FLIT_SWITCHED_CALF_OF:
return new Router_SortNet_OldestFirst(c);
case RouterAlgorithm.DR_FLIT_SWITCHED_RANDOM:
return new Router_Flit_Random(c);
case RouterAlgorithm.ROUTER_FLIT_EXHAUSTIVE:
return new Router_Flit_Exhaustive(c);
case RouterAlgorithm.OLDEST_FIRST_DO_ROUTER:
return new OldestFirstDORouter(c);
case RouterAlgorithm.ROUND_ROBIN_DO_ROUTER:
return new RoundRobinDORouter(c);
case RouterAlgorithm.STC_DO_ROUTER:
return new STC_DORouter(c);
default:
throw new Exception("invalid routing algorithm " + Config.router.algorithm);
}
}
public string portMap (int i) {
/// Helper function to map port index to N/W/E/S
/// Clockwise 0->3 map to N->E->S->W
switch (i) {
case 0: return "N";
case 1: return "E";
case 2: return "S";
case 3: return "W";
default:
return "Warning: network::portMap only map port 0-3. Need to extend it for high-radix router.";
}
}
} // end of network calss
}
| |
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
// This inventory system is totally scripted, no C++ code involved.
// It uses object datablock names to track inventory and is generally
// object type, or class, agnostic. In other words, it will inventory
// any kind of ShapeBase object, though the throw method does assume
// that the objects are small enough to throw :)
//
// For a ShapeBase object to support inventory, it must have an array
// of inventory max values:
// %this.maxInv[GunAmmo] = 100;
// %this.maxInv[SpeedGun] = 1;
// where the names "SpeedGun" and "GunAmmo" are datablocks.
//
// For objects to be inventoriable, they must provide a set of inventory
// callback methods, mainly:
// onUse
// onThrow
// onPickup
//
// Example methods are given further down. The item.cs file also contains
// example inventory items.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Inventory server commands
//-----------------------------------------------------------------------------
function serverCmdUse(%client, %data)
{
%client.getControlObject().use(%data);
}
//-----------------------------------------------------------------------------
// ShapeBase inventory support
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
function ShapeBase::use(%this, %data)
{
// Use an object in the inventory.
// Need to prevent weapon changing when zooming, but only shapes
// that have a connection.
%conn = %this.getControllingClient();
if (%conn)
{
%defaultFov = %conn.getControlCameraDefaultFov();
%fov = %conn.getControlCameraFov();
if (%fov != %defaultFov)
return false;
}
if (%this.getInventory(%data) > 0)
return %data.onUse(%this);
return false;
}
function ShapeBase::throw(%this, %data, %amount)
{
// Throw objects from inventory. The onThrow method is
// responsible for decrementing the inventory.
if (%this.getInventory(%data) > 0)
{
%obj = %data.onThrow(%this, %amount);
if (%obj)
{
%this.throwObject(%obj);
serverPlay3D(ThrowSnd, %this.getTransform());
return true;
}
}
return false;
}
function ShapeBase::pickup(%this, %obj, %amount)
{
// This method is called to pickup an object and add it to the inventory.
// The datablock onPickup method is actually responsible for doing all the
// work, including incrementing the inventory.
%data = %obj.getDatablock();
// Try and pickup the max if no value was specified
if (%amount $= "")
%amount = %this.maxInventory(%data) - %this.getInventory(%data);
// The datablock does the work...
if (%amount < 0)
%amount = 0;
if (%amount)
return %data.onPickup(%obj, %this, %amount);
return false;
}
//-----------------------------------------------------------------------------
function ShapeBase::hasInventory(%this, %data)
{
return (%this.inv[%data] > 0);
}
function ShapeBase::hasAmmo(%this, %weapon)
{
if (%weapon.image.ammo $= "")
return(true);
else
return(%this.getInventory(%weapon.image.ammo) > 0);
}
function ShapeBase::maxInventory(%this, %data)
{
if (%data.isField("clip"))
{
// Use the clip system which uses the maxInventory
// field on the ammo itself.
return %data.maxInventory;
}
else
{
// Use the ammo pool system which uses the maxInv[]
// array on the object's datablock.
// If there is no limit defined, we assume 0
return %this.getDatablock().maxInv[%data.getName()];
}
}
function ShapeBase::incInventory(%this, %data, %amount)
{
// Increment the inventory by the given amount. The return value
// is the amount actually added, which may be less than the
// requested amount due to inventory restrictions.
%max = %this.maxInventory(%data);
%total = %this.inv[%data.getName()];
if (%total < %max)
{
if (%total + %amount > %max)
%amount = %max - %total;
%this.setInventory(%data, %total + %amount);
return %amount;
}
return 0;
}
function ShapeBase::decInventory(%this, %data, %amount)
{
// Decrement the inventory by the given amount. The return value
// is the amount actually removed.
%total = %this.inv[%data.getName()];
if (%total > 0)
{
if (%total < %amount)
%amount = %total;
%this.setInventory(%data, %total - %amount);
return %amount;
}
return 0;
}
//-----------------------------------------------------------------------------
function ShapeBase::getInventory(%this, %data)
{
// Return the current inventory amount
return %this.inv[%data.getName()];
}
function ShapeBase::setInventory(%this, %data, %value)
{
// Set the inventory amount for this datablock and invoke inventory
// callbacks. All changes to inventory go through this single method.
// Impose inventory limits
if (%value < 0)
%value = 0;
else
{
%max = %this.maxInventory(%data);
if (%value > %max)
%value = %max;
}
// Set the value and invoke object callbacks
%name = %data.getName();
if (%this.inv[%name] != %value)
{
%this.inv[%name] = %value;
%data.onInventory(%this, %value);
%this.getDataBlock().onInventory(%data, %value);
}
return %value;
}
//-----------------------------------------------------------------------------
function ShapeBase::clearInventory(%this)
{
// To be filled in...
}
//-----------------------------------------------------------------------------
function ShapeBase::throwObject(%this, %obj)
{
// Throw the given object in the direction the shape is looking.
// The force value is hardcoded according to the current default
// object mass and mission gravity (20m/s^2).
%throwForce = %this.getDataBlock().throwForce;
if (!%throwForce)
%throwForce = 20;
// Start with the shape's eye vector...
%eye = %this.getEyeVector();
%vec = vectorScale(%eye, %throwForce);
// Add a vertical component to give the object a better arc
%verticalForce = %throwForce / 2;
%dot = vectorDot("0 0 1", %eye);
if (%dot < 0)
%dot = -%dot;
%vec = vectorAdd(%vec, vectorScale("0 0 "@%verticalForce, 1 - %dot));
// Add the shape's velocity
%vec = vectorAdd(%vec, %this.getVelocity());
// Set the object's position and initial velocity
%pos = getBoxCenter(%this.getWorldBox());
%obj.setTransform(%pos);
%obj.applyImpulse(%pos, %vec);
// Since the object is thrown from the center of the shape,
// the object needs to avoid colliding with it's thrower.
%obj.setCollisionTimeout(%this);
}
//-----------------------------------------------------------------------------
// Callback hooks invoked by the inventory system
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// ShapeBase object callbacks invoked by the inventory system
function ShapeBase::onInventory(%this, %data, %value)
{
// Invoked on ShapeBase objects whenever their inventory changes
// for the given datablock.
}
//-----------------------------------------------------------------------------
// ShapeBase datablock callback invoked by the inventory system.
function ShapeBaseData::onUse(%this, %user)
{
// Invoked when the object uses this datablock, should return
// true if the item was used.
return false;
}
function ShapeBaseData::onThrow(%this, %user, %amount)
{
// Invoked when the object is thrown. This method should
// construct and return the actual mission object to be
// physically thrown. This method is also responsible for
// decrementing the user's inventory.
return 0;
}
function ShapeBaseData::onPickup(%this, %obj, %user, %amount)
{
// Invoked when the user attempts to pickup this datablock object.
// The %amount argument is the space in the user's inventory for
// this type of datablock. This method is responsible for
// incrementing the user's inventory is something is addded.
// Should return true if something was added to the inventory.
return false;
}
function ShapeBaseData::onInventory(%this, %user, %value)
{
// Invoked whenever an user's inventory total changes for
// this datablock.
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.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.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ExpressRouteCircuitAuthorizationsOperations.
/// </summary>
public static partial class ExpressRouteCircuitAuthorizationsOperationsExtensions
{
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <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>
public static void Delete(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName)
{
operations.DeleteAsync(resourceGroupName, circuitName, authorizationName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <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='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <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>
public static ExpressRouteCircuitAuthorization Get(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName)
{
return operations.GetAsync(resourceGroupName, circuitName, authorizationName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <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='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitAuthorization> GetAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <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>
public static ExpressRouteCircuitAuthorization CreateOrUpdate(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <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='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitAuthorization> CreateOrUpdateAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
public static IPage<ExpressRouteCircuitAuthorization> List(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName)
{
return operations.ListAsync(resourceGroupName, circuitName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExpressRouteCircuitAuthorization>> ListAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <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>
public static void BeginDelete(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName)
{
operations.BeginDeleteAsync(resourceGroupName, circuitName, authorizationName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <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='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <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>
public static ExpressRouteCircuitAuthorization BeginCreateOrUpdate(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <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='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitAuthorization> BeginCreateOrUpdateAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </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<ExpressRouteCircuitAuthorization> ListNext(this IExpressRouteCircuitAuthorizationsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </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<ExpressRouteCircuitAuthorization>> ListNextAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HPSF.Basic
{
using System;
using System.IO;
using System.Text;
using System.Collections;
using NUnit.Framework;
using NPOI.HPSF;
using NPOI.HPSF.Wellknown;
using NPOI.Util;
/**
* Tests the basic HPSF functionality.
*
* @author Rainer Klute (klute@rainer-klute.de)
* @since 2002-07-20
* @version $Id: TestBasic.java 619848 2008-02-08 11:55:43Z klute $
*/
[TestFixture]
public class TestBasic
{
//static string dataDir = @"..\..\..\TestCases\HPSF\data\";
static String POI_FS = "TestGermanWord90.doc";
static String[] POI_FILES = new String[]
{
"\x0005SummaryInformation",
"\x0005DocumentSummaryInformation",
"WordDocument",
"\x0001CompObj",
"1Table"
};
static int BYTE_ORDER = 0xfffe;
static int FORMAT = 0x0000;
static int OS_VERSION = 0x00020A04;
static byte[] CLASS_ID =
{
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
};
static int[] SECTION_COUNT = { 1, 2 };
static bool[] IS_SUMMARY_INFORMATION = { true, false };
static bool[] IS_DOCUMENT_SUMMARY_INFORMATION = { false, true };
POIFile[] poiFiles;
/**
* Test case constructor.
*
* @param name The Test case's name.
*/
public TestBasic()
{
//FileStream data =File.OpenRead(dataDir+POI_FS);
POIDataSamples samples = POIDataSamples.GetHPSFInstance();
using (Stream data = (Stream)samples.OpenResourceAsStream(POI_FS))
{
poiFiles = Util.ReadPOIFiles(data);
}
}
/**
* Checks the names of the files in the POI filesystem. They
* are expected to be in a certain order.
*/
[Test]
public void TestReadFiles()
{
String[] expected = POI_FILES;
for (int i = 0; i < expected.Length; i++)
Assert.AreEqual(poiFiles[i].GetName(), expected[i]);
}
/**
* Tests whether property Sets can be Created from the POI
* files in the POI file system. This Test case expects the first
* file to be a {@link SummaryInformation}, the second file to be
* a {@link DocumentSummaryInformation} and the rest to be no
* property Sets. In the latter cases a {@link
* NoPropertySetStreamException} will be thrown when trying to
* Create a {@link PropertySet}.
*
* @exception IOException if an I/O exception occurs.
*
* @exception UnsupportedEncodingException if a character encoding is not
* supported.
*/
[Test]
public void TestCreatePropertySets()
{
Type[] expected = new Type[]
{
typeof(SummaryInformation),
typeof(DocumentSummaryInformation),
typeof(NoPropertySetStreamException),
typeof(NoPropertySetStreamException),
typeof(NoPropertySetStreamException)
};
for (int i = 0; i < expected.Length; i++)
{
Stream in1 = new ByteArrayInputStream(poiFiles[i].GetBytes());
Object o;
try
{
o = PropertySetFactory.Create(in1);
}
catch (NoPropertySetStreamException ex)
{
o = ex;
}
catch (MarkUnsupportedException ex)
{
o = ex;
}
in1.Close();
Assert.AreEqual(expected[i], o.GetType());
}
}
/**
* Tests the {@link PropertySet} methods. The Test file has two
* property Sets: the first one is a {@link SummaryInformation},
* the second one is a {@link DocumentSummaryInformation}.
*
* @exception IOException if an I/O exception occurs
* @exception HPSFException if any HPSF exception occurs
*/
[Test]
public void TestPropertySetMethods()
{
/* Loop over the two property Sets. */
for (int i = 0; i < 2; i++)
{
byte[] b = poiFiles[i].GetBytes();
PropertySet ps =
PropertySetFactory.Create(new ByteArrayInputStream(b));
Assert.AreEqual(ps.ByteOrder, BYTE_ORDER);
Assert.AreEqual(ps.Format, FORMAT);
Assert.AreEqual(ps.OSVersion, OS_VERSION);
byte[] a1=ps.ClassID.Bytes;
byte[] a2=CLASS_ID;
CollectionAssert.AreEqual(a1, a2);
Assert.AreEqual(ps.SectionCount, SECTION_COUNT[i]);
Assert.AreEqual(ps.IsSummaryInformation,
IS_SUMMARY_INFORMATION[i]);
Assert.AreEqual(ps.IsDocumentSummaryInformation,
IS_DOCUMENT_SUMMARY_INFORMATION[i]);
}
}
/**
* Tests the {@link Section} methods. The Test file has two
* property Sets: the first one is a {@link SummaryInformation},
* the second one is a {@link DocumentSummaryInformation}.
*
* @exception IOException if an I/O exception occurs
* @exception HPSFException if any HPSF exception occurs
*/
[Test]
public void TestSectionMethods()
{
SummaryInformation si = (SummaryInformation)
PropertySetFactory.Create(new ByteArrayInputStream
(poiFiles[0].GetBytes()));
IList sections = si.Sections;
Section s = (Section)sections[0];
Assert.IsTrue(Arrays.Equals
(s.FormatID.Bytes, SectionIDMap.SUMMARY_INFORMATION_ID));
Assert.IsNotNull(s.Properties);
Assert.AreEqual(18, s.PropertyCount);
Assert.AreEqual("Titel", s.GetProperty(2));
//Assert.assertEquals(1764, s.getSize());
Assert.AreEqual(1776, s.Size);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace DentedPixel.LTExamples{
public class TestingUnitTests : MonoBehaviour {
public GameObject cube1;
public GameObject cube2;
public GameObject cube3;
public GameObject cube4;
public GameObject cubeAlpha1;
public GameObject cubeAlpha2;
private bool eventGameObjectWasCalled = false, eventGeneralWasCalled = false;
private int lt1Id;
private LTDescr lt2;
private LTDescr lt3;
private LTDescr lt4;
private LTDescr[] groupTweens;
private GameObject[] groupGOs;
private int groupTweensCnt;
private int rotateRepeat;
private int rotateRepeatAngle;
private GameObject boxNoCollider;
private float timeElapsedNormalTimeScale;
private float timeElapsedIgnoreTimeScale;
void Awake(){
boxNoCollider = GameObject.CreatePrimitive(PrimitiveType.Cube);
Destroy( boxNoCollider.GetComponent( typeof(BoxCollider) ) as Component );
}
void Start () {
// Time.timeScale = 0.25f;
LeanTest.timeout = 46f;
LeanTest.expected = 55;
LeanTween.init(15 + 1200);
// add a listener
LeanTween.addListener(cube1, 0, eventGameObjectCalled);
LeanTest.expect(LeanTween.isTweening() == false, "NOTHING TWEEENING AT BEGINNING" );
LeanTest.expect(LeanTween.isTweening(cube1) == false, "OBJECT NOT TWEEENING AT BEGINNING" );
LeanTween.scaleX( cube4, 2f, 0f).setOnComplete( ()=>{
LeanTest.expect( cube4.transform.localScale.x == 2f, "TWEENED WITH ZERO TIME" );
});
// dispatch event that is received
LeanTween.dispatchEvent(0);
LeanTest.expect( eventGameObjectWasCalled, "EVENT GAMEOBJECT RECEIVED" );
// do not remove listener
LeanTest.expect(LeanTween.removeListener(cube2, 0, eventGameObjectCalled)==false, "EVENT GAMEOBJECT NOT REMOVED" );
// remove listener
LeanTest.expect(LeanTween.removeListener(cube1, 0, eventGameObjectCalled), "EVENT GAMEOBJECT REMOVED" );
// add a listener
LeanTween.addListener(1, eventGeneralCalled);
// dispatch event that is received
LeanTween.dispatchEvent(1);
LeanTest.expect( eventGeneralWasCalled, "EVENT ALL RECEIVED" );
// remove listener
LeanTest.expect( LeanTween.removeListener( 1, eventGeneralCalled), "EVENT ALL REMOVED" );
lt1Id = LeanTween.move( cube1, new Vector3(3f,2f,0.5f), 1.1f ).id;
LeanTween.move( cube2, new Vector3(-3f,-2f,-0.5f), 1.1f );
LeanTween.reset();
Vector3[] splineArr = new Vector3[] {new Vector3(-1f,0f,0f), new Vector3(0f,0f,0f), new Vector3(4f,0f,0f), new Vector3(20f,0f,0f), new Vector3(30f,0f,0f)};
LTSpline cr = new LTSpline( splineArr );
cr.place( cube4.transform, 0.5f );
LeanTest.expect( (Vector3.Distance( cube4.transform.position, new Vector3(10f,0f,0f) ) <= 0.7f), "SPLINE POSITIONING AT HALFWAY", "position is:"+cube4.transform.position+" but should be:(10f,0f,0f)");
LeanTween.color(cube4, Color.green, 0.01f);
// Debug.Log("Point 2:"+cr.ratioAtPoint(splineArr[2]));
// OnStart Speed Test for ignoreTimeScale vs normal timeScale
GameObject cubeDest = cubeNamed("cubeDest");
Vector3 cubeDestEnd = new Vector3(100f,20f,0f);
LeanTween.move( cubeDest, cubeDestEnd, 0.7f);
GameObject cubeToTrans = cubeNamed("cubeToTrans");
LeanTween.move( cubeToTrans, cubeDest.transform, 1.2f).setEase( LeanTweenType.easeOutQuad ).setOnComplete( ()=>{
LeanTest.expect( cubeToTrans.transform.position == cubeDestEnd, "MOVE TO TRANSFORM WORKS");
});
GameObject cubeDestroy = cubeNamed("cubeDestroy");
LeanTween.moveX( cubeDestroy, 200f, 0.05f).setDelay(0.02f).setDestroyOnComplete(true);
LeanTween.moveX( cubeDestroy, 200f, 0.1f).setDestroyOnComplete(true).setOnComplete( ()=>{
LeanTest.expect(true, "TWO DESTROY ON COMPLETE'S SUCCEED");
});
GameObject cubeSpline = cubeNamed("cubeSpline");
LeanTween.moveSpline(cubeSpline, new Vector3[]{new Vector3(0.5f,0f,0.5f),new Vector3(0.75f,0f,0.75f),new Vector3(1f,0f,1f),new Vector3(1f,0f,1f)}, 0.1f).setOnComplete( ()=>{
LeanTest.expect(Vector3.Distance(new Vector3(1f,0f,1f), cubeSpline.transform.position) < 0.01f, "SPLINE WITH TWO POINTS SUCCEEDS");
});
// This test works when it is positioned last in the test queue (probably worth fixing when you have time)
GameObject jumpCube = cubeNamed("jumpTime");
jumpCube.transform.position = new Vector3(100f,0f,0f);
jumpCube.transform.localScale *= 100f;
int jumpTimeId = LeanTween.moveX( jumpCube, 200f, 1f).id;
LeanTween.delayedCall(gameObject, 0.2f, ()=>{
LTDescr d = LeanTween.descr( jumpTimeId );
float beforeX = jumpCube.transform.position.x;
d.setTime( 0.5f );
LeanTween.delayedCall( 0.0f, ()=>{ }).setOnStart( ()=>{
float diffAmt = 1f;// This variable is dependent on a good frame-rate because it evalutes at the next Update
beforeX += Time.deltaTime * 100f * 2f;
LeanTest.expect( Mathf.Abs( jumpCube.transform.position.x - beforeX ) < diffAmt , "CHANGING TIME DOESN'T JUMP AHEAD", "Difference:"+Mathf.Abs( jumpCube.transform.position.x - beforeX ) +" beforeX:"+beforeX+" now:"+jumpCube.transform.position.x+" dt:"+Time.deltaTime);
});
});
// Tween with time of zero is needs to be set to it's final value
GameObject zeroCube = cubeNamed("zeroCube");
LeanTween.moveX( zeroCube, 10f, 0f).setOnComplete( ()=>{
LeanTest.expect( zeroCube.transform.position.x == 10f, "ZERO TIME FINSHES CORRECTLY", "final x:"+ zeroCube.transform.position.x);
});
// Scale, and OnStart
GameObject cubeScale = cubeNamed("cubeScale");
LeanTween.scale(cubeScale, new Vector3(5f,5f,5f),0.01f).setOnStart(()=>{
LeanTest.expect( true, "ON START WAS CALLED");
}).setOnComplete(()=>{
LeanTest.expect( cubeScale.transform.localScale.z == 5f, "SCALE","expected scale z:"+5f+" returned:"+cubeScale.transform.localScale.z);
});
// Rotate
GameObject cubeRotate = cubeNamed("cubeRotate");
LeanTween.rotate(cubeRotate, new Vector3(0f,180f,0f),0.02f).setOnComplete(()=>{
LeanTest.expect( cubeRotate.transform.eulerAngles.y == 180f, "ROTATE","expected rotate y:"+180f+" returned:"+cubeRotate.transform.eulerAngles.y);
});
// RotateAround
GameObject cubeRotateA = cubeNamed("cubeRotateA");
LeanTween.rotateAround(cubeRotateA,Vector3.forward,90f,0.3f).setOnComplete(()=>{
LeanTest.expect( cubeRotateA.transform.eulerAngles.z==90f, "ROTATE AROUND","expected rotate z:"+90f+" returned:"+cubeRotateA.transform.eulerAngles.z);
});
// RotateAround 360
GameObject cubeRotateB = cubeNamed("cubeRotateB");
cubeRotateB.transform.position = new Vector3(200f,10f,8f);
LeanTween.rotateAround(cubeRotateB,Vector3.forward,360f,0.3f).setPoint(new Vector3(5f,3f,2f)).setOnComplete(()=>{
LeanTest.expect( cubeRotateB.transform.position==new Vector3(200f,10f,8f), "ROTATE AROUND 360","expected rotate pos:"+(new Vector3(200f,10f,8f))+" returned:"+cubeRotateB.transform.position);
});
// Alpha, onUpdate with passing value, onComplete value
LeanTween.alpha(cubeAlpha1,0.5f,0.1f).setOnUpdate( (float val)=>{
LeanTest.expect(val!=0f ,"ON UPDATE VAL");
}).setOnCompleteParam( "Hi!" ).setOnComplete( (object completeObj)=>{
LeanTest.expect(((string)completeObj)=="Hi!","ONCOMPLETE OBJECT");
LeanTest.expect(cubeAlpha1.GetComponent<Renderer>().material.color.a == 0.5f,"ALPHA");
});
// Color
float onStartTime = -1f;
LeanTween.color(cubeAlpha2, Color.cyan, 0.3f).setOnComplete( ()=>{
LeanTest.expect(cubeAlpha2.GetComponent<Renderer>().material.color==Color.cyan, "COLOR");
LeanTest.expect(onStartTime>=0f && onStartTime<Time.time, "ON START","onStartTime:"+onStartTime+" time:"+Time.time);
}).setOnStart(()=>{
onStartTime = Time.time;
});
// moveLocalY (make sure uses y values)
Vector3 beforePos = cubeAlpha1.transform.position;
LeanTween.moveY(cubeAlpha1, 3f, 0.2f).setOnComplete( ()=>{
LeanTest.expect(cubeAlpha1.transform.position.x==beforePos.x && cubeAlpha1.transform.position.z==beforePos.z,"MOVE Y");
});
Vector3 beforePos2 = cubeAlpha2.transform.localPosition;
LeanTween.moveLocalZ(cubeAlpha2, 12f, 0.2f).setOnComplete( ()=>{
LeanTest.expect(cubeAlpha2.transform.localPosition.x==beforePos2.x && cubeAlpha2.transform.localPosition.y==beforePos2.y,"MOVE LOCAL Z","ax:"+cubeAlpha2.transform.localPosition.x+" bx:"+beforePos.x+" ay:"+cubeAlpha2.transform.localPosition.y+" by:"+beforePos2.y);
});
AudioClip audioClip = LeanAudio.createAudio(new AnimationCurve( new Keyframe(0f, 1f, 0f, -1f), new Keyframe(1f, 0f, -1f, 0f)), new AnimationCurve( new Keyframe(0f, 0.001f, 0f, 0f), new Keyframe(1f, 0.001f, 0f, 0f)), LeanAudio.options());
LeanTween.delayedSound(gameObject, audioClip, new Vector3(0f,0f,0f), 0.1f).setDelay(0.2f).setOnComplete( ()=>{
LeanTest.expect(Time.time>0,"DELAYED SOUND");
});
// value2
bool value2UpdateCalled = false;
LeanTween.value(gameObject, new Vector2(0, 0), new Vector2(256, 96), 0.1f).setOnUpdate((Vector2 value) => {
value2UpdateCalled = true;
});
LeanTween.delayedCall(0.2f, ()=>{
LeanTest.expect( value2UpdateCalled, "VALUE2 UPDATE");
} );
StartCoroutine( timeBasedTesting() );
}
private GameObject cubeNamed( string name ){
GameObject cube = Instantiate( boxNoCollider ) as GameObject;
cube.name = name;
return cube;
}
IEnumerator timeBasedTesting(){
yield return new WaitForEndOfFrame();
GameObject cubeNormal = cubeNamed("normalTimeScale");
// float timeElapsedNormal = Time.time;
LeanTween.moveX(cubeNormal, 12f, 1.5f).setIgnoreTimeScale( false ).setOnComplete( ()=>{
timeElapsedNormalTimeScale = Time.time;
});
LTDescr[] descr = LeanTween.descriptions( cubeNormal );
LeanTest.expect( descr.Length >= 0 && descr[0].to.x == 12f, "WE CAN RETRIEVE A DESCRIPTION");
GameObject cubeIgnore = cubeNamed("ignoreTimeScale");
LeanTween.moveX(cubeIgnore, 5f, 1.5f).setIgnoreTimeScale( true ).setOnComplete( ()=>{
timeElapsedIgnoreTimeScale = Time.time;
});
yield return new WaitForSeconds(1.5f);
LeanTest.expect( Mathf.Abs( timeElapsedNormalTimeScale - timeElapsedIgnoreTimeScale ) < 0.7f, "START IGNORE TIMING", "timeElapsedIgnoreTimeScale:"+timeElapsedIgnoreTimeScale+" timeElapsedNormalTimeScale:"+timeElapsedNormalTimeScale );
// yield return new WaitForSeconds(100f);
Time.timeScale = 4f;
int pauseCount = 0;
LeanTween.value( gameObject, 0f, 1f, 1f).setOnUpdate( ( float val )=>{
pauseCount++;
}).pause();
// Bezier should end at exact end position not just 99% close to it
Vector3[] roundCirc = new Vector3[]{ new Vector3(0f,0f,0f), new Vector3(-9.1f,25.1f,0f), new Vector3(-1.2f,15.9f,0f), new Vector3(-25f,25f,0f), new Vector3(-25f,25f,0f), new Vector3(-50.1f,15.9f,0f), new Vector3(-40.9f,25.1f,0f), new Vector3(-50f,0f,0f), new Vector3(-50f,0f,0f), new Vector3(-40.9f,-25.1f,0f), new Vector3(-50.1f,-15.9f,0f), new Vector3(-25f,-25f,0f), new Vector3(-25f,-25f,0f), new Vector3(0f,-15.9f,0f), new Vector3(-9.1f,-25.1f,0f), new Vector3(0f,0f,0f) };
GameObject cubeRound = cubeNamed("bRound");
Vector3 onStartPos = cubeRound.transform.position;
LeanTween.moveLocal(cubeRound, roundCirc, 0.5f).setOnComplete( ()=>{
LeanTest.expect(cubeRound.transform.position==onStartPos, "BEZIER CLOSED LOOP SHOULD END AT START","onStartPos:"+onStartPos+" onEnd:"+cubeRound.transform.position);
});
// Spline should end at exact end position not just 99% close to it
Vector3[] roundSpline = new Vector3[]{ new Vector3(0f,0f,0f), new Vector3(0f,0f,0f), new Vector3(2f,0f,0f), new Vector3(0.9f,2f,0f), new Vector3(0f,0f,0f), new Vector3(0f,0f,0f) };
GameObject cubeSpline = cubeNamed("bSpline");
Vector3 onStartPosSpline = cubeSpline.transform.position;
LeanTween.moveSplineLocal(cubeSpline, roundSpline, 0.5f).setOnComplete( ()=>{
LeanTest.expect(Vector3.Distance(onStartPosSpline, cubeSpline.transform.position) <= 0.01f, "SPLINE CLOSED LOOP SHOULD END AT START","onStartPos:"+onStartPosSpline+" onEnd:"+cubeSpline.transform.position+" dist:"+Vector3.Distance(onStartPosSpline, cubeSpline.transform.position));
});
// Groups of tweens testing
groupTweens = new LTDescr[ 1200 ];
groupGOs = new GameObject[ groupTweens.Length ];
groupTweensCnt = 0;
int descriptionMatchCount = 0;
for(int i = 0; i < groupTweens.Length; i++){
GameObject cube = cubeNamed("c"+i);
cube.transform.position = new Vector3(0,0,i*3);
groupGOs[i] = cube;
}
yield return new WaitForEndOfFrame();
bool hasGroupTweensCheckStarted = false;
int setOnStartNum = 0;
int setPosNum = 0;
bool setPosOnUpdate = true;
for(int i = 0; i < groupTweens.Length; i++){
Vector3 finalPos = transform.position + Vector3.one*3f;
Dictionary<string,object> finalDict = new Dictionary<string,object>{ {"final",finalPos}, {"go",groupGOs[i]} };
groupTweens[i] = LeanTween.move(groupGOs[i], finalPos, 3f ).setOnStart( ()=>{
setOnStartNum++;
}).setOnUpdate( (Vector3 newPosition) => {
if(transform.position.z > newPosition.z){
setPosOnUpdate = false;
}
// Debug.LogWarning("New Position: " + newPosition.ToString());
}).
setOnCompleteParam( finalDict ).
setOnComplete( (object param)=>{
Dictionary<string,object> finalDictRetr = param as Dictionary<string,object>;
Vector3 neededPos = (Vector3)finalDictRetr["final"];
GameObject tweenedGo = finalDictRetr["go"] as GameObject;
if(neededPos.ToString() == tweenedGo.transform.position.ToString())
setPosNum++;
else{
Debug.Log("neededPos:"+neededPos+" tweenedGo.transform.position:"+tweenedGo.transform.position);
}
if(hasGroupTweensCheckStarted==false){
hasGroupTweensCheckStarted = true;
LeanTween.delayedCall(gameObject, 0.1f, ()=>{
LeanTest.expect( setOnStartNum == groupTweens.Length, "SETONSTART CALLS", "expected:"+groupTweens.Length+" was:"+setOnStartNum);
LeanTest.expect( groupTweensCnt==groupTweens.Length, "GROUP FINISH", "expected "+groupTweens.Length+" tweens but got "+groupTweensCnt);
LeanTest.expect( setPosNum==groupTweens.Length, "GROUP POSITION FINISH", "expected "+groupTweens.Length+" tweens but got "+setPosNum);
LeanTest.expect( setPosOnUpdate, "GROUP POSITION ON UPDATE");
});
}
groupTweensCnt++;
});
if(LeanTween.description(groupTweens[i].id).trans==groupTweens[i].trans)
descriptionMatchCount++;
}
while (LeanTween.tweensRunning<groupTweens.Length)
yield return null;
LeanTest.expect( descriptionMatchCount==groupTweens.Length, "GROUP IDS MATCH" );
int expectedSearch = groupTweens.Length+5;
LeanTest.expect( LeanTween.maxSearch<=expectedSearch, "MAX SEARCH OPTIMIZED", "maxSearch:"+LeanTween.maxSearch+" should be:"+ expectedSearch);
LeanTest.expect( LeanTween.isTweening() == true, "SOMETHING IS TWEENING" );
// resume item before calling pause should continue item along it's way
float previousXlt4 = cube4.transform.position.x;
lt4 = LeanTween.moveX( cube4, 5.0f, 1.1f).setOnComplete( ()=>{
LeanTest.expect( cube4!=null && previousXlt4!=cube4.transform.position.x, "RESUME OUT OF ORDER", "cube4:"+cube4+" previousXlt4:"+previousXlt4+" cube4.transform.position.x:"+(cube4!=null ? cube4.transform.position.x : 0));
}).setDestroyOnComplete( true );
lt4.resume();
rotateRepeat = rotateRepeatAngle = 0;
LeanTween.rotateAround(cube3, Vector3.forward, 360f, 0.1f).setRepeat(3).setOnComplete(rotateRepeatFinished).setOnCompleteOnRepeat(true).setDestroyOnComplete(true);
yield return new WaitForEndOfFrame();
LeanTween.delayedCall(0.1f*8f+1f, rotateRepeatAllFinished);
int countBeforeCancel = LeanTween.tweensRunning;
LeanTween.cancel( lt1Id );
LeanTest.expect( countBeforeCancel==LeanTween.tweensRunning, "CANCEL AFTER RESET SHOULD FAIL", "expected "+countBeforeCancel+" but got "+LeanTween.tweensRunning);
LeanTween.cancel(cube2);
int tweenCount = 0;
for(int i = 0; i < groupTweens.Length; i++){
if(LeanTween.isTweening( groupGOs[i] ))
tweenCount++;
if(i%3==0)
LeanTween.pause( groupGOs[i] );
else if(i%3==1)
groupTweens[i].pause();
else
LeanTween.pause( groupTweens[i].id );
}
LeanTest.expect( tweenCount==groupTweens.Length, "GROUP ISTWEENING", "expected "+groupTweens.Length+" tweens but got "+tweenCount );
yield return new WaitForEndOfFrame();
tweenCount = 0;
for(int i = 0; i < groupTweens.Length; i++){
if(i%3==0)
LeanTween.resume( groupGOs[i] );
else if(i%3==1)
groupTweens[i].resume();
else
LeanTween.resume( groupTweens[i].id );
if(i%2==0 ? LeanTween.isTweening( groupTweens[i].id ) : LeanTween.isTweening( groupGOs[i] ) )
tweenCount++;
}
LeanTest.expect( tweenCount==groupTweens.Length, "GROUP RESUME" );
LeanTest.expect( LeanTween.isTweening(cube1)==false, "CANCEL TWEEN LTDESCR" );
LeanTest.expect( LeanTween.isTweening(cube2)==false, "CANCEL TWEEN LEANTWEEN" );
LeanTest.expect( pauseCount==0, "ON UPDATE NOT CALLED DURING PAUSE", "expect pause count of 0, but got "+pauseCount);
yield return new WaitForEndOfFrame();
Time.timeScale = 0.25f;
float tweenTime = 0.2f;
float expectedTime = tweenTime * (1f/Time.timeScale);
float start = Time.realtimeSinceStartup;
bool onUpdateWasCalled = false;
LeanTween.moveX(cube1, -5f, tweenTime).setOnUpdate( (float val)=>{
onUpdateWasCalled = true;
}).setOnComplete( ()=>{
float end = Time.realtimeSinceStartup;
float diff = end - start;
LeanTest.expect( Mathf.Abs( expectedTime - diff) < 0.05f, "SCALED TIMING DIFFERENCE", "expected to complete in roughly "+expectedTime+" but completed in "+diff );
LeanTest.expect( Mathf.Approximately(cube1.transform.position.x, -5f), "SCALED ENDING POSITION", "expected to end at -5f, but it ended at "+cube1.transform.position.x);
LeanTest.expect( onUpdateWasCalled, "ON UPDATE FIRED" );
});
bool didGetCorrectOnUpdate = false;
LeanTween.value(gameObject, new Vector3(1f,1f,1f), new Vector3(10f,10f,10f), 1f).setOnUpdate( ( Vector3 val )=>{
didGetCorrectOnUpdate = val.x >= 1f && val.y >= 1f && val.z >= 1f;
}).setOnComplete( ()=>{
LeanTest.expect( didGetCorrectOnUpdate, "VECTOR3 CALLBACK CALLED");
});
yield return new WaitForSeconds( expectedTime );
Time.timeScale = 1f;
int ltCount = 0;
GameObject[] allGos = FindObjectsOfType(typeof(GameObject)) as GameObject[];
foreach (GameObject go in allGos) {
if(go.name == "~LeanTween")
ltCount++;
}
LeanTest.expect( ltCount==1, "RESET CORRECTLY CLEANS UP" );
lotsOfCancels();
}
IEnumerator lotsOfCancels(){
yield return new WaitForEndOfFrame();
Time.timeScale = 4f;
int cubeCount = 10;
int[] tweensA = new int[ cubeCount ];
GameObject[] aGOs = new GameObject[ cubeCount ];
for(int i = 0; i < aGOs.Length; i++){
GameObject cube = Instantiate( boxNoCollider ) as GameObject;
cube.transform.position = new Vector3(0,0,i*2f);
cube.name = "a"+i;
aGOs[i] = cube;
tweensA[i] = LeanTween.move(cube, cube.transform.position + new Vector3(10f,0,0), 0.5f + 1f * (1.0f/(float)aGOs.Length) ).id;
LeanTween.color(cube, Color.red, 0.01f);
}
yield return new WaitForSeconds(1.0f);
int[] tweensB = new int[ cubeCount ];
GameObject[] bGOs = new GameObject[ cubeCount ];
for(int i = 0; i < bGOs.Length; i++){
GameObject cube = Instantiate( boxNoCollider ) as GameObject;
cube.transform.position = new Vector3(0,0,i*2f);
cube.name = "b"+i;
bGOs[i] = cube;
tweensB[i] = LeanTween.move(cube, cube.transform.position + new Vector3(10f,0,0), 2f).id;
}
for(int i = 0; i < aGOs.Length; i++){
LeanTween.cancel( aGOs[i] );
GameObject cube = aGOs[i];
tweensA[i] = LeanTween.move(cube, new Vector3(0,0,i*2f), 2f).id;
}
yield return new WaitForSeconds(0.5f);
for(int i = 0; i < aGOs.Length; i++){
LeanTween.cancel( aGOs[i] );
GameObject cube = aGOs[i];
tweensA[i] = LeanTween.move(cube, new Vector3(0,0,i*2f) + new Vector3(10f,0,0), 2f ).id;
}
for(int i = 0; i < bGOs.Length; i++){
LeanTween.cancel( bGOs[i] );
GameObject cube = bGOs[i];
tweensB[i] = LeanTween.move(cube, new Vector3(0,0,i*2f), 2f ).id;
}
yield return new WaitForSeconds(2.1f);
bool inFinalPlace = true;
for(int i = 0; i < aGOs.Length; i++){
if(Vector3.Distance( aGOs[i].transform.position, new Vector3(0,0,i*2f) + new Vector3(10f,0,0) ) > 0.1f)
inFinalPlace = false;
}
for(int i = 0; i < bGOs.Length; i++){
if(Vector3.Distance( bGOs[i].transform.position, new Vector3(0,0,i*2f) ) > 0.1f)
inFinalPlace = false;
}
LeanTest.expect(inFinalPlace,"AFTER LOTS OF CANCELS");
}
void rotateRepeatFinished(){
if( Mathf.Abs(cube3.transform.eulerAngles.z)<0.0001f )
rotateRepeatAngle++;
rotateRepeat++;
}
void rotateRepeatAllFinished(){
LeanTest.expect( rotateRepeatAngle==3, "ROTATE AROUND MULTIPLE", "expected 3 times received "+rotateRepeatAngle+" times" );
LeanTest.expect( rotateRepeat==3, "ROTATE REPEAT", "expected 3 times received "+rotateRepeat+" times" );
LeanTest.expect( cube3==null, "DESTROY ON COMPLETE", "cube3:"+cube3 );
}
void eventGameObjectCalled( LTEvent e ){
eventGameObjectWasCalled = true;
}
void eventGeneralCalled( LTEvent e ){
eventGeneralWasCalled = true;
}
}
}
| |
//
// Copyright (C) DataStax 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.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cassandra.Mapping;
using Cassandra.IntegrationTests.Linq.Structures;
using Cassandra.IntegrationTests.SimulacronAPI;
using Cassandra.IntegrationTests.SimulacronAPI.Models.Logs;
using Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement.Simulacron;
using Cassandra.Tests;
using Cassandra.Tests.Mapping.Pocos;
using NUnit.Framework;
namespace Cassandra.IntegrationTests.ExecutionProfiles
{
[TestFixture]
[Category(TestCategory.Short)]
public class MapperExecutionProfileTests : TestGlobals
{
private ISession _session;
private string _keyspace;
private MappingConfiguration _mappingConfig;
private List<Movie> _movieList;
private SimulacronCluster _simulacronCluster;
private IMapper _mapper;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_keyspace = TestUtils.GetUniqueKeyspaceName().ToLowerInvariant();
_simulacronCluster = SimulacronCluster.CreateNew(3);
_session = ClusterBuilder()
.AddContactPoint(_simulacronCluster.InitialContactPoint)
.WithExecutionProfiles(opts => opts
.WithProfile("testProfile", profile => profile
.WithConsistencyLevel(ConsistencyLevel.Two))
.WithDerivedProfile("testDerivedProfile", "testProfile", profile => profile
.WithConsistencyLevel(ConsistencyLevel.One)))
.WithQueryOptions(new QueryOptions().SetConsistencyLevel(ConsistencyLevel.Any))
.Build().Connect(_keyspace);
_mappingConfig = new MappingConfiguration()
.Define(new Map<Movie>().PartitionKey(c => c.Title).PartitionKey(c => c.MovieMaker).KeyspaceName(_keyspace))
.Define(new Map<Song>().PartitionKey(s => s.Id).TableName("song_insert").KeyspaceName(_keyspace));
_movieList = Movie.GetDefaultMovieList();
_mapper = new Mapper(_session, _mappingConfig);
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
_session.Cluster.Dispose();
_simulacronCluster.RemoveAsync().Wait();
}
private object[] CreatePrimeObject(Movie movie)
{
return new object[]
{
movie.MainActor,
movie.MovieMaker,
movie.Title,
movie.ExampleSet.ToArray(),
movie.Director,
movie.Year
};
}
private IThenFluent CreateThenForPrimeSelect(IWhenFluent when, IEnumerable<Movie> movies)
{
return when.ThenRowsSuccess(
new[]
{
("MainActor", DataType.Ascii),
("MovieMaker", DataType.Ascii),
("Title", DataType.Ascii),
("ExampleSet", DataType.List(DataType.Ascii)),
("Director", DataType.Ascii),
("Year", DataType.Int)
},
rows => rows.WithRows(movies.Select(CreatePrimeObject).ToArray())).WithIgnoreOnPrepare(true);
}
private void PrimeSelect(IEnumerable<Movie> movies, ConsistencyLevel consistencyLevel, string query = null)
{
var primeQuery =
CreateThenForPrimeSelect(SimulacronBase
.PrimeBuilder()
.WhenQuery(
(query ?? "SELECT MainActor, MovieMaker, Title, ExampleSet, Director, Year") + $" FROM {_keyspace}.Movie",
when => when.WithConsistency(consistencyLevel)),
movies).BuildRequest();
_simulacronCluster.Prime(primeQuery);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void Should_ExecuteFetchWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
PrimeSelect(_movieList, ConsistencyLevel.Two, "SELECT MainActor");
var movies = async
? _mapper.FetchAsync<Movie>(Cql.New($"SELECT MainActor FROM {_keyspace}.Movie").WithExecutionProfile("testProfile")).Result.ToList()
: _mapper.Fetch<Movie>(Cql.New($"SELECT MainActor FROM {_keyspace}.Movie").WithExecutionProfile("testProfile")).ToList();
CollectionAssert.AreEqual(_movieList, movies, new MovieComparer());
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void Should_ExecuteFetchPageWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
PrimeSelect(new List<Movie> { _movieList.First() }, ConsistencyLevel.One, "SELECT MovieMaker");
var movies = async
? _mapper.FetchPageAsync<Movie>(Cql.New($"SELECT MovieMaker FROM {_keyspace}.Movie").WithExecutionProfile("testDerivedProfile")).Result.ToList()
: _mapper.FetchPage<Movie>(Cql.New($"SELECT MovieMaker FROM {_keyspace}.Movie").WithExecutionProfile("testDerivedProfile")).ToList();
Assert.AreEqual(1, movies.Count);
Assert.IsTrue(new MovieComparer().Compare(_movieList.First(), movies.Single()) == 0);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void Should_ExecuteFirstWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
PrimeSelect(new List<Movie> { _movieList.Skip(1).First() }, ConsistencyLevel.Two, "SELECT Title");
var movie = async
? _mapper.FirstAsync<Movie>(Cql.New($"SELECT Title FROM {_keyspace}.Movie").WithExecutionProfile("testProfile")).Result
: _mapper.First<Movie>(Cql.New($"SELECT Title FROM {_keyspace}.Movie").WithExecutionProfile("testProfile"));
Assert.IsNotNull(movie);
Assert.IsTrue(new MovieComparer().Compare(_movieList.Skip(1).First(), movie) == 0);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void Should_ExecuteFirstOrDefaultWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
PrimeSelect(new List<Movie> { _movieList.First() }, ConsistencyLevel.Two, "SELECT Year");
var movie = async
? _mapper.FirstOrDefaultAsync<Movie>(Cql.New($"SELECT Year FROM {_keyspace}.Movie").WithExecutionProfile("testProfile")).Result
: _mapper.FirstOrDefault<Movie>(Cql.New($"SELECT Year FROM {_keyspace}.Movie").WithExecutionProfile("testProfile"));
Assert.IsNotNull(movie);
Assert.IsTrue(new MovieComparer().Compare(_movieList.First(), movie) == 0);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void Should_ExecuteSingletWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
PrimeSelect(new List<Movie> { _movieList.Skip(1).First() }, ConsistencyLevel.Two, "SELECT ExampleSet");
var movie = async
? _mapper.SingleAsync<Movie>(Cql.New($"SELECT ExampleSet FROM {_keyspace}.Movie").WithExecutionProfile("testProfile")).Result
: _mapper.Single<Movie>(Cql.New($"SELECT ExampleSet FROM {_keyspace}.Movie").WithExecutionProfile("testProfile"));
Assert.IsNotNull(movie);
Assert.IsTrue(new MovieComparer().Compare(_movieList.Skip(1).First(), movie) == 0);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void Should_ExecuteSingleOrDefaultWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
PrimeSelect(new List<Movie> { _movieList.Skip(2).First() }, ConsistencyLevel.Two, "SELECT Director");
var movie = async
? _mapper.SingleOrDefaultAsync<Movie>(Cql.New($"SELECT Director FROM {_keyspace}.Movie").WithExecutionProfile("testProfile")).Result
: _mapper.SingleOrDefault<Movie>(Cql.New($"SELECT Director FROM {_keyspace}.Movie").WithExecutionProfile("testProfile"));
Assert.IsNotNull(movie);
Assert.IsTrue(new MovieComparer().Compare(_movieList.Skip(2).First(), movie) == 0);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteInsertWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
var song = new Song
{
Id = Guid.NewGuid(),
Artist = "The Who",
Title = "Substitute",
ReleaseDate = DateTimeOffset.UtcNow
};
var insert = $"INSERT INTO {_keyspace}.song_insert (Artist, Id, ReleaseDate, Title) VALUES (?, ?, ?, ?)";
var queries = _simulacronCluster.GetQueries(insert, QueryType.Execute);
if (async)
{
await _mapper.InsertAsync(song, "testProfile", true, null).ConfigureAwait(false);
await _mapper.InsertAsync(song, "testProfile").ConfigureAwait(false);
await _mapper.InsertAsync(song, "testProfile", true).ConfigureAwait(false);
}
else
{
_mapper.Insert(song, "testProfile", true, null);
_mapper.Insert(song, "testProfile");
_mapper.Insert(song, "testProfile", true);
}
var newQueries = _simulacronCluster.GetQueries(insert, QueryType.Execute);
Assert.AreEqual(queries.Count + 3, newQueries.Count);
Assert.IsTrue(newQueries.All(q => q.ConsistencyLevel == ConsistencyLevel.Two));
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteInsertIfNotExistsWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
var song = new Song
{
Id = Guid.NewGuid(),
Artist = "The Who",
Title = "Substitute",
ReleaseDate = DateTimeOffset.UtcNow
};
var insertIfNotExists = $"INSERT INTO {_keyspace}.song_insert (Artist, Id, ReleaseDate, Title) VALUES (?, ?, ?, ?) IF NOT EXISTS";
var queries = _simulacronCluster.GetQueries(insertIfNotExists, QueryType.Execute);
if (async)
{
await _mapper.InsertIfNotExistsAsync(song, "testProfile", true, null).ConfigureAwait(false);
await _mapper.InsertIfNotExistsAsync(song, "testProfile").ConfigureAwait(false);
await _mapper.InsertIfNotExistsAsync(song, "testProfile", true).ConfigureAwait(false);
}
else
{
_mapper.InsertIfNotExists(song, "testProfile", true, null);
_mapper.InsertIfNotExists(song, "testProfile");
_mapper.InsertIfNotExists(song, "testProfile", true);
}
var newQueries = _simulacronCluster.GetQueries(insertIfNotExists, QueryType.Execute);
Assert.AreEqual(queries.Count + 3, newQueries.Count);
Assert.IsTrue(newQueries.All(q => q.ConsistencyLevel == ConsistencyLevel.Two));
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteDeleteWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
var song = new Song
{
Id = Guid.NewGuid(),
Artist = "The Who",
Title = "Substitute",
ReleaseDate = DateTimeOffset.UtcNow
};
var delete = $"DELETE FROM {_keyspace}.song_insert WHERE Id = ?";
var queries = _simulacronCluster.GetQueries(delete, QueryType.Execute);
if (async)
{
await _mapper.DeleteAsync(song, "testProfile").ConfigureAwait(false);
await _mapper.DeleteAsync<Song>(Cql.New("WHERE Id = ?", song.Id).WithExecutionProfile("testProfile")).ConfigureAwait(false);
}
else
{
_mapper.Delete(song, "testProfile");
_mapper.Delete<Song>(Cql.New("WHERE Id = ?", song.Id).WithExecutionProfile("testProfile"));
}
var newQueries = _simulacronCluster.GetQueries(delete, QueryType.Execute);
Assert.AreEqual(queries.Count + 2, newQueries.Count);
Assert.IsTrue(newQueries.All(q => q.ConsistencyLevel == ConsistencyLevel.Two));
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteDeleteIfWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
var song = new Song
{
Id = Guid.NewGuid(),
Artist = "The Who",
Title = "Substitute",
ReleaseDate = DateTimeOffset.UtcNow
};
var delete = $"DELETE FROM {_keyspace}.song_insert WHERE Id = ? IF EXISTS";
var queries = _simulacronCluster.GetQueries(delete, QueryType.Execute);
if (async)
{
await _mapper.DeleteIfAsync<Song>(Cql.New("WHERE Id = ? IF EXISTS", song.Id).WithExecutionProfile("testProfile")).ConfigureAwait(false);
}
else
{
_mapper.DeleteIf<Song>(Cql.New("WHERE Id = ? IF EXISTS", song.Id).WithExecutionProfile("testProfile"));
}
var newQueries = _simulacronCluster.GetQueries(delete, QueryType.Execute);
Assert.AreEqual(queries.Count + 1, newQueries.Count);
Assert.IsTrue(newQueries.All(q => q.ConsistencyLevel == ConsistencyLevel.Two));
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteUpdateWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
var song = new Song
{
Id = Guid.NewGuid(),
Artist = "The Who",
Title = "Substitute",
ReleaseDate = DateTimeOffset.UtcNow
};
var update = $"UPDATE {_keyspace}.song_insert SET Artist = ?, ReleaseDate = ?, Title = ? WHERE Id = ?";
var queries = _simulacronCluster.GetQueries(update, QueryType.Execute);
if (async)
{
await _mapper.UpdateAsync(song, "testProfile").ConfigureAwait(false);
await _mapper.UpdateAsync<Song>(
Cql.New("SET Artist = ?, ReleaseDate = ?, Title = ? WHERE Id = ?", song.Title, song.Artist, song.ReleaseDate, song.Id)
.WithExecutionProfile("testProfile")).ConfigureAwait(false);
}
else
{
_mapper.Update(song, "testProfile");
_mapper.Update<Song>(
Cql.New("SET Artist = ?, ReleaseDate = ?, Title = ? WHERE Id = ?", song.Title, song.Artist, song.ReleaseDate, song.Id)
.WithExecutionProfile("testProfile"));
}
var newQueries = _simulacronCluster.GetQueries(update, QueryType.Execute);
Assert.AreEqual(queries.Count + 2, newQueries.Count);
Assert.IsTrue(newQueries.All(q => q.ConsistencyLevel == ConsistencyLevel.Two));
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteUpdateIfWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
var song = new Song
{
Id = Guid.NewGuid(),
Artist = "The Who",
Title = "Substitute",
ReleaseDate = DateTimeOffset.UtcNow
};
var update = $"UPDATE {_keyspace}.song_insert SET Title = ?, Artist = ?, ReleaseDate = ? WHERE Id = ? IF EXISTS";
var queries = _simulacronCluster.GetQueries(update, QueryType.Execute);
if (async)
{
await _mapper.UpdateIfAsync<Song>(
Cql.New("SET Title = ?, Artist = ?, ReleaseDate = ? WHERE Id = ? IF EXISTS", song.Title, song.Artist, song.ReleaseDate, song.Id)
.WithExecutionProfile("testProfile")).ConfigureAwait(false);
}
else
{
_mapper.UpdateIf<Song>(
Cql.New("SET Title = ?, Artist = ?, ReleaseDate = ? WHERE Id = ? IF EXISTS", song.Title, song.Artist, song.ReleaseDate, song.Id)
.WithExecutionProfile("testProfile"));
}
var newQueries = _simulacronCluster.GetQueries(update, QueryType.Execute);
Assert.AreEqual(queries.Count + 1, newQueries.Count);
Assert.IsTrue(newQueries.All(q => q.ConsistencyLevel == ConsistencyLevel.Two));
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteBatchWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
var song = new Song
{
Id = Guid.NewGuid(),
Artist = "The Who",
Title = "Substitute",
ReleaseDate = DateTimeOffset.UtcNow
};
var queries = _simulacronCluster.GetQueries(null, QueryType.Batch);
var batch = _mapper.CreateBatch();
batch.InsertIfNotExists(song);
if (async)
{
await _mapper.ExecuteAsync(batch, "testProfile").ConfigureAwait(false);
}
else
{
_mapper.Execute(batch, "testProfile");
}
var newQueries = _simulacronCluster.GetQueries(null, QueryType.Batch);
Assert.AreEqual(queries.Count + 1, newQueries.Count);
Assert.AreEqual(ConsistencyLevel.Two, newQueries.Last().Frame.GetBatchMessage().ConsistencyLevel);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public async Task Should_ExecuteConditionalBatchWithExecutionProfile_When_ExecutionProfileIsProvided(bool async)
{
var song = new Song
{
Id = Guid.NewGuid(),
Artist = "The Who",
Title = "Substitute",
ReleaseDate = DateTimeOffset.UtcNow
};
var queries = _simulacronCluster.GetQueries(null, QueryType.Batch);
var batch = _mapper.CreateBatch();
batch.InsertIfNotExists(song);
if (async)
{
await _mapper.ExecuteConditionalAsync<Song>(batch, "testProfile").ConfigureAwait(false);
}
else
{
_mapper.ExecuteConditional<Song>(batch, "testProfile");
}
var newQueries = _simulacronCluster.GetQueries(null, QueryType.Batch);
Assert.AreEqual(queries.Count + 1, newQueries.Count);
Assert.AreEqual(ConsistencyLevel.Two, newQueries.Last().Frame.GetBatchMessage().ConsistencyLevel);
}
}
}
| |
using System;
namespace Pulsar.Helpers
{
/// <summary>
/// Math helper.
/// </summary>
public static class MathHelper
{
/// <summary>
/// The pi.
/// </summary>
public const float Pi = (float)Math.PI;
/// <summary>
/// The two pi.
/// </summary>
public const float TwoPi = Pi * 2;
/// <summary>
/// The e.
/// </summary>
public const float E = (float)(Math.E);
/// <summary>
/// Absolute the specified value.
/// </summary>
/// <param name="value">Value.</param>
public static float Abs(float value)
{
return Math.Abs(value);
}
/// <summary>
/// Square root the specified value.
/// </summary>
/// <param name="value">Value.</param>
public static float Sqrt(float value)
{
return (float)Math.Sqrt(value);
}
/// <summary>
/// Square the specified value.
/// </summary>
/// <param name="value">Value.</param>
public static float Square(float value)
{
return value * value;
}
/// <summary>
/// Pow the specified x by y.
/// </summary>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
public static float Pow(float x, float y)
{
return (float)Math.Pow(x, y);
}
/// <summary>
/// Acos the specified value.
/// </summary>
/// <param name="value">Value.</param>
public static float Acos(float value)
{
return (float)Math.Acos(value);
}
/// <summary>
/// Asin the specified value.
/// </summary>
/// <param name="value">Value.</param>
public static float Asin(float value)
{
return (float)Math.Asin(value);
}
/// <summary>
/// Atan the specified value.
/// </summary>
/// <param name="value">Value.</param>
public static float Atan(float value)
{
return (float)Math.Atan(value);
}
/// <summary>
/// Atan2 the specified y and x.
/// </summary>
/// <param name="y">The y coordinate.</param>
/// <param name="x">The x coordinate.</param>
public static float Atan2(float y, float x)
{
return (float)Math.Atan2(y, x);
}
/// <summary>
/// Sin the specified value.
/// </summary>
/// <param name="value">Value.</param>
public static float Sin(float value)
{
return (float)Math.Sin(value);
}
/// <summary>
/// Tan the specified value.
/// </summary>
/// <param name="value">Value.</param>
public static float Tan(float value)
{
return (float)Math.Tan(value);
}
/// <summary>
/// Cos the specified value.
/// </summary>
/// <param name="value">Value.</param>
public static float Cos(float value)
{
return (float)Math.Cos(value);
}
/// <summary>
/// E pow the specified value.
/// </summary>
/// <param name="value">Value.</param>
public static float Exp(float value)
{
return (float)Math.Exp(value);
}
/// <summary>
/// Log E the specified value.
/// </summary>
/// <param name="value">Value.</param>
public static float Log(float value)
{
return (float)Math.Log(value);
}
/// <summary>
/// Log 10 the specified value.
/// </summary>
/// <param name="value">Value.</param>
public static float Log10(float value)
{
return (float)Math.Log10(value);
}
/// <summary>
/// Linear interpolate the specified value1 and value2 by amount.
/// </summary>
/// <param name="value1">Value1.</param>
/// <param name="value2">Value2.</param>
/// <param name="amount">Amount.</param>
public static float Lerp(float value1, float value2, float amount)
{
return value1 + (value2 - value1) * amount;
}
/// <summary>
/// Max value between value1 and value2.
/// </summary>
/// <param name="value1">Value1.</param>
/// <param name="value2">Value2.</param>
public static float Max(float value1, float value2)
{
return (value1 > value2) ? value1 : value2;
}
/// <summary>
/// Minimum value between value1 and value2.
/// </summary>
/// <param name="value1">Value1.</param>
/// <param name="value2">Value2.</param>
public static float Min(float value1, float value2)
{
return (value1 < value2) ? value1 : value2;
}
/// <summary>
/// Clamp the specified value.
/// </summary>
/// <param name="value">Value.</param>
/// <param name="min">Minimum.</param>
/// <param name="max">Max.</param>
public static float Clamp(float value, float min, float max)
{
if (value > max)
return max;
else if (value < min)
return min;
else
return value;
}
/// <summary>
/// Round the specified f.
/// </summary>
/// <param name="f">F.</param>
public static float Round(float f)
{
return (float)Math.Round(f);
}
/// <summary>
/// Round the specified f and i.
/// </summary>
/// <param name="f">F.</param>
/// <param name="i">decimal next coma to round.</param>
public static float Round(float f, int i)
{
return (float)Math.Round(f, i);
}
/// <summary>
/// Distance between point 1 and 2.
/// </summary>
/// <param name="x1">The first x value.</param>
/// <param name="y1">The first y value.</param>
/// <param name="x2">The second x value.</param>
/// <param name="y2">The second y value.</param>
public static float Distance(float x1, float y1, float x2, float y2)
{
return Sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)));
}
/// <summary>
/// Radians angle between point 1 and 2.
/// </summary>
/// <returns>The angle.</returns>
/// <param name="x1">The first x value.</param>
/// <param name="y1">The first y value.</param>
/// <param name="x2">The second x value.</param>
/// <param name="y2">The second y value.</param>
public static float RadiansAngle(float x1, float y1, float x2, float y2)
{
return Atan2(x1 - x2, y2 - y1);
}
/// <summary>
/// Convert radians to the degrees.
/// </summary>
/// <returns>The degrees.</returns>
/// <param name="radians">Radians.</param>
public static float ToDegrees(float radians)
{
return radians * (180.0f / Pi);
}
/// <summary>
/// Convert radians to degrees.
/// </summary>
/// <returns>The radians.</returns>
/// <param name="degrees">Degrees.</param>
public static float ToRadians(float degrees)
{
return degrees * (Pi / 180.0f);
}
/// <summary>
/// ClockWise direction.
/// </summary>
/// <returns><c>true</c>, if ClockWise, <c>false</c> otherwise.</returns>
/// <param name="currentAngle">Current angle.</param>
/// <param name="angleToReach">Angle to reach.</param>
public static bool ClockWiseDirection(float currentAngle, float angleToReach)
{
var clockWiseDirection = angleToReach - currentAngle;
if (clockWiseDirection > 0f && Abs(clockWiseDirection) <= 180f) return true;
if (clockWiseDirection > 0f && Abs(clockWiseDirection) > 180f) return false;
if (clockWiseDirection < 0f && Abs(clockWiseDirection) <= 180f) return false;
if (clockWiseDirection < 0f && Abs(clockWiseDirection) > 180f) return true;
return true;
}
}
}
| |
#region MIT License
/*
* Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
using AdvanceMath.Design ;
namespace AdvanceMath
{
/// <summary>
/// This is the Vector Class.
/// </summary>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29"/></remarks>
[StructLayout(LayoutKind.Sequential, Size = Point2D.Size)]
[AdvBrowsableOrder("X,Y"), Serializable]
#if !CompactFramework && !WindowsCE && !PocketPC && !XBOX360 && !SILVERLIGHT
[System.ComponentModel.TypeConverter(typeof(AdvTypeConverter<Point2D>))]
#endif
public struct Point2D : IEquatable<Point2D>
{
#region const fields
/// <summary>
/// The number of int values in the class.
/// </summary>
public const int Count = 2;
/// <summary>
/// The Size of the class in bytes;
/// </summary>
public const int Size = sizeof(int) * Count;
#endregion
#region readonly fields
/// <summary>
/// Point(0,0)
/// </summary>
public static readonly Point2D Zero = new Point2D();
private static readonly string FormatString = MatrixHelper.CreateVectorFormatString(Count);
private readonly static string FormatableString = MatrixHelper.CreateVectorFormatableString(Count);
#endregion
#region static methods
/// <summary>
/// Adds 2 Vectors2Ds.
/// </summary>
/// <param name="left">The left Point operand.</param>
/// <param name="right">The right Point operand.</param>
/// <returns>The Sum of the 2 Points.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Vector_addition_and_subtraction"/></remarks>
public static Point2D Add(Point2D left, Point2D right)
{
Point2D result;
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
return result;
}
public static void Add(ref Point2D left, ref Point2D right, out Point2D result)
{
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
}
/// <summary>
/// Subtracts 2 Points.
/// </summary>
/// <param name="left">The left Point operand.</param>
/// <param name="right">The right Point operand.</param>
/// <returns>The Difference of the 2 Points.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Vector_addition_and_subtraction"/></remarks>
public static Point2D Subtract(Point2D left, Point2D right)
{
Point2D result;
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
return result;
}
public static void Subtract(ref Point2D left, ref Point2D right, out Point2D result)
{
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
}
/// <summary>
/// Does Scaler Multiplication on a Point.
/// </summary>
/// <param name="scalar">The scalar value that will multiply the Point.</param>
/// <param name="source">The Point to be multiplied.</param>
/// <returns>The Product of the Scaler Multiplication.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#int_multiplication"/></remarks>
public static Point2D Multiply(Point2D source, int scalar)
{
Point2D result;
result.X = source.X * scalar;
result.Y = source.Y * scalar;
return result;
}
public static void Multiply(ref Point2D source, ref int scalar, out Point2D result)
{
result.X = source.X * scalar;
result.Y = source.Y * scalar;
}
public static Point2D Multiply(int scalar, Point2D source)
{
Point2D result;
result.X = scalar * source.X;
result.Y = scalar * source.Y;
return result;
}
public static void Multiply(ref int scalar, ref Point2D source, out Point2D result)
{
result.X = scalar * source.X;
result.Y = scalar * source.Y;
}
/// <summary>
/// Negates a Point.
/// </summary>
/// <param name="source">The Point to be Negated.</param>
/// <returns>The Negated Point.</returns>
public static Point2D Negate(Point2D source)
{
Point2D result;
result.X = -source.X;
result.Y = -source.Y;
return result;
}
[CLSCompliant(false)]
public static void Negate(ref Point2D source)
{
Negate(ref source, out source);
}
public static void Negate(ref Point2D source, out Point2D result)
{
result.X = -source.X;
result.Y = -source.Y;
}
public static Point2D Max(Point2D value1, Point2D value2)
{
Point2D result;
Max(ref value1, ref value2, out result);
return result;
}
public static void Max(ref Point2D value1, ref Point2D value2, out Point2D result)
{
result.X = (value1.X < value2.X) ? (value2.X) : (value1.X);
result.Y = (value1.Y < value2.Y) ? (value2.Y) : (value1.Y);
}
public static Point2D Min(Point2D value1, Point2D value2)
{
Point2D result;
Min(ref value1, ref value2, out result);
return result;
}
public static void Min(ref Point2D value1, ref Point2D value2, out Point2D result)
{
result.X = (value1.X > value2.X) ? (value2.X) : (value1.X);
result.Y = (value1.Y > value2.Y) ? (value2.Y) : (value1.Y);
}
#endregion
#region fields
/// <summary>
/// This is the X value. (Usually represents a horizontal position or direction.)
/// </summary>
[AdvBrowsable]
[XmlAttribute]
[System.ComponentModel.Description("The Magnitude on the X-Axis")]
public int X;
/// <summary>
/// This is the Y value. (Usually represents a vertical position or direction.)
/// </summary>
[AdvBrowsable]
[XmlAttribute]
[System.ComponentModel.Description("The Magnitude on the Y-Axis")]
public int Y;
#endregion
#region constructors
/// <summary>
/// Creates a New Point Instance on the Stack.
/// </summary>
/// <param name="X">The X value.</param>
/// <param name="Y">The Y value.</param>
[InstanceConstructor("X,Y")]
public Point2D(int X, int Y)
{
this.X = X;
this.Y = Y;
}
#endregion
#region operators
/// <summary>
/// Adds 2 Vectors2Ds.
/// </summary>
/// <param name="left">The left Point operand.</param>
/// <param name="right">The right Point operand.</param>
/// <returns>The Sum of the 2 Points.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Vector_addition_and_subtraction"/></remarks>
public static Point2D operator +(Point2D left, Point2D right)
{
Point2D result;
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
return result;
}
/// <summary>
/// Subtracts 2 Points.
/// </summary>
/// <param name="left">The left Point operand.</param>
/// <param name="right">The right Point operand.</param>
/// <returns>The Difference of the 2 Points.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Vector_addition_and_subtraction"/></remarks>
public static Point2D operator -(Point2D left, Point2D right)
{
Point2D result;
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
return result;
}
/// <summary>
/// Does Scaler Multiplication on a Point.
/// </summary>
/// <param name="source">The Point to be multiplied.</param>
/// <param name="scalar">The scalar value that will multiply the Point.</param>
/// <returns>The Product of the Scaler Multiplication.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#int_multiplication"/></remarks>
public static Point2D operator *(Point2D source, int scalar)
{
Point2D result;
result.X = source.X * scalar;
result.Y = source.Y * scalar;
return result;
}
/// <summary>
/// Does Scaler Multiplication on a Point.
/// </summary>
/// <param name="scalar">The scalar value that will multiply the Point.</param>
/// <param name="source">The Point to be multiplied.</param>
/// <returns>The Product of the Scaler Multiplication.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#int_multiplication"/></remarks>
public static Point2D operator *(int scalar, Point2D source)
{
Point2D result;
result.X = scalar * source.X;
result.Y = scalar * source.Y;
return result;
}
/// <summary>
/// Negates a Point.
/// </summary>
/// <param name="source">The Point to be Negated.</param>
/// <returns>The Negated Point.</returns>
public static Point2D operator -(Point2D source)
{
Point2D result;
result.X = -source.X;
result.Y = -source.Y;
return result;
}
/// <summary>
/// Specifies whether the Points contain the same coordinates.
/// </summary>
/// <param name="left">The left Point to test.</param>
/// <param name="right">The right Point to test.</param>
/// <returns>true if the Points have the same coordinates; otherwise false</returns>
public static bool operator ==(Point2D left, Point2D right)
{
return left.X == right.X && left.Y == right.Y;
}
/// <summary>
/// Specifies whether the Points do not contain the same coordinates.
/// </summary>
/// <param name="left">The left Point to test.</param>
/// <param name="right">The right Point to test.</param>
/// <returns>true if the Points do not have the same coordinates; otherwise false</returns>
public static bool operator !=(Point2D left, Point2D right)
{
return !(left.X == right.X && left.Y == right.Y);
}
#endregion
#region overrides
private string ToStringInternal(string FormatString)
{
return string.Format(FormatString, X, Y);
}
/// <summary>
/// Converts the numeric value of this instance to its equivalent string representation, using the specified format.
/// </summary>
/// <param name="format">the format for each scaler in this Vector</param>
/// <returns></returns>
public string ToString(string format)
{
return ToStringInternal(string.Format(FormatableString, format));
}
public override string ToString()
{
return ToStringInternal(FormatString);
}
#if !CompactFramework && !WindowsCE && !PocketPC && !XBOX360 && !SILVERLIGHT
public static bool TryParse(string s, out Point2D result)
{
if (s == null)
{
result = Zero;
return false;
}
string[] vals = ParseHelper.SplitStringVector(s);
if (vals.Length != Count)
{
result = Zero;
return false;
}
if (int.TryParse(vals[0], out result.X) &&
int.TryParse(vals[1], out result.Y))
{
return true;
}
else
{
result = Zero;
return false;
}
}
#endif
[ParseMethod]
public static Point2D Parse(string s)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
string[] vals = ParseHelper.SplitStringVector(s);
if (vals.Length != Count)
{
ThrowHelper.ThrowVectorFormatException(s, Count, FormatString);
}
Point2D value;
value.X = int.Parse(vals[0]);
value.Y = int.Parse(vals[1]);
return value;
}
/// <summary>
/// Provides a unique hash code based on the member variables of this
/// class. This should be done because the equality operators (==, !=)
/// have been overriden by this class.
/// <p/>
/// The standard implementation is a simple XOR operation between all local
/// member variables.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode();
}
/// <summary>
/// Compares this Vector to another object. This should be done because the
/// equality operators (==, !=) have been overriden by this class.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return (obj is Point2D) && Equals((Point2D)obj);
}
public bool Equals(Point2D other)
{
return Equals(ref this, ref other);
}
public static bool Equals(Point2D left, Point2D right)
{
return
left.X == right.X &&
left.Y == right.Y;
}
[CLSCompliant(false)]
public static bool Equals(ref Point2D left, ref Point2D right)
{
return
left.X == right.X &&
left.Y == right.Y;
}
#endregion
}
}
| |
namespace System.Data.Entity.Core.Objects.ELinq
{
using System.Collections.Generic;
using System.Data.Entity.Core.Common.CommandTrees;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Resources;
using System.Data.Entity.Utilities;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using CqtExpression = System.Data.Entity.Core.Common.CommandTrees.DbExpression;
using LinqExpression = System.Linq.Expressions.Expression;
internal sealed partial class ExpressionConverter
{
internal static class StringTranslatorUtil
{
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily",
Justification = "the same linqExpression value is never cast to ConstantExpression twice")]
internal static DbExpression ConvertToString(ExpressionConverter parent, LinqExpression linqExpression)
{
if (linqExpression.Type == typeof(object))
{
var constantExpression = linqExpression as ConstantExpression;
linqExpression =
constantExpression != null ?
Expression.Constant(constantExpression.Value) :
linqExpression.RemoveConvert();
}
var expression = parent.TranslateExpression(linqExpression);
var clrType = TypeSystem.GetNonNullableType(linqExpression.Type);
if (clrType.IsEnum)
{
//Flag enums are not supported.
if (Attribute.IsDefined(clrType, typeof(FlagsAttribute)))
{
throw new NotSupportedException(Strings.Elinq_ToStringNotSupportedForEnumsWithFlags);
}
if (linqExpression.IsNullConstant())
{
return DbExpressionBuilder.Constant(string.Empty);
}
//Constant expression, optimize to constant name
if (linqExpression.NodeType == ExpressionType.Constant)
{
var value = ((ConstantExpression)linqExpression).Value;
var name = Enum.GetName(clrType, value) ?? value.ToString();
return DbExpressionBuilder.Constant(name);
}
var integralType = clrType.GetEnumUnderlyingType();
var type = parent.GetValueLayerType(integralType);
var values = clrType.GetEnumValues()
.Cast<object>()
.Select(v => System.Convert.ChangeType(v, integralType, CultureInfo.InvariantCulture)) //cast to integral type so that unmapped enum types works too
.Select(v => DbExpressionBuilder.Constant(v))
.Select(c => (DbExpression)expression.CastTo(type).Equal(c)) //cast expression to integral type before comparing to constant
.Concat(new[] { expression.CastTo(type).IsNull() }); // default case
var names = clrType.GetEnumNames()
.Select(s => DbExpressionBuilder.Constant(s))
.Concat(new[] { DbExpressionBuilder.Constant(string.Empty) }); // default case
//translate unnamed enum values for the else clause, raw linq -> as integral value -> translate to cqt -> to string
//e.g. ((DayOfWeek)99) -> "99"
var asIntegralLinq = LinqExpression.Convert(linqExpression, integralType);
var asStringCqt = parent
.TranslateExpression(asIntegralLinq)
.CastTo(parent.GetValueLayerType(typeof(string)));
return DbExpressionBuilder.Case(values, names, asStringCqt);
}
else if (TypeSemantics.IsPrimitiveType(expression.ResultType, PrimitiveTypeKind.String))
{
return StripNull(linqExpression, expression, expression, useDatabaseNullSemantics);
}
else if (TypeSemantics.IsPrimitiveType(expression.ResultType, PrimitiveTypeKind.Guid))
{
return StripNull(linqExpression, expression, expression.CastTo(parent.GetValueLayerType(typeof(string))).ToLower(), useDatabaseNullSemantics);
}
else if (TypeSemantics.IsPrimitiveType(expression.ResultType, PrimitiveTypeKind.Boolean))
{
if (linqExpression.IsNullConstant())
{
return DbExpressionBuilder.Constant(string.Empty);
}
if (linqExpression.NodeType == ExpressionType.Constant)
{
var name = ((ConstantExpression)linqExpression).Value.ToString();
return DbExpressionBuilder.Constant(name);
}
var whenTrue = expression.Equal(DbExpressionBuilder.True);
var whenFalse = expression.Equal(DbExpressionBuilder.False);
var thenTrue = DbExpressionBuilder.Constant(true.ToString());
var thenFalse = DbExpressionBuilder.Constant(false.ToString());
return DbExpressionBuilder.Case(
new[] { whenTrue, whenFalse },
new[] { thenTrue, thenFalse },
DbExpressionBuilder.Constant(string.Empty));
}
else
{
if (!SupportsCastToString(expression.ResultType))
{
throw new NotSupportedException(
Strings.Elinq_ToStringNotSupportedForType(expression.ResultType.EdmType.Name));
}
//treat all other types as a simple cast
return StripNull(linqExpression, expression, expression.CastTo(parent.GetValueLayerType(typeof(string))));
}
}
internal static IEnumerable<Expression> GetConcatArgs(Expression linq)
{
return StripNull(linqExpression, expression, expression.CastTo(parent.GetValueLayerType(typeof(string))).ToLower(), useDatabaseNullSemantics);
if (linq.IsStringAddExpression())
{
foreach (var arg in GetConcatArgs((BinaryExpression)linq))
{
yield return arg;
}
}
else
{
yield return linq; //leaf node
}
}
internal static IEnumerable<Expression> GetConcatArgs(BinaryExpression linq)
{
// one could also flatten calls to String.Concat here, to avoid multi concat
// in "a + b + String.Concat(d, e)", just flatten it to a, b, c, d, e
//rec traverse left node
foreach (var arg in GetConcatArgs(linq.Left))
{
yield return arg;
}
//rec traverse right node
foreach (var arg in GetConcatArgs(linq.Right))
{
yield return arg;
}
}
internal static CqtExpression ConcatArgs(ExpressionConverter parent, BinaryExpression linq)
{
return ConcatArgs(parent, linq, GetConcatArgs(linq).ToArray());
}
internal static CqtExpression ConcatArgs(ExpressionConverter parent, Expression linq, Expression[] linqArgs)
{
var args = linqArgs
.Where(arg => !arg.IsNullConstant()) // remove null constants
.Select(arg => ConvertToString(parent, arg)) // Apply ToString semantics
.ToArray();
//if all args was null constants, optimize the entire expression to constant ""
// e.g null + null + null == ""
if (args.Length == 0)
{
return DbExpressionBuilder.Constant(string.Empty);
}
var current = args.First();
foreach (var next in args.Skip(1)) //concat all args
{
current = parent.CreateCanonicalFunction(Concat, linq, current, next);
}
return current;
}
internal static CqtExpression StripNull(LinqExpression sourceExpression,
DbExpression inputExpression, DbExpression outputExpression)
{
if (sourceExpression.IsNullConstant())
{
return DbExpressionBuilder.Constant(string.Empty);
}
if (sourceExpression.NodeType == ExpressionType.Constant)
{
return outputExpression;
}
// converts evaluated null values to empty string, nullable primitive properties etc.
var castNullToEmptyString = DbExpressionBuilder.Case(
new[] { inputExpression.IsNull() },
new[] { DbExpressionBuilder.Constant(string.Empty) },
outputExpression);
return castNullToEmptyString;
}
internal static bool SupportsCastToString(TypeUsage typeUsage)
{
return (TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.String)
|| TypeSemantics.IsNumericType(typeUsage)
|| TypeSemantics.IsBooleanType(typeUsage)
|| TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.DateTime)
|| TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.DateTimeOffset)
|| TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.Time)
|| TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.Guid));
}
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.Common;
namespace NLog.Conditions
{
using System;
using System.Collections.Generic;
using System.Globalization;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Condition parser. Turns a string representation of condition expression
/// into an expression tree.
/// </summary>
public class ConditionParser
{
private readonly ConditionTokenizer _tokenizer;
private readonly ConfigurationItemFactory _configurationItemFactory;
/// <summary>
/// Initializes a new instance of the <see cref="ConditionParser"/> class.
/// </summary>
/// <param name="stringReader">The string reader.</param>
/// <param name="configurationItemFactory">Instance of <see cref="ConfigurationItemFactory"/> used to resolve references to condition methods and layout renderers.</param>
private ConditionParser(SimpleStringReader stringReader, ConfigurationItemFactory configurationItemFactory)
{
_configurationItemFactory = configurationItemFactory;
_tokenizer = new ConditionTokenizer(stringReader);
}
/// <summary>
/// Parses the specified condition string and turns it into
/// <see cref="ConditionExpression"/> tree.
/// </summary>
/// <param name="expressionText">The expression to be parsed.</param>
/// <returns>The root of the expression syntax tree which can be used to get the value of the condition in a specified context.</returns>
public static ConditionExpression ParseExpression(string expressionText)
{
return ParseExpression(expressionText, ConfigurationItemFactory.Default);
}
/// <summary>
/// Parses the specified condition string and turns it into
/// <see cref="ConditionExpression"/> tree.
/// </summary>
/// <param name="expressionText">The expression to be parsed.</param>
/// <param name="configurationItemFactories">Instance of <see cref="ConfigurationItemFactory"/> used to resolve references to condition methods and layout renderers.</param>
/// <returns>The root of the expression syntax tree which can be used to get the value of the condition in a specified context.</returns>
public static ConditionExpression ParseExpression(string expressionText, ConfigurationItemFactory configurationItemFactories)
{
if (expressionText == null)
{
return null;
}
var parser = new ConditionParser(new SimpleStringReader(expressionText), configurationItemFactories);
ConditionExpression expression = parser.ParseExpression();
if (!parser._tokenizer.IsEOF())
{
throw new ConditionParseException($"Unexpected token: {parser._tokenizer.TokenValue}");
}
return expression;
}
/// <summary>
/// Parses the specified condition string and turns it into
/// <see cref="ConditionExpression"/> tree.
/// </summary>
/// <param name="stringReader">The string reader.</param>
/// <param name="configurationItemFactories">Instance of <see cref="ConfigurationItemFactory"/> used to resolve references to condition methods and layout renderers.</param>
/// <returns>
/// The root of the expression syntax tree which can be used to get the value of the condition in a specified context.
/// </returns>
internal static ConditionExpression ParseExpression(SimpleStringReader stringReader, ConfigurationItemFactory configurationItemFactories)
{
var parser = new ConditionParser(stringReader, configurationItemFactories);
ConditionExpression expression = parser.ParseExpression();
return expression;
}
private ConditionMethodExpression ParsePredicate(string functionName)
{
var par = new List<ConditionExpression>();
while (!_tokenizer.IsEOF() && _tokenizer.TokenType != ConditionTokenType.RightParen)
{
par.Add(ParseExpression());
if (_tokenizer.TokenType != ConditionTokenType.Comma)
{
break;
}
_tokenizer.GetNextToken();
}
_tokenizer.Expect(ConditionTokenType.RightParen);
try
{
var methodInfo = _configurationItemFactory.ConditionMethods.CreateInstance(functionName);
var methodDelegate = _configurationItemFactory.ConditionMethodDelegates.CreateInstance(functionName);
return new ConditionMethodExpression(functionName, methodInfo, methodDelegate, par);
}
catch (Exception exception)
{
InternalLogger.Warn(exception, "Cannot resolve function '{0}'", functionName);
if (exception.MustBeRethrownImmediately())
{
throw;
}
throw new ConditionParseException($"Cannot resolve function '{functionName}'", exception);
}
}
private ConditionExpression ParseLiteralExpression()
{
if (_tokenizer.IsToken(ConditionTokenType.LeftParen))
{
_tokenizer.GetNextToken();
ConditionExpression e = ParseExpression();
_tokenizer.Expect(ConditionTokenType.RightParen);
return e;
}
if (_tokenizer.IsToken(ConditionTokenType.Minus))
{
_tokenizer.GetNextToken();
if (!_tokenizer.IsNumber())
{
throw new ConditionParseException($"Number expected, got {_tokenizer.TokenType}");
}
return ParseNumber(true);
}
if (_tokenizer.IsNumber())
{
return ParseNumber(false);
}
if (_tokenizer.TokenType == ConditionTokenType.String)
{
ConditionExpression e = new ConditionLayoutExpression(new SimpleLayout(_tokenizer.StringTokenValue, _configurationItemFactory));
_tokenizer.GetNextToken();
return e;
}
if (_tokenizer.TokenType == ConditionTokenType.Keyword)
{
string keyword = _tokenizer.EatKeyword();
if (TryPlainKeywordToExpression(keyword, out var expression))
{
return expression;
}
if (_tokenizer.TokenType == ConditionTokenType.LeftParen)
{
_tokenizer.GetNextToken();
ConditionMethodExpression predicateExpression = ParsePredicate(keyword);
return predicateExpression;
}
}
throw new ConditionParseException("Unexpected token: " + _tokenizer.TokenValue);
}
/// <summary>
/// Try stringed keyword to <see cref="ConditionExpression"/>
/// </summary>
/// <param name="keyword"></param>
/// <param name="expression"></param>
/// <returns>success?</returns>
private bool TryPlainKeywordToExpression(string keyword, out ConditionExpression expression)
{
if (0 == string.Compare(keyword, "level", StringComparison.OrdinalIgnoreCase))
{
{
expression = new ConditionLevelExpression();
return true;
}
}
if (0 == string.Compare(keyword, "logger", StringComparison.OrdinalIgnoreCase))
{
{
expression = new ConditionLoggerNameExpression();
return true;
}
}
if (0 == string.Compare(keyword, "message", StringComparison.OrdinalIgnoreCase))
{
{
expression = new ConditionMessageExpression();
return true;
}
}
if (0 == string.Compare(keyword, "loglevel", StringComparison.OrdinalIgnoreCase))
{
_tokenizer.Expect(ConditionTokenType.Dot);
{
expression = new ConditionLiteralExpression(LogLevel.FromString(_tokenizer.EatKeyword()));
return true;
}
}
if (0 == string.Compare(keyword, "true", StringComparison.OrdinalIgnoreCase))
{
{
expression = new ConditionLiteralExpression(true);
return true;
}
}
if (0 == string.Compare(keyword, "false", StringComparison.OrdinalIgnoreCase))
{
{
expression = new ConditionLiteralExpression(false);
return true;
}
}
if (0 == string.Compare(keyword, "null", StringComparison.OrdinalIgnoreCase))
{
{
expression = new ConditionLiteralExpression(null);
return true;
}
}
expression = null;
return false;
}
/// <summary>
/// Parse number
/// </summary>
/// <param name="negative">negative number? minus should be parsed first.</param>
/// <returns></returns>
private ConditionExpression ParseNumber(bool negative)
{
string numberString = _tokenizer.TokenValue;
_tokenizer.GetNextToken();
if (numberString.IndexOf('.') >= 0)
{
var d = double.Parse(numberString, CultureInfo.InvariantCulture);
return new ConditionLiteralExpression(negative ? -d : d);
}
var i = int.Parse(numberString, CultureInfo.InvariantCulture);
return new ConditionLiteralExpression(negative ? -i : i);
}
private ConditionExpression ParseBooleanRelation()
{
ConditionExpression e = ParseLiteralExpression();
if (_tokenizer.IsToken(ConditionTokenType.EqualTo))
{
_tokenizer.GetNextToken();
return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.Equal);
}
if (_tokenizer.IsToken(ConditionTokenType.NotEqual))
{
_tokenizer.GetNextToken();
return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.NotEqual);
}
if (_tokenizer.IsToken(ConditionTokenType.LessThan))
{
_tokenizer.GetNextToken();
return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.Less);
}
if (_tokenizer.IsToken(ConditionTokenType.GreaterThan))
{
_tokenizer.GetNextToken();
return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.Greater);
}
if (_tokenizer.IsToken(ConditionTokenType.LessThanOrEqualTo))
{
_tokenizer.GetNextToken();
return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.LessOrEqual);
}
if (_tokenizer.IsToken(ConditionTokenType.GreaterThanOrEqualTo))
{
_tokenizer.GetNextToken();
return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.GreaterOrEqual);
}
return e;
}
private ConditionExpression ParseBooleanPredicate()
{
if (_tokenizer.IsKeyword("not") || _tokenizer.IsToken(ConditionTokenType.Not))
{
_tokenizer.GetNextToken();
return new ConditionNotExpression(ParseBooleanPredicate());
}
return ParseBooleanRelation();
}
private ConditionExpression ParseBooleanAnd()
{
ConditionExpression expression = ParseBooleanPredicate();
while (_tokenizer.IsKeyword("and") || _tokenizer.IsToken(ConditionTokenType.And))
{
_tokenizer.GetNextToken();
expression = new ConditionAndExpression(expression, ParseBooleanPredicate());
}
return expression;
}
private ConditionExpression ParseBooleanOr()
{
ConditionExpression expression = ParseBooleanAnd();
while (_tokenizer.IsKeyword("or") || _tokenizer.IsToken(ConditionTokenType.Or))
{
_tokenizer.GetNextToken();
expression = new ConditionOrExpression(expression, ParseBooleanAnd());
}
return expression;
}
private ConditionExpression ParseBooleanExpression()
{
return ParseBooleanOr();
}
private ConditionExpression ParseExpression()
{
return ParseBooleanExpression();
}
}
}
| |
#region PDFsharp Charting - A .NET charting library based on PDFsharp
//
// Authors:
// Niklas Schneider
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using PdfSharp.Drawing;
namespace PdfSharp.Charting.Renderers
{
/// <summary>
/// Represents a bar chart renderer.
/// </summary>
internal class BarChartRenderer : ChartRenderer
{
/// <summary>
/// Initializes a new instance of the BarChartRenderer class with the
/// specified renderer parameters.
/// </summary>
internal BarChartRenderer(RendererParameters parms)
: base(parms)
{ }
/// <summary>
/// Returns an initialized and renderer specific rendererInfo.
/// </summary>
internal override RendererInfo Init()
{
ChartRendererInfo cri = new ChartRendererInfo();
cri._chart = (Chart)_rendererParms.DrawingItem;
_rendererParms.RendererInfo = cri;
InitSeriesRendererInfo();
LegendRenderer lr = GetLegendRenderer();
cri.legendRendererInfo = (LegendRendererInfo)lr.Init();
AxisRenderer xar = new VerticalXAxisRenderer(_rendererParms);
cri.xAxisRendererInfo = (AxisRendererInfo)xar.Init();
AxisRenderer yar = GetYAxisRenderer();
cri.yAxisRendererInfo = (AxisRendererInfo)yar.Init();
PlotArea plotArea = cri._chart.PlotArea;
PlotAreaRenderer renderer = GetPlotAreaRenderer();
cri.plotAreaRendererInfo = (PlotAreaRendererInfo)renderer.Init();
DataLabelRenderer dlr = new BarDataLabelRenderer(_rendererParms);
dlr.Init();
return cri;
}
/// <summary>
/// Layouts and calculates the space used by the column chart.
/// </summary>
internal override void Format()
{
ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo;
LegendRenderer lr = GetLegendRenderer();
lr.Format();
// axes
AxisRenderer xar = new VerticalXAxisRenderer(_rendererParms);
xar.Format();
AxisRenderer yar = GetYAxisRenderer();
yar.Format();
// Calculate rects and positions.
XRect chartRect = LayoutLegend();
cri.xAxisRendererInfo.X = chartRect.Left;
cri.xAxisRendererInfo.Y = chartRect.Top;
cri.xAxisRendererInfo.Height = chartRect.Height - cri.yAxisRendererInfo.Height;
cri.yAxisRendererInfo.X = chartRect.Left + cri.xAxisRendererInfo.Width;
cri.yAxisRendererInfo.Y = chartRect.Bottom - cri.yAxisRendererInfo.Height;
cri.yAxisRendererInfo.Width = chartRect.Width - cri.xAxisRendererInfo.Width;
cri.plotAreaRendererInfo.X = cri.yAxisRendererInfo.X;
cri.plotAreaRendererInfo.Y = cri.xAxisRendererInfo.Y;
cri.plotAreaRendererInfo.Width = cri.yAxisRendererInfo.InnerRect.Width;
cri.plotAreaRendererInfo.Height = cri.xAxisRendererInfo.Height;
// Calculated remaining plot area, now it's safe to format.
PlotAreaRenderer renderer = GetPlotAreaRenderer();
renderer.Format();
DataLabelRenderer dlr = new BarDataLabelRenderer(_rendererParms);
dlr.Format();
}
/// <summary>
/// Draws the column chart.
/// </summary>
internal override void Draw()
{
ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo;
LegendRenderer lr = GetLegendRenderer();
lr.Draw();
WallRenderer wr = new WallRenderer(_rendererParms);
wr.Draw();
GridlinesRenderer glr = new BarGridlinesRenderer(_rendererParms);
glr.Draw();
PlotAreaBorderRenderer pabr = new PlotAreaBorderRenderer(_rendererParms);
pabr.Draw();
PlotAreaRenderer renderer = GetPlotAreaRenderer();
renderer.Draw();
DataLabelRenderer dlr = new BarDataLabelRenderer(_rendererParms);
dlr.Draw();
if (cri.xAxisRendererInfo._axis != null)
{
AxisRenderer xar = new VerticalXAxisRenderer(_rendererParms);
xar.Draw();
}
if (cri.yAxisRendererInfo._axis != null)
{
AxisRenderer yar = GetYAxisRenderer();
yar.Draw();
}
}
/// <summary>
/// Returns the specific plot area renderer.
/// </summary>
private PlotAreaRenderer GetPlotAreaRenderer()
{
Chart chart = (Chart)_rendererParms.DrawingItem;
switch (chart._type)
{
case ChartType.Bar2D:
return new BarClusteredPlotAreaRenderer(_rendererParms);
case ChartType.BarStacked2D:
return new BarStackedPlotAreaRenderer(_rendererParms);
}
return null;
}
/// <summary>
/// Returns the specific legend renderer.
/// </summary>
private LegendRenderer GetLegendRenderer()
{
Chart chart = (Chart)_rendererParms.DrawingItem;
switch (chart._type)
{
case ChartType.Bar2D:
return new BarClusteredLegendRenderer(_rendererParms);
case ChartType.BarStacked2D:
return new ColumnLikeLegendRenderer(_rendererParms);
}
return null;
}
/// <summary>
/// Returns the specific plot area renderer.
/// </summary>
private YAxisRenderer GetYAxisRenderer()
{
Chart chart = (Chart)_rendererParms.DrawingItem;
switch (chart._type)
{
case ChartType.Bar2D:
return new HorizontalYAxisRenderer(_rendererParms);
case ChartType.BarStacked2D:
return new HorizontalStackedYAxisRenderer(_rendererParms);
}
return null;
}
/// <summary>
/// Initializes all necessary data to draw all series for a column chart.
/// </summary>
private void InitSeriesRendererInfo()
{
ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo;
SeriesCollection seriesColl = cri._chart.SeriesCollection;
cri.seriesRendererInfos = new SeriesRendererInfo[seriesColl.Count];
// Lowest series is the first, like in Excel
for (int idx = 0; idx < seriesColl.Count; ++idx)
{
SeriesRendererInfo sri = new SeriesRendererInfo();
sri._series = seriesColl[idx];
cri.seriesRendererInfos[idx] = sri;
}
InitSeries();
}
/// <summary>
/// Initializes all necessary data to draw all series for a column chart.
/// </summary>
internal void InitSeries()
{
ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo;
int seriesIndex = 0;
foreach (SeriesRendererInfo sri in cri.seriesRendererInfos)
{
sri.LineFormat = Converter.ToXPen(sri._series._lineFormat, XColors.Black, DefaultSeriesLineWidth);
sri.FillFormat = Converter.ToXBrush(sri._series._fillFormat, ColumnColors.Item(seriesIndex++));
sri._pointRendererInfos = new ColumnRendererInfo[sri._series._seriesElements.Count];
for (int pointIdx = 0; pointIdx < sri._pointRendererInfos.Length; ++pointIdx)
{
PointRendererInfo pri = new ColumnRendererInfo();
Point point = sri._series._seriesElements[pointIdx];
pri.Point = point;
if (point != null)
{
pri.LineFormat = sri.LineFormat;
pri.FillFormat = sri.FillFormat;
if (point._lineFormat != null && !point._lineFormat._color.IsEmpty)
pri.LineFormat = Converter.ToXPen(point._lineFormat, sri.LineFormat);
if (point._fillFormat != null && !point._fillFormat._color.IsEmpty)
pri.FillFormat = new XSolidBrush(point._fillFormat._color);
}
sri._pointRendererInfos[pointIdx] = pri;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Web.Mvc;
using System.Diagnostics.Contracts;
using HyperSlackers.Bootstrap.Core;
using HyperSlackers.Bootstrap.Extensions;
namespace HyperSlackers.Bootstrap
{
/// <summary>
/// Represents a Bootstrap Carousel (slideshow) object
/// </summary>
public class Carousel : HtmlElement<Carousel>
{
// TODO: add width/height to carousel? or just make user deal with it?
internal uint indicators;
internal uint interval;
internal Icon nextIcon = new FontAwesomeIcon(FontAwesomeIconType.ChevronRight);
internal Icon prevIcon = new FontAwesomeIcon(FontAwesomeIconType.ChevronLeft);
internal bool pause;
internal bool withJs;
/// <summary>
/// Initializes a new instance of the <see cref="Carousel"/> class.
/// </summary>
/// <param name="id">The identifier.</param>
public Carousel(string id)
: base("div")
{
Contract.Requires<ArgumentException>(!id.IsNullOrWhiteSpace());
this.id = HtmlHelper.GenerateIdFromName(id);
interval = 3500;
AddClass("carousel slide");
MergeHtmlAttribute("data-ride", "carousel");
AddOrReplaceHtmlAttribute("id", this.id);
}
/// <summary>
/// Sets the icon to use for the next button.
/// </summary>
/// <param name="icon">The icon.</param>
/// <returns>The current Carousel object.</returns>
public Carousel NextIcon(GlyphIconType icon)
{
Contract.Ensures(Contract.Result<Carousel>() != null);
nextIcon = new GlyphIcon(icon);
return this;
}
/// <summary>
/// Sets the icon to use for the next button.
/// </summary>
/// <param name="icon">The icon.</param>
/// <returns>The current Carousel object.</returns>
public Carousel NextIcon(FontAwesomeIconType icon)
{
Contract.Ensures(Contract.Result<Carousel>() != null);
nextIcon = new FontAwesomeIcon(icon);
return this;
}
/// <summary>
/// Sets the icon to use for the next button.
/// </summary>
/// <param name="icon">The icon.</param>
/// <returns>
/// The current Carousel object.
/// </returns>
public Carousel NextIcon(Icon icon)
{
Contract.Requires<ArgumentNullException>(icon != null, "icon");
Contract.Ensures(Contract.Result<Carousel>() != null);
nextIcon = icon;
return this;
}
/// <summary>
/// Sets the icon to use for the next button.
/// </summary>
/// <param name="iconCssClass">The icon CSS class.</param>
/// <returns>
/// The current Carousel object.
/// </returns>
public Carousel NextIcon(string iconCssClass)
{
Contract.Requires<ArgumentException>(!iconCssClass.IsNullOrWhiteSpace());
Contract.Ensures(Contract.Result<Carousel>() != null);
nextIcon = new GlyphIcon(iconCssClass);
return this;
}
/// <summary>
/// Sets the icon to use for the previous button.
/// </summary>
/// <param name="icon">The icon.</param>
/// <returns>
/// The current Carousel object.
/// </returns>
public Carousel PrevIcon(GlyphIconType icon)
{
Contract.Ensures(Contract.Result<Carousel>() != null);
prevIcon = new GlyphIcon(icon);
return this;
}
/// <summary>
/// Sets the icon to use for the previous button.
/// </summary>
/// <param name="icon">The icon.</param>
/// <returns>
/// The current Carousel object.
/// </returns>
public Carousel PrevIcon(FontAwesomeIconType icon)
{
Contract.Ensures(Contract.Result<Carousel>() != null);
prevIcon = new FontAwesomeIcon(icon);
return this;
}
/// <summary>
/// Sets the icon to use for the previous button.
/// </summary>
/// <param name="icon">The icon.</param>
/// <returns>
/// The current Carousel object.
/// </returns>
public Carousel PrevIcon(Icon icon)
{
Contract.Requires<ArgumentNullException>(icon != null, "icon");
Contract.Ensures(Contract.Result<Carousel>() != null);
prevIcon = icon;
return this;
}
/// <summary>
/// Sets the icon to use for the previous button.
/// </summary>
/// <param name="iconCssClass">The icon CSS class.</param>
/// <returns>
/// The current Carousel object.
/// </returns>
public Carousel PrevIcon(string iconCssClass)
{
Contract.Requires<ArgumentException>(!iconCssClass.IsNullOrWhiteSpace());
Contract.Ensures(Contract.Result<Carousel>() != null);
prevIcon = new GlyphIcon(iconCssClass);
return this;
}
/// <summary>
/// Removes the sliding animation from the Carousel.
/// </summary>
/// <returns>The current carousel object.</returns>
public Carousel DontSlide()
{
Contract.Ensures(Contract.Result<Carousel>() != null);
RemoveClass("slide");
return this;
}
/// <summary>
/// Adds the specified number of indicator icons to the bottom of the Carousel.
/// </summary>
/// <param name="indicators">The number of indicators to display.</param>
/// <returns>The current carousel object.</returns>
public Carousel Indicators(uint indicators)
{
Contract.Ensures(Contract.Result<Carousel>() != null);
this.indicators = indicators;
return this;
}
/// <summary>
/// Sets the interval (in milliseconds) between slide transitions.
/// </summary>
/// <param name="interval">The interval.</param>
/// <returns>The current carousel object.</returns>
public Carousel Interval(uint interval)
{
Contract.Requires<ArgumentOutOfRangeException>(interval > 0);
Contract.Ensures(Contract.Result<Carousel>() != null);
this.interval = interval;
AddOrReplaceHtmlAttribute("data-interval", interval.ToString());
return this;
}
/// <summary>
/// Causes the Carousel to pause on mouse hover and resume animation on mouse exit.
/// </summary>
/// <returns>The current carousel object.</returns>
public Carousel Pause()
{
Contract.Ensures(Contract.Result<Carousel>() != null);
pause = true;
AddOrReplaceHtmlAttribute("data-pause", "hover");
return this;
}
/// <summary>
/// Renders javascript to begin the carousel animation.
/// </summary>
/// <returns>The current carousel object.</returns>
public Carousel WithJs()
{
Contract.Ensures(Contract.Result<Carousel>() != null);
withJs = true;
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;
using Avalonia.FreeDesktop.DBusIme.Fcitx;
using Avalonia.Input.Raw;
using Avalonia.Input.TextInput;
using Avalonia.Logging;
using Tmds.DBus;
namespace Avalonia.FreeDesktop.DBusIme
{
internal class DBusInputMethodFactory<T> : IX11InputMethodFactory where T : ITextInputMethodImpl, IX11InputMethodControl
{
private readonly Func<IntPtr, T> _factory;
public DBusInputMethodFactory(Func<IntPtr, T> factory)
{
_factory = factory;
}
public (ITextInputMethodImpl method, IX11InputMethodControl control) CreateClient(IntPtr xid)
{
var im = _factory(xid);
return (im, im);
}
}
internal abstract class DBusTextInputMethodBase : IX11InputMethodControl, ITextInputMethodImpl
{
private List<IDisposable> _disposables = new List<IDisposable>();
private Queue<string> _onlineNamesQueue = new Queue<string>();
protected Connection Connection { get; }
private readonly string[] _knownNames;
private bool _connecting;
private string _currentName;
private DBusCallQueue _queue;
private bool _controlActive, _windowActive;
private bool? _imeActive;
private Rect _logicalRect;
private PixelRect? _lastReportedRect;
private double _scaling = 1;
private PixelPoint _windowPosition;
protected bool IsConnected => _currentName != null;
public DBusTextInputMethodBase(Connection connection, params string[] knownNames)
{
_queue = new DBusCallQueue(QueueOnError);
Connection = connection;
_knownNames = knownNames;
Watch();
}
async void Watch()
{
foreach (var name in _knownNames)
_disposables.Add(await Connection.ResolveServiceOwnerAsync(name, OnNameChange));
}
protected abstract Task<bool> Connect(string name);
protected string GetAppName() =>
Application.Current.Name ?? Assembly.GetEntryAssembly()?.GetName()?.Name ?? "Avalonia";
private async void OnNameChange(ServiceOwnerChangedEventArgs args)
{
if (args.NewOwner != null && _currentName == null)
{
_onlineNamesQueue.Enqueue(args.ServiceName);
if(!_connecting)
{
_connecting = true;
try
{
while (_onlineNamesQueue.Count > 0)
{
var name = _onlineNamesQueue.Dequeue();
try
{
if (await Connect(name))
{
_onlineNamesQueue.Clear();
_currentName = name;
return;
}
}
catch (Exception e)
{
Logger.TryGet(LogEventLevel.Error, "IME")
?.Log(this, "Unable to create IME input context:\n" + e);
}
}
}
finally
{
_connecting = false;
}
}
}
// IME has crashed
if (args.NewOwner == null && args.ServiceName == _currentName)
{
_currentName = null;
foreach(var s in _disposables)
s.Dispose();
_disposables.Clear();
OnDisconnected();
Reset();
// Watch again
Watch();
}
}
protected virtual Task Disconnect()
{
return Task.CompletedTask;
}
protected virtual void OnDisconnected()
{
}
protected virtual void Reset()
{
_lastReportedRect = null;
_imeActive = null;
}
async Task QueueOnError(Exception e)
{
Logger.TryGet(LogEventLevel.Error, "IME")
?.Log(this, "Error:\n" + e);
try
{
await Disconnect();
}
catch (Exception ex)
{
Logger.TryGet(LogEventLevel.Error, "IME")
?.Log(this, "Error while destroying the context:\n" + ex);
}
OnDisconnected();
_currentName = null;
}
protected void Enqueue(Func<Task> cb) => _queue.Enqueue(cb);
protected void AddDisposable(IDisposable d) => _disposables.Add(d);
public void Dispose()
{
foreach(var d in _disposables)
d.Dispose();
_disposables.Clear();
try
{
Disconnect().ContinueWith(_ => { });
}
catch
{
// fire and forget
}
_currentName = null;
}
protected abstract Task SetCursorRectCore(PixelRect rect);
protected abstract Task SetActiveCore(bool active);
protected abstract Task ResetContextCore();
protected abstract Task<bool> HandleKeyCore(RawKeyEventArgs args, int keyVal, int keyCode);
void UpdateActive()
{
_queue.Enqueue(async () =>
{
if(!IsConnected)
return;
var active = _windowActive && _controlActive;
if (active != _imeActive)
{
_imeActive = active;
await SetActiveCore(active);
}
});
}
void IX11InputMethodControl.SetWindowActive(bool active)
{
_windowActive = active;
UpdateActive();
}
void ITextInputMethodImpl.SetActive(bool active)
{
_controlActive = active;
UpdateActive();
}
bool IX11InputMethodControl.IsEnabled => IsConnected && _imeActive == true;
async ValueTask<bool> IX11InputMethodControl.HandleEventAsync(RawKeyEventArgs args, int keyVal, int keyCode)
{
try
{
return await _queue.EnqueueAsync(async () => await HandleKeyCore(args, keyVal, keyCode));
}
// Disconnected
catch (OperationCanceledException)
{
return false;
}
// Error, disconnect
catch (Exception e)
{
await QueueOnError(e);
return false;
}
}
private Action<string> _onCommit;
event Action<string> IX11InputMethodControl.Commit
{
add => _onCommit += value;
remove => _onCommit -= value;
}
protected void FireCommit(string s) => _onCommit?.Invoke(s);
private Action<X11InputMethodForwardedKey> _onForward;
event Action<X11InputMethodForwardedKey> IX11InputMethodControl.ForwardKey
{
add => _onForward += value;
remove => _onForward -= value;
}
protected void FireForward(X11InputMethodForwardedKey k) => _onForward?.Invoke(k);
void UpdateCursorRect()
{
_queue.Enqueue(async () =>
{
if(!IsConnected)
return;
var cursorRect = PixelRect.FromRect(_logicalRect, _scaling);
cursorRect = cursorRect.Translate(_windowPosition);
if (cursorRect != _lastReportedRect)
{
_lastReportedRect = cursorRect;
await SetCursorRectCore(cursorRect);
}
});
}
void IX11InputMethodControl.UpdateWindowInfo(PixelPoint position, double scaling)
{
_windowPosition = position;
_scaling = scaling;
UpdateCursorRect();
}
void ITextInputMethodImpl.SetCursorRect(Rect rect)
{
_logicalRect = rect;
UpdateCursorRect();
}
public abstract void SetOptions(TextInputOptionsQueryEventArgs options);
void ITextInputMethodImpl.Reset()
{
Reset();
_queue.Enqueue(async () =>
{
if (!IsConnected)
return;
await ResetContextCore();
});
}
}
}
| |
using UnityEngine;
using System.Collections;
public class CustomTeleporterP : MonoBehaviour
{
//teleport instantly upon entering trigger?
public bool instantTeleport;
//teleport to a random pad?
public bool randomTeleport;
//teleport when a button is pressed?
public bool buttonTeleport;
//the name of the button
public string buttonName;
//teleport delayed?
public bool delayedTeleport;
//time it takes to teleport, if not instant
public float teleportTime = 3;
//only allow specific tag object? if left empty, any object can teleport
public string objectTag = "if empty, any object will tp";
//one or more destination pads
public Transform[] destinationPad;
//height offset
public float teleportationHeightOffset = 1;
//a private float counting down the time
private float curTeleportTime;
//private bool checking if you entered the trigger
private bool inside;
//check to wait for arrived object to leave before enabling teleporation again
[HideInInspector]
public bool arrived;
//gameobjects inside the pad
private Transform subject;
//add a sound component if you want the teleport playing a sound when teleporting
public AudioSource teleportSound;
//add a sound component for the teleport pad, vibrating for example, or music if you want :D
//also to make it more apparent when the pad is off, stop this component playing with "teleportPadSound.Stop();"
//PS the distance is set to 10 units, so you only hear it standing close, not from the other side of the map
public AudioSource teleportPadSound;
//simple enable/disable function in case you want the teleport not working at some point
//without disabling the entire script, so receiving objects still works
public bool teleportPadOn = true;
void Start ()
{
//Set the countdown ready to the time you chose
curTeleportTime = teleportTime;
}
void Update ()
{
//check if theres something/someone inside
if(inside)
{
//if that object hasnt just arrived from another pad, teleport it
if(!arrived && teleportPadOn)
Teleport();
}
}
void Teleport()
{
//if you chose to teleport instantly
if(instantTeleport)
{
//if you chose instant + random teleport, teleport to a random pad from the array
if(randomTeleport)
{
//choose a random pad from the array
int chosenPad = Random.Range(0,destinationPad.Length);
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[chosenPad].GetComponent<CustomTeleporter>().arrived = true;
//and teleport the subject
subject.transform.position = destinationPad[chosenPad].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
else //if not random, teleport to the first one in the array list
{
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[0].GetComponent<CustomTeleporter>().arrived = true;
//and teleport the subject
subject.transform.position = destinationPad[0].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
}
else if(delayedTeleport) //if its a delayed teleport
{
//start the countdown
curTeleportTime-=1 * Time.deltaTime;
//if the countdown reaches zero
if(curTeleportTime <= 0)
{
//reset the countdown
curTeleportTime = teleportTime;
//if you chose delayed + random teleport, teleport to random pad from array, after the delay
if(randomTeleport)
{
Application.LoadLevel(2);
//choose a random pad from the array
int chosenPad = Random.Range(0,destinationPad.Length);
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[chosenPad].GetComponent<CustomTeleporter>().arrived = true;
//teleport
subject.transform.position = destinationPad[chosenPad].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
else //if not random, teleport to the first one in the array list
{
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[0].GetComponent<CustomTeleporter>().arrived = true;
//teleport
subject.transform.position = destinationPad[0].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
}
}
else if(buttonTeleport) //if you selected a teleport activated by a button
{
//checks if the button you set in the inspector is being pressed
if(Input.GetButtonDown(buttonName))
{
if(delayedTeleport) //if you set it to button + delayed
{
//start the countdown
curTeleportTime-=1 * Time.deltaTime;
//if the countdown reaches zero
if(curTeleportTime <= 0)
{
//reset the countdown
curTeleportTime = teleportTime;
//if you chose delayed + random teleport + button, teleport to random pad from array, after the delay
// and button press
if(randomTeleport)
{
//choose a random pad from the array
int chosenPad = Random.Range(0,destinationPad.Length);
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[chosenPad].GetComponent<CustomTeleporter>().arrived = true;
//teleport
subject.transform.position = destinationPad[chosenPad].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
else //if not random, teleport to the first one in the array list
{
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[0].GetComponent<CustomTeleporter>().arrived = true;
//teleport
subject.transform.position = destinationPad[0].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
}
}
//if you chose button + random teleport, teleport to random pad from array, on button down
else if(randomTeleport)
{
//choose a random pad from the array
int chosenPad = Random.Range(0,destinationPad.Length);
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[chosenPad].GetComponent<CustomTeleporter>().arrived = true;
//teleport
subject.transform.position = destinationPad[chosenPad].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
else
{
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[0].GetComponent<CustomTeleporter>().arrived = true;
//teleport
subject.transform.position = destinationPad[0].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
}
}
}
void OnTriggerEnter(Collider trig)
{
Application.LoadLevel(2);
//when an object enters the trigger
//if you set a tag in the inspector, check if an object has that tag
//otherwise the pad will take in and teleport any object
if (objectTag != "")
{
//if the objects tag is the same as the one allowed in the inspector
if(trig.gameObject.tag == objectTag)
{
//set the subject to be the entered object
subject = trig.transform;
//and check inside, ready for teleport
inside = true;
//if its a button teleport, the pad should be set to be ready to teleport again
//so the player/object doesn't have to leave the pad, and re enter again, we do that here
if(buttonTeleport)
{
arrived = false;
}
}
}
else
{
//set the subject to be the entered object
subject = trig.transform;
//and check inside, ready for teleport
inside = true;
//if its a button teleport, the pad should be set to be ready to teleport again
//so the player/object doesn't have to leave the pad, and re enter again, we do that here
if(buttonTeleport)
{
arrived = false;
}
}
}
void OnTriggerExit(Collider trig)
{
//////////////if you set a tag for the entering pad, you should also set it for the exiting pad////////
//when an object exists the trigger
//if you set a tag in the inspector, check if an object has that tag
//otherwise the pad will register any object as the one leaving
if (objectTag != "")
{
//if the objects tag is the same as the one allowed in the inspector
if(trig.gameObject.tag == objectTag)
{
//set that the object left
inside = false;
//reset countdown time
curTeleportTime = teleportTime;
//if the object that left the trigger is the same object as the subject
if(trig.transform == subject)
{
//set arrived to false, so that the pad can be used again
arrived = false;
}
//remove the subject from the pads memory
subject = null;
}
}
else //if tags arent important
{
//set that the object left
inside = false;
//reset countdown time
curTeleportTime = teleportTime;
//if the object that left the trigger is the same object as the subject
if(trig.transform == subject)
{
//set arrived to false, so that the pad can be used again
arrived = false;
}
//remove the subject from the pads memory
subject = null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
namespace Saga.Tasks
{
public static class BattleThread
{
#region BattleThread Private Members
/// <summary>
/// A list with all thread states. We use multiple thread-states
/// so we can do loadbalacing over threads. In total a average
/// server has 4 cpu's (Quad-Core) therefor 4 threads would be
/// sufficient for now.
/// </summary>
private static List<ThreadState> ThreadStateList = new List<ThreadState>(4);
/// <summary>
/// Finds the most suiteable threadstate to subscribe to.
/// </summary>
/// <returns></returns>
private static int FindBestThreadStateToSubscribe()
{
//Index of the best thread count
int index = 0;
//Number of activated ai for the best ai thread
int aicount = 0;
for (int i = 0; i < ThreadStateList.Count; i++)
{
//Get the current thread state
ThreadState current = ThreadStateList[i];
//Get the current activated ai count
int count = current.Count;
//If it fits in the default capacity
if (count < current.Capacity)
{
return i;
}
else
{
if (IsLower(i, count, aicount))
{
aicount = count;
index = i;
}
}
}
//Returns the best found AI
return index;
}
private static bool IsLower(int index, int a, int b)
{
//If it is the first index
//Or find the thread with the lowest ai's to equalize them
if (index == 0 || a < b)
{
return true;
}
else
{
return false;
}
}
private static void Subscribe(IBattleArtificialIntelligence e, int index)
{
if (index < ThreadStateList.Count)
{
ThreadState current = ThreadStateList[index];
current.Add(e);
e.BattleState.Subscribe(index);
}
}
private static void Unsubscribe(IBattleArtificialIntelligence e, int index)
{
if (index < ThreadStateList.Count)
{
//Actual ubsubscribement
ThreadState current = ThreadStateList[index];
current.Remove(e);
e.BattleState.Unsubscribe(index);
}
}
private static void AddNewThread()
{
//Adds a new threadstate
ThreadStateList.Add(
new ThreadState()
);
}
internal static void Stop()
{
for (int i = 0; i < ThreadStateList.Count; i++)
ThreadStateList[i].Abort();
ThreadStateList.Clear();
}
#endregion BattleThread Private Members
#region BattleThread Public Members
/// <summary>
/// Subscribes a IBattleArtificialIntelligence member on one of the designated lists
/// to be processed.
/// </summary>
/// <param name="e"></param>
public static void Subscribe(IBattleArtificialIntelligence e)
{
//If the object is subscribed cancel
if (e.BattleState.IsSubscribed == true) return;
int index = FindBestThreadStateToSubscribe();
Subscribe(e, index);
}
/// <summary>
/// Unsubscribes a IBattleArtificialIntelligence member on one of the designated lists
/// to be processed.
/// </summary>
/// <param name="e"></param>
public static void Unsubscribe(IBattleArtificialIntelligence e)
{
//If the object is not subscribed cancel
if (e.BattleState.IsSubscribed == false) return;
int index = e.BattleState.ThreadIndex;
Unsubscribe(e, index);
}
#endregion BattleThread Public Members
#region BattleThread Nested Classes
/// <summary>
/// Interfaces our BattleThread requires for a object to have
/// </summary>
public interface IBattleArtificialIntelligence
{
/// <summary>
/// Battle state containing whether
/// </summary>
IBattlestate BattleState { get; }
/// <summary>
/// Processing statement used to fire
/// </summary>
void Process();
}
public class IBattlestate
{
private int _listupdate = 0;
private byte _threadindex;
internal byte ThreadIndex
{
get
{
return (byte)(_threadindex - 1);
}
}
public bool IsSubscribed
{
get
{
return _threadindex > 0;
}
}
public int LastUpdate
{
get
{
return this._listupdate;
}
set
{
this._listupdate = value;
}
}
internal void Subscribe(int threadindex)
{
if (_threadindex > 0) return;
_threadindex = (byte)(threadindex + 1);
_listupdate = Environment.TickCount;
}
internal void Unsubscribe(int threadindex)
{
if (_threadindex == 0) return;
_threadindex = 0;
}
}
/// <summary>
/// Thread state: a internal helper class containing there own
/// processing list and thread.
/// </summary>
private class ThreadState
{
#region ThreadState Private Members
/// <summary>
/// A list of to be proccessed IBattleArtificialIntelligence
/// </summary>
private List<IBattleArtificialIntelligence> processinglist;
/// <summary>
/// The thread to execute it on.
/// </summary>
private Thread ProcessingThread;
/// <summary>
/// Processes all list members
/// </summary>
private void Process()
{
while (!Environment.HasShutdownStarted)
{
try
{
//Process all mobs
for (int i = 0; i < this.processinglist.Count; i++)
{
try
{
IBattleArtificialIntelligence ai = this.processinglist[i];
ai.Process();
}
catch (ThreadAbortException ex)
{
throw ex;
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
//Sleep one sec
Thread.Sleep(1);
}
catch (ThreadAbortException)
{
break;
}
}
}
#endregion ThreadState Private Members
#region ThreadState Public Members
/// <summary>
/// Adds the requested IBattleArtificialIntelligence.
/// </summary>
/// <param name="e"></param>
public void Add(IBattleArtificialIntelligence e)
{
lock (e)
{
this.processinglist.Add(e);
}
}
/// <summary>
/// Removes the requested
/// IBattleArtificialIntelligence
/// </summary>
/// <param name="e"></param>
public void Remove(IBattleArtificialIntelligence e)
{
lock (e)
{
this.processinglist.Remove(e);
}
}
/// <summary>
/// Checks if a threadstate contains the requested
/// IBattleArtificialIntelligence
/// </summary>
/// <param name="e"></param>
public void Contains(IBattleArtificialIntelligence e)
{
this.processinglist.Contains(e);
}
/// <summary>
/// Gets the count of AI's that are subscribed
/// </summary>
public int Count
{
get
{
return this.processinglist.Count;
}
}
/// <summary>
/// Get the default capacity
/// </summary>
public int Capacity
{
get
{
return this.processinglist.Capacity;
}
}
#endregion ThreadState Public Members
#region ThreadState Contructor/Deconstructor
/// <summary>
/// Initialize a new thread state
/// </summary>
public ThreadState()
{
//Set new processing list with 20 stack
this.processinglist = new List<IBattleArtificialIntelligence>(20);
//Set the thread
this.ProcessingThread = new Thread(new ThreadStart(Process));
this.ProcessingThread.Name = "BattleThread";
this.ProcessingThread.Start();
}
~ThreadState()
{
try
{
if (this.ProcessingThread != null && this.ProcessingThread.IsAlive)
{
GC.SuppressFinalize(this.ProcessingThread);
this.ProcessingThread.Abort();
}
this.processinglist.Clear();
}
finally
{
if (this.ProcessingThread != null)
GC.ReRegisterForFinalize(this.ProcessingThread);
ProcessingThread = null;
processinglist = null;
}
}
internal void Abort()
{
try
{
if (this.ProcessingThread != null && this.ProcessingThread.IsAlive)
{
GC.SuppressFinalize(this.ProcessingThread);
this.ProcessingThread.Abort();
}
}
finally
{
if (this.ProcessingThread != null)
GC.ReRegisterForFinalize(this.ProcessingThread);
}
}
#endregion ThreadState Contructor/Deconstructor
}
#endregion BattleThread Nested Classes
#region BattleThread Constructor/Descontructor
static BattleThread()
{
//Add 4 threadstates to the procssing list
for (int i = 0; i < 4; i++)
{
AddNewThread();
}
}
#endregion BattleThread Constructor/Descontructor
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsReport
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestReportService : ServiceClient<AutoRestReportService>, IAutoRestReportService
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestReportService class.
/// </summary>
public AutoRestReportService() : base()
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestReportService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestReportService(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestReportService class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestReportService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestReportService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AutoRestReportService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("http://localhost");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
}
/// <summary>
/// Get test coverage report
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<IDictionary<string, int?>>> GetReportWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetReport", tracingParameters);
}
// Construct URL
var baseUrl = this.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "report").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<IDictionary<string, int?>>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<IDictionary<string, int?>>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass()]
public partial class AutoCompleteTextView : android.widget.EditText, android.widget.Filter.FilterListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static AutoCompleteTextView()
{
InitJNI();
}
protected AutoCompleteTextView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.AutoCompleteTextView.Validator_))]
public interface Validator : global::MonoJavaBridge.IJavaObject
{
bool isValid(java.lang.CharSequence arg0);
global::java.lang.CharSequence fixText(java.lang.CharSequence arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.AutoCompleteTextView.Validator))]
public sealed partial class Validator_ : java.lang.Object, Validator
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Validator_()
{
InitJNI();
}
internal Validator_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _isValid10940;
bool android.widget.AutoCompleteTextView.Validator.isValid(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.Validator_._isValid10940, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.Validator_.staticClass, global::android.widget.AutoCompleteTextView.Validator_._isValid10940, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _fixText10941;
global::java.lang.CharSequence android.widget.AutoCompleteTextView.Validator.fixText(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.Validator_._fixText10941, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.Validator_.staticClass, global::android.widget.AutoCompleteTextView.Validator_._fixText10941, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AutoCompleteTextView.Validator_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AutoCompleteTextView$Validator"));
global::android.widget.AutoCompleteTextView.Validator_._isValid10940 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.Validator_.staticClass, "isValid", "(Ljava/lang/CharSequence;)Z");
global::android.widget.AutoCompleteTextView.Validator_._fixText10941 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.Validator_.staticClass, "fixText", "(Ljava/lang/CharSequence;)Ljava/lang/CharSequence;");
}
}
internal static global::MonoJavaBridge.MethodId _setThreshold10942;
public virtual void setThreshold(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setThreshold10942, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setThreshold10942, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onKeyDown10943;
public override bool onKeyDown(int arg0, android.view.KeyEvent arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._onKeyDown10943, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._onKeyDown10943, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _onKeyUp10944;
public override bool onKeyUp(int arg0, android.view.KeyEvent arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._onKeyUp10944, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._onKeyUp10944, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _onWindowFocusChanged10945;
public override void onWindowFocusChanged(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._onWindowFocusChanged10945, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._onWindowFocusChanged10945, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onAttachedToWindow10946;
protected override void onAttachedToWindow()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._onAttachedToWindow10946);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._onAttachedToWindow10946);
}
internal static global::MonoJavaBridge.MethodId _onDetachedFromWindow10947;
protected override void onDetachedFromWindow()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._onDetachedFromWindow10947);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._onDetachedFromWindow10947);
}
internal static global::MonoJavaBridge.MethodId _setOnClickListener10948;
public override void setOnClickListener(android.view.View.OnClickListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setOnClickListener10948, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setOnClickListener10948, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onFocusChanged10949;
protected override void onFocusChanged(bool arg0, int arg1, android.graphics.Rect arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._onFocusChanged10949, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._onFocusChanged10949, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _onDisplayHint10950;
protected override void onDisplayHint(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._onDisplayHint10950, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._onDisplayHint10950, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onKeyPreIme10951;
public override bool onKeyPreIme(int arg0, android.view.KeyEvent arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._onKeyPreIme10951, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._onKeyPreIme10951, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getFilter10952;
protected virtual global::android.widget.Filter getFilter()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getFilter10952)) as android.widget.Filter;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getFilter10952)) as android.widget.Filter;
}
internal static global::MonoJavaBridge.MethodId _setAdapter10953;
public virtual void setAdapter(android.widget.ListAdapter arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setAdapter10953, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setAdapter10953, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setOnItemSelectedListener10954;
public virtual void setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setOnItemSelectedListener10954, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setOnItemSelectedListener10954, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setOnItemClickListener10955;
public virtual void setOnItemClickListener(android.widget.AdapterView.OnItemClickListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setOnItemClickListener10955, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setOnItemClickListener10955, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getOnItemClickListener10956;
public virtual global::android.widget.AdapterView.OnItemClickListener getOnItemClickListener()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemClickListener>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getOnItemClickListener10956)) as android.widget.AdapterView.OnItemClickListener;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemClickListener>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getOnItemClickListener10956)) as android.widget.AdapterView.OnItemClickListener;
}
internal static global::MonoJavaBridge.MethodId _getOnItemSelectedListener10957;
public virtual global::android.widget.AdapterView.OnItemSelectedListener getOnItemSelectedListener()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemSelectedListener>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getOnItemSelectedListener10957)) as android.widget.AdapterView.OnItemSelectedListener;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemSelectedListener>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getOnItemSelectedListener10957)) as android.widget.AdapterView.OnItemSelectedListener;
}
internal static global::MonoJavaBridge.MethodId _getAdapter10958;
public virtual global::android.widget.ListAdapter getAdapter()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.ListAdapter>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getAdapter10958)) as android.widget.ListAdapter;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.ListAdapter>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getAdapter10958)) as android.widget.ListAdapter;
}
internal static global::MonoJavaBridge.MethodId _setFrame10959;
protected override bool setFrame(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setFrame10959, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setFrame10959, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _onCommitCompletion10960;
public override void onCommitCompletion(android.view.inputmethod.CompletionInfo arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._onCommitCompletion10960, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._onCommitCompletion10960, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onFilterComplete10961;
public virtual void onFilterComplete(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._onFilterComplete10961, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._onFilterComplete10961, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _performFiltering10962;
protected virtual void performFiltering(java.lang.CharSequence arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._performFiltering10962, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._performFiltering10962, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _enoughToFilter10963;
public virtual bool enoughToFilter()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._enoughToFilter10963);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._enoughToFilter10963);
}
internal static global::MonoJavaBridge.MethodId _performValidation10964;
public virtual void performValidation()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._performValidation10964);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._performValidation10964);
}
internal static global::MonoJavaBridge.MethodId _replaceText10965;
protected virtual void replaceText(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._replaceText10965, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._replaceText10965, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setCompletionHint10966;
public virtual void setCompletionHint(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setCompletionHint10966, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setCompletionHint10966, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setCompletionHint(string arg0)
{
setCompletionHint((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
internal static global::MonoJavaBridge.MethodId _getDropDownWidth10967;
public virtual int getDropDownWidth()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getDropDownWidth10967);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getDropDownWidth10967);
}
internal static global::MonoJavaBridge.MethodId _setDropDownWidth10968;
public virtual void setDropDownWidth(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setDropDownWidth10968, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setDropDownWidth10968, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getDropDownHeight10969;
public virtual int getDropDownHeight()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getDropDownHeight10969);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getDropDownHeight10969);
}
internal static global::MonoJavaBridge.MethodId _setDropDownHeight10970;
public virtual void setDropDownHeight(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setDropDownHeight10970, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setDropDownHeight10970, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getDropDownAnchor10971;
public virtual int getDropDownAnchor()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getDropDownAnchor10971);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getDropDownAnchor10971);
}
internal static global::MonoJavaBridge.MethodId _setDropDownAnchor10972;
public virtual void setDropDownAnchor(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setDropDownAnchor10972, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setDropDownAnchor10972, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getDropDownBackground10973;
public virtual global::android.graphics.drawable.Drawable getDropDownBackground()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getDropDownBackground10973)) as android.graphics.drawable.Drawable;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getDropDownBackground10973)) as android.graphics.drawable.Drawable;
}
internal static global::MonoJavaBridge.MethodId _setDropDownBackgroundDrawable10974;
public virtual void setDropDownBackgroundDrawable(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setDropDownBackgroundDrawable10974, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setDropDownBackgroundDrawable10974, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setDropDownBackgroundResource10975;
public virtual void setDropDownBackgroundResource(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setDropDownBackgroundResource10975, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setDropDownBackgroundResource10975, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setDropDownVerticalOffset10976;
public virtual void setDropDownVerticalOffset(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setDropDownVerticalOffset10976, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setDropDownVerticalOffset10976, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getDropDownVerticalOffset10977;
public virtual int getDropDownVerticalOffset()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getDropDownVerticalOffset10977);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getDropDownVerticalOffset10977);
}
internal static global::MonoJavaBridge.MethodId _setDropDownHorizontalOffset10978;
public virtual void setDropDownHorizontalOffset(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setDropDownHorizontalOffset10978, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setDropDownHorizontalOffset10978, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getDropDownHorizontalOffset10979;
public virtual int getDropDownHorizontalOffset()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getDropDownHorizontalOffset10979);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getDropDownHorizontalOffset10979);
}
internal static global::MonoJavaBridge.MethodId _getThreshold10980;
public virtual int getThreshold()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getThreshold10980);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getThreshold10980);
}
internal static global::MonoJavaBridge.MethodId _getItemClickListener10981;
public virtual global::android.widget.AdapterView.OnItemClickListener getItemClickListener()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemClickListener>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getItemClickListener10981)) as android.widget.AdapterView.OnItemClickListener;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemClickListener>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getItemClickListener10981)) as android.widget.AdapterView.OnItemClickListener;
}
internal static global::MonoJavaBridge.MethodId _getItemSelectedListener10982;
public virtual global::android.widget.AdapterView.OnItemSelectedListener getItemSelectedListener()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemSelectedListener>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getItemSelectedListener10982)) as android.widget.AdapterView.OnItemSelectedListener;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AdapterView.OnItemSelectedListener>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getItemSelectedListener10982)) as android.widget.AdapterView.OnItemSelectedListener;
}
internal static global::MonoJavaBridge.MethodId _isPopupShowing10983;
public virtual bool isPopupShowing()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._isPopupShowing10983);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._isPopupShowing10983);
}
internal static global::MonoJavaBridge.MethodId _convertSelectionToString10984;
protected virtual global::java.lang.CharSequence convertSelectionToString(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._convertSelectionToString10984, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._convertSelectionToString10984, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _clearListSelection10985;
public virtual void clearListSelection()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._clearListSelection10985);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._clearListSelection10985);
}
internal static global::MonoJavaBridge.MethodId _setListSelection10986;
public virtual void setListSelection(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setListSelection10986, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setListSelection10986, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getListSelection10987;
public virtual int getListSelection()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getListSelection10987);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getListSelection10987);
}
internal static global::MonoJavaBridge.MethodId _performCompletion10988;
public virtual void performCompletion()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._performCompletion10988);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._performCompletion10988);
}
internal static global::MonoJavaBridge.MethodId _isPerformingCompletion10989;
public virtual bool isPerformingCompletion()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._isPerformingCompletion10989);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._isPerformingCompletion10989);
}
internal static global::MonoJavaBridge.MethodId _dismissDropDown10990;
public virtual void dismissDropDown()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._dismissDropDown10990);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._dismissDropDown10990);
}
internal static global::MonoJavaBridge.MethodId _showDropDown10991;
public virtual void showDropDown()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._showDropDown10991);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._showDropDown10991);
}
internal static global::MonoJavaBridge.MethodId _setValidator10992;
public virtual void setValidator(android.widget.AutoCompleteTextView.Validator arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._setValidator10992, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._setValidator10992, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getValidator10993;
public virtual global::android.widget.AutoCompleteTextView.Validator getValidator()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AutoCompleteTextView.Validator>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView._getValidator10993)) as android.widget.AutoCompleteTextView.Validator;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.AutoCompleteTextView.Validator>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._getValidator10993)) as android.widget.AutoCompleteTextView.Validator;
}
internal static global::MonoJavaBridge.MethodId _AutoCompleteTextView10994;
public AutoCompleteTextView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._AutoCompleteTextView10994, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _AutoCompleteTextView10995;
public AutoCompleteTextView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._AutoCompleteTextView10995, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _AutoCompleteTextView10996;
public AutoCompleteTextView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AutoCompleteTextView.staticClass, global::android.widget.AutoCompleteTextView._AutoCompleteTextView10996, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AutoCompleteTextView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AutoCompleteTextView"));
global::android.widget.AutoCompleteTextView._setThreshold10942 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setThreshold", "(I)V");
global::android.widget.AutoCompleteTextView._onKeyDown10943 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "onKeyDown", "(ILandroid/view/KeyEvent;)Z");
global::android.widget.AutoCompleteTextView._onKeyUp10944 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "onKeyUp", "(ILandroid/view/KeyEvent;)Z");
global::android.widget.AutoCompleteTextView._onWindowFocusChanged10945 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "onWindowFocusChanged", "(Z)V");
global::android.widget.AutoCompleteTextView._onAttachedToWindow10946 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "onAttachedToWindow", "()V");
global::android.widget.AutoCompleteTextView._onDetachedFromWindow10947 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "onDetachedFromWindow", "()V");
global::android.widget.AutoCompleteTextView._setOnClickListener10948 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setOnClickListener", "(Landroid/view/View$OnClickListener;)V");
global::android.widget.AutoCompleteTextView._onFocusChanged10949 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "onFocusChanged", "(ZILandroid/graphics/Rect;)V");
global::android.widget.AutoCompleteTextView._onDisplayHint10950 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "onDisplayHint", "(I)V");
global::android.widget.AutoCompleteTextView._onKeyPreIme10951 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "onKeyPreIme", "(ILandroid/view/KeyEvent;)Z");
global::android.widget.AutoCompleteTextView._getFilter10952 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getFilter", "()Landroid/widget/Filter;");
global::android.widget.AutoCompleteTextView._setAdapter10953 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setAdapter", "(Landroid/widget/ListAdapter;)V");
global::android.widget.AutoCompleteTextView._setOnItemSelectedListener10954 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setOnItemSelectedListener", "(Landroid/widget/AdapterView$OnItemSelectedListener;)V");
global::android.widget.AutoCompleteTextView._setOnItemClickListener10955 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setOnItemClickListener", "(Landroid/widget/AdapterView$OnItemClickListener;)V");
global::android.widget.AutoCompleteTextView._getOnItemClickListener10956 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getOnItemClickListener", "()Landroid/widget/AdapterView$OnItemClickListener;");
global::android.widget.AutoCompleteTextView._getOnItemSelectedListener10957 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getOnItemSelectedListener", "()Landroid/widget/AdapterView$OnItemSelectedListener;");
global::android.widget.AutoCompleteTextView._getAdapter10958 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getAdapter", "()Landroid/widget/ListAdapter;");
global::android.widget.AutoCompleteTextView._setFrame10959 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setFrame", "(IIII)Z");
global::android.widget.AutoCompleteTextView._onCommitCompletion10960 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "onCommitCompletion", "(Landroid/view/inputmethod/CompletionInfo;)V");
global::android.widget.AutoCompleteTextView._onFilterComplete10961 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "onFilterComplete", "(I)V");
global::android.widget.AutoCompleteTextView._performFiltering10962 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "performFiltering", "(Ljava/lang/CharSequence;I)V");
global::android.widget.AutoCompleteTextView._enoughToFilter10963 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "enoughToFilter", "()Z");
global::android.widget.AutoCompleteTextView._performValidation10964 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "performValidation", "()V");
global::android.widget.AutoCompleteTextView._replaceText10965 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "replaceText", "(Ljava/lang/CharSequence;)V");
global::android.widget.AutoCompleteTextView._setCompletionHint10966 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setCompletionHint", "(Ljava/lang/CharSequence;)V");
global::android.widget.AutoCompleteTextView._getDropDownWidth10967 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getDropDownWidth", "()I");
global::android.widget.AutoCompleteTextView._setDropDownWidth10968 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setDropDownWidth", "(I)V");
global::android.widget.AutoCompleteTextView._getDropDownHeight10969 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getDropDownHeight", "()I");
global::android.widget.AutoCompleteTextView._setDropDownHeight10970 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setDropDownHeight", "(I)V");
global::android.widget.AutoCompleteTextView._getDropDownAnchor10971 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getDropDownAnchor", "()I");
global::android.widget.AutoCompleteTextView._setDropDownAnchor10972 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setDropDownAnchor", "(I)V");
global::android.widget.AutoCompleteTextView._getDropDownBackground10973 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getDropDownBackground", "()Landroid/graphics/drawable/Drawable;");
global::android.widget.AutoCompleteTextView._setDropDownBackgroundDrawable10974 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setDropDownBackgroundDrawable", "(Landroid/graphics/drawable/Drawable;)V");
global::android.widget.AutoCompleteTextView._setDropDownBackgroundResource10975 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setDropDownBackgroundResource", "(I)V");
global::android.widget.AutoCompleteTextView._setDropDownVerticalOffset10976 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setDropDownVerticalOffset", "(I)V");
global::android.widget.AutoCompleteTextView._getDropDownVerticalOffset10977 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getDropDownVerticalOffset", "()I");
global::android.widget.AutoCompleteTextView._setDropDownHorizontalOffset10978 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setDropDownHorizontalOffset", "(I)V");
global::android.widget.AutoCompleteTextView._getDropDownHorizontalOffset10979 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getDropDownHorizontalOffset", "()I");
global::android.widget.AutoCompleteTextView._getThreshold10980 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getThreshold", "()I");
global::android.widget.AutoCompleteTextView._getItemClickListener10981 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getItemClickListener", "()Landroid/widget/AdapterView$OnItemClickListener;");
global::android.widget.AutoCompleteTextView._getItemSelectedListener10982 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getItemSelectedListener", "()Landroid/widget/AdapterView$OnItemSelectedListener;");
global::android.widget.AutoCompleteTextView._isPopupShowing10983 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "isPopupShowing", "()Z");
global::android.widget.AutoCompleteTextView._convertSelectionToString10984 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "convertSelectionToString", "(Ljava/lang/Object;)Ljava/lang/CharSequence;");
global::android.widget.AutoCompleteTextView._clearListSelection10985 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "clearListSelection", "()V");
global::android.widget.AutoCompleteTextView._setListSelection10986 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setListSelection", "(I)V");
global::android.widget.AutoCompleteTextView._getListSelection10987 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getListSelection", "()I");
global::android.widget.AutoCompleteTextView._performCompletion10988 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "performCompletion", "()V");
global::android.widget.AutoCompleteTextView._isPerformingCompletion10989 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "isPerformingCompletion", "()Z");
global::android.widget.AutoCompleteTextView._dismissDropDown10990 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "dismissDropDown", "()V");
global::android.widget.AutoCompleteTextView._showDropDown10991 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "showDropDown", "()V");
global::android.widget.AutoCompleteTextView._setValidator10992 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "setValidator", "(Landroid/widget/AutoCompleteTextView$Validator;)V");
global::android.widget.AutoCompleteTextView._getValidator10993 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "getValidator", "()Landroid/widget/AutoCompleteTextView$Validator;");
global::android.widget.AutoCompleteTextView._AutoCompleteTextView10994 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::android.widget.AutoCompleteTextView._AutoCompleteTextView10995 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V");
global::android.widget.AutoCompleteTextView._AutoCompleteTextView10996 = @__env.GetMethodIDNoThrow(global::android.widget.AutoCompleteTextView.staticClass, "<init>", "(Landroid/content/Context;)V");
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// 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: ErrorMailHtmlFormatter.cs 640 2009-06-01 17:22:02Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using TextWriter = System.IO.TextWriter;
using HttpUtility = System.Web.HttpUtility;
using NameValueCollection = System.Collections.Specialized.NameValueCollection;
using HtmlTextWriter = System.Web.UI.HtmlTextWriter;
using Html32TextWriter = System.Web.UI.Html32TextWriter;
using HtmlTextWriterTag = System.Web.UI.HtmlTextWriterTag;
using HtmlTextWriterAttribute = System.Web.UI.HtmlTextWriterAttribute;
#endregion
/// <summary>
/// Formats the HTML to display the details of a given error that is
/// suitable for sending as the body of an e-mail message.
/// </summary>
public class ErrorMailHtmlFormatter : ErrorTextFormatter
{
private HtmlTextWriter _writer;
private Error _error;
/// <summary>
/// Returns the text/html MIME type that is the format provided
/// by this <see cref="ErrorTextFormatter"/> implementation.
/// </summary>
public override string MimeType
{
get { return "text/html"; }
}
/// <summary>
/// Formats a complete HTML document describing the given
/// <see cref="Error"/> instance.
/// </summary>
public override void Format(TextWriter writer, Error error)
{
if (writer == null)
throw new ArgumentNullException("writer");
if (error == null)
throw new ArgumentNullException("error");
//
// Create a HTML writer on top of the given writer and
// write out the document. Note that the incoming
// writer and error parameters are promoted to members
// during formatting in order to avoid passing them
// as context to each downstream method responsible
// for rendering a part of the document. The important
// assumption here is that Format will never be called
// from more than one thread at the same time.
//
Html32TextWriter htmlWriter = new Html32TextWriter(writer);
htmlWriter.RenderBeginTag(HtmlTextWriterTag.Html);
_writer = htmlWriter;
_error = error;
try
{
RenderHead();
RenderBody();
}
finally
{
_writer = null;
_error = null;
}
htmlWriter.RenderEndTag(); // </html>
htmlWriter.WriteLine();
}
/// <summary>
/// Gets the <see cref="HtmlTextWriter"/> used for HTML formatting.
/// </summary>
/// <remarks>
/// This property is only available to downstream methods in the
/// context of the <see cref="Format"/> method call.
/// </remarks>
protected HtmlTextWriter Writer
{
get { return _writer; }
}
/// <summary>
/// Gets the <see cref="Error"/> object for which a HTML document
/// is being formatted.
/// </summary>
/// <remarks>
/// This property is only available to downstream methods in the
/// context of the <see cref="Format"/> method call.
/// </remarks>
protected Error Error
{
get { return _error; }
}
/// <summary>
/// Renders the <head> section of the HTML document.
/// </summary>
protected virtual void RenderHead()
{
HtmlTextWriter writer = this.Writer;
writer.RenderBeginTag(HtmlTextWriterTag.Head);
//
// Write the document title and style.
//
writer.RenderBeginTag(HtmlTextWriterTag.Title);
writer.Write("Error: ");
HttpUtility.HtmlEncode(this.Error.Message, writer);
writer.RenderEndTag(); // </title>
writer.WriteLine();
RenderStyle();
writer.RenderEndTag(); // </head>
writer.WriteLine();
}
/// <summary>
/// Renders the <body> section of the HTML document.
/// </summary>
protected virtual void RenderBody()
{
HtmlTextWriter writer = this.Writer;
writer.RenderBeginTag(HtmlTextWriterTag.Body);
RenderSummary();
if (this.Error.Detail.Length != 0)
{
RenderDetail();
}
RenderCollections();
RenderFooter();
writer.RenderEndTag(); // </body>
writer.WriteLine();
}
/// <summary>
/// Renders the footer content that appears at the end of the
/// HTML document body.
/// </summary>
protected virtual void RenderFooter()
{
HtmlTextWriter writer = this.Writer;
writer.RenderBeginTag(HtmlTextWriterTag.P);
PoweredBy poweredBy = new PoweredBy();
poweredBy.RenderControl(writer);
writer.RenderEndTag();
}
/// <summary>
/// Renders the <style> element along with in-line styles
/// used to format the body of the HTML document.
/// </summary>
protected virtual void RenderStyle()
{
HtmlTextWriter writer = this.Writer;
writer.RenderBeginTag(HtmlTextWriterTag.Style);
writer.WriteLine(@"
body { font-family: verdana, arial, helvetic; font-size: x-small; }
td, th, pre { font-size: x-small; }
#errorDetail { padding: 1em; background-color: #FFFFCC; }
#errorMessage { font-size: medium; font-style: italic; color: maroon; }
h1 { font-size: small; }");
writer.RenderEndTag(); // </style>
writer.WriteLine();
}
/// <summary>
/// Renders the details about the <see cref="Error" /> object in
/// body of the HTML document.
/// </summary>
protected virtual void RenderDetail()
{
HtmlTextWriter writer = this.Writer;
//
// Write the full text of the error.
//
writer.AddAttribute(HtmlTextWriterAttribute.Id, "errorDetail");
writer.RenderBeginTag(HtmlTextWriterTag.Pre);
writer.InnerWriter.Flush();
HttpUtility.HtmlEncode(this.Error.Detail, writer.InnerWriter);
writer.RenderEndTag(); // </pre>
writer.WriteLine();
}
/// <summary>
/// Renders a summary about the <see cref="Error"/> object in
/// body of the HTML document.
/// </summary>
protected virtual void RenderSummary()
{
HtmlTextWriter writer = this.Writer;
Error error = this.Error;
//
// Write the error type and message.
//
writer.AddAttribute(HtmlTextWriterAttribute.Id, "errorMessage");
writer.RenderBeginTag(HtmlTextWriterTag.P);
HttpUtility.HtmlEncode(error.Type, writer);
writer.Write(": ");
HttpUtility.HtmlEncode(error.Message, writer);
writer.RenderEndTag(); // </p>
writer.WriteLine();
//
// Write out the time, in UTC, at which the error was generated.
//
if (error.Time != DateTime.MinValue)
{
writer.RenderBeginTag(HtmlTextWriterTag.P);
writer.Write("Generated: ");
HttpUtility.HtmlEncode(error.Time.ToUniversalTime().ToString("r"), writer);
writer.RenderEndTag(); // </p>
writer.WriteLine();
}
}
/// <summary>
/// Renders the diagnostic collections of the <see cref="Error" /> object in
/// body of the HTML document.
/// </summary>
protected virtual void RenderCollections()
{
RenderCollection(this.Error.ServerVariables, "Server Variables");
}
/// <summary>
/// Renders a collection as a table in HTML document body.
/// </summary>
/// <remarks>
/// This method is called by <see cref="RenderCollections"/> to
/// format a diagnostic collection from <see cref="Error"/> object.
/// </remarks>
protected virtual void RenderCollection(NameValueCollection collection, string caption)
{
if (collection == null || collection.Count == 0)
{
return;
}
HtmlTextWriter writer = this.Writer;
writer.RenderBeginTag(HtmlTextWriterTag.H1);
HttpUtility.HtmlEncode(caption, writer);
writer.RenderEndTag(); // </h1>
writer.WriteLine();
//
// Write a table with each key in the left column
// and its value in the right column.
//
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "5");
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
writer.AddAttribute(HtmlTextWriterAttribute.Border, "1");
writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
writer.RenderBeginTag(HtmlTextWriterTag.Table);
//
// Write the column headings.
//
writer.AddAttribute(HtmlTextWriterAttribute.Valign, "top");
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.AddAttribute(HtmlTextWriterAttribute.Align, "left");
writer.RenderBeginTag(HtmlTextWriterTag.Th);
writer.Write("Name");
writer.RenderEndTag(); // </th>
writer.AddAttribute(HtmlTextWriterAttribute.Align, "left");
writer.RenderBeginTag(HtmlTextWriterTag.Th);
writer.Write("Value");
writer.RenderEndTag(); // </th>
writer.RenderEndTag(); // </tr>
//
// Write the main body of the table containing keys
// and values in a two-column layout.
//
foreach (string key in collection.Keys)
{
writer.AddAttribute(HtmlTextWriterAttribute.Valign, "top");
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.RenderBeginTag(HtmlTextWriterTag.Td);
HttpUtility.HtmlEncode(key, writer);
writer.RenderEndTag(); // </td>
writer.RenderBeginTag(HtmlTextWriterTag.Td);
string value = collection[key] ?? string.Empty;
if (value.Length != 0)
{
HttpUtility.HtmlEncode(value, writer);
}
else
{
writer.Write(" ");
}
writer.RenderEndTag(); // </td>
writer.RenderEndTag(); // </tr>
}
writer.RenderEndTag(); // </table>
writer.WriteLine();
}
}
}
| |
#if UNITY_EDITOR || !(UNITY_WEBPLAYER || UNITY_WEBGL)
#region License
/*
* HttpListenerResponse.cs
*
* This code is derived from HttpListenerResponse.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2015 sta.blockhead
*
* 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
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Nicholas Devenish
*/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides the access to a response to a request received by the <see cref="HttpListener"/>.
/// </summary>
/// <remarks>
/// The HttpListenerResponse class cannot be inherited.
/// </remarks>
public sealed class HttpListenerResponse : IDisposable
{
#region Private Fields
private bool _closeConnection;
private Encoding _contentEncoding;
private long _contentLength;
private string _contentType;
private HttpListenerContext _context;
private CookieCollection _cookies;
private bool _disposed;
private WebHeaderCollection _headers;
private bool _headersSent;
private bool _keepAlive;
private string _location;
private ResponseStream _outputStream;
private bool _sendChunked;
private int _statusCode;
private string _statusDescription;
private Version _version;
#endregion
#region Internal Constructors
internal HttpListenerResponse (HttpListenerContext context)
{
_context = context;
_keepAlive = true;
_statusCode = 200;
_statusDescription = "OK";
_version = HttpVersion.Version11;
}
#endregion
#region Internal Properties
internal bool CloseConnection {
get {
return _closeConnection;
}
set {
_closeConnection = value;
}
}
internal bool HeadersSent {
get {
return _headersSent;
}
set {
_headersSent = value;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the encoding for the entity body data included in the response.
/// </summary>
/// <value>
/// A <see cref="Encoding"/> that represents the encoding for the entity body data,
/// or <see langword="null"/> if no encoding is specified.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public Encoding ContentEncoding {
get {
return _contentEncoding;
}
set {
checkDisposed ();
_contentEncoding = value;
}
}
/// <summary>
/// Gets or sets the number of bytes in the entity body data included in the response.
/// </summary>
/// <value>
/// A <see cref="long"/> that represents the value of the Content-Length entity-header.
/// </value>
/// <exception cref="ArgumentOutOfRangeException">
/// The value specified for a set operation is less than zero.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public long ContentLength64 {
get {
return _contentLength;
}
set {
checkDisposedOrHeadersSent ();
if (value < 0)
throw new ArgumentOutOfRangeException ("Less than zero.", "value");
_contentLength = value;
}
}
/// <summary>
/// Gets or sets the media type of the entity body included in the response.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the media type of the entity body,
/// or <see langword="null"/> if no media type is specified. This value is
/// used for the value of the Content-Type entity-header.
/// </value>
/// <exception cref="ArgumentException">
/// The value specified for a set operation is empty.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public string ContentType {
get {
return _contentType;
}
set {
checkDisposed ();
if (value != null && value.Length == 0)
throw new ArgumentException ("An empty string.", "value");
_contentType = value;
}
}
/// <summary>
/// Gets or sets the cookies sent with the response.
/// </summary>
/// <value>
/// A <see cref="CookieCollection"/> that contains the cookies sent with the response.
/// </value>
public CookieCollection Cookies {
get {
return _cookies ?? (_cookies = new CookieCollection ());
}
set {
_cookies = value;
}
}
/// <summary>
/// Gets or sets the HTTP headers sent to the client.
/// </summary>
/// <value>
/// A <see cref="WebHeaderCollection"/> that contains the headers sent to the client.
/// </value>
/// <exception cref="InvalidOperationException">
/// The value specified for a set operation isn't valid for a response.
/// </exception>
public WebHeaderCollection Headers {
get {
return _headers ?? (_headers = new WebHeaderCollection (HttpHeaderType.Response, false));
}
set {
if (value != null && value.State != HttpHeaderType.Response)
throw new InvalidOperationException (
"The specified headers aren't valid for a response.");
_headers = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server requests a persistent connection.
/// </summary>
/// <value>
/// <c>true</c> if the server requests a persistent connection; otherwise, <c>false</c>.
/// The default value is <c>true</c>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public bool KeepAlive {
get {
return _keepAlive;
}
set {
checkDisposedOrHeadersSent ();
_keepAlive = value;
}
}
/// <summary>
/// Gets a <see cref="Stream"/> to use to write the entity body data.
/// </summary>
/// <value>
/// A <see cref="Stream"/> to use to write the entity body data.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public Stream OutputStream {
get {
checkDisposed ();
return _outputStream ?? (_outputStream = _context.Connection.GetResponseStream ());
}
}
/// <summary>
/// Gets or sets the HTTP version used in the response.
/// </summary>
/// <value>
/// A <see cref="Version"/> that represents the version used in the response.
/// </value>
/// <exception cref="ArgumentNullException">
/// The value specified for a set operation is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// The value specified for a set operation doesn't have its <c>Major</c> property set to 1 or
/// doesn't have its <c>Minor</c> property set to either 0 or 1.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public Version ProtocolVersion {
get {
return _version;
}
set {
checkDisposedOrHeadersSent ();
if (value == null)
throw new ArgumentNullException ("value");
if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
throw new ArgumentException ("Not 1.0 or 1.1.", "value");
_version = value;
}
}
/// <summary>
/// Gets or sets the URL to which the client is redirected to locate a requested resource.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the Location response-header,
/// or <see langword="null"/> if no redirect location is specified.
/// </value>
/// <exception cref="ArgumentException">
/// The value specified for a set operation isn't an absolute URL.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public string RedirectLocation {
get {
return _location;
}
set {
checkDisposed ();
if (value == null) {
_location = null;
return;
}
Uri uri = null;
if (!value.MaybeUri () || !Uri.TryCreate (value, UriKind.Absolute, out uri))
throw new ArgumentException ("Not an absolute URL.", "value");
_location = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the response uses the chunked transfer encoding.
/// </summary>
/// <value>
/// <c>true</c> if the response uses the chunked transfer encoding;
/// otherwise, <c>false</c>. The default value is <c>false</c>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public bool SendChunked {
get {
return _sendChunked;
}
set {
checkDisposedOrHeadersSent ();
_sendChunked = value;
}
}
/// <summary>
/// Gets or sets the HTTP status code returned to the client.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the status code for the response to
/// the request. The default value is same as <see cref="HttpStatusCode.OK"/>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
/// <exception cref="System.Net.ProtocolViolationException">
/// The value specified for a set operation is invalid. Valid values are
/// between 100 and 999 inclusive.
/// </exception>
public int StatusCode {
get {
return _statusCode;
}
set {
checkDisposedOrHeadersSent ();
if (value < 100 || value > 999)
throw new System.Net.ProtocolViolationException (
"A value isn't between 100 and 999 inclusive.");
_statusCode = value;
_statusDescription = value.GetStatusDescription ();
}
}
/// <summary>
/// Gets or sets the description of the HTTP status code returned to the client.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the description of the status code. The default
/// value is the <see href="http://tools.ietf.org/html/rfc2616#section-10">RFC 2616</see>
/// description for the <see cref="HttpListenerResponse.StatusCode"/> property value,
/// or <see cref="String.Empty"/> if an RFC 2616 description doesn't exist.
/// </value>
/// <exception cref="ArgumentException">
/// The value specified for a set operation contains invalid characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public string StatusDescription {
get {
return _statusDescription;
}
set {
checkDisposedOrHeadersSent ();
if (value == null || value.Length == 0) {
_statusDescription = _statusCode.GetStatusDescription ();
return;
}
if (!value.IsText () || value.IndexOfAny (new[] { '\r', '\n' }) > -1)
throw new ArgumentException ("Contains invalid characters.", "value");
_statusDescription = value;
}
}
#endregion
#region Private Methods
private bool canAddOrUpdate (Cookie cookie)
{
if (_cookies == null || _cookies.Count == 0)
return true;
var found = findCookie (cookie).ToList ();
if (found.Count == 0)
return true;
var ver = cookie.Version;
foreach (var c in found)
if (c.Version == ver)
return true;
return false;
}
private void checkDisposed ()
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
}
private void checkDisposedOrHeadersSent ()
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (_headersSent)
throw new InvalidOperationException ("Cannot be changed after the headers are sent.");
}
private void close (bool force)
{
_disposed = true;
_context.Connection.Close (force);
}
private IEnumerable<Cookie> findCookie (Cookie cookie)
{
var name = cookie.Name;
var domain = cookie.Domain;
var path = cookie.Path;
if (_cookies != null)
foreach (Cookie c in _cookies)
if (c.Name.Equals (name, StringComparison.OrdinalIgnoreCase) &&
c.Domain.Equals (domain, StringComparison.OrdinalIgnoreCase) &&
c.Path.Equals (path, StringComparison.Ordinal))
yield return c;
}
#endregion
#region Internal Methods
internal WebHeaderCollection WriteHeadersTo (MemoryStream destination)
{
var headers = new WebHeaderCollection (HttpHeaderType.Response, true);
if (_headers != null)
headers.Add (_headers);
if (_contentType != null) {
var type = _contentType.IndexOf ("charset=", StringComparison.Ordinal) == -1 &&
_contentEncoding != null
? String.Format ("{0}; charset={1}", _contentType, _contentEncoding.WebName)
: _contentType;
headers.InternalSet ("Content-Type", type, true);
}
if (headers["Server"] == null)
headers.InternalSet ("Server", "websocket-sharp/1.0", true);
var prov = CultureInfo.InvariantCulture;
if (headers["Date"] == null)
headers.InternalSet ("Date", DateTime.UtcNow.ToString ("r", prov), true);
if (!_sendChunked)
headers.InternalSet ("Content-Length", _contentLength.ToString (prov), true);
else
headers.InternalSet ("Transfer-Encoding", "chunked", true);
/*
* Apache forces closing the connection for these status codes:
* - 400 Bad Request
* - 408 Request Timeout
* - 411 Length Required
* - 413 Request Entity Too Large
* - 414 Request-Uri Too Long
* - 500 Internal Server Error
* - 503 Service Unavailable
*/
var closeConn = !_context.Request.KeepAlive ||
!_keepAlive ||
_statusCode == 400 ||
_statusCode == 408 ||
_statusCode == 411 ||
_statusCode == 413 ||
_statusCode == 414 ||
_statusCode == 500 ||
_statusCode == 503;
var reuses = _context.Connection.Reuses;
if (closeConn || reuses >= 100) {
headers.InternalSet ("Connection", "close", true);
}
else {
headers.InternalSet (
"Keep-Alive", String.Format ("timeout=15,max={0}", 100 - reuses), true);
if (_context.Request.ProtocolVersion < HttpVersion.Version11)
headers.InternalSet ("Connection", "keep-alive", true);
}
if (_location != null)
headers.InternalSet ("Location", _location, true);
if (_cookies != null)
foreach (Cookie cookie in _cookies)
headers.InternalSet ("Set-Cookie", cookie.ToResponseString (), true);
var enc = _contentEncoding ?? Encoding.Default;
var writer = new StreamWriter (destination, enc, 256);
writer.Write ("HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription);
writer.Write (headers.ToStringMultiValue (true));
writer.Flush ();
// Assumes that the destination was at position 0.
destination.Position = enc.GetPreamble ().Length;
return headers;
}
#endregion
#region Public Methods
/// <summary>
/// Closes the connection to the client without returning a response.
/// </summary>
public void Abort ()
{
if (_disposed)
return;
close (true);
}
/// <summary>
/// Adds an HTTP header with the specified <paramref name="name"/> and
/// <paramref name="value"/> to the headers for the response.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The header cannot be allowed to add to the current headers.
/// </exception>
public void AddHeader (string name, string value)
{
Headers.Set (name, value);
}
/// <summary>
/// Appends the specified <paramref name="cookie"/> to the cookies sent with the response.
/// </summary>
/// <param name="cookie">
/// A <see cref="Cookie"/> to append.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookie"/> is <see langword="null"/>.
/// </exception>
public void AppendCookie (Cookie cookie)
{
Cookies.Add (cookie);
}
/// <summary>
/// Appends a <paramref name="value"/> to the specified HTTP header sent with the response.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to append
/// <paramref name="value"/> to.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value to append to the header.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current headers cannot allow the header to append a value.
/// </exception>
public void AppendHeader (string name, string value)
{
Headers.Add (name, value);
}
/// <summary>
/// Returns the response to the client and releases the resources used by
/// this <see cref="HttpListenerResponse"/> instance.
/// </summary>
public void Close ()
{
if (_disposed)
return;
close (false);
}
/// <summary>
/// Returns the response with the specified array of <see cref="byte"/> to the client and
/// releases the resources used by this <see cref="HttpListenerResponse"/> instance.
/// </summary>
/// <param name="responseEntity">
/// An array of <see cref="byte"/> that contains the response entity body data.
/// </param>
/// <param name="willBlock">
/// <c>true</c> if this method blocks execution while flushing the stream to the client;
/// otherwise, <c>false</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="responseEntity"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public void Close (byte[] responseEntity, bool willBlock)
{
checkDisposed ();
if (responseEntity == null)
throw new ArgumentNullException ("responseEntity");
var len = responseEntity.Length;
var output = OutputStream;
if (willBlock) {
output.Write (responseEntity, 0, len);
close (false);
return;
}
output.BeginWrite (
responseEntity,
0,
len,
ar => {
output.EndWrite (ar);
close (false);
},
null);
}
/// <summary>
/// Copies some properties from the specified <see cref="HttpListenerResponse"/> to
/// this response.
/// </summary>
/// <param name="templateResponse">
/// A <see cref="HttpListenerResponse"/> to copy.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="templateResponse"/> is <see langword="null"/>.
/// </exception>
public void CopyFrom (HttpListenerResponse templateResponse)
{
if (templateResponse == null)
throw new ArgumentNullException ("templateResponse");
if (templateResponse._headers != null) {
if (_headers != null)
_headers.Clear ();
Headers.Add (templateResponse._headers);
}
else if (_headers != null) {
_headers = null;
}
_contentLength = templateResponse._contentLength;
_statusCode = templateResponse._statusCode;
_statusDescription = templateResponse._statusDescription;
_keepAlive = templateResponse._keepAlive;
_version = templateResponse._version;
}
/// <summary>
/// Configures the response to redirect the client's request to
/// the specified <paramref name="url"/>.
/// </summary>
/// <remarks>
/// This method sets the <see cref="HttpListenerResponse.RedirectLocation"/> property to
/// <paramref name="url"/>, the <see cref="HttpListenerResponse.StatusCode"/> property to
/// <c>302</c>, and the <see cref="HttpListenerResponse.StatusDescription"/> property to
/// <c>"Found"</c>.
/// </remarks>
/// <param name="url">
/// A <see cref="string"/> that represents the URL to redirect the client's request to.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="url"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="url"/> isn't an absolute URL.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has already been sent.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public void Redirect (string url)
{
checkDisposedOrHeadersSent ();
if (url == null)
throw new ArgumentNullException ("url");
Uri uri = null;
if (!url.MaybeUri () || !Uri.TryCreate (url, UriKind.Absolute, out uri))
throw new ArgumentException ("Not an absolute URL.", "url");
_location = url;
_statusCode = 302;
_statusDescription = "Found";
}
/// <summary>
/// Adds or updates a <paramref name="cookie"/> in the cookies sent with the response.
/// </summary>
/// <param name="cookie">
/// A <see cref="Cookie"/> to set.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookie"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="cookie"/> already exists in the cookies and couldn't be replaced.
/// </exception>
public void SetCookie (Cookie cookie)
{
if (cookie == null)
throw new ArgumentNullException ("cookie");
if (!canAddOrUpdate (cookie))
throw new ArgumentException ("Cannot be replaced.", "cookie");
Cookies.Add (cookie);
}
#endregion
#region Explicit Interface Implementations
/// <summary>
/// Releases all resources used by the <see cref="HttpListenerResponse"/>.
/// </summary>
void IDisposable.Dispose ()
{
if (_disposed)
return;
close (true); // Same as the Abort method.
}
#endregion
}
}
#endif
| |
using UnityEngine;
using System.Collections;
[ExecuteInEditMode] // Make water live-update even when not in play mode
public class SeaShader : MonoBehaviour
{
//private WhirldObject whirldObject;
public enum WaterMode {
Simple = 0,
Reflective = 1,
Refractive = 2,
};
public WaterMode m_WaterMode = WaterMode.Reflective;
public bool m_DisablePixelLights = true;
public int m_TextureSize = 256;
public float m_ClipPlaneOffset = 0.07f;
public LayerMask cullingMask;
public Transform WaterTransform;
public LayerMask m_ReflectLayers = -1;
public LayerMask m_RefractLayers = -1;
public Shader m_ShaderFull;
public Shader m_ShaderSimple;
public bool isSurface = true;
private Hashtable m_ReflectionCameras = new Hashtable(); // Camera -> Camera table
private Hashtable m_RefractionCameras = new Hashtable(); // Camera -> Camera table
private RenderTexture m_ReflectionTexture = null;
private RenderTexture m_RefractionTexture = null;
private WaterMode m_HardwareWaterSupport = WaterMode.Reflective;
private int m_OldReflectionTextureSize = 0;
private int m_OldRefractionTextureSize = 0;
//private double tickTime = 0.0f;
private Terrain m_Terrain;
private static bool s_InsideWater = false;
// This is called when it's known that the object will be rendered by some
// camera. We render reflections / refractions and do other updates here.
// Because the script executes in edit mode, reflections for the scene view
// camera will just work!
/*void Start() {
whirldObject = transform.parent.gameObject.GetComponent(WhirldObject);
if(whirldObject == null || whirldObject.params == null) {
return;
}
if(whirldObject.params["Mode"]) {
m_SeaMode = Enum.Parse(typeof(SeaMode), whirldObject.params["Mode"], true);
}
}*/
/*public void SetSeaMode(string mode)
{
m_SeaMode = (SeaMode) System.Enum.Parse(typeof(SeaMode), mode, true);
}*/
public void OnWillRenderObject()
{
if( !enabled || !renderer || !renderer.sharedMaterial || !renderer.enabled ) // || Time.time < tickTime)
return;
//tickTime = Time.time + .05;
if( !m_Terrain ) {
m_Terrain = Terrain.activeTerrain;
/*GameObject go = GameObject.Find("Terrain");
if( !go )
return;
m_Terrain = go.GetComponent(typeof(Terrain)) as Terrain;
if( !m_Terrain )
return;*/
}
Camera cam = Camera.current;
if( !cam )
return;
// Safeguard from recursive water reflections.
if( s_InsideWater )
return;
s_InsideWater = true;
// Actual water rendering mode depends on both the current setting AND
// the hardware support. There's no point in rendering refraction textures
// if they won't be visible in the end.
m_HardwareWaterSupport = FindHardwareWaterSupport();
WaterMode mode = GetWaterMode();
Shader newShader = ( mode == WaterMode.Refractive ) ? m_ShaderFull : m_ShaderSimple;
if( renderer.sharedMaterial.shader != newShader )
renderer.sharedMaterial.shader = newShader;
Camera reflectionCamera, refractionCamera;
CreateWaterObjects( cam, out reflectionCamera, out refractionCamera );
//Apply SeaMode
//renderer.sharedMaterial.SetColor( "_RefrColor", SeaModeColors[ (int)m_SeaMode ] );
// find out the reflection plane: position and normal in world space
Vector3 pos = transform.position;
Vector3 normal = transform.up;
// Optionally disable pixel lights for reflection/refraction
int oldPixelLightCount = QualitySettings.pixelLightCount;
if( m_DisablePixelLights )
QualitySettings.pixelLightCount = 0;
UpdateCameraModes( cam, reflectionCamera );
UpdateCameraModes( cam, refractionCamera );
bool oldSoftVegetation = QualitySettings.softVegetation;
QualitySettings.softVegetation = false;
// Render reflection if needed
if( mode >= WaterMode.Reflective/* && isSurface*/)
{
// Reflect camera around reflection plane
float d = -Vector3.Dot (normal, pos) - m_ClipPlaneOffset;
Vector4 reflectionPlane = new Vector4 (normal.x, normal.y, normal.z, d);
Matrix4x4 reflection = Matrix4x4.zero;
CalculateReflectionMatrix (ref reflection, reflectionPlane);
Vector3 oldpos = cam.transform.position;
Vector3 newpos = reflection.MultiplyPoint( oldpos );
reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
// Setup oblique projection matrix so that near plane is our reflection
// plane. This way we clip everything below/above it for free.
Vector4 clipPlane = CameraSpacePlane( reflectionCamera, pos, normal, 1.0f );
Matrix4x4 projection = cam.projectionMatrix;
CalculateObliqueMatrix (ref projection, clipPlane);
reflectionCamera.projectionMatrix = projection;
reflectionCamera.cullingMask = cullingMask & m_ReflectLayers.value; // never render water layer
reflectionCamera.targetTexture = m_ReflectionTexture;
GL.SetRevertBackfacing (true);
reflectionCamera.transform.position = newpos;
Vector3 euler = cam.transform.eulerAngles;
reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z);
// don't render tree meshes or grass in reflection :)
float oldDetailDist = m_Terrain.detailObjectDistance;
float oldTreeDist = m_Terrain.treeDistance;
float oldTreeBillDist = m_Terrain.treeBillboardDistance;
float oldSplatDist = m_Terrain.basemapDistance;
m_Terrain.detailObjectDistance = 0.0f;
m_Terrain.treeBillboardDistance = 0.0f;
m_Terrain.basemapDistance = 0.0f;
reflectionCamera.Render();
m_Terrain.detailObjectDistance = oldDetailDist;
m_Terrain.treeDistance = oldTreeDist;
m_Terrain.treeBillboardDistance = oldTreeBillDist;
m_Terrain.basemapDistance = oldSplatDist;
reflectionCamera.transform.position = oldpos;
GL.SetRevertBackfacing (false);
renderer.sharedMaterial.SetTexture( "_ReflectionTex", m_ReflectionTexture );
}
else renderer.sharedMaterial.SetTexture( "_ReflectionTex", null );
// Render refraction
if( mode >= WaterMode.Refractive )
{
refractionCamera.worldToCameraMatrix = cam.worldToCameraMatrix;
// Setup oblique projection matrix so that near plane is our reflection
// plane. This way we clip everything below/above it for free.
Vector4 clipPlane = CameraSpacePlane( refractionCamera, pos, normal, -1.0f );
Matrix4x4 projection = cam.projectionMatrix;
CalculateObliqueMatrix (ref projection, clipPlane);
refractionCamera.projectionMatrix = projection;
refractionCamera.cullingMask = cullingMask & m_RefractLayers.value; // never render water layer
refractionCamera.targetTexture = m_RefractionTexture;
refractionCamera.transform.position = cam.transform.position;
refractionCamera.transform.rotation = cam.transform.rotation;
// don't render trees or grass in refraction :)
float oldDetailDist = m_Terrain.detailObjectDistance;
float oldTreeDist = m_Terrain.treeDistance;
float oldTreeBillDist = m_Terrain.treeBillboardDistance;
m_Terrain.detailObjectDistance = 0.0f;
m_Terrain.treeDistance = 0.0f;
m_Terrain.treeBillboardDistance = 0.0f;
refractionCamera.Render();
m_Terrain.detailObjectDistance = oldDetailDist;
m_Terrain.treeDistance = oldTreeDist;
m_Terrain.treeBillboardDistance = oldTreeBillDist;
renderer.sharedMaterial.SetTexture( "_RefractionTex", m_RefractionTexture );
}
QualitySettings.softVegetation = oldSoftVegetation;
// Restore pixel light count
if( m_DisablePixelLights )
QualitySettings.pixelLightCount = oldPixelLightCount;
// Setup shader keywords based on water mode
switch( mode )
{
case WaterMode.Simple:
Shader.EnableKeyword( "WATER_SIMPLE" );
Shader.DisableKeyword( "WATER_REFLECTIVE" );
Shader.DisableKeyword( "WATER_REFRACTIVE" );
break;
case WaterMode.Reflective:
Shader.DisableKeyword( "WATER_SIMPLE" );
Shader.EnableKeyword( "WATER_REFLECTIVE" );
Shader.DisableKeyword( "WATER_REFRACTIVE" );
break;
case WaterMode.Refractive:
Shader.DisableKeyword( "WATER_SIMPLE" );
Shader.DisableKeyword( "WATER_REFLECTIVE" );
Shader.EnableKeyword( "WATER_REFRACTIVE" );
break;
}
s_InsideWater = false;
}
// Cleanup all the objects we possibly have created
void OnDisable()
{
if( renderer )
{
Material mat = renderer.sharedMaterial;
if( mat )
{
mat.SetTexture( "_ReflectionTex", null );
mat.SetTexture( "_RefractionTex", null );
mat.shader = m_ShaderSimple;
}
}
if( m_ReflectionTexture ) {
DestroyImmediate( m_ReflectionTexture );
m_ReflectionTexture = null;
}
if( m_RefractionTexture ) {
DestroyImmediate( m_RefractionTexture );
m_RefractionTexture = null;
}
foreach( DictionaryEntry kvp in m_ReflectionCameras )
DestroyImmediate( ((Camera)kvp.Value).gameObject );
m_ReflectionCameras.Clear();
foreach( DictionaryEntry kvp in m_RefractionCameras )
DestroyImmediate( ((Camera)kvp.Value).gameObject );
m_RefractionCameras.Clear();
}
// This just sets up some matrices in the material; for really
// old cards to make water texture scroll.
void Update()
{
Camera cam = Camera.main;
if( !cam )
return;
//Flip upsidedown if cam is below us
isSurface = (cam.transform.position.y > WaterTransform.position.y);
WaterTransform.rotation = (isSurface ? Quaternion.identity : Quaternion.Euler(180, 0, 0));
if( !renderer )
return;
Material mat = renderer.sharedMaterial;
if( !mat )
return;
Vector4 waveSpeed = mat.GetVector( "WaveSpeed" );
float waveScale = mat.GetFloat( "_WaveScale" );
float t = Time.time / 40.0f;
Vector3 scale = new Vector3( 1.0f/waveScale, 1.0f/waveScale, 1 );
Vector3 offset = new Vector3( t * waveSpeed.x / scale.x, t * waveSpeed.y / scale.y, 0 );
Matrix4x4 scrollMatrix = Matrix4x4.TRS( offset, Quaternion.identity, scale );
mat.SetMatrix( "_WaveMatrix", scrollMatrix );
offset = new Vector3( t * waveSpeed.z / scale.x, t * waveSpeed.w / scale.y, 0 );
scrollMatrix = Matrix4x4.TRS( offset, Quaternion.identity, scale * 0.45f );
mat.SetMatrix( "_WaveMatrix2", scrollMatrix );
}
private void UpdateCameraModes( Camera src, Camera dest )
{
if( dest == null )
return;
// set water camera to clear the same way as current camera
dest.clearFlags = src.clearFlags;
dest.backgroundColor = src.backgroundColor;
if( src.clearFlags == CameraClearFlags.Skybox )
{
Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox;
Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox;
if( !sky || !sky.material )
{
mysky.enabled = false;
}
else
{
mysky.enabled = true;
mysky.material = sky.material;
}
}
// update other values to match current camera.
// even if we are supplying custom camera&projection matrices,
// some of values are used elsewhere (e.g. skybox uses far plane)
dest.farClipPlane = src.farClipPlane;
dest.nearClipPlane = src.nearClipPlane;
dest.orthographic = src.orthographic;
dest.fieldOfView = src.fieldOfView;
dest.aspect = src.aspect;
dest.orthographicSize = src.orthographicSize;
}
// On-demand create any objects we need for water
private void CreateWaterObjects( Camera currentCamera, out Camera reflectionCamera, out Camera refractionCamera )
{
WaterMode mode = GetWaterMode();
reflectionCamera = null;
refractionCamera = null;
if( mode >= WaterMode.Reflective )
{
// Reflection render texture
if( !m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize )
{
if( m_ReflectionTexture )
DestroyImmediate( m_ReflectionTexture );
m_ReflectionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 );
m_ReflectionTexture.name = "__WaterReflection" + GetInstanceID();
m_ReflectionTexture.isPowerOfTwo = true;
m_ReflectionTexture.hideFlags = HideFlags.DontSave;
m_OldReflectionTextureSize = m_TextureSize;
}
// Camera for reflection
reflectionCamera = m_ReflectionCameras[currentCamera] as Camera;
if( !reflectionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
{
GameObject go = new GameObject( "Water Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) );
reflectionCamera = go.camera;
reflectionCamera.enabled = false;
reflectionCamera.transform.position = transform.position;
reflectionCamera.transform.rotation = transform.rotation;
reflectionCamera.gameObject.AddComponent("FlareLayer");
go.hideFlags = HideFlags.HideAndDontSave;
m_ReflectionCameras[currentCamera] = reflectionCamera;
}
}
if( mode >= WaterMode.Refractive )
{
// Refraction render texture
if( !m_RefractionTexture || m_OldRefractionTextureSize != m_TextureSize )
{
if( m_RefractionTexture )
DestroyImmediate( m_RefractionTexture );
m_RefractionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 );
m_RefractionTexture.name = "__WaterRefraction" + GetInstanceID();
m_RefractionTexture.isPowerOfTwo = true;
m_RefractionTexture.hideFlags = HideFlags.DontSave;
m_OldRefractionTextureSize = m_TextureSize;
}
// Camera for refraction
refractionCamera = m_RefractionCameras[currentCamera] as Camera;
if( !refractionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
{
GameObject go = new GameObject( "Water Refr Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) );
refractionCamera = go.camera;
refractionCamera.enabled = false;
refractionCamera.transform.position = transform.position;
refractionCamera.transform.rotation = transform.rotation;
refractionCamera.gameObject.AddComponent("FlareLayer");
go.hideFlags = HideFlags.HideAndDontSave;
m_RefractionCameras[currentCamera] = refractionCamera;
}
}
}
public WaterMode GetWaterMode()
{
if( m_HardwareWaterSupport < m_WaterMode )
return m_HardwareWaterSupport;
else
return m_WaterMode;
}
public WaterMode FindHardwareWaterSupport()
{
if( !SystemInfo.supportsRenderTextures || !renderer || !m_ShaderFull )
return WaterMode.Simple;
Material mat = renderer.sharedMaterial;
if( !mat )
return WaterMode.Simple;
if( m_ShaderFull.isSupported )
return WaterMode.Refractive;
string mode = mat.GetTag("WATERMODE", false);
if( mode == "Refractive" )
return WaterMode.Refractive;
if( mode == "Reflective" )
return WaterMode.Reflective;
return WaterMode.Simple;
}
// Extended sign: returns -1, 0 or 1 based on sign of a
private static float sgn(float a)
{
if (a > 0.0f) return 1.0f;
if (a < 0.0f) return -1.0f;
return 0.0f;
}
// Given position/normal of the plane, calculates plane in camera space.
private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
{
Vector3 offsetPos = pos + normal * m_ClipPlaneOffset;
Matrix4x4 m = cam.worldToCameraMatrix;
Vector3 cpos = m.MultiplyPoint( offsetPos );
Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign;
return new Vector4( cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal) );
}
// Adjusts the given projection matrix so that near plane is the given clipPlane
// clipPlane is given in camera space. See article in Game Programming Gems 5.
private static void CalculateObliqueMatrix (ref Matrix4x4 projection, Vector4 clipPlane)
{
Vector4 q;
q.x = (sgn(clipPlane.x) + projection[8]) / projection[0];
q.y = (sgn(clipPlane.y) + projection[9]) / projection[5];
q.z = -1.0F;
q.w = (1.0F + projection[10]) / projection[14];
Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
projection[2] = c.x;
projection[6] = c.y;
projection[10] = c.z + 1.0F;
projection[14] = c.w;
}
// Calculates reflection matrix around the given plane
private static void CalculateReflectionMatrix (ref Matrix4x4 reflectionMat, Vector4 plane)
{
reflectionMat.m00 = (1F - 2F*plane[0]*plane[0]);
reflectionMat.m01 = ( - 2F*plane[0]*plane[1]);
reflectionMat.m02 = ( - 2F*plane[0]*plane[2]);
reflectionMat.m03 = ( - 2F*plane[3]*plane[0]);
reflectionMat.m10 = ( - 2F*plane[1]*plane[0]);
reflectionMat.m11 = (1F - 2F*plane[1]*plane[1]);
reflectionMat.m12 = ( - 2F*plane[1]*plane[2]);
reflectionMat.m13 = ( - 2F*plane[3]*plane[1]);
reflectionMat.m20 = ( - 2F*plane[2]*plane[0]);
reflectionMat.m21 = ( - 2F*plane[2]*plane[1]);
reflectionMat.m22 = (1F - 2F*plane[2]*plane[2]);
reflectionMat.m23 = ( - 2F*plane[3]*plane[2]);
reflectionMat.m30 = 0F;
reflectionMat.m31 = 0F;
reflectionMat.m32 = 0F;
reflectionMat.m33 = 1F;
}
}
| |
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
// The master server is declared with the server defaults, which is
// loaded on both clients & dedicated servers. If the server mod
// is not loaded on a client, then the master must be defined.
// $pref::Master[0] = "2:master.garagegames.com:28002";
$pref::Player::Name = "Visitor";
$pref::Player::defaultFov = 65;
$pref::Player::zoomSpeed = 0;
$pref::Net::LagThreshold = 400;
$pref::Net::Port = 28000;
$pref::HudMessageLogSize = 40;
$pref::ChatHudLength = 1;
$pref::Input::LinkMouseSensitivity = 1;
// DInput keyboard, mouse, and joystick prefs
$pref::Input::KeyboardEnabled = 1;
$pref::Input::MouseEnabled = 1;
$pref::Input::JoystickEnabled = 0;
$pref::Input::KeyboardTurnSpeed = 0.1;
$sceneLighting::cacheSize = 20000;
$sceneLighting::purgeMethod = "lastCreated";
$sceneLighting::cacheLighting = 1;
$pref::Video::displayDevice = "D3D9";
$pref::Video::disableVerticalSync = 1;
$pref::Video::mode = "1024 768 false 32 60 4";
$pref::Video::defaultFenceCount = 0;
$pref::Video::screenShotSession = 0;
$pref::Video::screenShotFormat = "PNG";
/// This disables the hardware FSAA/MSAA so that
/// we depend completely on the FXAA post effect
/// which works on all cards and in deferred mode.
///
/// Note the new Intel Hybrid graphics on laptops
/// will fail to initialize when hardware AA is
/// enabled... so you've been warned.
///
$pref::Video::disableHardwareAA = true;
$pref::Video::disableNormalmapping = false;
$pref::Video::disablePixSpecular = false;
$pref::Video::disableCubemapping = false;
///
$pref::Video::disableParallaxMapping = false;
$pref::Video::Gamma = 1.0;
// Console-friendly defaults
if($platform $= "xenon")
{
// Save some fillrate on the X360, and take advantage of the HW scaling
$pref::Video::Resolution = "1152 640";
$pref::Video::mode = $pref::Video::Resolution SPC "true 32 60 0";
$pref::Video::fullScreen = 1;
}
/// This is the path used by ShaderGen to cache procedural
/// shaders. If left blank ShaderGen will only cache shaders
/// to memory and not to disk.
$shaderGen::cachePath = "shaders/procedural";
/// The perfered light manager to use at startup. If blank
/// or if the selected one doesn't work on this platfom it
/// will try the defaults below.
$pref::lightManager = "";
/// This is the default list of light managers ordered from
/// most to least desirable for initialization.
$lightManager::defaults = "Advanced Lighting" NL "Basic Lighting";
/// A scale to apply to the camera view distance
/// typically used for tuning performance.
$pref::camera::distanceScale = 1.0;
/// Causes the system to do a one time autodetect
/// of an SFX provider and device at startup if the
/// provider is unset.
$pref::SFX::autoDetect = true;
/// The sound provider to select at startup. Typically
/// this is DirectSound, OpenAL, or XACT. There is also
/// a special Null provider which acts normally, but
/// plays no sound.
$pref::SFX::provider = "";
/// The sound device to select from the provider. Each
/// provider may have several different devices.
$pref::SFX::device = "OpenAL";
/// If true the device will try to use hardware buffers
/// and sound mixing. If not it will use software.
$pref::SFX::useHardware = false;
/// If you have a software device you have a
/// choice of how many software buffers to
/// allow at any one time. More buffers cost
/// more CPU time to process and mix.
$pref::SFX::maxSoftwareBuffers = 16;
/// This is the playback frequency for the primary
/// sound buffer used for mixing. Although most
/// providers will reformat on the fly, for best
/// quality and performance match your sound files
/// to this setting.
$pref::SFX::frequency = 44100;
/// This is the playback bitrate for the primary
/// sound buffer used for mixing. Although most
/// providers will reformat on the fly, for best
/// quality and performance match your sound files
/// to this setting.
$pref::SFX::bitrate = 32;
/// The overall system volume at startup. Note that
/// you can only scale volume down, volume does not
/// get louder than 1.
$pref::SFX::masterVolume = 0.8;
/// The startup sound channel volumes. These are
/// used to control the overall volume of different
/// classes of sounds.
$pref::SFX::channelVolume1 = 1;
$pref::SFX::channelVolume2 = 1;
$pref::SFX::channelVolume3 = 1;
$pref::SFX::channelVolume4 = 1;
$pref::SFX::channelVolume5 = 1;
$pref::SFX::channelVolume6 = 1;
$pref::SFX::channelVolume7 = 1;
$pref::SFX::channelVolume8 = 1;
$pref::PostEffect::PreferedHDRFormat = "GFXFormatR8G8B8A8";
/// This is an scalar which can be used to reduce the
/// reflection textures on all objects to save fillrate.
$pref::Reflect::refractTexScale = 1.0;
/// This is the total frame in milliseconds to budget for
/// reflection rendering. If your CPU bound and have alot
/// of smaller reflection surfaces try reducing this time.
$pref::Reflect::frameLimitMS = 10;
/// Set true to force all water objects to use static cubemap reflections.
$pref::Water::disableTrueReflections = false;
// A global LOD scalar which can reduce the overall density of placed GroundCover.
$pref::GroundCover::densityScale = 1.0;
/// An overall scaler on the lod switching between DTS models.
/// Smaller numbers makes the lod switch sooner.
$pref::TS::detailAdjust = 1.0;
///
$pref::Decals::enabled = true;
///
$pref::Decals::lifeTimeScale = "1";
/// The number of mipmap levels to drop on loaded textures
/// to reduce video memory usage.
///
/// It will skip any textures that have been defined as not
/// allowing down scaling.
///
$pref::Video::textureReductionLevel = 0;
///
$pref::Shadows::textureScalar = 1.0;
///
$pref::Shadows::disable = false;
/// Sets the shadow filtering mode.
///
/// None - Disables filtering.
///
/// SoftShadow - Does a simple soft shadow
///
/// SoftShadowHighQuality
///
$pref::Shadows::filterMode = "SoftShadow";
///
$pref::Video::defaultAnisotropy = 1;
/// Radius in meters around the camera that ForestItems are affected by wind.
/// Note that a very large number with a large number of items is not cheap.
$pref::windEffectRadius = 25;
/// AutoDetect graphics quality levels the next startup.
$pref::Video::autoDetect = 1;
//-----------------------------------------------------------------------------
// Graphics Quality Groups
//-----------------------------------------------------------------------------
// The graphics quality groups are used by the options dialog to
// control the state of the $prefs. You should overload these in
// your game specific defaults.cs file if they need to be changed.
if ( isObject( MeshQualityGroup ) )
MeshQualityGroup.delete();
if ( isObject( TextureQualityGroup ) )
TextureQualityGroup.delete();
if ( isObject( LightingQualityGroup ) )
LightingQualityGroup.delete();
if ( isObject( ShaderQualityGroup ) )
ShaderQualityGroup.delete();
new SimGroup( MeshQualityGroup )
{
new ArrayObject( [Lowest] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::TS::detailAdjust"] = 0.5;
key["$pref::TS::skipRenderDLs"] = 1;
key["$pref::Terrain::lodScale"] = 2.0;
key["$pref::decalMgr::enabled"] = false;
key["$pref::GroundCover::densityScale"] = 0.5;
};
new ArrayObject( [Low] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::TS::detailAdjust"] = 0.75;
key["$pref::TS::skipRenderDLs"] = 0;
key["$pref::Terrain::lodScale"] = 1.5;
key["$pref::decalMgr::enabled"] = true;
key["$pref::GroundCover::densityScale"] = 0.75;
};
new ArrayObject( [Normal] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::TS::detailAdjust"] = 1.0;
key["$pref::TS::skipRenderDLs"] = 0;
key["$pref::Terrain::lodScale"] = 1.0;
key["$pref::decalMgr::enabled"] = true;
key["$pref::GroundCover::densityScale"] = 1.0;
};
new ArrayObject( [High] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::TS::detailAdjust"] = 1.5;
key["$pref::TS::skipRenderDLs"] = 0;
key["$pref::Terrain::lodScale"] = 0.75;
key["$pref::decalMgr::enabled"] = true;
key["$pref::GroundCover::densityScale"] = 1.0;
};
};
new SimGroup( TextureQualityGroup )
{
new ArrayObject( [Lowest] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::Video::textureReductionLevel"] = 2;
key["$pref::Reflect::refractTexScale"] = 0.5;
key["$pref::Terrain::detailScale"] = 0.5;
};
new ArrayObject( [Low] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::Video::textureReductionLevel"] = 1;
key["$pref::Reflect::refractTexScale"] = 0.75;
key["$pref::Terrain::detailScale"] = 0.75;
};
new ArrayObject( [Normal] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::Video::textureReductionLevel"] = 0;
key["$pref::Reflect::refractTexScale"] = 1;
key["$pref::Terrain::detailScale"] = 1;
};
new ArrayObject( [High] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::Video::textureReductionLevel"] = 0;
key["$pref::Reflect::refractTexScale"] = 1.25;
key["$pref::Terrain::detailScale"] = 1.5;
};
};
function TextureQualityGroup::onApply( %this, %level )
{
// Note that this can be a slow operation.
reloadTextures();
}
new SimGroup( LightingQualityGroup )
{
new ArrayObject( [Lowest] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::lightManager"] = "Basic Lighting";
key["$pref::Shadows::disable"] = false;
key["$pref::Shadows::textureScalar"] = 0.5;
key["$pref::Shadows::filterMode"] = "None";
};
new ArrayObject( [Low] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::lightManager"] = "Advanced Lighting";
key["$pref::Shadows::disable"] = false;
key["$pref::Shadows::textureScalar"] = 0.5;
key["$pref::Shadows::filterMode"] = "SoftShadow";
};
new ArrayObject( [Normal] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::lightManager"] = "Advanced Lighting";
key["$pref::Shadows::disable"] = false;
key["$pref::Shadows::textureScalar"] = 1.0;
key["$pref::Shadows::filterMode"] = "SoftShadowHighQuality";
};
new ArrayObject( [High] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::lightManager"] = "Advanced Lighting";
key["$pref::Shadows::disable"] = false;
key["$pref::Shadows::textureScalar"] = 2.0;
key["$pref::Shadows::filterMode"] = "SoftShadowHighQuality";
};
};
function LightingQualityGroup::onApply( %this, %level )
{
// Set the light manager. This should do nothing
// if its already set or if its not compatible.
setLightManager( $pref::lightManager );
}
// TODO: Reduce shader complexity of water and the scatter sky here!
new SimGroup( ShaderQualityGroup )
{
new ArrayObject( [Lowest] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::Video::disablePixSpecular"] = true;
key["$pref::Video::disableNormalmapping"] = true;
key["$pref::Video::disableParallaxMapping"] = true;
key["$pref::Water::disableTrueReflections"] = true;
};
new ArrayObject( [Low] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::Video::disablePixSpecular"] = false;
key["$pref::Video::disableNormalmapping"] = false;
key["$pref::Video::disableParallaxMapping"] = true;
key["$pref::Water::disableTrueReflections"] = true;
};
new ArrayObject( [Normal] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::Video::disablePixSpecular"] = false;
key["$pref::Video::disableNormalmapping"] = false;
key["$pref::Video::disableParallaxMapping"] = false;
key["$pref::Water::disableTrueReflections"] = false;
};
new ArrayObject( [High] )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
key["$pref::Video::disablePixSpecular"] = false;
key["$pref::Video::disableNormalmapping"] = false;
key["$pref::Video::disableParallaxMapping"] = false;
key["$pref::Water::disableTrueReflections"] = false;
};
};
function GraphicsQualityAutodetect()
{
$pref::Video::autoDetect = false;
%shaderVer = getPixelShaderVersion();
%intel = ( strstr( strupr( getDisplayDeviceInformation() ), "INTEL" ) != -1 ) ? true : false;
%videoMem = GFXCardProfilerAPI::getVideoMemoryMB();
return GraphicsQualityAutodetect_Apply( %shaderVer, %intel, %videoMem );
}
function GraphicsQualityAutodetect_Apply( %shaderVer, %intel, %videoMem )
{
if ( %shaderVer < 2.0 )
{
return "Your video card does not meet the minimum requirment of shader model 2.0.";
}
if ( %shaderVer < 3.0 || %intel )
{
// Allow specular and normals for 2.0a and 2.0b
if ( %shaderVer > 2.0 )
{
MeshQualityGroup-->Lowest.apply();
TextureQualityGroup-->Lowest.apply();
LightingQualityGroup-->Lowest.apply();
ShaderQualityGroup-->Low.apply();
}
else
{
MeshQualityGroup-->Lowest.apply();
TextureQualityGroup-->Lowest.apply();
LightingQualityGroup-->Lowest.apply();
ShaderQualityGroup-->Lowest.apply();
}
}
else
{
if ( %videoMem > 1000 )
{
MeshQualityGroup-->High.apply();
TextureQualityGroup-->High.apply();
LightingQualityGroup-->High.apply();
ShaderQualityGroup-->High.apply();
}
else if ( %videoMem > 400 || %videoMem == 0 )
{
MeshQualityGroup-->Normal.apply();
TextureQualityGroup-->Normal.apply();
LightingQualityGroup-->Normal.apply();
ShaderQualityGroup-->Normal.apply();
if ( %videoMem == 0 )
return "Torque was unable to detect available video memory. Applying 'Normal' quality.";
}
else
{
MeshQualityGroup-->Low.apply();
TextureQualityGroup-->Low.apply();
LightingQualityGroup-->Low.apply();
ShaderQualityGroup-->Low.apply();
}
}
return "Graphics quality settings have been auto detected.";
}
| |
using UnityEngine;
using System.Collections;
using System;
/// <summary>
/// Game Jolt API Helper main class. Inherit from <see cref="MonoBehaviour"/>
/// </summary>
public class GJAPIHelper : MonoBehaviour {
#region Singleton Pattern
/// <summary>
/// The GJAPIHelper instance.
/// </summary>
private static GJAPIHelper instance;
/// <summary>
/// Gets the GJAPIHelper instance.
/// </summary>
/// <value>
/// The GJAPIHelper instance.
/// </value>
public static GJAPIHelper Instance
{
get
{
if (instance == null)
{
GJAPI gjapi = (GJAPI) FindObjectOfType (typeof (GJAPI));
if (gjapi == null)
{
Debug.LogError ("An instance of GJAPI is needed in the scene, but there is none. Can't initialise GJAPIHelper.");
}
else
{
instance = gjapi.gameObject.AddComponent<GJAPIHelper>();
if (instance == null)
{
Debug.Log ("An error occured creating GJAPIHelper.");
}
}
}
return instance;
}
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the application quit.
/// </summary>
void OnDestroy ()
{
StopAllCoroutines ();
skin = null;
users = null;
scores = null;
trophies = null;
instance = null;
}
#endregion Singleton Pattern
/// <summary>
/// The <see cref="GUISkin"/>.
/// </summary>
protected GUISkin skin = null;
/// <summary>
/// Gets or sets the <see cref="GUISkin"/>.
/// </summary>
/// <value>
/// The <see cref="GUISkin"/>.
/// </value>
public static GUISkin Skin
{
get
{
if (Instance.skin == null) {
Instance.skin = (GUISkin) Resources.Load ("GJSkin", typeof (GUISkin)) ?? GUI.skin;
}
return Instance.skin;
}
set { Instance.skin = value; }
}
/// <summary>
/// The users helpers.
/// </summary>
GJHUsersMethods users = null;
/// <summary>
/// Gets the users helpers.
/// </summary>
/// <value>
/// The users helpers.
/// </value>
public static GJHUsersMethods Users
{
get
{
if (Instance.users == null)
{
Instance.users = new GJHUsersMethods ();
}
return Instance.users;
}
}
/// <summary>
/// The scores helpers.
/// </summary>
GJHScoresMethods scores = null;
/// <summary>
/// Gets the scores helpers.
/// </summary>
/// <value>
/// The scores helpers.
/// </value>
public static GJHScoresMethods Scores
{
get
{
if (Instance.scores == null)
{
Instance.scores = new GJHScoresMethods ();
}
return Instance.scores;
}
}
/// <summary>
/// The trophies helpers.
/// </summary>
GJHTrophiesMethods trophies = null;
/// <summary>
/// Gets the trophies helpers.
/// </summary>
/// <value>
/// The trophies helpers.
/// </value>
public static GJHTrophiesMethods Trophies
{
get
{
if (Instance.trophies == null)
{
Instance.trophies = new GJHTrophiesMethods ();
}
return Instance.trophies;
}
}
/// <summary>
/// Downloads the image.
/// </summary>
/// <param name='url'>
/// The image URL.
/// </param>
/// <param name='OnComplete'>
/// The callback.
/// </param>
public static void DownloadImage (string url, Action<Texture2D> OnComplete)
{
Instance.StartCoroutine (Instance.DownloadImageCoroutine (url, OnComplete));
}
/// <summary>
/// Downloads the image coroutine.
/// </summary>
/// <param name='url'>
/// The image URL.
/// </param>
/// <param name='OnComplete'>
/// The callback.
/// </param>
IEnumerator DownloadImageCoroutine (string url, Action<Texture2D> OnComplete)
{
if (!string.IsNullOrEmpty (url))
{
Texture2D tex;
WWW www = new WWW (url);
yield return www;
if (www.error == null)
{
tex = new Texture2D (1, 1, TextureFormat.RGB24, false);
tex.LoadImage (www.bytes);
tex.wrapMode = TextureWrapMode.Clamp;
}
else
{
Debug.Log ("GJAPIHelper: Error downloading image:\n" + www.error);
tex = null;
}
if (OnComplete != null)
{
OnComplete (tex);
}
}
}
public void OnGetUserFromWeb (string response)
{
users.ReadGetFromWebResponse (response);
}
}
| |
using System;
using System.ComponentModel;
using System.Reflection;
using Should;
using NUnit.Framework;
namespace AutoMapper.UnitTests
{
namespace CustomMapping
{
public class When_specifying_type_converters : AutoMapperSpecBase
{
private Destination _result;
public class Source
{
public string Value1 { get; set; }
public string Value2 { get; set; }
public string Value3 { get; set; }
}
public class Destination
{
public int Value1 { get; set; }
public DateTime Value2 { get; set; }
public Type Value3 { get; set; }
}
public class DateTimeTypeConverter : TypeConverter<string, DateTime>
{
protected override DateTime ConvertCore(string source)
{
return System.Convert.ToDateTime(source);
}
}
public class TypeTypeConverter : TypeConverter<string, Type>
{
protected override Type ConvertCore(string source)
{
Type type = Assembly.GetExecutingAssembly().GetType(source);
return type;
}
}
protected override void Establish_context()
{
Mapper.CreateMap<string, int>().ConvertUsing(arg => Convert.ToInt32(arg));
Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
Mapper.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>();
Mapper.CreateMap<Source, Destination>();
var source = new Source
{
Value1 = "5",
Value2 = "01/01/2000",
Value3 = "AutoMapper.UnitTests.CustomMapping.When_specifying_type_converters+Destination"
};
_result = Mapper.Map<Source, Destination>(source);
}
[Test]
public void Should_convert_type_using_expression()
{
_result.Value1.ShouldEqual(5);
}
[Test]
public void Should_convert_type_using_instance()
{
_result.Value2.ShouldEqual(new DateTime(2000, 1, 1));
}
[Test]
public void Should_convert_type_using_Func_that_returns_instance()
{
_result.Value3.ShouldEqual(typeof(Destination));
}
}
public class When_specifying_type_converters_on_types_with_incompatible_members : AutoMapperSpecBase
{
private ParentDestination _result;
public class Source
{
public string Foo { get; set; }
}
public class Destination
{
public int Type { get; set; }
}
public class ParentSource
{
public Source Value { get; set; }
}
public class ParentDestination
{
public Destination Value { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>().ConvertUsing(arg => new Destination {Type = Convert.ToInt32(arg.Foo)});
Mapper.CreateMap<ParentSource, ParentDestination>();
var source = new ParentSource
{
Value = new Source { Foo = "5",}
};
_result = Mapper.Map<ParentSource, ParentDestination>(source);
}
[Test]
public void Should_convert_type_using_expression()
{
_result.Value.Type.ShouldEqual(5);
}
}
public class When_specifying_mapping_with_the_BCL_type_converter_class : AutoMapperSpecBase
{
[TypeConverter(typeof(CustomTypeConverter))]
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int OtherValue { get; set; }
}
public class CustomTypeConverter : TypeConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof (Destination);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
return new Destination
{
OtherValue = ((Source) value).Value + 10
};
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(Destination);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
return new Source {Value = ((Destination) value).OtherValue - 10};
}
}
[Test]
public void Should_convert_from_type_using_the_custom_type_converter()
{
var source = new Source
{
Value = 5
};
var destination = Mapper.Map<Source, Destination>(source);
destination.OtherValue.ShouldEqual(15);
}
[Test]
public void Should_convert_to_type_using_the_custom_type_converter()
{
var source = new Destination()
{
OtherValue = 15
};
var destination = Mapper.Map<Destination, Source>(source);
destination.Value.ShouldEqual(5);
}
}
public class When_specifying_a_type_converter_for_a_non_generic_configuration : SpecBase
{
private Destination _result;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int OtherValue { get; set; }
}
public class CustomConverter : TypeConverter<Source, Destination>
{
protected override Destination ConvertCore(Source source)
{
return new Destination
{
OtherValue = source.Value + 10
};
}
}
protected override void Establish_context()
{
Mapper.CreateMap(typeof(Source), typeof(Destination)).ConvertUsing<CustomConverter>();
}
protected override void Because_of()
{
_result = Mapper.Map<Source, Destination>(new Source {Value = 5});
}
[Test]
public void Should_use_converter_specified()
{
_result.OtherValue.ShouldEqual(15);
}
[Test]
public void Should_pass_configuration_validation()
{
Mapper.AssertConfigurationIsValid();
}
}
public class When_specifying_a_non_generic_type_converter_for_a_non_generic_configuration : SpecBase
{
private Destination _result;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int OtherValue { get; set; }
}
public class CustomConverter : TypeConverter<Source, Destination>
{
protected override Destination ConvertCore(Source source)
{
return new Destination
{
OtherValue = source.Value + 10
};
}
}
protected override void Establish_context()
{
Mapper.CreateMap(typeof(Source), typeof(Destination)).ConvertUsing(typeof(CustomConverter));
}
protected override void Because_of()
{
_result = Mapper.Map<Source, Destination>(new Source {Value = 5});
}
[Test]
public void Should_use_converter_specified()
{
_result.OtherValue.ShouldEqual(15);
}
[Test]
public void Should_pass_configuration_validation()
{
Mapper.AssertConfigurationIsValid();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace IdentityDemo.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using Avalonia.Input.Platform;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Utils;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Metadata;
using Avalonia.Data;
using Avalonia.Layout;
using Avalonia.Utilities;
using Avalonia.Controls.Metadata;
namespace Avalonia.Controls
{
/// <summary>
/// Represents a control that can be used to display or edit unformatted text.
/// </summary>
[PseudoClasses(":empty")]
public class TextBox : TemplatedControl, UndoRedoHelper<TextBox.UndoRedoState>.IUndoRedoHost
{
public static KeyGesture CutGesture { get; } = AvaloniaLocator.Current
.GetService<PlatformHotkeyConfiguration>()?.Cut.FirstOrDefault();
public static KeyGesture CopyGesture { get; } = AvaloniaLocator.Current
.GetService<PlatformHotkeyConfiguration>()?.Copy.FirstOrDefault();
public static KeyGesture PasteGesture { get; } = AvaloniaLocator.Current
.GetService<PlatformHotkeyConfiguration>()?.Paste.FirstOrDefault();
public static readonly StyledProperty<bool> AcceptsReturnProperty =
AvaloniaProperty.Register<TextBox, bool>(nameof(AcceptsReturn));
public static readonly StyledProperty<bool> AcceptsTabProperty =
AvaloniaProperty.Register<TextBox, bool>(nameof(AcceptsTab));
public static readonly DirectProperty<TextBox, int> CaretIndexProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(CaretIndex),
o => o.CaretIndex,
(o, v) => o.CaretIndex = v);
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextBox, bool>(nameof(IsReadOnly));
public static readonly StyledProperty<char> PasswordCharProperty =
AvaloniaProperty.Register<TextBox, char>(nameof(PasswordChar));
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextBox, IBrush>(nameof(SelectionBrushProperty));
public static readonly StyledProperty<IBrush> SelectionForegroundBrushProperty =
AvaloniaProperty.Register<TextBox, IBrush>(nameof(SelectionForegroundBrushProperty));
public static readonly StyledProperty<IBrush> CaretBrushProperty =
AvaloniaProperty.Register<TextBox, IBrush>(nameof(CaretBrushProperty));
public static readonly DirectProperty<TextBox, int> SelectionStartProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(SelectionStart),
o => o.SelectionStart,
(o, v) => o.SelectionStart = v);
public static readonly DirectProperty<TextBox, int> SelectionEndProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(SelectionEnd),
o => o.SelectionEnd,
(o, v) => o.SelectionEnd = v);
public static readonly StyledProperty<int> MaxLengthProperty =
AvaloniaProperty.Register<TextBox, int>(nameof(MaxLength), defaultValue: 0);
public static readonly DirectProperty<TextBox, string> TextProperty =
TextBlock.TextProperty.AddOwnerWithDataValidation<TextBox>(
o => o.Text,
(o, v) => o.Text = v,
defaultBindingMode: BindingMode.TwoWay,
enableDataValidation: true);
public static readonly StyledProperty<TextAlignment> TextAlignmentProperty =
TextBlock.TextAlignmentProperty.AddOwner<TextBox>();
/// <summary>
/// Defines the <see cref="HorizontalAlignment"/> property.
/// </summary>
public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty =
ContentControl.HorizontalContentAlignmentProperty.AddOwner<TextBox>();
/// <summary>
/// Defines the <see cref="VerticalAlignment"/> property.
/// </summary>
public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty =
ContentControl.VerticalContentAlignmentProperty.AddOwner<TextBox>();
public static readonly StyledProperty<TextWrapping> TextWrappingProperty =
TextBlock.TextWrappingProperty.AddOwner<TextBox>();
public static readonly StyledProperty<string> WatermarkProperty =
AvaloniaProperty.Register<TextBox, string>(nameof(Watermark));
public static readonly StyledProperty<bool> UseFloatingWatermarkProperty =
AvaloniaProperty.Register<TextBox, bool>(nameof(UseFloatingWatermark));
public static readonly DirectProperty<TextBox, string> NewLineProperty =
AvaloniaProperty.RegisterDirect<TextBox, string>(nameof(NewLine),
textbox => textbox.NewLine, (textbox, newline) => textbox.NewLine = newline);
public static readonly StyledProperty<object> InnerLeftContentProperty =
AvaloniaProperty.Register<TextBox, object>(nameof(InnerLeftContent));
public static readonly StyledProperty<object> InnerRightContentProperty =
AvaloniaProperty.Register<TextBox, object>(nameof(InnerRightContent));
public static readonly StyledProperty<bool> RevealPasswordProperty =
AvaloniaProperty.Register<TextBox, bool>(nameof(RevealPassword));
public static readonly DirectProperty<TextBox, bool> CanCutProperty =
AvaloniaProperty.RegisterDirect<TextBox, bool>(
nameof(CanCut),
o => o.CanCut);
public static readonly DirectProperty<TextBox, bool> CanCopyProperty =
AvaloniaProperty.RegisterDirect<TextBox, bool>(
nameof(CanCopy),
o => o.CanCopy);
public static readonly DirectProperty<TextBox, bool> CanPasteProperty =
AvaloniaProperty.RegisterDirect<TextBox, bool>(
nameof(CanPaste),
o => o.CanPaste);
public static readonly StyledProperty<bool> IsUndoEnabledProperty =
AvaloniaProperty.Register<TextBox, bool>(
nameof(IsUndoEnabled),
defaultValue: true);
public static readonly DirectProperty<TextBox, int> UndoLimitProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(UndoLimit),
o => o.UndoLimit,
(o, v) => o.UndoLimit = v,
unsetValue: -1);
public static readonly RoutedEvent<RoutedEventArgs> CopyingToClipboardEvent =
RoutedEvent.Register<TextBox, RoutedEventArgs>(
"CopyingToClipboard", RoutingStrategies.Bubble);
public static readonly RoutedEvent<RoutedEventArgs> CuttingToClipboardEvent =
RoutedEvent.Register<TextBox, RoutedEventArgs>(
"CuttingToClipboard", RoutingStrategies.Bubble);
public static readonly RoutedEvent<RoutedEventArgs> PastingFromClipboardEvent =
RoutedEvent.Register<TextBox, RoutedEventArgs>(
"PastingFromClipboard", RoutingStrategies.Bubble);
readonly struct UndoRedoState : IEquatable<UndoRedoState>
{
public string Text { get; }
public int CaretPosition { get; }
public UndoRedoState(string text, int caretPosition)
{
Text = text;
CaretPosition = caretPosition;
}
public bool Equals(UndoRedoState other) => ReferenceEquals(Text, other.Text) || Equals(Text, other.Text);
public override bool Equals(object obj) => obj is UndoRedoState other && Equals(other);
public override int GetHashCode() => Text.GetHashCode();
}
private string _text;
private int _caretIndex;
private int _selectionStart;
private int _selectionEnd;
private TextPresenter _presenter;
private TextBoxTextInputMethodClient _imClient = new TextBoxTextInputMethodClient();
private UndoRedoHelper<UndoRedoState> _undoRedoHelper;
private bool _isUndoingRedoing;
private bool _ignoreTextChanges;
private bool _canCut;
private bool _canCopy;
private bool _canPaste;
private string _newLine = Environment.NewLine;
private static readonly string[] invalidCharacters = new String[1] { "\u007f" };
private int _selectedTextChangesMadeSinceLastUndoSnapshot;
private bool _hasDoneSnapshotOnce;
private const int _maxCharsBeforeUndoSnapshot = 7;
static TextBox()
{
FocusableProperty.OverrideDefaultValue(typeof(TextBox), true);
TextInputMethodClientRequestedEvent.AddClassHandler<TextBox>((tb, e) =>
{
e.Client = tb._imClient;
});
}
public TextBox()
{
var horizontalScrollBarVisibility = Observable.CombineLatest(
this.GetObservable(AcceptsReturnProperty),
this.GetObservable(TextWrappingProperty),
(acceptsReturn, wrapping) =>
{
if (wrapping != TextWrapping.NoWrap)
{
return ScrollBarVisibility.Disabled;
}
return acceptsReturn ? ScrollBarVisibility.Auto : ScrollBarVisibility.Hidden;
});
this.Bind(
ScrollViewer.HorizontalScrollBarVisibilityProperty,
horizontalScrollBarVisibility,
BindingPriority.Style);
_undoRedoHelper = new UndoRedoHelper<UndoRedoState>(this);
_selectedTextChangesMadeSinceLastUndoSnapshot = 0;
_hasDoneSnapshotOnce = false;
UpdatePseudoclasses();
}
public bool AcceptsReturn
{
get { return GetValue(AcceptsReturnProperty); }
set { SetValue(AcceptsReturnProperty, value); }
}
public bool AcceptsTab
{
get { return GetValue(AcceptsTabProperty); }
set { SetValue(AcceptsTabProperty, value); }
}
public int CaretIndex
{
get
{
return _caretIndex;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(CaretIndexProperty, ref _caretIndex, value);
UndoRedoState state;
if (IsUndoEnabled && _undoRedoHelper.TryGetLastState(out state) && state.Text == Text)
_undoRedoHelper.UpdateLastState();
}
}
public bool IsReadOnly
{
get { return GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty, value); }
}
public char PasswordChar
{
get => GetValue(PasswordCharProperty);
set => SetValue(PasswordCharProperty, value);
}
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
public IBrush SelectionForegroundBrush
{
get => GetValue(SelectionForegroundBrushProperty);
set => SetValue(SelectionForegroundBrushProperty, value);
}
public IBrush CaretBrush
{
get => GetValue(CaretBrushProperty);
set => SetValue(CaretBrushProperty, value);
}
public int SelectionStart
{
get
{
return _selectionStart;
}
set
{
value = CoerceCaretIndex(value);
var changed = SetAndRaise(SelectionStartProperty, ref _selectionStart, value);
if (changed)
{
UpdateCommandStates();
}
if (SelectionStart == SelectionEnd)
{
CaretIndex = SelectionStart;
}
}
}
public int SelectionEnd
{
get
{
return _selectionEnd;
}
set
{
value = CoerceCaretIndex(value);
var changed = SetAndRaise(SelectionEndProperty, ref _selectionEnd, value);
if (changed)
{
UpdateCommandStates();
}
if (SelectionStart == SelectionEnd)
{
CaretIndex = SelectionEnd;
}
}
}
public int MaxLength
{
get { return GetValue(MaxLengthProperty); }
set { SetValue(MaxLengthProperty, value); }
}
[Content]
public string Text
{
get { return _text; }
set
{
if (!_ignoreTextChanges)
{
var caretIndex = CaretIndex;
SelectionStart = CoerceCaretIndex(SelectionStart, value);
SelectionEnd = CoerceCaretIndex(SelectionEnd, value);
CaretIndex = CoerceCaretIndex(caretIndex, value);
if (SetAndRaise(TextProperty, ref _text, value) && IsUndoEnabled && !_isUndoingRedoing)
{
_undoRedoHelper.Clear();
SnapshotUndoRedo(); // so we always have an initial state
}
}
}
}
public string SelectedText
{
get { return GetSelection(); }
set
{
if (string.IsNullOrEmpty(value))
{
_selectedTextChangesMadeSinceLastUndoSnapshot++;
SnapshotUndoRedo(ignoreChangeCount: false);
DeleteSelection();
}
else
{
HandleTextInput(value);
}
}
}
/// <summary>
/// Gets or sets the horizontal alignment of the content within the control.
/// </summary>
public HorizontalAlignment HorizontalContentAlignment
{
get { return GetValue(HorizontalContentAlignmentProperty); }
set { SetValue(HorizontalContentAlignmentProperty, value); }
}
/// <summary>
/// Gets or sets the vertical alignment of the content within the control.
/// </summary>
public VerticalAlignment VerticalContentAlignment
{
get { return GetValue(VerticalContentAlignmentProperty); }
set { SetValue(VerticalContentAlignmentProperty, value); }
}
public TextAlignment TextAlignment
{
get { return GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
public string Watermark
{
get { return GetValue(WatermarkProperty); }
set { SetValue(WatermarkProperty, value); }
}
public bool UseFloatingWatermark
{
get { return GetValue(UseFloatingWatermarkProperty); }
set { SetValue(UseFloatingWatermarkProperty, value); }
}
public object InnerLeftContent
{
get { return GetValue(InnerLeftContentProperty); }
set { SetValue(InnerLeftContentProperty, value); }
}
public object InnerRightContent
{
get { return GetValue(InnerRightContentProperty); }
set { SetValue(InnerRightContentProperty, value); }
}
public bool RevealPassword
{
get { return GetValue(RevealPasswordProperty); }
set { SetValue(RevealPasswordProperty, value); }
}
public TextWrapping TextWrapping
{
get { return GetValue(TextWrappingProperty); }
set { SetValue(TextWrappingProperty, value); }
}
/// <summary>
/// Gets or sets which characters are inserted when Enter is pressed. Default: <see cref="Environment.NewLine"/>
/// </summary>
public string NewLine
{
get { return _newLine; }
set { SetAndRaise(NewLineProperty, ref _newLine, value); }
}
/// <summary>
/// Clears the current selection, maintaining the <see cref="CaretIndex"/>
/// </summary>
public void ClearSelection()
{
SelectionStart = SelectionEnd = CaretIndex;
}
/// <summary>
/// Property for determining if the Cut command can be executed.
/// </summary>
public bool CanCut
{
get { return _canCut; }
private set { SetAndRaise(CanCutProperty, ref _canCut, value); }
}
/// <summary>
/// Property for determining if the Copy command can be executed.
/// </summary>
public bool CanCopy
{
get { return _canCopy; }
private set { SetAndRaise(CanCopyProperty, ref _canCopy, value); }
}
/// <summary>
/// Property for determining if the Paste command can be executed.
/// </summary>
public bool CanPaste
{
get { return _canPaste; }
private set { SetAndRaise(CanPasteProperty, ref _canPaste, value); }
}
/// <summary>
/// Property for determining whether undo/redo is enabled
/// </summary>
public bool IsUndoEnabled
{
get { return GetValue(IsUndoEnabledProperty); }
set { SetValue(IsUndoEnabledProperty, value); }
}
public int UndoLimit
{
get { return _undoRedoHelper.Limit; }
set
{
if (_undoRedoHelper.Limit != value)
{
// can't use SetAndRaise due to using _undoRedoHelper.Limit
// (can't send a ref of a property to SetAndRaise),
// so use RaisePropertyChanged instead.
var oldValue = _undoRedoHelper.Limit;
_undoRedoHelper.Limit = value;
RaisePropertyChanged(UndoLimitProperty, oldValue, value);
}
// from docs at
// https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.textboxbase.isundoenabled:
// "Setting UndoLimit clears the undo queue."
_undoRedoHelper.Clear();
_selectedTextChangesMadeSinceLastUndoSnapshot = 0;
_hasDoneSnapshotOnce = false;
}
}
public event EventHandler<RoutedEventArgs> CopyingToClipboard
{
add => AddHandler(CopyingToClipboardEvent, value);
remove => RemoveHandler(CopyingToClipboardEvent, value);
}
public event EventHandler<RoutedEventArgs> CuttingToClipboard
{
add => AddHandler(CuttingToClipboardEvent, value);
remove => RemoveHandler(CuttingToClipboardEvent, value);
}
public event EventHandler<RoutedEventArgs> PastingFromClipboard
{
add => AddHandler(PastingFromClipboardEvent, value);
remove => RemoveHandler(PastingFromClipboardEvent, value);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
_presenter = e.NameScope.Get<TextPresenter>("PART_TextPresenter");
_imClient.SetPresenter(_presenter);
if (IsFocused)
{
_presenter?.ShowCaret();
}
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == TextProperty)
{
UpdatePseudoclasses();
UpdateCommandStates();
}
else if (change.Property == IsUndoEnabledProperty && change.NewValue.GetValueOrDefault<bool>() == false)
{
// from docs at
// https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.textboxbase.isundoenabled:
// "Setting this property to false clears the undo stack.
// Therefore, if you disable undo and then re-enable it, undo commands still do not work
// because the undo stack was emptied when you disabled undo."
_undoRedoHelper.Clear();
_selectedTextChangesMadeSinceLastUndoSnapshot = 0;
_hasDoneSnapshotOnce = false;
}
}
private void UpdateCommandStates()
{
var text = GetSelection();
var isSelectionNullOrEmpty = string.IsNullOrEmpty(text);
CanCopy = !IsPasswordBox && !isSelectionNullOrEmpty;
CanCut = !IsPasswordBox && !isSelectionNullOrEmpty && !IsReadOnly;
CanPaste = !IsReadOnly;
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
// when navigating to a textbox via the tab key, select all text if
// 1) this textbox is *not* a multiline textbox
// 2) this textbox has any text to select
if (e.NavigationMethod == NavigationMethod.Tab &&
!AcceptsReturn &&
Text?.Length > 0)
{
SelectAll();
}
UpdateCommandStates();
_presenter?.ShowCaret();
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
if ((ContextFlyout == null || !ContextFlyout.IsOpen) &&
(ContextMenu == null || !ContextMenu.IsOpen))
{
ClearSelection();
RevealPassword = false;
}
UpdateCommandStates();
_presenter?.HideCaret();
}
protected override void OnTextInput(TextInputEventArgs e)
{
if (!e.Handled)
{
HandleTextInput(e.Text);
e.Handled = true;
}
}
private void HandleTextInput(string input)
{
if (IsReadOnly)
{
return;
}
input = RemoveInvalidCharacters(input);
if (string.IsNullOrEmpty(input))
{
return;
}
_selectedTextChangesMadeSinceLastUndoSnapshot++;
SnapshotUndoRedo(ignoreChangeCount: false);
string text = Text ?? string.Empty;
int caretIndex = CaretIndex;
int newLength = input.Length + text.Length - Math.Abs(SelectionStart - SelectionEnd);
if (MaxLength > 0 && newLength > MaxLength)
{
input = input.Remove(Math.Max(0, input.Length - (newLength - MaxLength)));
}
if (!string.IsNullOrEmpty(input))
{
var oldText = _text;
_ignoreTextChanges = true;
try
{
DeleteSelection(false);
caretIndex = CaretIndex;
text = Text ?? string.Empty;
SetTextInternal(text.Substring(0, caretIndex) + input + text.Substring(caretIndex));
CaretIndex += input.Length;
ClearSelection();
if (IsUndoEnabled)
{
_undoRedoHelper.DiscardRedo();
}
if (_text != oldText)
{
RaisePropertyChanged(TextProperty, oldText, _text);
}
}
finally
{
_ignoreTextChanges = false;
}
}
}
public string RemoveInvalidCharacters(string text)
{
for (var i = 0; i < invalidCharacters.Length; i++)
{
text = text.Replace(invalidCharacters[i], string.Empty);
}
return text;
}
public async void Cut()
{
var text = GetSelection();
if (string.IsNullOrEmpty(text))
{
return;
}
var eventArgs = new RoutedEventArgs(CuttingToClipboardEvent);
RaiseEvent(eventArgs);
if (!eventArgs.Handled)
{
SnapshotUndoRedo();
await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard)))
.SetTextAsync(text);
DeleteSelection();
}
}
public async void Copy()
{
var text = GetSelection();
if (string.IsNullOrEmpty(text))
{
return;
}
var eventArgs = new RoutedEventArgs(CopyingToClipboardEvent);
RaiseEvent(eventArgs);
if (!eventArgs.Handled)
{
await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard)))
.SetTextAsync(text);
}
}
public async void Paste()
{
var eventArgs = new RoutedEventArgs(PastingFromClipboardEvent);
RaiseEvent(eventArgs);
if (eventArgs.Handled)
{
return;
}
var text = await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))).GetTextAsync();
if (string.IsNullOrEmpty(text))
{
return;
}
SnapshotUndoRedo();
HandleTextInput(text);
}
protected override void OnKeyDown(KeyEventArgs e)
{
string text = Text ?? string.Empty;
int caretIndex = CaretIndex;
bool movement = false;
bool selection = false;
bool handled = false;
var modifiers = e.KeyModifiers;
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
bool Match(List<KeyGesture> gestures) => gestures.Any(g => g.Matches(e));
bool DetectSelection() => e.KeyModifiers.HasAllFlags(keymap.SelectionModifiers);
if (Match(keymap.SelectAll))
{
SelectAll();
handled = true;
}
else if (Match(keymap.Copy))
{
if (!IsPasswordBox)
{
Copy();
}
handled = true;
}
else if (Match(keymap.Cut))
{
if (!IsPasswordBox)
{
Cut();
}
handled = true;
}
else if (Match(keymap.Paste))
{
Paste();
handled = true;
}
else if (Match(keymap.Undo) && IsUndoEnabled)
{
try
{
SnapshotUndoRedo();
_isUndoingRedoing = true;
_undoRedoHelper.Undo();
}
finally
{
_isUndoingRedoing = false;
}
handled = true;
}
else if (Match(keymap.Redo) && IsUndoEnabled)
{
try
{
_isUndoingRedoing = true;
_undoRedoHelper.Redo();
}
finally
{
_isUndoingRedoing = false;
}
handled = true;
}
else if (Match(keymap.MoveCursorToTheStartOfDocument))
{
MoveHome(true);
movement = true;
selection = false;
handled = true;
}
else if (Match(keymap.MoveCursorToTheEndOfDocument))
{
MoveEnd(true);
movement = true;
selection = false;
handled = true;
}
else if (Match(keymap.MoveCursorToTheStartOfLine))
{
MoveHome(false);
movement = true;
selection = false;
handled = true;
}
else if (Match(keymap.MoveCursorToTheEndOfLine))
{
MoveEnd(false);
movement = true;
selection = false;
handled = true;
}
else if (Match(keymap.MoveCursorToTheStartOfDocumentWithSelection))
{
MoveHome(true);
movement = true;
selection = true;
handled = true;
}
else if (Match(keymap.MoveCursorToTheEndOfDocumentWithSelection))
{
MoveEnd(true);
movement = true;
selection = true;
handled = true;
}
else if (Match(keymap.MoveCursorToTheStartOfLineWithSelection))
{
MoveHome(false);
movement = true;
selection = true;
handled = true;
}
else if (Match(keymap.MoveCursorToTheEndOfLineWithSelection))
{
MoveEnd(false);
movement = true;
selection = true;
handled = true;
}
else
{
bool hasWholeWordModifiers = modifiers.HasAllFlags(keymap.WholeWordTextActionModifiers);
switch (e.Key)
{
case Key.Left:
selection = DetectSelection();
MoveHorizontal(-1, hasWholeWordModifiers, selection);
movement = true;
break;
case Key.Right:
selection = DetectSelection();
MoveHorizontal(1, hasWholeWordModifiers, selection);
movement = true;
break;
case Key.Up:
movement = MoveVertical(-1);
selection = DetectSelection();
break;
case Key.Down:
movement = MoveVertical(1);
selection = DetectSelection();
break;
case Key.Back:
SnapshotUndoRedo();
if (hasWholeWordModifiers && SelectionStart == SelectionEnd)
{
SetSelectionForControlBackspace();
}
if (!DeleteSelection() && CaretIndex > 0)
{
var removedCharacters = 1;
// handle deleting /r/n
// you don't ever want to leave a dangling /r around. So, if deleting /n, check to see if
// a /r should also be deleted.
if (CaretIndex > 1 &&
text[CaretIndex - 1] == '\n' &&
text[CaretIndex - 2] == '\r')
{
removedCharacters = 2;
}
SetTextInternal(text.Substring(0, caretIndex - removedCharacters) +
text.Substring(caretIndex));
CaretIndex -= removedCharacters;
ClearSelection();
}
handled = true;
break;
case Key.Delete:
SnapshotUndoRedo();
if (hasWholeWordModifiers && SelectionStart == SelectionEnd)
{
SetSelectionForControlDelete();
}
if (!DeleteSelection() && caretIndex < text.Length)
{
var removedCharacters = 1;
// handle deleting /r/n
// you don't ever want to leave a dangling /r around. So, if deleting /n, check to see if
// a /r should also be deleted.
if (CaretIndex < text.Length - 1 &&
text[caretIndex + 1] == '\n' &&
text[caretIndex] == '\r')
{
removedCharacters = 2;
}
SetTextInternal(text.Substring(0, caretIndex) +
text.Substring(caretIndex + removedCharacters));
}
handled = true;
break;
case Key.Enter:
if (AcceptsReturn)
{
SnapshotUndoRedo();
HandleTextInput(NewLine);
handled = true;
}
break;
case Key.Tab:
if (AcceptsTab)
{
SnapshotUndoRedo();
HandleTextInput("\t");
handled = true;
}
else
{
base.OnKeyDown(e);
}
break;
case Key.Space:
SnapshotUndoRedo(); // always snapshot in between words
break;
default:
handled = false;
break;
}
}
if (movement && selection)
{
SelectionEnd = CaretIndex;
}
else if (movement)
{
ClearSelection();
}
if (handled || movement)
{
e.Handled = true;
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
var text = Text;
var clickInfo = e.GetCurrentPoint(this);
if (text != null && clickInfo.Properties.IsLeftButtonPressed && !(clickInfo.Pointer?.Captured is Border))
{
var point = e.GetPosition(_presenter);
var index = CaretIndex = _presenter.GetCaretIndex(point);
#pragma warning disable CS0618 // Type or member is obsolete
switch (e.ClickCount)
#pragma warning restore CS0618 // Type or member is obsolete
{
case 1:
SelectionStart = SelectionEnd = index;
break;
case 2:
if (!StringUtils.IsStartOfWord(text, index))
{
SelectionStart = StringUtils.PreviousWord(text, index);
}
SelectionEnd = StringUtils.NextWord(text, index);
break;
case 3:
SelectAll();
break;
}
}
e.Pointer.Capture(_presenter);
e.Handled = true;
}
protected override void OnPointerMoved(PointerEventArgs e)
{
// selection should not change during pointer move if the user right clicks
if (_presenter != null && e.Pointer.Captured == _presenter && e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
{
var point = e.GetPosition(_presenter);
point = new Point(
MathUtilities.Clamp(point.X, 0, Math.Max(_presenter.Bounds.Width - 1, 0)),
MathUtilities.Clamp(point.Y, 0, Math.Max(_presenter.Bounds.Height - 1, 0)));
CaretIndex = SelectionEnd = _presenter.GetCaretIndex(point);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_presenter != null && e.Pointer.Captured == _presenter)
{
if (e.InitialPressMouseButton == MouseButton.Right)
{
var point = e.GetPosition(_presenter);
var caretIndex = _presenter.GetCaretIndex(point);
// see if mouse clicked inside current selection
// if it did not, we change the selection to where the user clicked
var firstSelection = Math.Min(SelectionStart, SelectionEnd);
var lastSelection = Math.Max(SelectionStart, SelectionEnd);
var didClickInSelection = SelectionStart != SelectionEnd &&
caretIndex >= firstSelection && caretIndex <= lastSelection;
if (!didClickInSelection)
{
CaretIndex = SelectionEnd = SelectionStart = caretIndex;
}
}
e.Pointer.Capture(null);
}
}
protected override void UpdateDataValidation<T>(AvaloniaProperty<T> property, BindingValue<T> value)
{
if (property == TextProperty)
{
DataValidationErrors.SetError(this, value.Error);
}
}
private int CoerceCaretIndex(int value) => CoerceCaretIndex(value, Text);
private int CoerceCaretIndex(int value, string text)
{
if (text == null)
{
return 0;
}
var length = text.Length;
if (value < 0)
{
return 0;
}
else if (value > length)
{
return length;
}
else if (value > 0 && text[value - 1] == '\r' && value < length && text[value] == '\n')
{
return value + 1;
}
else
{
return value;
}
}
public void Clear()
{
Text = string.Empty;
}
private int DeleteCharacter(int index)
{
var start = index + 1;
var text = Text;
var c = text[index];
var result = 1;
if (c == '\n' && index > 0 && text[index - 1] == '\r')
{
--index;
++result;
}
else if (c == '\r' && index < text.Length - 1 && text[index + 1] == '\n')
{
++start;
++result;
}
Text = text.Substring(0, index) + text.Substring(start);
return result;
}
private void MoveHorizontal(int direction, bool wholeWord, bool isSelecting)
{
var text = Text ?? string.Empty;
var caretIndex = CaretIndex;
if (!wholeWord)
{
if (SelectionStart != SelectionEnd && !isSelecting)
{
var start = Math.Min(SelectionStart, SelectionEnd);
var end = Math.Max(SelectionStart, SelectionEnd);
CaretIndex = direction < 0 ? start : end;
return;
}
var index = caretIndex + direction;
if (index < 0 || index > text.Length)
{
return;
}
else if (index == text.Length)
{
CaretIndex = index;
return;
}
var c = text[index];
if (direction > 0)
{
CaretIndex += (c == '\r' && index < text.Length - 1 && text[index + 1] == '\n') ? 2 : 1;
}
else
{
CaretIndex -= (c == '\n' && index > 0 && text[index - 1] == '\r') ? 2 : 1;
}
}
else
{
if (direction > 0)
{
CaretIndex += StringUtils.NextWord(text, caretIndex) - caretIndex;
}
else
{
CaretIndex += StringUtils.PreviousWord(text, caretIndex) - caretIndex;
}
}
}
private bool MoveVertical(int count)
{
if (_presenter is null)
{
return false;
}
var formattedText = _presenter.FormattedText;
var lines = formattedText.GetLines().ToList();
var caretIndex = CaretIndex;
var lineIndex = GetLine(caretIndex, lines) + count;
if (lineIndex >= 0 && lineIndex < lines.Count)
{
var line = lines[lineIndex];
var rect = formattedText.HitTestTextPosition(caretIndex);
var y = count < 0 ? rect.Y : rect.Bottom;
var point = new Point(rect.X, y + (count * (line.Height / 2)));
var hit = formattedText.HitTestPoint(point);
CaretIndex = hit.TextPosition + (hit.IsTrailing ? 1 : 0);
return true;
}
return false;
}
private void MoveHome(bool document)
{
if (_presenter is null)
{
return;
}
var text = Text ?? string.Empty;
var caretIndex = CaretIndex;
if (document)
{
caretIndex = 0;
}
else
{
var lines = _presenter.FormattedText.GetLines();
var pos = 0;
foreach (var line in lines)
{
if (pos + line.Length > caretIndex || pos + line.Length == text.Length)
{
break;
}
pos += line.Length;
}
caretIndex = pos;
}
CaretIndex = caretIndex;
}
private void MoveEnd(bool document)
{
if (_presenter is null)
{
return;
}
var text = Text ?? string.Empty;
var caretIndex = CaretIndex;
if (document)
{
caretIndex = text.Length;
}
else
{
var lines = _presenter.FormattedText.GetLines();
var pos = 0;
foreach (var line in lines)
{
pos += line.Length;
if (pos > caretIndex)
{
if (pos < text.Length)
{
--pos;
if (pos > 0 && text[pos - 1] == '\r' && text[pos] == '\n')
{
--pos;
}
}
break;
}
}
caretIndex = pos;
}
CaretIndex = caretIndex;
}
/// <summary>
/// Select all text in the TextBox
/// </summary>
public void SelectAll()
{
SelectionStart = 0;
SelectionEnd = Text?.Length ?? 0;
CaretIndex = SelectionEnd;
}
private bool DeleteSelection(bool raiseTextChanged = true)
{
if (!IsReadOnly)
{
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
if (selectionStart != selectionEnd)
{
var start = Math.Min(selectionStart, selectionEnd);
var end = Math.Max(selectionStart, selectionEnd);
var text = Text;
SetTextInternal(text.Substring(0, start) + text.Substring(end), raiseTextChanged);
CaretIndex = start;
ClearSelection();
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
private string GetSelection()
{
var text = Text;
if (string.IsNullOrEmpty(text))
return "";
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
var start = Math.Min(selectionStart, selectionEnd);
var end = Math.Max(selectionStart, selectionEnd);
if (start == end || (Text?.Length ?? 0) < end)
{
return "";
}
return text.Substring(start, end - start);
}
private int GetLine(int caretIndex, IList<FormattedTextLine> lines)
{
int pos = 0;
int i;
for (i = 0; i < lines.Count - 1; ++i)
{
var line = lines[i];
pos += line.Length;
if (pos > caretIndex)
{
break;
}
}
return i;
}
private void SetTextInternal(string value, bool raiseTextChanged = true)
{
if (raiseTextChanged)
{
try
{
_ignoreTextChanges = true;
SetAndRaise(TextProperty, ref _text, value);
}
finally
{
_ignoreTextChanges = false;
}
}
else
{
_text = value;
}
}
private void SetSelectionForControlBackspace()
{
SelectionStart = CaretIndex;
MoveHorizontal(-1, true, false);
SelectionEnd = CaretIndex;
}
private void SetSelectionForControlDelete()
{
SelectionStart = CaretIndex;
MoveHorizontal(1, true, false);
SelectionEnd = CaretIndex;
}
private void UpdatePseudoclasses()
{
PseudoClasses.Set(":empty", string.IsNullOrEmpty(Text));
}
private bool IsPasswordBox => PasswordChar != default(char);
UndoRedoState UndoRedoHelper<UndoRedoState>.IUndoRedoHost.UndoRedoState
{
get { return new UndoRedoState(Text, CaretIndex); }
set
{
Text = value.Text;
CaretIndex = value.CaretPosition;
ClearSelection();
}
}
private void SnapshotUndoRedo(bool ignoreChangeCount = true)
{
if (IsUndoEnabled)
{
if (ignoreChangeCount ||
!_hasDoneSnapshotOnce ||
(!ignoreChangeCount &&
_selectedTextChangesMadeSinceLastUndoSnapshot >= _maxCharsBeforeUndoSnapshot))
{
_undoRedoHelper.Snapshot();
_selectedTextChangesMadeSinceLastUndoSnapshot = 0;
_hasDoneSnapshotOnce = true;
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing.Dependencies;
namespace osu.Framework.Tests.Dependencies
{
[TestFixture]
public class CachedAttributeTest
{
[Test]
public void TestCacheType()
{
var provider = new Provider1();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.AreEqual(provider, dependencies.Get<Provider1>());
}
[Test]
public void TestCacheTypeAsParentType()
{
var provider = new Provider2();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.AreEqual(provider, dependencies.Get<object>());
}
[Test]
public void TestCacheTypeOverrideParentCache()
{
var provider = new Provider3();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.AreEqual(provider, dependencies.Get<Provider1>());
Assert.AreEqual(null, dependencies.Get<Provider3>());
}
[Test]
public void TestAttemptToCacheStruct()
{
var provider = new Provider4();
Assert.Throws<ArgumentException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCacheMultipleFields()
{
var provider = new Provider5();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<ProvidedType1>());
Assert.IsNotNull(dependencies.Get<ProvidedType2>());
}
[Test]
public void TestCacheFieldsOverrideBaseFields()
{
var provider = new Provider6();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.AreEqual(provider.Provided3, dependencies.Get<ProvidedType1>());
}
[Test]
public void TestCacheFieldsAsMultipleTypes()
{
var provider = new Provider7();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<object>());
Assert.IsNotNull(dependencies.Get<ProvidedType1>());
}
[Test]
public void TestCacheTypeAsMultipleTypes()
{
var provider = new Provider8();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<object>());
Assert.IsNotNull(dependencies.Get<Provider8>());
}
[Test]
public void TestAttemptToCacheBaseAsDerived()
{
var provider = new Provider9();
Assert.Throws<ArgumentException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCacheMostDerivedType()
{
var provider = new Provider10();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<ProvidedType1>());
}
[Test]
public void TestCacheClassAsInterface()
{
var provider = new Provider11();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<IProvidedInterface1>());
Assert.IsNotNull(dependencies.Get<ProvidedType1>());
}
[Test]
public void TestCacheStructAsInterface()
{
var provider = new Provider12();
Assert.Throws<ArgumentException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
/// <summary>
/// Tests caching a struct, where the providing type is within the osu.Framework assembly.
/// </summary>
[Test]
public void TestCacheStructInternal()
{
var provider = new CachedStructProvider();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.AreEqual(provider.CachedObject.Value, dependencies.GetValue<CachedStructProvider.Struct>().Value);
}
[Test]
public void TestGetValueNullInternal()
{
Assert.AreEqual(default(int), new DependencyContainer().GetValue<int>());
}
/// <summary>
/// Test caching a nullable, where the providing type is within the osu.Framework assembly.
/// </summary>
[TestCase(null)]
[TestCase(10)]
public void TestCacheNullableInternal(int? testValue)
{
var provider = new CachedNullableProvider();
provider.SetValue(testValue);
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.AreEqual(testValue, dependencies.GetValue<int?>());
}
[Test]
public void TestInvalidPublicAccessor()
{
var provider = new Provider13();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestInvalidProtectedAccessor()
{
var provider = new Provider14();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestInvalidInternalAccessor()
{
var provider = new Provider15();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestInvalidProtectedInternalAccessor()
{
var provider = new Provider16();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestValidPublicAccessor()
{
var provider = new Provider17();
Assert.DoesNotThrow(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCacheNullReferenceValue()
{
var provider = new Provider18();
Assert.Throws<NullReferenceException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCacheProperty()
{
var provider = new Provider19();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<object>());
}
[Test]
public void TestCachePropertyWithNoSetter()
{
var provider = new Provider20();
Assert.DoesNotThrow(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCachePropertyWithPublicSetter()
{
var provider = new Provider21();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCachePropertyWithNonAutoSetter()
{
var provider = new Provider22();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCachePropertyWithNoGetter()
{
var provider = new Provider23();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCacheWithNonAutoGetter()
{
var provider = new Provider24();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
private interface IProvidedInterface1
{
}
private class ProvidedType1 : IProvidedInterface1
{
}
private class ProvidedType2
{
}
private struct ProvidedType3 : IProvidedInterface1
{
}
[Cached]
private class Provider1
{
}
[Cached(Type = typeof(object))]
private class Provider2
{
}
[Cached(Type = typeof(Provider1))]
private class Provider3 : Provider1
{
}
private class Provider4
{
[Cached]
#pragma warning disable 169
private int fail;
#pragma warning restore 169
}
private class Provider5
{
[Cached]
private ProvidedType1 provided1 = new ProvidedType1();
public ProvidedType1 Provided1 => provided1;
[Cached]
private ProvidedType2 provided2 = new ProvidedType2();
}
private class Provider6 : Provider5
{
[Cached]
private ProvidedType1 provided3 = new ProvidedType1();
public ProvidedType1 Provided3 => provided3;
}
private class Provider7
{
[Cached]
[Cached(Type = typeof(object))]
private ProvidedType1 provided1 = new ProvidedType1();
}
[Cached]
[Cached(Type = typeof(object))]
private class Provider8
{
}
private class Provider9
{
[Cached(Type = typeof(ProvidedType1))]
private object provided1 = new object();
}
private class Provider10
{
[Cached]
private object provided1 = new ProvidedType1();
}
private class Provider11
{
[Cached]
[Cached(Type = typeof(IProvidedInterface1))]
private IProvidedInterface1 provided1 = new ProvidedType1();
}
private class Provider12
{
[Cached(Type = typeof(IProvidedInterface1))]
private IProvidedInterface1 provided1 = new ProvidedType3();
}
private class Provider13
{
[Cached]
public object Provided1 = new ProvidedType1();
}
private class Provider14
{
[Cached]
protected object Provided1 = new ProvidedType1();
}
private class Provider15
{
[Cached]
internal object Provided1 = new ProvidedType1();
}
private class Provider16
{
[Cached]
protected internal object Provided1 = new ProvidedType1();
}
private class Provider17
{
[Cached]
public readonly object Provided1 = new ProvidedType1();
}
private class Provider18
{
#pragma warning disable 649
[Cached]
public readonly object Provided1;
#pragma warning restore 649
}
private class Provider19
{
[Cached]
public object Provided1 { get; private set; } = new object();
}
private class Provider20
{
[Cached]
public object Provided1 { get; } = new object();
}
private class Provider21
{
[Cached]
public object Provided1 { get; set; }
}
private class Provider22
{
[Cached]
public object Provided1
{
get => null;
// ReSharper disable once ValueParameterNotUsed
set
{
}
}
}
private class Provider23
{
[Cached]
public object Provided1
{
// ReSharper disable once ValueParameterNotUsed
set
{
}
}
}
private class Provider24
{
[Cached]
public object Provided1 => null;
}
}
}
| |
using System;
using Foundation;
using UIKit;
using System.CodeDom.Compiler;
namespace MonkeyBrowse
{
public partial class FourthViewController : UIViewController
{
#region Computed Properties
/// <summary>
/// Gets a value indicating whether this <see cref="MonkeyBrowse.FirstViewController"/> user interface idiom is phone.
/// </summary>
/// <value><c>true</c> if user interface idiom is phone; otherwise, <c>false</c>.</value>
public bool UserInterfaceIdiomIsPhone {
get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; }
}
/// <summary>
/// Returns the delegate of the current running application
/// </summary>
/// <value>The this app.</value>
public AppDelegate ThisApp {
get { return (AppDelegate)UIApplication.SharedApplication.Delegate; }
}
/// <summary>
/// Gets or sets the user activity.
/// </summary>
/// <value>The user activity.</value>
public NSUserActivity UserActivity { get; set; }
#endregion
#region Constructors
public FourthViewController (IntPtr handle) : base (handle)
{
}
#endregion
#region Private Methods
/// <summary>
/// Navigates the Webview to the given URL string.
/// </summary>
/// <param name="url">URL.</param>
private void NavigateToURL(string url) {
// Properly formatted?
if (!url.StartsWith ("http://")) {
// Add web
url = "http://" + url;
}
// Display the give webpage
WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(url)));
// Invalidate existing Activity
if (UserActivity != null) {
UserActivity.Invalidate();
UserActivity = null;
}
// Create a new user Activity to support this tab
UserActivity = new NSUserActivity (ThisApp.UserActivityTab4);
UserActivity.Title = "Coffee Break Tab";
// Update the activity when the tab's URL changes
var userInfo = new NSMutableDictionary ();
userInfo.Add (new NSString ("Url"), new NSString (url));
UserActivity.AddUserInfoEntries (userInfo);
// Inform Activity that it has been updated
UserActivity.BecomeCurrent ();
// Log User Activity
Console.WriteLine ("Creating User Activity: {0} - {1}", UserActivity.Title, url);
}
/// <summary>
/// Shows the busy indicator
/// </summary>
/// <param name="reason">Reason.</param>
private void ShowBusy(string reason) {
// Display reason
BusyText.Text = reason;
//Define Animation
UIView.BeginAnimations("Show");
UIView.SetAnimationDuration(1.0f);
Handoff.Alpha = 0.5f;
//Execute Animation
UIView.CommitAnimations();
}
/// <summary>
/// Hides the busy.
/// </summary>
private void HideBusy() {
//Define Animation
UIView.BeginAnimations("Hide");
UIView.SetAnimationDuration(1.0f);
Handoff.Alpha = 0f;
//Execute Animation
UIView.CommitAnimations();
}
#endregion
#region Public Methods
public void PreparingToHandoff() {
// Inform caller
ShowBusy ("Continuing Activity...");
}
public void PerformHandoff(NSUserActivity activity) {
// Hide busy indicator
HideBusy ();
// Extract URL from dictionary
var url = activity.UserInfo ["Url"].ToString ();
// Display value
URL.Text = url;
// Display the give webpage
WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(url)));
// Save activity
UserActivity = activity;
UserActivity.BecomeCurrent ();
}
#endregion
#region Override Methods
/// <summary>
/// Views the did load.
/// </summary>
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Hide Handoff notification
Handoff.Alpha = 0f;
// Attach to the App Delegate
ThisApp.Tab4 = this;
// Wireup Webview notifications
WebView.LoadStarted += (sender, e) => {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
ShowBusy(string .Format("Loading {0}...",URL.Text));
};
WebView.LoadFinished += (sender, e) => {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
HideBusy();
};
// Configure URL entry field
URL.Placeholder = "(enter url)";
// Wire-up URL field
URL.ShouldReturn = delegate (UITextField field){
field.ResignFirstResponder ();
NavigateToURL(field.Text);
return true;
};
// Wire-up the Go Button
GoButton.Clicked += (sender, e) => {
NavigateToURL(URL.Text);
};
}
/// <summary>
/// Restores the state of the user activity.
/// </summary>
/// <param name="activity">Activity.</param>
public override void RestoreUserActivityState (NSUserActivity activity)
{
base.RestoreUserActivityState (activity);
// Log activity
Console.WriteLine ("Restoring Activity {0}", activity.Title);
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
}
public override void ViewWillDisappear (bool animated)
{
base.ViewWillDisappear (animated);
}
public override void ViewDidDisappear (bool animated)
{
base.ViewDidDisappear (animated);
}
#endregion
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Security.Cert.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Javax.Security.Cert
{
/// <summary>
/// <para>The exception that is thrown when an error occurs while a <c> Certificate </c> is being encoded. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateEncodingException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateEncodingException", AccessFlags = 33)]
public partial class CertificateEncodingException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateEncodingException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateEncodingException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateEncodingException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateEncodingException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>The base class for all <c> Certificate </c> related exceptions. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateException", AccessFlags = 33)]
public partial class CertificateException : global::System.Exception
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>The exception that is thrown when a <c> Certificate </c> has expired. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateExpiredException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateExpiredException", AccessFlags = 33)]
public partial class CertificateExpiredException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateExpiredException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateExpiredException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateExpiredException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateExpiredException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Abstract base class for X.509 certificates. </para><para>This represents a standard way for accessing the attributes of X.509 v1 certificates. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/X509Certificate
/// </java-name>
[Dot42.DexImport("javax/security/cert/X509Certificate", AccessFlags = 1057)]
public abstract partial class X509Certificate : global::Javax.Security.Cert.Certificate
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public X509Certificate() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para>
/// </summary>
/// <returns>
/// <para>the certificate initialized from the specified input stream </para>
/// </returns>
/// <java-name>
/// getInstance
/// </java-name>
[Dot42.DexImport("getInstance", "(Ljava/io/InputStream;)Ljavax/security/cert/X509Certificate;", AccessFlags = 25)]
public static global::Javax.Security.Cert.X509Certificate GetInstance(global::Java.Io.InputStream inStream) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Cert.X509Certificate);
}
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para>
/// </summary>
/// <returns>
/// <para>the certificate initialized from the specified input stream </para>
/// </returns>
/// <java-name>
/// getInstance
/// </java-name>
[Dot42.DexImport("getInstance", "([B)Ljavax/security/cert/X509Certificate;", AccessFlags = 25)]
public static global::Javax.Security.Cert.X509Certificate GetInstance(sbyte[] inStream) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Cert.X509Certificate);
}
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para>
/// </summary>
/// <returns>
/// <para>the certificate initialized from the specified input stream </para>
/// </returns>
/// <java-name>
/// getInstance
/// </java-name>
[Dot42.DexImport("getInstance", "([B)Ljavax/security/cert/X509Certificate;", AccessFlags = 25, IgnoreFromJava = true)]
public static global::Javax.Security.Cert.X509Certificate GetInstance(byte[] inStream) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Cert.X509Certificate);
}
/// <summary>
/// <para>Checks whether the certificate is currently valid. </para><para>The validity defined in ASN.1:</para><para><pre>
/// validity Validity
///
/// Validity ::= SEQUENCE {
/// notBefore CertificateValidityDate,
/// notAfter CertificateValidityDate }
///
/// CertificateValidityDate ::= CHOICE {
/// utcTime UTCTime,
/// generalTime GeneralizedTime }
/// </pre></para><para></para>
/// </summary>
/// <java-name>
/// checkValidity
/// </java-name>
[Dot42.DexImport("checkValidity", "()V", AccessFlags = 1025)]
public abstract void CheckValidity() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks whether the certificate is valid at the specified date.</para><para><para>checkValidity() </para></para>
/// </summary>
/// <java-name>
/// checkValidity
/// </java-name>
[Dot42.DexImport("checkValidity", "(Ljava/util/Date;)V", AccessFlags = 1025)]
public abstract void CheckValidity(global::Java.Util.Date date) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the certificates <c> version </c> (version number). </para><para>The version defined is ASN.1:</para><para><pre>
/// Version ::= INTEGER { v1(0), v2(1), v3(2) }
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the version number. </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
public abstract int GetVersion() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> serialNumber </c> of the certificate. </para><para>The ASN.1 definition of <c> serialNumber </c> :</para><para><pre>
/// CertificateSerialNumber ::= INTEGER
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the serial number. </para>
/// </returns>
/// <java-name>
/// getSerialNumber
/// </java-name>
[Dot42.DexImport("getSerialNumber", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
public abstract global::Java.Math.BigInteger GetSerialNumber() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> issuer </c> (issuer distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> issuer </c> :</para><para><pre>
/// issuer Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> issuer </c> as an implementation specific <c> Principal </c> . </para>
/// </returns>
/// <java-name>
/// getIssuerDN
/// </java-name>
[Dot42.DexImport("getIssuerDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
public abstract global::Java.Security.IPrincipal GetIssuerDN() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> subject </c> (subject distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> subject </c> :</para><para><pre>
/// subject Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> subject </c> (subject distinguished name). </para>
/// </returns>
/// <java-name>
/// getSubjectDN
/// </java-name>
[Dot42.DexImport("getSubjectDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
public abstract global::Java.Security.IPrincipal GetSubjectDN() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> notBefore </c> date from the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the start of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotBefore
/// </java-name>
[Dot42.DexImport("getNotBefore", "()Ljava/util/Date;", AccessFlags = 1025)]
public abstract global::Java.Util.Date GetNotBefore() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> notAfter </c> date of the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the end of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotAfter
/// </java-name>
[Dot42.DexImport("getNotAfter", "()Ljava/util/Date;", AccessFlags = 1025)]
public abstract global::Java.Util.Date GetNotAfter() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the name of the algorithm for the certificate signature.</para><para></para>
/// </summary>
/// <returns>
/// <para>the signature algorithm name. </para>
/// </returns>
/// <java-name>
/// getSigAlgName
/// </java-name>
[Dot42.DexImport("getSigAlgName", "()Ljava/lang/String;", AccessFlags = 1025)]
public abstract string GetSigAlgName() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the OID of the signature algorithm from the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the OID of the signature algorithm. </para>
/// </returns>
/// <java-name>
/// getSigAlgOID
/// </java-name>
[Dot42.DexImport("getSigAlgOID", "()Ljava/lang/String;", AccessFlags = 1025)]
public abstract string GetSigAlgOID() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters of the signature algorithm, or null if none are used. </para>
/// </returns>
/// <java-name>
/// getSigAlgParams
/// </java-name>
[Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025)]
public abstract sbyte[] JavaGetSigAlgParams() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters of the signature algorithm, or null if none are used. </para>
/// </returns>
/// <java-name>
/// getSigAlgParams
/// </java-name>
[Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
public abstract byte[] GetSigAlgParams() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the certificates <c> version </c> (version number). </para><para>The version defined is ASN.1:</para><para><pre>
/// Version ::= INTEGER { v1(0), v2(1), v3(2) }
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the version number. </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
public int Version
{
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
get{ return GetVersion(); }
}
/// <summary>
/// <para>Returns the <c> serialNumber </c> of the certificate. </para><para>The ASN.1 definition of <c> serialNumber </c> :</para><para><pre>
/// CertificateSerialNumber ::= INTEGER
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the serial number. </para>
/// </returns>
/// <java-name>
/// getSerialNumber
/// </java-name>
public global::Java.Math.BigInteger SerialNumber
{
[Dot42.DexImport("getSerialNumber", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
get{ return GetSerialNumber(); }
}
/// <summary>
/// <para>Returns the <c> issuer </c> (issuer distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> issuer </c> :</para><para><pre>
/// issuer Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> issuer </c> as an implementation specific <c> Principal </c> . </para>
/// </returns>
/// <java-name>
/// getIssuerDN
/// </java-name>
public global::Java.Security.IPrincipal IssuerDN
{
[Dot42.DexImport("getIssuerDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
get{ return GetIssuerDN(); }
}
/// <summary>
/// <para>Returns the <c> subject </c> (subject distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> subject </c> :</para><para><pre>
/// subject Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> subject </c> (subject distinguished name). </para>
/// </returns>
/// <java-name>
/// getSubjectDN
/// </java-name>
public global::Java.Security.IPrincipal SubjectDN
{
[Dot42.DexImport("getSubjectDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
get{ return GetSubjectDN(); }
}
/// <summary>
/// <para>Returns the <c> notBefore </c> date from the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the start of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotBefore
/// </java-name>
public global::Java.Util.Date NotBefore
{
[Dot42.DexImport("getNotBefore", "()Ljava/util/Date;", AccessFlags = 1025)]
get{ return GetNotBefore(); }
}
/// <summary>
/// <para>Returns the <c> notAfter </c> date of the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the end of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotAfter
/// </java-name>
public global::Java.Util.Date NotAfter
{
[Dot42.DexImport("getNotAfter", "()Ljava/util/Date;", AccessFlags = 1025)]
get{ return GetNotAfter(); }
}
/// <summary>
/// <para>Returns the name of the algorithm for the certificate signature.</para><para></para>
/// </summary>
/// <returns>
/// <para>the signature algorithm name. </para>
/// </returns>
/// <java-name>
/// getSigAlgName
/// </java-name>
public string SigAlgName
{
[Dot42.DexImport("getSigAlgName", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetSigAlgName(); }
}
/// <summary>
/// <para>Returns the OID of the signature algorithm from the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the OID of the signature algorithm. </para>
/// </returns>
/// <java-name>
/// getSigAlgOID
/// </java-name>
public string SigAlgOID
{
[Dot42.DexImport("getSigAlgOID", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetSigAlgOID(); }
}
/// <summary>
/// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters of the signature algorithm, or null if none are used. </para>
/// </returns>
/// <java-name>
/// getSigAlgParams
/// </java-name>
public byte[] SigAlgParams
{
[Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
get{ return GetSigAlgParams(); }
}
}
/// <summary>
/// <para>The exception that is thrown when a <c> Certificate </c> is not yet valid. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateNotYetValidException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateNotYetValidException", AccessFlags = 33)]
public partial class CertificateNotYetValidException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateNotYetValidException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateNotYetValidException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateNotYetValidException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateNotYetValidException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>The exception that is thrown when a <c> Certificate </c> can not be parsed. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateParsingException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateParsingException", AccessFlags = 33)]
public partial class CertificateParsingException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateParsingException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateParsingException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateParsingException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateParsingException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Abstract class to represent identity certificates. It represents a way to verify the binding of a Principal and its public key. Examples are X.509, PGP, and SDSI. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/Certificate
/// </java-name>
[Dot42.DexImport("javax/security/cert/Certificate", AccessFlags = 1057)]
public abstract partial class Certificate
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> Certificate </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public Certificate() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Compares the argument to this Certificate. If both have the same bytes they are assumed to be equal.</para><para><para>hashCode </para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if <c> obj </c> is the same as this <c> Certificate </c> , <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object obj) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns an integer hash code for the receiver. Any two objects which return <code>true</code> when passed to <code>equals</code> must answer the same value for this method.</para><para><para>equals </para></para>
/// </summary>
/// <returns>
/// <para>the receiver's hash </para>
/// </returns>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns the encoded representation for this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the encoded representation for this certificate. </para>
/// </returns>
/// <java-name>
/// getEncoded
/// </java-name>
[Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025)]
public abstract sbyte[] JavaGetEncoded() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the encoded representation for this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the encoded representation for this certificate. </para>
/// </returns>
/// <java-name>
/// getEncoded
/// </java-name>
[Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
public abstract byte[] GetEncoded() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Verifies that this certificate was signed with the given public key.</para><para></para>
/// </summary>
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/security/PublicKey;)V", AccessFlags = 1025)]
public abstract void Verify(global::Java.Security.IPublicKey key) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Verifies that this certificate was signed with the given public key. Uses the signature algorithm given by the provider.</para><para></para>
/// </summary>
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/security/PublicKey;Ljava/lang/String;)V", AccessFlags = 1025)]
public abstract void Verify(global::Java.Security.IPublicKey key, string sigProvider) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a string containing a concise, human-readable description of the receiver.</para><para></para>
/// </summary>
/// <returns>
/// <para>a printable representation for the receiver. </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1025)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the public key corresponding to this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the public key corresponding to this certificate. </para>
/// </returns>
/// <java-name>
/// getPublicKey
/// </java-name>
[Dot42.DexImport("getPublicKey", "()Ljava/security/PublicKey;", AccessFlags = 1025)]
public abstract global::Java.Security.IPublicKey GetPublicKey() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the encoded representation for this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the encoded representation for this certificate. </para>
/// </returns>
/// <java-name>
/// getEncoded
/// </java-name>
public byte[] Encoded
{
[Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
get{ return GetEncoded(); }
}
/// <summary>
/// <para>Returns the public key corresponding to this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the public key corresponding to this certificate. </para>
/// </returns>
/// <java-name>
/// getPublicKey
/// </java-name>
public global::Java.Security.IPublicKey PublicKey
{
[Dot42.DexImport("getPublicKey", "()Ljava/security/PublicKey;", AccessFlags = 1025)]
get{ return GetPublicKey(); }
}
}
}
| |
#if UNITY_EDITOR
#define NF_CLIENT_FRAME
#elif UNITY_IPHONE
#define NF_CLIENT_FRAME
#elif UNITY_ANDROID
#define NF_CLIENT_FRAME
#elif UNITY_STANDALONE_OSX
#define NF_CLIENT_FRAME
#elif UNITY_STANDALONE_WIN
#define NF_CLIENT_FRAME
#endif
//-----------------------------------------------------------------------
// <copyright file="NFCElementModule.cs">
// Copyright (C) 2015-2015 lvsheng.huang <https://github.com/ketoo/NFrame>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Collections;
using System.IO;
namespace NFrame
{
public class NFCElementModule : NFIElementModule
{
public NFCElementModule()
{
mhtObject = new Dictionary<string, NFIElement>();
}
public override void Init()
{
#if NF_CLIENT_FRAME
mxLogicClassModule = NFCKernelModule.Instance.GetLogicClassModule();
#else
mxLogicClassModule = GetMng().GetModule<NFILogicClassModule>();
mstrRootPath = GetMng().GetClassPath();
#endif
}
public override void AfterInit()
{
Load();
}
public override void BeforeShut()
{
}
public override void Shut()
{
}
public override void Execute()
{
}
public override bool Load()
{
ClearInstanceElement();
Dictionary<string, NFILogicClass> xTable = mxLogicClassModule.GetElementList();
foreach (KeyValuePair<string, NFILogicClass> kv in xTable)
{
LoadInstanceElement(kv.Value);
}
return false;
}
public override bool Clear()
{
return false;
}
public override bool ExistElement(string strConfigName)
{
if (mhtObject.ContainsKey(strConfigName))
{
return true;
}
return false;
}
public override Int64 QueryPropertyInt(string strConfigName, string strPropertyName)
{
NFIElement xElement = GetElement(strConfigName);
if (null != xElement)
{
return xElement.QueryInt(strPropertyName);
}
return 0;
}
public override float QueryPropertyFloat(string strConfigName, string strPropertyName)
{
NFIElement xElement = GetElement(strConfigName);
if (null != xElement)
{
return xElement.QueryFloat(strPropertyName);
}
return 0;
}
public override double QueryPropertyDouble(string strConfigName, string strPropertyName)
{
NFIElement xElement = GetElement(strConfigName);
if (null != xElement)
{
xElement.QueryDouble(strPropertyName);
}
return 0;
}
public override string QueryPropertyString(string strConfigName, string strPropertyName)
{
NFIElement xElement = GetElement(strConfigName);
if (null != xElement)
{
return xElement.QueryString(strPropertyName);
}
return NFIDataList.NULL_STRING;
}
public override bool AddElement(string strName, NFIElement xElement)
{
if (!mhtObject.ContainsKey(strName))
{
mhtObject.Add(strName, xElement);
return true;
}
return false;
}
public override NFIElement GetElement(string strConfigName)
{
if (mhtObject.ContainsKey(strConfigName))
{
return (NFIElement)mhtObject[strConfigName];
}
return null;
}
private void ClearInstanceElement()
{
mhtObject.Clear();
}
private void LoadInstanceElement(NFILogicClass xLogicClass)
{
string strLogicPath = mstrRootPath;
strLogicPath += xLogicClass.GetInstance();
XmlDocument xmldoc = new XmlDocument();
//xmldoc.Load(strLogicPath);
///////////////////////////////////////////////////////////////////////////////////////
StreamReader cepherReader = new StreamReader(strLogicPath); ;
string strContent = cepherReader.ReadToEnd();
cepherReader.Close();
byte[] data = Convert.FromBase64String(strContent);
// MemoryStream stream = new MemoryStream(data);
// XmlReader x = XmlReader.Create(stream);
// x.MoveToContent();
// string res = x.ReadOuterXml();
string res = System.Text.ASCIIEncoding.Default.GetString(data);
xmldoc.LoadXml(res);
/////////////////////////////////////////////////////////////////
XmlNode xRoot = xmldoc.SelectSingleNode("XML");
XmlNodeList xNodeList = xRoot.SelectNodes("Object");
for (int i = 0; i < xNodeList.Count; ++i)
{
//NFCLog.Instance.Log("Class:" + xLogicClass.GetName());
XmlNode xNodeClass = xNodeList.Item(i);
XmlAttribute strID = xNodeClass.Attributes["ID"];
//NFCLog.Instance.Log("ClassID:" + strID.Value);
NFIElement xElement = GetElement(strID.Value);
if (null == xElement)
{
xElement = new NFCElement();
AddElement(strID.Value, xElement);
xLogicClass.AddConfigName(strID.Value);
XmlAttributeCollection xCollection = xNodeClass.Attributes;
for (int j = 0; j < xCollection.Count; ++j)
{
XmlAttribute xAttribute = xCollection[j];
NFIProperty xProperty = xLogicClass.GetPropertyManager().GetProperty(xAttribute.Name);
if (null != xProperty)
{
NFIDataList.VARIANT_TYPE eType = xProperty.GetType();
switch (eType)
{
case NFIDataList.VARIANT_TYPE.VTYPE_INT:
{
NFIDataList xValue = new NFCDataList();
xValue.AddInt(int.Parse(xAttribute.Value));
xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_FLOAT:
{
NFIDataList xValue = new NFCDataList();
xValue.AddFloat(float.Parse(xAttribute.Value));
xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_DOUBLE:
{
NFIDataList xValue = new NFCDataList();
xValue.AddDouble(double.Parse(xAttribute.Value));
xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_STRING:
{
NFIDataList xValue = new NFCDataList();
xValue.AddString(xAttribute.Value);
NFIProperty xTestProperty = xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_OBJECT:
{
NFIDataList xValue = new NFCDataList();
xValue.AddObject(new NFGUID(0, int.Parse(xAttribute.Value)));
xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue);
}
break;
default:
break;
}
}
}
}
}
}
/////////////////////////////////////////
private NFILogicClassModule mxLogicClassModule;
/////////////////////////////////////////
private Dictionary<string, NFIElement> mhtObject;
private string mstrRootPath;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
**
** Purpose: Class to represent all synchronization objects in the runtime (that allow multiple wait)
**
**
=============================================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using Internal.Runtime.Augments;
using Microsoft.Win32.SafeHandles;
namespace System.Threading
{
public abstract partial class WaitHandle : MarshalByRefObject, IDisposable
{
internal const int WaitObject0 = (int)Interop.Constants.WaitObject0;
public const int WaitTimeout = (int)Interop.Constants.WaitTimeout;
internal const int WaitAbandoned = (int)Interop.Constants.WaitAbandoned0;
internal const int WaitFailed = unchecked((int)Interop.Constants.WaitFailed);
internal const int MaxWaitHandles = 64;
protected static readonly IntPtr InvalidHandle = Interop.InvalidHandleValue;
internal SafeWaitHandle _waitHandle;
internal enum OpenExistingResult
{
Success,
NameNotFound,
PathNotFound,
NameInvalid
}
protected WaitHandle()
{
}
[Obsolete("Use the SafeWaitHandle property instead.")]
public virtual IntPtr Handle
{
get
{
return _waitHandle == null ? InvalidHandle : _waitHandle.DangerousGetHandle();
}
set
{
if (value == InvalidHandle)
{
// This line leaks a handle. However, it's currently
// not perfectly clear what the right behavior is here
// anyways. This preserves Everett behavior. We should
// ideally do these things:
// *) Expose a settable SafeHandle property on WaitHandle.
// *) Expose a settable OwnsHandle property on SafeHandle.
if (_waitHandle != null)
{
_waitHandle.SetHandleAsInvalid();
_waitHandle = null;
}
}
else
{
_waitHandle = new SafeWaitHandle(value, true);
}
}
}
public SafeWaitHandle SafeWaitHandle
{
get
{
if (_waitHandle == null)
{
_waitHandle = new SafeWaitHandle(InvalidHandle, false);
}
return _waitHandle;
}
set
{ _waitHandle = value; }
}
internal static int ToTimeoutMilliseconds(TimeSpan timeout)
{
var timeoutMilliseconds = (long)timeout.TotalMilliseconds;
if (timeoutMilliseconds < -1 || timeoutMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
return (int)timeoutMilliseconds;
}
public virtual bool WaitOne(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
return WaitOneCore(millisecondsTimeout);
}
private bool WaitOneCore(int millisecondsTimeout, bool interruptible = true)
{
Debug.Assert(millisecondsTimeout >= -1);
// The field value is modifiable via the public <see cref="WaitHandle.SafeWaitHandle"/> property, save it locally
// to ensure that one instance is used in all places in this method
SafeWaitHandle waitHandle = _waitHandle;
if (waitHandle == null)
{
// Throw ObjectDisposedException for backward compatibility even though it is not be representative of the issue
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
}
waitHandle.DangerousAddRef();
try
{
return WaitOneCore(waitHandle.DangerousGetHandle(), millisecondsTimeout, interruptible);
}
finally
{
waitHandle.DangerousRelease();
}
}
public virtual bool WaitOne(TimeSpan timeout) => WaitOneCore(ToTimeoutMilliseconds(timeout));
public virtual bool WaitOne() => WaitOneCore(Timeout.Infinite);
public virtual bool WaitOne(int millisecondsTimeout, bool exitContext) => WaitOne(millisecondsTimeout);
public virtual bool WaitOne(TimeSpan timeout, bool exitContext) => WaitOne(timeout);
internal bool WaitOne(bool interruptible) => WaitOneCore(Timeout.Infinite, interruptible);
/// <summary>
/// Obtains all of the corresponding safe wait handles and adds a ref to each. Since the <see cref="SafeWaitHandle"/>
/// property is publically modifiable, this makes sure that we add and release refs one the same set of safe wait
/// handles to keep them alive during a multi-wait operation.
/// </summary>
private static SafeWaitHandle[] ObtainSafeWaitHandles(
RuntimeThread currentThread,
WaitHandle[] waitHandles,
int numWaitHandles,
out SafeWaitHandle[] rentedSafeWaitHandles)
{
Debug.Assert(currentThread == RuntimeThread.CurrentThread);
Debug.Assert(waitHandles != null);
Debug.Assert(numWaitHandles > 0);
Debug.Assert(numWaitHandles <= MaxWaitHandles);
Debug.Assert(numWaitHandles <= waitHandles.Length);
rentedSafeWaitHandles = currentThread.RentWaitedSafeWaitHandleArray(numWaitHandles);
SafeWaitHandle[] safeWaitHandles = rentedSafeWaitHandles ?? new SafeWaitHandle[numWaitHandles];
bool success = false;
try
{
for (int i = 0; i < numWaitHandles; ++i)
{
WaitHandle waitHandle = waitHandles[i];
if (waitHandle == null)
{
throw new ArgumentNullException("waitHandles[" + i + ']', SR.ArgumentNull_ArrayElement);
}
SafeWaitHandle safeWaitHandle = waitHandle._waitHandle;
if (safeWaitHandle == null)
{
// Throw ObjectDisposedException for backward compatibility even though it is not be representative of the issue
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
}
safeWaitHandle.DangerousAddRef();
safeWaitHandles[i] = safeWaitHandle;
}
success = true;
}
finally
{
if (!success)
{
for (int i = 0; i < numWaitHandles; ++i)
{
SafeWaitHandle safeWaitHandle = safeWaitHandles[i];
if (safeWaitHandle == null)
{
break;
}
safeWaitHandle.DangerousRelease();
safeWaitHandles[i] = null;
}
if (rentedSafeWaitHandles != null)
{
currentThread.ReturnWaitedSafeWaitHandleArray(rentedSafeWaitHandles);
}
}
}
return safeWaitHandles;
}
public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout)
{
if (waitHandles == null)
{
throw new ArgumentNullException(nameof(waitHandles), SR.ArgumentNull_Waithandles);
}
if (waitHandles.Length == 0)
{
//
// Some history: in CLR 1.0 and 1.1, we threw ArgumentException in this case, which was correct.
// Somehow, in 2.0, this became ArgumentNullException. This was not fixed until Silverlight 2,
// which went back to ArgumentException.
//
// Now we're in a bit of a bind. Backward-compatibility requires us to keep throwing ArgumentException
// in CoreCLR, and ArgumentNullException in the desktop CLR. This is ugly, but so is breaking
// user code.
//
throw new ArgumentNullException(nameof(waitHandles), SR.Argument_EmptyWaithandleArray);
}
if (waitHandles.Length > MaxWaitHandles)
{
throw new NotSupportedException(SR.NotSupported_MaxWaitHandles);
}
if (-1 > millisecondsTimeout)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
RuntimeThread currentThread = RuntimeThread.CurrentThread;
SafeWaitHandle[] rentedSafeWaitHandles;
SafeWaitHandle[] safeWaitHandles = ObtainSafeWaitHandles(currentThread, waitHandles, waitHandles.Length, out rentedSafeWaitHandles);
try
{
return WaitAllCore(currentThread, safeWaitHandles, waitHandles, millisecondsTimeout);
}
finally
{
for (int i = 0; i < waitHandles.Length; ++i)
{
safeWaitHandles[i].DangerousRelease();
safeWaitHandles[i] = null;
}
if (rentedSafeWaitHandles != null)
{
currentThread.ReturnWaitedSafeWaitHandleArray(rentedSafeWaitHandles);
}
}
}
public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout) =>
WaitAll(waitHandles, ToTimeoutMilliseconds(timeout));
public static bool WaitAll(WaitHandle[] waitHandles) => WaitAll(waitHandles, Timeout.Infinite);
public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) =>
WaitAll(waitHandles, millisecondsTimeout);
public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) =>
WaitAll(waitHandles, timeout);
/*========================================================================
** Waits for notification from any of the objects.
** timeout indicates how long to wait before the method returns.
** This method will return either when either one of the object have been
** signalled or timeout milliseonds have elapsed.
========================================================================*/
public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout) => WaitAny(waitHandles, waitHandles?.Length ?? 0, millisecondsTimeout);
internal static int WaitAny(WaitHandle[] waitHandles, int numWaitHandles, int millisecondsTimeout)
{
if (waitHandles == null)
{
throw new ArgumentNullException(nameof(waitHandles), SR.ArgumentNull_Waithandles);
}
if (waitHandles.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyWaithandleArray);
}
if (MaxWaitHandles < waitHandles.Length)
{
throw new NotSupportedException(SR.NotSupported_MaxWaitHandles);
}
if (-1 > millisecondsTimeout)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
RuntimeThread currentThread = RuntimeThread.CurrentThread;
SafeWaitHandle[] rentedSafeWaitHandles;
SafeWaitHandle[] safeWaitHandles = ObtainSafeWaitHandles(currentThread, waitHandles, numWaitHandles, out rentedSafeWaitHandles);
try
{
return WaitAnyCore(currentThread, safeWaitHandles, waitHandles, numWaitHandles, millisecondsTimeout);
}
finally
{
for (int i = 0; i < numWaitHandles; ++i)
{
safeWaitHandles[i].DangerousRelease();
safeWaitHandles[i] = null;
}
if (rentedSafeWaitHandles != null)
{
currentThread.ReturnWaitedSafeWaitHandleArray(rentedSafeWaitHandles);
}
}
}
public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout) =>
WaitAny(waitHandles, ToTimeoutMilliseconds(timeout));
public static int WaitAny(WaitHandle[] waitHandles) => WaitAny(waitHandles, Timeout.Infinite);
public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) =>
WaitAny(waitHandles, millisecondsTimeout);
public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) =>
WaitAny(waitHandles, timeout);
/*=================================================
==
== SignalAndWait
==
==================================================*/
private static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout)
{
if (null == toSignal)
{
throw new ArgumentNullException(nameof(toSignal));
}
if (null == toWaitOn)
{
throw new ArgumentNullException(nameof(toWaitOn));
}
if (-1 > millisecondsTimeout)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
// The field value is modifiable via the public <see cref="WaitHandle.SafeWaitHandle"/> property, save it locally
// to ensure that one instance is used in all places in this method
SafeWaitHandle safeWaitHandleToSignal = toSignal._waitHandle;
SafeWaitHandle safeWaitHandleToWaitOn = toWaitOn._waitHandle;
if (safeWaitHandleToSignal == null || safeWaitHandleToWaitOn == null)
{
// Throw ObjectDisposedException for backward compatibility even though it is not be representative of the issue
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
}
Contract.EndContractBlock();
safeWaitHandleToSignal.DangerousAddRef();
try
{
safeWaitHandleToWaitOn.DangerousAddRef();
try
{
return
SignalAndWaitCore(
safeWaitHandleToSignal.DangerousGetHandle(),
safeWaitHandleToWaitOn.DangerousGetHandle(),
millisecondsTimeout);
}
finally
{
safeWaitHandleToWaitOn.DangerousRelease();
}
}
finally
{
safeWaitHandleToSignal.DangerousRelease();
}
}
public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn) =>
SignalAndWait(toSignal, toWaitOn, Timeout.Infinite);
public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, TimeSpan timeout, bool exitContext) =>
SignalAndWait(toSignal, toWaitOn, ToTimeoutMilliseconds(timeout));
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")]
public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext) =>
SignalAndWait(toSignal, toWaitOn, millisecondsTimeout);
public virtual void Close() => Dispose();
protected virtual void Dispose(bool explicitDisposing)
{
if (_waitHandle != null)
{
_waitHandle.Close();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
internal static void ThrowInvalidHandleException()
{
var ex = new InvalidOperationException(SR.InvalidOperation_InvalidHandle);
ex.SetErrorCode(__HResults.ERROR_INVALID_HANDLE);
throw ex;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
namespace BotSuite.ImageLibrary
{
/// <summary>
/// serach for patterns or images in a image
/// </summary>
public static class Template
{
/// <summary>
/// Searches for a binary pattern
/// </summary>
/// <param name="img">The image to look in</param>
/// <param name="pattern">The pattern to look for</param>
/// <param name="tolerance">Tolerance (0,...,255)</param>
/// <example>
/// <code>
/// <![CDATA[
/// ImageData img = new ImageData(...);
/// int[,] pattern = new int[,] {
/// {1,1,0,0,0,0,0,0},
/// {0,0,1,0,0,0,0,0},
/// {0,0,1,0,0,0,0,0},
/// {0,1,0,0,0,0,0,0},
/// {1,0,0,0,0,0,0,0},
/// {1,1,1,0,0,0,0,0},
/// {0,0,0,0,0,0,0,0},
/// {0,0,0,0,0,0,0,0}
/// };
/// Rectangle location = Template.BinaryPattern(img, pattern, 2);
/// ]]>
/// </code>
/// </example>
/// <returns></returns>
public static Rectangle BinaryPattern(ImageData img, int[,] pattern, uint tolerance = 0)
{
Point location = Point.Empty;
Color referenceColor = Color.Empty;
for (int imageColumn = 0; imageColumn < img.Width - pattern.GetLength(1); imageColumn++)
{
for (int imageRow = 0; imageRow < img.Height - pattern.GetLength(0); imageRow++)
{
bool patternMatch = true;
for (int patternColumn = 0; patternColumn < pattern.GetLength(1); patternColumn++)
{
if (!patternMatch) break;
for (int patternRow = 0; patternRow < pattern.GetLength(0); patternRow++)
{
if (!patternMatch) break;
if (pattern[patternRow, patternColumn] == 1)
{
if (referenceColor == Color.Empty)
{
referenceColor = img[imageColumn, imageRow];
}
else
{
if (!CommonFunctions.ColorsSimilar(referenceColor,
img[imageColumn + patternColumn, imageRow + patternRow], tolerance))
{
patternMatch = false;
referenceColor = Color.Empty;
break;
}
}
}
else
{
if (referenceColor != Color.Empty)
{
if (CommonFunctions.ColorsSimilar(referenceColor,
img[imageColumn + patternColumn, imageRow + patternRow], tolerance))
{
patternMatch = false;
referenceColor = Color.Empty;
}
}
}
}
}
if (patternMatch)
{
location.X = imageColumn;
location.Y = imageRow;
return new Rectangle(location.X, location.Y, pattern.GetLength(1), pattern.GetLength(0));
}
}
}
return Rectangle.Empty;
}
/// <summary>
/// Converts an Integer MultiArray to a Boolean MultiArray
/// </summary>
/// <param name="input">The input Integer MultiArray</param>
/// <returns>The Boolean MultiArray</returns>
public static bool[,] ToMultiArrayBool(this int[,] input)
{
int columnCount = input.GetUpperBound(0);
int rowCount = input.GetLength(0);
var result = new bool[rowCount, columnCount];
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < columnCount; j++)
{
result[i, j] = input[i, j] == 1;
}
}
return result;
}
/// <summary>
/// Searches for an image in another image
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// ImageData Img = new ImageData(...);
/// ImageData Search= new ImageData(...);
/// // search with tolerance 25
/// Rectangle Position = Template.Image(Img,Search,25);
/// ]]>
/// </code>
/// </example>
/// <param name="img">Image to look in</param>
/// <param name="Ref">Image to look for</param>
/// <param name="tolerance">Tolerance of similarity (0,...,255)</param>
/// <returns>The best matching position as a rectangle</returns>
public static Rectangle Image(ImageData img, ImageData Ref, uint tolerance = 0)
{
Double bestScore = (Math.Abs(Byte.MaxValue - Byte.MinValue)*3);
Point location = Point.Empty;
Boolean found = false;
for (int originalX = 0; originalX < img.Width - Ref.Width; originalX++)
{
for (int originalY = 0; originalY < img.Height - Ref.Height; originalY++)
{
Color currentInnerPictureColor = Ref[0, 0];
Color currentOuterPictureColor = img[originalX, originalY];
if (CommonFunctions.ColorsSimilar(currentInnerPictureColor, currentOuterPictureColor, tolerance))
{
Int32 currentScore = 0;
Boolean allSimilar = true;
for (int referenceX = 0; referenceX < Ref.Width; referenceX++)
{
if (!allSimilar) break;
for (Int32 referenceY = 0; referenceY < Ref.Height; referenceY++)
{
if (!allSimilar) break;
currentInnerPictureColor = Ref[referenceX, referenceY];
currentOuterPictureColor = img[originalX + referenceX, originalY + referenceY];
if (
!CommonFunctions.ColorsSimilar(currentInnerPictureColor, currentOuterPictureColor,
tolerance))
allSimilar = false;
currentScore +=
(Math.Abs(currentInnerPictureColor.R - currentOuterPictureColor.R)
+ Math.Abs(currentInnerPictureColor.G - currentOuterPictureColor.G)
+ Math.Abs(currentInnerPictureColor.B - currentOuterPictureColor.B));
}
}
if (allSimilar)
{
if ((currentScore/(Double) (Ref.Width*Ref.Height)) < bestScore)
{
location.X = originalX;
location.Y = originalY;
bestScore = (currentScore/(Double) (Ref.Width*Ref.Height));
found = true;
}
}
}
}
}
if (found)
return new Rectangle(location.X, location.Y, Ref.Width, Ref.Height);
return Rectangle.Empty;
}
/// <summary>
/// Searches for an image in another image
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// ImageData Img = new ImageData(...);
/// ImageData Search= new ImageData(...);
/// // search with tolerance 25
/// List<Rectangle> Positions = Template.AllImages(Img,Search,25);
/// ]]>
/// </code>
/// </example>
/// <param name="img">Image to look in</param>
/// <param name="Ref">Image to look for</param>
/// <param name="tolerance">Tolerance of similarity (0,...,255)</param>
/// <returns>A Rectangle list of matching positions</returns>
public static List<Rectangle> AllImages(ImageData img, ImageData Ref, uint tolerance = 0)
{
var retVal = new List<Rectangle>();
for (int originalX = 0; originalX < img.Width - Ref.Width; originalX++)
{
for (int originalY = 0; originalY < img.Height - Ref.Height; originalY++)
{
Color currentInnerPictureColor = Ref[0, 0];
Color currentOuterPictureColor = img[originalX, originalY];
if (CommonFunctions.ColorsSimilar(currentInnerPictureColor, currentOuterPictureColor, tolerance))
{
Boolean allSimilar = true;
for (int referenceX = 0; referenceX < Ref.Width; referenceX++)
{
if (!allSimilar)
break;
for (Int32 referenceY = 0; referenceY < Ref.Height; referenceY++)
{
if (!allSimilar)
break;
currentInnerPictureColor = Ref[referenceX, referenceY];
currentOuterPictureColor = img[originalX + referenceX, originalY + referenceY];
if (
!CommonFunctions.ColorsSimilar(currentInnerPictureColor, currentOuterPictureColor,
tolerance))
allSimilar = false;
}
}
if (allSimilar)
{
retVal.Add(new Rectangle(originalX, originalY, Ref.Width, Ref.Height));
}
}
}
}
return retVal;
}
}
}
| |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.RabbitMqTransport
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Security;
using System.Security.Authentication;
using System.Text;
using System.Text.RegularExpressions;
using Configuration;
using Configuration.Configurators;
using NewIdFormatters;
using RabbitMQ.Client;
using Topology;
using Util;
public static class RabbitMqAddressExtensions
{
static readonly INewIdFormatter _formatter = new ZBase32Formatter();
static readonly Regex _regex = new Regex(@"^[A-Za-z0-9\-_\.:]+$");
public static string GetTemporaryQueueName(this IRabbitMqBusFactoryConfigurator configurator, string prefix)
{
var sb = new StringBuilder(prefix);
var host = HostMetadataCache.Host;
foreach (char c in host.MachineName)
{
if (char.IsLetterOrDigit(c))
sb.Append(c);
else if (c == '.' || c == '_' || c == '-' || c == ':')
sb.Append(c);
}
sb.Append('-');
foreach (char c in host.ProcessName)
{
if (char.IsLetterOrDigit(c))
sb.Append(c);
else if (c == '.' || c == '_' || c == '-' || c == ':')
sb.Append(c);
}
sb.Append('-');
sb.Append(NewId.Next().ToString(_formatter));
return sb.ToString();
}
public static string ToDebugString(this RabbitMqHostSettings settings)
{
var sb = new StringBuilder();
if (!string.IsNullOrWhiteSpace(settings.Username))
sb.Append(settings.Username).Append('@');
sb.Append(settings.Host);
if (settings.Port != -1)
sb.Append(':').Append(settings.Port);
if (string.IsNullOrWhiteSpace(settings.VirtualHost))
sb.Append('/');
else if (settings.VirtualHost.StartsWith("/"))
sb.Append(settings.VirtualHost);
else
sb.Append("/").Append(settings.VirtualHost);
return sb.ToString();
}
public static Uri GetInputAddress(this RabbitMqHostSettings hostSettings, ReceiveSettings receiveSettings)
{
var builder = new UriBuilder
{
Scheme = "rabbitmq",
Host = hostSettings.Host,
Port = hostSettings.Port,
Path = (string.IsNullOrWhiteSpace(hostSettings.VirtualHost) || hostSettings.VirtualHost == "/")
? receiveSettings.QueueName
: string.Join("/", hostSettings.VirtualHost, receiveSettings.QueueName)
};
builder.Query += string.Join("&", GetQueryStringOptions(receiveSettings));
return builder.Uri;
}
public static Uri GetQueueAddress(this RabbitMqHostSettings hostSettings, string queueName)
{
UriBuilder builder = GetHostUriBuilder(hostSettings, queueName);
return builder.Uri;
}
/// <summary>
/// Returns a UriBuilder for the host and entity specified
/// </summary>
/// <param name="hostSettings">The host settings</param>
/// <param name="entityName">The entity name (queue/exchange)</param>
/// <returns>A UriBuilder</returns>
static UriBuilder GetHostUriBuilder(RabbitMqHostSettings hostSettings, string entityName)
{
return new UriBuilder
{
Scheme = "rabbitmq",
Host = hostSettings.Host,
Port = hostSettings.Port,
Path = (string.IsNullOrWhiteSpace(hostSettings.VirtualHost) || hostSettings.VirtualHost == "/")
? entityName
: string.Join("/", hostSettings.VirtualHost, entityName)
};
}
/// <summary>
/// Return a send address for the exchange
/// </summary>
/// <param name="host">The RabbitMQ host</param>
/// <param name="exchangeName">The exchange name</param>
/// <param name="configure">An optional configuration for the exchange to set type, durable, etc.</param>
/// <returns></returns>
public static Uri GetSendAddress(this IRabbitMqHost host, string exchangeName, Action<IExchangeConfigurator> configure = null)
{
var builder = GetHostUriBuilder(host.Settings, exchangeName);
var sendSettings = new RabbitMqSendSettings(exchangeName, ExchangeType.Fanout, true, false);
configure?.Invoke(sendSettings);
builder.Query += string.Join("&", GetQueryStringOptions(sendSettings));
return builder.Uri;
}
public static Uri GetSendAddress(this RabbitMqHostSettings hostSettings, SendSettings sendSettings)
{
var builder = new UriBuilder
{
Scheme = "rabbitmq",
Host = hostSettings.Host,
Port = hostSettings.Port,
Path = hostSettings.VirtualHost != "/"
? string.Join("/", hostSettings.VirtualHost, sendSettings.ExchangeName)
: sendSettings.ExchangeName
};
builder.Query += string.Join("&", GetQueryStringOptions(sendSettings));
return builder.Uri;
}
static IEnumerable<string> GetQueryStringOptions(ReceiveSettings settings)
{
if (!settings.Durable)
yield return "durable=false";
if (settings.AutoDelete)
yield return "autodelete=true";
if (settings.Exclusive)
yield return "exclusive=true";
if (settings.PrefetchCount != 0)
yield return "prefetch=" + settings.PrefetchCount;
}
static IEnumerable<string> GetQueryStringOptions(SendSettings settings)
{
if (!settings.Durable)
yield return "durable=false";
if (settings.AutoDelete)
yield return "autodelete=true";
if (settings.BindToQueue)
yield return "bind=true";
if (!string.IsNullOrWhiteSpace(settings.QueueName))
yield return "queue=" + WebUtility.UrlEncode(settings.QueueName);
if (settings.ExchangeType != ExchangeType.Fanout)
yield return "type=" + settings.ExchangeType;
if (settings.ExchangeArguments != null && settings.ExchangeArguments.ContainsKey("x-delayed-type"))
yield return "delayedType=" + settings.ExchangeArguments["x-delayed-type"];
}
public static ReceiveSettings GetReceiveSettings(this Uri address)
{
if (string.Compare("rabbitmq", address.Scheme, StringComparison.OrdinalIgnoreCase) != 0)
throw new RabbitMqAddressException("The invalid scheme was specified: " + address.Scheme);
var connectionFactory = new ConnectionFactory
{
HostName = address.Host,
UserName = "guest",
Password = "guest",
};
if (address.IsDefaultPort)
connectionFactory.Port = 5672;
else if (!address.IsDefaultPort)
connectionFactory.Port = address.Port;
string name = address.AbsolutePath.Substring(1);
string[] pathSegments = name.Split('/');
if (pathSegments.Length == 2)
{
connectionFactory.VirtualHost = pathSegments[0];
name = pathSegments[1];
}
ushort heartbeat = address.Query.GetValueFromQueryString("heartbeat", connectionFactory.RequestedHeartbeat);
connectionFactory.RequestedHeartbeat = heartbeat;
if (name == "*")
{
string uri = address.GetLeftPart(UriPartial.Path);
if (uri.EndsWith("*"))
{
name = NewId.Next().ToString("NS");
uri = uri.Remove(uri.Length - 1) + name;
var builder = new UriBuilder(uri);
builder.Query = string.IsNullOrEmpty(address.Query) ? "" : address.Query.Substring(1);
address = builder.Uri;
}
else
throw new InvalidOperationException("Uri is not properly formed");
}
else
VerifyQueueOrExchangeNameIsLegal(name);
ushort prefetch = address.Query.GetValueFromQueryString("prefetch", (ushort)Math.Max(Environment.ProcessorCount, 16));
int timeToLive = address.Query.GetValueFromQueryString("ttl", 0);
bool isTemporary = address.Query.GetValueFromQueryString("temporary", false);
bool durable = address.Query.GetValueFromQueryString("durable", !isTemporary);
bool exclusive = address.Query.GetValueFromQueryString("exclusive", isTemporary);
bool autoDelete = address.Query.GetValueFromQueryString("autodelete", isTemporary);
ReceiveSettings settings = new RabbitMqReceiveSettings
{
AutoDelete = autoDelete,
Durable = durable,
Exclusive = exclusive,
QueueName = name,
PrefetchCount = prefetch,
};
if (timeToLive > 0)
settings.QueueArguments.Add("x-message-ttl", timeToLive.ToString("F0", CultureInfo.InvariantCulture));
return settings;
}
/// <summary>
/// Return the send settings for the address
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public static SendSettings GetSendSettings(this Uri address)
{
if (string.Compare("rabbitmq", address.Scheme, StringComparison.OrdinalIgnoreCase) != 0)
throw new RabbitMqAddressException("The invalid scheme was specified: " + address.Scheme);
string name = address.AbsolutePath.Substring(1);
string[] pathSegments = name.Split('/');
if (pathSegments.Length == 2)
name = pathSegments[1];
if (name == "*")
throw new ArgumentException("Cannot send to a dynamic address");
VerifyQueueOrExchangeNameIsLegal(name);
bool isTemporary = address.Query.GetValueFromQueryString("temporary", false);
bool durable = address.Query.GetValueFromQueryString("durable", !isTemporary);
bool autoDelete = address.Query.GetValueFromQueryString("autodelete", isTemporary);
string exchangeType = address.Query.GetValueFromQueryString("type") ?? ExchangeType.Fanout;
var settings = new RabbitMqSendSettings(name, exchangeType, durable, autoDelete);
bool bindToQueue = address.Query.GetValueFromQueryString("bind", false);
if (bindToQueue)
{
string queueName = WebUtility.UrlDecode(address.Query.GetValueFromQueryString("queue"));
settings.BindToQueue(queueName);
}
string delayedType = address.Query.GetValueFromQueryString("delayedType");
if (!string.IsNullOrWhiteSpace(delayedType))
settings.SetExchangeArgument("x-delayed-type", delayedType);
return settings;
}
public static SendSettings GetSendSettings(this IRabbitMqHost host, Type messageType)
{
bool isTemporary = messageType.IsTemporaryMessageType();
bool durable = !isTemporary;
bool autoDelete = isTemporary;
string name = host.MessageNameFormatter.GetMessageName(messageType).ToString();
SendSettings settings = new RabbitMqSendSettings(name, ExchangeType.Fanout, durable, autoDelete);
return settings;
}
public static ConnectionFactory GetConnectionFactory(this RabbitMqHostSettings settings)
{
var factory = new ConnectionFactory
{
AutomaticRecoveryEnabled = false,
NetworkRecoveryInterval = TimeSpan.FromSeconds(1),
TopologyRecoveryEnabled = false,
HostName = settings.Host,
Port = settings.Port,
VirtualHost = settings.VirtualHost ?? "/",
RequestedHeartbeat = settings.Heartbeat
};
factory.Ssl.Enabled = settings.Ssl;
factory.Ssl.Version = SslProtocols.Tls;
factory.Ssl.AcceptablePolicyErrors = settings.AcceptablePolicyErrors;
factory.Ssl.ServerName = settings.SslServerName;
if (string.IsNullOrWhiteSpace(factory.Ssl.ServerName))
factory.Ssl.AcceptablePolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
if (string.IsNullOrEmpty(settings.ClientCertificatePath))
{
if (!string.IsNullOrWhiteSpace(settings.Username))
factory.UserName = settings.Username;
if (!string.IsNullOrWhiteSpace(settings.Password))
factory.Password = settings.Password;
factory.Ssl.CertPath = "";
factory.Ssl.CertPassphrase = "";
factory.Ssl.Certs = null;
}
else
{
factory.Ssl.CertPath = settings.ClientCertificatePath;
factory.Ssl.CertPassphrase = settings.ClientCertificatePassphrase;
}
factory.ClientProperties = factory.ClientProperties ?? new Dictionary<string, object>();
HostInfo hostInfo = HostMetadataCache.Host;
factory.ClientProperties["client_api"] = "MassTransit";
factory.ClientProperties["masstransit_version"] = hostInfo.MassTransitVersion;
factory.ClientProperties["net_version"] = hostInfo.FrameworkVersion;
factory.ClientProperties["hostname"] = hostInfo.MachineName;
factory.ClientProperties["connected"] = DateTimeOffset.Now.ToString("R");
factory.ClientProperties["process_id"] = hostInfo.ProcessId.ToString();
factory.ClientProperties["process_name"] = hostInfo.ProcessName;
if (hostInfo.Assembly != null)
factory.ClientProperties["assembly"] = hostInfo.Assembly;
if (hostInfo.AssemblyVersion != null)
factory.ClientProperties["assembly_version"] = hostInfo.AssemblyVersion;
return factory;
}
public static RabbitMqHostSettings GetHostSettings(this Uri address)
{
if (string.Compare("rabbitmq", address.Scheme, StringComparison.OrdinalIgnoreCase) != 0)
throw new RabbitMqAddressException("The invalid scheme was specified: " + address.Scheme);
var hostSettings = new ConfigurationHostSettings
{
Host = address.Host,
Username = "",
Password = "",
Port = address.IsDefaultPort ? 5672 : address.Port
};
if (!string.IsNullOrEmpty(address.UserInfo))
{
string[] parts = address.UserInfo.Split(':');
hostSettings.Username = parts[0];
if (parts.Length >= 2)
hostSettings.Password = parts[1];
}
string name = address.AbsolutePath.Substring(1);
string[] pathSegments = name.Split('/');
hostSettings.VirtualHost = pathSegments.Length == 2 ? pathSegments[0] : "/";
hostSettings.Heartbeat = address.Query.GetValueFromQueryString("heartbeat", (ushort)0);
return hostSettings;
}
static void VerifyQueueOrExchangeNameIsLegal(string queueName)
{
if (string.IsNullOrWhiteSpace(queueName))
throw new RabbitMqAddressException("The queue name must not be null or empty");
bool success = IsValidQueueName(queueName);
if (!success)
{
throw new RabbitMqAddressException(
"The queueName must be a sequence of these characters: letters, digits, hyphen, underscore, period, or colon.");
}
}
public static bool IsValidQueueName(string queueName)
{
Match match = _regex.Match(queueName);
bool success = match.Success;
return success;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ExtractSingle129()
{
var test = new ExtractScalarTest__ExtractSingle129();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ExtractScalarTest__ExtractSingle129
{
private struct TestStruct
{
public Vector128<Single> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(ExtractScalarTest__ExtractSingle129 testClass)
{
var result = Sse41.Extract(_fld, 129);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar;
private Vector128<Single> _fld;
private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable;
static ExtractScalarTest__ExtractSingle129()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public ExtractScalarTest__ExtractSingle129()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.Extract(
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr),
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.Extract(
Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)),
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.Extract(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)),
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr),
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Single)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)),
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Single)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)),
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Single)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Extract(
_clsVar,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr);
var result = Sse41.Extract(firstOp, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse.LoadVector128((Single*)(_dataTable.inArrayPtr));
var result = Sse41.Extract(firstOp, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr));
var result = Sse41.Extract(firstOp, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ExtractScalarTest__ExtractSingle129();
var result = Sse41.Extract(test._fld, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Extract(_fld, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Extract(test._fld, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(firstOp[1])))
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Extract)}<Single>(Vector128<Single><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Xunit;
namespace System.Diagnostics.TraceSourceTests
{
using Method = TestTraceListener.Method;
public sealed class TraceSourceClassTests
{
[Fact]
public void ConstrutorExceptionTest()
{
Assert.Throws<ArgumentNullException>(() => new TraceSource(null));
AssertExtensions.Throws<ArgumentException>("name", null, () => new TraceSource(""));
}
[Fact]
public void DefaultListenerTest()
{
var trace = new TraceSource("TestTraceSource");
Assert.Equal(1, trace.Listeners.Count);
Assert.IsType<DefaultTraceListener>(trace.Listeners[0]);
}
[Fact]
public void SetSourceSwitchExceptionTest()
{
var trace = new TraceSource("TestTraceSource");
Assert.Throws<ArgumentNullException>(() => trace.Switch = null);
}
[Fact]
public void SetSourceSwitchTest()
{
var trace = new TraceSource("TestTraceSource");
var @switch = new SourceSwitch("TestTraceSwitch");
trace.Switch = @switch;
Assert.Equal(@switch, trace.Switch);
}
[Fact]
public void DefaultLevelTest()
{
var trace = new TraceSource("TestTraceSource");
Assert.Equal(SourceLevels.Off, trace.Switch.Level);
}
[Fact]
public void CloseTest()
{
var trace = new TraceSource("T1", SourceLevels.All);
trace.Listeners.Clear();
var listener = new TestTraceListener();
trace.Listeners.Add(listener);
trace.Close();
Assert.Equal(1, listener.GetCallCount(Method.Close));
// Assert that writing to a closed TraceSource is not an error.
trace.TraceEvent(TraceEventType.Critical, 0);
}
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
static WeakReference PruneMakeRef()
{
return new WeakReference(new TraceSource("TestTraceSource"));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public void PruneTest()
{
var strongTrace = new TraceSource("TestTraceSource");
var traceRef = PruneMakeRef();
Assert.True(traceRef.IsAlive);
GC.Collect(2);
Trace.Refresh();
Assert.False(traceRef.IsAlive);
GC.Collect(2);
Trace.Refresh();
}
[Fact]
public void TraceInformationTest()
{
var trace = new TraceSource("TestTraceSource", SourceLevels.All);
var listener = new TestTraceListener();
trace.Listeners.Add(listener);
trace.TraceInformation("message");
Assert.Equal(0, listener.GetCallCount(Method.TraceData));
Assert.Equal(0, listener.GetCallCount(Method.Write));
Assert.Equal(1, listener.GetCallCount(Method.TraceEvent));
trace.TraceInformation("format", "arg1", "arg2");
Assert.Equal(2, listener.GetCallCount(Method.TraceEvent));
}
[Theory]
[InlineData(SourceLevels.Off, TraceEventType.Critical, 0)]
[InlineData(SourceLevels.Critical, TraceEventType.Critical, 1)]
[InlineData(SourceLevels.Critical, TraceEventType.Error, 0)]
[InlineData(SourceLevels.Error, TraceEventType.Error, 1)]
[InlineData(SourceLevels.Error, TraceEventType.Warning, 0)]
[InlineData(SourceLevels.Warning, TraceEventType.Warning, 1)]
[InlineData(SourceLevels.Warning, TraceEventType.Information, 0)]
[InlineData(SourceLevels.Information, TraceEventType.Information, 1)]
[InlineData(SourceLevels.Information, TraceEventType.Verbose, 0)]
[InlineData(SourceLevels.Verbose, TraceEventType.Verbose, 1)]
[InlineData(SourceLevels.All, TraceEventType.Critical, 1)]
[InlineData(SourceLevels.All, TraceEventType.Verbose, 1)]
// NOTE: tests to cover a TraceEventType value that is not in CoreFX (0x20 == TraceEventType.Start in 4.5)
[InlineData(SourceLevels.Verbose, (TraceEventType)0x20, 0)]
[InlineData(SourceLevels.All, (TraceEventType)0x20, 1)]
public void SwitchLevelTest(SourceLevels sourceLevel, TraceEventType messageLevel, int expected)
{
var trace = new TraceSource("TestTraceSource");
var listener = new TestTraceListener();
trace.Listeners.Add(listener);
trace.Switch.Level = sourceLevel;
trace.TraceEvent(messageLevel, 0);
Assert.Equal(expected, listener.GetCallCount(Method.TraceEvent));
}
[Fact]
public void NullSourceName()
{
AssertExtensions.Throws<ArgumentNullException>("name", () => new TraceSource(null));
AssertExtensions.Throws<ArgumentNullException>("name", () => new TraceSource(null, SourceLevels.All));
}
[Fact]
public void EmptySourceName()
{
AssertExtensions.Throws<ArgumentException>("name", null, () => new TraceSource(string.Empty));
AssertExtensions.Throws<ArgumentException>("name", null, () => new TraceSource(string.Empty, SourceLevels.All));
}
}
public sealed class TraceSourceTests_Default : TraceSourceTestsBase
{
// default mode: GlobalLock = true, AutoFlush = false, ThreadSafeListener = false
}
public sealed class TraceSourceTests_AutoFlush : TraceSourceTestsBase
{
internal override bool AutoFlush
{
get { return true; }
}
}
public sealed class TraceSourceTests_NoGlobalLock : TraceSourceTestsBase
{
internal override bool UseGlobalLock
{
get { return false; }
}
}
public sealed class TraceSourceTests_NoGlobalLock_AutoFlush : TraceSourceTestsBase
{
internal override bool UseGlobalLock
{
get { return false; }
}
internal override bool AutoFlush
{
get { return true; }
}
}
public sealed class TraceSourceTests_ThreadSafeListener : TraceSourceTestsBase
{
internal override bool ThreadSafeListener
{
get { return true; }
}
}
public sealed class TraceSourceTests_ThreadSafeListener_AutoFlush : TraceSourceTestsBase
{
internal override bool ThreadSafeListener
{
get { return true; }
}
internal override bool AutoFlush
{
get { return true; }
}
}
// Defines abstract tests that will be executed in different modes via the above concrete classes.
public abstract class TraceSourceTestsBase : IDisposable
{
void IDisposable.Dispose()
{
TraceTestHelper.ResetState();
}
public TraceSourceTestsBase()
{
Trace.AutoFlush = AutoFlush;
Trace.UseGlobalLock = UseGlobalLock;
}
// properties are overridden to define different "modes" of execution
internal virtual bool UseGlobalLock
{
get
{
// ThreadSafeListener is only meaningful when not using a global lock,
// so UseGlobalLock will be auto-disabled in that mode.
return true && !ThreadSafeListener;
}
}
internal virtual bool AutoFlush
{
get { return false; }
}
internal virtual bool ThreadSafeListener
{
get { return false; }
}
private TestTraceListener GetTraceListener()
{
return new TestTraceListener(ThreadSafeListener);
}
[Fact]
public void FlushTest()
{
var trace = new TraceSource("TestTraceSource", SourceLevels.All);
var listener = GetTraceListener();
trace.Listeners.Add(listener);
trace.Flush();
Assert.Equal(1, listener.GetCallCount(Method.Flush));
}
[Fact]
public void TraceEvent1Test()
{
var trace = new TraceSource("TestTraceSource", SourceLevels.All);
var listener = GetTraceListener();
trace.Listeners.Add(listener);
trace.TraceEvent(TraceEventType.Verbose, 0);
Assert.Equal(1, listener.GetCallCount(Method.TraceEvent));
}
[Fact]
public void TraceEvent2Test()
{
var trace = new TraceSource("TestTraceSource", SourceLevels.All);
var listener = GetTraceListener();
trace.Listeners.Add(listener);
trace.TraceEvent(TraceEventType.Verbose, 0, "Message");
Assert.Equal(1, listener.GetCallCount(Method.TraceEvent));
var flushExpected = AutoFlush ? 1 : 0;
Assert.Equal(flushExpected, listener.GetCallCount(Method.Flush));
}
[Fact]
public void TraceEvent3Test()
{
var trace = new TraceSource("TestTraceSource", SourceLevels.All);
var listener = GetTraceListener();
trace.Listeners.Add(listener);
trace.TraceEvent(TraceEventType.Verbose, 0, "Format", "Arg1", "Arg2");
Assert.Equal(1, listener.GetCallCount(Method.TraceEvent));
var flushExpected = AutoFlush ? 1 : 0;
Assert.Equal(flushExpected, listener.GetCallCount(Method.Flush));
}
[Fact]
public void TraceData1Test()
{
var trace = new TraceSource("TestTraceSource", SourceLevels.All);
var listener = GetTraceListener();
trace.Listeners.Add(listener);
trace.TraceData(TraceEventType.Verbose, 0, new object());
Assert.Equal(1, listener.GetCallCount(Method.TraceData));
var flushExpected = AutoFlush ? 1 : 0;
Assert.Equal(flushExpected, listener.GetCallCount(Method.Flush));
}
[Fact]
public void TraceData2Test()
{
var trace = new TraceSource("TestTraceSource", SourceLevels.All);
var listener = GetTraceListener();
trace.Listeners.Add(listener);
trace.TraceData(TraceEventType.Verbose, 0, new object[0]);
Assert.Equal(1, listener.GetCallCount(Method.TraceData));
var flushExpected = AutoFlush ? 1 : 0;
Assert.Equal(flushExpected, listener.GetCallCount(Method.Flush));
}
[Fact]
public void TraceTransferTest()
{
var trace = new TraceSource("TestTraceSource", SourceLevels.All);
var listener = GetTraceListener();
trace.Listeners.Add(listener);
trace.TraceTransfer(1, "Trace transfer test message", Trace.CorrelationManager.ActivityId);
Assert.Equal(1, listener.GetCallCount(Method.TraceTransfer));
var flushExpected = AutoFlush ? 1 : 0;
Assert.Equal(flushExpected, listener.GetCallCount(Method.Flush));
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using ParquetSharp.Bytes;
using ParquetSharp.Column;
using ParquetSharp.Column.Page;
using ParquetSharp.External;
using ParquetSharp.Format;
using ParquetSharp.Format.Converter;
using ParquetSharp.Hadoop.Metadata;
using ParquetSharp.Hadoop.Util;
using ParquetSharp.Hadoop.Util.Counters;
using ParquetSharp.IO;
using static ParquetSharp.Format.Converter.ParquetMetadataConverter;
using static ParquetSharp.Log;
using static ParquetSharp.Hadoop.ParquetFileWriter;
using FileMetaData = ParquetSharp.Hadoop.Metadata.FileMetaData;
using Path = ParquetSharp.External.Path;
namespace ParquetSharp.Hadoop
{
/**
* Internal implementation of the Parquet file reader as a block container
*
* @author Julien Le Dem
*
*/
public class ParquetFileReader : IDisposable
{
private static readonly Log LOG = Log.getLog(typeof(ParquetFileReader));
public const string PARQUET_READ_PARALLELISM = "parquet.metadata.read.parallelism";
private static ParquetMetadataConverter converter = new ParquetMetadataConverter();
/**
* for files provided, check if there's a summary file.
* If a summary file is found it is used otherwise the file footer is used.
* @param configuration the hadoop conf to connect to the file system;
* @param partFiles the part files to read
* @return the footers for those files using the summary file if possible.
* @throws IOException
*/
[Obsolete]
public static List<Footer> readAllFootersInParallelUsingSummaryFiles(Configuration configuration, List<FileStatus> partFiles)
{
return readAllFootersInParallelUsingSummaryFiles(configuration, partFiles, false);
}
private static MetadataFilter filter(bool skipRowGroups)
{
return skipRowGroups ? SKIP_ROW_GROUPS : NO_FILTER;
}
/**
* for files provided, check if there's a summary file.
* If a summary file is found it is used otherwise the file footer is used.
* @param configuration the hadoop conf to connect to the file system;
* @param partFiles the part files to read
* @param skipRowGroups to skipRowGroups in the footers
* @return the footers for those files using the summary file if possible.
* @throws IOException
*/
public static List<Footer> readAllFootersInParallelUsingSummaryFiles(
Configuration configuration,
List<FileStatus> partFiles,
bool skipRowGroups)
{
// figure out list of all parents to part files
HashSet<Path> parents = new HashSet<Path>();
foreach (FileStatus part in partFiles)
{
parents.Add(part.getPath().getParent());
}
// read corresponding summary files if they exist
List<Func<Dictionary<Path, Footer>>> summaries = new List<Func<Dictionary<Path, Footer>>>();
foreach (Path path in parents)
{
summaries.Add(() =>
{
ParquetMetadata mergedMetadata = readSummaryMetadata(configuration, path, skipRowGroups);
if (mergedMetadata != null)
{
List<Footer> footers;
if (skipRowGroups)
{
footers = new List<Footer>();
foreach (FileStatus f in partFiles)
{
footers.Add(new Footer(f.getPath(), mergedMetadata));
}
}
else {
footers = footersFromSummaryFile(path, mergedMetadata);
}
Dictionary<Path, Footer> map = new Dictionary<Path, Footer>();
foreach (Footer footer in footers)
{
// the folder may have been moved
footer = new Footer(new Path(path, footer.getFile().getName()), footer.getParquetMetadata());
map.put(footer.getFile(), footer);
}
return map;
}
else
{
return new Dictionary<External.Path, Footer>();
}
});
}
Dictionary<Path, Footer> cache = new Dictionary<Path, Footer>();
try
{
List<Dictionary<Path, Footer>> footersFromSummaries = runAllInParallel(configuration.getInt(PARQUET_READ_PARALLELISM, 5), summaries);
foreach (Dictionary<Path, Footer> footers in footersFromSummaries)
{
cache.putAll(footers);
}
}
catch (ExecutionException e)
{
throw new IOException("Error reading summaries", e);
}
// keep only footers for files actually requested and read file footer if not found in summaries
List<Footer> result = new List<Footer>(partFiles.Count);
List<FileStatus> toRead = new List<FileStatus>();
foreach (FileStatus part in partFiles)
{
Footer f;
if (cache.TryGetValue(part.getPath(), out f))
{
result.Add(f);
}
else
{
toRead.Add(part);
}
}
if (toRead.Count > 0)
{
// read the footers of the files that did not have a summary file
if (Log.INFO)
{
LOG.info("reading another " + toRead.Count + " footers");
}
result.AddRange(readAllFootersInParallel(configuration, toRead, skipRowGroups));
}
return result;
}
private static List<T> runAllInParallel<T>(int parallelism, List<Func<T>> toRun)
{
LOG.info("Initiating action with parallelism: " + parallelism);
ExecutorService threadPool = Executors.newFixedThreadPool(parallelism);
try
{
List<Future<T>> futures = new List<Future<T>>();
foreach (Func<T> callable in toRun)
{
futures.Add(threadPool.submit(callable));
}
List<T> result = new List<T>(toRun.Count);
foreach (Future<T> future in futures)
{
try
{
result.Add(future.get());
}
catch (InterruptedException e)
{
throw new RuntimeException("The thread was interrupted", e);
}
}
return result;
}
finally
{
threadPool.shutdownNow();
}
}
[Obsolete]
public static List<Footer> readAllFootersInParallel(Configuration configuration, List<FileStatus> partFiles)
{
return readAllFootersInParallel(configuration, partFiles, false);
}
/**
* read all the footers of the files provided
* (not using summary files)
* @param configuration the conf to access the File System
* @param partFiles the files to read
* @param skipRowGroups to skip the rowGroup info
* @return the footers
* @throws IOException
*/
public static List<Footer> readAllFootersInParallel(Configuration configuration, List<FileStatus> partFiles, bool skipRowGroups)
{
List<Func<Footer>> footers = new List<Func<Footer>>();
foreach (FileStatus currentFile in partFiles)
{
footers.Add(() =>
{
try
{
return new Footer(currentFile.getPath(), readFooter(configuration, currentFile, filter(skipRowGroups)));
}
catch (IOException e)
{
throw new IOException("Could not read footer for file " + currentFile, e);
}
});
}
try
{
return runAllInParallel(configuration.getInt(PARQUET_READ_PARALLELISM, 5), footers);
}
catch (ExecutionException e)
{
throw new IOException("Could not read footer: " + e.Message, e.getCause());
}
}
/**
* Read the footers of all the files under that path (recursively)
* not using summary files.
*/
public static List<Footer> readAllFootersInParallel(Configuration configuration, FileStatus fileStatus, bool skipRowGroups)
{
List<FileStatus> statuses = listFiles(configuration, fileStatus);
return readAllFootersInParallel(configuration, statuses, skipRowGroups);
}
/**
* Read the footers of all the files under that path (recursively)
* not using summary files.
* rowGroups are not skipped
* @param configuration the configuration to access the FS
* @param fileStatus the root dir
* @return all the footers
* @throws IOException
*/
public static List<Footer> readAllFootersInParallel(Configuration configuration, FileStatus fileStatus)
{
return readAllFootersInParallel(configuration, fileStatus, false);
}
[Obsolete]
public static List<Footer> readFooters(Configuration configuration, Path path)
{
return readFooters(configuration, status(configuration, path));
}
private static FileStatus status(Configuration configuration, Path path)
{
return path.getFileSystem(configuration).getFileStatus(path);
}
/**
* this always returns the row groups
* @param configuration
* @param pathStatus
* @return
* @throws IOException
*/
[Obsolete]
public static List<Footer> readFooters(Configuration configuration, FileStatus pathStatus)
{
return readFooters(configuration, pathStatus, false);
}
/**
* Read the footers of all the files under that path (recursively)
* using summary files if possible
* @param configuration the configuration to access the FS
* @param pathStatus the root dir
* @return all the footers
* @throws IOException
*/
public static List<Footer> readFooters(Configuration configuration, FileStatus pathStatus, bool skipRowGroups)
{
List<FileStatus> files = listFiles(configuration, pathStatus);
return readAllFootersInParallelUsingSummaryFiles(configuration, files, skipRowGroups);
}
private static List<FileStatus> listFiles(Configuration conf, FileStatus fileStatus)
{
if (fileStatus.isDir())
{
FileSystem fs = fileStatus.getPath().getFileSystem(conf);
FileStatus[] list = fs.listStatus(fileStatus.getPath(), HiddenFileFilter.INSTANCE);
List<FileStatus> result = new List<FileStatus>();
foreach (FileStatus sub in list)
{
result.AddRange(listFiles(conf, sub));
}
return result;
}
else
{
return new List<FileStatus> { fileStatus };
}
}
/**
* Specifically reads a given summary file
* @param configuration
* @param summaryStatus
* @return the metadata translated for each file
* @throws IOException
*/
public static List<Footer> readSummaryFile(Configuration configuration, FileStatus summaryStatus)
{
Path parent = summaryStatus.getPath().getParent();
ParquetMetadata mergedFooters = readFooter(configuration, summaryStatus, filter(false));
return footersFromSummaryFile(parent, mergedFooters);
}
static ParquetMetadata readSummaryMetadata(Configuration configuration, Path basePath, bool skipRowGroups)
{
Path metadataFile = new Path(basePath, PARQUET_METADATA_FILE);
Path commonMetaDataFile = new Path(basePath, PARQUET_COMMON_METADATA_FILE);
FileSystem fileSystem = basePath.getFileSystem(configuration);
if (skipRowGroups && fileSystem.exists(commonMetaDataFile))
{
// reading the summary file that does not contain the row groups
if (Log.INFO) LOG.info("reading summary file: " + commonMetaDataFile);
return readFooter(configuration, commonMetaDataFile, filter(skipRowGroups));
}
else if (fileSystem.exists(metadataFile))
{
if (Log.INFO)
{
LOG.info("reading summary file: " + metadataFile);
}
return readFooter(configuration, metadataFile, filter(skipRowGroups));
}
else {
return null;
}
}
static List<Footer> footersFromSummaryFile(Path parent, ParquetMetadata mergedFooters)
{
Dictionary<Path, ParquetMetadata> footers = new Dictionary<Path, ParquetMetadata>();
List<BlockMetaData> blocks = mergedFooters.getBlocks();
foreach (BlockMetaData block in blocks)
{
string path = block.getPath();
Path fullPath = new Path(parent, path);
ParquetMetadata current;
if (!footers.TryGetValue(fullPath, out current))
{
current = new ParquetMetadata(mergedFooters.getFileMetaData(), new List<BlockMetaData>());
footers.Add(fullPath, current);
}
current.getBlocks().Add(block);
}
List<Footer> result = new List<Footer>();
foreach (KeyValuePair<Path, ParquetMetadata> entry in footers)
{
result.Add(new Footer(entry.Key, entry.Value));
}
return result;
}
/**
* Reads the meta data block in the footer of the file
* @param configuration
* @param file the parquet File
* @return the metadata blocks in the footer
* @throws IOException if an error occurs while reading the file
*/
[Obsolete]
public static ParquetMetadata readFooter(Configuration configuration, Path file)
{
return readFooter(configuration, file, NO_FILTER);
}
/**
* Reads the meta data in the footer of the file.
* Skipping row groups (or not) based on the provided filter
* @param configuration
* @param file the Parquet File
* @param filter the filter to apply to row groups
* @return the metadata with row groups filtered.
* @throws IOException if an error occurs while reading the file
*/
internal static ParquetMetadata readFooter(Configuration configuration, Path file, MetadataFilter filter)
{
FileSystem fileSystem = file.getFileSystem(configuration);
return readFooter(configuration, fileSystem.getFileStatus(file), filter);
}
/**
* [Obsolete] use {@link ParquetFileReader#readFooter(Configuration, FileStatus, MetadataFilter)}
*/
[Obsolete]
public static ParquetMetadata readFooter(Configuration configuration, FileStatus file)
{
return readFooter(configuration, file, NO_FILTER);
}
/**
* Reads the meta data block in the footer of the file
* @param configuration
* @param file the parquet File
* @param filter the filter to apply to row groups
* @return the metadata blocks in the footer
* @throws IOException if an error occurs while reading the file
*/
internal static ParquetMetadata readFooter(Configuration configuration, FileStatus file, MetadataFilter filter)
{
FileSystem fileSystem = file.getPath().getFileSystem(configuration);
FSDataInputStream f = fileSystem.open(file.getPath());
try
{
long l = file.getLen();
if (Log.DEBUG)
{
LOG.debug("File length " + l);
}
int FOOTER_LENGTH_SIZE = 4;
if (l < MAGIC.Length + FOOTER_LENGTH_SIZE + MAGIC.Length)
{ // MAGIC + data + footer + footerIndex + MAGIC
throw new RuntimeException(file.getPath() + " is not a Parquet file (too small)");
}
long footerLengthIndex = l - FOOTER_LENGTH_SIZE - MAGIC.Length;
if (Log.DEBUG)
{
LOG.debug("reading footer index at " + footerLengthIndex);
}
f.seek(footerLengthIndex);
int footerLength = readIntLittleEndian(f);
byte[] magic = new byte[MAGIC.Length];
f.readFully(magic);
if (!Arrays.equals(MAGIC, magic))
{
throw new RuntimeException(file.getPath() + " is not a Parquet file. expected magic number at tail " + Arrays.toString(MAGIC) + " but found " + Arrays.toString(magic));
}
long footerIndex = footerLengthIndex - footerLength;
if (Log.DEBUG)
{
LOG.debug("read footer length: " + footerLength + ", footer index: " + footerIndex);
}
if (footerIndex < MAGIC.Length || footerIndex >= footerLengthIndex)
{
throw new RuntimeException("corrupted file: the footer index is not within the file");
}
f.seek(footerIndex);
return converter.readParquetMetadata(f, filter);
}
finally
{
f.close();
}
}
internal static ParquetFileReader open(Configuration conf, Path file)
{
ParquetMetadata footer = readFooter(conf, file, NO_FILTER);
return new ParquetFileReader(conf, footer.getFileMetaData(), file,
footer.getBlocks(), footer.getFileMetaData().getSchema().getColumns());
}
private readonly CodecFactory codecFactory;
private readonly List<BlockMetaData> blocks;
private readonly FSDataInputStream f;
private readonly Path filePath;
private readonly Dictionary<ColumnPath, ColumnDescriptor> paths = new Dictionary<ColumnPath, ColumnDescriptor>();
private readonly FileMetaData fileMetaData;
private readonly string createdBy;
private readonly ByteBufferAllocator allocator;
private int currentBlock = 0;
/**
* [Obsolete] use @link{ParquetFileReader(Configuration configuration, FileMetaData fileMetaData,
* Path filePath, List<BlockMetaData> blocks, List<ColumnDescriptor> columns)} instead
*/
public ParquetFileReader(Configuration configuration, Path filePath, List<BlockMetaData> blocks, List<ColumnDescriptor> columns)
: this(configuration, null, filePath, blocks, columns)
{
}
/**
* @param configuration the Hadoop conf
* @param fileMetaData fileMetaData for parquet file
* @param blocks the blocks to read
* @param columns the columns to read (their path)
* @throws IOException if the file can not be opened
*/
public ParquetFileReader(
Configuration configuration, FileMetaData fileMetaData,
Path filePath, List<BlockMetaData> blocks, List<ColumnDescriptor> columns)
{
this.filePath = filePath;
this.fileMetaData = fileMetaData;
this.createdBy = fileMetaData == null ? null : fileMetaData.getCreatedBy();
FileSystem fs = filePath.getFileSystem(configuration);
this.f = fs.open(filePath);
this.blocks = blocks;
foreach (ColumnDescriptor col in columns)
{
paths[ColumnPath.get(col.getPath())] = col;
}
// the page size parameter isn't meaningful when only using
// the codec factory to get decompressors
this.codecFactory = new CodecFactory(configuration, 0);
this.allocator = new HeapByteBufferAllocator();
}
public void appendTo(ParquetFileWriter writer)
{
writer.appendRowGroups(f, blocks, true);
}
/**
* Reads all the columns requested from the row group at the current file position.
* @throws IOException if an error occurs while reading
* @return the PageReadStore which can provide PageReaders for each column.
*/
public PageReadStore readNextRowGroup()
{
if (currentBlock == blocks.Count)
{
return null;
}
BlockMetaData block = blocks[currentBlock];
if (block.getRowCount() == 0)
{
throw new RuntimeException("Illegal row group of 0 rows");
}
ColumnChunkPageReadStore columnChunkPageReadStore = new ColumnChunkPageReadStore(block.getRowCount());
// prepare the list of consecutive chunks to read them in one scan
List<ConsecutiveChunkList> allChunks = new List<ConsecutiveChunkList>();
ConsecutiveChunkList currentChunks = null;
foreach (ColumnChunkMetaData mc in block.getColumns())
{
ColumnPath pathKey = mc.getPath();
BenchmarkCounter.incrementTotalBytes(mc.getTotalSize());
ColumnDescriptor columnDescriptor;
if (paths.TryGetValue(pathKey, out columnDescriptor))
{
long startingPos = mc.getStartingPos();
// first chunk or not consecutive => new list
if (currentChunks == null || currentChunks.endPos() != startingPos)
{
currentChunks = new ConsecutiveChunkList(this, startingPos);
allChunks.Add(currentChunks);
}
currentChunks.addChunk(new ChunkDescriptor(columnDescriptor, mc, startingPos, (int)mc.getTotalSize()));
}
}
// actually read all the chunks
foreach (ConsecutiveChunkList consecutiveChunks in allChunks)
{
List<Chunk> chunks = consecutiveChunks.readAll(f);
foreach (Chunk chunk in chunks)
{
columnChunkPageReadStore.addColumn(chunk.Descriptor.Col, chunk.readAllPages());
}
}
++currentBlock;
return columnChunkPageReadStore;
}
public void close()
{
f.close();
this.codecFactory.release();
}
/**
* The data for a column chunk
*
* @author Julien Le Dem
*
*/
class Chunk : ByteBufferInputStream
{
private readonly ParquetFileReader reader;
private readonly ChunkDescriptor descriptor;
/**
*
* @param descriptor descriptor for the chunk
* @param data contains the chunk data at offset
* @param offset where the chunk starts in offset
*/
public Chunk(ParquetFileReader reader, ChunkDescriptor descriptor, ByteBuffer data, int offset)
: base(data, offset, descriptor.Size)
{
this.descriptor = descriptor;
}
internal ParquetFileReader Reader
{
get { return this.reader; }
}
internal ChunkDescriptor Descriptor
{
get { return this.descriptor; }
}
protected virtual PageHeader readPageHeader()
{
return ParquetSharp.Util.readPageHeader(this);
}
/**
* Read all of the pages in a given column chunk.
* @return the list of pages
*/
public ColumnChunkPageReadStore.ColumnChunkPageReader readAllPages()
{
List<DataPage> pagesInChunk = new List<DataPage>();
DictionaryPage dictionaryPage = null;
long valuesCountReadSoFar = 0;
while (valuesCountReadSoFar < descriptor.Metadata.getValueCount())
{
PageHeader pageHeader = readPageHeader();
int uncompressedPageSize = pageHeader.Uncompressed_page_size;
int compressedPageSize = pageHeader.Compressed_page_size;
switch (pageHeader.Type)
{
case PageType.DICTIONARY_PAGE:
// there is only one dictionary page per column chunk
if (dictionaryPage != null)
{
throw new ParquetDecodingException("more than one dictionary page in column " + descriptor.Col);
}
DictionaryPageHeader dicHeader = pageHeader.Dictionary_page_header;
dictionaryPage =
new DictionaryPage(
this.readAsBytesInput(compressedPageSize),
uncompressedPageSize,
dicHeader.Num_values,
converter.getEncoding(dicHeader.Encoding)
);
break;
case PageType.DATA_PAGE:
DataPageHeader dataHeaderV1 = pageHeader.Data_page_header;
pagesInChunk.Add(
new DataPageV1(
this.readAsBytesInput(compressedPageSize),
dataHeaderV1.Num_values,
uncompressedPageSize,
fromParquetStatistics(
reader.createdBy,
dataHeaderV1.Statistics,
descriptor.Col.getType()),
converter.getEncoding(dataHeaderV1.Repetition_level_encoding),
converter.getEncoding(dataHeaderV1.Definition_level_encoding),
converter.getEncoding(dataHeaderV1.Encoding)
));
valuesCountReadSoFar += dataHeaderV1.Num_values;
break;
case PageType.DATA_PAGE_V2:
DataPageHeaderV2 dataHeaderV2 = pageHeader.Data_page_header_v2;
int dataSize = compressedPageSize - dataHeaderV2.Repetition_levels_byte_length - dataHeaderV2.Definition_levels_byte_length;
pagesInChunk.Add(
new DataPageV2(
dataHeaderV2.Num_rows,
dataHeaderV2.Num_nulls,
dataHeaderV2.Num_values,
this.readAsBytesInput(dataHeaderV2.Repetition_levels_byte_length),
this.readAsBytesInput(dataHeaderV2.Definition_levels_byte_length),
converter.getEncoding(dataHeaderV2.Encoding),
this.readAsBytesInput(dataSize),
uncompressedPageSize,
fromParquetStatistics(
reader.createdBy,
dataHeaderV2.Statistics,
descriptor.Col.getType()),
dataHeaderV2.Is_compressed
));
valuesCountReadSoFar += dataHeaderV2.Num_values;
break;
default:
if (DEBUG)
{
LOG.debug("skipping page of type " + pageHeader.Type + " of size " + compressedPageSize);
}
this.skip(compressedPageSize);
break;
}
}
if (valuesCountReadSoFar != descriptor.Metadata.getValueCount())
{
// Would be nice to have a CorruptParquetFileException or something as a subclass?
throw new IOException(
"Expected " + descriptor.Metadata.getValueCount() + " values in column chunk at " +
reader.filePath + " offset " + descriptor.Metadata.getFirstDataPageOffset() +
" but got " + valuesCountReadSoFar + " values instead over " + pagesInChunk.Count
+ " pages ending at file offset " + (descriptor.FileOffset + pos()));
}
CodecFactory.BytesDecompressor decompressor = reader.codecFactory.getDecompressor(descriptor.Metadata.getCodec());
return new ColumnChunkPageReadStore.ColumnChunkPageReader(decompressor, pagesInChunk, dictionaryPage);
}
/**
* @return the current position in the chunk
*/
public int pos()
{
return this.byteBuf.position();
}
/**
* @param size the size of the page
* @return the page
* @throws IOException
*/
public virtual BytesInput readAsBytesInput(int size)
{
int pos = this.byteBuf.position();
BytesInput r = BytesInput.from(this.byteBuf, pos, size);
this.byteBuf.position(pos + size);
return r;
}
}
/**
* deals with a now fixed bug where compressedLength was missing a few bytes.
*
* @author Julien Le Dem
*
*/
private class WorkaroundChunk : Chunk
{
private readonly FSDataInputStream f;
/**
* @param descriptor the descriptor of the chunk
* @param byteBuf contains the data of the chunk at offset
* @param offset where the chunk starts in data
* @param f the file stream positioned at the end of this chunk
*/
internal WorkaroundChunk(ParquetFileReader reader, ChunkDescriptor descriptor, ByteBuffer byteBuf, int offset, FSDataInputStream f)
: base(reader, descriptor, byteBuf, offset)
{
this.f = f;
}
protected override PageHeader readPageHeader()
{
PageHeader pageHeader;
int initialPos = pos();
try
{
pageHeader = ParquetSharp.Util.readPageHeader(this);
}
catch (IOException)
{
// this is to workaround a bug where the compressedLength
// of the chunk is missing the size of the header of the dictionary
// to allow reading older files (using dictionary) we need this.
// usually 13 to 19 bytes are missing
// if the last page is smaller than this, the page header itself is truncated in the buffer.
this.byteBuf.rewind(); // resetting the buffer to the position before we got the error
LOG.info("completing the column chunk to read the page header");
pageHeader = ParquetSharp.Util.readPageHeader(new SequenceInputStream(this, f)); // trying again from the buffer + remainder of the stream.
}
return pageHeader;
}
public override BytesInput readAsBytesInput(int size)
{
if (pos() + size > initPos + count)
{
// this is to workaround a bug where the compressedLength
// of the chunk is missing the size of the header of the dictionary
// to allow reading older files (using dictionary) we need this.
// usually 13 to 19 bytes are missing
int l1 = initPos + count - pos();
int l2 = size - l1;
LOG.info("completed the column chunk with " + l2 + " bytes");
return BytesInput.concat(base.readAsBytesInput(l1), BytesInput.copy(BytesInput.from(f, l2)));
}
return base.readAsBytesInput(size);
}
}
/**
* information needed to read a column chunk
*/
class ChunkDescriptor
{
private readonly ColumnDescriptor col;
private readonly ColumnChunkMetaData metadata;
private readonly long fileOffset;
private readonly int size;
/**
* @param col column this chunk is part of
* @param metadata metadata for the column
* @param fileOffset offset in the file where this chunk starts
* @param size size of the chunk
*/
internal ChunkDescriptor(
ColumnDescriptor col,
ColumnChunkMetaData metadata,
long fileOffset,
int size)
{
this.col = col;
this.metadata = metadata;
this.fileOffset = fileOffset;
this.size = size;
}
internal ColumnDescriptor Col
{
get { return this.col; }
}
internal ColumnChunkMetaData Metadata
{
get { return this.metadata; }
}
internal long FileOffset
{
get { return this.fileOffset; }
}
internal int Size
{
get { return this.size; }
}
}
/**
* describes a list of consecutive column chunks to be read at once.
*
* @author Julien Le Dem
*/
private class ConsecutiveChunkList
{
private readonly ParquetFileReader reader;
private readonly long offset;
private int length;
private readonly List<ChunkDescriptor> chunks = new List<ChunkDescriptor>();
/**
* @param offset where the first chunk starts
*/
internal ConsecutiveChunkList(ParquetFileReader reader, long offset)
{
this.reader = reader;
this.offset = offset;
}
/**
* adds a chunk to the list.
* It must be consecutive to the previous chunk
* @param descriptor
*/
public void addChunk(ChunkDescriptor descriptor)
{
chunks.Add(descriptor);
length += descriptor.Size;
}
/**
* @param f file to read the chunks from
* @return the chunks
* @throws IOException
*/
public List<Chunk> readAll(FSDataInputStream f)
{
List<Chunk> result = new List<Chunk>(chunks.Count);
f.seek(offset);
ByteBuffer chunksByteBuffer = reader.allocator.allocate(length);
CompatibilityUtil.getBuf(f, chunksByteBuffer, length);
// report in a counter the data we just scanned
BenchmarkCounter.incrementBytesRead(length);
int currentChunkOffset = 0;
for (int i = 0; i < chunks.Count; i++)
{
ChunkDescriptor descriptor = chunks[i];
if (i < chunks.Count - 1)
{
result.Add(new Chunk(reader, descriptor, chunksByteBuffer, currentChunkOffset));
}
else
{
// because of a bug, the last chunk might be larger than descriptor.size
result.Add(new WorkaroundChunk(reader, descriptor, chunksByteBuffer, currentChunkOffset, f));
}
currentChunkOffset += descriptor.Size;
}
return result;
}
/**
* @return the position following the last byte of these chunks
*/
public long endPos()
{
return offset + length;
}
}
}
}
| |
//Copyright 2014 Spin Services Limited
//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.Configuration;
using System.Text;
using log4net;
using log4net.Repository.Hierarchy;
using SS.Integration.Adapter.Interface;
namespace SS.Integration.Adapter.Configuration
{
public class Settings : ISettings
{
private const int DEFAULT_FIXTURE_CHECK_FREQUENCY_VALUE = 60000;
private const int DEFAULT_FIXTURE_CREATION_CONCURRENCY_VALUE = 20;
private const int DEFAULT_STARTING_RETRY_DELAY_VALUE = 500;
private const int DEFAULT_MAX_RETRY_DELAY_VALUE = 65000;
private const int DEFAULT_MAX_RETRY_ATTEMPT_VALUE = 3;
private const int DEFAULT_ECHO_INTERVAL_VALUE = 10000;
private const int DEFAULT_ECHO_DELAY_VALUE = 3000;
private const string DEFAULT_STATE_PROVIDER_DIRECTORY = @"FixturesStateFiles";
private const string DEFAULT_FIXTURES_STATE_FILE = @"fixturesState.json";
private const int DEFAULT_FIXTURES_STATE_AUTO_STORE_INTERVAL_VALUE = 5000;
private const string DEFAULT_MARKET_STATE_MANAGER_DIRECTORY = @"MarketsState";
private const int DEFAULT_CACHE_EXPIRY_MINUTES_VALUE = 15;
private const bool DEFAULT_ENABLE_DELTA_RULE = false;
private const bool DEFAULT_USE_STATS = false;
private const bool DEFAULT_USE_SUPERVISOR = false;
private const int DEFAULT_PROCESSING_LOCK_TIMEOUT = 720;
private const double DEFAULT_STOP_STREAMING_DELAY_MINUTES = 0;
private const string DEFAULT_SUPERVISOR_STATE_PATH = @"SupervisorState";
private const int DEFAULT_PREMATCH_SUSPENSION_BEFORE_STARTTIME_IN_MINS = 15;
private const int DEFAULT_START_STREAMING_TIMEOUT = 60;
private const int DEFAULT_START_STREAMING_ATTEMPTS = 10;
private const int DEFAULT_STREAM_THRESHOLD = int.MaxValue;
private const int DEFAULT_FIXTURE_TIMESTAMP_DIFFERENCE_VALUE = 1440;
private const int DEFAULT_FIXTURE_RECOVER_INTERVAL = 30;
private const int DEFAULT_MAX_IN_ERRORED_STATE = 10;
public const int MinimalHealthcheckInterval = 30;
public Settings()
{
User = ConfigurationManager.AppSettings["user"];
Password = ConfigurationManager.AppSettings["password"];
Url = ConfigurationManager.AppSettings["url"];
var value = ConfigurationManager.AppSettings["newFixtureCheckerFrequency"];
FixtureCheckerFrequency = string.IsNullOrEmpty(value) ? DEFAULT_FIXTURE_CHECK_FREQUENCY_VALUE : Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["fixtureCreationConcurrency"];
FixtureCreationConcurrency = string.IsNullOrEmpty(value) ? DEFAULT_FIXTURE_CREATION_CONCURRENCY_VALUE : Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["startingRetryDelay"];
StartingRetryDelay = string.IsNullOrEmpty(value) ? DEFAULT_STARTING_RETRY_DELAY_VALUE : Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["maxRetryDelay"];
MaxRetryDelay = string.IsNullOrEmpty(value) ? DEFAULT_MAX_RETRY_DELAY_VALUE : Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["maxRetryAttempts"];
MaxRetryAttempts = string.IsNullOrEmpty(value) ? DEFAULT_MAX_RETRY_ATTEMPT_VALUE : Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["echoInterval"];
EchoInterval = string.IsNullOrEmpty(value) ? DEFAULT_ECHO_INTERVAL_VALUE : Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["echoDelay"];
EchoDelay = string.IsNullOrEmpty(value) ? DEFAULT_ECHO_DELAY_VALUE : Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["stateProviderPath"];
StateProviderPath = string.IsNullOrEmpty(value) ? DEFAULT_STATE_PROVIDER_DIRECTORY : Convert.ToString(value);
value = ConfigurationManager.AppSettings["fixturesStateFilePath"];
FixturesStateFilePath = string.IsNullOrEmpty(value) ? DEFAULT_FIXTURES_STATE_FILE : Convert.ToString(value);
value = ConfigurationManager.AppSettings["fixturesStateAutoStoreInterval"];
FixturesStateAutoStoreInterval = string.IsNullOrEmpty(value)
? DEFAULT_FIXTURES_STATE_AUTO_STORE_INTERVAL_VALUE
: int.Parse(value);
value = ConfigurationManager.AppSettings["marketFiltersDirectory"];
MarketFiltersDirectory = string.IsNullOrEmpty(value) ? DEFAULT_MARKET_STATE_MANAGER_DIRECTORY : Convert.ToString(value);
value = ConfigurationManager.AppSettings["cacheExpiryInMins"];
CacheExpiryInMins = string.IsNullOrEmpty(value) ? DEFAULT_CACHE_EXPIRY_MINUTES_VALUE : Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["deltaRuleEnabled"];
DeltaRuleEnabled = string.IsNullOrEmpty(value) ? DEFAULT_ENABLE_DELTA_RULE : Convert.ToBoolean(value);
value = ConfigurationManager.AppSettings["statsEnabled"];
StatsEnabled = string.IsNullOrEmpty(value) ? DEFAULT_USE_STATS : Convert.ToBoolean(value);
value = ConfigurationManager.AppSettings["useSupervisor"];
UseSupervisor = string.IsNullOrEmpty(value) ? DEFAULT_USE_SUPERVISOR : Convert.ToBoolean(value);
value = ConfigurationManager.AppSettings["processingLockTimeOutInSecs"];
ProcessingLockTimeOutInSecs = string.IsNullOrEmpty(value) ? DEFAULT_PROCESSING_LOCK_TIMEOUT : Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["supervisorStatePath"];
SupervisorStatePath = string.IsNullOrEmpty(value) ? DEFAULT_SUPERVISOR_STATE_PATH : value;
value = ConfigurationManager.AppSettings["preMatchSuspensionBeforeStartTimeInMins"];
PreMatchSuspensionBeforeStartTimeInMins = string.IsNullOrEmpty(value)
? DEFAULT_PREMATCH_SUSPENSION_BEFORE_STARTTIME_IN_MINS
: int.Parse(value);
value = ConfigurationManager.AppSettings["startStreamingTimeoutInSeconds"];
StartStreamingTimeoutInSeconds = string.IsNullOrEmpty(value)
? DEFAULT_START_STREAMING_TIMEOUT
: int.Parse(value);
value = ConfigurationManager.AppSettings["startStreamingAttempts"];
StartStreamingAttempts = string.IsNullOrEmpty(value)
? DEFAULT_START_STREAMING_ATTEMPTS
: int.Parse(value);
value = ConfigurationManager.AppSettings["disablePrematchSuspensionOnDisconnection"];
DisablePrematchSuspensionOnDisconnection = string.IsNullOrEmpty(value) ? false : Convert.ToBoolean(value);
value = ConfigurationManager.AppSettings["skipRulesOnError"];
SkipRulesOnError = string.IsNullOrEmpty(value) ? false : Convert.ToBoolean(value);
value = ConfigurationManager.AppSettings["logDetailedMarketRules"];
LogDetailedMarketRules = string.IsNullOrEmpty(value) && Convert.ToBoolean(value);
value = ConfigurationManager.AppSettings["streamSafetyThreshold"];
StreamSafetyThreshold = string.IsNullOrEmpty(value) ? DEFAULT_STREAM_THRESHOLD : Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["allowFixtureStreamingInSetupMode"];
AllowFixtureStreamingInSetupMode = !string.IsNullOrEmpty(value) && Convert.ToBoolean(value);
value = ConfigurationManager.AppSettings["isSdkServiceCacheEnabled"];
IsSdkServiceCacheEnabled = !string.IsNullOrEmpty(value) && Convert.ToBoolean(value);
value = ConfigurationManager.AppSettings["maxFixtureUpdateDelayInSeconds"];
maxFixtureUpdateDelayInSeconds = string.IsNullOrEmpty(value)
? DEFAULT_FIXTURE_TIMESTAMP_DIFFERENCE_VALUE
: Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["delayedFixtureRecoveryAttemptSchedule"];
delayedFixtureRecoveryAttemptSchedule = string.IsNullOrEmpty(value)
? DEFAULT_FIXTURE_RECOVER_INTERVAL
: Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["maxInErroredState"];
MaxInErroredState = string.IsNullOrEmpty(value)
? DEFAULT_MAX_IN_ERRORED_STATE
: Convert.ToInt32(value);
value = ConfigurationManager.AppSettings["autoReconnect"];
AutoReconnect = !string.IsNullOrEmpty(value) && Convert.ToBoolean(value);
LogAll();
}
private void LogAll()
{
var properties = this.GetType().GetProperties();
var logString = new StringBuilder();
foreach (var propertyInfo in properties)
{
logString.AppendLine($"Setting {propertyInfo.Name}={propertyInfo.GetValue(this)}");
}
//it's not defined at the class level because it's only used once during lifetime of the class
var logger = LogManager.GetLogger(typeof(Settings));
logger.Info(logString.ToString());
}
public string MarketFiltersDirectory { get; private set; }
public int CacheExpiryInMins { get; private set; }
public string User { get; private set; }
public string Password { get; private set; }
public string Url { get; private set; }
public int FixtureCheckerFrequency { get; private set; }
public int StartingRetryDelay { get; private set; }
public int MaxRetryDelay { get; private set; }
public int MaxRetryAttempts { get; private set; }
public int EchoInterval { get; private set; }
public int EchoDelay { get; private set; }
public string FixturesStateFilePath { get; private set; }
public int FixturesStateAutoStoreInterval { get; private set; }
public bool DeltaRuleEnabled { get; private set; }
public int FixtureCreationConcurrency { get; private set; }
public bool StatsEnabled { get; private set; }
public string StateProviderPath { get; private set; }
public int ProcessingLockTimeOutInSecs { get; private set; }
public string SupervisorStatePath { get; private set; }
public bool DisablePrematchSuspensionOnDisconnection { get; private set; }
public int PreMatchSuspensionBeforeStartTimeInMins { get; private set; }
public int StartStreamingTimeoutInSeconds { get; private set; }
public int StartStreamingAttempts { get; private set; }
public int MaxInErroredState { get; private set; }
public bool AllowFixtureStreamingInSetupMode { get; }
public bool IsSdkServiceCacheEnabled { get; }
public bool SkipRulesOnError { get; private set; }
public int StreamSafetyThreshold { get; private set; }
public bool UseSupervisor { get; private set; }
public int maxFixtureUpdateDelayInSeconds { get; private set; }
public bool AutoReconnect { get; private set; }
public bool LogDetailedMarketRules { get; private set; }
public int delayedFixtureRecoveryAttemptSchedule { get; private set; }
}
}
| |
//
// Microsoft.TeamFoundation.VersionControl.Client.PendingChange
//
// Authors:
// Joel Reed (joelwreed@gmail.com)
// Ventsislav Mladenov (ventsislav.mladenov@gmail.com)
//
// Copyright (C) 2013 Joel Reed, Ventsislav Mladenov
//
// 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 System.Text;
using System.Security.Cryptography;
using System.Xml.Linq;
using Microsoft.TeamFoundation.VersionControl.Client.Enums;
using Microsoft.TeamFoundation.VersionControl.Client.Helpers;
namespace Microsoft.TeamFoundation.VersionControl.Client.Objects
{
//<s:complexType name="PendingChange">
// <s:sequence>
// <s:element minOccurs="0" maxOccurs="1" name="MergeSources" type="tns:ArrayOfMergeSource"/>
// <s:element minOccurs="0" maxOccurs="1" name="PropertyValues" type="tns:ArrayOfPropertyValue"/>
// </s:sequence>
// <s:attribute default="0" name="chgEx" type="s:int"/>
// <s:attribute default="None" name="chg" type="tns:ChangeType"/>
// <s:attribute name="date" type="s:dateTime" use="required"/>
// <s:attribute default="0" name="did" type="s:int"/>
// <s:attribute default="Any" name="type" type="tns:ItemType"/>
// <s:attribute default="-2" name="enc" type="s:int"/>
// <s:attribute default="0" name="itemid" type="s:int"/>
// <s:attribute name="local" type="s:string"/>
// <s:attribute default="None" name="lock" type="tns:LockLevel"/>
// <s:attribute name="item" type="s:string"/>
// <s:attribute name="srclocal" type="s:string"/>
// <s:attribute name="srcitem" type="s:string"/>
// <s:attribute default="0" name="svrfm" type="s:int"/>
// <s:attribute default="0" name="sdi" type="s:int"/>
// <s:attribute default="0" name="ver" type="s:int"/>
// <s:attribute name="hash" type="s:base64Binary"/>
// <s:attribute default="-1" name="len" type="s:long"/>
// <s:attribute name="uhash" type="s:base64Binary"/>
// <s:attribute default="0" name="pcid" type="s:int"/>
// <s:attribute name="durl" type="s:string"/>
// <s:attribute name="shelvedurl" type="s:string"/>
// <s:attribute name="ct" type="s:int" use="required"/>
//</s:complexType>
public class PendingChange
{
internal static PendingChange FromXml(XElement element)
{
PendingChange change = new PendingChange();
change.ServerItem = element.GetAttribute("item");
change.LocalItem = TfsPath.ToPlatformPath(element.GetAttribute("local"));
change.ItemId = GeneralHelper.XmlAttributeToInt(element.GetAttribute("itemid"));
change.Encoding = GeneralHelper.XmlAttributeToInt(element.GetAttribute("enc"));
change.Version = GeneralHelper.XmlAttributeToInt(element.GetAttribute("ver"));
change.CreationDate = DateTime.Parse(element.GetAttribute("date"));
change.Hash = GeneralHelper.ToByteArray(element.GetAttribute("hash"));
change.uploadHashValue = GeneralHelper.ToByteArray(element.GetAttribute("uhash"));
change.ItemType = EnumHelper.ParseItemType(element.GetAttribute("type"));
change.DownloadUrl = element.GetAttribute("durl");
change.ChangeType = EnumHelper.ParseChangeType(element.GetAttribute("chg"));
if (change.ChangeType == ChangeType.Edit)
change.ItemType = ItemType.File;
return change;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("PendingChange instance ");
sb.Append(GetHashCode());
sb.Append("\n ServerItem: ");
sb.Append(ServerItem);
sb.Append("\n LocalItem: ");
sb.Append(LocalItem);
sb.Append("\n ItemId: ");
sb.Append(ItemId);
sb.Append("\n Encoding: ");
sb.Append(Encoding);
sb.Append("\n Creation Date: ");
sb.Append(CreationDate);
sb.Append("\n ChangeType: ");
sb.Append(ChangeType);
sb.Append("\n ItemType: ");
sb.Append(ItemType);
sb.Append("\n Download URL: ");
sb.Append(DownloadUrl);
return sb.ToString();
}
internal void UpdateUploadHashValue()
{
using (FileStream stream = new FileStream(LocalItem, FileMode.Open, FileAccess.Read))
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
md5.ComputeHash(stream);
uploadHashValue = md5.Hash;
}
}
public byte[] Hash { get; set; }
private byte[] uploadHashValue;
public byte[] UploadHashValue
{
get
{
if (uploadHashValue == null)
UpdateUploadHashValue();
return uploadHashValue;
}
}
public DateTime CreationDate { get; private set; }
public int Encoding { get; private set; }
public string LocalItem { get; private set; }
public int ItemId { get; private set; }
public ItemType ItemType { get; private set; }
public int Version { get; private set; }
public bool IsAdd
{
get { return (ChangeType & ChangeType.Add) == ChangeType.Add; }
}
public bool IsBranch
{
get { return (ChangeType & ChangeType.Branch) == ChangeType.Branch; }
}
public bool IsDelete
{
get { return (ChangeType & ChangeType.Delete) == ChangeType.Delete; }
}
public bool IsEdit
{
get { return (ChangeType & ChangeType.Edit) == ChangeType.Edit; }
}
public bool IsEncoding
{
get { return (ChangeType & ChangeType.Encoding) == ChangeType.Encoding; }
}
public bool IsLock
{
get { return (ChangeType & ChangeType.Lock) == ChangeType.Lock; }
}
public bool IsMerge
{
get { return (ChangeType & ChangeType.Merge) == ChangeType.Merge; }
}
public bool IsRename
{
get { return (ChangeType & ChangeType.Rename) == ChangeType.Rename; }
}
public ChangeType ChangeType { get; private set; }
public string ServerItem { get; private set; }
public string DownloadUrl { get; set; }
static public string GetLocalizedStringForChangeType(ChangeType changeType)
{
return changeType.ToString();
}
}
}
| |
namespace Aardvark.Base.Coder
{
// AUTO GENERATED CODE - DO NOT CHANGE!
public partial class StreamCodeWriter
{
#region Vectors
public void Write(V2i x)
{
Write(x.X); Write(x.Y);
}
public void Write(V2l x)
{
Write(x.X); Write(x.Y);
}
public void Write(V2f x)
{
Write(x.X); Write(x.Y);
}
public void Write(V2d x)
{
Write(x.X); Write(x.Y);
}
public void Write(V3i x)
{
Write(x.X); Write(x.Y); Write(x.Z);
}
public void Write(V3l x)
{
Write(x.X); Write(x.Y); Write(x.Z);
}
public void Write(V3f x)
{
Write(x.X); Write(x.Y); Write(x.Z);
}
public void Write(V3d x)
{
Write(x.X); Write(x.Y); Write(x.Z);
}
public void Write(V4i x)
{
Write(x.X); Write(x.Y); Write(x.Z); Write(x.W);
}
public void Write(V4l x)
{
Write(x.X); Write(x.Y); Write(x.Z); Write(x.W);
}
public void Write(V4f x)
{
Write(x.X); Write(x.Y); Write(x.Z); Write(x.W);
}
public void Write(V4d x)
{
Write(x.X); Write(x.Y); Write(x.Z); Write(x.W);
}
#endregion
#region Matrices
public void Write(M22i x)
{
Write(x.M00); Write(x.M01);
Write(x.M10); Write(x.M11);
}
public void Write(M22l x)
{
Write(x.M00); Write(x.M01);
Write(x.M10); Write(x.M11);
}
public void Write(M22f x)
{
Write(x.M00); Write(x.M01);
Write(x.M10); Write(x.M11);
}
public void Write(M22d x)
{
Write(x.M00); Write(x.M01);
Write(x.M10); Write(x.M11);
}
public void Write(M23i x)
{
Write(x.M00); Write(x.M01); Write(x.M02);
Write(x.M10); Write(x.M11); Write(x.M12);
}
public void Write(M23l x)
{
Write(x.M00); Write(x.M01); Write(x.M02);
Write(x.M10); Write(x.M11); Write(x.M12);
}
public void Write(M23f x)
{
Write(x.M00); Write(x.M01); Write(x.M02);
Write(x.M10); Write(x.M11); Write(x.M12);
}
public void Write(M23d x)
{
Write(x.M00); Write(x.M01); Write(x.M02);
Write(x.M10); Write(x.M11); Write(x.M12);
}
public void Write(M33i x)
{
Write(x.M00); Write(x.M01); Write(x.M02);
Write(x.M10); Write(x.M11); Write(x.M12);
Write(x.M20); Write(x.M21); Write(x.M22);
}
public void Write(M33l x)
{
Write(x.M00); Write(x.M01); Write(x.M02);
Write(x.M10); Write(x.M11); Write(x.M12);
Write(x.M20); Write(x.M21); Write(x.M22);
}
public void Write(M33f x)
{
Write(x.M00); Write(x.M01); Write(x.M02);
Write(x.M10); Write(x.M11); Write(x.M12);
Write(x.M20); Write(x.M21); Write(x.M22);
}
public void Write(M33d x)
{
Write(x.M00); Write(x.M01); Write(x.M02);
Write(x.M10); Write(x.M11); Write(x.M12);
Write(x.M20); Write(x.M21); Write(x.M22);
}
public void Write(M34i x)
{
Write(x.M00); Write(x.M01); Write(x.M02); Write(x.M03);
Write(x.M10); Write(x.M11); Write(x.M12); Write(x.M13);
Write(x.M20); Write(x.M21); Write(x.M22); Write(x.M23);
}
public void Write(M34l x)
{
Write(x.M00); Write(x.M01); Write(x.M02); Write(x.M03);
Write(x.M10); Write(x.M11); Write(x.M12); Write(x.M13);
Write(x.M20); Write(x.M21); Write(x.M22); Write(x.M23);
}
public void Write(M34f x)
{
Write(x.M00); Write(x.M01); Write(x.M02); Write(x.M03);
Write(x.M10); Write(x.M11); Write(x.M12); Write(x.M13);
Write(x.M20); Write(x.M21); Write(x.M22); Write(x.M23);
}
public void Write(M34d x)
{
Write(x.M00); Write(x.M01); Write(x.M02); Write(x.M03);
Write(x.M10); Write(x.M11); Write(x.M12); Write(x.M13);
Write(x.M20); Write(x.M21); Write(x.M22); Write(x.M23);
}
public void Write(M44i x)
{
Write(x.M00); Write(x.M01); Write(x.M02); Write(x.M03);
Write(x.M10); Write(x.M11); Write(x.M12); Write(x.M13);
Write(x.M20); Write(x.M21); Write(x.M22); Write(x.M23);
Write(x.M30); Write(x.M31); Write(x.M32); Write(x.M33);
}
public void Write(M44l x)
{
Write(x.M00); Write(x.M01); Write(x.M02); Write(x.M03);
Write(x.M10); Write(x.M11); Write(x.M12); Write(x.M13);
Write(x.M20); Write(x.M21); Write(x.M22); Write(x.M23);
Write(x.M30); Write(x.M31); Write(x.M32); Write(x.M33);
}
public void Write(M44f x)
{
Write(x.M00); Write(x.M01); Write(x.M02); Write(x.M03);
Write(x.M10); Write(x.M11); Write(x.M12); Write(x.M13);
Write(x.M20); Write(x.M21); Write(x.M22); Write(x.M23);
Write(x.M30); Write(x.M31); Write(x.M32); Write(x.M33);
}
public void Write(M44d x)
{
Write(x.M00); Write(x.M01); Write(x.M02); Write(x.M03);
Write(x.M10); Write(x.M11); Write(x.M12); Write(x.M13);
Write(x.M20); Write(x.M21); Write(x.M22); Write(x.M23);
Write(x.M30); Write(x.M31); Write(x.M32); Write(x.M33);
}
#endregion
#region Ranges and Boxes
public void Write(Range1b x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Range1sb x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Range1s x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Range1us x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Range1i x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Range1ui x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Range1l x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Range1ul x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Range1f x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Range1d x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Box2i x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Box2l x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Box2f x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Box2d x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Box3i x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Box3l x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Box3f x)
{
Write(x.Min); Write(x.Max);
}
public void Write(Box3d x)
{
Write(x.Min); Write(x.Max);
}
#endregion
#region Colors
public void Write(C3b c)
{
Write(c.R); Write(c.G); Write(c.B);
}
public void Write(C3us c)
{
Write(c.R); Write(c.G); Write(c.B);
}
public void Write(C3ui c)
{
Write(c.R); Write(c.G); Write(c.B);
}
public void Write(C3f c)
{
Write(c.R); Write(c.G); Write(c.B);
}
public void Write(C3d c)
{
Write(c.R); Write(c.G); Write(c.B);
}
public void Write(C4b c)
{
Write(c.R); Write(c.G); Write(c.B); Write(c.A);
}
public void Write(C4us c)
{
Write(c.R); Write(c.G); Write(c.B); Write(c.A);
}
public void Write(C4ui c)
{
Write(c.R); Write(c.G); Write(c.B); Write(c.A);
}
public void Write(C4f c)
{
Write(c.R); Write(c.G); Write(c.B); Write(c.A);
}
public void Write(C4d c)
{
Write(c.R); Write(c.G); Write(c.B); Write(c.A);
}
#endregion
}
}
| |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Org.Apache.REEF.Common.Catalog;
using Org.Apache.REEF.Driver;
using Org.Apache.REEF.Driver.Bridge;
using Org.Apache.REEF.Driver.Evaluator;
using Org.Apache.REEF.IMRU.API;
using Org.Apache.REEF.IMRU.OnREEF.Driver;
using Org.Apache.REEF.IMRU.OnREEF.Driver.StateMachine;
using Org.Apache.REEF.IMRU.OnREEF.Parameters;
using Org.Apache.REEF.IO.PartitionedData;
using Org.Apache.REEF.Network.Group.Config;
using Org.Apache.REEF.Network.Group.Driver;
using Org.Apache.REEF.Network.Group.Driver.Impl;
using Org.Apache.REEF.Tang.Annotations;
using Org.Apache.REEF.Tang.Formats;
using Org.Apache.REEF.Tang.Implementations.Configuration;
using Org.Apache.REEF.Tang.Implementations.Tang;
using Org.Apache.REEF.Tang.Interface;
using Org.Apache.REEF.Tang.Util;
using Xunit;
namespace Org.Apache.REEF.IMRU.Tests
{
public class ImruDriverCancelTests
{
[Fact]
[Trait("Description", "Verifies that IMRU driver handles cancel signal: changes state to Fail and throw exception with predefined message.")]
public void ImruDriverHandlesCancelledEventAfterStart()
{
var driver = TangFactory
.GetTang()
.NewInjector(GetDriverConfig<TestMapInput, TestMapOutput, TestResult, TestPartitionType>())
.GetInstance(typeof(IMRUDriver<TestMapInput, TestMapOutput, TestResult, TestPartitionType>))
as IMRUDriver<TestMapInput, TestMapOutput, TestResult, TestPartitionType>;
IDriverStarted startedEvent = null;
driver.OnNext(startedEvent);
var cancelMessage = "cancel_" + Guid.NewGuid();
var cancelTime = DateTime.Now;
IJobCancelled cancelledEvent = new JobCancelled(cancelTime, cancelMessage);
Assert.False(GetDriverState(driver).CurrentState == SystemState.Fail, "driver's state is Fail after Onstarted event");
AssertExceptionThrown<ApplicationException>(
() => driver.OnNext(cancelledEvent),
expectedExceptionMessageContent: new[] { "Job cancelled", cancelTime.ToString("u"), cancelMessage },
assertMessagePrefix: "Cancel event handler failed to throw expected exception");
var stateAfterCancel = GetDriverState(driver);
Assert.True(stateAfterCancel.CurrentState == SystemState.Fail, "invalid driver state after cancel event: expected= Fail, actual=" + stateAfterCancel.CurrentState);
}
private SystemStateMachine GetDriverState(object driver)
{
return driver.GetType()
.GetField("_systemState", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(driver) as SystemStateMachine;
}
private void AssertExceptionThrown<TException>(Action ationWithException,
IEnumerable<string> expectedExceptionMessageContent,
string assertMessagePrefix)
{
try
{
ationWithException();
Assert.True(false, assertMessagePrefix + " action did not result in any exception");
}
catch (Exception ex)
{
Assert.True(ex is TException,
string.Format("{0}: expected exception of type: {1}", assertMessagePrefix, typeof(TException)));
var missingContent = expectedExceptionMessageContent
.Where(expectedContent => !ex.Message.Contains(expectedContent));
Assert.False(
missingContent.Any(),
string.Format("{0}: Did not find missing content in exception message. Missing content: {1}, actual message: {2}", assertMessagePrefix, string.Join(" | ", missingContent), ex.Message));
}
}
/// <summary>
/// This generates empty driver configuration which can be used to construct instance of the IMRUDriver,
/// but is not functional.
/// this is used to unit test specific code path (like JobCancelledEvent in this case)
/// </summary>
private IConfiguration GetDriverConfig<TMapInput, TMapOutput, TResult, TPartitionType>()
{
var testConfig = TangFactory.GetTang().NewConfigurationBuilder()
.BindImplementation(GenericType<IPartitionedInputDataSet>.Class, GenericType<TestPartitionedInputDataSet>.Class)
.BindImplementation(GenericType<IEvaluatorRequestor>.Class, GenericType<TestEvaluatorRequestor>.Class)
.Build();
var jobDefinition = new IMRUJobDefinitionBuilder()
.SetJobName("Test")
.SetMapFunctionConfiguration(testConfig)
.SetMapInputCodecConfiguration(testConfig)
.SetUpdateFunctionCodecsConfiguration(testConfig)
.SetReduceFunctionConfiguration(testConfig)
.SetUpdateFunctionConfiguration(testConfig)
.SetPartitionedDatasetConfiguration(testConfig)
.Build();
var _configurationSerializer = new AvroConfigurationSerializer();
var overallPerMapConfig = Configurations.Merge(jobDefinition.PerMapConfigGeneratorConfig.ToArray());
var driverConfig = TangFactory.GetTang().NewConfigurationBuilder(new[]
{
DriverConfiguration.ConfigurationModule
.Set(DriverConfiguration.OnEvaluatorAllocated,
GenericType<IMRUDriver<TMapInput, TMapOutput, TResult, TPartitionType>>.Class)
.Set(DriverConfiguration.OnDriverStarted,
GenericType<IMRUDriver<TMapInput, TMapOutput, TResult, TPartitionType>>.Class)
.Set(DriverConfiguration.OnContextActive,
GenericType<IMRUDriver<TMapInput, TMapOutput, TResult, TPartitionType>>.Class)
.Set(DriverConfiguration.OnTaskCompleted,
GenericType<IMRUDriver<TMapInput, TMapOutput, TResult, TPartitionType>>.Class)
.Set(DriverConfiguration.OnEvaluatorFailed,
GenericType<IMRUDriver<TMapInput, TMapOutput, TResult, TPartitionType>>.Class)
.Set(DriverConfiguration.OnContextFailed,
GenericType<IMRUDriver<TMapInput, TMapOutput, TResult, TPartitionType>>.Class)
.Set(DriverConfiguration.OnTaskFailed,
GenericType<IMRUDriver<TMapInput, TMapOutput, TResult, TPartitionType>>.Class)
.Set(DriverConfiguration.OnTaskRunning,
GenericType<IMRUDriver<TMapInput, TMapOutput, TResult, TPartitionType>>.Class)
.Set(DriverConfiguration.CustomTraceLevel, TraceLevel.Info.ToString())
.Build(),
TangFactory.GetTang().NewConfigurationBuilder()
.BindStringNamedParam<GroupCommConfigurationOptions.DriverId>("driverId")
.BindStringNamedParam<GroupCommConfigurationOptions.MasterTaskId>(IMRUConstants.UpdateTaskName)
.BindStringNamedParam<GroupCommConfigurationOptions.GroupName>(
IMRUConstants.CommunicationGroupName)
.BindIntNamedParam<GroupCommConfigurationOptions.FanOut>(
IMRUConstants.TreeFanout.ToString(CultureInfo.InvariantCulture)
.ToString(CultureInfo.InvariantCulture))
.BindIntNamedParam<GroupCommConfigurationOptions.NumberOfTasks>(
(jobDefinition.NumberOfMappers + 1).ToString(CultureInfo.InvariantCulture))
.BindImplementation(GenericType<IGroupCommDriver>.Class, GenericType<GroupCommDriver>.Class)
.Build(),
jobDefinition.PartitionedDatasetConfiguration,
overallPerMapConfig,
jobDefinition.JobCancelSignalConfiguration
})
.BindNamedParameter(typeof(SerializedUpdateTaskStateConfiguration),
_configurationSerializer.ToString(jobDefinition.UpdateTaskStateConfiguration))
.BindNamedParameter(typeof(SerializedMapTaskStateConfiguration),
_configurationSerializer.ToString(jobDefinition.MapTaskStateConfiguration))
.BindNamedParameter(typeof(SerializedMapConfiguration),
_configurationSerializer.ToString(jobDefinition.MapFunctionConfiguration))
.BindNamedParameter(typeof(SerializedUpdateConfiguration),
_configurationSerializer.ToString(jobDefinition.UpdateFunctionConfiguration))
.BindNamedParameter(typeof(SerializedMapInputCodecConfiguration),
_configurationSerializer.ToString(jobDefinition.MapInputCodecConfiguration))
.BindNamedParameter(typeof(SerializedMapInputPipelineDataConverterConfiguration),
_configurationSerializer.ToString(jobDefinition.MapInputPipelineDataConverterConfiguration))
.BindNamedParameter(typeof(SerializedUpdateFunctionCodecsConfiguration),
_configurationSerializer.ToString(jobDefinition.UpdateFunctionCodecsConfiguration))
.BindNamedParameter(typeof(SerializedMapOutputPipelineDataConverterConfiguration),
_configurationSerializer.ToString(jobDefinition.MapOutputPipelineDataConverterConfiguration))
.BindNamedParameter(typeof(SerializedReduceConfiguration),
_configurationSerializer.ToString(jobDefinition.ReduceFunctionConfiguration))
.BindNamedParameter(typeof(SerializedResultHandlerConfiguration),
_configurationSerializer.ToString(jobDefinition.ResultHandlerConfiguration))
.BindNamedParameter(typeof(MemoryPerMapper),
jobDefinition.MapperMemory.ToString(CultureInfo.InvariantCulture))
.BindNamedParameter(typeof(MemoryForUpdateTask),
jobDefinition.UpdateTaskMemory.ToString(CultureInfo.InvariantCulture))
.BindNamedParameter(typeof(CoresPerMapper),
jobDefinition.MapTaskCores.ToString(CultureInfo.InvariantCulture))
.BindNamedParameter(typeof(CoresForUpdateTask),
jobDefinition.UpdateTaskCores.ToString(CultureInfo.InvariantCulture))
.BindNamedParameter(typeof(MaxRetryNumberInRecovery),
jobDefinition.MaxRetryNumberInRecovery.ToString(CultureInfo.InvariantCulture))
.BindNamedParameter(typeof(InvokeGC),
jobDefinition.InvokeGarbageCollectorAfterIteration.ToString(CultureInfo.InvariantCulture))
.Build();
return driverConfig;
}
internal class TestMapInput
{
[Inject]
private TestMapInput()
{
}
}
internal class TestMapOutput
{
[Inject]
private TestMapOutput()
{
}
}
internal class TestResult
{
[Inject]
private TestResult()
{
}
}
internal class TestPartitionType
{
[Inject]
private TestPartitionType()
{
}
}
/// <summary>
/// Simple Type to help with Tang injection when constructing IMRUDriver.
/// Cares minimum implementation to satisfy new driver instance for test scenarios
/// </summary>
internal class TestEvaluatorRequestor : IEvaluatorRequestor
{
public IResourceCatalog ResourceCatalog { get; private set; }
[Inject]
private TestEvaluatorRequestor()
{
}
public void Submit(IEvaluatorRequest request)
{
// for test we don't really submit evaluator request,
// but can't throw exception here as Driver calls this method before cancellation flow can be initiated.
}
public EvaluatorRequestBuilder NewBuilder()
{
var builder = Activator.CreateInstance(
typeof(EvaluatorRequestBuilder),
nonPublic: true);
return builder as EvaluatorRequestBuilder;
}
public EvaluatorRequestBuilder NewBuilder(IEvaluatorRequest request)
{
return NewBuilder();
}
}
/// <summary>
/// Simple Type to help with Tang injection when constructing IMRUDriver.
/// Cares minimum implementation to satisfy new driver instance for test scenarios
/// </summary>
internal class TestPartitionedInputDataSet : IPartitionedInputDataSet
{
public int Count { get; private set; }
public string Id { get; private set; }
[Inject]
private TestPartitionedInputDataSet()
{
}
public IEnumerator<IPartitionDescriptor> GetEnumerator()
{
return new List<IPartitionDescriptor>().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IPartitionDescriptor GetPartitionDescriptorForId(string partitionId)
{
throw new NotImplementedException();
}
}
}
}
| |
using System;
using LanguageExt;
using static LanguageExt.Prelude;
using static LanguageExt.TypeClass;
using System.Diagnostics.Contracts;
using LanguageExt.TypeClasses;
using LanguageExt.ClassInstances;
namespace LanguageExt
{
public static partial class Prelude
{
/// <summary>
/// Append an extra item to the tuple
/// </summary>
[Pure]
public static Tuple<A, B, C, D, E, F> add<A, B, C, D, E, F>(Tuple<A, B, C, D, E> self, F sixth) =>
Tuple(self.Item1, self.Item2, self.Item3, self.Item4, self.Item5, sixth);
/// <summary>
/// Semigroup append
/// </summary>
[Pure]
public static Tuple<A, B, C, D, E> append<SemiA, SemiB, SemiC, SemiD, SemiE, A, B, C, D, E>(Tuple<A, B, C, D, E> a, Tuple<A, B, C, D, E> b)
where SemiA : struct, Semigroup<A>
where SemiB : struct, Semigroup<B>
where SemiC : struct, Semigroup<C>
where SemiD : struct, Semigroup<D>
where SemiE : struct, Semigroup<E> =>
Tuple(default(SemiA).Append(a.Item1, b.Item1),
default(SemiB).Append(a.Item2, b.Item2),
default(SemiC).Append(a.Item3, b.Item3),
default(SemiD).Append(a.Item4, b.Item4),
default(SemiE).Append(a.Item5, b.Item5));
/// <summary>
/// Semigroup append
/// </summary>
[Pure]
public static A append<SemiA, A>(Tuple<A, A, A, A, A> a)
where SemiA : struct, Semigroup<A> =>
default(SemiA).Append(a.Item1,
default(SemiA).Append(a.Item2,
default(SemiA).Append(a.Item3,
default(SemiA).Append(a.Item4, a.Item5))));
/// <summary>
/// Monoid concat
/// </summary>
[Pure]
public static Tuple<A, B, C, D, E> concat<MonoidA, MonoidB, MonoidC, MonoidD, MonoidE, A, B, C, D, E>(Tuple<A, B, C, D, E> a, Tuple<A, B, C, D, E> b)
where MonoidA : struct, Monoid<A>
where MonoidB : struct, Monoid<B>
where MonoidC : struct, Monoid<C>
where MonoidD : struct, Monoid<D>
where MonoidE : struct, Monoid<E> =>
Tuple(mconcat<MonoidA, A>(a.Item1, b.Item1),
mconcat<MonoidB, B>(a.Item2, b.Item2),
mconcat<MonoidC, C>(a.Item3, b.Item3),
mconcat<MonoidD, D>(a.Item4, b.Item4),
mconcat<MonoidE, E>(a.Item5, b.Item5));
/// <summary>
/// Monoid concat
/// </summary>
[Pure]
public static A concat<MonoidA, A>(Tuple<A, A, A, A, A> a)
where MonoidA : struct, Monoid<A> =>
mconcat<MonoidA, A>(a.Item1, a.Item2, a.Item3, a.Item4, a.Item5);
/// <summary>
/// Take the first item
/// </summary>
[Pure]
public static A head<A, B, C, D, E>(Tuple<A, B, C, D, E> self) =>
self.Item1;
/// <summary>
/// Take the last item
/// </summary>
[Pure]
public static E last<A, B, C, D, E>(Tuple<A, B, C, D, E> self) =>
self.Item5;
/// <summary>
/// Take the second item onwards and build a new tuple
/// </summary>
[Pure]
public static Tuple<B, C, D, E> tail<A, B, C, D, E>(Tuple<A, B, C, D, E> self) =>
Tuple(self.Item2, self.Item3, self.Item4, self.Item5);
/// <summary>
/// Sum of the items
/// </summary>
[Pure]
public static A sum<NUM, A>(Tuple<A, A, A, A, A> self)
where NUM : struct, Num<A> =>
TypeClass.sum<NUM, FoldTuple<A>, Tuple<A, A, A, A, A>, A>(self);
/// <summary>
/// Product of the items
/// </summary>
[Pure]
public static A product<NUM, A>(Tuple<A, A, A, A, A> self)
where NUM : struct, Num<A> =>
TypeClass.product<NUM, FoldTuple<A>, Tuple<A, A, A, A, A>, A>(self);
/// <summary>
/// One of the items matches the value passed
/// </summary>
[Pure]
public static bool contains<EQ, A>(Tuple<A, A, A, A, A> self, A value)
where EQ : struct, Eq<A> =>
default(EQ).Equals(self.Item1, value) ||
default(EQ).Equals(self.Item2, value) ||
default(EQ).Equals(self.Item3, value) ||
default(EQ).Equals(self.Item4, value) ||
default(EQ).Equals(self.Item5, value);
/// <summary>
/// Map
/// </summary>
[Pure]
public static R map<A, B, C, D, E, R>(Tuple<A, B, C, D, E> self, Func<Tuple<A, B, C, D, E>, R> map) =>
map(self);
/// <summary>
/// Map
/// </summary>
[Pure]
public static R map<A, B, C, D, E, R>(Tuple<A, B, C, D, E> self, Func<A, B, C, D, E, R> map) =>
map(self.Item1, self.Item2, self.Item3, self.Item4, self.Item5);
/// <summary>
/// Tri-map to tuple
/// </summary>
[Pure]
public static Tuple<V, W, X, Y, Z> map<A, B, C, D, E, V, W, X, Y, Z>(Tuple<A, B, C, D, E> self, Func<A, V> firstMap, Func<B, W> secondMap, Func<C, X> thirdMap, Func<D, Y> fourthMap, Func<E, Z> fifthMap) =>
Tuple(firstMap(self.Item1), secondMap(self.Item2), thirdMap(self.Item3), fourthMap(self.Item4), fifthMap(self.Item5));
/// <summary>
/// First item-map to tuple
/// </summary>
[Pure]
public static Tuple<R1, B, C, D, E> mapFirst<A, B, C, D, E, R1>(Tuple<A, B, C, D, E> self, Func<A, R1> firstMap) =>
Tuple(firstMap(self.Item1), self.Item2, self.Item3, self.Item4, self.Item5);
/// <summary>
/// Second item-map to tuple
/// </summary>
[Pure]
public static Tuple<A, R2, C, D, E> mapSecond<A, B, C, D, E, R2>(Tuple<A, B, C, D, E> self, Func<B, R2> secondMap) =>
Tuple(self.Item1, secondMap(self.Item2), self.Item3, self.Item4, self.Item5);
/// <summary>
/// Third item-map to tuple
/// </summary>
[Pure]
public static Tuple<A, B, R3, D, E> mapThird<A, B, C, D, E, R3>(Tuple<A, B, C, D, E> self, Func<C, R3> thirdMap) =>
Tuple(self.Item1, self.Item2, thirdMap(self.Item3), self.Item4, self.Item5);
/// <summary>
/// Fourth item-map to tuple
/// </summary>
[Pure]
public static Tuple<A, B, C, R4, E> mapFourth<A, B, C, D, E, R4>(Tuple<A, B, C, D, E> self, Func<D, R4> fourthMap) =>
Tuple(self.Item1, self.Item2, self.Item3, fourthMap(self.Item4), self.Item5);
/// <summary>
/// Fifth item-map to tuple
/// </summary>
[Pure]
public static Tuple<A, B, C, D, R5> mapFifth<A, B, C, D, E, R5>(Tuple<A, B, C, D, E> self, Func<E, R5> fifthMap) =>
Tuple(self.Item1, self.Item2, self.Item3, self.Item4, fifthMap(self.Item5));
/// <summary>
/// Iterate
/// </summary>
public static Unit iter<A, B, C, D, E>(Tuple<A, B, C, D, E> self, Action<A, B, C, D, E> func)
{
func(self.Item1, self.Item2, self.Item3, self.Item4, self.Item5);
return Unit.Default;
}
/// <summary>
/// Iterate
/// </summary>
public static Unit iter<A, B, C, D, E>(Tuple<A, B, C, D, E> self, Action<A> first, Action<B> second, Action<C> third, Action<D> fourth, Action<E> fifth)
{
first(self.Item1);
second(self.Item2);
third(self.Item3);
fourth(self.Item4);
fifth(self.Item5);
return Unit.Default;
}
/// <summary>
/// Fold
/// </summary>
[Pure]
public static S fold<A, B, C, D, E, S>(Tuple<A, B, C, D, E> self, S state, Func<S, A, B, C, D, E, S> fold) =>
fold(state, self.Item1, self.Item2, self.Item3, self.Item4, self.Item5);
/// <summary>
/// Fold
/// </summary>
[Pure]
public static S quintFold<A, B, C, D, E, S>(Tuple<A, B, C, D, E> self, S state, Func<S, A, S> firstFold, Func<S, B, S> secondFold, Func<S, C, S> thirdFold, Func<S, D, S> fourthFold, Func<S, E, S> fifthFold) =>
fifthFold(fourthFold(thirdFold(secondFold(firstFold(state, self.Item1), self.Item2), self.Item3), self.Item4), self.Item5);
/// <summary>
/// Fold back
/// </summary>
[Pure]
public static S quintFoldBack<A, B, C, D, E, S>(Tuple<A, B, C, D, E> self, S state, Func<S, E, S> firstFold, Func<S, D, S> secondFold, Func<S, C, S> thirdFold, Func<S, B, S> fourthFold, Func<S, A, S> fifthFold) =>
fifthFold(fourthFold(thirdFold(secondFold(firstFold(state, self.Item5), self.Item4), self.Item3), self.Item2), self.Item1);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.IO;
//using UnityStandardAssets.ImageEffects;
/// <summary>
/// Copyright (c) 2016 Eric Zhu
/// </summary>
namespace GreatArcStudios
{
/// <summary>
/// The pause menu manager. You can extend this to make your own. Everything is pretty modular, so creating you own based off of this should be easy. Thanks for downloading and good luck!
/// </summary>
public class PauseManager : MonoBehaviour
{
/// <summary>
/// This is the main panel holder, which holds the main panel and should be called "main panel"
/// </summary>
public GameObject MainPanel;
/// <summary>
/// This is the video panel holder, which holds all of the controls for the video panel and should be called "vid panel"
/// </summary>
public GameObject VidPanel;
/// <summary>
/// This is the audio panel holder, which holds all of the silders for the audio panel and should be called "audio panel"
/// </summary>
public GameObject AudioPanel;
/// <summary>
/// This is the credits panel holder, which holds all of the silders for the audio panel and should be called "credits panel"
/// </summary>
public GameObject CreditsPanel;
/// <summary>
/// These are the game objects with the title texts like "Pause menu" and "Game Title"
/// </summary>
public GameObject TitleTexts;
/// <summary>
/// The mask that makes the scene darker
/// </summary>
public GameObject Mask;
/// <summary>
/// Audio Panel animator
/// </summary>
public Animator AudioPanelAnimator;
/// <summary>
/// Video Panel animator
/// </summary>
public Animator VidPanelAnimator;
/// <summary>
/// Quit Panel animator
/// </summary>
public Animator QuitPanelAnimator;
/// <summary>
/// Credits Panel animator
/// </summary>
public Animator CreditsPanelAnimator;
/// <summary>
/// Pause menu text
/// </summary>
public Text PauseMenu;
/// <summary>
/// Main menu level string used for loading the main menu. This means you'll need to type in the editor text box, the name of the main menu level, ie: "mainmenu";
/// </summary>
public String MainMenu;
//DOF script name
/// <summary>
/// The Depth of Field script name, ie: "DepthOfField". You can leave this blank in the editor, but will throw a null refrence exception, which is harmless.
/// </summary>
public String DofScriptName;
/// <summary>
/// The Ambient Occlusion script name, ie: "AmbientOcclusion". You can leave this blank in the editor, but will throw a null refrence exception, which is harmless.
/// </summary>
public String AoScriptName;
/// <summary>
/// The main camera, assign this through the editor.
/// </summary>
public Camera MainCam;
internal static Camera MainCamShared;
/// <summary>
/// The main camera game object, assign this through the editor.
/// </summary>
public GameObject MainCamObj;
/// <summary>
/// The terrain detail density float. It's only public because you may want to adjust it in editor
/// </summary>
public float DetailDensity;
/// <summary>
/// Timescale value. The defualt is 1 for most games. You may want to change it if you are pausing the game in a slow motion situation
/// </summary>
public float TimeScale = 1f;
/// <summary>
/// One terrain variable used if you have a terrain plugin like rtp.
/// </summary>
public Terrain Terrain;
/// <summary>
/// Other terrain variable used if you want to have an option to target low end harware.
/// </summary>
public Terrain SimpleTerrain;
/// <summary>
/// Inital shadow distance
/// </summary>
internal static float ShadowDistIni;
/// <summary>
/// Inital render distance
/// </summary>
internal static float RenderDistIni;
/// <summary>
/// Inital AA quality 2, 4, or 8
/// </summary>
internal static float AaQualIni;
/// <summary>
/// Inital terrain detail density
/// </summary>
internal static float DensityIni;
/// <summary>
/// Amount of trees that are acutal meshes
/// </summary>
internal static float TreeMeshAmtIni;
/// <summary>
/// Inital fov
/// </summary>
internal static float FovIni;
/// <summary>
/// Inital msaa amount
/// </summary>
internal static int MsaaIni;
/// <summary>
/// Inital vsync count, the Unity docs say,
/// <code>
/// //This will set the game to have one VSync per frame
/// QualitySettings.vSyncCount = 1;
/// </code>
/// <code>
/// //This will disable vsync
/// QualitySettings.vSyncCount = 0;
/// </code>
/// </summary>
internal static int VsyncIni;
/// <summary>
/// AA drop down menu.
/// </summary>
public Dropdown AaCombo;
/// <summary>
/// Aniso drop down menu.
/// </summary>
public Dropdown AfCombo;
public Slider FovSlider;
public Slider ModelQualSlider;
public Slider TerrainQualSlider;
public Slider HighQualTreeSlider;
public Slider RenderDistSlider;
public Slider TerrainDensitySlider;
public Slider ShadowDistSlider;
public Slider AudioMasterSlider;
public Slider AudioMusicSlider;
public Slider AudioEffectsSlider;
public Slider MasterTexSlider;
public Slider ShadowCascadesSlider;
public Toggle VSyncToggle;
public Toggle AoToggle;
public Toggle DofToggle;
public Toggle FullscreenToggle;
/// <summary>
/// The preset text label.
/// </summary>
public Text PresetLabel;
/// <summary>
/// Resolution text label.
/// </summary>
public Text ResolutionLabel;
/// <summary>
/// Lod bias float array. You should manually assign these based on the quality level.
/// </summary>
public float[] LodBias;
/// <summary>
/// Shadow distance array. You should manually assign these based on the quality level.
/// </summary>
public float[] ShadowDist;
/// <summary>
/// An array of music audio sources
/// </summary>
public AudioSource[] Music;
/// <summary>
/// An array of sound effect audio sources
/// </summary>
public AudioSource[] Effects;
/// <summary>
/// An array of the other UI elements, which is used for disabling the other elements when the game is paused.
/// </summary>
public GameObject[] OtherUiElements;
/// <summary>
/// Editor boolean for hardcoding certain video settings. It will allow you to use the values defined in LOD Bias and Shadow Distance
/// </summary>
public Boolean HardCodeSomeVideoSettings;
/// <summary>
/// Boolean for turning on simple terrain
/// </summary>
public Boolean UseSimpleTerrain;
public static Boolean ReadUseSimpleTerrain;
/// <summary>
/// Event system
/// </summary>
public EventSystem UiEventSystem;
/// <summary>
/// Defualt selected on the video panel
/// </summary>
public GameObject DefualtSelectedVideo;
/// <summary>
/// Defualt selected on the video panel
/// </summary>
public GameObject DefualtSelectedAudio;
/// <summary>
/// Defualt selected on the video panel
/// </summary>
public GameObject DefualtSelectedMain;
public GameObject DefualtSelectedCredits;
//last music multiplier; this should be a value between 0-1
internal static float LastMusicMult;
//last audio multiplier; this should be a value between 0-1
internal static float LastAudioMult;
//Initial master volume
internal static float BeforeMaster;
//last texture limit
internal static int LastTexLimit;
//int for amount of effects
private int _audioEffectAmt = 0;
//Inital audio effect volumes
private float[] _beforeEffectVol;
//Initial music volume
private float _beforeMusic;
//Preset level
private int _currentLevel;
//Resoutions
private Resolution[] _allRes;
//Camera dof script
private MonoBehaviour _tempScript;
//Presets
private String[] _presets;
//Fullscreen Boolean
private Boolean _isFullscreen;
//current resoultion
internal static Resolution CurrentRes;
//Last resoultion
private Resolution _beforeRes;
//last shadow cascade value
internal static int LastShadowCascade;
public static Boolean AoBool;
public static Boolean DofBool;
private Boolean _lastAoBool;
private Boolean _lastDofBool;
public static Terrain ReadTerrain;
public static Terrain ReadSimpleTerrain;
private SaveSettings _saveSettings = new SaveSettings();
private Terrain CurrentTerrain
{
get
{
return UseSimpleTerrain ? SimpleTerrain : Terrain;
}
}
/*
//Color fade duration value
//public float crossFadeDuration;
//custom color
//public Color _customColor;
//Animation clips
private AnimationClip audioIn;
private AnimationClip audioOut;
public AnimationClip vidIn;
public AnimationClip vidOut;
public AnimationClip mainIn;
public AnimationClip mainOut;
*/
//Blur Variables
//Blur Effect Script (using the standard image effects package)
//public Blur blurEffect;
//Blur Effect Shader (should be the one that came with the package)
//public Shader blurEffectShader;
//Boolean for if the blur effect was originally enabled
//public Boolean blurBool;
/// <summary>
/// The start method; you will need to place all of your inital value getting/setting here.
/// </summary>
public void Start()
{
ReadUseSimpleTerrain = UseSimpleTerrain;
if (UseSimpleTerrain)
{
ReadSimpleTerrain = SimpleTerrain;
}
else
{
ReadTerrain = Terrain;
}
MainCamShared = MainCam;
//Set the lastmusicmult and last audiomult
LastMusicMult = AudioMusicSlider.value;
LastAudioMult = AudioEffectsSlider.value;
//Set the first selected item
UiEventSystem.firstSelectedGameObject = DefualtSelectedMain;
//Get the presets from the quality settings
_presets = QualitySettings.names;
PresetLabel.text = _presets[QualitySettings.GetQualityLevel()].ToString();
_currentLevel = QualitySettings.GetQualityLevel();
//Get the current resoultion, if the game is in fullscreen, and set the label to the original resolution
_allRes = Screen.resolutions;
CurrentRes.width = Screen.width;
CurrentRes.height = Screen.height;
//Debug.Log("ini res" + currentRes);
ResolutionLabel.text = Screen.width.ToString() + " x " + Screen.height.ToString();
_isFullscreen = Screen.fullScreen;
//get initial screen effect bools
_lastAoBool = AoToggle.isOn;
_lastDofBool = DofToggle.isOn;
//get all specified audio source volumes
_beforeEffectVol = new float[_audioEffectAmt];
BeforeMaster = AudioListener.volume;
//get all ini values
AaQualIni = QualitySettings.antiAliasing;
RenderDistIni = MainCam.farClipPlane;
ShadowDistIni = QualitySettings.shadowDistance;
FovIni = MainCam.fieldOfView;
MsaaIni = QualitySettings.antiAliasing;
VsyncIni = QualitySettings.vSyncCount;
//enable titles
TitleTexts.SetActive(true);
//Find terrain
Terrain = Terrain.activeTerrain;
//Disable other panels
MainPanel.SetActive(false);
VidPanel.SetActive(false);
AudioPanel.SetActive(false);
CreditsPanel.SetActive(false);
//Enable mask
Mask.SetActive(false);
//set last texture limit
LastTexLimit = QualitySettings.masterTextureLimit;
//set last shadow cascade
LastShadowCascade = QualitySettings.shadowCascades;
try
{
_saveSettings.LoadGameSettings();
}
catch
{
Debug.Log("Game settings not found in: " + Application.persistentDataPath + "/" + _saveSettings.FileName);
_saveSettings.SaveGameSettings();
}
try
{
DensityIni = Terrain.activeTerrain.detailObjectDensity;
}
catch
{
if (Terrain = null)
{
Debug.Log("Terrain Not Assigned");
}
}
//set the blur boolean to false;
//blurBool = false;
//Add the blur effect
/*mainCamObj.AddComponent(typeof(Blur));
blurEffect = (Blur)mainCamObj.GetComponent(typeof(Blur));
blurEffect.blurShader = blurEffectShader;
blurEffect.enabled = false; */
}
/// <summary>
/// Restart the level by loading the loaded level.
/// </summary>
public void Restart()
{
Application.LoadLevel(Application.loadedLevel);
UiEventSystem.firstSelectedGameObject = DefualtSelectedMain;
Time.timeScale = TimeScale;
}
/// <summary>
/// Method to resume the game, so disable the pause menu and re-enable all other ui elements
/// </summary>
public void Resume()
{
Time.timeScale = TimeScale;
MainPanel.SetActive(false);
VidPanel.SetActive(false);
AudioPanel.SetActive(false);
TitleTexts.SetActive(false);
Mask.SetActive(false);
for (int i = 0; i < OtherUiElements.Length; i++)
{
OtherUiElements[i].gameObject.SetActive(true);
}
/* if (blurBool == false)
{
blurEffect.enabled = false;
}
else
{
//if you want to add in your own stuff do so here
return;
} */
}
/// <summary>
/// All the methods relating to qutting should be called here.
/// </summary>
public void QuitOptions()
{
VidPanel.SetActive(false);
AudioPanel.SetActive(false);
QuitPanelAnimator.enabled = true;
QuitPanelAnimator.Play("QuitPanelIn");
}
/// <summary>
/// Method to quit the game. Call methods such as auto saving before qutting here.
/// </summary>
public void QuitGame()
{
Application.Quit();
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#endif
}
/// <summary>
/// Cancels quittting by playing an animation.
/// </summary>
public void QuitCancel()
{
QuitPanelAnimator.Play("QuitPanelOut");
}
/// <summary>
///Loads the main menu scene.
/// </summary>
public void ReturnToMenu()
{
Application.LoadLevel(MainMenu);
UiEventSystem.SetSelectedGameObject(DefualtSelectedMain);
}
// Update is called once per frame
/// <summary>
/// The update method. This mainly searches for the user pressing the escape key.
/// </summary>
public void Update()
{
ReadUseSimpleTerrain = UseSimpleTerrain;
UseSimpleTerrain = ReadUseSimpleTerrain;
//colorCrossfade();
if (VidPanel.active == true)
{
PauseMenu.text = "Video Menu";
}
else if (AudioPanel.active == true)
{
PauseMenu.text = "Audio Menu";
}
else if (MainPanel.active == true)
{
PauseMenu.text = "Pause Menu";
}
if (Input.GetKeyDown(KeyCode.Escape) && MainPanel.active == false)
{
UiEventSystem.SetSelectedGameObject(DefualtSelectedMain);
MainPanel.SetActive(true);
VidPanel.SetActive(false);
AudioPanel.SetActive(false);
TitleTexts.SetActive(true);
Mask.SetActive(true);
Time.timeScale = 0;
for (int i = 0; i < OtherUiElements.Length; i++)
{
OtherUiElements[i].gameObject.SetActive(false);
}
/* if (blurBool == false)
{
blurEffect.enabled = true;
} */
}
else if (Input.GetKeyDown(KeyCode.Escape) && MainPanel.active == true)
{
Time.timeScale = TimeScale;
MainPanel.SetActive(false);
VidPanel.SetActive(false);
AudioPanel.SetActive(false);
TitleTexts.SetActive(false);
Mask.SetActive(false);
for (int i = 0; i < OtherUiElements.Length; i++)
{
OtherUiElements[i].gameObject.SetActive(true);
}
}
}
/*
void colorCrossfade()
{
Debug.Log(pauseMenu.color);
if (pauseMenu.color == Color.white)
{
pauseMenu.CrossFadeColor(_customColor, crossFadeDuration, true, false);
}
else {
pauseMenu.CrossFadeColor(Color.white, crossFadeDuration, true, false);
}
} */
/////Audio Options
/// <summary>
/// Show the audio panel
/// </summary>
public void Audio()
{
MainPanel.SetActive(false);
VidPanel.SetActive(false);
AudioPanel.SetActive(true);
AudioPanelAnimator.enabled = true;
AudioIn();
PauseMenu.text = "Audio Menu";
}
/// <summary>
/// Play the "audio panel in" animation.
/// </summary>
public void AudioIn()
{
UiEventSystem.SetSelectedGameObject(DefualtSelectedAudio);
AudioPanelAnimator.Play("Audio Panel In");
AudioMasterSlider.value = AudioListener.volume;
//Perform modulo to find factor f to allow for non uniform music volumes
float a; float b; float f;
try
{
a = Music[0].volume;
b = Music[1].volume;
f = a % b;
AudioMusicSlider.value = f;
}
catch
{
Debug.Log("You do not have multiple audio sources");
AudioMusicSlider.value = LastMusicMult;
}
//Do this with the effects
try
{
a = Effects[0].volume;
b = Effects[1].volume;
f = a % b;
AudioEffectsSlider.value = f;
}
catch
{
Debug.Log("You do not have multiple audio sources");
AudioEffectsSlider.value = LastAudioMult;
}
}
/// <summary>
/// Audio Option Methods
/// </summary>
/// <param name="f"></param>
public void UpdateMasterVol(float f)
{
//Controls volume of all audio listeners
AudioListener.volume = f;
}
/// <summary>
/// Update music effects volume
/// </summary>
/// <param name="f"></param>
public void UpdateMusicVol(float f)
{
try
{
for (int musicAmt = 0; musicAmt < Music.Length; musicAmt++)
{
Music[musicAmt].volume *= f;
}
}
catch
{
Debug.Log("Please assign music sources in the manager");
}
//_beforeMusic = music.volume;
}
/// <summary>
/// Update the audio effects volume
/// </summary>
/// <param name="f"></param>
public void UpdateEffectsVol(float f)
{
try
{
for (_audioEffectAmt = 0; _audioEffectAmt < Effects.Length; _audioEffectAmt++)
{
//get the values for all effects before the change
_beforeEffectVol[_audioEffectAmt] = Effects[_audioEffectAmt].volume;
//lower it by a factor of f because we don't want every effect to be set to a uniform volume
Effects[_audioEffectAmt].volume *= f;
}
}
catch
{
Debug.Log("Please assign audio effects sources in the manager.");
}
}
/// <summary>
/// The method for changing the applying new audio settings
/// </summary>
public void ApplyAudio()
{
StartCoroutine(ApplyAudioMain());
UiEventSystem.SetSelectedGameObject(DefualtSelectedMain);
}
/// <summary>
/// Use an IEnumerator to first play the animation and then change the audio settings
/// </summary>
/// <returns></returns>
internal IEnumerator ApplyAudioMain()
{
AudioPanelAnimator.Play("Audio Panel Out");
yield return StartCoroutine(CoroutineUtilities.WaitForRealTime((float)AudioPanelAnimator.GetCurrentAnimatorClipInfo(0).Length));
MainPanel.SetActive(true);
VidPanel.SetActive(false);
AudioPanel.SetActive(false);
BeforeMaster = AudioListener.volume;
LastMusicMult = AudioMusicSlider.value;
LastAudioMult = AudioEffectsSlider.value;
_saveSettings.SaveGameSettings();
}
/// <summary>
/// Cancel the audio setting changes
/// </summary>
public void CancelAudio()
{
UiEventSystem.SetSelectedGameObject(DefualtSelectedMain);
StartCoroutine(CancelAudioMain());
}
/// <summary>
/// Use an IEnumerator to first play the animation and then change the audio settings
/// </summary>
/// <returns></returns>
internal IEnumerator CancelAudioMain()
{
AudioPanelAnimator.Play("Audio Panel Out");
// Debug.Log(audioPanelAnimator.GetCurrentAnimatorClipInfo(0).Length);
yield return StartCoroutine(CoroutineUtilities.WaitForRealTime((float)AudioPanelAnimator.GetCurrentAnimatorClipInfo(0).Length));
MainPanel.SetActive(true);
VidPanel.SetActive(false);
AudioPanel.SetActive(false);
AudioListener.volume = BeforeMaster;
//Debug.Log(_beforeMaster + AudioListener.volume);
try
{
for (_audioEffectAmt = 0; _audioEffectAmt < Effects.Length; _audioEffectAmt++)
{
//get the values for all effects before the change
Effects[_audioEffectAmt].volume = _beforeEffectVol[_audioEffectAmt];
}
for (int musicAmt = 0; musicAmt < Music.Length; musicAmt++)
{
Music[musicAmt].volume = _beforeMusic;
}
}
catch
{
Debug.Log("please assign the audio sources in the manager");
}
}
/////Video Options
/// <summary>
/// Show video
/// </summary>
public void Video()
{
MainPanel.SetActive(false);
VidPanel.SetActive(true);
AudioPanel.SetActive(false);
VidPanelAnimator.enabled = true;
VideoIn();
PauseMenu.text = "Video Menu";
}
private static readonly Dictionary<int, int> AaDict = new Dictionary<int, int>() { { 0, 0 }, { 2, 1 }, { 4, 2 }, { 8, 3 } };
/// <summary>
/// Play the "video panel in" animation
/// </summary>
public void VideoIn()
{
UiEventSystem.SetSelectedGameObject(DefualtSelectedVideo);
VidPanelAnimator.Play("Video Panel In");
AaCombo.value = AaDict[QualitySettings.antiAliasing];
// --------
// todo: that stuff is stupid:
if (QualitySettings.anisotropicFiltering == AnisotropicFiltering.ForceEnable)
{
AfCombo.value = 1;
}
else if (QualitySettings.anisotropicFiltering == AnisotropicFiltering.Disable)
{
AfCombo.value = 0;
}
else if (QualitySettings.anisotropicFiltering == AnisotropicFiltering.Enable)
{
AfCombo.value = 2;
}
/*
* the unity constants already have int values:
* AnisotropicFiltering.ForceEnable = 2
* AnisotropicFiltering.Enable = 1
* would be smarter to use them, also this hard coded values just work with the "hardcoded" dropdownlist
*/
// --------
PresetLabel.text = _presets[QualitySettings.GetQualityLevel()].ToString();
FovSlider.value = MainCam.fieldOfView;
ModelQualSlider.value = QualitySettings.lodBias;
RenderDistSlider.value = MainCam.farClipPlane;
ShadowDistSlider.value = QualitySettings.shadowDistance;
MasterTexSlider.value = QualitySettings.masterTextureLimit;
ShadowCascadesSlider.value = QualitySettings.shadowCascades;
FullscreenToggle.isOn = Screen.fullScreen;
AoToggle.isOn = AoBool;
DofToggle.isOn = DofBool;
if (QualitySettings.vSyncCount == 0)
{
VSyncToggle.isOn = false;
}
else if (QualitySettings.vSyncCount == 1)
{
VSyncToggle.isOn = true;
}
try
{
HighQualTreeSlider.value = CurrentTerrain.treeMaximumFullLODCount;
TerrainDensitySlider.value = CurrentTerrain.detailObjectDensity;
TerrainQualSlider.value = CurrentTerrain.heightmapMaximumLOD;
}
catch
{
return;
}
}
/// <summary>
/// Cancel the video setting changes
/// </summary>
public void CancelVideo()
{
UiEventSystem.SetSelectedGameObject(DefualtSelectedMain);
StartCoroutine(CancelVideoMain());
}
/// <summary>
/// Use an IEnumerator to first play the animation and then changethe video settings
/// </summary>
/// <returns></returns>
internal IEnumerator CancelVideoMain()
{
VidPanelAnimator.Play("Video Panel Out");
yield return StartCoroutine(CoroutineUtilities.WaitForRealTime((float)VidPanelAnimator.GetCurrentAnimatorClipInfo(0).Length));
try
{
MainCam.farClipPlane = RenderDistIni;
Terrain.activeTerrain.detailObjectDensity = DensityIni;
MainCam.fieldOfView = FovIni;
MainPanel.SetActive(true);
VidPanel.SetActive(false);
AudioPanel.SetActive(false);
AoBool = _lastAoBool;
DofBool = _lastDofBool;
Screen.SetResolution(_beforeRes.width, _beforeRes.height, Screen.fullScreen);
QualitySettings.shadowDistance = ShadowDistIni;
QualitySettings.antiAliasing = (int)AaQualIni;
QualitySettings.antiAliasing = MsaaIni;
QualitySettings.vSyncCount = VsyncIni;
QualitySettings.masterTextureLimit = LastTexLimit;
QualitySettings.shadowCascades = LastShadowCascade;
Screen.fullScreen = _isFullscreen;
}
catch
{
Debug.Log("A problem occured (chances are the terrain was not assigned )");
MainCam.farClipPlane = RenderDistIni;
MainCam.fieldOfView = FovIni;
MainPanel.SetActive(true);
VidPanel.SetActive(false);
AudioPanel.SetActive(false);
AoBool = _lastAoBool;
DofBool = _lastDofBool;
QualitySettings.shadowDistance = ShadowDistIni;
Screen.SetResolution(_beforeRes.width, _beforeRes.height, Screen.fullScreen);
QualitySettings.antiAliasing = (int)AaQualIni;
QualitySettings.antiAliasing = MsaaIni;
QualitySettings.vSyncCount = VsyncIni;
QualitySettings.masterTextureLimit = LastTexLimit;
QualitySettings.shadowCascades = LastShadowCascade;
//Screen.fullScreen = isFullscreen;
}
}
//Apply the video prefs
/// <summary>
/// Apply the video settings
/// </summary>
public void Apply()
{
StartCoroutine(ApplyVideo());
UiEventSystem.SetSelectedGameObject(DefualtSelectedMain);
}
/// <summary>
/// Use an IEnumerator to first play the animation and then change the video settings.
/// </summary>
/// <returns></returns>
internal IEnumerator ApplyVideo()
{
VidPanelAnimator.Play("Video Panel Out");
yield return StartCoroutine(CoroutineUtilities.WaitForRealTime((float)VidPanelAnimator.GetCurrentAnimatorClipInfo(0).Length));
MainPanel.SetActive(true);
VidPanel.SetActive(false);
AudioPanel.SetActive(false);
RenderDistIni = MainCam.farClipPlane;
ShadowDistIni = QualitySettings.shadowDistance;
Debug.Log("Shadow dist ini" + ShadowDistIni);
FovIni = MainCam.fieldOfView;
AoBool = AoToggle.isOn;
DofBool = DofToggle.isOn;
_lastAoBool = AoBool;
_lastDofBool = DofBool;
_beforeRes = CurrentRes;
LastTexLimit = QualitySettings.masterTextureLimit;
LastShadowCascade = QualitySettings.shadowCascades;
VsyncIni = QualitySettings.vSyncCount;
_isFullscreen = Screen.fullScreen;
try
{
DensityIni = CurrentTerrain.detailObjectDensity;
TreeMeshAmtIni = CurrentTerrain.treeMaximumFullLODCount;
}
catch { Debug.Log("Please assign a terrain"); }
_saveSettings.SaveGameSettings();
}
public void TurnOnVSync(bool b)
{
VsyncIni = QualitySettings.vSyncCount;
QualitySettings.vSyncCount = b ? 1 : 0;
}
/// <summary>
/// Update full high quality tree mesh amount.
/// </summary>
/// <param name="f"></param>
public void UpdateTreeMeshAmt(int f)
{
CurrentTerrain.treeMaximumFullLODCount = f;
}
/// <summary>
/// Change the lod bias using
/// <c>
/// QualitySettings.lodBias = LoDBias / 2.15f;
/// </c>
/// LoDBias is only divided by 2.15 because the max is set to 10 on the slider, and dividing by 2.15 results in 4.65, our desired max. However, deleting or changing 2.15 is compeletly fine.
/// </summary>
/// <param name="loDBias"></param>
public void SetLodBias(float loDBias)
{
QualitySettings.lodBias = loDBias / 2.15f;
}
/// <summary>
/// Update the render distance using
/// <c>
/// mainCam.farClipPlane = f;
/// </c>
/// </summary>
/// <param name="f"></param>
public void UpdateRenderDist(float f)
{
try
{
MainCam.farClipPlane = f;
}
catch
{
Debug.Log(" Finding main camera now...it is still suggested that you manually assign this");
MainCam = Camera.main;
MainCam.farClipPlane = f;
}
}
/// <summary>
/// Update the texture quality using
/// <c>QualitySettings.masterTextureLimit </c>
/// </summary>
/// <param name="qual"></param>
public void UpdateTex(float qual)
{
QualitySettings.masterTextureLimit = (int)qual;
}
/// <summary>
/// Update the shadow distance using
/// <c>
/// QualitySettings.shadowDistance = dist;
/// </c>
/// </summary>
/// <param name="dist"></param>
public void UpdateShadowDistance(float dist)
{
QualitySettings.shadowDistance = dist;
}
/// <summary>
/// Change the max amount of high quality trees using
/// <c>
/// terrain.treeMaximumFullLODCount = (int)qual;
/// </c>
/// </summary>
/// <param name="qual"></param>
public void TreeMaxLod(float qual)
{
CurrentTerrain.treeMaximumFullLODCount = (int)qual;
}
/// <summary>
/// Change the height map max LOD using
/// <c>
/// terrain.heightmapMaximumLOD = (int)qual;
/// </c>
/// </summary>
/// <param name="qual"></param>
public void UpdateTerrainLod(float qual)
{
if (CurrentTerrain == null) return; // fail silently
CurrentTerrain.heightmapMaximumLOD = (int)qual;
}
/// <summary>
/// Change the fov using a float. The defualt should be 60.
/// </summary>
/// <param name="fov"></param>
public void UpdateFov(float fov)
{
MainCam.fieldOfView = fov;
}
/// <summary>
/// Toggle on or off Depth of Field. This is meant to be used with a checkbox.
/// </summary>
/// <param name="b"></param>
public void ToggleDof(bool b)
{
try
{
_tempScript = (MonoBehaviour)MainCamObj.GetComponent(DofScriptName);
_tempScript.enabled = b;
DofBool = b;
}
catch
{
Debug.Log("No AO post processing found");
}
}
/// <summary>
/// Toggle on or off Ambient Occulusion. This is meant to be used with a checkbox.
/// </summary>
/// <param name="b"></param>
public void ToggleAo(bool b)
{
try
{
_tempScript = (MonoBehaviour)MainCamObj.GetComponent(AoScriptName);
_tempScript.enabled = b;
AoBool = b;
}
catch
{
Debug.Log("No AO post processing found");
return;
}
}
/// <summary>
/// Set the game to windowed or full screen. This is meant to be used with a checkbox
/// </summary>
/// <param name="b"></param>
public void SetFullScreen(bool b) { Screen.SetResolution(Screen.width, Screen.height, b); }
private void ChangeRes(int index)
{
for (int i = 0; i < _allRes.Length; i++)
{
//If the resoultion matches the current resoution height and width then go through the statement.
if (_allRes[i].height == CurrentRes.height && _allRes[i].width == CurrentRes.width)
{
Screen.SetResolution(_allRes[i + index].width, _allRes[i + index].height, _isFullscreen); _isFullscreen = _isFullscreen; CurrentRes = Screen.resolutions[i + index]; ResolutionLabel.text = CurrentRes.width.ToString() + " x " + CurrentRes.height.ToString();
}
}
}
/// <summary>
/// Method for moving to the next resoution in the allRes array. WARNING: This is not finished/buggy.
/// </summary>
//Method for moving to the next resoution in the allRes array. WARNING: This is not finished/buggy.
public void NextRes()
{
_beforeRes = CurrentRes;
//Iterate through all of the resoultions.
ChangeRes(1);
}
/// <summary>
/// Method for moving to the last resoution in the allRes array. WARNING: This is not finished/buggy.
/// </summary>
//Method for moving to the last resoution in the allRes array. WARNING: This is not finished/buggy.
public void LastRes()
{
_beforeRes = CurrentRes;
ChangeRes(-1);
}
public void EnableSimpleTerrain(Boolean b)
{
UseSimpleTerrain = b;
}
/// <summary>
/// The method for changing aniso settings
/// </summary>
/// <param name="anisoSetting"></param>
public void UpdateAniso(int anisoSetting)
{
if (anisoSetting == 0)
{
QualitySettings.anisotropicFiltering = AnisotropicFiltering.Disable;
}
else if (anisoSetting == 1)
{
QualitySettings.anisotropicFiltering = AnisotropicFiltering.ForceEnable;
}
else if (anisoSetting == 2)
{
QualitySettings.anisotropicFiltering = AnisotropicFiltering.Enable;
}
}
/// <summary>
/// The method for setting the amount of shadow cascades
/// </summary>
/// <param name="cascades"></param>
public void UpdateCascades(float cascades)
{
int c = Mathf.RoundToInt(cascades);
if (c == 1)
{
c = 2;
}
else if (c == 3)
{
c = 2;
}
QualitySettings.shadowCascades = c;
}
/// <summary>
/// Update terrain density
/// </summary>
/// <param name="density"></param>
public void UpdateDensity(float density)
{
DetailDensity = density;
try
{
Terrain.detailObjectDensity = DetailDensity;
}
catch
{
Debug.Log("Please assign a terrain");
}
}
/// <summary>
/// Sets the MSAA to a specific level (between 0 and 4)
/// </summary>
/// <param name="level">
/// 0 -> 0x MSAA (disabled).
/// 1 -> 2x MSAA.
/// 2 -> 4x MSAA.
/// 3 -> 8x MSAA.
/// Left shift works too by getting the log2 of the desired level.
/// <c>
/// QualitySettings.antiAliasing = level == 0 ? 0 : 1 *left shift operator* level ;
/// </c>
/// </param>
public void SetMsaaLevel(int level)
{
level = Mathf.Clamp(level, 0, 4);
QualitySettings.antiAliasing = level == 0 ? 0 : (int)Math.Pow(2.0d, level);
}
#region GraphicPresets
/// <summary>
/// Set the quality level one level higher. This is done by getting the current quality level, then using
/// <c>
/// QualitySettings.IncreaseLevel();
/// </c>
/// to increase the level. The current level variable is set to the new quality setting, and the label is updated.
/// </summary>
public void NextPreset()
{
QualitySettings.IncreaseLevel();
FromPreset();
}
/// <summary>
/// Set the quality level one level lower. This is done by getting the current quality level, then using
/// <c>
/// QualitySettings.DecreaseLevel();
/// </c>
/// to decrease the level. The current level variable is set to the new quality setting, and the label is updated.
/// </summary>
public void LastPreset()
{
QualitySettings.DecreaseLevel();
FromPreset();
}
private void FromPreset()
{
_currentLevel = QualitySettings.GetQualityLevel();
PresetLabel.text = _presets[_currentLevel];
if (HardCodeSomeVideoSettings)
{
QualitySettings.shadowDistance = ShadowDist[_currentLevel];
QualitySettings.lodBias = LodBias[_currentLevel];
}
}
/// <summary>
/// Sets the Graphic to a Preset (from very low to extreme)
/// (note: UI buttons in the inspector can carry a parameter, so you wont need 7 methods)
/// </summary>
public void SetGraphicsPreset(int preset)
{
preset = Mathf.Clamp(preset, 0, 6);
QualitySettings.SetQualityLevel(preset);
QualitySettings.shadowDistance = ShadowDist[preset];
QualitySettings.lodBias = LodBias[preset];
// in the previous 7 methods were hardcoded values but commented out
// the logic behind those hardcoded values can be archived by this:
// QualitySettings.shadowDistance = shadowPreset[preset];
}
// private static readonly float[] shadowPreset = {12.6f, 17.4f, 29.7f, 82f, 110f, 338f, 800f};
#endregion
/// <summary>
/// Return to the main menu from the credits panel
/// </summary>
public void CreditsReturn()
{
StartCoroutine(CreditsReturnMain());
UiEventSystem.SetSelectedGameObject(DefualtSelectedMain);
}
/// <summary>
/// Use an IEnumerator to first play the animation and then hide other panels settings
/// </summary>
/// <returns></returns>
internal IEnumerator CreditsReturnMain()
{
CreditsPanelAnimator.Play("Credits Panel Out 1");
yield return StartCoroutine(CoroutineUtilities.WaitForRealTime((float)CreditsPanelAnimator.GetCurrentAnimatorClipInfo(0).Length));
MainPanel.SetActive(true);
VidPanel.SetActive(false);
AudioPanel.SetActive(false);
CreditsPanel.SetActive(false);
}
public void CreditsIn()
{
MainPanel.SetActive(false);
VidPanel.SetActive(false);
AudioPanel.SetActive(false);
CreditsPanel.SetActive(true);
CreditsPanelAnimator.enabled = true;
UiEventSystem.SetSelectedGameObject(DefualtSelectedCredits);
CreditsPanelAnimator.Play("Credits Panel In");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
{
using Microsoft.CodeAnalysis.ErrorLogger;
using DiagnosticId = String;
using LanguageKind = String;
[Export(typeof(ICodeFixService)), Shared]
internal partial class CodeFixService : ICodeFixService
{
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> _workspaceFixersMap;
private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>> _projectFixersMap;
// Shared by project fixers and workspace fixers.
private ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>> _fixerToFixableIdsMap = ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>>.Empty;
private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> _fixerPriorityMap;
private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider> _analyzerReferenceToFixersMap;
private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback _createProjectCodeFixProvider;
private readonly ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> _suppressionProvidersMap;
private readonly IEnumerable<Lazy<IErrorLoggerService>> _errorLoggers;
private ImmutableDictionary<object, FixAllProviderInfo> _fixAllProviderMap;
[ImportingConstructor]
public CodeFixService(
IDiagnosticAnalyzerService service,
[ImportMany]IEnumerable<Lazy<IErrorLoggerService>> loggers,
[ImportMany]IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> fixers,
[ImportMany]IEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>> suppressionProviders)
{
_errorLoggers = loggers;
_diagnosticService = service;
var fixersPerLanguageMap = fixers.ToPerLanguageMapWithMultipleLanguages();
var suppressionProvidersPerLanguageMap = suppressionProviders.ToPerLanguageMapWithMultipleLanguages();
_workspaceFixersMap = GetFixerPerLanguageMap(fixersPerLanguageMap, null);
_suppressionProvidersMap = GetSuppressionProvidersPerLanguageMap(suppressionProvidersPerLanguageMap);
// REVIEW: currently, fixer's priority is statically defined by the fixer itself. might considering making it more dynamic or configurable.
_fixerPriorityMap = GetFixerPriorityPerLanguageMap(fixersPerLanguageMap);
// Per-project fixers
_projectFixersMap = new ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<string, List<CodeFixProvider>>>();
_analyzerReferenceToFixersMap = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>();
_createProjectCodeFixProvider = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback(r => new ProjectCodeFixProvider(r));
_fixAllProviderMap = ImmutableDictionary<object, FixAllProviderInfo>.Empty;
}
public async Task<FirstDiagnosticResult> GetFirstDiagnosticWithFixAsync(Document document, TextSpan range, bool considerSuppressionFixes, CancellationToken cancellationToken)
{
if (document == null || !document.IsOpen())
{
return default(FirstDiagnosticResult);
}
using (var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject())
{
var fullResult = await _diagnosticService.TryAppendDiagnosticsForSpanAsync(document, range, diagnostics.Object, cancellationToken: cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics.Object)
{
cancellationToken.ThrowIfCancellationRequested();
if (!range.IntersectsWith(diagnostic.TextSpan))
{
continue;
}
// REVIEW: 2 possible designs.
// 1. find the first fix and then return right away. if the lightbulb is actually expanded, find all fixes for the line synchronously. or
// 2. kick off a task that finds all fixes for the given range here but return once we find the first one.
// at the same time, let the task to run to finish. if the lightbulb is expanded, we just simply use the task to get all fixes.
//
// first approach is simpler, so I will implement that first. if the first approach turns out to be not good enough, then
// I will try the second approach which will be more complex but quicker
var hasFix = await ContainsAnyFix(document, diagnostic, considerSuppressionFixes, cancellationToken).ConfigureAwait(false);
if (hasFix)
{
return new FirstDiagnosticResult(!fullResult, hasFix, diagnostic);
}
}
return new FirstDiagnosticResult(!fullResult, false, default(DiagnosticData));
}
}
public async Task<IEnumerable<CodeFixCollection>> GetFixesAsync(Document document, TextSpan range, bool includeSuppressionFixes, CancellationToken cancellationToken)
{
// REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back
// current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information
// (if it is up-to-date) or synchronously do the work at the spot.
//
// this design's weakness is that each side don't have enough information to narrow down works to do. it will most likely always do more works than needed.
// sometimes way more than it is needed. (compilation)
Dictionary<TextSpan, List<DiagnosticData>> aggregatedDiagnostics = null;
foreach (var diagnostic in await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, cancellationToken: cancellationToken).ConfigureAwait(false))
{
if (diagnostic.IsSuppressed)
{
continue;
}
cancellationToken.ThrowIfCancellationRequested();
aggregatedDiagnostics = aggregatedDiagnostics ?? new Dictionary<TextSpan, List<DiagnosticData>>();
aggregatedDiagnostics.GetOrAdd(diagnostic.TextSpan, _ => new List<DiagnosticData>()).Add(diagnostic);
}
var result = new List<CodeFixCollection>();
if (aggregatedDiagnostics == null)
{
return result;
}
foreach (var spanAndDiagnostic in aggregatedDiagnostics)
{
result = await AppendFixesAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false);
}
if (result.Any())
{
// sort the result to the order defined by the fixers
var priorityMap = _fixerPriorityMap[document.Project.Language].Value;
result.Sort((d1, d2) => priorityMap.ContainsKey((CodeFixProvider)d1.Provider) ? (priorityMap.ContainsKey((CodeFixProvider)d2.Provider) ? priorityMap[(CodeFixProvider)d1.Provider] - priorityMap[(CodeFixProvider)d2.Provider] : -1) : 1);
}
if (includeSuppressionFixes)
{
foreach (var spanAndDiagnostic in aggregatedDiagnostics)
{
result = await AppendSuppressionsAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false);
}
}
return result;
}
private async Task<List<CodeFixCollection>> AppendFixesAsync(
Document document,
TextSpan span,
IEnumerable<DiagnosticData> diagnosticDataCollection,
List<CodeFixCollection> result,
CancellationToken cancellationToken)
{
Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap;
bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap);
var projectFixersMap = GetProjectFixers(document.Project);
var hasAnyProjectFixer = projectFixersMap.Any();
if (!hasAnySharedFixer && !hasAnyProjectFixer)
{
return result;
}
ImmutableArray<CodeFixProvider> workspaceFixers;
List<CodeFixProvider> projectFixers;
var allFixers = new List<CodeFixProvider>();
foreach (var diagnosticId in diagnosticDataCollection.Select(d => d.Id).Distinct())
{
cancellationToken.ThrowIfCancellationRequested();
if (hasAnySharedFixer && fixerMap.Value.TryGetValue(diagnosticId, out workspaceFixers))
{
allFixers.AddRange(workspaceFixers);
}
if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out projectFixers))
{
allFixers.AddRange(projectFixers);
}
}
var diagnostics = await DiagnosticData.ToDiagnosticsAsync(document.Project, diagnosticDataCollection, cancellationToken).ConfigureAwait(false);
var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
foreach (var fixer in allFixers.Distinct())
{
cancellationToken.ThrowIfCancellationRequested();
Func<Diagnostic, bool> hasFix = (d) => this.GetFixableDiagnosticIds(fixer, extensionManager).Contains(d.Id);
Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes =
async (dxs) =>
{
var fixes = new List<CodeFix>();
var context = new CodeFixContext(document, span, dxs,
// TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs?
(a, d) =>
{
// Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
lock (fixes)
{
fixes.Add(new CodeFix(a, d));
}
},
verifyArguments: false,
cancellationToken: cancellationToken);
var task = fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask;
await task.ConfigureAwait(false);
return fixes;
};
await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, fixer,
hasFix, getFixes, cancellationToken).ConfigureAwait(false);
}
return result;
}
private async Task<List<CodeFixCollection>> AppendSuppressionsAsync(
Document document, TextSpan span, IEnumerable<DiagnosticData> diagnosticDataCollection, List<CodeFixCollection> result, CancellationToken cancellationToken)
{
Lazy<ISuppressionFixProvider> lazySuppressionProvider;
if (!_suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) || lazySuppressionProvider.Value == null)
{
return result;
}
var diagnostics = await DiagnosticData.ToDiagnosticsAsync(document.Project, diagnosticDataCollection, cancellationToken).ConfigureAwait(false);
Func<Diagnostic, bool> hasFix = (d) => lazySuppressionProvider.Value.CanBeSuppressedOrUnsuppressed(d);
Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes = (dxs) => lazySuppressionProvider.Value.GetSuppressionsAsync(document, span, dxs, cancellationToken);
await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, lazySuppressionProvider.Value, hasFix, getFixes, cancellationToken).ConfigureAwait(false);
return result;
}
private async Task<List<CodeFixCollection>> AppendFixesOrSuppressionsAsync(
Document document,
TextSpan span,
IEnumerable<Diagnostic> diagnosticsWithSameSpan,
List<CodeFixCollection> result,
object fixer,
Func<Diagnostic, bool> hasFix,
Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes,
CancellationToken cancellationToken)
{
var diagnostics = diagnosticsWithSameSpan.Where(d => hasFix(d)).OrderByDescending(d => d.Severity).ToImmutableArray();
if (diagnostics.Length <= 0)
{
// this can happen for suppression case where all diagnostics can't be suppressed
return result;
}
var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
var fixes = await extensionManager.PerformFunctionAsync(fixer, () => getFixes(diagnostics), defaultValue: SpecializedCollections.EmptyEnumerable<CodeFix>()).ConfigureAwait(false);
if (fixes != null && fixes.Any())
{
// If the fix provider supports fix all occurrences, then get the corresponding FixAllProviderInfo and fix all context.
var fixAllProviderInfo = extensionManager.PerformFunction(fixer, () => ImmutableInterlocked.GetOrAdd(ref _fixAllProviderMap, fixer, FixAllProviderInfo.Create), defaultValue: null);
FixAllCodeActionContext fixAllContext = null;
if (fixAllProviderInfo != null)
{
var codeFixProvider = (fixer as CodeFixProvider) ?? new WrapperCodeFixProvider((ISuppressionFixProvider)fixer, diagnostics);
fixAllContext = FixAllCodeActionContext.Create(document, fixAllProviderInfo, codeFixProvider, diagnostics, this.GetDocumentDiagnosticsAsync, this.GetProjectDiagnosticsAsync, cancellationToken);
}
result = result ?? new List<CodeFixCollection>();
var codeFix = new CodeFixCollection(fixer, span, fixes, fixAllContext);
result.Add(codeFix);
}
return result;
}
public CodeFixProvider GetSuppressionFixer(string language, ImmutableArray<Diagnostic> diagnostics)
{
Lazy<ISuppressionFixProvider> lazySuppressionProvider;
if (!_suppressionProvidersMap.TryGetValue(language, out lazySuppressionProvider) || lazySuppressionProvider.Value == null)
{
return null;
}
return new WrapperCodeFixProvider(lazySuppressionProvider.Value, diagnostics);
}
private async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(document);
var solution = document.Project.Solution;
var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(solution, null, document.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId != null));
return await DiagnosticData.ToDiagnosticsAsync(document.Project, diagnostics, cancellationToken).ConfigureAwait(false);
}
private async Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(project);
if (includeAllDocumentDiagnostics)
{
// Get all diagnostics for the entire project, including document diagnostics.
var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
var documentIdsToTreeMap = await GetDocumentIdsToTreeMapAsync(project, cancellationToken).ConfigureAwait(false);
return await DiagnosticData.ToDiagnosticsAsync(project, diagnostics, documentIdsToTreeMap, cancellationToken).ConfigureAwait(false);
}
else
{
// Get all no-location diagnostics for the project, doesn't include document diagnostics.
var diagnostics = await _diagnosticService.GetProjectDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId == null));
return await DiagnosticData.ToDiagnosticsAsync(project, diagnostics, cancellationToken).ConfigureAwait(false);
}
}
private static async Task<ImmutableDictionary<DocumentId, SyntaxTree>> GetDocumentIdsToTreeMapAsync(Project project, CancellationToken cancellationToken)
{
var builder = ImmutableDictionary.CreateBuilder<DocumentId, SyntaxTree>();
foreach (var document in project.Documents)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
builder.Add(document.Id, tree);
}
return builder.ToImmutable();
}
private async Task<bool> ContainsAnyFix(Document document, DiagnosticData diagnostic, bool considerSuppressionFixes, CancellationToken cancellationToken)
{
ImmutableArray<CodeFixProvider> workspaceFixers = ImmutableArray<CodeFixProvider>.Empty;
List<CodeFixProvider> projectFixers = null;
Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap;
bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap) && fixerMap.Value.TryGetValue(diagnostic.Id, out workspaceFixers);
var hasAnyProjectFixer = GetProjectFixers(document.Project).TryGetValue(diagnostic.Id, out projectFixers);
Lazy<ISuppressionFixProvider> lazySuppressionProvider = null;
var hasSuppressionFixer =
considerSuppressionFixes &&
_suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) &&
lazySuppressionProvider.Value != null;
if (!hasAnySharedFixer && !hasAnyProjectFixer && !hasSuppressionFixer)
{
return false;
}
var allFixers = ImmutableArray<CodeFixProvider>.Empty;
if (hasAnySharedFixer)
{
allFixers = workspaceFixers;
}
if (hasAnyProjectFixer)
{
allFixers = allFixers.AddRange(projectFixers);
}
var dx = await diagnostic.ToDiagnosticAsync(document.Project, cancellationToken).ConfigureAwait(false);
if (hasSuppressionFixer && lazySuppressionProvider.Value.CanBeSuppressedOrUnsuppressed(dx))
{
return true;
}
var fixes = new List<CodeFix>();
var context = new CodeFixContext(document, dx,
// TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs?
(a, d) =>
{
// Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
lock (fixes)
{
fixes.Add(new CodeFix(a, d));
}
},
verifyArguments: false,
cancellationToken: cancellationToken);
var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
// we do have fixer. now let's see whether it actually can fix it
foreach (var fixer in allFixers)
{
await extensionManager.PerformActionAsync(fixer, () => fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask).ConfigureAwait(false);
if (!fixes.Any())
{
continue;
}
return true;
}
return false;
}
private static readonly Func<DiagnosticId, List<CodeFixProvider>> s_createList = _ => new List<CodeFixProvider>();
private ImmutableArray<DiagnosticId> GetFixableDiagnosticIds(CodeFixProvider fixer, IExtensionManager extensionManager)
{
// If we are passed a null extension manager it means we do not have access to a document so there is nothing to
// show the user. In this case we will log any exceptions that occur, but the user will not see them.
if (extensionManager != null)
{
return extensionManager.PerformFunction(
fixer,
() => ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f)),
defaultValue: ImmutableArray<DiagnosticId>.Empty);
}
try
{
return ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f));
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception e)
{
foreach (var logger in _errorLoggers)
{
logger.Value.LogException(fixer, e);
}
return ImmutableArray<DiagnosticId>.Empty;
}
}
private static ImmutableArray<string> GetAndTestFixableDiagnosticIds(CodeFixProvider codeFixProvider)
{
var ids = codeFixProvider.FixableDiagnosticIds;
if (ids.IsDefault)
{
throw new InvalidOperationException(
string.Format(
WorkspacesResources.FixableDiagnosticIdsIncorrectlyInitialized,
codeFixProvider.GetType().Name+ "."+ nameof(CodeFixProvider.FixableDiagnosticIds)));
}
return ids;
}
private ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> GetFixerPerLanguageMap(
Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage,
IExtensionManager extensionManager)
{
var fixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>>();
foreach (var languageKindAndFixers in fixersPerLanguage)
{
var lazyMap = new Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>(() =>
{
var mutableMap = new Dictionary<DiagnosticId, List<CodeFixProvider>>();
foreach (var fixer in languageKindAndFixers.Value)
{
foreach (var id in this.GetFixableDiagnosticIds(fixer.Value, extensionManager))
{
if (string.IsNullOrWhiteSpace(id))
{
continue;
}
var list = mutableMap.GetOrAdd(id, s_createList);
list.Add(fixer.Value);
}
}
var immutableMap = ImmutableDictionary.CreateBuilder<DiagnosticId, ImmutableArray<CodeFixProvider>>();
foreach (var diagnosticIdAndFixers in mutableMap)
{
immutableMap.Add(diagnosticIdAndFixers.Key, diagnosticIdAndFixers.Value.AsImmutableOrEmpty());
}
return immutableMap.ToImmutable();
}, isThreadSafe: true);
fixerMap = fixerMap.Add(languageKindAndFixers.Key, lazyMap);
}
return fixerMap;
}
private static ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> GetSuppressionProvidersPerLanguageMap(
Dictionary<LanguageKind, List<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>> suppressionProvidersPerLanguage)
{
var suppressionFixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ISuppressionFixProvider>>();
foreach (var languageKindAndFixers in suppressionProvidersPerLanguage)
{
var suppressionFixerLazyMap = new Lazy<ISuppressionFixProvider>(() => languageKindAndFixers.Value.SingleOrDefault().Value);
suppressionFixerMap = suppressionFixerMap.Add(languageKindAndFixers.Key, suppressionFixerLazyMap);
}
return suppressionFixerMap;
}
private static ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> GetFixerPriorityPerLanguageMap(
Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage)
{
var languageMap = ImmutableDictionary.CreateBuilder<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>>();
foreach (var languageAndFixers in fixersPerLanguage)
{
var lazyMap = new Lazy<ImmutableDictionary<CodeFixProvider, int>>(() =>
{
var priorityMap = ImmutableDictionary.CreateBuilder<CodeFixProvider, int>();
var fixers = ExtensionOrderer.Order(languageAndFixers.Value);
for (var i = 0; i < fixers.Count; i++)
{
priorityMap.Add(fixers[i].Value, i);
}
return priorityMap.ToImmutable();
}, isThreadSafe: true);
languageMap.Add(languageAndFixers.Key, lazyMap);
}
return languageMap.ToImmutable();
}
private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> GetProjectFixers(Project project)
{
return _projectFixersMap.GetValue(project.AnalyzerReferences, pId => ComputeProjectFixers(project));
}
private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> ComputeProjectFixers(Project project)
{
var extensionManager = project.Solution.Workspace.Services.GetService<IExtensionManager>();
ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Builder builder = null;
foreach (var reference in project.AnalyzerReferences)
{
var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue(reference, _createProjectCodeFixProvider);
foreach (var fixer in projectCodeFixerProvider.GetFixers(project.Language))
{
var fixableIds = this.GetFixableDiagnosticIds(fixer, extensionManager);
foreach (var id in fixableIds)
{
if (string.IsNullOrWhiteSpace(id))
{
continue;
}
builder = builder ?? ImmutableDictionary.CreateBuilder<DiagnosticId, List<CodeFixProvider>>();
var list = builder.GetOrAdd(id, s_createList);
list.Add(fixer);
}
}
}
if (builder == null)
{
return ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty;
}
return builder.ToImmutable();
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
using ErrorEventArgs=Newtonsoft.Json.Serialization.ErrorEventArgs;
namespace Newtonsoft.Json
{
/// <summary>
/// Serializes and deserializes objects into and from the JSON format.
/// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into JSON.
/// </summary>
public class JsonSerializer
{
#region Properties
private TypeNameHandling _typeNameHandling;
private FormatterAssemblyStyle _typeNameAssemblyFormat;
private PreserveReferencesHandling _preserveReferencesHandling;
private ReferenceLoopHandling _referenceLoopHandling;
private MissingMemberHandling _missingMemberHandling;
private ObjectCreationHandling _objectCreationHandling;
private NullValueHandling _nullValueHandling;
private DefaultValueHandling _defaultValueHandling;
private ConstructorHandling _constructorHandling;
private JsonConverterCollection _converters;
private IContractResolver _contractResolver;
private IReferenceResolver _referenceResolver;
private SerializationBinder _binder;
private StreamingContext _context;
/// <summary>
/// Occurs when the <see cref="JsonSerializer"/> errors during serialization and deserialization.
/// </summary>
public virtual event EventHandler<ErrorEventArgs> Error;
/// <summary>
/// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references.
/// </summary>
public virtual IReferenceResolver ReferenceResolver
{
get
{
if (_referenceResolver == null)
_referenceResolver = new DefaultReferenceResolver();
return _referenceResolver;
}
set
{
if (value == null)
throw new ArgumentNullException("value", "Reference resolver cannot be null.");
_referenceResolver = value;
}
}
/// <summary>
/// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names.
/// </summary>
public virtual SerializationBinder Binder
{
get
{
return _binder;
}
set
{
if (value == null)
throw new ArgumentNullException("value", "Serialization binder cannot be null.");
_binder = value;
}
}
/// <summary>
/// Gets or sets how type name writing and reading is handled by the serializer.
/// </summary>
public virtual TypeNameHandling TypeNameHandling
{
get { return _typeNameHandling; }
set
{
if (value < TypeNameHandling.None || value > TypeNameHandling.Auto)
throw new ArgumentOutOfRangeException("value");
_typeNameHandling = value;
}
}
/// <summary>
/// Gets or sets how a type name assembly is written and resolved by the serializer.
/// </summary>
/// <value>The type name assembly format.</value>
public virtual FormatterAssemblyStyle TypeNameAssemblyFormat
{
get { return _typeNameAssemblyFormat; }
set
{
if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full)
throw new ArgumentOutOfRangeException("value");
_typeNameAssemblyFormat = value;
}
}
/// <summary>
/// Gets or sets how object references are preserved by the serializer.
/// </summary>
public virtual PreserveReferencesHandling PreserveReferencesHandling
{
get { return _preserveReferencesHandling; }
set
{
if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All)
throw new ArgumentOutOfRangeException("value");
_preserveReferencesHandling = value;
}
}
/// <summary>
/// Get or set how reference loops (e.g. a class referencing itself) is handled.
/// </summary>
public virtual ReferenceLoopHandling ReferenceLoopHandling
{
get { return _referenceLoopHandling; }
set
{
if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
throw new ArgumentOutOfRangeException("value");
_referenceLoopHandling = value;
}
}
/// <summary>
/// Get or set how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization.
/// </summary>
public virtual MissingMemberHandling MissingMemberHandling
{
get { return _missingMemberHandling; }
set
{
if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error)
throw new ArgumentOutOfRangeException("value");
_missingMemberHandling = value;
}
}
/// <summary>
/// Get or set how null values are handled during serialization and deserialization.
/// </summary>
public virtual NullValueHandling NullValueHandling
{
get { return _nullValueHandling; }
set
{
if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
throw new ArgumentOutOfRangeException("value");
_nullValueHandling = value;
}
}
/// <summary>
/// Get or set how null default are handled during serialization and deserialization.
/// </summary>
public virtual DefaultValueHandling DefaultValueHandling
{
get { return _defaultValueHandling; }
set
{
if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate)
throw new ArgumentOutOfRangeException("value");
_defaultValueHandling = value;
}
}
/// <summary>
/// Gets or sets how objects are created during deserialization.
/// </summary>
/// <value>The object creation handling.</value>
public virtual ObjectCreationHandling ObjectCreationHandling
{
get { return _objectCreationHandling; }
set
{
if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace)
throw new ArgumentOutOfRangeException("value");
_objectCreationHandling = value;
}
}
/// <summary>
/// Gets or sets how constructors are used during deserialization.
/// </summary>
/// <value>The constructor handling.</value>
public virtual ConstructorHandling ConstructorHandling
{
get { return _constructorHandling; }
set
{
if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor)
throw new ArgumentOutOfRangeException("value");
_constructorHandling = value;
}
}
/// <summary>
/// Gets a collection <see cref="JsonConverter"/> that will be used during serialization.
/// </summary>
/// <value>Collection <see cref="JsonConverter"/> that will be used during serialization.</value>
public virtual JsonConverterCollection Converters
{
get
{
if (_converters == null)
_converters = new JsonConverterCollection();
return _converters;
}
}
/// <summary>
/// Gets or sets the contract resolver used by the serializer when
/// serializing .NET objects to JSON and vice versa.
/// </summary>
public virtual IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
_contractResolver = DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
/// <summary>
/// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods.
/// </summary>
/// <value>The context.</value>
public virtual StreamingContext Context
{
get { return _context; }
set { _context = value; }
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializer"/> class.
/// </summary>
public JsonSerializer()
{
_referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling;
_missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling;
_nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling;
_defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling;
_objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling;
_preserveReferencesHandling = JsonSerializerSettings.DefaultPreserveReferencesHandling;
_constructorHandling = JsonSerializerSettings.DefaultConstructorHandling;
_typeNameHandling = JsonSerializerSettings.DefaultTypeNameHandling;
_context = JsonSerializerSettings.DefaultContext;
_binder = DefaultSerializationBinder.Instance;
}
/// <summary>
/// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param>
/// <returns>A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.</returns>
public static JsonSerializer Create(JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = new JsonSerializer();
if (settings != null)
{
if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
jsonSerializer.Converters.AddRange(settings.Converters);
jsonSerializer.TypeNameHandling = settings.TypeNameHandling;
jsonSerializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat;
jsonSerializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
jsonSerializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
jsonSerializer.MissingMemberHandling = settings.MissingMemberHandling;
jsonSerializer.ObjectCreationHandling = settings.ObjectCreationHandling;
jsonSerializer.NullValueHandling = settings.NullValueHandling;
jsonSerializer.DefaultValueHandling = settings.DefaultValueHandling;
jsonSerializer.ConstructorHandling = settings.ConstructorHandling;
jsonSerializer.Context = settings.Context;
if (settings.Error != null)
jsonSerializer.Error += settings.Error;
if (settings.ContractResolver != null)
jsonSerializer.ContractResolver = settings.ContractResolver;
if (settings.ReferenceResolver != null)
jsonSerializer.ReferenceResolver = settings.ReferenceResolver;
if (settings.Binder != null)
jsonSerializer.Binder = settings.Binder;
}
return jsonSerializer;
}
/// <summary>
/// Populates the JSON values onto the target object.
/// </summary>
/// <param name="reader">The <see cref="TextReader"/> that contains the JSON structure to reader values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public void Populate(TextReader reader, object target)
{
Populate(new JsonTextReader(reader), target);
}
/// <summary>
/// Populates the JSON values onto the target object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to reader values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public void Populate(JsonReader reader, object target)
{
PopulateInternal(reader, target);
}
internal virtual void PopulateInternal(JsonReader reader, object target)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
ValidationUtils.ArgumentNotNull(target, "target");
JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
serializerReader.Populate(reader, target);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to deserialize.</param>
/// <returns>The <see cref="Object"/> being deserialized.</returns>
public object Deserialize(JsonReader reader)
{
return Deserialize(reader, null);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="StringReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="TextReader"/> containing the object.</param>
/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
public object Deserialize(TextReader reader, Type objectType)
{
return Deserialize(new JsonTextReader(reader), objectType);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the object.</param>
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <returns>The instance of <typeparamref name="T"/> being deserialized.</returns>
public T Deserialize<T>(JsonReader reader)
{
return (T)Deserialize(reader, typeof(T));
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the object.</param>
/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
public object Deserialize(JsonReader reader, Type objectType)
{
return DeserializeInternal(reader, objectType);
}
internal virtual object DeserializeInternal(JsonReader reader, Type objectType)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
return serializerReader.Deserialize(reader, objectType);
}
/// <summary>
/// Serializes the specified <see cref="Object"/> and writes the Json structure
/// to a <c>Stream</c> using the specified <see cref="TextWriter"/>.
/// </summary>
/// <param name="textWriter">The <see cref="TextWriter"/> used to write the Json structure.</param>
/// <param name="value">The <see cref="Object"/> to serialize.</param>
public void Serialize(TextWriter textWriter, object value)
{
Serialize(new JsonTextWriter(textWriter), value);
}
/// <summary>
/// Serializes the specified <see cref="Object"/> and writes the Json structure
/// to a <c>Stream</c> using the specified <see cref="JsonWriter"/>.
/// </summary>
/// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the Json structure.</param>
/// <param name="value">The <see cref="Object"/> to serialize.</param>
public void Serialize(JsonWriter jsonWriter, object value)
{
SerializeInternal(jsonWriter, value);
}
internal virtual void SerializeInternal(JsonWriter jsonWriter, object value)
{
ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter");
JsonSerializerInternalWriter serializerWriter = new JsonSerializerInternalWriter(this);
serializerWriter.Serialize(jsonWriter, value);
}
internal JsonConverter GetMatchingConverter(Type type)
{
return GetMatchingConverter(_converters, type);
}
internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType)
{
#if DEBUG
ValidationUtils.ArgumentNotNull(objectType, "objectType");
#endif
if (converters != null)
{
for (int i = 0; i < converters.Count; i++)
{
JsonConverter converter = converters[i];
if (converter.CanConvert(objectType))
return converter;
}
}
return null;
}
internal void OnError(ErrorEventArgs e)
{
EventHandler<ErrorEventArgs> error = Error;
if (error != null)
error(this, e);
}
}
}
| |
// 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.Windows.Data;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting
{
/// <summary>
/// This is the view model for CodeStyle options page.
/// </summary>
/// <remarks>
/// The codestyle options page is defined in <see cref="CodeStylePage"/>
/// </remarks>
internal class StyleViewModel : AbstractOptionPreviewViewModel
{
internal override bool ShouldPersistOption(OptionKey key)
{
return key.Option.Feature == CSharpCodeStyleOptions.FeatureName ||
key.Option.Feature == CodeStyleOptions.PerLanguageCodeStyleOption ||
key.Option.Feature == SimplificationOptions.PerLanguageFeatureName;
}
#region "Preview Text"
private static readonly string s_fieldDeclarationPreviewTrue = @"
class C{
int capacity;
void Method()
{
//[
this.capacity = 0;
//]
}
}";
private static readonly string s_fieldDeclarationPreviewFalse = @"
class C{
int capacity;
void Method()
{
//[
capacity = 0;
//]
}
}";
private static readonly string s_propertyDeclarationPreviewTrue = @"
class C{
public int Id { get; set; }
void Method()
{
//[
this.Id = 0;
//]
}
}";
private static readonly string s_propertyDeclarationPreviewFalse = @"
class C{
public int Id { get; set; }
void Method()
{
//[
Id = 0;
//]
}
}";
private static readonly string s_eventDeclarationPreviewTrue = @"
using System;
class C{
event EventHandler Elapsed;
void Handler(object sender, EventArgs args)
{
//[
this.Elapsed += Handler;
//]
}
}";
private static readonly string s_eventDeclarationPreviewFalse = @"
using System;
class C{
event EventHandler Elapsed;
void Handler(object sender, EventArgs args)
{
//[
Elapsed += Handler;
//]
}
}";
private static readonly string s_methodDeclarationPreviewTrue = @"
using System;
class C{
void Display()
{
//[
this.Display();
//]
}
}";
private static readonly string s_methodDeclarationPreviewFalse = @"
using System;
class C{
void Display()
{
//[
Display();
//]
}
}";
private static readonly string s_intrinsicPreviewDeclarationTrue = @"
class Program
{
//[
private int _member;
static void M(int argument)
{
int local;
}
//]
}";
private static readonly string s_intrinsicPreviewDeclarationFalse = @"
using System;
class Program
{
//[
private Int32 _member;
static void M(Int32 argument)
{
Int32 local;
}
//]
}";
private static readonly string s_intrinsicPreviewMemberAccessTrue = @"
class Program
{
//[
static void M()
{
var local = int.MaxValue;
}
//]
}";
private static readonly string s_intrinsicPreviewMemberAccessFalse = @"
using System;
class Program
{
//[
static void M()
{
var local = Int32.MaxValue;
}
//]
}";
private static readonly string s_varForIntrinsicsPreviewFalse = @"
using System;
class C{
void Method()
{
//[
int x = 5; // built-in types
//]
}
}";
private static readonly string s_varForIntrinsicsPreviewTrue = @"
using System;
class C{
void Method()
{
//[
var x = 5; // built-in types
//]
}
}";
private static readonly string s_varWhereApparentPreviewFalse = @"
using System;
class C{
void Method()
{
//[
C cobj = new C(); // type is apparent from assignment expression
//]
}
}";
private static readonly string s_varWhereApparentPreviewTrue = @"
using System;
class C{
void Method()
{
//[
var cobj = new C(); // type is apparent from assignment expression
//]
}
}";
private static readonly string s_varWherePossiblePreviewFalse = @"
using System;
class C{
void Init()
{
//[
Action f = this.Init(); // everywhere else.
//]
}
}";
private static readonly string s_varWherePossiblePreviewTrue = @"
using System;
class C{
void Init()
{
//[
var f = this.Init(); // everywhere else.
//]
}
}";
#endregion
internal StyleViewModel(OptionSet optionSet, IServiceProvider serviceProvider) : base(optionSet, serviceProvider, LanguageNames.CSharp)
{
var collectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(CodeStyleItems);
collectionView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(AbstractCodeStyleOptionViewModel.GroupName)));
var qualifyGroupTitle = CSharpVSResources.this_preferences_colon;
var predefinedTypesGroupTitle = CSharpVSResources.predefined_type_preferences_colon;
var varGroupTitle = CSharpVSResources.var_preferences_colon;
var qualifyMemberAccessPreferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Prefer_this, isChecked: true),
new CodeStylePreference(CSharpVSResources.Do_not_prefer_this, isChecked: false),
};
var predefinedTypesPreferences = new List<CodeStylePreference>
{
new CodeStylePreference(ServicesVSResources.Prefer_predefined_type, isChecked: true),
new CodeStylePreference(ServicesVSResources.Prefer_framework_type, isChecked: false),
};
var typeStylePreferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Prefer_var, isChecked: true),
new CodeStylePreference(CSharpVSResources.Prefer_explicit_type, isChecked: false),
};
CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.QualifyFieldAccess, CSharpVSResources.Qualify_field_access_with_this, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, this, optionSet, qualifyGroupTitle, qualifyMemberAccessPreferences));
CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.QualifyPropertyAccess, CSharpVSResources.Qualify_property_access_with_this, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, this, optionSet, qualifyGroupTitle, qualifyMemberAccessPreferences));
CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.QualifyMethodAccess, CSharpVSResources.Qualify_method_access_with_this, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, this, optionSet, qualifyGroupTitle, qualifyMemberAccessPreferences));
CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.QualifyEventAccess, CSharpVSResources.Qualify_event_access_with_this, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, this, optionSet, qualifyGroupTitle, qualifyMemberAccessPreferences));
CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, s_intrinsicPreviewDeclarationTrue, s_intrinsicPreviewDeclarationFalse, this, optionSet, predefinedTypesGroupTitle, predefinedTypesPreferences));
CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, s_intrinsicPreviewMemberAccessTrue, s_intrinsicPreviewMemberAccessFalse, this, optionSet, predefinedTypesGroupTitle, predefinedTypesPreferences));
CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, CSharpVSResources.For_built_in_types, s_varForIntrinsicsPreviewTrue, s_varForIntrinsicsPreviewFalse, this, optionSet, varGroupTitle, typeStylePreferences));
CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, CSharpVSResources.When_variable_type_is_apparent, s_varWhereApparentPreviewTrue, s_varWhereApparentPreviewFalse, this, optionSet, varGroupTitle, typeStylePreferences));
CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, CSharpVSResources.Elsewhere, s_varWherePossiblePreviewTrue, s_varWherePossiblePreviewFalse, this, optionSet, varGroupTitle, typeStylePreferences));
}
}
}
| |
using System;
using SuperSimple.Auth;
using Nancy;
using Nancy.Security;
using System.Linq;
using MtgDb.Info.Driver;
using System.Collections.Generic;
using System.Configuration;
using Nancy.ModelBinding;
using System.Reflection;
using Nancy.Validation;
namespace MtgDb.Info
{
public class CardModule : NancyModule
{
public IRepository repository =
new MongoRepository (ConfigurationManager.AppSettings.Get("db"));
public Db magicdb =
new Db (ConfigurationManager.AppSettings.Get("api"));
public CardModule ()
{
this.RequiresAuthentication ();
Get["/cr/{status?}"] = parameters => {
ChangeRequestModel model = new ChangeRequestModel();
string status = (string)parameters.status;
model.Planeswalker = (Planeswalker)this.Context.CurrentUser;
model.Title = "M:tgDb.Info Admin";
if(status == null)
{
model.Changes = repository.GetChangeRequests().ToList();
}
else
{
model.Changes = repository.GetChangeRequests(status).ToList();
}
return View["Change/ChangeRequests", model];
};
Get["/cards/{id}/logs"] = parameters => {
CardLogsModel model = new CardLogsModel();
model.ActiveMenu = "sets";
model.Planeswalker = (Planeswalker)this.Context.CurrentUser;
model.Mvid = (int)parameters.id;
try
{
model.Changes = repository.GetCardChangeRequests((int)parameters.id)
.OrderByDescending(x => x.Version)
.ToList();
}
catch(Exception e)
{
model.Errors.Add(e.Message);
}
return View["Change/CardLogs", model];
};
Get["/cards/{id}/logs/{logid}"] = parameters => {
CardChange model = new CardChange();
try
{
model = repository.GetCardChangeRequest((Guid)parameters.logid);
}
catch(Exception e)
{
model.Errors.Add(e.Message);
}
model.ActiveMenu = "sets";
model.Planeswalker = (Planeswalker)this.Context.CurrentUser;
model.Mvid = (int)parameters.id;
return View["Change/CardChange", model];
};
Post["/change/{id}/field/{field}"] = parameters => {
Admin admin = new Admin(ConfigurationManager.AppSettings.Get("api"));
Planeswalker planeswalker = (Planeswalker)this.Context.CurrentUser;
Guid changeId = Guid.Parse((string)parameters.id);
string field = (string)parameters.field;
CardChange change = null;
if(!planeswalker.InRole("admin"))
{
return HttpStatusCode.Unauthorized;
}
try
{
change = repository.GetCardChangeRequest(changeId);
if(field == "close")
{
repository.UpdateCardChangeStatus(change.Id, "Closed");
return Response.AsRedirect(string.Format("/cards/{0}/logs/{1}",
change.Mvid, change.Id));
}
if(field == "open")
{
repository.UpdateCardChangeStatus(change.Id, "Pending");
return Response.AsRedirect(string.Format("/cards/{0}/logs/{1}",
change.Mvid, change.Id));
}
if(field == "formats")
{
admin.UpdateCardFormats(planeswalker.AuthToken,
change.Mvid, change.Formats);
}
else if(field == "rulings")
{
admin.UpdateCardRulings(planeswalker.AuthToken,
change.Mvid, change.Rulings);
}
else
{
string value = change.GetFieldValue(field);
admin.UpdateCardField(planeswalker.AuthToken,
change.Mvid, field, (string)value);
}
repository.UpdateCardChangeStatus(change.Id, "Accepted", field);
}
catch(Exception e)
{
throw e;
}
return Response.AsRedirect(string.Format("/cards/{0}/logs/{1}",
change.Mvid, change.Id));
};
Get ["/cards/{id}/change"] = parameters => {
CardChange model = new CardChange();
Card card;
try
{
card = magicdb.GetCard((int)parameters.id);
model = CardChange.MapCard(card);
}
catch(Exception e)
{
throw e;
}
return View["Change/Card", model];
};
Post ["/cards/{id}/change"] = parameters => {
CardChange model = this.Bind<CardChange>();
Card current = magicdb.GetCard((int)parameters.id);
model.CardSetId = current.CardSetId;
model.CardSetName = current.CardSetName;
model.Name = current.Name;
model.Mvid = (int)parameters.id;
model.Rulings = Bind.Rulings(Request);
model.Formats = Bind.Formats(Request);
model.Planeswalker = (Planeswalker)this.Context.CurrentUser;
model.UserId = model.Planeswalker.Id;
CardChange card = null;
var result = this.Validate(model);
if (!result.IsValid)
{
model.Errors = ErrorUtility.GetValidationErrors(result);
return View["Change/Card", model];
}
try
{
card = repository.GetCardChangeRequest(
repository.AddCardChangeRequest(model)
);
}
catch(Exception e)
{
model.Errors.Add(e.Message);
return View["Change/Card", model];
}
return Response.AsRedirect(string.Format("/cards/{0}/logs?v={1}",
card.Mvid, card.Version));
//return model.Description;
//return View["Change/Card", model];
};
Post ["/cards/{id}/amount/{count}"] = parameters => {
int multiverseId = (int)parameters.id;
int count = (int)parameters.count;
Guid walkerId = ((Planeswalker)this.Context.CurrentUser).Id;
repository.AddUserCard(walkerId,multiverseId,count);
return count.ToString();
};
//TODO: Refactor this, to long and confusing
Get ["/pw/{planeswalker}/blocks/{block}/cards/{setId?}"] = parameters => {
PlaneswalkerModel model = new PlaneswalkerModel();
model.ActiveMenu = "mycards";
string setId = (string)parameters.setId;
model.Block = (string)parameters.block;
model.Planeswalker = (Planeswalker)this.Context.CurrentUser;
if(model.Planeswalker.UserName.ToLower() !=
((string)parameters.planeswalker).ToLower())
{
model.Errors.Add(string.Format("Tsk Tsk! {0}, this profile is not yours.",
model.Planeswalker.UserName));
return View["Page", model];
}
try
{
model.Counts = repository.GetSetCardCounts(model.Planeswalker.Id);
if(model.Counts == null ||
model.Counts.Count == 0)
{
return Response.AsRedirect("~/" + model.Planeswalker.UserName +
"/cards");
}
model.TotalCards = model.Counts.Sum(x => x.Value);
model.TotalAmount = repository.GetUserCards(model.Planeswalker.Id).Sum(x => x.Amount);
string[] blocks;
if(model.Counts.Count > 0)
{
model.Sets = magicdb.GetSets(model.Counts
.AsEnumerable().Select(x => x.Key)
.ToArray());
blocks = model.Sets.Select(x => x.Block).Distinct().OrderBy(x => x).ToArray();
foreach(string block in blocks)
{
CardSet[] sets = model.Sets.Where(x => x.Block == block).ToArray();
int total = 0;
foreach(CardSet set in sets)
{
total += model.Counts[set.Id];
}
model.Blocks.Add(block,total);
}
model.Sets = model.Sets
.Where(x => x.Block == model.Block)
.OrderBy(x => x.Name).ToArray();
if(model.Sets == null || model.Sets.Length == 0)
{
return Response.AsRedirect(string.Format("~/{0}/cards",
model.Planeswalker.UserName));
}
if(setId == null)
{
setId = model.Sets.FirstOrDefault().Id;
}
model.SetId = setId;
model.UserCards = repository.GetUserCards(model.Planeswalker.Id, setId);
if(model.UserCards == null ||
model.UserCards.Length == 0)
{
return Response.AsRedirect(string.Format("~/{0}/cards",
model.Planeswalker.UserName));
}
Card[] dbcards = null;
if(Request.Query.Show != null)
{
dbcards = magicdb.GetSetCards(model.SetId);
model.Show = true;
}
else
{
dbcards = magicdb.GetCards(model.UserCards
.AsEnumerable()
.Where(x => x.Amount > 0)
.Select(x => x.MultiverseId)
.ToArray());
model.Show = false;
}
if(dbcards == null ||
dbcards.Length == 0)
{
return Response.AsRedirect(string.Format("~/{0}/cards",
model.Planeswalker.UserName));
}
List<CardInfo> cards = new List<CardInfo>();
CardInfo card = null;
foreach(Card c in dbcards)
{
card = new CardInfo();
card.Amount = model.UserCards
.AsEnumerable()
.Where(x => x.MultiverseId == c.Id)
.Select(x => x.Amount)
.FirstOrDefault();
card.Card = c;
cards.Add(card);
}
model.Cards = cards.OrderBy(x => x.Card.SetNumber).ToArray();
}
else
{
model.Messages.Add("You have no cards in your library.");
}
}
catch(Exception e)
{
model.Errors.Add(e.Message);
}
return View["MyCards", model];
};
Get ["/pw/{planeswalker}/cards"] = parameters => {
PageModel model = new PageModel();
model.ActiveMenu = "mycards";
model.Planeswalker = (Planeswalker)this.Context.CurrentUser;
if(model.Planeswalker.UserName.ToLower() !=
((string)parameters.planeswalker).ToLower())
{
model.Errors.Add(string.Format("Tsk Tsk! {0}, this profile is not yours.",
model.Planeswalker.UserName));
return View["Page", model];
}
try
{
string setId = repository.GetSetCardCounts(model.Planeswalker.Id)
.Select(x => x.Key)
.OrderBy(x => x).FirstOrDefault();
if(setId != null)
{
CardSet s = magicdb.GetSet(setId);
return Response.AsRedirect(string.Format("/pw/{0}/blocks/{1}/cards",
model.Planeswalker.UserName, s.Block ));
}
model.Information.Add("You have no cards yet in your library. " +
"Browse the sets and start adding cards Planeswalker!");
}
catch(Exception e)
{
model.Errors.Add(e.Message);
}
return View["Page", model];
};
}
}
}
| |
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 Provisioning.Extensibility.Providers
{
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
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Management.Automation.Language;
using System.Collections.ObjectModel;
using System.Management.Automation.Internal;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// The base class for all command processor classes. It provides
/// abstract methods to execute a command.
/// </summary>
internal abstract class CommandProcessorBase : IDisposable
{
#region ctor
/// <summary>
/// Default constructor
/// </summary>
///
internal CommandProcessorBase()
{
}
/// <summary>
/// Initializes the base command processor class with the command metadata
/// </summary>
///
/// <param name="commandInfo">
/// The metadata about the command to run.
/// </param>
///
internal CommandProcessorBase(
CommandInfo commandInfo)
{
if (commandInfo == null)
{
throw PSTraceSource.NewArgumentNullException("commandInfo");
}
CommandInfo = commandInfo;
}
#endregion ctor
#region properties
private InternalCommand _command;
// marker of whether BeginProcessing() has already run,
// also used by CommandProcessor
internal bool RanBeginAlready;
// marker of whether this command has already been added to
// a PipelineProcessor. It is an error to add the same command
// more than once.
internal bool AddedToPipelineAlready
{
get { return _addedToPipelineAlready; }
set { _addedToPipelineAlready = value; }
}
internal bool _addedToPipelineAlready;
/// <summary>
/// Gets the CommandInfo for the command this command processor represents
/// </summary>
/// <value></value>
internal CommandInfo CommandInfo { get; set; }
/// <summary>
/// This indicates whether this command processor is created from
/// a script file.
/// </summary>
/// <remarks>
/// Script command processor created from a script file is special
/// in following two perspectives,
///
/// 1. New scope created needs to be a 'script' scope in the
/// sense that it needs to handle $script: variables.
/// For normal functions or scriptblocks, script scope
/// variables are not supported.
///
/// 2. ExitException will be handled by setting lastExitCode.
/// For normal functions or scriptblocks, exit command will
/// kill current powershell session.
/// </remarks>
public bool FromScriptFile { get { return _fromScriptFile; } }
protected bool _fromScriptFile = false;
/// <summary>
/// If this flag is true, the commands in this Pipeline will redirect
/// the global error output pipe to the command's error output pipe.
///
/// (see the comment in Pipeline.RedirectShellErrorOutputPipe for an
/// explanation of why this flag is needed)
/// </summary>
internal bool RedirectShellErrorOutputPipe { get; set; } = false;
/// <summary>
/// Gets or sets the command object.
/// </summary>
internal InternalCommand Command
{
get { return _command; }
set
{
// The command runtime needs to be set up...
if (value != null)
{
value.commandRuntime = this.commandRuntime;
if (_command != null)
value.CommandInfo = _command.CommandInfo;
// Set the execution context for the command it's currently
// null and our context has already been set up.
if (value.Context == null && _context != null)
value.Context = _context;
}
_command = value;
}
}
/// <summary>
/// Get the ObsoleteAttribute of the current command
/// </summary>
internal virtual ObsoleteAttribute ObsoleteAttribute
{
get { return null; }
}
// Full Qualified ID for the obsolete command warning
private const string FQIDCommandObsolete = "CommandObsolete";
/// <summary>
/// The command runtime used for this instance of a command processor.
/// </summary>
protected MshCommandRuntime commandRuntime;
internal MshCommandRuntime CommandRuntime
{
get { return commandRuntime; }
set { commandRuntime = value; }
}
/// <summary>
/// For commands that use the scope stack, if this flag is
/// true, don't create a new scope when running this command.
/// </summary>
/// <value></value>
internal bool UseLocalScope
{
get { return _useLocalScope; }
set { _useLocalScope = value; }
}
protected bool _useLocalScope;
/// <summary>
/// Ensures that the provided script block is compatible with the current language mode - to
/// be used when a script block is being dotted.
/// </summary>
/// <param name="scriptBlock">The script block being dotted</param>
/// <param name="languageMode">The current language mode</param>
/// <param name="invocationInfo">The invocation info about the command</param>
protected static void ValidateCompatibleLanguageMode(ScriptBlock scriptBlock,
PSLanguageMode languageMode,
InvocationInfo invocationInfo)
{
// If we are in a constrained language mode (Core or Restricted), block it.
// We are currently restricting in one direction:
// - Can't dot something from a more permissive mode, since that would probably expose
// functions that were never designed to handle untrusted data.
// This function won't be called for NoLanguage mode so the only direction checked is trusted
// (FullLanguage mode) script running in a constrained/restricted session.
if ((scriptBlock.LanguageMode.HasValue) &&
(scriptBlock.LanguageMode != languageMode) &&
((languageMode == PSLanguageMode.RestrictedLanguage) ||
(languageMode == PSLanguageMode.ConstrainedLanguage)))
{
// Finally check if script block is really just PowerShell commands plus parameters.
// If so then it is safe to dot source across language mode boundaries.
bool isSafeToDotSource = false;
try
{
scriptBlock.GetPowerShell();
isSafeToDotSource = true;
}
catch (Exception e)
{
CheckForSevereException(e);
}
if (!isSafeToDotSource)
{
ErrorRecord errorRecord = new ErrorRecord(
new NotSupportedException(
DiscoveryExceptions.DotSourceNotSupported),
"DotSourceNotSupported",
ErrorCategory.InvalidOperation,
null);
errorRecord.SetInvocationInfo(invocationInfo);
throw new CmdletInvocationException(errorRecord);
}
}
}
/// <summary>
/// The execution context used by the system.
/// </summary>
protected ExecutionContext _context;
internal ExecutionContext Context
{
get { return _context; }
set { _context = value; }
}
/// <summary>
/// Etw activity for this pipeline
/// </summary>
internal Guid PipelineActivityId { get; set; } = Guid.Empty;
#endregion properties
#region methods
#region handling of -? parameter
/// <summary>
/// Checks if user has requested help (for example passing "-?" parameter for a cmdlet)
/// and if yes, then returns the help target to display.
/// </summary>
/// <param name="helpTarget">help target to request</param>
/// <param name="helpCategory">help category to request</param>
/// <returns><c>true</c> if user requested help; <c>false</c> otherwise</returns>
internal virtual bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
{
// by default we don't handle "-?" parameter at all
// (we want to do the checks only for cmdlets - this method is overridden in CommandProcessor)
helpTarget = null;
helpCategory = HelpCategory.None;
return false;
}
/// <summary>
/// Creates a command processor for "get-help [helpTarget]"
/// </summary>
/// <param name="context">context for the command processor</param>
/// <param name="helpTarget">help target</param>
/// <param name="helpCategory">help category</param>
/// <returns>command processor for "get-help [helpTarget]"</returns>
internal static CommandProcessorBase CreateGetHelpCommandProcessor(
ExecutionContext context,
string helpTarget,
HelpCategory helpCategory)
{
if (context == null)
{
throw PSTraceSource.NewArgumentNullException("context");
}
if (string.IsNullOrEmpty(helpTarget))
{
throw PSTraceSource.NewArgumentNullException("helpTarget");
}
CommandProcessorBase helpCommandProcessor = context.CreateCommand("get-help", false);
var cpi = CommandParameterInternal.CreateParameterWithArgument(
PositionUtilities.EmptyExtent, "Name", "-Name:",
PositionUtilities.EmptyExtent, helpTarget,
false);
helpCommandProcessor.AddParameter(cpi);
cpi = CommandParameterInternal.CreateParameterWithArgument(
PositionUtilities.EmptyExtent, "Category", "-Category:",
PositionUtilities.EmptyExtent, helpCategory.ToString(),
false);
helpCommandProcessor.AddParameter(cpi);
return helpCommandProcessor;
}
#endregion
/// <summary>
/// Tells whether pipeline input is expected or not.
/// </summary>
/// <returns>A bool indicating whether pipeline input is expected.</returns>
internal bool IsPipelineInputExpected()
{
return commandRuntime.IsPipelineInputExpected;
}
/// <summary>
/// If you want this command to execute in other than the default session
/// state, use this API to get and set that session state instance...
/// </summary>
internal SessionStateInternal CommandSessionState { get; set; }
/// <summary>
/// Gets sets the session state scope for this command processor object
/// </summary>
protected internal SessionStateScope CommandScope { get; protected set; }
protected virtual void OnSetCurrentScope()
{
}
protected virtual void OnRestorePreviousScope()
{
}
/// <summary>
/// This method sets the current session state scope to the execution scope for the pipeline
/// that was stored in the pipeline manager when it was first invoked.
/// </summary>
internal void SetCurrentScopeToExecutionScope()
{
// Make sure we have a session state instance for this command.
// If one hasn't been explicitly set, then use the session state
// available on the engine execution context...
if (CommandSessionState == null)
{
CommandSessionState = Context.EngineSessionState;
}
// Store off the current scope
_previousScope = CommandSessionState.CurrentScope;
_previousCommandSessionState = Context.EngineSessionState;
Context.EngineSessionState = CommandSessionState;
// Set the current scope to the pipeline execution scope
CommandSessionState.CurrentScope = CommandScope;
OnSetCurrentScope();
}
/// <summary>
/// Restores the current session state scope to the scope which was active when SetCurrentScopeToExecutionScope
/// was called.
/// </summary>
///
internal void RestorePreviousScope()
{
OnRestorePreviousScope();
Context.EngineSessionState = _previousCommandSessionState;
if (_previousScope != null)
{
// Restore the scope but use the same session state instance we
// got it from because the command may have changed the execution context
// session state...
CommandSessionState.CurrentScope = _previousScope;
}
}
private SessionStateScope _previousScope;
private SessionStateInternal _previousCommandSessionState;
/// <summary>
/// A collection of arguments that have been added by the parser or
/// host interfaces. These will be sent to the parameter binder controller
/// for processing.
/// </summary>
///
internal Collection<CommandParameterInternal> arguments = new Collection<CommandParameterInternal>();
/// <summary>
/// Adds an unbound parameter.
/// </summary>
/// <param name="parameter">
/// The parameter to add to the unbound arguments list
/// </param>
internal void AddParameter(CommandParameterInternal parameter)
{
Diagnostics.Assert(parameter != null, "Caller to verify parameter argument");
arguments.Add(parameter);
} // AddParameter
/// <summary>
/// Prepares the command for execution.
/// This should be called once before ProcessRecord().
/// </summary>
internal abstract void Prepare(IDictionary psDefaultParameterValues);
/// <summary>
/// Write warning message for an obsolete command
/// </summary>
/// <param name="obsoleteAttr"></param>
private void HandleObsoleteCommand(ObsoleteAttribute obsoleteAttr)
{
string commandName =
String.IsNullOrEmpty(CommandInfo.Name)
? "script block"
: String.Format(System.Globalization.CultureInfo.InvariantCulture,
CommandBaseStrings.ObsoleteCommand, CommandInfo.Name);
string warningMsg = String.Format(
System.Globalization.CultureInfo.InvariantCulture,
CommandBaseStrings.UseOfDeprecatedCommandWarning,
commandName, obsoleteAttr.Message);
// We ignore the IsError setting because we don't want to break people when obsoleting a command
using (this.CommandRuntime.AllowThisCommandToWrite(false))
{
this.CommandRuntime.WriteWarning(new WarningRecord(FQIDCommandObsolete, warningMsg));
}
}
/// <summary>
/// Sets the execution scope for the pipeline and then calls the Prepare
/// abstract method which gets overridden by derived classes.
/// </summary>
internal void DoPrepare(IDictionary psDefaultParameterValues)
{
CommandProcessorBase oldCurrentCommandProcessor = _context.CurrentCommandProcessor;
try
{
Context.CurrentCommandProcessor = this;
SetCurrentScopeToExecutionScope();
Prepare(psDefaultParameterValues);
// Check obsolete attribute after Prepare so that -WarningAction will be respected for cmdlets
if (ObsoleteAttribute != null)
{
// Obsolete command is rare. Put the IF here to avoid method call overhead
HandleObsoleteCommand(ObsoleteAttribute);
}
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
if (_useLocalScope)
{
// If we had an exception during Prepare, we're done trying to execute the command
// so the scope we created needs to release any resources it hold.s
CommandSessionState.RemoveScope(CommandScope);
}
throw;
}
finally
{
Context.CurrentCommandProcessor = oldCurrentCommandProcessor;
RestorePreviousScope();
}
}
/// <summary>
/// Called once before ProcessRecord(). Internally it calls
/// BeginProcessing() of the InternalCommand.
/// </summary>
/// <exception cref="PipelineStoppedException">
/// a terminating error occurred, or the pipeline was otherwise stopped
/// </exception>
internal virtual void DoBegin()
{
// Note that DoPrepare() and DoBegin() should NOT be combined.
// Reason: Encoding of commandline parameters happen as part
// of DoPrepare(). If they are combined, the first command's
// DoBegin() will be called before the next command's
// DoPrepare(). Since BeginProcessing() can write objects
// to the downstream commandlet, it will end up calling
// DoExecute() (from Pipe.Add()) before DoPrepare.
if (!RanBeginAlready)
{
RanBeginAlready = true;
Pipe oldErrorOutputPipe = _context.ShellFunctionErrorOutputPipe;
CommandProcessorBase oldCurrentCommandProcessor = _context.CurrentCommandProcessor;
try
{
//
// On V1 the output pipe was redirected to the command's output pipe only when it
// was already redirected. This is the original comment explaining this behaviour:
//
// NTRAID#Windows Out of Band Releases-926183-2005-12-15
// MonadTestHarness has a bad dependency on an artifact of the current implementation
// The following code only redirects the output pipe if it's already redirected
// to preserve the artifact. The test suites need to be fixed and then this
// the check can be removed and the assignment always done.
//
// However, this makes the hosting APIs behave differently than commands executed
// from the command-line host (for example, see bugs Win7:415915 and Win7:108670).
// The RedirectShellErrorOutputPipe flag is used by the V2 hosting API to force the
// redirection.
//
if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe != null)
{
_context.ShellFunctionErrorOutputPipe = this.commandRuntime.ErrorOutputPipe;
}
_context.CurrentCommandProcessor = this;
using (commandRuntime.AllowThisCommandToWrite(true))
{
using (ParameterBinderBase.bindingTracer.TraceScope(
"CALLING BeginProcessing"))
{
SetCurrentScopeToExecutionScope();
if (Context._debuggingMode > 0 && !(Command is PSScriptCmdlet))
{
Context.Debugger.CheckCommand(this.Command.MyInvocation);
}
Command.DoBeginProcessing();
}
}
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
// This cmdlet threw an exception, so
// wrap it and bubble it up.
throw ManageInvocationException(e);
}
finally
{
_context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe;
_context.CurrentCommandProcessor = oldCurrentCommandProcessor;
RestorePreviousScope();
}
}
}
/// <summary>
/// This calls the command. It assumes that DoPrepare() has already been called.
/// </summary>
internal abstract void ProcessRecord();
/// <summary>
/// This method sets the execution scope to the
/// appropriate scope for the pipeline and then calls
/// the ProcessRecord abstract method that derived command processors
/// override.
/// </summary>
///
internal void DoExecute()
{
ExecutionContext.CheckStackDepth();
CommandProcessorBase oldCurrentCommandProcessor = _context.CurrentCommandProcessor;
try
{
Context.CurrentCommandProcessor = this;
SetCurrentScopeToExecutionScope();
ProcessRecord();
}
finally
{
Context.CurrentCommandProcessor = oldCurrentCommandProcessor;
RestorePreviousScope();
}
}
/// <summary>
/// Called once after ProcessRecord().
/// Internally it calls EndProcessing() of the InternalCommand.
/// </summary>
/// <exception cref="PipelineStoppedException">
/// a terminating error occurred, or the pipeline was otherwise stopped
/// </exception>
internal virtual void Complete()
{
// Call ProcessRecord once from complete. Don't call DoExecute...
ProcessRecord();
try
{
using (commandRuntime.AllowThisCommandToWrite(true))
{
using (ParameterBinderBase.bindingTracer.TraceScope(
"CALLING EndProcessing"))
{
this.Command.DoEndProcessing();
}
}
}
// 2004/03/18-JonN This is understood to be
// an FXCOP violation, cleared by KCwalina.
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
// This cmdlet threw an exception, so
// wrap it and bubble it up.
throw ManageInvocationException(e);
}
} // Complete
/// <summary>
/// Calls the virtual Complete method after setting the appropriate session state scope
/// </summary>
///
internal void DoComplete()
{
Pipe oldErrorOutputPipe = _context.ShellFunctionErrorOutputPipe;
CommandProcessorBase oldCurrentCommandProcessor = _context.CurrentCommandProcessor;
try
{
//
// On V1 the output pipe was redirected to the command's output pipe only when it
// was already redirected. This is the original comment explaining this behaviour:
//
// NTRAID#Windows Out of Band Releases-926183-2005-12-15
// MonadTestHarness has a bad dependency on an artifact of the current implementation
// The following code only redirects the output pipe if it's already redirected
// to preserve the artifact. The test suites need to be fixed and then this
// the check can be removed and the assignment always done.
//
// However, this makes the hosting APIs behave differently than commands executed
// from the command-line host (for example, see bugs Win7:415915 and Win7:108670).
// The RedirectShellErrorOutputPipe flag is used by the V2 hosting API to force the
// redirection.
//
if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe != null)
{
_context.ShellFunctionErrorOutputPipe = this.commandRuntime.ErrorOutputPipe;
}
_context.CurrentCommandProcessor = this;
SetCurrentScopeToExecutionScope();
Complete();
}
finally
{
OnRestorePreviousScope();
_context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe;
_context.CurrentCommandProcessor = oldCurrentCommandProcessor;
// Destroy the local scope at this point if there is one...
if (_useLocalScope && CommandScope != null)
{
CommandSessionState.RemoveScope(CommandScope);
}
// and the previous scope...
if (_previousScope != null)
{
// Restore the scope but use the same session state instance we
// got it from because the command may have changed the execution context
// session state...
CommandSessionState.CurrentScope = _previousScope;
}
// Restore the previous session state
if (_previousCommandSessionState != null)
{
Context.EngineSessionState = _previousCommandSessionState;
}
}
}
/// <summary>
/// for diagnostic purposes
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (null != CommandInfo)
return CommandInfo.ToString();
return "<NullCommandInfo>"; // does not require localization
}
/// <summary>
/// True if Read() has not be called, false otherwise.
/// </summary>
private bool _firstCallToRead = true;
/// <summary>
/// Entry point used by the engine to reads the input pipeline object
/// and binds the parameters.
///
/// This default implementation reads the next pipeline object and sets
/// it as the CurrentPipelineObject in the InternalCommand.
/// </summary>
///
/// <returns>
/// True if read succeeds.
/// </returns>
///
/// does not throw
internal virtual bool Read()
{
// Prepare the default value parameter list if this is the first call to Read
if (_firstCallToRead)
{
_firstCallToRead = false;
}
// Retrieve the object from the input pipeline
object inputObject = this.commandRuntime.InputPipe.Retrieve();
if (inputObject == AutomationNull.Value)
{
return false;
}
// If we are reading input for the first command in the pipeline increment PipelineIterationInfo[0], which is the number of items read from the input
if (this.Command.MyInvocation.PipelinePosition == 1)
{
this.Command.MyInvocation.PipelineIterationInfo[0]++;
}
Command.CurrentPipelineObject = LanguagePrimitives.AsPSObjectOrNull(inputObject);
return true;
}
#if CORECLR
// AccessViolationException/StackOverflowException Not In CoreCLR.
// The CoreCLR team told us to not check for these exceptions because they
// usually won't be caught.
internal static void CheckForSevereException(Exception e) { }
#else
// Keep in sync:
// S.M.A.CommandProcessorBase.CheckForSevereException
// S.M.A.Internal.ConsoleHost.CheckForSevereException
// S.M.A.Commands.CommandsCommon.CheckForSevereException
// S.M.A.Commands.UtilityCommon.CheckForSevereException
/// <summary>
/// Checks whether the exception is a severe exception which should
/// cause immediate process failure.
/// </summary>
/// <param name="e"></param>
/// <remarks>
/// CB says 02/23/2005: I personally would err on the side
/// of treating OOM like an application exception, rather than
/// a critical system failure.I think this will be easier to justify
/// in Orcas, if we tease apart the two cases of OOM better.
/// But even in Whidbey, how likely is it that we couldnt JIT
/// some backout code? At that point, the process or possibly
/// the machine is likely to stop executing soon no matter
/// what you do in this routine. So I would just consider
/// AccessViolationException. (I understand why you have SO here,
/// at least temporarily).
/// </remarks>
internal static void CheckForSevereException(Exception e)
{
if (e is AccessViolationException || e is StackOverflowException)
{
try
{
if (!alreadyFailing)
{
alreadyFailing = true;
// Get the ExecutionContext from the thread.
ExecutionContext context = Runspaces.LocalPipeline.GetExecutionContextFromTLS();
// Log a command health event for this critical error.
MshLog.LogCommandHealthEvent(context, e, Severity.Critical);
}
}
finally
{
WindowsErrorReporting.FailFast(e);
}
}
}
private static bool alreadyFailing = false;
#endif
/// <summary>
/// Wraps the exception which occurred during cmdlet invocation,
/// stores that as the exception to be returned from
/// PipelineProcessor.SynchronousExecute, and writes it to
/// the error variable.
/// </summary>
///
/// <param name="e">
/// The exception to wrap in a CmdletInvocationException or
/// CmdletProviderInvocationException.
/// </param>
///
/// <returns>
/// Always returns PipelineStoppedException. The caller should
/// throw this exception.
/// </returns>
///
/// <remarks>
/// Almost all exceptions which occur during pipeline invocation
/// are wrapped in CmdletInvocationException before they are stored
/// in the pipeline. However, there are several exceptions:
///
/// AccessViolationException, StackOverflowException:
/// These are considered to be such severe errors that we
/// FailFast the process immediately.
///
/// ProviderInvocationException: In this case, we assume that the
/// cmdlet is get-item or the like, a thin wrapper around the
/// provider API. We discard the original ProviderInvocationException
/// and re-wrap its InnerException (the real error) in
/// CmdletProviderInvocationException. This makes it easier to reach
/// the real error.
///
/// CmdletInvocationException, ActionPreferenceStopException:
/// This indicates that the cmdlet itself ran a command which failed.
/// We could go ahead and wrap the original exception in multiple
/// layers of CmdletInvocationException, but this makes it difficult
/// for the caller to access the root problem, plus the serialization
/// layer might not communicate properties beyond some fixed depth.
/// Instead, we choose to not re-wrap the exception.
///
/// PipelineStoppedException: This could mean one of two things.
/// It usually means that this pipeline has already stopped,
/// in which case the pipeline already stores the original error.
/// It could also mean that the cmdlet ran a command which was
/// stopped by CTRL-C etc, in which case we choose not to
/// re-wrap the exception as with CmdletInvocationException.
/// </remarks>
internal PipelineStoppedException ManageInvocationException(Exception e)
{
try
{
if (null != Command)
{
do // false loop
{
ProviderInvocationException pie = e as ProviderInvocationException;
if (pie != null)
{
// If a ProviderInvocationException occurred,
// discard the ProviderInvocationException and
// re-wrap in CmdletProviderInvocationException
e = new CmdletProviderInvocationException(
pie,
Command.MyInvocation);
break;
}
// 1021203-2005/05/09-JonN
// HaltCommandException will cause the command
// to stop, but not be reported as an error.
// 906445-2005/05/16-JonN
// FlowControlException should not be wrapped
if (e is PipelineStoppedException
|| e is CmdletInvocationException
|| e is ActionPreferenceStopException
|| e is HaltCommandException
|| e is FlowControlException
|| e is ScriptCallDepthException)
{
// do nothing; do not rewrap these exceptions
break;
}
RuntimeException rte = e as RuntimeException;
if (rte != null && rte.WasThrownFromThrowStatement)
{
// do not rewrap a script based throw
break;
}
// wrap all other exceptions
e = new CmdletInvocationException(
e,
Command.MyInvocation);
} while (false);
// commandRuntime.ManageException will always throw PipelineStoppedException
// Otherwise, just return this exception...
// If this exception happened in a transacted cmdlet,
// rollback the transaction
if (commandRuntime.UseTransaction)
{
// The "transaction timed out" exception is
// exceedingly obtuse. We clarify things here.
bool isTimeoutException = false;
Exception tempException = e;
while (tempException != null)
{
if (tempException is System.TimeoutException)
{
isTimeoutException = true;
break;
}
tempException = tempException.InnerException;
}
if (isTimeoutException)
{
ErrorRecord errorRecord = new ErrorRecord(
new InvalidOperationException(
TransactionStrings.TransactionTimedOut),
"TRANSACTION_TIMEOUT",
ErrorCategory.InvalidOperation,
e);
errorRecord.SetInvocationInfo(Command.MyInvocation);
e = new CmdletInvocationException(errorRecord);
}
// Rollback the transaction in the case of errors.
if (
_context.TransactionManager.HasTransaction
&&
_context.TransactionManager.RollbackPreference != RollbackSeverity.Never
)
{
Context.TransactionManager.Rollback(true);
}
}
return (PipelineStoppedException)this.commandRuntime.ManageException(e);
}
// Upstream cmdlets see only that execution stopped
// This should only happen if Command is null
return new PipelineStoppedException();
}
catch (Exception)
{
// this method should not throw exceptions; warn about any violations on checked builds and re-throw
Diagnostics.Assert(false, "This method should not throw exceptions!");
throw;
}
}
/// <summary>
/// Stores the exception to be returned from
/// PipelineProcessor.SynchronousExecute, and writes it to
/// the error variable.
/// </summary>
///
/// <param name="e">
/// The exception which occurred during script execution
/// </param>
///
/// <exception cref="PipelineStoppedException">
/// ManageScriptException throws PipelineStoppedException if-and-only-if
/// the exception is a RuntimeException, otherwise it returns.
/// This allows the caller to rethrow unexpected exceptions.
/// </exception>
internal void ManageScriptException(RuntimeException e)
{
if (null != Command && null != commandRuntime.PipelineProcessor)
{
commandRuntime.PipelineProcessor.RecordFailure(e, Command);
// An explicit throw is written to $error as an ErrorRecord, so we
// skip adding what is more or less a duplicate.
if (!(e is PipelineStoppedException) && !e.WasThrownFromThrowStatement)
commandRuntime.AppendErrorToVariables(e);
}
// Upstream cmdlets see only that execution stopped
throw new PipelineStoppedException();
}
/// <summary>
/// Sometimes we shouldn't be rethrow the exception we previously caught,
/// such as when the exception is handled by a trap.
/// </summary>
internal void ForgetScriptException()
{
if (null != Command && null != commandRuntime.PipelineProcessor)
{
commandRuntime.PipelineProcessor.ForgetFailure();
}
}
#endregion methods
#region IDispose
// 2004/03/05-JonN BrucePay has suggested that the IDispose
// implementations in PipelineProcessor and CommandProcessor can be
// removed.
private bool _disposed;
/// <summary>
/// IDisposable implementation
/// When the command is complete, the CommandProcessorBase should be disposed.
/// This enables cmdlets to reliably release file handles etc.
/// without waiting for garbage collection
/// </summary>
/// <remarks>We use the standard IDispose pattern</remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
// 2004/03/05-JonN Look into using metadata to check
// whether IDisposable is implemented, in order to avoid
// this expensive reflection cast.
IDisposable id = Command as IDisposable;
if (null != id)
{
id.Dispose();
}
}
_disposed = true;
}
/// <summary>
/// Finalizer for class CommandProcessorBase
/// </summary>
~CommandProcessorBase()
{
Dispose(false);
}
#endregion IDispose
}
}
| |
using System;
using HalconDotNet;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace MatchingModule
{
/// <summary>
/// This class optimizes the performance of a defined shape-based model
/// for a given set of test images.
/// To perform an optimization of the detection parameters, the instance
/// has to know the used set of matching parameters and the calling
/// MatchingAssistant, to retrieve the set of test images and to call
/// the methods for finding the model.
/// The optimization is performed in the sense that the two detection
/// parameters ScoreMin and Greediness are iteratively increased and
/// decreased, respectively, and every new parameter combination is used
/// to detect the model in the set of test images. Each performance is
/// then measured and compared with the best performance so far.
/// The single execution steps are triggered by a timer from the
/// class MatchingAssistant, so that you can stop the optimization anytime
/// during the run.
/// </summary>
public class MatchingOptSpeed: MatchingOpt
{
// private class members
private int mCurrScoreMin;
private int mCurrGreediness;
private double mCurrMeanTime;
private int mScoreMinStep;
private int mGreedinessStep;
private int mOptScoreMin;
private int mOptGreediness;
private double mOptMeanTime;
private int mMatchesNum;
private int mExpMatchesNum;
/// <summary>Constructor</summary>
/// <param name="mAss">MatchingAssistant that created this instance</param>
/// <param name="mPars">Current set of matching parameters</param>
public MatchingOptSpeed(MatchingAssistant mAss, MatchingParam mPars)
{
mAssistant = mAss;
mParams = mPars;
NotifyStatisticsObserver = new StatisticsDelegate(dummy);
mScoreMinStep = -10;
mGreedinessStep = 10;
reset();
tImageCount = mAssistant.TestImages.Count;
}
/// <summary>
/// In each execution step a certain parameter set is applied
/// to the whole set of test images and the performance is then
/// evaluated.
/// </summary>
public override bool ExecuteStep()
{
double cScoreMin, cGreed, recogRate;
string fileName;
int actualMatches, expectedMatches;
bool success;
if(!iterator.MoveNext())
return false;
cScoreMin = mCurrScoreMin / 100.0;
cGreed = mCurrGreediness / 100.0;
statusString = "Testing Image " + (mCurrentIndex + 1) +
" - Minimum Score: " + cScoreMin +
" - Greediness: " + cGreed;
NotifyStatisticsObserver(MatchingOpt.UPDATE_RECOG_STATISTICS_STATUS);
fileName = (string)iterator.Current;
mAssistant.setTestImage(fileName);
mAssistant.setMinScore(cScoreMin);
mAssistant.setGreediness(cGreed);
if(!mAssistant.applyFindModel())
return false;
mResults = mAssistant.getMatchingResults();
actualMatches = mResults.count;
expectedMatches = 0;
switch(mParams.mRecogSpeedMode)
{
case MatchingParam.RECOGM_MANUALSELECT:
expectedMatches = mParams.mRecogManualSel;
break;
case MatchingParam.RECOGM_ATLEASTONE:
expectedMatches = 1;
if(actualMatches > 1)
actualMatches = 1;
break;
case MatchingParam.RECOGM_MAXNUMBER:
expectedMatches = mParams.mNumMatches;
break;
default:
break;
}
mMatchesNum += actualMatches;
mExpMatchesNum += expectedMatches;
recogRate = (mExpMatchesNum > 0) ?
(100.0 * mMatchesNum / mExpMatchesNum) : 0.0;
mCurrMeanTime = mCurrMeanTime * mCurrentIndex + mResults.mTime;
mCurrMeanTime /= ++mCurrentIndex;
//write data into strings and call for update
recogTabOptimizationData [0] = "" + Math.Round(cScoreMin, 2);
recogTabOptimizationData [1] = "" + Math.Round(cGreed, 2);
recogTabOptimizationData [2] = "" + Math.Round(recogRate, 2) + " %";
if( mCurrMeanTime < 1000.0 )
recogTabOptimizationData [3] = Math.Round(mCurrMeanTime, 2) + " ms";
else
recogTabOptimizationData [3] = Math.Round(mCurrMeanTime/1000.0, 2)+ " s";
NotifyStatisticsObserver(MatchingOpt.UPDATE_RECOG_UPDATE_VALS);
if(mCurrentIndex < tImageCount)
return true;
iterator.Reset();
mCurrentIndex = 0;
mMatchesNum = 0;
mExpMatchesNum = 0;
success = (mParams.mRecogRateOpt == 0) ?
(Math.Abs((double)recogRate - mParams.mRecogRate) < 0.001)
: (recogRate >= (mParams.mRecogRate - 0.000001));
if(success)
{
mOptSuccess = true;
if(mCurrMeanTime < mOptMeanTime)
{
mOptScoreMin = mCurrScoreMin;
mOptGreediness = mCurrGreediness;
this.recogTabOptimizationData[4] = "" + Math.Round(mOptScoreMin/100.0, 2);
this.recogTabOptimizationData[5] = "" + Math.Round(mOptGreediness/100.0, 2);
this.recogTabOptimizationData[6] = Math.Round(recogRate, 2) + " %";
mOptMeanTime = mCurrMeanTime;
recogTabOptimizationData[7] = recogTabOptimizationData[3];
NotifyStatisticsObserver(MatchingOpt.UPDATE_RECOG_OPTIMUM_VALS);
}
mCurrGreediness += mGreedinessStep;
return (mCurrGreediness <= 100);
}
mCurrScoreMin += mScoreMinStep;
if(mOptSuccess)
return (mCurrScoreMin >= 10);
return (mCurrScoreMin > 0);
}
/// <summary>
/// Resets all parameters for evaluating the performance to their initial values.
/// </summary>
public override void reset()
{
mOptSuccess = false;
for(int i=0; i<8; i++)
this.recogTabOptimizationData[i]="-";
statusString = "Optimization Status:";
mCurrScoreMin = 100;
mCurrGreediness = 0;
mCurrMeanTime = 0.0;
mOptScoreMin = 100;
mOptGreediness = 0;
mOptMeanTime = Double.MaxValue;
mMatchesNum = 0;
mExpMatchesNum = 0;
tImageCount = mAssistant.TestImages.Count;
iterator = mAssistant.TestImages.Keys.GetEnumerator();
mCurrentIndex = 0;
}
/// <summary>
/// If the optimization has stopped, then check whether it was
/// completed successfully or whether it was aborted due to errors or
/// to user interaction.
/// Depending on the failure or success of the run, the GUI is notified
/// for visual update of the results and obtained statistics.
/// </summary>
public override void stop()
{
if(tImageCount==0)
{
NotifyStatisticsObserver(MatchingAssistant.ERR_NO_TESTIMAGE);
NotifyStatisticsObserver(MatchingOpt.RUN_FAILED);
}
else if(!mOptSuccess && (mCurrScoreMin==0.0))
{
NotifyStatisticsObserver(MatchingOpt.UPDATE_RECOG_ERR);
NotifyStatisticsObserver(MatchingOpt.RUN_FAILED);
}
else if(!mOptSuccess)
{
NotifyStatisticsObserver(MatchingOpt.UPDATE_TEST_ERR);
NotifyStatisticsObserver(MatchingOpt.RUN_FAILED);
}
else
{
statusString = "Optimization finished successfully";
NotifyStatisticsObserver(MatchingOpt.UPDATE_RECOG_STATISTICS_STATUS);
mAssistant.setMinScore(mOptScoreMin/100.0);
mAssistant.setGreediness(mOptGreediness/100.0);
NotifyStatisticsObserver(MatchingOpt.RUN_SUCCESSFUL);
}
}
}//end of class
}//end of namespace
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Xml;
using System.Collections;
using System.Diagnostics;
namespace System.Runtime.Serialization
{
internal static class XmlFormatGeneratorStatics
{
private static MethodInfo s_writeStartElementMethod2;
internal static MethodInfo WriteStartElementMethod2
{
get
{
if (s_writeStartElementMethod2 == null)
{
s_writeStartElementMethod2 = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", Globals.ScanAllMembers, new Type[] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
Debug.Assert(s_writeStartElementMethod2 != null);
}
return s_writeStartElementMethod2;
}
}
private static MethodInfo s_writeStartElementMethod3;
internal static MethodInfo WriteStartElementMethod3
{
get
{
if (s_writeStartElementMethod3 == null)
{
s_writeStartElementMethod3 = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", Globals.ScanAllMembers, new Type[] { typeof(string), typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
Debug.Assert(s_writeStartElementMethod3 != null);
}
return s_writeStartElementMethod3;
}
}
private static MethodInfo s_writeEndElementMethod;
internal static MethodInfo WriteEndElementMethod
{
get
{
if (s_writeEndElementMethod == null)
{
s_writeEndElementMethod = typeof(XmlWriterDelegator).GetMethod("WriteEndElement", Globals.ScanAllMembers, Array.Empty<Type>());
Debug.Assert(s_writeEndElementMethod != null);
}
return s_writeEndElementMethod;
}
}
private static MethodInfo s_writeNamespaceDeclMethod;
internal static MethodInfo WriteNamespaceDeclMethod
{
get
{
if (s_writeNamespaceDeclMethod == null)
{
s_writeNamespaceDeclMethod = typeof(XmlWriterDelegator).GetMethod("WriteNamespaceDecl", Globals.ScanAllMembers, new Type[] { typeof(XmlDictionaryString) });
Debug.Assert(s_writeNamespaceDeclMethod != null);
}
return s_writeNamespaceDeclMethod;
}
}
private static PropertyInfo s_extensionDataProperty;
internal static PropertyInfo ExtensionDataProperty => s_extensionDataProperty ??
(s_extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData"));
private static ConstructorInfo s_dictionaryEnumeratorCtor;
internal static ConstructorInfo DictionaryEnumeratorCtor
{
get
{
if (s_dictionaryEnumeratorCtor == null)
s_dictionaryEnumeratorCtor = Globals.TypeOfDictionaryEnumerator.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfIDictionaryEnumerator });
return s_dictionaryEnumeratorCtor;
}
}
private static MethodInfo s_ienumeratorMoveNextMethod;
internal static MethodInfo MoveNextMethod
{
get
{
if (s_ienumeratorMoveNextMethod == null)
{
s_ienumeratorMoveNextMethod = typeof(IEnumerator).GetMethod("MoveNext");
Debug.Assert(s_ienumeratorMoveNextMethod != null);
}
return s_ienumeratorMoveNextMethod;
}
}
private static MethodInfo s_ienumeratorGetCurrentMethod;
internal static MethodInfo GetCurrentMethod
{
get
{
if (s_ienumeratorGetCurrentMethod == null)
{
s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current").GetMethod;
Debug.Assert(s_ienumeratorGetCurrentMethod != null);
}
return s_ienumeratorGetCurrentMethod;
}
}
private static MethodInfo s_getItemContractMethod;
internal static MethodInfo GetItemContractMethod
{
get
{
if (s_getItemContractMethod == null)
{
s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers).GetMethod;
Debug.Assert(s_getItemContractMethod != null);
}
return s_getItemContractMethod;
}
}
private static MethodInfo s_isStartElementMethod2;
internal static MethodInfo IsStartElementMethod2
{
get
{
if (s_isStartElementMethod2 == null)
{
s_isStartElementMethod2 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", Globals.ScanAllMembers, new Type[] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
Debug.Assert(s_isStartElementMethod2 != null);
}
return s_isStartElementMethod2;
}
}
private static MethodInfo s_isStartElementMethod0;
internal static MethodInfo IsStartElementMethod0
{
get
{
if (s_isStartElementMethod0 == null)
{
s_isStartElementMethod0 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", Globals.ScanAllMembers, Array.Empty<Type>());
Debug.Assert(s_isStartElementMethod0 != null);
}
return s_isStartElementMethod0;
}
}
private static MethodInfo s_getUninitializedObjectMethod;
internal static MethodInfo GetUninitializedObjectMethod
{
get
{
if (s_getUninitializedObjectMethod == null)
{
s_getUninitializedObjectMethod = typeof(XmlFormatReaderGenerator).GetMethod("UnsafeGetUninitializedObject", Globals.ScanAllMembers, new Type[] { typeof(int) });
Debug.Assert(s_getUninitializedObjectMethod != null);
}
return s_getUninitializedObjectMethod;
}
}
private static MethodInfo s_onDeserializationMethod;
internal static MethodInfo OnDeserializationMethod
{
get
{
if (s_onDeserializationMethod == null)
s_onDeserializationMethod = typeof(IDeserializationCallback).GetMethod("OnDeserialization");
return s_onDeserializationMethod;
}
}
private static PropertyInfo s_nodeTypeProperty;
internal static PropertyInfo NodeTypeProperty
{
get
{
if (s_nodeTypeProperty == null)
{
s_nodeTypeProperty = typeof(XmlReaderDelegator).GetProperty("NodeType", Globals.ScanAllMembers);
Debug.Assert(s_nodeTypeProperty != null);
}
return s_nodeTypeProperty;
}
}
private static ConstructorInfo s_extensionDataObjectCtor;
internal static ConstructorInfo ExtensionDataObjectCtor => s_extensionDataObjectCtor ??
(s_extensionDataObjectCtor =
typeof (ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, null, new Type[] {}, null));
private static ConstructorInfo s_hashtableCtor;
internal static ConstructorInfo HashtableCtor
{
get
{
if (s_hashtableCtor == null)
s_hashtableCtor = Globals.TypeOfHashtable.GetConstructor(Globals.ScanAllMembers, Array.Empty<Type>());
return s_hashtableCtor;
}
}
private static MethodInfo s_getStreamingContextMethod;
internal static MethodInfo GetStreamingContextMethod
{
get
{
if (s_getStreamingContextMethod == null)
{
s_getStreamingContextMethod = typeof(XmlObjectSerializerContext).GetMethod("GetStreamingContext", Globals.ScanAllMembers);
Debug.Assert(s_getStreamingContextMethod != null);
}
return s_getStreamingContextMethod;
}
}
private static MethodInfo s_getCollectionMemberMethod;
internal static MethodInfo GetCollectionMemberMethod
{
get
{
if (s_getCollectionMemberMethod == null)
{
s_getCollectionMemberMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetCollectionMember", Globals.ScanAllMembers);
Debug.Assert(s_getCollectionMemberMethod != null);
}
return s_getCollectionMemberMethod;
}
}
private static MethodInfo s_storeCollectionMemberInfoMethod;
internal static MethodInfo StoreCollectionMemberInfoMethod
{
get
{
if (s_storeCollectionMemberInfoMethod == null)
{
s_storeCollectionMemberInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("StoreCollectionMemberInfo", Globals.ScanAllMembers, new Type[] { typeof(object) });
Debug.Assert(s_storeCollectionMemberInfoMethod != null);
}
return s_storeCollectionMemberInfoMethod;
}
}
private static MethodInfo s_storeIsGetOnlyCollectionMethod;
internal static MethodInfo StoreIsGetOnlyCollectionMethod
{
get
{
if (s_storeIsGetOnlyCollectionMethod == null)
{
s_storeIsGetOnlyCollectionMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("StoreIsGetOnlyCollection", Globals.ScanAllMembers);
Debug.Assert(s_storeIsGetOnlyCollectionMethod != null);
}
return s_storeIsGetOnlyCollectionMethod;
}
}
private static MethodInfo s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod;
internal static MethodInfo ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod
{
get
{
if (s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod == null)
{
s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowNullValueReturnedForGetOnlyCollectionException", Globals.ScanAllMembers);
Debug.Assert(s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod != null);
}
return s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod;
}
}
private static MethodInfo s_throwArrayExceededSizeExceptionMethod;
internal static MethodInfo ThrowArrayExceededSizeExceptionMethod
{
get
{
if (s_throwArrayExceededSizeExceptionMethod == null)
{
s_throwArrayExceededSizeExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowArrayExceededSizeException", Globals.ScanAllMembers);
Debug.Assert(s_throwArrayExceededSizeExceptionMethod != null);
}
return s_throwArrayExceededSizeExceptionMethod;
}
}
private static MethodInfo s_incrementItemCountMethod;
internal static MethodInfo IncrementItemCountMethod
{
get
{
if (s_incrementItemCountMethod == null)
{
s_incrementItemCountMethod = typeof(XmlObjectSerializerContext).GetMethod("IncrementItemCount", Globals.ScanAllMembers);
Debug.Assert(s_incrementItemCountMethod != null);
}
return s_incrementItemCountMethod;
}
}
private static MethodInfo s_internalDeserializeMethod;
internal static MethodInfo InternalDeserializeMethod
{
get
{
if (s_internalDeserializeMethod == null)
{
s_internalDeserializeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("InternalDeserialize", Globals.ScanAllMembers, new Type[] { typeof(XmlReaderDelegator), typeof(int), typeof(RuntimeTypeHandle), typeof(string), typeof(string) });
Debug.Assert(s_internalDeserializeMethod != null);
}
return s_internalDeserializeMethod;
}
}
private static MethodInfo s_moveToNextElementMethod;
internal static MethodInfo MoveToNextElementMethod
{
get
{
if (s_moveToNextElementMethod == null)
{
s_moveToNextElementMethod = typeof(XmlObjectSerializerReadContext).GetMethod("MoveToNextElement", Globals.ScanAllMembers);
Debug.Assert(s_moveToNextElementMethod != null);
}
return s_moveToNextElementMethod;
}
}
private static MethodInfo s_getMemberIndexMethod;
internal static MethodInfo GetMemberIndexMethod
{
get
{
if (s_getMemberIndexMethod == null)
{
s_getMemberIndexMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetMemberIndex", Globals.ScanAllMembers);
Debug.Assert(s_getMemberIndexMethod != null);
}
return s_getMemberIndexMethod;
}
}
private static MethodInfo s_getMemberIndexWithRequiredMembersMethod;
internal static MethodInfo GetMemberIndexWithRequiredMembersMethod
{
get
{
if (s_getMemberIndexWithRequiredMembersMethod == null)
{
s_getMemberIndexWithRequiredMembersMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetMemberIndexWithRequiredMembers", Globals.ScanAllMembers);
Debug.Assert(s_getMemberIndexWithRequiredMembersMethod != null);
}
return s_getMemberIndexWithRequiredMembersMethod;
}
}
private static MethodInfo s_throwRequiredMemberMissingExceptionMethod;
internal static MethodInfo ThrowRequiredMemberMissingExceptionMethod
{
get
{
if (s_throwRequiredMemberMissingExceptionMethod == null)
{
s_throwRequiredMemberMissingExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowRequiredMemberMissingException", Globals.ScanAllMembers);
Debug.Assert(s_throwRequiredMemberMissingExceptionMethod != null);
}
return s_throwRequiredMemberMissingExceptionMethod;
}
}
private static MethodInfo s_skipUnknownElementMethod;
internal static MethodInfo SkipUnknownElementMethod
{
get
{
if (s_skipUnknownElementMethod == null)
{
s_skipUnknownElementMethod = typeof(XmlObjectSerializerReadContext).GetMethod("SkipUnknownElement", Globals.ScanAllMembers);
Debug.Assert(s_skipUnknownElementMethod != null);
}
return s_skipUnknownElementMethod;
}
}
private static MethodInfo s_readIfNullOrRefMethod;
internal static MethodInfo ReadIfNullOrRefMethod
{
get
{
if (s_readIfNullOrRefMethod == null)
{
s_readIfNullOrRefMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadIfNullOrRef", Globals.ScanAllMembers, new Type[] { typeof(XmlReaderDelegator), typeof(Type), typeof(bool) });
Debug.Assert(s_readIfNullOrRefMethod != null);
}
return s_readIfNullOrRefMethod;
}
}
private static MethodInfo s_readAttributesMethod;
internal static MethodInfo ReadAttributesMethod
{
get
{
if (s_readAttributesMethod == null)
{
s_readAttributesMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadAttributes", Globals.ScanAllMembers);
Debug.Assert(s_readAttributesMethod != null);
}
return s_readAttributesMethod;
}
}
private static MethodInfo s_resetAttributesMethod;
internal static MethodInfo ResetAttributesMethod
{
get
{
if (s_resetAttributesMethod == null)
{
s_resetAttributesMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ResetAttributes", Globals.ScanAllMembers);
Debug.Assert(s_resetAttributesMethod != null);
}
return s_resetAttributesMethod;
}
}
private static MethodInfo s_getObjectIdMethod;
internal static MethodInfo GetObjectIdMethod
{
get
{
if (s_getObjectIdMethod == null)
{
s_getObjectIdMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetObjectId", Globals.ScanAllMembers);
Debug.Assert(s_getObjectIdMethod != null);
}
return s_getObjectIdMethod;
}
}
private static MethodInfo s_getArraySizeMethod;
internal static MethodInfo GetArraySizeMethod
{
get
{
if (s_getArraySizeMethod == null)
{
s_getArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetArraySize", Globals.ScanAllMembers);
Debug.Assert(s_getArraySizeMethod != null);
}
return s_getArraySizeMethod;
}
}
private static MethodInfo s_addNewObjectMethod;
internal static MethodInfo AddNewObjectMethod
{
get
{
if (s_addNewObjectMethod == null)
{
s_addNewObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("AddNewObject", Globals.ScanAllMembers);
Debug.Assert(s_addNewObjectMethod != null);
}
return s_addNewObjectMethod;
}
}
private static MethodInfo s_addNewObjectWithIdMethod;
internal static MethodInfo AddNewObjectWithIdMethod
{
get
{
if (s_addNewObjectWithIdMethod == null)
{
s_addNewObjectWithIdMethod = typeof(XmlObjectSerializerReadContext).GetMethod("AddNewObjectWithId", Globals.ScanAllMembers);
Debug.Assert(s_addNewObjectWithIdMethod != null);
}
return s_addNewObjectWithIdMethod;
}
}
private static MethodInfo s_getExistingObjectMethod;
internal static MethodInfo GetExistingObjectMethod
{
get
{
if (s_getExistingObjectMethod == null)
{
s_getExistingObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetExistingObject", Globals.ScanAllMembers);
Debug.Assert(s_getExistingObjectMethod != null);
}
return s_getExistingObjectMethod;
}
}
private static MethodInfo s_ensureArraySizeMethod;
internal static MethodInfo EnsureArraySizeMethod
{
get
{
if (s_ensureArraySizeMethod == null)
{
s_ensureArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("EnsureArraySize", Globals.ScanAllMembers);
Debug.Assert(s_ensureArraySizeMethod != null);
}
return s_ensureArraySizeMethod;
}
}
private static MethodInfo s_trimArraySizeMethod;
internal static MethodInfo TrimArraySizeMethod
{
get
{
if (s_trimArraySizeMethod == null)
{
s_trimArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("TrimArraySize", Globals.ScanAllMembers);
Debug.Assert(s_trimArraySizeMethod != null);
}
return s_trimArraySizeMethod;
}
}
private static MethodInfo s_checkEndOfArrayMethod;
internal static MethodInfo CheckEndOfArrayMethod
{
get
{
if (s_checkEndOfArrayMethod == null)
{
s_checkEndOfArrayMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CheckEndOfArray", Globals.ScanAllMembers);
Debug.Assert(s_checkEndOfArrayMethod != null);
}
return s_checkEndOfArrayMethod;
}
}
private static MethodInfo s_getArrayLengthMethod;
internal static MethodInfo GetArrayLengthMethod
{
get
{
if (s_getArrayLengthMethod == null)
{
s_getArrayLengthMethod = Globals.TypeOfArray.GetProperty("Length").GetMethod;
Debug.Assert(s_getArrayLengthMethod != null);
}
return s_getArrayLengthMethod;
}
}
private static MethodInfo s_createSerializationExceptionMethod;
internal static MethodInfo CreateSerializationExceptionMethod
{
get
{
if (s_createSerializationExceptionMethod == null)
{
s_createSerializationExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CreateSerializationException", Globals.ScanAllMembers, new Type[] { typeof(string) });
Debug.Assert(s_createSerializationExceptionMethod != null);
}
return s_createSerializationExceptionMethod;
}
}
private static MethodInfo s_readSerializationInfoMethod;
internal static MethodInfo ReadSerializationInfoMethod
{
get
{
if (s_readSerializationInfoMethod == null)
s_readSerializationInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadSerializationInfo", Globals.ScanAllMembers);
return s_readSerializationInfoMethod;
}
}
private static MethodInfo s_createUnexpectedStateExceptionMethod;
internal static MethodInfo CreateUnexpectedStateExceptionMethod
{
get
{
if (s_createUnexpectedStateExceptionMethod == null)
{
s_createUnexpectedStateExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CreateUnexpectedStateException", Globals.ScanAllMembers, new Type[] { typeof(XmlNodeType), typeof(XmlReaderDelegator) });
Debug.Assert(s_createUnexpectedStateExceptionMethod != null);
}
return s_createUnexpectedStateExceptionMethod;
}
}
private static MethodInfo s_internalSerializeReferenceMethod;
internal static MethodInfo InternalSerializeReferenceMethod
{
get
{
if (s_internalSerializeReferenceMethod == null)
{
s_internalSerializeReferenceMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("InternalSerializeReference", Globals.ScanAllMembers);
Debug.Assert(s_internalSerializeReferenceMethod != null);
}
return s_internalSerializeReferenceMethod;
}
}
private static MethodInfo s_internalSerializeMethod;
internal static MethodInfo InternalSerializeMethod
{
get
{
if (s_internalSerializeMethod == null)
{
s_internalSerializeMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("InternalSerialize", Globals.ScanAllMembers);
Debug.Assert(s_internalSerializeMethod != null);
}
return s_internalSerializeMethod;
}
}
private static MethodInfo s_writeNullMethod;
internal static MethodInfo WriteNullMethod
{
get
{
if (s_writeNullMethod == null)
{
s_writeNullMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteNull", Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), typeof(Type), typeof(bool) });
Debug.Assert(s_writeNullMethod != null);
}
return s_writeNullMethod;
}
}
private static MethodInfo s_incrementArrayCountMethod;
internal static MethodInfo IncrementArrayCountMethod
{
get
{
if (s_incrementArrayCountMethod == null)
{
s_incrementArrayCountMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementArrayCount", Globals.ScanAllMembers);
Debug.Assert(s_incrementArrayCountMethod != null);
}
return s_incrementArrayCountMethod;
}
}
private static MethodInfo s_incrementCollectionCountMethod;
internal static MethodInfo IncrementCollectionCountMethod
{
get
{
if (s_incrementCollectionCountMethod == null)
{
s_incrementCollectionCountMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementCollectionCount", Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), typeof(ICollection) });
Debug.Assert(s_incrementCollectionCountMethod != null);
}
return s_incrementCollectionCountMethod;
}
}
private static MethodInfo s_incrementCollectionCountGenericMethod;
internal static MethodInfo IncrementCollectionCountGenericMethod
{
get
{
if (s_incrementCollectionCountGenericMethod == null)
{
s_incrementCollectionCountGenericMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementCollectionCountGeneric", Globals.ScanAllMembers);
Debug.Assert(s_incrementCollectionCountGenericMethod != null);
}
return s_incrementCollectionCountGenericMethod;
}
}
private static MethodInfo s_getDefaultValueMethod;
internal static MethodInfo GetDefaultValueMethod
{
get
{
if (s_getDefaultValueMethod == null)
{
s_getDefaultValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(nameof(XmlObjectSerializerWriteContext.GetDefaultValue), Globals.ScanAllMembers);
Debug.Assert(s_getDefaultValueMethod != null);
}
return s_getDefaultValueMethod;
}
}
internal static object GetDefaultValue(Type type)
{
return GetDefaultValueMethod.MakeGenericMethod(type).Invoke(null, Array.Empty<object>());
}
private static MethodInfo s_getNullableValueMethod;
internal static MethodInfo GetNullableValueMethod
{
get
{
if (s_getNullableValueMethod == null)
{
s_getNullableValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetNullableValue", Globals.ScanAllMembers);
Debug.Assert(s_getNullableValueMethod != null);
}
return s_getNullableValueMethod;
}
}
private static MethodInfo s_throwRequiredMemberMustBeEmittedMethod;
internal static MethodInfo ThrowRequiredMemberMustBeEmittedMethod
{
get
{
if (s_throwRequiredMemberMustBeEmittedMethod == null)
{
s_throwRequiredMemberMustBeEmittedMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("ThrowRequiredMemberMustBeEmitted", Globals.ScanAllMembers);
Debug.Assert(s_throwRequiredMemberMustBeEmittedMethod != null);
}
return s_throwRequiredMemberMustBeEmittedMethod;
}
}
private static MethodInfo s_getHasValueMethod;
internal static MethodInfo GetHasValueMethod
{
get
{
if (s_getHasValueMethod == null)
{
s_getHasValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetHasValue", Globals.ScanAllMembers);
Debug.Assert(s_getHasValueMethod != null);
}
return s_getHasValueMethod;
}
}
private static MethodInfo s_writeISerializableMethod;
internal static MethodInfo WriteISerializableMethod
{
get
{
if (s_writeISerializableMethod == null)
s_writeISerializableMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteISerializable", Globals.ScanAllMembers);
return s_writeISerializableMethod;
}
}
private static MethodInfo s_isMemberTypeSameAsMemberValue;
internal static MethodInfo IsMemberTypeSameAsMemberValue
{
get
{
if (s_isMemberTypeSameAsMemberValue == null)
{
s_isMemberTypeSameAsMemberValue = typeof(XmlObjectSerializerWriteContext).GetMethod("IsMemberTypeSameAsMemberValue", Globals.ScanAllMembers, new Type[] { typeof(object), typeof(Type) });
Debug.Assert(s_isMemberTypeSameAsMemberValue != null);
}
return s_isMemberTypeSameAsMemberValue;
}
}
private static MethodInfo s_writeExtensionDataMethod;
internal static MethodInfo WriteExtensionDataMethod => s_writeExtensionDataMethod ??
(s_writeExtensionDataMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteExtensionData", Globals.ScanAllMembers));
private static MethodInfo s_writeXmlValueMethod;
internal static MethodInfo WriteXmlValueMethod
{
get
{
if (s_writeXmlValueMethod == null)
{
s_writeXmlValueMethod = typeof(DataContract).GetMethod("WriteXmlValue", Globals.ScanAllMembers);
Debug.Assert(s_writeXmlValueMethod != null);
}
return s_writeXmlValueMethod;
}
}
private static MethodInfo s_readXmlValueMethod;
internal static MethodInfo ReadXmlValueMethod
{
get
{
if (s_readXmlValueMethod == null)
{
s_readXmlValueMethod = typeof(DataContract).GetMethod("ReadXmlValue", Globals.ScanAllMembers);
Debug.Assert(s_readXmlValueMethod != null);
}
return s_readXmlValueMethod;
}
}
private static PropertyInfo s_namespaceProperty;
internal static PropertyInfo NamespaceProperty
{
get
{
if (s_namespaceProperty == null)
{
s_namespaceProperty = typeof(DataContract).GetProperty("Namespace", Globals.ScanAllMembers);
Debug.Assert(s_namespaceProperty != null);
}
return s_namespaceProperty;
}
}
private static FieldInfo s_contractNamespacesField;
internal static FieldInfo ContractNamespacesField
{
get
{
if (s_contractNamespacesField == null)
{
s_contractNamespacesField = typeof(ClassDataContract).GetField("ContractNamespaces", Globals.ScanAllMembers);
Debug.Assert(s_contractNamespacesField != null);
}
return s_contractNamespacesField;
}
}
private static FieldInfo s_memberNamesField;
internal static FieldInfo MemberNamesField
{
get
{
if (s_memberNamesField == null)
{
s_memberNamesField = typeof(ClassDataContract).GetField("MemberNames", Globals.ScanAllMembers);
Debug.Assert(s_memberNamesField != null);
}
return s_memberNamesField;
}
}
private static MethodInfo s_extensionDataSetExplicitMethodInfo;
internal static MethodInfo ExtensionDataSetExplicitMethodInfo => s_extensionDataSetExplicitMethodInfo ??
(s_extensionDataSetExplicitMethodInfo = typeof(IExtensibleDataObject).GetMethod(Globals.ExtensionDataSetMethod));
private static PropertyInfo s_childElementNamespacesProperty;
internal static PropertyInfo ChildElementNamespacesProperty
{
get
{
if (s_childElementNamespacesProperty == null)
{
s_childElementNamespacesProperty = typeof(ClassDataContract).GetProperty("ChildElementNamespaces", Globals.ScanAllMembers);
Debug.Assert(s_childElementNamespacesProperty != null);
}
return s_childElementNamespacesProperty;
}
}
private static PropertyInfo s_collectionItemNameProperty;
internal static PropertyInfo CollectionItemNameProperty
{
get
{
if (s_collectionItemNameProperty == null)
{
s_collectionItemNameProperty = typeof(CollectionDataContract).GetProperty("CollectionItemName", Globals.ScanAllMembers);
Debug.Assert(s_collectionItemNameProperty != null);
}
return s_collectionItemNameProperty;
}
}
private static PropertyInfo s_childElementNamespaceProperty;
internal static PropertyInfo ChildElementNamespaceProperty
{
get
{
if (s_childElementNamespaceProperty == null)
{
s_childElementNamespaceProperty = typeof(CollectionDataContract).GetProperty("ChildElementNamespace", Globals.ScanAllMembers);
Debug.Assert(s_childElementNamespaceProperty != null);
}
return s_childElementNamespaceProperty;
}
}
private static MethodInfo s_getDateTimeOffsetMethod;
internal static MethodInfo GetDateTimeOffsetMethod
{
get
{
if (s_getDateTimeOffsetMethod == null)
{
s_getDateTimeOffsetMethod = typeof(DateTimeOffsetAdapter).GetMethod("GetDateTimeOffset", Globals.ScanAllMembers);
Debug.Assert(s_getDateTimeOffsetMethod != null);
}
return s_getDateTimeOffsetMethod;
}
}
private static MethodInfo s_getDateTimeOffsetAdapterMethod;
internal static MethodInfo GetDateTimeOffsetAdapterMethod
{
get
{
if (s_getDateTimeOffsetAdapterMethod == null)
{
s_getDateTimeOffsetAdapterMethod = typeof(DateTimeOffsetAdapter).GetMethod("GetDateTimeOffsetAdapter", Globals.ScanAllMembers);
Debug.Assert(s_getDateTimeOffsetAdapterMethod != null);
}
return s_getDateTimeOffsetAdapterMethod;
}
}
#if !uapaot
private static MethodInfo s_getTypeHandleMethod;
internal static MethodInfo GetTypeHandleMethod
{
get
{
if (s_getTypeHandleMethod == null)
{
s_getTypeHandleMethod = typeof(Type).GetMethod("get_TypeHandle");
Debug.Assert(s_getTypeHandleMethod != null);
}
return s_getTypeHandleMethod;
}
}
private static MethodInfo s_getTypeMethod;
internal static MethodInfo GetTypeMethod
{
get
{
if (s_getTypeMethod == null)
{
s_getTypeMethod = typeof(object).GetMethod("GetType");
Debug.Assert(s_getTypeMethod != null);
}
return s_getTypeMethod;
}
}
private static MethodInfo s_throwInvalidDataContractExceptionMethod;
internal static MethodInfo ThrowInvalidDataContractExceptionMethod
{
get
{
if (s_throwInvalidDataContractExceptionMethod == null)
{
s_throwInvalidDataContractExceptionMethod = typeof(DataContract).GetMethod("ThrowInvalidDataContractException", Globals.ScanAllMembers, new Type[] { typeof(string), typeof(Type) });
Debug.Assert(s_throwInvalidDataContractExceptionMethod != null);
}
return s_throwInvalidDataContractExceptionMethod;
}
}
private static PropertyInfo s_serializeReadOnlyTypesProperty;
internal static PropertyInfo SerializeReadOnlyTypesProperty
{
get
{
if (s_serializeReadOnlyTypesProperty == null)
{
s_serializeReadOnlyTypesProperty = typeof(XmlObjectSerializerWriteContext).GetProperty("SerializeReadOnlyTypes", Globals.ScanAllMembers);
Debug.Assert(s_serializeReadOnlyTypesProperty != null);
}
return s_serializeReadOnlyTypesProperty;
}
}
private static PropertyInfo s_classSerializationExceptionMessageProperty;
internal static PropertyInfo ClassSerializationExceptionMessageProperty
{
get
{
if (s_classSerializationExceptionMessageProperty == null)
{
s_classSerializationExceptionMessageProperty = typeof(ClassDataContract).GetProperty("SerializationExceptionMessage", Globals.ScanAllMembers);
Debug.Assert(s_classSerializationExceptionMessageProperty != null);
}
return s_classSerializationExceptionMessageProperty;
}
}
private static PropertyInfo s_collectionSerializationExceptionMessageProperty;
internal static PropertyInfo CollectionSerializationExceptionMessageProperty
{
get
{
if (s_collectionSerializationExceptionMessageProperty == null)
{
s_collectionSerializationExceptionMessageProperty = typeof(CollectionDataContract).GetProperty("SerializationExceptionMessage", Globals.ScanAllMembers);
Debug.Assert(s_collectionSerializationExceptionMessageProperty != null);
}
return s_collectionSerializationExceptionMessageProperty;
}
}
#endif
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using Apache.Geode.Client;
namespace Apache.Geode.Client.Tests
{
/// <summary>
/// User class for testing the put functionality for object.
/// </summary>
public class PortfolioPdx
: IPdxSerializable
{
#region Private members and methods
private int m_id;
private string m_pkid;
private PositionPdx m_position1;
private PositionPdx m_position2;
private Hashtable m_positions;
private string m_type;
private string m_status;
private string[] m_names;
private byte[] m_newVal;
private DateTime m_creationDate;
private byte[] m_arrayZeroSize;
private byte[] m_arrayNull;
private static string[] m_secIds = { "SUN", "IBM", "YHOO", "GOOG", "MSFT",
"AOL", "APPL", "ORCL", "SAP", "DELL" };
private UInt32 GetObjectSize(IGeodeSerializable obj)
{
return (obj == null ? 0 : obj.ObjectSize);
}
#endregion
#region Public accessors
public int ID
{
get
{
return m_id;
}
}
public string Pkid
{
get
{
return m_pkid;
}
}
public PositionPdx P1
{
get
{
return m_position1;
}
}
public PositionPdx P2
{
get
{
return m_position2;
}
}
public Hashtable Positions
{
get
{
return m_positions;
}
}
public string Status
{
get
{
return m_status;
}
}
public bool IsActive
{
get
{
return (m_status == "active");
}
}
public byte[] NewVal
{
get
{
return m_newVal;
}
}
public byte[] ArrayNull
{
get
{
return m_arrayNull;
}
}
public byte[] ArrayZeroSize
{
get
{
return m_arrayZeroSize;
}
}
public DateTime CreationDate
{
get
{
return m_creationDate;
}
}
public string Type
{
get
{
return m_type;
}
}
public static string[] SecIds
{
get
{
return m_secIds;
}
}
public override string ToString()
{
string portStr = string.Format("Portfolio [ID={0} status={1} " +
"type={2} pkid={3}]", m_id, m_status, m_type, m_pkid);
portStr += string.Format("{0}\tP1: {1}",
Environment.NewLine, m_position1);
portStr += string.Format("{0}\tP2: {1}",
Environment.NewLine, m_position2);
portStr += string.Format("{0}Creation Date: {1}", Environment.NewLine,
m_creationDate);
return portStr;
}
#endregion
#region Constructors
public PortfolioPdx()
{
m_id = 0;
m_pkid = null;
m_type = null;
m_status = null;
m_newVal = null;
m_creationDate = new DateTime();
}
public PortfolioPdx(int id)
: this(id, 0)
{
}
public PortfolioPdx(int id, int size)
: this(id, size, null)
{
}
public PortfolioPdx(int id, int size, string[] names)
{
m_names = names;
m_id = id;
m_pkid = id.ToString();
m_status = (id % 2 == 0) ? "active" : "inactive";
m_type = "type" + (id % 3);
int numSecIds = m_secIds.Length;
m_position1 = new PositionPdx(m_secIds[PositionPdx.Count % numSecIds],
PositionPdx.Count * 1000);
if (id % 2 != 0)
{
m_position2 = new PositionPdx(m_secIds[PositionPdx.Count % numSecIds],
PositionPdx.Count * 1000);
}
else
{
m_position2 = null;
}
m_positions = new Hashtable();
m_positions[m_secIds[PositionPdx.Count % numSecIds]] =
m_position1;
if (size > 0)
{
m_newVal = new byte[size];
for (int index = 0; index < size; index++)
{
m_newVal[index] = (byte)'B';
}
}
m_creationDate = DateTime.Now;
m_arrayNull = null;
m_arrayZeroSize = new byte[0];
}
#endregion
/*
public UInt32 ClassId
{
get
{
return 0x03;
}
}
*/
public static IPdxSerializable CreateDeserializable()
{
return new PortfolioPdx();
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_id = reader.ReadInt("ID");
m_pkid = reader.ReadString("pkid");
m_position1 = (PositionPdx)reader.ReadObject("position1");
m_position2 = (PositionPdx)reader.ReadObject("position2");
m_positions = (Hashtable)reader.ReadObject("positions");
m_type = reader.ReadString("type");
m_status = reader.ReadString("status");
m_names = reader.ReadStringArray("names");
m_newVal = reader.ReadByteArray("newVal");
m_creationDate = reader.ReadDate("creationDate");
m_arrayNull = reader.ReadByteArray("arrayNull");
m_arrayZeroSize = reader.ReadByteArray("arrayZeroSize");
}
public void ToData(IPdxWriter writer)
{
writer.WriteInt("ID", m_id)
.MarkIdentityField("ID")
.WriteString("pkid", m_pkid)
.MarkIdentityField("pkid")
.WriteObject("position1", m_position1)
.MarkIdentityField("position1")
.WriteObject("position2", m_position2)
.MarkIdentityField("position2")
.WriteObject("positions", m_positions)
.MarkIdentityField("positions")
.WriteString("type", m_type)
.MarkIdentityField("type")
.WriteString("status", m_status)
.MarkIdentityField("status")
.WriteStringArray("names", m_names)
.MarkIdentityField("names")
.WriteByteArray("newVal", m_newVal)
.MarkIdentityField("newVal")
.WriteDate("creationDate", m_creationDate)
.MarkIdentityField("creationDate")
.WriteByteArray("arrayNull", m_arrayNull)
.WriteByteArray("arrayZeroSize", m_arrayZeroSize);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mail;
using System.Web.UI.WebControls;
using Rainbow.Framework;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.Data;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Settings;
using Rainbow.Framework.Site.Configuration;
using Rainbow.Framework.Web.UI.WebControls;
namespace Rainbow.Content.Web.Modules
{
/// <summary>
/// Summary description for SendNewsletter.
/// </summary>
public partial class SendNewsletter : PortalModuleControl
{
private string InvalidRecipients = string.Empty;
protected string ServerVariables;
protected string Titulo;
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void Page_Load(object sender, EventArgs e)
{
// Added EsperantusKeys for Localization
// Mario Endara mario@softworks.com.uy 11/05/2004
Titulo = General.GetString("NEWSLETTER_TITLE");
if (!Page.IsPostBack)
{
CreatedDate.Text = DateTime.Now.ToLongDateString();
//Set default
txtName.Text = Settings["NEWSLETTER_DEFAULTNAME"].ToString();
txtEMail.Text = Settings["NEWSLETTER_DEFAULTEMAIL"].ToString();
if (txtEMail.Text == string.Empty)
txtEMail.Text = PortalSettings.CurrentUser.Identity.Email;
//create a DataTable
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("StringValue"));
NewsletterDB newsletter = new NewsletterDB();
if (!bool.Parse(Settings["TestMode"].ToString()))
{
SqlDataReader dReader =
newsletter.GetUsersNewsletter(portalSettings.PortalID,
Int32.Parse(Settings["NEWSLETTER_USERBLOCK"].ToString()),
Int32.Parse(Settings["NEWSLETTER_DONOTRESENDWITHIN"].ToString()));
try
{
while (dReader.Read())
{
DataRow dr = dt.NewRow();
dr[0] = "<b>" + dReader["Name"].ToString() + ":</b> " + dReader["EMail"].ToString();
dt.Rows.Add(dr);
}
}
finally
{
dReader.Close(); //by Manu, fixed bug 807858
}
DataList1.DataSource = new DataView(dt);
DataList1.RepeatDirection = RepeatDirection.Vertical;
DataList1.RepeatLayout = RepeatLayout.Table;
DataList1.BorderWidth = Unit.Pixel(1);
DataList1.GridLines = GridLines.Both;
DataList1.RepeatColumns = 3;
DataList1.DataBind();
DataList1.Visible = true;
int cnt =
newsletter.GetUsersNewsletterCount(portalSettings.PortalID,
Int32.Parse(Settings["NEWSLETTER_USERBLOCK"].ToString()),
Int32.Parse(
Settings["NEWSLETTER_DONOTRESENDWITHIN"].ToString()));
// Added EsperantusKeys for Localization
// Mario Endara mario@softworks.com.uy 11/05/2004
lblMessage.Text = General.GetString("NEWSLETTER_MSG").Replace("{1}", cnt.ToString());
}
else
{
// Added EsperantusKeys for Localization
// Mario Endara mario@softworks.com.uy 11/05/2004
lblMessage.Text =
General.GetString("NEWSLETTER_MSG_TEST").Replace("{1}", txtName.Text).Replace("{2}",
txtEMail.Text);
}
//Try to get template
int HTMLModID = int.Parse(Settings["NEWSLETTER_HTMLTEMPLATE"].ToString());
if (HTMLModID > 0)
{
// Obtain the selected item from the HtmlText table
NewsletterHtmlTextDB text = new NewsletterHtmlTextDB();
SqlDataReader dr = text.GetHtmlText(HTMLModID, WorkFlowVersion.Staging);
try
{
if (dr.Read())
{
string buffer = (string) dr["DesktopHtml"];
// Replace relative path to absolute path. jviladiu@portalServices.net 19/07/2004
buffer = buffer.Replace(Path.ApplicationFullPath, Path.ApplicationRoot);
if (Path.ApplicationRoot.Length > 0)
//by Manu... on root PortalSettings.ApplicationPath is empty
buffer = buffer.Replace(Path.ApplicationRoot, Path.ApplicationFullPath);
txtBody.Text = Server.HtmlDecode(buffer);
HtmlMode.Checked = true;
}
else
HtmlMode.Checked = false;
}
finally
{
dr.Close();
}
}
}
EditPanel.Visible = true;
PrewiewPanel.Visible = false;
UsersPanel.Visible = true;
}
/// <summary>
/// The CancelBtn_Click server event handler on this page is used
/// to handle the scenario where a user clicks the "cancel"
/// button to discard a message post and toggle out of edit mode.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void cancelButton_Click(object sender, EventArgs e)
{
txtSubject.Text = string.Empty;
txtBody.Text = string.Empty;
}
/// <summary>
/// The SubmitBtn_Click server event handler on this page is used
/// to handle the scenario where a user clicks the "send"
/// button after entering a response to a message post.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void submitButton_Click(object sender, EventArgs e)
{
string message;
int cnt = 0;
EditPanel.Visible = false;
PrewiewPanel.Visible = true;
UsersPanel.Visible = false;
SmtpMail.SmtpServer = Config.SmtpServer;
message = General.GetString("NEWSLETTER_SENDTO", "<b>Message:</b> sent to:<br>");
try
{
NewsletterDB newsletter = new NewsletterDB();
if (!bool.Parse(Settings["TestMode"].ToString()))
{
// Get Newsletter Users from DB
SqlDataReader dReader =
newsletter.GetUsersNewsletter(portalSettings.PortalID,
Int32.Parse(Settings["NEWSLETTER_USERBLOCK"].ToString()),
Int32.Parse(Settings["NEWSLETTER_DONOTRESENDWITHIN"].ToString()));
try
{
while (dReader.Read())
{
cnt++;
message += dReader["Email"].ToString() + ", ";
try
{
//Send the email
newsletter.SendMessage(txtEMail.Text, dReader["Email"].ToString(),
dReader["Name"].ToString(), dReader["Password"].ToString(),
Settings["NEWSLETTER_LOGINHOMEPAGE"].ToString(), txtSubject.Text,
txtBody.Text, true, HtmlMode.Checked, InsertBreakLines.Checked);
//Update db
newsletter.SendNewsletterTo(portalSettings.PortalID, dReader["Email"].ToString());
}
catch (Exception ex)
{
InvalidRecipients += dReader["Email"].ToString() + "<br>";
BlacklistDB.AddToBlackList(portalSettings.PortalID, dReader["Email"].ToString(),
ex.Message);
}
}
}
finally
{
dReader.Close(); //by Manu, fixed bug 807858
}
lblMessage.Text =
General.GetString("NEWSLETTER_SENDINGTO", "Message has been sent to {1} registered users.").
Replace("{1}", cnt.ToString());
}
else
{
newsletter.SendMessage(txtEMail.Text, txtEMail.Text, txtName.Text, "******",
Settings["NEWSLETTER_LOGINHOMEPAGE"].ToString(), txtSubject.Text,
txtBody.Text, true, HtmlMode.Checked, InsertBreakLines.Checked);
lblMessage.Text = General.GetString("NEWSLETTER_TESTSENDTO", "Test message sent to: ") +
txtName.Text + " [" + txtEMail.Text + "]";
}
}
catch (Exception ex)
{
lblMessage.Text = General.GetString("NEWSLETTER_ERROR", "An error occurred: ") + ex.Message;
}
CreatedDate.Text = General.GetString("NEWSLETTER_SENDDATE", "Message sent: ") +
DateTime.Now.ToLongDateString() + "<br>";
if (InvalidRecipients.Length > 0)
CreatedDate.Text += General.GetString("NEWSLETTER_INVALID_RECIPIENTS", "Invalid recipients:<br>") +
InvalidRecipients;
//Hides commands
submitButton.Visible = false;
cancelButton2.Visible = false;
}
/// <summary>
/// Admin Module
/// </summary>
/// <value></value>
public override bool AdminModule
{
get { return true; }
}
/// <summary>
/// GUID of module (mandatory)
/// </summary>
/// <value></value>
public override Guid GuidID
{
get { return new Guid("{B484D450-5D30-4C4B-817C-14A25D06577E}"); }
}
#region Web Form Designer generated code
/// <summary>
/// Raises Init event
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
this.previewButton.Click += new EventHandler(this.previewButton_Click);
this.cancelButton.Click += new EventHandler(this.cancelButton_Click);
this.submitButton.Click += new EventHandler(this.submitButton_Click);
this.Load += new EventHandler(this.Page_Load);
base.OnInit(e);
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="T:SendNewsletter"/> class.
/// </summary>
public SendNewsletter()
{
// modified by Hongwei Shen
SettingItemGroup group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
int groupBase = (int) group;
SettingItem DefaultEmail = new SettingItem(new StringDataType());
DefaultEmail.EnglishName = "Sender Email";
DefaultEmail.Group = group;
DefaultEmail.Order = groupBase + 20;
_baseSettings.Add("NEWSLETTER_DEFAULTEMAIL", DefaultEmail);
SettingItem DefaultName = new SettingItem(new StringDataType());
DefaultName.Group = group;
DefaultName.Order = groupBase + 25;
DefaultName.EnglishName = "Sender Name";
_baseSettings.Add("NEWSLETTER_DEFAULTNAME", DefaultName);
SettingItem TestMode = new SettingItem(new BooleanDataType());
TestMode.Value = "False";
TestMode.Group = group;
TestMode.Order = groupBase + 30;
TestMode.EnglishName = "Test Mode";
TestMode.Description =
"Use Test Mode for testing your settings. It will send only one email to the address specified as sender. Useful for testing";
_baseSettings.Add("TestMode", TestMode);
//SettingItem HTMLTemplate = new SettingItem(new CustomListDataType(new Rainbow.Framework.Site.Configuration.ModulesDB().GetModuleDefinitionByGuid(p, new Guid("{0B113F51-FEA3-499A-98E7-7B83C192FDBB}")), "ModuleTitle", "ModuleID"));
SettingItem HTMLTemplate = new SettingItem(new ModuleListDataType("Html Document"));
HTMLTemplate.Value = "0";
HTMLTemplate.Group = group;
HTMLTemplate.Order = groupBase + 35;
HTMLTemplate.EnglishName = "HTML Template";
HTMLTemplate.Description =
"Select an HTML module that the will be used as base for this newsletter sent with this module.";
_baseSettings.Add("NEWSLETTER_HTMLTEMPLATE", HTMLTemplate);
SettingItem LoginHomePage = new SettingItem(new StringDataType());
LoginHomePage.EnglishName = "Site URL";
LoginHomePage.Group = group;
LoginHomePage.Order = groupBase + 40;
LoginHomePage.Description =
"The Url or the Home page of the site used for build the instant login url. Leave blank if using the current site.";
_baseSettings.Add("NEWSLETTER_LOGINHOMEPAGE", LoginHomePage);
SettingItem DoNotResendWithin = new SettingItem(new ListDataType("1;2;3;4;5;6;7;10;15;30;60;90"));
DoNotResendWithin.Value = "7";
DoNotResendWithin.Group = group;
DoNotResendWithin.Order = groupBase + 45;
DoNotResendWithin.EnglishName = "Do not resend within (days)";
DoNotResendWithin.Description =
"To avoid spam and duplicate sent you cannot email an user more than one time in specifed number of days.";
_baseSettings.Add("NEWSLETTER_DONOTRESENDWITHIN", DoNotResendWithin);
SettingItem UserBlock = new SettingItem(new ListDataType("50;100;200;250;300;1000;1500;5000"));
UserBlock.EnglishName = "Group users";
UserBlock.Group = group;
UserBlock.Order = groupBase + 50;
UserBlock.Description =
"Select the maximum number of users. For sending emails to all you have to repeat the process. Use small values to avoid server timeouts.";
UserBlock.Value = "250";
_baseSettings.Add("NEWSLETTER_USERBLOCK", UserBlock);
}
/// <summary>
/// The previewButton_Click server event handler on this page is used
/// to handle the scenario where a user clicks the "preview"
/// button to see a preview of the message.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void previewButton_Click(object sender, EventArgs e)
{
//SmtpMail.SmtpServer = Portal.SmtpServer;
SmtpMail.SmtpServer = Config.SmtpServer;
CreatedDate.Text = General.GetString("NEWSLETTER_LOCALTIME", "Local time: ") +
DateTime.Now.ToLongDateString();
NewsletterDB newsletter = new NewsletterDB();
string email;
string name;
string password;
if (!bool.Parse(Settings["TestMode"].ToString()))
{
SqlDataReader dReader =
newsletter.GetUsersNewsletter(portalSettings.PortalID,
Int32.Parse(Settings["NEWSLETTER_USERBLOCK"].ToString()),
Int32.Parse(Settings["NEWSLETTER_DONOTRESENDWITHIN"].ToString()));
try
{
if (dReader.Read())
{
email = dReader["Email"].ToString();
name = dReader["Name"].ToString();
password = dReader["Password"].ToString();
}
else
{
lblMessage.Text = General.GetString("NEWSLETTER_NORECIPIENTS", "No recipients");
return; //nothing more to do here
}
}
finally
{
dReader.Close(); //by Manu, fixed bug 807858
}
}
else
{
email = txtEMail.Text;
name = txtName.Text;
password = "*******"; //Fake password
}
EditPanel.Visible = false;
PrewiewPanel.Visible = true;
UsersPanel.Visible = false;
lblFrom.Text = txtName.Text + " (" + txtEMail.Text + ")";
lblTo.Text = name + " (" + email + ")";
lblSubject.Text = txtSubject.Text;
string body =
newsletter.SendMessage(txtEMail.Text, email, name, password,
Settings["NEWSLETTER_LOGINHOMEPAGE"].ToString(), txtSubject.Text, txtBody.Text,
false, HtmlMode.Checked, InsertBreakLines.Checked);
if (HtmlMode.Checked)
{
lblBody.Text = body;
}
else
{
lblBody.Text = "<PRE>" + body + "</PRE>";
}
}
# region Install / Uninstall Implementation
/// <summary>
/// Unknown
/// </summary>
/// <param name="stateSaver"></param>
public override void Install(IDictionary stateSaver)
{
string currentScriptName = Server.MapPath(this.TemplateSourceDirectory + "/Newsletter_Install.sql");
ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
// Call rollback
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
/// <summary>
/// Unknown
/// </summary>
/// <param name="stateSaver"></param>
public override void Uninstall(IDictionary stateSaver)
{
string currentScriptName = Server.MapPath(this.TemplateSourceDirectory + "/Newsletter_Uninstall.sql");
ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
// Call rollback
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
#endregion
}
}
| |
/*
* Copyright (C) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using System;
using System.Web;
using System.IO;
using System.Security;
using System.Security.Principal;
using System.Web.UI;
using System.Net;
using System.Security.AccessControl;
using System.Collections;
namespace SAMLServices.Wia
{
/// <summary>
/// Implementation for AA interfaces, Windows Integrated Auth and IIS security check
/// </summary>
public class AuthImpl : AuthenticationPage, IAuthn, IAuthz
{
System.Web.UI.Page page;
public AuthImpl(System.Web.UI.Page page)
{
this.page = page;
}
#region IAuthn Members
/// <summary>
// Method to obtain a user's acount name
/// </summary>
/// <returns>user account user@domain</returns>
public String GetUserIdentity()
{
String principal = page.User.Identity.Name;
if (Common.subjectFormat.Contains("\\"))
return principal;
else if (Common.subjectFormat.Contains("@"))
{
String[] prins = principal.Split('\\');
if (prins.Length == 2)
principal = prins[1] + "@" + prins[0];
}
else
{
String[] prins = principal.Split('\\');
if (prins.Length == 2)
principal = prins[1];
}
return principal;
}
#endregion
#region IAuthz Members
/// <summary>
/// Method to determine whether a user has acces to a given URL
/// </summary>
/// <param name="url">Target URL</param>
/// <param name="subject">account to be tested, in the form of username@domain</param>
/// <returns>Permit|Deny|Intermediate</returns>
public String GetPermission(String url, String subject)
{
Common.debug("inside AuthImpl::GetPermission");
Common.debug("url=" + url);
Common.debug("subject=" + subject);
// Convert the user name from domainName\userName format to
// userName@domainName format if necessary
// The WindowsIdentity(string) constructor uses the new
// Kerberos S4U extension to get a logon for the user
// without a password.
// Default AuthZ decision is set to "Deny"
String status = "Deny";
// Attempt to impersonate the user and verify access to the URL
WindowsImpersonationContext wic = null;
try
{
status = "before impersonation";
Common.debug("before WindowsIdentity");
// Create a Windows Identity
WindowsIdentity wi = new WindowsIdentity(subject);
if (wi == null)
{
Common.error("Couldn't get WindowsIdentity for account " + subject);
return "Indeterminate";
}
Common.debug("name=" + wi.Name + ", authed=" + wi.IsAuthenticated);
Common.debug("after WindowsIdentity");
// Impersonate the user
wic = wi.Impersonate();
Common.debug("after impersonate");
// Attempt to access the network resources as this user
if (url.StartsWith("http"))
status = GetURL(url, CredentialCache.DefaultCredentials);
else if (url.StartsWith("smb"))
{
String file = url;
file = file.Replace("smb://", "\\\\");
status = GetFile(file, wi);
}
else if (url.StartsWith("\\\\"))
{
status = GetFile(url, wi);
}
else
{
status = "Deny";
}
// Successfully retrieved URL, so set AuthZ decision to "Permit"
}
catch(SecurityException e)
{
Common.error("AuthImpl::caught SecurityException");
// Determine what sort of exception was thrown by checking the response status
Common.error("e = " + e.ToString());
Common.error("msg = " + e.Message);
Common.error("grantedset = " + e.GrantedSet);
Common.error("innerException= " + e.InnerException);
Common.error("PermissionState = " + e.PermissionState);
Common.error("PermissionType = " + e.PermissionType);
Common.error("RefusedSet = " + e.RefusedSet);
Common.error("TargetSet = " + e.TargetSite);
status = "Indeterminate";
return status;
}
catch(WebException e)
{
if( wic != null)
{
wic.Undo();
wic = null;
}
Common.debug("AuthImpl::caught WebException");
// Determine what sort of exception was thrown by checking the response status
Common.debug("e = " + e.ToString());
HttpWebResponse resp = (HttpWebResponse)((WebException)e).Response;
if (resp != null)
Common.debug("status = " + resp.StatusCode.ToString());
else
{
Common.debug("response is null");
status = "Indeterminate";
return status;
}
status = "Deny";
}
catch(UnauthorizedAccessException e) //can't write to the log file
{
if (wic != null)
{
wic.Undo();
wic = null;
}
Common.debug("caught UnauthorizedAccessException");
Common.debug(e.Message);
status = "Deny";
}
catch(Exception e)
{
if( wic != null)
{
wic.Undo();
wic = null;
}
// Some undetermined exception occured
// Setting the AuthZ decision to "Indeterminate" allows the GSA to use other
// AuthZ methods (i.e. Basic, NTLM, SSO) to determine access
Common.error("AuthImpl::caught exception");
Common.error(e.Message);
status = "Indeterminate, unknown exception, check ac.log";
}
finally
{
// Make sure to remove the impersonation token
if( wic != null)
wic.Undo();
Common.debug("exit AuthImpl::GetPermission::finally status=" + status);
}
Common.debug("exit AuthImpl::GetPermission return status=" + status);
return status;
}
/// <summary>
/// Method to perform an HTTP GET request for a URL.
///This is used in combination with user impersonation
/// to determine whether the user has access to the document
/// </summary>
/// <param name="url">target URL</param>
/// <param name="cred">The credential to be used when accessing the URL</param>
/// <returns></returns>
public String GetURL(String url, ICredentials cred)
{
Common.debug("inside GetURL internal");
HttpWebRequest web = (HttpWebRequest) WebRequest.Create(url);
web.AllowAutoRedirect = false;
web.Method = "HEAD";
web.Credentials = cred;
//web.Credentials = CredentialCache.DefaultNetworkCredentials;
//web.Credentials = new NetworkCredential("username", "password", "myDomain");
Common.debug("Sending a Head request to target URL");
//you can set a proxy if you need to
//web.Proxy = new WebProxy("http://proxyhost.abccorp.com", 3128);
// Get/Read the response from the remote HTTP server
HttpWebResponse response = (HttpWebResponse)web.GetResponse();
if (Common.LOG_LEVEL == Common.DEBUG)
{
Common.debug("Response code: " + response.StatusCode);
Common.debug("let's see what we've got, the response page content is: ");
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader (responseStream);
String res = reader.ReadToEnd ();
Common.debug(res);
Common.debug("end of response");
}
return handleDeny(response);
}
public String GetFile(String url, WindowsIdentity wi)
{
Common.debug("GetFile: " + url);
//urldecode, because GSA sends URL for file in encoded format
url = System.Web.HttpUtility.UrlDecode(url);
Common.debug("afer : " + url);
//FileInfo fi = new FileInfo(url);
FileSecurity security = File.GetAccessControl(url);
AuthorizationRuleCollection acl = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
bool allowRead = false;
String user = wi.Name;
//check users directly
Common.debug(" acl count = " + acl.Count);
Common.debug("user " + wi.Name);
bool bAllow = false;
//check user
for (int i = 0; i < acl.Count; i++)
{
System.Security.AccessControl.FileSystemAccessRule rule = (System.Security.AccessControl.FileSystemAccessRule)acl[i];
Common.debug("user listed in acl: '" + rule.IdentityReference.Value + "'");
Common.debug("current user:'" + user + "'");
if (user.Equals(rule.IdentityReference.Value))
{
Common.debug("match user " + user);
if (System.Security.AccessControl.AccessControlType.Deny.Equals(rule.AccessControlType))
{
Common.debug("deny");
if (contains(FileSystemRights.Read, rule))
{
Common.debug("read");
return "Deny"; //if any deny, it's deny
}
}
if (System.Security.AccessControl.AccessControlType.Allow.Equals(rule.AccessControlType))
{
Common.debug("allow");
if (contains(FileSystemRights.Read, rule))
{
Common.debug("allow @ user level is set");
bAllow = true;
}
}
}
}
//check groups
IdentityReferenceCollection groups = wi.Groups;
for (int j = 0; j < groups.Count; j++)
{
for (int i = 0; i < acl.Count; i++)
{
System.Security.AccessControl.FileSystemAccessRule rule = (System.Security.AccessControl.FileSystemAccessRule)acl[i];
IdentityReference group = groups[j].Translate(typeof(System.Security.Principal.NTAccount));
//Common.debug("check the group " + group.Value);
//Common.debug("rule.IdentityReference.Value = " + rule.IdentityReference.Value);
if (group.Value.Equals(rule.IdentityReference.Value))
{
int iCurrent = -1;
Common.debug("found the group!" + group.Value);
if (System.Security.AccessControl.AccessControlType.Deny.Equals(rule.AccessControlType))
{
Common.debug("deny");
if (contains(FileSystemRights.Read, rule))
{
Common.debug("read");
return "Deny";
}
}
if (System.Security.AccessControl.AccessControlType.Allow.Equals(rule.AccessControlType))
{
Common.debug("allow");
if (contains(FileSystemRights.Read, rule))
{
Common.debug("read");
bAllow = true;
}
}
}
}
}
if (bAllow)
return "Permit";
else
return "Deny";
}
private bool contains(System.Security.AccessControl.FileSystemRights right, System.Security.AccessControl.FileSystemAccessRule rule)
{
return (((int)right & (int)rule.FileSystemRights) == (int)right);
}
#endregion
}
}
| |
using System;
using CPUx86 = Cosmos.Assembler.x86;
using Cosmos.Assembler;
using Cosmos.IL2CPU.ILOpCodes;
using Cosmos.Assembler.x86;
using SysReflection = System.Reflection;
namespace Cosmos.IL2CPU.X86.IL
{
[Cosmos.IL2CPU.OpCode( ILOpCode.Code.Ldarga )]
public class Ldarga : ILOp
{
public Ldarga( Cosmos.Assembler.Assembler aAsmblr )
: base( aAsmblr )
{
}
public static int GetArgumentDisplacement(MethodInfo aMethod, ushort aParam)
{
var xMethodBase = aMethod.MethodBase;
if (aMethod.PluggedMethod != null)
{
xMethodBase = aMethod.PluggedMethod.MethodBase;
}
var xMethodInfo = xMethodBase as SysReflection.MethodInfo;
uint xReturnSize = 0;
if (xMethodInfo != null)
{
xReturnSize = Align(SizeOfType(xMethodInfo.ReturnType), 4);
}
uint xOffset = 8;
var xCorrectedOpValValue = aParam;
if (!aMethod.MethodBase.IsStatic && aParam > 0)
{
// if the method has a $this, the OpCode value includes the this at index 0, but GetParameters() doesnt include the this
xCorrectedOpValValue -= 1;
}
var xParams = xMethodBase.GetParameters();
if (aParam == 0 && !xMethodBase.IsStatic)
{
// return the this parameter, which is not in .GetParameters()
var xCurArgSize = Align(SizeOfType(xMethodBase.DeclaringType), 4);
for (int i = xParams.Length - 1; i >= aParam; i--) {
var xSize = Align(SizeOfType(xParams[i].ParameterType), 4);
xOffset += xSize;
}
if (xReturnSize > xCurArgSize) {
uint xExtraSize = xReturnSize - xCurArgSize;
xOffset += xExtraSize;
}
return (int)(xOffset);
}
else
{
for (int i = xParams.Length - 1; i > xCorrectedOpValValue; i--) {
var xSize = Align(SizeOfType(xParams[i].ParameterType), 4);
xOffset += xSize;
}
var xCurArgSize = Align(SizeOfType(xParams[xCorrectedOpValValue].ParameterType), 4);
uint xArgSize = 0;
foreach (var xParam in xParams) {
xArgSize += Align(SizeOfType(xParam.ParameterType), 4);
}
xReturnSize = 0;
if (xReturnSize > xArgSize) {
uint xExtraSize = xReturnSize - xArgSize;
xOffset += xExtraSize;
}
return (int)(xOffset);
}
}
public override void Execute( MethodInfo aMethod, ILOpCode aOpCode )
{
var xOpVar = (OpVar)aOpCode;
var xDisplacement = Ldarga.GetArgumentDisplacement(aMethod, xOpVar.Value);
new Mov {DestinationReg=RegistersEnum.EBX, SourceValue = (uint)(xDisplacement) };
new Mov{DestinationReg = RegistersEnum.EAX, SourceReg = RegistersEnum.EBP };
new CPUx86.Add { DestinationReg = RegistersEnum.EAX, SourceReg = RegistersEnum.EBX };
new CPUx86.Push { DestinationReg = RegistersEnum.EAX };
// if (aMethod.MethodBase.DeclaringType.FullName == "Cosmos.Kernel.Plugs.Console"
// && aMethod.MethodBase.Name == "Write"
// && aMethod.MethodBase.GetParameters()[0].ParameterType == typeof(int))
// {
// Console.Write("");
// }
// Cosmos.IL2CPU.ILOpCodes.OpVar xOpVar = ( Cosmos.IL2CPU.ILOpCodes.OpVar )aOpCode;
// var xMethodInfo = aMethod.MethodBase as System.Reflection.MethodInfo;
// uint xReturnSize = 0;
// if( xMethodInfo != null )
// {
// xReturnSize = Align( SizeOfType( xMethodInfo.ReturnType ), 4 );
// }
// uint xOffset = 8;
// var xCorrectedOpValValue = xOpVar.Value;
// if( !aMethod.MethodBase.IsStatic && xOpVar.Value > 0 )
// {
// // if the method has a $this, the OpCode value includes the this at index 0, but GetParameters() doesnt include the this
// xCorrectedOpValValue -= 1;
// }
// var xParams = aMethod.MethodBase.GetParameters();
// for( int i = xParams.Length - 1; i > xCorrectedOpValValue; i-- )
// {
// var xSize = Align( SizeOfType( xParams[ i ].ParameterType ), 4 );
// xOffset += xSize;
// }
// var xCurArgSize = Align( SizeOfType( xParams[ xCorrectedOpValValue ].ParameterType ), 4 );
// uint xArgSize = 0;
// foreach( var xParam in xParams )
// {
// xArgSize += Align( SizeOfType( xParam.ParameterType ), 4 );
// }
// xReturnSize = 0;
// uint xExtraSize = 0;
// if( xReturnSize > xArgSize )
// {
// xExtraSize = xArgSize - xReturnSize;
// }
// xOffset += xExtraSize;
//#warning TODO: check this
// new CPUx86.Push { DestinationReg = CPUx86.Registers.EBP };
// for( int i = 0; i < ( xCurArgSize / 4 ); i++ )
// {
// new CPUx86.Push { DestinationValue = ( uint )( xCurArgSize - ( ( i + 1 ) * 4 ) ) };
// }
// Assembler.Stack.Push( ( int )xCurArgSize, xParams[ xCorrectedOpValValue ].ParameterType );
// //for( int i = 0; i < ( mSize / 4 ); i++ )
// //{
// // mVirtualAddresses[ i ] = ( mOffset + ( ( i + 1 ) * 4 ) + 4 );
// //}
// //mAddress = aMethodInfo.Arguments[ aIndex ].VirtualAddresses.First();
// Assembler.Stack.Push( new StackContents.Item( 4, typeof( uint ) ) );
// //new CPUx86.Push { DestinationValue = ( uint )mAddress };
// //
// Assembler.Stack.Push( new StackContents.Item( 4, typeof( uint ) ) );
// new Add( Assembler ).Execute( aMethod, aOpCode );
}
// using System;
// using System.Linq;
//
//
// using CPU = Cosmos.Assembler.x86;
// using Cosmos.IL2CPU.X86;
//
// namespace Cosmos.IL2CPU.IL.X86 {
// [Cosmos.Assembler.OpCode(OpCodeEnum.Ldarga)]
// public class Ldarga: Op {
// private int mAddress;
// private string mNextLabel;
// private string mCurLabel;
// private uint mCurOffset;
// private MethodInformation mMethodInformation;
// protected void SetArgIndex(int aIndex, MethodInformation aMethodInfo) {
// mAddress = aMethodInfo.Arguments[aIndex].VirtualAddresses.First();
// }
// public Ldarga(MethodInformation aMethodInfo, int aIndex, string aCurrentLabel, uint aCurrentOffset, string aNextLabel)
// : base(null, aMethodInfo) {
// SetArgIndex(aIndex, aMethodInfo);
//
// mMethodInformation = aMethodInfo;
// mCurOffset = aCurrentOffset;
// mCurLabel = aCurrentLabel;
// mNextLabel = aNextLabel;
// }
//
// public Ldarga(ILReader aReader, MethodInformation aMethodInfo)
// : base(aReader, aMethodInfo) {
// if (aReader != null) {
// SetArgIndex(aReader.OperandValueInt32, aMethodInfo);
// //ParameterDefinition xParam = aReader.Operand as ParameterDefinition;
// //if (xParam != null) {
// // SetArgIndex(xParam.Sequence - 1, aMethodInfo);
// //}
// }
// mMethodInformation = aMethodInfo;
// mCurOffset = aReader.Position;
// mCurLabel = IL.Op.GetInstructionLabel(aReader);
// mNextLabel = IL.Op.GetInstructionLabel(aReader.NextPosition);
// }
// public override void DoAssemble() {
// new CPU.Push { DestinationReg = CPU.Registers.EBP };
// Assembler.Stack.Push(new StackContent(4, typeof(uint)));
// new CPU.Push { DestinationValue = (uint)mAddress };
// Assembler.Stack.Push(new StackContent(4, typeof(uint)));
// Add(Assembler, GetServiceProvider(), mCurLabel, mMethodInformation, mCurOffset, mNextLabel);
// }
// }
// }
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Serialization;
namespace Orleans.Runtime
{
/// <summary>
/// This is the base class for all typed grain references.
/// </summary>
[Serializable]
public class GrainReference : IAddressable, IEquatable<GrainReference>, ISerializable
{
private readonly string genericArguments;
private readonly GuidId observerId;
[NonSerialized]
private static readonly Logger logger = LogManager.GetLogger("GrainReference", LoggerType.Runtime);
[NonSerialized]
private static ConcurrentDictionary<int, string> debugContexts = new ConcurrentDictionary<int, string>();
[NonSerialized] private const bool USE_DEBUG_CONTEXT = true;
[NonSerialized] private const bool USE_DEBUG_CONTEXT_PARAMS = false;
[NonSerialized]
private readonly bool isUnordered = false;
internal bool IsSystemTarget { get { return GrainId.IsSystemTarget; } }
internal bool IsObserverReference { get { return GrainId.IsClient; } }
internal GuidId ObserverId { get { return observerId; } }
private bool HasGenericArgument { get { return !String.IsNullOrEmpty(genericArguments); } }
internal GrainId GrainId { get; private set; }
/// <summary>
/// Called from generated code.
/// </summary>
protected internal readonly SiloAddress SystemTargetSilo;
/// <summary>
/// Whether the runtime environment for system targets has been initialized yet.
/// Called from generated code.
/// </summary>
protected internal bool IsInitializedSystemTarget { get { return SystemTargetSilo != null; } }
internal bool IsUnordered { get { return isUnordered; } }
#region Constructors
/// <summary>Constructs a reference to the grain with the specified Id.</summary>
/// <param name="grainId">The Id of the grain to refer to.</param>
/// <param name="genericArgument">Type arguments in case of a generic grain.</param>
/// <param name="systemTargetSilo">Target silo in case of a system target reference.</param>
/// <param name="observerId">Observer ID in case of an observer reference.</param>
private GrainReference(GrainId grainId, string genericArgument, SiloAddress systemTargetSilo, GuidId observerId)
{
GrainId = grainId;
genericArguments = genericArgument;
SystemTargetSilo = systemTargetSilo;
this.observerId = observerId;
if (String.IsNullOrEmpty(genericArgument))
{
genericArguments = null; // always keep it null instead of empty.
}
// SystemTarget checks
if (grainId.IsSystemTarget && systemTargetSilo==null)
{
throw new ArgumentNullException("systemTargetSilo", String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, but passing null systemTargetSilo.", grainId));
}
if (grainId.IsSystemTarget && genericArguments != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument");
}
if (grainId.IsSystemTarget && observerId != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null observerId {1}.", grainId, observerId), "genericArgument");
}
if (!grainId.IsSystemTarget && systemTargetSilo != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for non-SystemTarget grain id {0}, but passing a non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "systemTargetSilo");
}
// ObserverId checks
if (grainId.IsClient && observerId == null)
{
throw new ArgumentNullException("observerId", String.Format("Trying to create a GrainReference for Observer with Client grain id {0}, but passing null observerId.", grainId));
}
if (grainId.IsClient && genericArguments != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument");
}
if (grainId.IsClient && systemTargetSilo != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "genericArgument");
}
if (!grainId.IsClient && observerId != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference with non null Observer {0}, but non Client grain id {1}.", observerId, grainId), "observerId");
}
isUnordered = GetUnordered();
}
/// <summary>
/// Constructs a copy of a grain reference.
/// </summary>
/// <param name="other">The reference to copy.</param>
protected GrainReference(GrainReference other)
: this(other.GrainId, other.genericArguments, other.SystemTargetSilo, other.ObserverId) { }
#endregion
#region Instance creator factory functions
/// <summary>Constructs a reference to the grain with the specified ID.</summary>
/// <param name="grainId">The ID of the grain to refer to.</param>
/// <param name="genericArguments">Type arguments in case of a generic grain.</param>
/// <param name="systemTargetSilo">Target silo in case of a system target reference.</param>
internal static GrainReference FromGrainId(GrainId grainId, string genericArguments = null, SiloAddress systemTargetSilo = null)
{
return new GrainReference(grainId, genericArguments, systemTargetSilo, null);
}
internal static GrainReference NewObserverGrainReference(GrainId grainId, GuidId observerId)
{
return new GrainReference(grainId, null, null, observerId);
}
#endregion
/// <summary>
/// Tests this reference for equality to another object.
/// Two grain references are equal if they both refer to the same grain.
/// </summary>
/// <param name="obj">The object to test for equality against this reference.</param>
/// <returns><c>true</c> if the object is equal to this reference.</returns>
public override bool Equals(object obj)
{
return Equals(obj as GrainReference);
}
public bool Equals(GrainReference other)
{
if (other == null)
return false;
if (genericArguments != other.genericArguments)
return false;
if (!GrainId.Equals(other.GrainId))
{
return false;
}
if (IsSystemTarget)
{
return Equals(SystemTargetSilo, other.SystemTargetSilo);
}
if (IsObserverReference)
{
return observerId.Equals(other.observerId);
}
return true;
}
/// <summary> Calculates a hash code for a grain reference. </summary>
public override int GetHashCode()
{
int hash = GrainId.GetHashCode();
if (IsSystemTarget)
{
hash = hash ^ SystemTargetSilo.GetHashCode();
}
if (IsObserverReference)
{
hash = hash ^ observerId.GetHashCode();
}
return hash;
}
/// <summary>Get a uniform hash code for this grain reference.</summary>
public uint GetUniformHashCode()
{
// GrainId already includes the hashed type code for generic arguments.
return GrainId.GetUniformHashCode();
}
/// <summary>
/// Compares two references for equality.
/// Two grain references are equal if they both refer to the same grain.
/// </summary>
/// <param name="reference1">First grain reference to compare.</param>
/// <param name="reference2">Second grain reference to compare.</param>
/// <returns><c>true</c> if both grain references refer to the same grain (by grain identifier).</returns>
public static bool operator ==(GrainReference reference1, GrainReference reference2)
{
if (((object)reference1) == null)
return ((object)reference2) == null;
return reference1.Equals(reference2);
}
/// <summary>
/// Compares two references for inequality.
/// Two grain references are equal if they both refer to the same grain.
/// </summary>
/// <param name="reference1">First grain reference to compare.</param>
/// <param name="reference2">Second grain reference to compare.</param>
/// <returns><c>false</c> if both grain references are resolved to the same grain (by grain identifier).</returns>
public static bool operator !=(GrainReference reference1, GrainReference reference2)
{
if (((object)reference1) == null)
return ((object)reference2) != null;
return !reference1.Equals(reference2);
}
#region Protected members
/// <summary>
/// Implemented by generated subclasses to return a constant
/// Implemented in generated code.
/// </summary>
protected virtual int InterfaceId
{
get
{
throw new InvalidOperationException("Should be overridden by subclass");
}
}
/// <summary>
/// Implemented in generated code.
/// </summary>
public virtual bool IsCompatible(int interfaceId)
{
throw new InvalidOperationException("Should be overridden by subclass");
}
/// <summary>
/// Return the name of the interface for this GrainReference.
/// Implemented in Orleans generated code.
/// </summary>
public virtual string InterfaceName
{
get
{
throw new InvalidOperationException("Should be overridden by subclass");
}
}
/// <summary>
/// Return the method name associated with the specified interfaceId and methodId values.
/// </summary>
/// <param name="interfaceId">Interface Id</param>
/// <param name="methodId">Method Id</param>
/// <returns>Method name string.</returns>
protected virtual string GetMethodName(int interfaceId, int methodId)
{
throw new InvalidOperationException("Should be overridden by subclass");
}
/// <summary>
/// Called from generated code.
/// </summary>
protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
{
Task<object> resultTask = InvokeMethodAsync<object>(methodId, arguments, options | InvokeMethodOptions.OneWay);
if (!resultTask.IsCompleted && resultTask.Result != null)
{
throw new OrleansException("Unexpected return value: one way InvokeMethod is expected to return null.");
}
}
/// <summary>
/// Called from generated code.
/// </summary>
protected Task<T> InvokeMethodAsync<T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
{
object[] argsDeepCopy = null;
if (arguments != null)
{
CheckForGrainArguments(arguments);
SetGrainCancellationTokensTarget(arguments, this);
argsDeepCopy = (object[])SerializationManager.DeepCopy(arguments);
}
var request = new InvokeMethodRequest(this.InterfaceId, methodId, argsDeepCopy);
if (IsUnordered)
options |= InvokeMethodOptions.Unordered;
Task<object> resultTask = InvokeMethod_Impl(request, null, options);
if (resultTask == null)
{
if (typeof(T) == typeof(object))
{
// optimize for most common case when using one way calls.
return PublicOrleansTaskExtensions.CompletedTask as Task<T>;
}
return Task.FromResult(default(T));
}
resultTask = OrleansTaskExtentions.ConvertTaskViaTcs(resultTask);
return resultTask.Unbox<T>();
}
#endregion
#region Private members
private Task<object> InvokeMethod_Impl(InvokeMethodRequest request, string debugContext, InvokeMethodOptions options)
{
if (debugContext == null && USE_DEBUG_CONTEXT)
{
if (USE_DEBUG_CONTEXT_PARAMS)
{
#pragma warning disable 162
// This is normally unreachable code, but kept for debugging purposes
debugContext = GetDebugContext(this.InterfaceName, GetMethodName(this.InterfaceId, request.MethodId), request.Arguments);
#pragma warning restore 162
}
else
{
var hash = InterfaceId ^ request.MethodId;
if (!debugContexts.TryGetValue(hash, out debugContext))
{
debugContext = GetDebugContext(this.InterfaceName, GetMethodName(this.InterfaceId, request.MethodId), request.Arguments);
debugContexts[hash] = debugContext;
}
}
}
// Call any registered client pre-call interceptor function.
CallClientInvokeCallback(request);
bool isOneWayCall = ((options & InvokeMethodOptions.OneWay) != 0);
var resolver = isOneWayCall ? null : new TaskCompletionSource<object>();
RuntimeClient.Current.SendRequest(this, request, resolver, ResponseCallback, debugContext, options, genericArguments);
return isOneWayCall ? null : resolver.Task;
}
private void CallClientInvokeCallback(InvokeMethodRequest request)
{
// Make callback to any registered client callback function, allowing opportunity for an application to set any additional RequestContext info, etc.
// Should we set some kind of callback-in-progress flag to detect and prevent any inappropriate callback loops on this GrainReference?
try
{
Action<InvokeMethodRequest, IGrain> callback = GrainClient.ClientInvokeCallback; // Take copy to avoid potential race conditions
if (callback == null) return;
// Call ClientInvokeCallback only for grain calls, not for system targets.
if (this is IGrain)
{
callback(request, (IGrain) this);
}
}
catch (Exception exc)
{
logger.Warn(ErrorCode.ProxyClient_ClientInvokeCallback_Error,
"Error while invoking ClientInvokeCallback function " + GrainClient.ClientInvokeCallback,
exc);
throw;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void ResponseCallback(Message message, TaskCompletionSource<object> context)
{
Response response;
if (message.Result != Message.ResponseTypes.Rejection)
{
try
{
response = (Response)message.BodyObject;
}
catch (Exception exc)
{
// catch the Deserialize exception and break the promise with it.
response = Response.ExceptionResponse(exc);
}
}
else
{
Exception rejection;
switch (message.RejectionType)
{
case Message.RejectionTypes.GatewayTooBusy:
rejection = new GatewayTooBusyException();
break;
case Message.RejectionTypes.DuplicateRequest:
return; // Ignore duplicates
default:
rejection = message.BodyObject as OrleansException;
if (rejection == null)
{
if (string.IsNullOrEmpty(message.RejectionInfo))
{
message.RejectionInfo = "Unable to send request - no rejection info available";
}
rejection = new OrleansException(message.RejectionInfo);
}
break;
}
response = Response.ExceptionResponse(rejection);
}
if (!response.ExceptionFlag)
{
context.TrySetResult(response.Data);
}
else
{
context.TrySetException(response.Exception);
}
}
private bool GetUnordered()
{
if (RuntimeClient.Current == null) return false;
return RuntimeClient.Current.GrainTypeResolver != null && RuntimeClient.Current.GrainTypeResolver.IsUnordered(GrainId.GetTypeCode());
}
#endregion
/// <summary>
/// Internal implementation of Cast operation for grain references
/// Called from generated code.
/// </summary>
/// <param name="targetReferenceType">Type that this grain reference should be cast to</param>
/// <param name="grainRefCreatorFunc">Delegate function to create grain references of the target type</param>
/// <param name="grainRef">Grain reference to cast from</param>
/// <param name="interfaceId">Interface id value for the target cast type</param>
/// <returns>GrainReference that is usable as the target type</returns>
/// <exception cref="System.InvalidCastException">if the grain cannot be cast to the target type</exception>
protected internal static IAddressable CastInternal(
Type targetReferenceType,
Func<GrainReference, IAddressable> grainRefCreatorFunc,
IAddressable grainRef,
int interfaceId)
{
if (grainRef == null) throw new ArgumentNullException("grainRef");
Type sourceType = grainRef.GetType();
if (!typeof(IAddressable).IsAssignableFrom(targetReferenceType))
{
throw new InvalidCastException(String.Format("Target type must be derived from Orleans.IAddressable - cannot handle {0}", targetReferenceType));
}
else if (typeof(Grain).IsAssignableFrom(sourceType))
{
Grain grainClassRef = (Grain)grainRef;
GrainReference g = FromGrainId(grainClassRef.Data.Identity);
grainRef = g;
}
else if (!typeof(GrainReference).IsAssignableFrom(sourceType))
{
throw new InvalidCastException(String.Format("Grain reference object must an Orleans.GrainReference - cannot handle {0}", sourceType));
}
if (targetReferenceType.IsAssignableFrom(sourceType))
{
// Already compatible - no conversion or wrapping necessary
return grainRef;
}
// We have an untyped grain reference that may resolve eventually successfully -- need to enclose in an apprroately typed wrapper class
var grainReference = (GrainReference) grainRef;
var grainWrapper = (GrainReference) grainRefCreatorFunc(grainReference);
return grainWrapper;
}
private static String GetDebugContext(string interfaceName, string methodName, object[] arguments)
{
// String concatenation is approx 35% faster than string.Format here
//debugContext = String.Format("{0}:{1}()", this.InterfaceName, GetMethodName(this.InterfaceId, methodId));
var debugContext = new StringBuilder();
debugContext.Append(interfaceName);
debugContext.Append(":");
debugContext.Append(methodName);
if (USE_DEBUG_CONTEXT_PARAMS && arguments != null && arguments.Length > 0)
{
debugContext.Append("(");
debugContext.Append(Utils.EnumerableToString(arguments));
debugContext.Append(")");
}
else
{
debugContext.Append("()");
}
return debugContext.ToString();
}
private static void CheckForGrainArguments(object[] arguments)
{
foreach (var argument in arguments)
if (argument is Grain)
throw new ArgumentException(String.Format("Cannot pass a grain object {0} as an argument to a method. Pass this.AsReference<GrainInterface>() instead.", argument.GetType().FullName));
}
/// <summary>
/// Sets target grain to the found instances of type GrainCancellationToken
/// </summary>
/// <param name="arguments"> Grain method arguments list</param>
/// <param name="target"> Target grain reference</param>
private static void SetGrainCancellationTokensTarget(object[] arguments, GrainReference target)
{
if (arguments == null) return;
foreach (var argument in arguments)
{
(argument as GrainCancellationToken)?.AddGrainReference(target);
}
}
/// <summary> Serializer function for grain reference.</summary>
/// <seealso cref="SerializationManager"/>
[SerializerMethod]
protected internal static void SerializeGrainReference(object obj, BinaryTokenStreamWriter stream, Type expected)
{
var input = (GrainReference)obj;
stream.Write(input.GrainId);
if (input.IsSystemTarget)
{
stream.Write((byte)1);
stream.Write(input.SystemTargetSilo);
}
else
{
stream.Write((byte)0);
}
if (input.IsObserverReference)
{
input.observerId.SerializeToStream(stream);
}
// store as null, serialize as empty.
var genericArg = String.Empty;
if (input.HasGenericArgument)
genericArg = input.genericArguments;
stream.Write(genericArg);
}
/// <summary> Deserializer function for grain reference.</summary>
/// <seealso cref="SerializationManager"/>
[DeserializerMethod]
protected internal static object DeserializeGrainReference(Type t, BinaryTokenStreamReader stream)
{
GrainId id = stream.ReadGrainId();
SiloAddress silo = null;
GuidId observerId = null;
byte siloAddressPresent = stream.ReadByte();
if (siloAddressPresent != 0)
{
silo = stream.ReadSiloAddress();
}
bool expectObserverId = id.IsClient;
if (expectObserverId)
{
observerId = GuidId.DeserializeFromStream(stream);
}
// store as null, serialize as empty.
var genericArg = stream.ReadString();
if (String.IsNullOrEmpty(genericArg))
genericArg = null;
if (expectObserverId)
{
return NewObserverGrainReference(id, observerId);
}
return FromGrainId(id, genericArg, silo);
}
/// <summary> Copier function for grain reference. </summary>
/// <seealso cref="SerializationManager"/>
[CopierMethod]
protected internal static object CopyGrainReference(object original)
{
return (GrainReference)original;
}
private const string GRAIN_REFERENCE_STR = "GrainReference";
private const string SYSTEM_TARGET_STR = "SystemTarget";
private const string OBSERVER_ID_STR = "ObserverId";
private const string GENERIC_ARGUMENTS_STR = "GenericArguments";
/// <summary>Returns a string representation of this reference.</summary>
public override string ToString()
{
if (IsSystemTarget)
{
return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId, SystemTargetSilo);
}
if (IsObserverReference)
{
return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId, observerId);
}
return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId,
!HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments));
}
internal string ToDetailedString()
{
if (IsSystemTarget)
{
return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId.ToDetailedString(), SystemTargetSilo);
}
if (IsObserverReference)
{
return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId.ToDetailedString(), observerId.ToDetailedString());
}
return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId.ToDetailedString(),
!HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments));
}
/// <summary> Get the key value for this grain, as a string. </summary>
public string ToKeyString()
{
if (IsObserverReference)
{
return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), OBSERVER_ID_STR, observerId.ToParsableString());
}
if (IsSystemTarget)
{
return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), SYSTEM_TARGET_STR, SystemTargetSilo.ToParsableString());
}
if (HasGenericArgument)
{
return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), GENERIC_ARGUMENTS_STR, genericArguments);
}
return String.Format("{0}={1}", GRAIN_REFERENCE_STR, GrainId.ToParsableString());
}
public static GrainReference FromKeyString(string key)
{
if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException("key", "GrainReference.FromKeyString cannot parse null key");
string trimmed = key.Trim();
string grainIdStr;
int grainIdIndex = (GRAIN_REFERENCE_STR + "=").Length;
int genericIndex = trimmed.IndexOf(GENERIC_ARGUMENTS_STR + "=", StringComparison.Ordinal);
int observerIndex = trimmed.IndexOf(OBSERVER_ID_STR + "=", StringComparison.Ordinal);
int systemTargetIndex = trimmed.IndexOf(SYSTEM_TARGET_STR + "=", StringComparison.Ordinal);
if (genericIndex >= 0)
{
grainIdStr = trimmed.Substring(grainIdIndex, genericIndex - grainIdIndex).Trim();
string genericStr = trimmed.Substring(genericIndex + (GENERIC_ARGUMENTS_STR + "=").Length);
if (String.IsNullOrEmpty(genericStr))
{
genericStr = null;
}
return FromGrainId(GrainId.FromParsableString(grainIdStr), genericStr);
}
else if (observerIndex >= 0)
{
grainIdStr = trimmed.Substring(grainIdIndex, observerIndex - grainIdIndex).Trim();
string observerIdStr = trimmed.Substring(observerIndex + (OBSERVER_ID_STR + "=").Length);
GuidId observerId = GuidId.FromParsableString(observerIdStr);
return NewObserverGrainReference(GrainId.FromParsableString(grainIdStr), observerId);
}
else if (systemTargetIndex >= 0)
{
grainIdStr = trimmed.Substring(grainIdIndex, systemTargetIndex - grainIdIndex).Trim();
string systemTargetStr = trimmed.Substring(systemTargetIndex + (SYSTEM_TARGET_STR + "=").Length);
SiloAddress siloAddress = SiloAddress.FromParsableString(systemTargetStr);
return FromGrainId(GrainId.FromParsableString(grainIdStr), null, siloAddress);
}
else
{
grainIdStr = trimmed.Substring(grainIdIndex);
return FromGrainId(GrainId.FromParsableString(grainIdStr));
}
//return FromGrainId(GrainId.FromParsableString(grainIdStr), generic);
}
#region ISerializable Members
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Use the AddValue method to specify serialized values.
info.AddValue("GrainId", GrainId.ToParsableString(), typeof(string));
if (IsSystemTarget)
{
info.AddValue("SystemTargetSilo", SystemTargetSilo.ToParsableString(), typeof(string));
}
if (IsObserverReference)
{
info.AddValue(OBSERVER_ID_STR, observerId.ToParsableString(), typeof(string));
}
string genericArg = String.Empty;
if (HasGenericArgument)
genericArg = genericArguments;
info.AddValue("GenericArguments", genericArg, typeof(string));
}
// The special constructor is used to deserialize values.
protected GrainReference(SerializationInfo info, StreamingContext context)
{
// Reset the property value using the GetValue method.
var grainIdStr = info.GetString("GrainId");
GrainId = GrainId.FromParsableString(grainIdStr);
if (IsSystemTarget)
{
var siloAddressStr = info.GetString("SystemTargetSilo");
SystemTargetSilo = SiloAddress.FromParsableString(siloAddressStr);
}
if (IsObserverReference)
{
var observerIdStr = info.GetString(OBSERVER_ID_STR);
observerId = GuidId.FromParsableString(observerIdStr);
}
var genericArg = info.GetString("GenericArguments");
if (String.IsNullOrEmpty(genericArg))
genericArg = null;
genericArguments = genericArg;
}
#endregion
}
}
| |
/*
* Copyright (c) 2013 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace AssetBundleGraph {
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// LogUtility.Logger.Log("deserialized: " + dict.GetType());
// LogUtility.Logger.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// LogUtility.Logger.Log("dict['string']: " + (string) dict["string"]);
// LogUtility.Logger.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// LogUtility.Logger.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// LogUtility.Logger.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// LogUtility.Logger.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class Json {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WORD_BREAK = "{}[],:\"";
public static bool IsWordBreak(char c) {
return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1;
}
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
StringReader json;
Parser(string jsonString) {
json = new StringReader(jsonString);
}
public static object Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return instance.ParseValue();
}
}
public void Dispose() {
json.Dispose();
json = null;
}
Dictionary<string, object> ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
table[name] = ParseValue();
break;
}
}
}
List<object> ParseArray() {
List<object> array = new List<object>();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new char[4];
for (int i=0; i< 4; i++) {
hex[i] = NextChar;
}
s.Append((char) Convert.ToInt32(new string(hex), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
if (number.IndexOf('.') == -1) {
long parsedInt;
Int64.TryParse(number, out parsedInt);
return parsedInt;
}
double parsedDouble;
Double.TryParse(number, out parsedDouble);
return parsedDouble;
}
void EatWhitespace() {
while (Char.IsWhiteSpace(PeekChar)) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (!IsWordBreak(PeekChar)) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
switch (PeekChar) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
switch (NextWord) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(object obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value) {
IList asList;
IDictionary asDict;
string asStr;
if (value == null) {
builder.Append("null");
} else if ((asStr = value as string) != null) {
SerializeString(asStr);
} else if (value is bool) {
builder.Append((bool) value ? "true" : "false");
} else if ((asList = value as IList) != null) {
SerializeArray(asList);
} else if ((asDict = value as IDictionary) != null) {
SerializeObject(asDict);
} else if (value is char) {
SerializeString(new string((char) value, 1));
} else {
SerializeOther(value);
}
}
void SerializeObject(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray) {
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
} else {
builder.Append("\\u");
builder.Append(codepoint.ToString("x4"));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value) {
// NOTE: decimals lose precision during serialization.
// They always have, I'm just letting you know.
// Previously floats and doubles lost precision too.
if (value is float) {
builder.Append(((float) value).ToString("R"));
} else if (value is int
|| value is uint
|| value is long
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong) {
builder.Append(value);
} else if (value is double
|| value is decimal) {
builder.Append(Convert.ToDouble(value).ToString("R"));
} else {
SerializeString(value.ToString());
}
}
}
private const string INDENT_STRING = " ";
public static string Prettify (string sourceJson) {
var indent = 0;
var quoted = false;
var sb = new StringBuilder();
for (var i = 0; i < sourceJson.Length; i++)
{
var ch = sourceJson[i];
switch (ch)
{
case '{':
case '[':
sb.Append(ch);
if (!quoted)
{
sb.AppendLine();
++indent;
for (int j = 0; j < indent; j++)
{
sb.Append(INDENT_STRING);
}
}
break;
case '}':
case ']':
if (!quoted)
{
sb.AppendLine();
--indent;
for (int j = 0; j < indent; j++)
{
sb.Append(INDENT_STRING);
}
}
sb.Append(ch);
break;
case '"':
sb.Append(ch);
bool escaped = false;
var index = i;
while (index > 0 && sourceJson[--index] == '\\')
escaped = !escaped;
if (!escaped)
quoted = !quoted;
break;
case ',':
sb.Append(ch);
if (!quoted)
{
sb.AppendLine();
for (int j = 0; j < indent; j++)
{
sb.Append(INDENT_STRING);
}
}
break;
case ':':
sb.Append(ch);
if (!quoted)
sb.Append(" ");
break;
default:
sb.Append(ch);
break;
}
}
return sb.ToString();
}
}
}
| |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Saga
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Logging;
using MassTransit.Pipeline;
using Util;
public class InMemorySagaRepository<TSaga> :
ISagaRepository<TSaga>,
IQuerySagaRepository<TSaga>
where TSaga : class, ISaga
{
static readonly ILog _log = Logger.Get(typeof(InMemorySagaRepository<TSaga>));
readonly IndexedSagaDictionary<TSaga> _sagas;
public InMemorySagaRepository()
{
_sagas = new IndexedSagaDictionary<TSaga>();
}
public SagaInstance<TSaga> this[Guid id] => _sagas[id];
public Task<IEnumerable<Guid>> Find(ISagaQuery<TSaga> query)
{
return Task.FromResult(_sagas.Where(query).Select(x => x.Instance.CorrelationId));
}
void IProbeSite.Probe(ProbeContext context)
{
ProbeContext scope = context.CreateScope("sagaRepository");
scope.Set(new
{
_sagas.Count,
Persistence = "memory"
});
}
async Task ISagaRepository<TSaga>.Send<T>(ConsumeContext<T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next)
{
if (!context.CorrelationId.HasValue)
throw new SagaException("The CorrelationId was not specified", typeof(TSaga), typeof(T));
Guid sagaId = context.CorrelationId.Value;
bool needToLeaveSagas = true;
await _sagas.MarkInUse(context.CancellationToken).ConfigureAwait(false);
try
{
SagaInstance<TSaga> saga = _sagas[sagaId];
if (saga == null)
{
var missingSagaPipe = new MissingPipe<T>(this, next, true);
await policy.Missing(context, missingSagaPipe).ConfigureAwait(false);
_sagas.Release();
needToLeaveSagas = false;
}
else
{
await saga.MarkInUse(context.CancellationToken).ConfigureAwait(false);
try
{
_sagas.Release();
needToLeaveSagas = false;
if (_log.IsDebugEnabled)
_log.DebugFormat("SAGA:{0}:{1} Used {2}", TypeMetadataCache<TSaga>.ShortName, sagaId, TypeMetadataCache<T>.ShortName);
SagaConsumeContext<TSaga, T> sagaConsumeContext = new InMemorySagaConsumeContext<TSaga, T>(context, saga.Instance, () => Remove(saga, context.CancellationToken));
await policy.Existing(sagaConsumeContext, next).ConfigureAwait(false);
}
finally
{
saga.Release();
}
}
}
finally
{
if (needToLeaveSagas)
_sagas.Release();
}
}
async Task ISagaRepository<TSaga>.SendQuery<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy,
IPipe<SagaConsumeContext<TSaga, T>> next)
{
SagaInstance<TSaga>[] existingSagas = _sagas.Where(context.Query).ToArray();
if (existingSagas.Length == 0)
{
var missingSagaPipe = new MissingPipe<T>(this, next);
await policy.Missing(context, missingSagaPipe).ConfigureAwait(false);
}
else
await Task.WhenAll(existingSagas.Select(instance => SendToInstance(context, policy, instance, next))).ConfigureAwait(false);
}
async Task SendToInstance<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy, SagaInstance<TSaga> saga,
IPipe<SagaConsumeContext<TSaga, T>> next)
where T : class
{
await saga.MarkInUse(context.CancellationToken).ConfigureAwait(false);
try
{
if (_log.IsDebugEnabled)
_log.DebugFormat("SAGA:{0}:{1} Used {2}", TypeMetadataCache<TSaga>.ShortName, saga.Instance.CorrelationId, TypeMetadataCache<T>.ShortName);
SagaConsumeContext<TSaga, T> sagaConsumeContext = new InMemorySagaConsumeContext<TSaga, T>(context, saga.Instance,
() => Remove(saga, context.CancellationToken));
await policy.Existing(sagaConsumeContext, next).ConfigureAwait(false);
}
finally
{
saga.Release();
}
}
/// <summary>
/// Add an instance to the saga repository
/// </summary>
/// <param name="newSaga"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task Add(TSaga newSaga, CancellationToken cancellationToken)
{
await _sagas.MarkInUse(cancellationToken).ConfigureAwait(false);
try
{
_sagas.Add(newSaga);
}
finally
{
_sagas.Release();
}
}
/// <summary>
/// Remove an instance from the saga repository
/// </summary>
/// <param name="saga"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task Remove(TSaga saga, CancellationToken cancellationToken)
{
await _sagas.MarkInUse(cancellationToken).ConfigureAwait(false);
try
{
_sagas.Remove(new SagaInstance<TSaga>(saga));
}
finally
{
_sagas.Release();
}
}
async Task Remove(SagaInstance<TSaga> saga, CancellationToken cancellationToken)
{
await _sagas.MarkInUse(cancellationToken).ConfigureAwait(false);
try
{
_sagas.Remove(saga);
}
finally
{
_sagas.Release();
}
}
/// <summary>
/// Adds the saga within an existing lock
/// </summary>
/// <param name="newSaga"></param>
void AddWithinLock(TSaga newSaga)
{
_sagas.Add(newSaga);
}
void RemoveWithinLock(TSaga saga)
{
_sagas.Remove(new SagaInstance<TSaga>(saga));
}
/// <summary>
/// Once the message pipe has processed the saga instance, add it to the saga repository
/// </summary>
/// <typeparam name="TMessage"></typeparam>
class MissingPipe<TMessage> :
IPipe<SagaConsumeContext<TSaga, TMessage>>
where TMessage : class
{
readonly IPipe<SagaConsumeContext<TSaga, TMessage>> _next;
readonly InMemorySagaRepository<TSaga> _repository;
readonly bool _withinLock;
public MissingPipe(InMemorySagaRepository<TSaga> repository, IPipe<SagaConsumeContext<TSaga, TMessage>> next, bool withinLock = false)
{
_repository = repository;
_next = next;
_withinLock = withinLock;
}
void IProbeSite.Probe(ProbeContext context)
{
_next.Probe(context);
}
public async Task Send(SagaConsumeContext<TSaga, TMessage> context)
{
var proxy = new InMemorySagaConsumeContext<TSaga, TMessage>(context, context.Saga,
() => RemoveNewSaga(context.Saga, context.CancellationToken));
if (_withinLock)
_repository.AddWithinLock(context.Saga);
else
await _repository.Add(context.Saga, context.CancellationToken).ConfigureAwait(false);
if (_log.IsDebugEnabled)
{
_log.DebugFormat("SAGA:{0}:{1} Added {2}", TypeMetadataCache<TSaga>.ShortName, context.Saga.CorrelationId,
TypeMetadataCache<TMessage>.ShortName);
}
try
{
await _next.Send(proxy).ConfigureAwait(false);
if (proxy.IsCompleted)
{
await RemoveNewSaga(proxy.Saga, context.CancellationToken).ConfigureAwait(false);
}
}
catch (Exception)
{
if (_log.IsDebugEnabled)
{
_log.DebugFormat("SAGA:{0}:{1} Removed(Fault) {2}", TypeMetadataCache<TSaga>.ShortName, context.Saga.CorrelationId,
TypeMetadataCache<TMessage>.ShortName);
}
await RemoveNewSaga(proxy.Saga, context.CancellationToken).ConfigureAwait(false);
throw;
}
}
async Task RemoveNewSaga(TSaga saga, CancellationToken cancellationToken)
{
if (_withinLock)
_repository.RemoveWithinLock(saga);
else
await _repository.Remove(saga, cancellationToken).ConfigureAwait(false);
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Workflow.Runtime
{
using System.Collections;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.IO;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
class StreamedWorkflowDefinitionContext : WorkflowDefinitionContext
{
object lockObject = new object();
// Double-checked locking pattern requires volatile for read/write synchronization
volatile System.Workflow.ComponentModel.Activity rootActivity = null;
byte[] ruleDefinition = null;
ITypeProvider typeProvider = null;
byte[] workflowDefinition = null;
internal StreamedWorkflowDefinitionContext(Stream workflowDefinition, Stream ruleDefinition, ITypeProvider typeProvider)
{
if (workflowDefinition == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workflowDefinition");
}
this.workflowDefinition = new byte[workflowDefinition.Length];
workflowDefinition.Read(this.workflowDefinition, 0, (int) workflowDefinition.Length);
if (ruleDefinition != null)
{
this.ruleDefinition = new byte[ruleDefinition.Length];
ruleDefinition.Read(this.ruleDefinition, 0, (int) ruleDefinition.Length);
}
this.typeProvider = typeProvider;
}
internal StreamedWorkflowDefinitionContext(string workflowDefinitionPath, string ruleDefinitionPath, ITypeProvider typeProvider)
{
FileStream workflowDefStream = null;
FileStream ruleDefStream = null;
if (workflowDefinitionPath == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workflowDefinitionPath");
}
try
{
workflowDefStream = new FileStream(workflowDefinitionPath, FileMode.Open, FileAccess.Read);
if (ruleDefinitionPath != null)
{
ruleDefStream = new FileStream(ruleDefinitionPath, FileMode.Open, FileAccess.Read);
}
this.workflowDefinition = new byte[workflowDefStream.Length];
workflowDefStream.Read(workflowDefinition, 0, (int) workflowDefStream.Length);
if (ruleDefStream != null)
{
this.ruleDefinition = new byte[ruleDefStream.Length];
ruleDefStream.Read(this.ruleDefinition, 0, (int) ruleDefStream.Length);
}
this.typeProvider = typeProvider;
}
finally
{
if (workflowDefStream != null)
{
workflowDefStream.Close();
}
if (ruleDefStream != null)
{
ruleDefStream.Close();
}
}
}
// This is a valid catch of all exceptions
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
// We don't have tracing in Silver as of M2
[System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "Reliability104:CaughtAndHandledExceptionsRule")]
public override string ConfigurationName
{
get
{
if (rootActivity == null)
{
try
{
GetWorkflowDefinition();
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
#if !_PRESHARP_
// this throw in a getter is valid
throw;
#endif
}
}
}
return rootActivity != null ? rootActivity.QualifiedName : null;
}
}
// This is a valid catch of all exceptions
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
// We don't have tracing in Silver as of M2
[System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "Reliability104:CaughtAndHandledExceptionsRule")]
public override string WorkflowName
{
get
{
if (rootActivity == null)
{
try
{
GetWorkflowDefinition();
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
#if !_PRESHARP_
// this throw in a getter is valid
throw;
#endif
}
}
}
return rootActivity != null ? NamingHelper.XmlName(rootActivity.QualifiedName) : null;
}
}
public override WorkflowInstance CreateWorkflow()
{
return this.CreateWorkflow(Guid.NewGuid());
}
public override WorkflowInstance CreateWorkflow(Guid instanceId)
{
System.IO.Stream definitionStream = null;
System.IO.Stream ruleStream = null;
System.Xml.XmlReader definitionReader = null;
System.Xml.XmlReader ruleReader = null;
try
{
definitionStream = new System.IO.MemoryStream(workflowDefinition);
definitionStream.Position = 0;
definitionReader = System.Xml.XmlReader.Create(definitionStream);
if (ruleDefinition != null)
{
ruleStream = new System.IO.MemoryStream(ruleDefinition);
ruleStream.Position = 0;
ruleReader = System.Xml.XmlReader.Create(ruleStream);
}
return this.WorkflowRuntime.CreateWorkflow(definitionReader, ruleReader, null, instanceId);
}
finally
{
if (definitionStream != null)
{
definitionStream.Dispose();
}
if (ruleStream != null)
{
ruleStream.Dispose();
}
}
}
public override System.Workflow.ComponentModel.Activity GetWorkflowDefinition()
{
if (rootActivity == null)
{
lock (lockObject)
{
if (rootActivity == null)
{
rootActivity = DeSerizalizeDefinition(workflowDefinition, ruleDefinition);
}
}
}
return rootActivity;
}
protected override void OnRegister()
{
if (this.typeProvider != null)
{
if (this.WorkflowRuntime.IsStarted)
{
this.WorkflowRuntime.StopRuntime();
}
this.WorkflowRuntime.AddService(this.typeProvider);
}
}
protected override void OnValidate(ValidationErrorCollection errors)
{
if (!string.IsNullOrEmpty(this.rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string))
{
errors.Add(new ValidationError(SR2.XomlWorkflowHasClassName, ErrorNumbers.Error_XomlWorkflowHasClassName));
}
Queue compositeActivities = new Queue();
compositeActivities.Enqueue(this.rootActivity);
while (compositeActivities.Count > 0)
{
System.Workflow.ComponentModel.Activity activity = compositeActivities.Dequeue() as System.Workflow.ComponentModel.Activity;
if (activity.GetValue(WorkflowMarkupSerializer.XCodeProperty) != null)
{
errors.Add(new ValidationError(SR2.XomlWorkflowHasCode, ErrorNumbers.Error_XomlWorkflowHasCode));
}
CompositeActivity compositeActivity = activity as CompositeActivity;
if (compositeActivity != null)
{
foreach (System.Workflow.ComponentModel.Activity childActivity in compositeActivity.EnabledActivities)
{
compositeActivities.Enqueue(childActivity);
}
}
}
}
System.Workflow.ComponentModel.Activity DeSerizalizeDefinition(byte[] workflowDefinition, byte[] ruleDefinition)
{
System.IO.Stream definitionStream = null;
System.IO.Stream ruleStream = null;
System.Xml.XmlReader definitionReader = null;
System.Xml.XmlReader ruleReader = null;
try
{
definitionStream = new System.IO.MemoryStream(workflowDefinition);
definitionStream.Position = 0;
definitionReader = System.Xml.XmlReader.Create(definitionStream);
if (ruleDefinition != null)
{
ruleStream = new System.IO.MemoryStream(ruleDefinition);
ruleStream.Position = 0;
ruleReader = System.Xml.XmlReader.Create(ruleStream);
}
System.Workflow.ComponentModel.Activity root = null;
ValidationErrorCollection errors = new ValidationErrorCollection();
ServiceContainer serviceContainer = new ServiceContainer();
if (this.typeProvider != null)
{
serviceContainer.AddService(typeof(ITypeProvider), this.typeProvider);
}
DesignerSerializationManager manager = new DesignerSerializationManager(serviceContainer);
try
{
using (manager.CreateSession())
{
WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
root = new WorkflowMarkupSerializer().Deserialize(xomlSerializationManager, definitionReader) as System.Workflow.ComponentModel.Activity;
if (root != null && ruleReader != null)
{
object rules = new WorkflowMarkupSerializer().Deserialize(xomlSerializationManager, ruleReader);
root.SetValue(System.Workflow.Activities.Rules.RuleDefinitions.RuleDefinitionsProperty, rules);
}
foreach (object error in manager.Errors)
{
if (error is WorkflowMarkupSerializationException)
{
errors.Add(new ValidationError(((WorkflowMarkupSerializationException) error).Message, 1));
}
else
{
errors.Add(new ValidationError(error.ToString(), 1));
}
}
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
errors.Add(new ValidationError(e.Message, 1));
}
if (errors.HasErrors)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WorkflowValidationFailedException(SR2.GetString(SR2.WorkflowValidationFailed), errors));
}
return root;
}
finally
{
if (definitionStream != null)
{
definitionStream.Dispose();
}
if (ruleStream != null)
{
ruleStream.Dispose();
}
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.Compute;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure
{
/// <summary>
/// The Service Management API provides programmatic access to much of the
/// functionality available through the Management Portal. The Service
/// Management API is a REST API. All API operations are performed over
/// SSL, and are mutually authenticated using X.509 v3 certificates. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
/// more information)
/// </summary>
public static partial class DNSServerOperationsExtensions
{
/// <summary>
/// Add a definition for a DNS server to an existing deployment. VM's
/// in this deployment will be programmed to use this DNS server for
/// all DNS resolutions
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Add DNS Server operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static OperationStatusResponse AddDNSServer(this IDNSServerOperations operations, string serviceName, string deploymentName, DNSAddParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDNSServerOperations)s).AddDNSServerAsync(serviceName, deploymentName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Add a definition for a DNS server to an existing deployment. VM's
/// in this deployment will be programmed to use this DNS server for
/// all DNS resolutions
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Add DNS Server operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<OperationStatusResponse> AddDNSServerAsync(this IDNSServerOperations operations, string serviceName, string deploymentName, DNSAddParameters parameters)
{
return operations.AddDNSServerAsync(serviceName, deploymentName, parameters, CancellationToken.None);
}
/// <summary>
/// Add a definition for a DNS server to an existing deployment. VM's
/// in this deployment will be programmed to use this DNS server for
/// all DNS resolutions
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Add DNS Server operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static OperationStatusResponse BeginAddingDNSServer(this IDNSServerOperations operations, string serviceName, string deploymentName, DNSAddParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDNSServerOperations)s).BeginAddingDNSServerAsync(serviceName, deploymentName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Add a definition for a DNS server to an existing deployment. VM's
/// in this deployment will be programmed to use this DNS server for
/// all DNS resolutions
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Add DNS Server operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<OperationStatusResponse> BeginAddingDNSServerAsync(this IDNSServerOperations operations, string serviceName, string deploymentName, DNSAddParameters parameters)
{
return operations.BeginAddingDNSServerAsync(serviceName, deploymentName, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes a definition for an existing DNS server from the deployment
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static OperationStatusResponse BeginDeletingDNSServer(this IDNSServerOperations operations, string serviceName, string deploymentName, string dnsServerName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDNSServerOperations)s).BeginDeletingDNSServerAsync(serviceName, deploymentName, dnsServerName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a definition for an existing DNS server from the deployment
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<OperationStatusResponse> BeginDeletingDNSServerAsync(this IDNSServerOperations operations, string serviceName, string deploymentName, string dnsServerName)
{
return operations.BeginDeletingDNSServerAsync(serviceName, deploymentName, dnsServerName, CancellationToken.None);
}
/// <summary>
/// Updates a definition for an existing DNS server. Updates to address
/// is the only change allowed. DNS server name cannot be changed
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update DNS Server operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static OperationStatusResponse BeginUpdatingDNSServer(this IDNSServerOperations operations, string serviceName, string deploymentName, string dnsServerName, DNSUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDNSServerOperations)s).BeginUpdatingDNSServerAsync(serviceName, deploymentName, dnsServerName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a definition for an existing DNS server. Updates to address
/// is the only change allowed. DNS server name cannot be changed
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update DNS Server operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<OperationStatusResponse> BeginUpdatingDNSServerAsync(this IDNSServerOperations operations, string serviceName, string deploymentName, string dnsServerName, DNSUpdateParameters parameters)
{
return operations.BeginUpdatingDNSServerAsync(serviceName, deploymentName, dnsServerName, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes a definition for an existing DNS server from the deployment
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static OperationStatusResponse DeleteDNSServer(this IDNSServerOperations operations, string serviceName, string deploymentName, string dnsServerName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDNSServerOperations)s).DeleteDNSServerAsync(serviceName, deploymentName, dnsServerName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a definition for an existing DNS server from the deployment
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<OperationStatusResponse> DeleteDNSServerAsync(this IDNSServerOperations operations, string serviceName, string deploymentName, string dnsServerName)
{
return operations.DeleteDNSServerAsync(serviceName, deploymentName, dnsServerName, CancellationToken.None);
}
/// <summary>
/// Updates a definition for an existing DNS server. Updates to address
/// is the only change allowed. DNS server name cannot be changed
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update DNS Server operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static OperationStatusResponse UpdateDNSServer(this IDNSServerOperations operations, string serviceName, string deploymentName, string dnsServerName, DNSUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDNSServerOperations)s).UpdateDNSServerAsync(serviceName, deploymentName, dnsServerName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a definition for an existing DNS server. Updates to address
/// is the only change allowed. DNS server name cannot be changed
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Compute.IDNSServerOperations.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='dnsServerName'>
/// Required. The name of the dns server.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update DNS Server operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<OperationStatusResponse> UpdateDNSServerAsync(this IDNSServerOperations operations, string serviceName, string deploymentName, string dnsServerName, DNSUpdateParameters parameters)
{
return operations.UpdateDNSServerAsync(serviceName, deploymentName, dnsServerName, parameters, CancellationToken.None);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.verify.verify
{
public class Verify
{
public static int Check(dynamic actual, dynamic expected)
{
int index = 0;
foreach (var item in expected)
{
if (actual[index] != expected[index])
return 0;
index++;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease001.decrease001
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>prefix increment</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public int flag;
public int this[int index]
{
set
{
flag = value;
}
get
{
return index;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
int x1 = t[1]--;
if (x1 != 1 || t.flag != 0)
return 1;
dynamic index = 5;
int x2 = t[index]--;
if (x2 != 5 || t.flag != 4)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease001e.decrease001e
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>prefix increment</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public bool flag;
public bool this[int index]
{
set
{
flag = value;
}
get
{
return index > 5;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
dynamic index = 5;
try
{
int x1 = t[1]--;
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "--", "bool");
if (!ret)
return 1;
}
try
{
var x2 = t[index]++;
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "++", "bool");
if (!ret)
return 1;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease002.decrease002
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>prefix increment</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public int flag;
public int this[int index]
{
set
{
flag = value;
}
get
{
return index;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
int x1 = --t[1];
if (x1 != 0 || t.flag != 0)
return 1;
dynamic index = 5;
int x2 = --t[index];
if (x2 != 4 || t.flag != 4)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.decrease002e.decrease002e
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>postfix decrement</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public bool flag;
public bool this[int index]
{
set
{
flag = value;
}
get
{
return index > 5;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
dynamic index = 5;
try
{
int x1 = --t[1];
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "--", "bool");
if (!ret)
return 1;
}
try
{
var x2 = --t[index];
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "--", "bool");
if (!ret)
return 1;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.increase001.increase001
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>prefix increment</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public int flag;
public int this[int index]
{
set
{
flag = value;
}
get
{
return index;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
int x1 = t[1]++;
if (x1 != 1 || t.flag != 2)
return 1;
dynamic index = 5;
int x2 = t[index]++;
if (x2 != 5 || t.flag != 6)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.increase001e.increase001e
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>postfix increment</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public bool flag;
public bool this[int index]
{
set
{
flag = value;
}
get
{
return index > 5;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
dynamic index = 5;
try
{
int x1 = t[1]++;
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "++", "bool");
if (!ret)
return 1;
}
try
{
var x2 = t[index]++;
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "++", "bool");
if (!ret)
return 1;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.increase002.increase002
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>prefix increment</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public int flag;
public int this[int index]
{
set
{
flag = value;
}
get
{
return index;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
int x1 = ++t[1];
if (x1 != 2 || t.flag != 2)
return 1;
dynamic index = 5;
int x2 = ++t[index];
if (x2 != 6 || t.flag != 6)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.increase002e.increase002e
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>postfix increment</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public bool flag;
public bool this[int index]
{
set
{
flag = value;
}
get
{
return index > 5;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
dynamic index = 5;
try
{
int x1 = ++t[1];
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "++", "bool");
if (!ret)
return 1;
}
try
{
var x2 = ++t[index];
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "++", "bool");
if (!ret)
return 1;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.minus001.minus001
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>minus</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public int flag;
public int this[int index]
{
set
{
flag = value;
}
get
{
return index;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
int x1 = -t[1];
if (x1 != -1)
return 1;
dynamic index = 5;
int x2 = -t[index];
if (x2 != -5)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.minus001e.minus001e
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>minus</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public bool flag;
public bool this[int index]
{
set
{
flag = value;
}
get
{
return index > 5;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
dynamic index = 5;
try
{
var x1 = -t[1];
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "-", "bool");
if (!ret)
return 1;
}
try
{
var x2 = -t[index];
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "-", "bool");
if (!ret)
return 1;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.not001.not001
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>prefix increment</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public bool flag;
public bool this[bool index]
{
set
{
flag = value;
}
get
{
return index;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
bool x1 = !t[true];
if (x1 != false)
return 1;
dynamic index = true;
bool x2 = !t[index];
if (x2 != false)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.not001e.not001e
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>prefix increment</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public int flag;
public int this[int index]
{
set
{
flag = value;
}
get
{
return index;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
dynamic index = 2;
try
{
var x1 = !t[1];
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "!", "int");
if (!ret)
return 1;
}
try
{
var x2 = !t[index];
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "!", "int");
if (!ret)
return 1;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.plus001.plus001
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>minus</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public int flag;
public int this[int index]
{
set
{
flag = value;
}
get
{
return index;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
int x1 = +t[1];
if (x1 != 1)
return 1;
dynamic index = 5;
int x2 = +t[index];
if (x2 != 5)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.IndexerOperator.Unary.plus001e.plus001e
{
// <Area>operator on dynamic indexer</Area>
// <Title> unary operator </Title>
// <Description>minus</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public bool flag;
public bool this[int index]
{
set
{
flag = value;
}
get
{
return index > 5;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
dynamic index = 5;
try
{
var x1 = +t[1];
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "+", "bool");
if (!ret)
return 1;
}
try
{
var x2 = +t[index];
return 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadUnaryOp, ex.Message, "+", "bool");
if (!ret)
return 1;
}
return 0;
}
}
// </Code>
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Roslyn.Utilities;
using System.Reflection;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
using TypeInfo = System.Reflection.TypeInfo;
public abstract partial class ObjectFormatter
{
// internal for testing
internal sealed class Formatter
{
private readonly ObjectFormatter _language;
private readonly ObjectFormattingOptions _options;
private HashSet<object> _lazyVisitedObjects;
private HashSet<object> VisitedObjects
{
get
{
if (_lazyVisitedObjects == null)
{
_lazyVisitedObjects = new HashSet<object>(ReferenceEqualityComparer.Instance);
}
return _lazyVisitedObjects;
}
}
public Formatter(ObjectFormatter language, ObjectFormattingOptions options)
{
_options = options ?? ObjectFormattingOptions.Default;
_language = language;
}
private Builder MakeMemberBuilder(int limit)
{
return new Builder(Math.Min(_options.MaxLineLength, limit), _options, insertEllipsis: false);
}
public string FormatObject(object obj)
{
try
{
var builder = new Builder(_options.MaxOutputLength, _options, insertEllipsis: true);
string _;
return FormatObjectRecursive(builder, obj, _options.QuoteStrings, _options.MemberFormat, out _).ToString();
}
catch (InsufficientExecutionStackException)
{
return ScriptingResources.StackOverflowWhileEvaluating;
}
}
private Builder FormatObjectRecursive(Builder result, object obj, bool quoteStrings, MemberDisplayFormat memberFormat, out string name)
{
name = null;
string primitive = _language.FormatPrimitive(obj, quoteStrings, _options.IncludeCodePoints, _options.UseHexadecimalNumbers);
if (primitive != null)
{
result.Append(primitive);
return result;
}
object originalObj = obj;
TypeInfo originalType = originalObj.GetType().GetTypeInfo();
//
// Override KeyValuePair<,>.ToString() to get better dictionary elements formatting:
//
// { { format(key), format(value) }, ... }
// instead of
// { [key.ToString(), value.ToString()], ... }
//
// This is more general than overriding Dictionary<,> debugger proxy attribute since it applies on all
// types that return an array of KeyValuePair in their DebuggerDisplay to display items.
//
if (originalType.IsGenericType && originalType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
if (memberFormat != MemberDisplayFormat.InlineValue)
{
result.Append(_language.FormatTypeName(originalType.AsType(), _options));
result.Append(' ');
}
FormatKeyValuePair(result, originalObj);
return result;
}
if (originalType.IsArray)
{
if (!VisitedObjects.Add(originalObj))
{
result.AppendInfiniteRecursionMarker();
return result;
}
FormatArray(result, (Array)originalObj, inline: memberFormat != MemberDisplayFormat.List);
VisitedObjects.Remove(originalObj);
return result;
}
DebuggerDisplayAttribute debuggerDisplay = GetApplicableDebuggerDisplayAttribute(originalType);
if (debuggerDisplay != null)
{
name = debuggerDisplay.Name;
}
bool suppressMembers = false;
//
// TypeName(count) for ICollection implementers
// or
// TypeName([[DebuggerDisplay.Value]]) // Inline
// [[DebuggerDisplay.Value]] // InlineValue
// or
// [[ToString()]] if ToString overridden
// or
// TypeName
//
ICollection collection;
if ((collection = originalObj as ICollection) != null)
{
FormatCollectionHeader(result, collection);
}
else if (debuggerDisplay != null && !String.IsNullOrEmpty(debuggerDisplay.Value))
{
if (memberFormat != MemberDisplayFormat.InlineValue)
{
result.Append(_language.FormatTypeName(originalType.AsType(), _options));
result.Append('(');
}
FormatWithEmbeddedExpressions(result, debuggerDisplay.Value, originalObj);
if (memberFormat != MemberDisplayFormat.InlineValue)
{
result.Append(')');
}
suppressMembers = true;
}
else if (HasOverriddenToString(originalType))
{
ObjectToString(result, originalObj);
suppressMembers = true;
}
else
{
result.Append(_language.FormatTypeName(originalType.AsType(), _options));
}
if (memberFormat == MemberDisplayFormat.NoMembers)
{
return result;
}
bool includeNonPublic = memberFormat == MemberDisplayFormat.List;
object proxy = GetDebuggerTypeProxy(obj);
if (proxy != null)
{
obj = proxy;
includeNonPublic = false;
suppressMembers = false;
}
if (memberFormat != MemberDisplayFormat.List && suppressMembers)
{
return result;
}
// TODO (tomat): we should not use recursion
RuntimeHelpers.EnsureSufficientExecutionStack();
result.Append(' ');
if (!VisitedObjects.Add(originalObj))
{
result.AppendInfiniteRecursionMarker();
return result;
}
// handle special types only if a proxy isn't defined
if (proxy == null)
{
IDictionary dictionary;
if ((dictionary = obj as IDictionary) != null)
{
FormatDictionary(result, dictionary, inline: memberFormat != MemberDisplayFormat.List);
return result;
}
IEnumerable enumerable;
if ((enumerable = obj as IEnumerable) != null)
{
FormatSequence(result, enumerable, inline: memberFormat != MemberDisplayFormat.List);
return result;
}
}
FormatObjectMembers(result, obj, originalType, includeNonPublic, inline: memberFormat != MemberDisplayFormat.List);
VisitedObjects.Remove(obj);
return result;
}
#region Members
/// <summary>
/// Formats object members to a list.
///
/// Inline == false:
/// <code>
/// { A=true, B=false, C=new int[3] { 1, 2, 3 } }
/// </code>
///
/// Inline == true:
/// <code>
/// {
/// A: true,
/// B: false,
/// C: new int[3] { 1, 2, 3 }
/// }
/// </code>
/// </summary>
private void FormatObjectMembers(Builder result, object obj, TypeInfo originalType, bool includeNonPublic, bool inline)
{
int lengthLimit = result.Remaining;
if (lengthLimit < 0)
{
return;
}
var members = new List<FormattedMember>();
// Limits the number of members added into the result. Some more members may be added than it will fit into the result
// and will be thrown away later but not many more.
FormatObjectMembersRecursive(members, obj, includeNonPublic, ref lengthLimit);
bool useCollectionFormat = UseCollectionFormat(members, originalType);
result.AppendGroupOpening();
for (int i = 0; i < members.Count; i++)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
if (useCollectionFormat)
{
members[i].AppendAsCollectionEntry(result);
}
else
{
members[i].Append(result, inline ? "=" : ": ");
}
if (result.LimitReached)
{
break;
}
}
result.AppendGroupClosing(inline);
}
private static bool UseCollectionFormat(IEnumerable<FormattedMember> members, TypeInfo originalType)
{
return typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(originalType) && members.All(member => member.Index >= 0);
}
private struct FormattedMember
{
// Non-negative if the member is an inlined element of an array (DebuggerBrowsableState.RootHidden applied on a member of array type).
public readonly int Index;
// Formatted name of the member or null if it doesn't have a name (Index is >=0 then).
public readonly string Name;
// Formatted value of the member.
public readonly string Value;
public FormattedMember(int index, string name, string value)
{
Name = name;
Index = index;
Value = value;
}
public int MinimalLength
{
get { return (Name != null ? Name.Length : "[0]".Length) + Value.Length; }
}
public string GetDisplayName()
{
return Name ?? "[" + Index.ToString() + "]";
}
public bool HasKeyName()
{
return Index >= 0 && Name != null && Name.Length >= 2 && Name[0] == '[' && Name[Name.Length - 1] == ']';
}
public bool AppendAsCollectionEntry(Builder result)
{
// Some BCL collections use [{key.ToString()}]: {value.ToString()} pattern to display collection entries.
// We want them to be printed initializer-style, i.e. { <key>, <value> }
if (HasKeyName())
{
result.AppendGroupOpening();
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
result.Append(Name, 1, Name.Length - 2);
result.AppendCollectionItemSeparator(isFirst: false, inline: true);
result.Append(Value);
result.AppendGroupClosing(inline: true);
}
else
{
result.Append(Value);
}
return true;
}
public bool Append(Builder result, string separator)
{
result.Append(GetDisplayName());
result.Append(separator);
result.Append(Value);
return true;
}
}
/// <summary>
/// Enumerates sorted object members to display.
/// </summary>
private void FormatObjectMembersRecursive(List<FormattedMember> result, object obj, bool includeNonPublic, ref int lengthLimit)
{
Debug.Assert(obj != null);
var members = new List<MemberInfo>();
var type = obj.GetType().GetTypeInfo();
while (type != null)
{
members.AddRange(type.DeclaredFields.Where(f => !f.IsStatic));
members.AddRange(type.DeclaredProperties.Where(f => f.GetMethod != null && !f.GetMethod.IsStatic));
type = type.BaseType?.GetTypeInfo();
}
members.Sort((x, y) =>
{
// Need case-sensitive comparison here so that the order of members is
// always well-defined (members can differ by case only). And we don't want to
// depend on that order.
int comparisonResult = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name);
if (comparisonResult == 0)
{
comparisonResult = StringComparer.Ordinal.Compare(x.Name, y.Name);
}
return comparisonResult;
});
foreach (var member in members)
{
if (_language.IsHiddenMember(member))
{
continue;
}
bool rootHidden = false, ignoreVisibility = false;
var browsable = (DebuggerBrowsableAttribute)member.GetCustomAttributes(typeof(DebuggerBrowsableAttribute), false).FirstOrDefault();
if (browsable != null)
{
if (browsable.State == DebuggerBrowsableState.Never)
{
continue;
}
ignoreVisibility = true;
rootHidden = browsable.State == DebuggerBrowsableState.RootHidden;
}
FieldInfo field = member as FieldInfo;
if (field != null)
{
if (!(includeNonPublic || ignoreVisibility || field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly))
{
continue;
}
}
else
{
PropertyInfo property = (PropertyInfo)member;
var getter = property.GetMethod;
if (getter == null)
{
continue;
}
var setter = property.SetMethod;
// If not ignoring visibility include properties that has a visible getter or setter.
if (!(includeNonPublic || ignoreVisibility ||
getter.IsPublic || getter.IsFamily || getter.IsFamilyOrAssembly ||
(setter != null && (setter.IsPublic || setter.IsFamily || setter.IsFamilyOrAssembly))))
{
continue;
}
if (getter.GetParameters().Length > 0)
{
continue;
}
}
var debuggerDisplay = GetApplicableDebuggerDisplayAttribute(member);
if (debuggerDisplay != null)
{
string k = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Name, obj) ?? _language.FormatMemberName(member);
string v = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Value, obj) ?? string.Empty; // TODO: ?
if (!AddMember(result, new FormattedMember(-1, k, v), ref lengthLimit))
{
return;
}
continue;
}
Exception exception;
object value = GetMemberValue(member, obj, out exception);
if (exception != null)
{
var memberValueBuilder = MakeMemberBuilder(lengthLimit);
FormatException(memberValueBuilder, exception);
if (!AddMember(result, new FormattedMember(-1, _language.FormatMemberName(member), memberValueBuilder.ToString()), ref lengthLimit))
{
return;
}
continue;
}
if (rootHidden)
{
if (value != null && !VisitedObjects.Contains(value))
{
Array array;
if ((array = value as Array) != null) // TODO (tomat): n-dim arrays
{
int i = 0;
foreach (object item in array)
{
string name;
Builder valueBuilder = MakeMemberBuilder(lengthLimit);
FormatObjectRecursive(valueBuilder, item, _options.QuoteStrings, MemberDisplayFormat.InlineValue, out name);
if (!string.IsNullOrEmpty(name))
{
name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, item).ToString();
}
if (!AddMember(result, new FormattedMember(i, name, valueBuilder.ToString()), ref lengthLimit))
{
return;
}
i++;
}
}
else if (_language.FormatPrimitive(value, _options.QuoteStrings, _options.IncludeCodePoints, _options.UseHexadecimalNumbers) == null && VisitedObjects.Add(value))
{
FormatObjectMembersRecursive(result, value, includeNonPublic, ref lengthLimit);
VisitedObjects.Remove(value);
}
}
}
else
{
string name;
Builder valueBuilder = MakeMemberBuilder(lengthLimit);
FormatObjectRecursive(valueBuilder, value, _options.QuoteStrings, MemberDisplayFormat.InlineValue, out name);
if (String.IsNullOrEmpty(name))
{
name = _language.FormatMemberName(member);
}
else
{
name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, value).ToString();
}
if (!AddMember(result, new FormattedMember(-1, name, valueBuilder.ToString()), ref lengthLimit))
{
return;
}
}
}
}
private bool AddMember(List<FormattedMember> members, FormattedMember member, ref int remainingLength)
{
// Add this item even if we exceed the limit - its prefix might be appended to the result.
members.Add(member);
// We don't need to calculate an exact length, just a lower bound on the size.
// We can add more members to the result than it will eventually fit, we shouldn't add less.
// Add 2 more, even if only one or half of it fit, so that the separator is included in edge cases.
if (remainingLength == int.MinValue)
{
return false;
}
remainingLength -= member.MinimalLength;
if (remainingLength <= 0)
{
remainingLength = int.MinValue;
}
return true;
}
private void FormatException(Builder result, Exception exception)
{
result.Append("!<");
result.Append(_language.FormatTypeName(exception.GetType(), _options));
result.Append('>');
}
#endregion
#region Collections
private void FormatKeyValuePair(Builder result, object obj)
{
TypeInfo type = obj.GetType().GetTypeInfo();
object key = type.GetDeclaredProperty("Key").GetValue(obj, SpecializedCollections.EmptyObjects);
object value = type.GetDeclaredProperty("Value").GetValue(obj, SpecializedCollections.EmptyObjects);
string _;
result.AppendGroupOpening();
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
FormatObjectRecursive(result, key, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out _);
result.AppendCollectionItemSeparator(isFirst: false, inline: true);
FormatObjectRecursive(result, value, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out _);
result.AppendGroupClosing(inline: true);
}
private void FormatCollectionHeader(Builder result, ICollection collection)
{
Array array = collection as Array;
if (array != null)
{
result.Append(_language.FormatArrayTypeName(array.GetType(), array, _options));
return;
}
result.Append(_language.FormatTypeName(collection.GetType(), _options));
try
{
result.Append('(');
result.Append(collection.Count.ToString());
result.Append(')');
}
catch (Exception)
{
// skip
}
}
private void FormatArray(Builder result, Array array, bool inline)
{
FormatCollectionHeader(result, array);
if (array.Rank > 1)
{
FormatMultidimensionalArray(result, array, inline);
}
else
{
result.Append(' ');
FormatSequence(result, (IEnumerable)array, inline);
}
}
private void FormatDictionary(Builder result, IDictionary dict, bool inline)
{
result.AppendGroupOpening();
int i = 0;
try
{
IDictionaryEnumerator enumerator = dict.GetEnumerator();
IDisposable disposable = enumerator as IDisposable;
try
{
while (enumerator.MoveNext())
{
var entry = enumerator.Entry;
string _;
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
result.AppendGroupOpening();
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
FormatObjectRecursive(result, entry.Key, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out _);
result.AppendCollectionItemSeparator(isFirst: false, inline: true);
FormatObjectRecursive(result, entry.Value, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out _);
result.AppendGroupClosing(inline: true);
i++;
}
}
finally
{
if (disposable != null)
{
disposable.Dispose();
}
}
}
catch (Exception e)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatException(result, e);
result.Append(' ');
result.Append(_options.Ellipsis);
}
result.AppendGroupClosing(inline);
}
private void FormatSequence(Builder result, IEnumerable sequence, bool inline)
{
result.AppendGroupOpening();
int i = 0;
try
{
foreach (var item in sequence)
{
string name;
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatObjectRecursive(result, item, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out name);
i++;
}
}
catch (Exception e)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatException(result, e);
result.Append(" ...");
}
result.AppendGroupClosing(inline);
}
private void FormatMultidimensionalArray(Builder result, Array array, bool inline)
{
Debug.Assert(array.Rank > 1);
if (array.Length == 0)
{
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
result.AppendGroupOpening();
result.AppendGroupClosing(inline: true);
return;
}
int[] indices = new int[array.Rank];
for (int i = array.Rank - 1; i >= 0; i--)
{
indices[i] = array.GetLowerBound(i);
}
int nesting = 0;
int flatIndex = 0;
while (true)
{
// increment indices (lower index overflows to higher):
int i = indices.Length - 1;
while (indices[i] > array.GetUpperBound(i))
{
indices[i] = array.GetLowerBound(i);
result.AppendGroupClosing(inline: inline || nesting != 1);
nesting--;
i--;
if (i < 0)
{
return;
}
indices[i]++;
}
result.AppendCollectionItemSeparator(isFirst: flatIndex == 0, inline: inline || nesting != 1);
i = indices.Length - 1;
while (i >= 0 && indices[i] == array.GetLowerBound(i))
{
result.AppendGroupOpening();
nesting++;
// array isn't empty, so there is always an element following this separator
result.AppendCollectionItemSeparator(isFirst: true, inline: inline || nesting != 1);
i--;
}
string name;
FormatObjectRecursive(result, array.GetValue(indices), quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out name);
indices[indices.Length - 1]++;
flatIndex++;
}
}
#endregion
#region Scalars
private void ObjectToString(Builder result, object obj)
{
try
{
string str = obj.ToString();
result.Append('[');
result.Append(str);
result.Append(']');
}
catch (Exception e)
{
FormatException(result, e);
}
}
#endregion
#region DebuggerDisplay Embedded Expressions
/// <summary>
/// Evaluate a format string with possible member references enclosed in braces.
/// E.g. "foo = {GetFooString(),nq}, bar = {Bar}".
/// </summary>
/// <remarks>
/// Although in theory any expression is allowed to be embedded in the string such behavior is in practice fundamentally broken.
/// The attribute doesn't specify what language (VB, C#, F#, etc.) to use to parse these expressions. Even if it did all languages
/// would need to be able to evaluate each other language's expressions, which is not viable and the Expression Evaluator doesn't
/// work that way today. Instead it evaluates the embedded expressions in the language of the current method frame. When consuming
/// VB objects from C#, for example, the evaluation might fail due to language mismatch (evaluating VB expression using C# parser).
///
/// Therefore we limit the expressions to a simple language independent syntax: {clr-member-name} '(' ')' ',nq',
/// where parentheses and ,nq suffix (no-quotes) are optional and the name is an arbitrary CLR field, property, or method name.
/// We then resolve the member by name using case-sensitive lookup first with fallback to case insensitive and evaluate it.
/// If parentheses are present we only look for methods.
/// Only parameter less members are considered.
/// </remarks>
private string FormatWithEmbeddedExpressions(int lengthLimit, string format, object obj)
{
if (String.IsNullOrEmpty(format))
{
return null;
}
return FormatWithEmbeddedExpressions(new Builder(lengthLimit, _options, insertEllipsis: false), format, obj).ToString();
}
private Builder FormatWithEmbeddedExpressions(Builder result, string format, object obj)
{
int i = 0;
while (i < format.Length)
{
char c = format[i++];
if (c == '{')
{
if (i >= 2 && format[i - 2] == '\\')
{
result.Append('{');
}
else
{
int expressionEnd = format.IndexOf('}', i);
bool noQuotes, callableOnly;
string memberName;
if (expressionEnd == -1 || (memberName = ParseSimpleMemberName(format, i, expressionEnd, out noQuotes, out callableOnly)) == null)
{
// the expression isn't properly formatted
result.Append(format, i - 1, format.Length - i + 1);
break;
}
MemberInfo member = ResolveMember(obj, memberName, callableOnly);
if (member == null)
{
result.AppendFormat(callableOnly ? "!<Method '{0}' not found>" : "!<Member '{0}' not found>", memberName);
}
else
{
Exception exception;
object value = GetMemberValue(member, obj, out exception);
if (exception != null)
{
FormatException(result, exception);
}
else
{
string name;
FormatObjectRecursive(result, value, !noQuotes, MemberDisplayFormat.NoMembers, out name);
}
}
i = expressionEnd + 1;
}
}
else
{
result.Append(c);
}
}
return result;
}
// Parses
// <clr-member-name>
// <clr-member-name> ',' 'nq'
// <clr-member-name> '(' ')'
// <clr-member-name> '(' ')' ',' 'nq'
//
// Internal for testing purposes.
internal static string ParseSimpleMemberName(string str, int start, int end, out bool noQuotes, out bool isCallable)
{
Debug.Assert(str != null && start >= 0 && end >= start);
isCallable = false;
noQuotes = false;
// no-quotes suffix:
if (end - 3 >= start && str[end - 2] == 'n' && str[end - 1] == 'q')
{
int j = end - 3;
while (j >= start && Char.IsWhiteSpace(str[j]))
{
j--;
}
if (j >= start && str[j] == ',')
{
noQuotes = true;
end = j;
}
}
int i = end - 1;
EatTrailingWhiteSpace(str, start, ref i);
if (i > start && str[i] == ')')
{
int closingParen = i;
i--;
EatTrailingWhiteSpace(str, start, ref i);
if (str[i] != '(')
{
i = closingParen;
}
else
{
i--;
EatTrailingWhiteSpace(str, start, ref i);
isCallable = true;
}
}
EatLeadingWhiteSpace(str, ref start, i);
return str.Substring(start, i - start + 1);
}
private static void EatTrailingWhiteSpace(string str, int start, ref int i)
{
while (i >= start && Char.IsWhiteSpace(str[i]))
{
i--;
}
}
private static void EatLeadingWhiteSpace(string str, ref int i, int end)
{
while (i < end && Char.IsWhiteSpace(str[i]))
{
i++;
}
}
#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 Microsoft.Win32.SafeHandles;
using Xunit;
namespace System.IO.Pipes.Tests
{
/// <summary>
/// Tests for the constructors for NamedPipeServerStream
/// </summary>
public class NamedPipeTest_CreateServer : NamedPipeTestBase
{
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
public static void NullPipeName_Throws_ArgumentNullException(PipeDirection direction)
{
Assert.Throws<ArgumentNullException>("pipeName", () => new NamedPipeServerStream(null));
Assert.Throws<ArgumentNullException>("pipeName", () => new NamedPipeServerStream(null, direction));
Assert.Throws<ArgumentNullException>("pipeName", () => new NamedPipeServerStream(null, direction, 2));
Assert.Throws<ArgumentNullException>("pipeName", () => new NamedPipeServerStream(null, direction, 3, PipeTransmissionMode.Byte));
Assert.Throws<ArgumentNullException>("pipeName", () => new NamedPipeServerStream(null, direction, 3, PipeTransmissionMode.Byte, PipeOptions.None));
Assert.Throws<ArgumentNullException>("pipeName", () => new NamedPipeServerStream(null, direction, 3, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0));
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
public static void ZeroLengthPipeName_Throws_ArgumentException(PipeDirection direction)
{
Assert.Throws<ArgumentException>(() => new NamedPipeServerStream(""));
Assert.Throws<ArgumentException>(() => new NamedPipeServerStream("", direction));
Assert.Throws<ArgumentException>(() => new NamedPipeServerStream("", direction, 2));
Assert.Throws<ArgumentException>(() => new NamedPipeServerStream("", direction, 3, PipeTransmissionMode.Byte));
Assert.Throws<ArgumentException>(() => new NamedPipeServerStream("", direction, 3, PipeTransmissionMode.Byte, PipeOptions.None));
Assert.Throws<ArgumentException>(() => new NamedPipeServerStream("", direction, 3, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0));
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
[PlatformSpecific(PlatformID.Windows)]
public static void ReservedPipeName_Throws_ArgumentOutOfRangeException(PipeDirection direction)
{
const string reservedName = "anonymous";
Assert.Throws<ArgumentOutOfRangeException>("pipeName", () => new NamedPipeServerStream(reservedName));
Assert.Throws<ArgumentOutOfRangeException>("pipeName", () => new NamedPipeServerStream(reservedName, direction));
Assert.Throws<ArgumentOutOfRangeException>("pipeName", () => new NamedPipeServerStream(reservedName, direction, 1));
Assert.Throws<ArgumentOutOfRangeException>("pipeName", () => new NamedPipeServerStream(reservedName, direction, 1, PipeTransmissionMode.Byte));
Assert.Throws<ArgumentOutOfRangeException>("pipeName", () => new NamedPipeServerStream(reservedName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.None));
Assert.Throws<ArgumentOutOfRangeException>("pipeName", () => new NamedPipeServerStream(reservedName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0));}
[Fact]
public static void Create_PipeName()
{
new NamedPipeServerStream(GetUniquePipeName()).Dispose();
}
[Fact]
public static void Create_PipeName_Direction_MaxInstances()
{
new NamedPipeServerStream(GetUniquePipeName(), PipeDirection.Out, 1).Dispose();
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public static void CreateWithNegativeOneServerInstances_DefaultsToMaxServerInstances()
{
// When passed -1 as the maxnumberofserverisntances, the NamedPipeServerStream.Windows class
// will translate that to the platform specific maximum number (255)
using (var server = new NamedPipeServerStream(GetUniquePipeName(), PipeDirection.InOut, -1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var server2 = new NamedPipeServerStream(PipeDirection.InOut, false, true, server.SafePipeHandle))
using (var server3 = new NamedPipeServerStream(PipeDirection.InOut, false, true, server.SafePipeHandle))
{
}
}
[Fact]
public static void InvalidPipeDirection_Throws_ArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("direction", () => new NamedPipeServerStream("temp1", (PipeDirection)123));
Assert.Throws<ArgumentOutOfRangeException>("direction", () => new NamedPipeServerStream("temp1", (PipeDirection)123, 1));
Assert.Throws<ArgumentOutOfRangeException>("direction", () => new NamedPipeServerStream("temp1", (PipeDirection)123, 1, PipeTransmissionMode.Byte));
Assert.Throws<ArgumentOutOfRangeException>("direction", () => new NamedPipeServerStream("temp1", (PipeDirection)123, 1, PipeTransmissionMode.Byte, PipeOptions.None));
Assert.Throws<ArgumentOutOfRangeException>("direction", () => new NamedPipeServerStream("tempx", (PipeDirection)123, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0));
}
[Theory]
[InlineData(0)]
[InlineData(-2)]
public static void InvalidServerInstances_Throws_ArgumentOutOfRangeException(int numberOfServerInstances)
{
Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", PipeDirection.In, numberOfServerInstances));
Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", PipeDirection.In, numberOfServerInstances, PipeTransmissionMode.Byte));
Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", PipeDirection.In, numberOfServerInstances, PipeTransmissionMode.Byte, PipeOptions.None));
Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", PipeDirection.In, numberOfServerInstances, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0));
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
[PlatformSpecific(PlatformID.AnyUnix)]
public static void Unix_ServerInstancesOver254_Allowed(PipeDirection direction)
{
// MaxNumberOfServerInstances has functionality on Unix and as such is not upper bound.
new NamedPipeServerStream(GetUniquePipeName(), direction, 255).Dispose();
new NamedPipeServerStream(GetUniquePipeName(), direction, 255, PipeTransmissionMode.Byte).Dispose();
new NamedPipeServerStream(GetUniquePipeName(), direction, 255, PipeTransmissionMode.Byte, PipeOptions.None).Dispose();
new NamedPipeServerStream(GetUniquePipeName(), direction, 255, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0).Dispose();
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
[PlatformSpecific(PlatformID.Windows)]
public static void Windows_ServerInstancesOver254_Throws_ArgumentOutOfRangeException(PipeDirection direction)
{
Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", direction, 255));
Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", direction, 255, PipeTransmissionMode.Byte));
Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", direction, 255, PipeTransmissionMode.Byte, PipeOptions.None));
Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", direction, 255, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0));
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
public static void InvalidTransmissionMode_Throws_ArgumentOutOfRangeException(PipeDirection direction)
{
Assert.Throws<ArgumentOutOfRangeException>("transmissionMode", () => new NamedPipeServerStream("temp1", direction, 1, (PipeTransmissionMode)123));
Assert.Throws<ArgumentOutOfRangeException>("transmissionMode", () => new NamedPipeServerStream("temp1", direction, 1, (PipeTransmissionMode)123, PipeOptions.None));
Assert.Throws<ArgumentOutOfRangeException>("transmissionMode", () => new NamedPipeServerStream("tempx", direction, 1, (PipeTransmissionMode)123, PipeOptions.None, 0, 0));
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
public static void InvalidPipeOptions_Throws_ArgumentOutOfRangeException(PipeDirection direction)
{
Assert.Throws<ArgumentOutOfRangeException>("options", () => new NamedPipeServerStream("temp1", direction, 1, PipeTransmissionMode.Byte, (PipeOptions)255));
Assert.Throws<ArgumentOutOfRangeException>("options", () => new NamedPipeServerStream("tempx", direction, 1, PipeTransmissionMode.Byte, (PipeOptions)255, 0, 0));
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
public static void InvalidBufferSize_Throws_ArgumentOutOfRangeException(PipeDirection direction)
{
Assert.Throws<ArgumentOutOfRangeException>("inBufferSize", () => new NamedPipeServerStream("temp2", direction, 1, PipeTransmissionMode.Byte, PipeOptions.None, -1, 0));
Assert.Throws<ArgumentOutOfRangeException>("outBufferSize", () => new NamedPipeServerStream("temp2", direction, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, -123));
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
public static void NullPipeHandle_Throws_ArgumentNullException(PipeDirection direction)
{
Assert.Throws<ArgumentNullException>("safePipeHandle", () => new NamedPipeServerStream(direction, false, true, null));
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
public static void InvalidPipeHandle_Throws_ArgumentException(PipeDirection direction)
{
SafePipeHandle pipeHandle = new SafePipeHandle(new IntPtr(-1), true);
Assert.Throws<ArgumentException>("safePipeHandle", () => new NamedPipeServerStream(direction, false, true, pipeHandle));
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
public static void BadHandleKind_Throws_IOException(PipeDirection direction)
{
using (FileStream fs = new FileStream(Path.Combine(Path.GetTempPath(), "_BadHandleKind_Throws_IOException_" + Path.GetRandomFileName()), FileMode.Create, FileAccess.Write, FileShare.None, 8, FileOptions.DeleteOnClose))
{
SafeFileHandle safeHandle = fs.SafeFileHandle;
bool gotRef = false;
try
{
safeHandle.DangerousAddRef(ref gotRef);
IntPtr handle = safeHandle.DangerousGetHandle();
SafePipeHandle fakePipeHandle = new SafePipeHandle(handle, ownsHandle: false);
Assert.Throws<IOException>(() => new NamedPipeServerStream(direction, false, true, fakePipeHandle));
}
finally
{
if (gotRef)
safeHandle.DangerousRelease();
}
}
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
[PlatformSpecific(PlatformID.Windows)]
public static void Windows_CreateFromDisposedServerHandle_Throws_ObjectDisposedException(PipeDirection direction)
{
// The pipe is closed when we try to make a new Stream with it
var pipe = new NamedPipeServerStream(GetUniquePipeName(), direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
SafePipeHandle handle = pipe.SafePipeHandle;
pipe.Dispose();
Assert.Throws<ObjectDisposedException>(() => new NamedPipeServerStream(direction, true, true, pipe.SafePipeHandle).Dispose());
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public static void Unix_GetHandleOfNewServerStream_Throws_InvalidOperationException()
{
var pipe = new NamedPipeServerStream(GetUniquePipeName(), PipeDirection.Out, 1, PipeTransmissionMode.Byte);
Assert.Throws<InvalidOperationException>(() => pipe.SafePipeHandle);
}
[Theory]
[InlineData(PipeDirection.In)]
[InlineData(PipeDirection.InOut)]
[InlineData(PipeDirection.Out)]
[PlatformSpecific(PlatformID.Windows)]
public static void Windows_CreateFromAlreadyBoundHandle_Throws_ArgumentException(PipeDirection direction)
{
// The pipe is already bound
var pipe = new NamedPipeServerStream(GetUniquePipeName(), direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
Assert.Throws<ArgumentException>(() => new NamedPipeServerStream(direction, true, true, pipe.SafePipeHandle));
pipe.Dispose();
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // NumberOfServerInstances > 1 isn't supported and has undefined behavior on Unix
public static void ServerCountOverMaxServerInstances_Throws_IOException()
{
string uniqueServerName = GetUniquePipeName();
using (NamedPipeServerStream server = new NamedPipeServerStream(uniqueServerName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
{
Assert.Throws<IOException>(() => new NamedPipeServerStream(uniqueServerName));
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // NumberOfServerInstances > 1 isn't supported and has undefined behavior on Unix
public static void Windows_ServerCloneWithDifferentDirection_Throws_UnauthorizedAccessException()
{
string uniqueServerName = GetUniquePipeName();
using (NamedPipeServerStream server = new NamedPipeServerStream(uniqueServerName, PipeDirection.In, 2, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
{
Assert.Throws<UnauthorizedAccessException>(() => new NamedPipeServerStream(uniqueServerName, PipeDirection.Out));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;
namespace LibGit2Sharp.Tests
{
public class FilterSubstitutionCipherFixture : BaseFixture
{
[Fact]
public void SmugdeIsNotCalledForFileWhichDoesNotMatchAnAttributeEntry()
{
const string decodedInput = "This is a substitution cipher";
const string encodedInput = "Guvf vf n fhofgvghgvba pvcure";
var attributes = new List<FilterAttributeEntry> { new FilterAttributeEntry("rot13") };
var filter = new SubstitutionCipherFilter("cipher-filter", attributes);
var filterRegistration = GlobalSettings.RegisterFilter(filter);
string repoPath = InitNewRepository();
string fileName = Guid.NewGuid() + ".rot13";
string configPath = CreateConfigurationWithDummyUser(Constants.Signature);
var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, repositoryOptions))
{
CreateAttributesFile(repo, "*.rot13 filter=rot13");
var blob = CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput);
var textDetected = blob.GetContentText();
Assert.Equal(encodedInput, textDetected);
Assert.Equal(1, filter.CleanCalledCount);
Assert.Equal(0, filter.SmudgeCalledCount);
var branch = repo.CreateBranch("delete-files");
repo.Checkout(branch.FriendlyName);
DeleteFile(repo, fileName);
repo.Checkout("master");
var fileContents = ReadTextFromFile(repo, fileName);
Assert.Equal(1, filter.SmudgeCalledCount);
Assert.Equal(decodedInput, fileContents);
}
GlobalSettings.DeregisterFilter(filterRegistration);
}
[Fact]
public void CorrectlyEncodesAndDecodesInput()
{
const string decodedInput = "This is a substitution cipher";
const string encodedInput = "Guvf vf n fhofgvghgvba pvcure";
var attributes = new List<FilterAttributeEntry> { new FilterAttributeEntry("rot13") };
var filter = new SubstitutionCipherFilter("cipher-filter", attributes);
var filterRegistration = GlobalSettings.RegisterFilter(filter);
string repoPath = InitNewRepository();
string fileName = Guid.NewGuid() + ".rot13";
string configPath = CreateConfigurationWithDummyUser(Constants.Signature);
var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, repositoryOptions))
{
CreateAttributesFile(repo, "*.rot13 filter=rot13");
var blob = CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput);
var textDetected = blob.GetContentText();
Assert.Equal(encodedInput, textDetected);
Assert.Equal(1, filter.CleanCalledCount);
Assert.Equal(0, filter.SmudgeCalledCount);
var branch = repo.CreateBranch("delete-files");
repo.Checkout(branch.FriendlyName);
DeleteFile(repo, fileName);
repo.Checkout("master");
var fileContents = ReadTextFromFile(repo, fileName);
Assert.Equal(1, filter.SmudgeCalledCount);
Assert.Equal(decodedInput, fileContents);
}
GlobalSettings.DeregisterFilter(filterRegistration);
}
[Theory]
[InlineData("*.txt", ".bat", 0, 0)]
[InlineData("*.txt", ".txt", 1, 0)]
public void WhenStagedFileDoesNotMatchPathSpecFileIsNotFiltered(string pathSpec, string fileExtension, int cleanCount, int smudgeCount)
{
const string filterName = "rot13";
const string decodedInput = "This is a substitution cipher";
string attributeFileEntry = string.Format("{0} filter={1}", pathSpec, filterName);
var filterForAttributes = new List<FilterAttributeEntry> { new FilterAttributeEntry(filterName) };
var filter = new SubstitutionCipherFilter("cipher-filter", filterForAttributes);
var filterRegistration = GlobalSettings.RegisterFilter(filter);
string repoPath = InitNewRepository();
string fileName = Guid.NewGuid() + fileExtension;
string configPath = CreateConfigurationWithDummyUser(Constants.Signature);
var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, repositoryOptions))
{
CreateAttributesFile(repo, attributeFileEntry);
CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput);
Assert.Equal(cleanCount, filter.CleanCalledCount);
Assert.Equal(smudgeCount, filter.SmudgeCalledCount);
}
GlobalSettings.DeregisterFilter(filterRegistration);
}
[Theory]
[InlineData("rot13", "*.txt filter=rot13", 1)]
[InlineData("rot13", "*.txt filter=fake", 0)]
[InlineData("rot13", "*.bat filter=rot13", 0)]
[InlineData("rot13", "*.txt filter=fake", 0)]
[InlineData("fake", "*.txt filter=fake", 1)]
[InlineData("fake", "*.bat filter=fake", 0)]
[InlineData("rot13", "*.txt filter=rot13 -crlf", 1)]
public void CleanIsCalledIfAttributeEntryMatches(string filterAttribute, string attributeEntry, int cleanCount)
{
const string decodedInput = "This is a substitution cipher";
var filterForAttributes = new List<FilterAttributeEntry> { new FilterAttributeEntry(filterAttribute) };
var filter = new SubstitutionCipherFilter("cipher-filter", filterForAttributes);
var filterRegistration = GlobalSettings.RegisterFilter(filter);
string repoPath = InitNewRepository();
string fileName = Guid.NewGuid() + ".txt";
string configPath = CreateConfigurationWithDummyUser(Constants.Signature);
var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, repositoryOptions))
{
CreateAttributesFile(repo, attributeEntry);
CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput);
Assert.Equal(cleanCount, filter.CleanCalledCount);
}
GlobalSettings.DeregisterFilter(filterRegistration);
}
[Theory]
[InlineData("rot13", "*.txt filter=rot13", 1)]
[InlineData("rot13", "*.txt filter=fake", 0)]
[InlineData("rot13", "*.txt filter=rot13 -crlf", 1)]
public void SmudgeIsCalledIfAttributeEntryMatches(string filterAttribute, string attributeEntry, int smudgeCount)
{
const string decodedInput = "This is a substitution cipher";
var filterForAttributes = new List<FilterAttributeEntry> { new FilterAttributeEntry(filterAttribute) };
var filter = new SubstitutionCipherFilter("cipher-filter", filterForAttributes);
var filterRegistration = GlobalSettings.RegisterFilter(filter);
string repoPath = InitNewRepository();
string fileName = Guid.NewGuid() + ".txt";
string configPath = CreateConfigurationWithDummyUser(Constants.Signature);
var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, repositoryOptions))
{
CreateAttributesFile(repo, attributeEntry);
CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput);
var branch = repo.CreateBranch("delete-files");
repo.Checkout(branch.FriendlyName);
DeleteFile(repo, fileName);
repo.Checkout("master");
Assert.Equal(smudgeCount, filter.SmudgeCalledCount);
}
GlobalSettings.DeregisterFilter(filterRegistration);
}
private static string ReadTextFromFile(Repository repo, string fileName)
{
return File.ReadAllText(Path.Combine(repo.Info.WorkingDirectory, fileName));
}
private static void DeleteFile(Repository repo, string fileName)
{
File.Delete(Path.Combine(repo.Info.WorkingDirectory, fileName));
repo.Stage(fileName);
repo.Commit("remove file");
}
private static Blob CommitOnBranchAndReturnDatabaseBlob(Repository repo, string fileName, string input)
{
Touch(repo.Info.WorkingDirectory, fileName, input);
repo.Stage(fileName);
var commit = repo.Commit("new file");
var blob = (Blob)commit.Tree[fileName].Target;
return blob;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WebAPIConnectWithChrist.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using Caliburn.Micro;
using csCommon.csMapCustomControls.CircularMenu;
using DataServer;
using csAppraisalPlugin.Classes;
using csAppraisalPlugin.ViewModels;
using csImb;
using csShared;
using csShared.Interfaces;
using csShared.TabItems;
using csShared.Utils;
using PowerPointGenerator;
namespace csAppraisalPlugin {
public class Rfi : BaseContent {
private string title;
public string Title {
get { return title; }
set {
title = value;
NotifyOfPropertyChange(() => Title);
}
}
}
public class RfiService : PoiService {
private ContentList rfis;
public ContentList Rfis {
get { return rfis; }
set {
rfis = value;
NotifyOfPropertyChange(() => Rfis);
}
}
public void InitRfisService() {
InitPoiService();
Rfis = new ContentList {Service = this};
AllContent.Add(Rfis);
}
}
[Export(typeof (IPlugin))]
public class AppraisalPlugin : PropertyChangedBase, IPlugin {
private bool active;
private string file;
private FunctionList functions = new FunctionList();
private bool hideFromSettings;
private bool isRunning;
private IPluginScreen screen;
private string screenshotFolder;
private BindableCollection<Appraisal> selectedAppraisals = new BindableCollection<Appraisal>();
private ISettingsScreen settings;
public string BFile {
get { return file; }
set {
file = value;
NotifyOfPropertyChange(() => BFile);
}
}
public string ScreenshotFolder {
get {
if (!string.IsNullOrEmpty(screenshotFolder)) return screenshotFolder;
var c = AppState.Config.Get("Appraisal.Screenshot.Folder", @"%TEMP%\cs\Appraisals\");
if (c[c.Length - 1] != '\\') c += @"\";
screenshotFolder = Environment.ExpandEnvironmentVariables(c);
if (!Directory.Exists(screenshotFolder)) Directory.CreateDirectory(screenshotFolder);
return screenshotFolder;
}
}
public BindableCollection<Appraisal> SelectedAppraisals {
get { return selectedAppraisals; }
set {
selectedAppraisals = value;
NotifyOfPropertyChange(() => SelectedAppraisals);
}
}
public FloatingElement Element { get; set; }
#region IPlugin Members
private AppraisalList appraisals;
private Appraisal selectedAppraisal = new Appraisal();
public FunctionList Functions {
get { return functions; }
set {
functions = value;
NotifyOfPropertyChange(() => Functions);
}
}
public Appraisal SelectedAppraisal {
get { return selectedAppraisal; }
set {
selectedAppraisal = value;
NotifyOfPropertyChange(() => SelectedAppraisal);
}
}
public AppraisalList Appraisals {
get
{
return appraisals;
}
set
{
appraisals = value;
}
}
public bool Active {
get { return active; }
set {
if (active == value) return;
active = value;
NotifyOfPropertyChange(() => Active);
//OnActiveChanged();
UpdateTabs();
}
}
public AppraisalTabViewModel TabViewModel { get; set; }
public FunctionsTabViewModel FunctionsViewModel { get; set; }
public StartPanelTabItem AppraisalTabItem { get; set; }
public StartPanelTabItem FunctionsTabItem { get; set; }
public string SavedFunctionsFileName {
get { return Path.Combine(ScreenshotFolder, "Functions.xml"); }
}
public string SavedAppraisalsFileName {
get { return Path.Combine(ScreenshotFolder, "Appraisals.xml"); }
}
public IPluginScreen Screen {
get { return screen; }
set {
screen = value;
NotifyOfPropertyChange(() => Screen);
}
}
public bool CanStop {
get { return true; }
}
public ISettingsScreen Settings {
get { return settings; }
set {
settings = value;
NotifyOfPropertyChange(() => Settings);
}
}
public bool HideFromSettings {
get { return hideFromSettings; }
set {
hideFromSettings = value;
NotifyOfPropertyChange(() => HideFromSettings);
}
}
public int Priority {
get { return 3; }
}
public string Icon {
get { return @"icons\ThumbsUp.png"; }
}
public string Name {
get { return "AppraisalPlugin"; }
}
public bool IsRunning {
get { return isRunning; }
set {
isRunning = value;
NotifyOfPropertyChange(() => IsRunning);
}
}
public AppStateSettings AppState { get; set; }
public void Init() {
//appStateSettings = AppStateSettings.Instance;
//isTimelineVisible = AppState.TimelineVisible;
//UpdateTabs();
// get file location
appraisals = new AppraisalList();
//DefaultFunctions = new List<Guid>();
AppState.Drop += AppStateDrop;
Load();
functions.CollectionChanged += (sender, e) => {
Save();
switch (e.Action) {
case NotifyCollectionChangedAction.Move:
UpdateAllAppraisals();
break;
case NotifyCollectionChangedAction.Add:
UpdateAllAppraisals();
foreach (var newItem in e.NewItems) {
var function = newItem as Function;
if (function == null) continue;
function.PropertyChanged += OnFunctionPropertyChanged;
}
break;
case NotifyCollectionChangedAction.Replace:
case NotifyCollectionChangedAction.Remove:
foreach (var oldItem in e.OldItems) {
var function = oldItem as Function;
if (function == null) continue;
function.PropertyChanged -= OnFunctionPropertyChanged;
}
foreach (var appraisal in SelectedAppraisals) {
foreach (Function function in e.OldItems)
appraisal.Criteria.RemoveCriterion(function);
}
break;
}
};
TabViewModel = (AppraisalTabViewModel)IoC.GetInstance(typeof(IAppraisalTab), "");
TabViewModel.Plugin = this;
AppraisalTabItem = new StartPanelTabItem
{
Name = "Appraisals",
ModelInstance = TabViewModel,
};
FunctionsViewModel = (FunctionsTabViewModel)IoC.GetInstance(typeof(IFunctionsTab), "");
FunctionsViewModel.Plugin = this;
FunctionsTabItem = new StartPanelTabItem
{
Name = "Functions",
ModelInstance = FunctionsViewModel
};
Application.Current.MainWindow.PreviewKeyUp += MainWindowPreviewKeyUp;
SelectedAppraisals.CollectionChanged += SelectedAppraisalsCollectionChanged;
AppState.AddStartPanelTabItem(AppraisalTabItem);
AppState.AddStartPanelTabItem(FunctionsTabItem);
}
public void Start() {
IsRunning = true;
//isTimelineVisible = AppState.TimelineVisible;
UpdateTabs();
var avm = AppState.Container.GetExportedValue<IAppraisal>();
if (avm == null) throw new SystemException("Couldn't create AppraisalViewModel");
avm.Plugin = this;
if (menu != null) AppState.CircularMenus.Add(menu);
// Since the AppraisalPlugin is not part of the lifecycle, I need to activate the AppraisalViewModel myself.
ScreenExtensions.TryActivate(avm);
Screen = avm as IPluginScreen;
}
public void Pause()
{
IsRunning = false;
}
private CircularMenuItem menu;
public void Stop() {
//AppState.RemoveStartPanelTabItem(AppraisalTabItem);
//AppState.RemoveStartPanelTabItem(FunctionsTabItem);
menu = AppState.CircularMenus.FirstOrDefault(m => string.Equals(m.Id, "AppraisalMenu"));
if (menu != null) AppState.CircularMenus.Remove(menu);
IsRunning = false;
Active = false;
UpdateTabs();
Save();
}
private void UpdateTabs() {
AppState.DockedFloatingElementsVisible = !Active;
AppState.BottomTabMenuVisible = true;
AppState.BotomPanelVisible = true;
if (Active)
{
AppState.LeftTabMenuVisible = false;
AppState.ExcludedStartTabItems.Clear();
if (!AppState.FilteredStartTabItems.Contains("Appraisals")) AppState.FilteredStartTabItems.Add("Appraisals");
if (!AppState.FilteredStartTabItems.Contains("Functions")) AppState.FilteredStartTabItems.Add("Functions");
//isTimelineVisible = AppState.TimelineVisible;
//AppState.TimelineVisible = false;
}
else {
AppState.LeftTabMenuVisible = true;
AppState.FilteredStartTabItems.Clear();
if (!AppState.ExcludedStartTabItems.Contains("Appraisals")) AppState.ExcludedStartTabItems.Add("Appraisals");
if (!AppState.ExcludedStartTabItems.Contains("Functions")) AppState.ExcludedStartTabItems.Add("Functions");
//AppState.TimelineVisible = isTimelineVisible;
}
}
private void OnActiveChanged()
{
var handler = ActiveChanged;
if (handler != null) ActiveChanged(this, null);
}
public event EventHandler ActiveChanged;
public event EventHandler AppraisalsUpdated;
public void TriggerAppraisalsUpdated()
{
if (AppraisalsUpdated != null) AppraisalsUpdated(this, null);
}
//public List<Guid> DefaultFunctions { get; set; }
private void UpdateAllAppraisals() {
foreach (var appraisal in SelectedAppraisals)
appraisal.Criteria.Update(functions);
}
private void OnFunctionPropertyChanged(object sender, PropertyChangedEventArgs e) {
if (e.PropertyName.Equals("Name") || e.PropertyName.Equals("IsSelected"))
UpdateAllAppraisals();
}
/// <summary>
/// Load all functions and appraisals from disk
/// </summary>
public void Load() {
try {
if (File.Exists(SavedFunctionsFileName)) {
var xmlSerializer = new XmlSerializer(typeof (FunctionList));
using (var stream = new StreamReader(SavedFunctionsFileName)) {
var ff = xmlSerializer.Deserialize(stream) as FunctionList;
if (ff != null) {
foreach (var function in ff)
function.PropertyChanged += OnFunctionPropertyChanged;
Functions.AddRange(ff);
}
}
}
if (!File.Exists(SavedAppraisalsFileName)) return;
var xmlSerializer2 = new XmlSerializer(typeof(AppraisalList));
using (var stream = new StreamReader(SavedAppraisalsFileName))
{
var a = xmlSerializer2.Deserialize(stream) as AppraisalList;
if (a == null) return;
foreach (var appraisal in a)
{
// Adjust path filename as they may have moved to a different location
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(appraisal.FileName);
if (string.IsNullOrWhiteSpace(fileNameWithoutExtension)) continue;
appraisal.FileName = FullFileName(fileNameWithoutExtension);
}
Appraisals.AddRange(a);
SelectedAppraisals.AddRange(a);
}
}
catch (Exception e) {
Logger.Log("AppraisalPlugin", "Load", e.Message, Logger.Level.Error);
}
}
/// <summary>
/// Save all functions and appraisals to disk
/// </summary>
public void Save() {
try
{
var xmlSerializer = new XmlSerializer(typeof (FunctionList));
using (var stream = new StreamWriter(SavedFunctionsFileName))
xmlSerializer.Serialize(stream, Functions);
var xmlSerializer2 = new XmlSerializer(typeof (AppraisalList));
using (var stream = new StreamWriter(SavedAppraisalsFileName))
xmlSerializer2.Serialize(stream, Appraisals);
}
catch (Exception e)
{
Logger.Log("AppraisalPlugin","Error saving xml file",e.Message,Logger.Level.Error);
}
}
private void AppStateDrop(object sender, DropEventArgs e) {
if (!IsRunning || !(e.EventArgs.Cursor.Data is Appraisal)) return;
//var a = (Appraisal) e.EventArgs.Cursor.Data;
var avm = AppState.Container.GetExportedValue<IAppraisal>();
avm.Plugin = this;
var fe = new FloatingElement {
ModelInstance = avm,
OpacityDragging = 0.5,
OpacityNormal = 1.0,
CanDrag = true,
CanMove = true,
CanRotate = true,
CanScale = true,
Background = Brushes.DarkOrange,
//MaxSize = new Size(500, (500.0 / pf.Width) * pf.Height),
StartPosition = e.Pos,
StartSize = new Size(200, 200),
Width = 300,
Height = 300,
ShowsActivationEffects = false,
RemoveOnEdge = true,
Contained = true,
CanFullScreen = true,
Title = "Appraisal",
Foreground = Brushes.White,
DockingStyle = DockingStyles.None,
};
AppState.FloatingItems.Add(fe);
}
private void SelectedAppraisalsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
if (e.Action != NotifyCollectionChangedAction.Add) return;
foreach (var appraisal in SelectedAppraisals) {
if (appraisal.Criteria == null || appraisal.Criteria.Count == 0) appraisal.Criteria = new CriteriaList(functions, 0, 10);
else appraisal.Criteria.Update(functions);
}
}
#endregion
public void GoTo() {}
private void MainWindowPreviewKeyUp(object sender, KeyEventArgs e) {
// Key.Snapshot is the PrintScreen key. However, when ALT is pressed, I have to check the SystemKey for Key.Snapshot.
// NOTE The PrintScreen key is not captured in the KeyDown event!
if (e.Key != Key.Snapshot && e.SystemKey != Key.Snapshot) return;
//if (e.Key != Key.LeftCtrl) return;
e.Handled = true;
CreateNewAppraisal();
}
public ImageSource CreateNewAppraisal() {
var appraisal = new Appraisal {
Title = "New Appraisal",
Criteria = new CriteriaList(functions, 0, 10)
};
appraisal.FileName = FullFileName(appraisal.Id.ToString());
var r = Screenshots.SaveImageOfControl(Application.Current.MainWindow, appraisal.FileName);
if (r == null) return null;
Appraisals.Add(appraisal);
SelectedAppraisals.Add(appraisal);
return r;
}
public void Export()
{
try
{
var ap = Appraisals.Where(a => a.IsSelected && File.Exists(a.FileName)).Select(a => a).ToList();
if (!ap.Any())
{
AppStateSettings.Instance.TriggerNotification(string.Format("No appraisals created or selected", "export"));
return;
}
var imagePaths = ap.Select(a => a.FileName).ToList();
var titles = ap.Select(a => a.Title).ToList();
var at = Path.ChangeExtension(Path.Combine(Path.GetDirectoryName(imagePaths[0]), "export - " + DateTime.Now.Ticks.ToString()), "pptx");
var pptFactory = new PowerPointFactory(at);
pptFactory.CreateTitleAndImageSlides(imagePaths, titles);
var ne = new NotificationEventArgs()
{
Header = "Export",
Text = "Finished creating PowerPoint"
};
ne.Foreground = Brushes.Black;
ne.Background = Brushes.LightBlue;
ne.Options = new List<string> { "Open" };
ne.OptionClicked += (f, b) =>
{
Process.Start(at);
};
AppStateSettings.Instance.TriggerNotification(ne);
}
catch (Exception)
{
AppStateSettings.Instance.TriggerNotification(string.Format("Error creating PowerPoint, check if folder exist", "export"));
}
}
public ImageSource CreateNewMapAppraisal() {
var appraisal = new Appraisal {
Title = "New Appraisal",
Criteria = new CriteriaList(functions, 0, 10),
IsSelected = true
};
appraisal.FileName = FullFileName(appraisal.Id.ToString());
var r = Screenshots.SaveImageOfControl(AppState.ViewDef.MapControl, appraisal.FileName);
if (r == null) return null;
Appraisals.Add(appraisal);
if (SelectedAppraisals.IndexOf(appraisal)==-1) SelectedAppraisals.Add(appraisal);
SelectedAppraisal = appraisal;
return r;
}
private string FullFileName(string screenshotName) {
return Path.ChangeExtension(Path.Combine(ScreenshotFolder, screenshotName), "png");
}
#region ImageHandling
///// <summary>
///// Convert any control to a PngBitmapEncoder
///// </summary>
///// <param name="controlToConvert"> The control to convert to an ImageSource </param>
///// <returns> The returned ImageSource of the controlToConvert </returns>
///// <see cref="http://www.dreamincode.net/code/snippet4326.htm" />
//private static PngBitmapEncoder GetImageFromControl(FrameworkElement controlToConvert) {
// //var printDialog = new PrintDialog();
// //if (printDialog.ShowDialog() == true) printDialog.PrintVisual(controlToConvert, "ActivityInspector diagram");
// // save current canvas transform
// // var transform = controlToConvert.LayoutTransform;
// // get size of control
// var sizeOfControl = new Size(controlToConvert.ActualWidth, controlToConvert.ActualHeight);
// // measure and arrange the control
// controlToConvert.Measure(sizeOfControl);
// // arrange the surface
// controlToConvert.Arrange(new Rect(sizeOfControl));
// // craete and render surface and push bitmap to it
// var renderBitmap = new RenderTargetBitmap((Int32) sizeOfControl.Width, (Int32) sizeOfControl.Height, 96d, 96d,
// PixelFormats.Pbgra32);
// // now render surface to bitmap
// renderBitmap.Render(controlToConvert);
// // encode png data
// var pngEncoder = new PngBitmapEncoder();
// // puch rendered bitmap into it
// pngEncoder.Frames.Add(BitmapFrame.Create(renderBitmap));
// //pngEncoder.Metadata = new BitmapMetadata("png") {
// // ApplicationName = "Marvelous",
// // DateTaken = DateTime.Now.ToString(CultureInfo.InvariantCulture),
// // Subject = "Casual Loop Analysis using Marvel",
// // Title = "Marvelous screenshot",
// // Author = new ReadOnlyCollection<string>(new List<string> {
// // Properties.Settings.Default.UserName
// // })
// // };
// // return encoder
// return pngEncoder;
//}
///// <summary>
///// Get an ImageSource of a control
///// </summary>
///// <param name="controlToConvert"> The control to convert to an ImageSource </param>
///// <returns> The returned ImageSource of the controlToConvert </returns>
//public static ImageSource GetImageOfControl(Control controlToConvert) {
// // return first frame of image
// return GetImageFromControl(controlToConvert).Frames[0];
//}
///// <summary>
///// Save an image of a control
///// </summary>
///// <param name="controlToConvert"> The control to convert to an ImageSource </param>
///// ///
///// <param name="fileName"> The location to save the image to </param>
///// <returns> The returned ImageSource of the controlToConvert </returns>
//public static ImageSource SaveImageOfControl(Control controlToConvert, string fileName) {
// ImageSource result = null;
// try {
// // create a file stream for saving image
// using (var outStream = new FileStream(fileName, FileMode.Create)) {
// PngBitmapEncoder r = GetImageFromControl(controlToConvert);
// r.Save(outStream);
// return r.Frames[0];
// } // save encoded data to stream
// }
// catch (Exception e) {
// // display for debugging
// MessageBox.Show(String.Format("Exception caught saving stream: {0}", e.Message), "Error saving image", MessageBoxButton.OK,
// MessageBoxImage.Error);
// // return fail
// return null;
// }
//}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Security.Principal;
namespace SocketHttpListener.Net.WebSockets
{
/// <summary>
/// Provides the properties used to access the information in a WebSocket connection request
/// received by the <see cref="HttpListener"/>.
/// </summary>
/// <remarks>
/// </remarks>
public class HttpListenerWebSocketContext : WebSocketContext
{
#region Private Fields
private HttpListenerContext _context;
private WebSocket _websocket;
#endregion
#region Internal Constructors
internal HttpListenerWebSocketContext(
HttpListenerContext context, string protocol)
{
_context = context;
_websocket = new WebSocket(this, protocol);
}
#endregion
#region Internal Properties
internal Stream Stream
{
get
{
return _context.Connection.Stream;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the HTTP cookies included in the request.
/// </summary>
/// <value>
/// A <see cref="System.Net.CookieCollection"/> that contains the cookies.
/// </value>
public override CookieCollection CookieCollection
{
get
{
return _context.Request.Cookies;
}
}
/// <summary>
/// Gets the HTTP headers included in the request.
/// </summary>
/// <value>
/// A <see cref="NameValueCollection"/> that contains the headers.
/// </value>
public override NameValueCollection Headers
{
get
{
return _context.Request.Headers;
}
}
/// <summary>
/// Gets the value of the Host header included in the request.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the Host header.
/// </value>
public override string Host
{
get
{
return _context.Request.Headers["Host"];
}
}
/// <summary>
/// Gets a value indicating whether the client is authenticated.
/// </summary>
/// <value>
/// <c>true</c> if the client is authenticated; otherwise, <c>false</c>.
/// </value>
public override bool IsAuthenticated
{
get
{
return _context.Request.IsAuthenticated;
}
}
/// <summary>
/// Gets a value indicating whether the client connected from the local computer.
/// </summary>
/// <value>
/// <c>true</c> if the client connected from the local computer; otherwise, <c>false</c>.
/// </value>
public override bool IsLocal
{
get
{
return _context.Request.IsLocal;
}
}
/// <summary>
/// Gets a value indicating whether the WebSocket connection is secured.
/// </summary>
/// <value>
/// <c>true</c> if the connection is secured; otherwise, <c>false</c>.
/// </value>
public override bool IsSecureConnection
{
get
{
return _context.Connection.IsSecure;
}
}
/// <summary>
/// Gets a value indicating whether the request is a WebSocket connection request.
/// </summary>
/// <value>
/// <c>true</c> if the request is a WebSocket connection request; otherwise, <c>false</c>.
/// </value>
public override bool IsWebSocketRequest
{
get
{
return _context.Request.IsWebSocketRequest;
}
}
/// <summary>
/// Gets the value of the Origin header included in the request.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the Origin header.
/// </value>
public override string Origin
{
get
{
return _context.Request.Headers["Origin"];
}
}
/// <summary>
/// Gets the query string included in the request.
/// </summary>
/// <value>
/// A <see cref="NameValueCollection"/> that contains the query string parameters.
/// </value>
public override NameValueCollection QueryString
{
get
{
return _context.Request.QueryString;
}
}
/// <summary>
/// Gets the URI requested by the client.
/// </summary>
/// <value>
/// A <see cref="Uri"/> that represents the requested URI.
/// </value>
public override Uri RequestUri
{
get
{
return _context.Request.Url;
}
}
/// <summary>
/// Gets the value of the Sec-WebSocket-Key header included in the request.
/// </summary>
/// <remarks>
/// This property provides a part of the information used by the server to prove that it
/// received a valid WebSocket connection request.
/// </remarks>
/// <value>
/// A <see cref="string"/> that represents the value of the Sec-WebSocket-Key header.
/// </value>
public override string SecWebSocketKey
{
get
{
return _context.Request.Headers["Sec-WebSocket-Key"];
}
}
/// <summary>
/// Gets the values of the Sec-WebSocket-Protocol header included in the request.
/// </summary>
/// <remarks>
/// This property represents the subprotocols requested by the client.
/// </remarks>
/// <value>
/// An <see cref="T:System.Collections.Generic.IEnumerable{string}"/> instance that provides
/// an enumerator which supports the iteration over the values of the Sec-WebSocket-Protocol
/// header.
/// </value>
public override IEnumerable<string> SecWebSocketProtocols
{
get
{
var protocols = _context.Request.Headers["Sec-WebSocket-Protocol"];
if (protocols != null)
foreach (var protocol in protocols.Split(','))
yield return protocol.Trim();
}
}
/// <summary>
/// Gets the value of the Sec-WebSocket-Version header included in the request.
/// </summary>
/// <remarks>
/// This property represents the WebSocket protocol version.
/// </remarks>
/// <value>
/// A <see cref="string"/> that represents the value of the Sec-WebSocket-Version header.
/// </value>
public override string SecWebSocketVersion
{
get
{
return _context.Request.Headers["Sec-WebSocket-Version"];
}
}
/// <summary>
/// Gets the server endpoint as an IP address and a port number.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the server endpoint.
/// </value>
public override System.Net.IPEndPoint ServerEndPoint
{
get
{
return _context.Connection.LocalEndPoint;
}
}
/// <summary>
/// Gets the client information (identity, authentication, and security roles).
/// </summary>
/// <value>
/// A <see cref="IPrincipal"/> that represents the client information.
/// </value>
public override IPrincipal User
{
get
{
return _context.User;
}
}
/// <summary>
/// Gets the client endpoint as an IP address and a port number.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the client endpoint.
/// </value>
public override System.Net.IPEndPoint UserEndPoint
{
get
{
return _context.Connection.RemoteEndPoint;
}
}
/// <summary>
/// Gets the <see cref="SocketHttpListener.WebSocket"/> instance used for two-way communication
/// between client and server.
/// </summary>
/// <value>
/// A <see cref="SocketHttpListener.WebSocket"/>.
/// </value>
public override WebSocket WebSocket
{
get
{
return _websocket;
}
}
#endregion
#region Internal Methods
internal void Close()
{
try
{
_context.Connection.Close(true);
}
catch
{
// catch errors sending the closing handshake
}
}
internal void Close(HttpStatusCode code)
{
_context.Response.Close(code);
}
#endregion
#region Public Methods
/// <summary>
/// Returns a <see cref="string"/> that represents the current
/// <see cref="HttpListenerWebSocketContext"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the current
/// <see cref="HttpListenerWebSocketContext"/>.
/// </returns>
public override string ToString()
{
return _context.Request.ToString();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using Lucene.Net.Support;
using NUnit.Framework;
namespace Lucene.Net.Util.junitcompat
{
/*
* 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 Assert = junit.framework.Assert;
using Before = org.junit.Before;
using BeforeClass = org.junit.BeforeClass;
using Test = org.junit.Test;
using JUnitCore = org.junit.runner.JUnitCore;
using Result = org.junit.runner.Result;
using Failure = org.junit.runner.notification.Failure;
*/
public class TestExceptionInBeforeClassHooks : WithNestedTests
{
public TestExceptionInBeforeClassHooks() : base(true)
{
}
public class Nested1 : WithNestedTests.AbstractNestedTest
{
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @BeforeClass public static void beforeClass() throws Exception
public static void BeforeClass()
{
ThreadClass t = new ThreadAnonymousInnerClassHelper();
t.Start();
t.Join();
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
public ThreadAnonymousInnerClassHelper()
{
}
public override void Run()
{
throw new Exception("foobar");
}
}
public virtual void Test()
{
}
}
public class Nested2 : WithNestedTests.AbstractNestedTest
{
public virtual void Test1()
{
ThreadClass t = new ThreadAnonymousInnerClassHelper(this);
t.Start();
t.Join();
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
private readonly Nested2 OuterInstance;
public ThreadAnonymousInnerClassHelper(Nested2 outerInstance)
{
this.OuterInstance = outerInstance;
}
public override void Run()
{
throw new Exception("foobar1");
}
}
public virtual void Test2()
{
ThreadClass t = new ThreadAnonymousInnerClassHelper2(this);
t.Start();
t.Join();
}
private class ThreadAnonymousInnerClassHelper2 : ThreadClass
{
private readonly Nested2 OuterInstance;
public ThreadAnonymousInnerClassHelper2(Nested2 outerInstance)
{
this.OuterInstance = outerInstance;
}
public override void Run()
{
throw new Exception("foobar2");
}
}
public virtual void Test3()
{
ThreadClass t = new ThreadAnonymousInnerClassHelper3(this);
t.Start();
t.Join();
}
private class ThreadAnonymousInnerClassHelper3 : ThreadClass
{
private readonly Nested2 OuterInstance;
public ThreadAnonymousInnerClassHelper3(Nested2 outerInstance)
{
this.OuterInstance = outerInstance;
}
public override void Run()
{
throw new Exception("foobar3");
}
}
}
public class Nested3 : WithNestedTests.AbstractNestedTest
{
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void runBeforeTest() throws Exception
public virtual void RunBeforeTest()
{
ThreadClass t = new ThreadAnonymousInnerClassHelper(this);
t.Start();
t.Join();
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
private readonly Nested3 OuterInstance;
public ThreadAnonymousInnerClassHelper(Nested3 outerInstance)
{
this.OuterInstance = outerInstance;
}
public override void Run()
{
throw new Exception("foobar");
}
}
public virtual void Test1()
{
}
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testExceptionInBeforeClassFailsTheTest()
public virtual void TestExceptionInBeforeClassFailsTheTest()
{
Result runClasses = JUnitCore.runClasses(typeof(Nested1));
Assert.AreEqual(1, runClasses.FailureCount);
Assert.AreEqual(1, runClasses.RunCount);
Assert.IsTrue(runClasses.Failures.Get(0).Trace.Contains("foobar"));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testExceptionWithinTestFailsTheTest()
public virtual void TestExceptionWithinTestFailsTheTest()
{
Result runClasses = JUnitCore.runClasses(typeof(Nested2));
Assert.AreEqual(3, runClasses.FailureCount);
Assert.AreEqual(3, runClasses.RunCount);
List<string> foobars = new List<string>();
foreach (Failure f in runClasses.Failures)
{
Matcher m = Pattern.compile("foobar[0-9]+").matcher(f.Trace);
while (m.find())
{
foobars.Add(m.group());
}
}
foobars.Sort();
Assert.AreEqual("[foobar1, foobar2, foobar3]", Arrays.ToString(foobars.ToArray()));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testExceptionWithinBefore()
public virtual void TestExceptionWithinBefore()
{
Result runClasses = JUnitCore.runClasses(typeof(Nested3));
Assert.AreEqual(1, runClasses.FailureCount);
Assert.AreEqual(1, runClasses.RunCount);
Assert.IsTrue(runClasses.Failures.Get(0).Trace.Contains("foobar"));
}
}
}
| |
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
namespace Fluent
{
/// <summary>
/// Represents KeyTip control
/// </summary>
public class KeyTip : Label
{
#region Keys Attached Property
/// <summary>
/// Using a DependencyProperty as the backing store for Keys.
/// This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty KeysProperty = DependencyProperty.RegisterAttached(
"Keys",
typeof(string),
typeof(KeyTip),
new FrameworkPropertyMetadata(null, KeysPropertyChanged)
);
static void KeysPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
/// <summary>
/// Sets value of attached property Keys for the given element
/// </summary>
/// <param name="element">The given element</param>
/// <param name="value">Value</param>
public static void SetKeys(DependencyObject element, string value)
{
element.SetValue(KeysProperty, value);
}
/// <summary>
/// Gets value of the attached property Keys of the given element
/// </summary>
/// <param name="element">The given element</param>
[System.ComponentModel.DisplayName("Keys"),
AttachedPropertyBrowsableForChildren(IncludeDescendants = true),
System.ComponentModel.Category("KeyTips"),
System.ComponentModel.Description("Key sequence for the given element")]
public static string GetKeys(DependencyObject element)
{
return (string)element.GetValue(KeysProperty);
}
#endregion
#region AutoPlacement Attached Property
/// <summary>
/// Using a DependencyProperty as the backing store for AutoPlacement.
/// This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty AutoPlacementProperty = DependencyProperty.RegisterAttached(
"AutoPlacement",
typeof(bool),
typeof(KeyTip),
new FrameworkPropertyMetadata(true)
);
/// <summary>
/// Sets whether key tip placement is auto
/// or defined by alignment and margin properties
/// </summary>
/// <param name="element">The given element</param>
/// <param name="value">Value</param>
public static void SetAutoPlacement(DependencyObject element, bool value)
{
element.SetValue(AutoPlacementProperty, value);
}
/// <summary>
/// Gets whether key tip placement is auto
/// or defined by alignment and margin properties
/// </summary>
/// <param name="element">The given element</param>
[System.ComponentModel.DisplayName("AutoPlacement"),
AttachedPropertyBrowsableForChildren(IncludeDescendants = true),
System.ComponentModel.Category("KeyTips"),
System.ComponentModel.Description("Whether key tip placement is auto or defined by alignment and margin properties")]
public static bool GetAutoPlacement(DependencyObject element)
{
return (bool)element.GetValue(AutoPlacementProperty);
}
#endregion
#region HorizontalAlignment Attached Property
/// <summary>
/// Using a DependencyProperty as the backing store for HorizontalAlignment.
/// This enables animation, styling, binding, etc...
/// </summary>
public static new readonly DependencyProperty HorizontalAlignmentProperty = DependencyProperty.RegisterAttached(
"HorizontalAlignment",
typeof(HorizontalAlignment),
typeof(KeyTip),
new FrameworkPropertyMetadata(HorizontalAlignment.Center)
);
/// <summary>
/// Sets Horizontal Alignment of the key tip
/// </summary>
/// <param name="element">The given element</param>
/// <param name="value">Value</param>
public static void SetHorizontalAlignment(DependencyObject element, HorizontalAlignment value)
{
element.SetValue(HorizontalAlignmentProperty, value);
}
/// <summary>
/// Gets Horizontal alignment of the key tip
/// </summary>
/// <param name="element">The given element</param>
[System.ComponentModel.DisplayName("HorizontalAlignment"),
AttachedPropertyBrowsableForChildren(IncludeDescendants = true),
System.ComponentModel.Category("KeyTips"),
System.ComponentModel.Description("Horizontal alignment of the key tip")]
public static HorizontalAlignment GetHorizontalAlignment(DependencyObject element)
{
return (HorizontalAlignment)element.GetValue(HorizontalAlignmentProperty);
}
#endregion
#region VerticalAlignment Attached Property
/// <summary>
/// Gets vertical alignment of the key tip
/// </summary>
/// <param name="element">The given element</param>
[System.ComponentModel.DisplayName("VerticalAlignment"),
AttachedPropertyBrowsableForChildren(IncludeDescendants = true),
System.ComponentModel.Category("KeyTips"),
System.ComponentModel.Description("Vertical alignment of the key tip")]
public static VerticalAlignment GetVerticalAlignment(DependencyObject element)
{
return (VerticalAlignment)element.GetValue(VerticalAlignmentProperty);
}
/// <summary>
/// Sets vertical alignment of the key tip
/// </summary>
/// <param name="obj">The given element</param>
/// <param name="value">Value</param>
public static void SetVerticalAlignment(DependencyObject obj, VerticalAlignment value)
{
obj.SetValue(VerticalAlignmentProperty, value);
}
/// <summary>
/// Using a DependencyProperty as the backing store for VerticalAlignment.
/// This enables animation, styling, binding, etc...
/// </summary>
public static new readonly DependencyProperty VerticalAlignmentProperty =
DependencyProperty.RegisterAttached("VerticalAlignment",
typeof(VerticalAlignment), typeof(KeyTip),
new UIPropertyMetadata(VerticalAlignment.Center));
#endregion
#region Margin Attached Property
/// <summary>
/// Gets margin of the key tip
/// </summary>
/// <param name="obj">The key tip</param>
/// <returns>Margin</returns>
[System.ComponentModel.DisplayName("Margin"),
AttachedPropertyBrowsableForChildren(IncludeDescendants = true),
System.ComponentModel.Category("KeyTips"),
System.ComponentModel.Description("Margin of the key tip")]
public static Thickness GetMargin(DependencyObject obj)
{
return (Thickness)obj.GetValue(MarginProperty);
}
/// <summary>
/// Sets margin of the key tip
/// </summary>
/// <param name="obj">The key tip</param>
/// <param name="value">Value</param>
public static void SetMargin(DependencyObject obj, Thickness value)
{
obj.SetValue(MarginProperty, value);
}
/// <summary>
/// Using a DependencyProperty as the backing store for Margin.
/// This enables animation, styling, binding, etc...
/// </summary>
public static new readonly DependencyProperty MarginProperty =
DependencyProperty.RegisterAttached("Margin", typeof(Thickness), typeof(KeyTip), new UIPropertyMetadata(new Thickness()));
#endregion
#region Initialization
// Static constructor
[SuppressMessage("Microsoft.Performance", "CA1810")]
static KeyTip()
{
// Override metadata to allow slyling
//StyleProperty.OverrideMetadata(typeof(KeyTip), new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnCoerceStyle)));
DefaultStyleKeyProperty.OverrideMetadata(typeof(KeyTip), new FrameworkPropertyMetadata(typeof(KeyTip)));
StyleProperty.OverrideMetadata(typeof(KeyTip), new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnCoerceStyle)));
}
// Coerce object style
static object OnCoerceStyle(DependencyObject d, object basevalue)
{
if (basevalue == null)
{
basevalue = (d as FrameworkElement).TryFindResource(typeof(KeyTip));
}
return basevalue;
}
/// <summary>
/// Default constrctor
/// </summary>
public KeyTip()
{
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using System.Linq;
namespace EFAuditing
{
/// <summary>
/// Summary:
/// A AuditingDbContext instane extends DbContext that represents a session with
/// the database and can be used to query and save instances of your entities.
/// DbContext is a combination of the Unit Of Work and Repository patterns.
/// </summary>
public abstract class AuditingDbContext : DbContext
{
private const string DefaultAuditTableName = "AuditLogs";
private const string DefaultAuditSchemaName = "audit";
private readonly string _auditTableName;
private readonly string _auditSchemaName;
private readonly IExternalAuditStoreProvider _externalAuditStoreProvider;
private bool ExternalProviderSpecified => _externalAuditStoreProvider != null;
#region Constructors
/// <summary>
/// Initializes a new instance of the AuditingDbContext class (Extends Microsoft.Data.Entity.DbContext).
/// This class writes Audit Logs to the current database using Entity Framework to the default table: [audit].[AuditLogs]
/// The Microsoft.Data.Entity.DbContext.OnConfiguring(Microsoft.Data.Entity.DbContextOptionsBuilder)
/// method will be called to configure the database (and other options) to be used
/// for this context.
/// </summary>
protected AuditingDbContext()
{
_auditTableName = DefaultAuditTableName;
_auditSchemaName = DefaultAuditSchemaName;
}
/// <summary>
/// Initializes a new instance of the AuditingDbContext class (Extends Microsoft.Data.Entity.DbContext).
/// This class writes Audit Logs to the current database using Entity Framework to the default table: [audit].[AuditLogs]
/// The Microsoft.Data.Entity.DbContext.OnConfiguring(Microsoft.Data.Entity.DbContextOptionsBuilder)
/// method will be called to configure the database (and other options) to be used
/// for this context.
/// </summary>
protected AuditingDbContext(IExternalAuditStoreProvider externalAuditStoreProvider)
{
_externalAuditStoreProvider = externalAuditStoreProvider;
}
/// <summary>
/// Initializes a new instance of the AuditingDbContext class (Extends Microsoft.Data.Entity.DbContext).
/// This class writes Audit Logs to the current database using Entity Framework using the specified table and schema.
/// The Microsoft.Data.Entity.DbContext.OnConfiguring(Microsoft.Data.Entity.DbContextOptionsBuilder)
/// method will be called to configure the database (and other options) to be used
/// for this context.
/// </summary>
/// <param name="auditTableName">SQL Table Name</param>
/// <param name="auditSchemaName">SQL Schema Name</param>
protected AuditingDbContext(string auditTableName, string auditSchemaName)
{
_auditTableName = auditTableName;
_auditSchemaName = auditSchemaName;
}
/// <summary>
/// Initializes a new instance of the AuditingDbContext class (Extends Microsoft.Data.Entity.DbContext) with the specified
/// options. The Microsoft.Data.Entity.DbContext.OnConfiguring(Microsoft.Data.Entity.DbContextOptionsBuilder)
/// method will still be called to allow further configuration of the options.
/// </summary>
/// <param name="options">The options for this context.</param>
protected AuditingDbContext(DbContextOptions options) : base(options)
{
}
/// <summary>
/// Initializes a new instance of the AuditingDbContext class (Extends Microsoft.Data.Entity.DbContext) using an System.IServiceProvider.
/// The service provider must contain all the services required by Entity Framework
/// (and the database being used). The Entity Framework services can be registered
/// using the Microsoft.Framework.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddEntityFramework(Microsoft.Framework.DependencyInjection.IServiceCollection)
/// method. Most databases also provide an extension method on Microsoft.Framework.DependencyInjection.IServiceCollection
/// to register the services required.
/// If the System.IServiceProvider has a Microsoft.Data.Entity.Infrastructure.DbContextOptions
/// or Microsoft.Data.Entity.Infrastructure.DbContextOptions`1 registered, then this
/// will be used as the options for this context instance. The Microsoft.Data.Entity.DbContext.OnConfiguring(Microsoft.Data.Entity.DbContextOptionsBuilder)
/// method will still be called to allow further configuration of the options.
/// </summary>
/// <param name="serviceProvider">The service provider to be used.</param>
protected AuditingDbContext(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
/// <summary>
/// Initializes a new instance of the AuditingDbContext class (Extends Microsoft.Data.Entity.DbContext) using
/// an System.IServiceProvider and the specified options.
/// The Microsoft.Data.Entity.DbContext.OnConfiguring(Microsoft.Data.Entity.DbContextOptionsBuilder)
/// method will still be called to allow further configuration of the options.
/// The service provider must contain all the services required by Entity Framework
/// (and the databases being used). The Entity Framework services can be registered
/// using the Microsoft.Framework.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddEntityFramework(Microsoft.Framework.DependencyInjection.IServiceCollection)
/// method. Most databases also provide an extension method on Microsoft.Framework.DependencyInjection.IServiceCollection
/// to register the services required.
/// If the System.IServiceProvider has a Microsoft.Data.Entity.Infrastructure.DbContextOptions
/// or Microsoft.Data.Entity.Infrastructure.DbContextOptions`1 registered, then this
/// will be used as the options for this context instance. The Microsoft.Data.Entity.DbContext.OnConfiguring(Microsoft.Data.Entity.DbContextOptionsBuilder)
/// method will still be called to allow further configuration of the options.
/// </summary>
/// <param name="serviceProvider">The service provider to be used.</param>
/// <param name="options">The options for this context.</param>
protected AuditingDbContext(IServiceProvider serviceProvider, DbContextOptions options)
: base(serviceProvider, options)
{
}
#endregion
#region Obsolete Base Members
[Obsolete("A UserName is required. Use SaveChanges(string userName) instead.")]
public new int SaveChanges()
{
throw new InvalidOperationException("A UserName is required. Use SaveChanges(string userName) instead.");
}
[Obsolete("A UserName is required. Use SaveChanges(string userName) instead.")]
public new int SaveChanges(bool acceptAllChangesOnSuccess)
{
throw new InvalidOperationException("A UserName is required. Use SaveChanges(string userName) instead.");
}
[Obsolete("A UserName is required. Use SaveChangesAsync(userName, cancellationToken) instead.")]
public new Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
throw new InvalidOperationException(
"A UserName is required. Use SaveChangesAsync(userName, cancellationToken) instead.");
}
[Obsolete("A UserName is required. Use SaveChangesAsync(userName, cancellationToken) instead.")]
public new Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess,
CancellationToken cancellationToken = default(CancellationToken))
{
throw new InvalidOperationException(
"A UserName is required. Use SaveChangesAsync(userName, cancellationToken) instead.");
}
#endregion
/// <summary>
/// Override this method to further configure the model that was discovered by convention from the entity types
/// exposed in <see cref="T:Microsoft.Data.Entity.DbSet`1"/> properties on your derived context. The resulting model may be cached
/// and re-used for subsequent instances of your derived context.
/// </summary>
/// <param name="modelBuilder">The builder being used to construct the model for this context. Databases (and other extensions) typically
/// define extension methods on this object that allow you to configure aspects of the model that are specific
/// to a given database.
/// </param>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AuditLog>(entity => {
entity.Index(e => e.AuditBatchId);
});
base.OnModelCreating(modelBuilder);
if (!ExternalProviderSpecified)
ConfigureModelBuilder(modelBuilder, _auditTableName, _auditSchemaName);
}
/// <summary>
/// Configuration that sets up the ModelBuilder.
/// This method can be used in scenarios where OnModelCreating will not be called like
/// when an external DbContext is used to centrally manage code first migrations when multiple
/// DbContexts is used in the same solution on the same database. This typically occurs when following using Bounded Contexts
/// as per DDD (Domain Driven Design)
/// </summary>
/// <param name="modelBuilder">The builder being used to construct the model for this context. Databases (and other extensions) typically define extension methods on this object that allow you to configure aspects of the model that are specific to a given database.</param>
/// <param name="auditTableName">SQL Table Name</param>
/// <param name="auditSchemaName">SQL Schema Name</param>
public static void ConfigureModelBuilder(ModelBuilder modelBuilder, string auditTableName,
string auditSchemaName)
{
modelBuilder.Entity<AuditLog>().ToTable(auditTableName, schema: auditSchemaName);
}
/// <summary>
/// Saves all changes made in this context to the underlying database.
/// </summary>
/// <remarks>
/// This method will automatically call <see cref="M:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.DetectChanges"/> to discover any changes
/// to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="P:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.AutoDetectChangesEnabled"/>.
/// </remarks>
/// <param name="userName">Username that will be used in the audit entry.</param>
/// <returns>
/// The number of state entries written to the underlying database.
/// </returns>
public virtual int SaveChanges(string userName)
{
var addedEntityEntries = ChangeTracker.Entries().Where(p => p.State == EntityState.Added).ToList();
var modifiedEntityEntries = ChangeTracker.Entries().Where(p => p.State == EntityState.Modified).ToList();
var deletedEntityEntries = ChangeTracker.Entries().Where(p => p.State == EntityState.Deleted).ToList();
var auditLogs = AuditLogBuilder.GetAuditLogsForExistingEntities(userName, modifiedEntityEntries, deletedEntityEntries);
var result = base.SaveChanges();
auditLogs.AddRange(AuditLogBuilder.GetAuditLogsForAddedEntities(userName, addedEntityEntries));
//auditLogs.
if (ExternalProviderSpecified)
{
var task = _externalAuditStoreProvider.WriteAuditLogs(auditLogs);
while (!task.IsCompleted)
{
task.Wait(10);
}
if (!task.IsFaulted) return result;
if (task.Exception != null) throw task.Exception.InnerException;
}
else
{
Set<AuditLog>().AddRange(auditLogs);
base.SaveChanges();
}
return result;
}
/// <summary>
/// Asynchronously saves all changes made in this context to the underlying database.
/// </summary>
/// <remarks>
/// <para>
/// This method will automatically call <see cref="M:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.DetectChanges"/> to discover any changes
/// to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="P:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.AutoDetectChangesEnabled"/>.
/// </para>
/// <para>
/// Multiple active operations on the same context instance are not supported. Use 'await' to ensure
/// that any asynchronous operations have completed before calling another method on this context.
/// </para>
/// </remarks>
/// <param name="userName">Username that will be used in the audit entry.</param>
/// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken"/> to observe while waiting for the task to complete.</param>
/// <returns>
/// A task that represents the asynchronous save operation. The task result contains the
/// number of state entries written to the underlying database.
/// </returns>
public virtual Task<int> SaveChangesAsync(string userName, CancellationToken cancellationToken)
{
//TODO: Implement this
throw new NotImplementedException(
$"Audit logic not implemented for SaveChangesAsync(string userName, CancellationToken cancellationToken) yet. Use SaveChanges(string userName) instead.");
//return base.SaveChangesAsync(cancellationToken);
}
/// <summary>
/// Reads the audit logs. Simple method that should be refined when using external AuditStoreProviders.
/// </summary>
/// <returns></returns>
public IEnumerable<AuditLog> GetAuditLogs()
{
return ExternalProviderSpecified ? _externalAuditStoreProvider.ReadAuditLogs() : Set<AuditLog>();
//TODO: This should filter when using external providers as _externalAuditStoreProvider.ReadAuditLogs() does not chain LINQ to subsystem queries.
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Quilt4.Service.Entity;
using Quilt4.Service.Interface.Repository;
namespace Quilt4.Service.Authentication
{
public class CustomUserStore<T>
: IUserPasswordStore<T>, IUserRoleStore<T>, IUserStore<T>, IUserLockoutStore<T, string>, IUserTwoFactorStore<T, string>, IUserLoginStore<T, string>, IUserPhoneNumberStore<T, string> where T : ApplicationUser
{
private readonly IRepository _repository;
public CustomUserStore(IRepository repository)
{
_repository = repository;
}
public void Dispose()
{
}
public async Task CreateAsync(T user)
{
await Task.Run(() => _repository.CreateUser(new User(Guid.NewGuid().ToString(), user.UserName, user.Email, user.PasswordHash), DateTime.UtcNow));
}
public async Task UpdateAsync(T user)
{
await Task.Run(() => _repository.UpdateUser(new User(user.Id, user.UserName, user.Email, user.PasswordHash)));
}
public async Task DeleteAsync(T user)
{
throw new NotImplementedException();
}
public async Task<T> FindByIdAsync(string userId)
{
var user = await Task.Run(() => _repository.GetUserByUserKey(userId));
if (user == null)
{
return null;
}
return (T)ToApplicationUser(user);
}
public async Task<T> FindByNameAsync(string userName)
{
var user = await Task.Run(() => _repository.GetUserByUserName(userName));
if (user == null)
{
return null;
}
return (T)ToApplicationUser(user);
}
private static ApplicationUser ToApplicationUser(User user)
{
return new ApplicationUser { Id = user.UserKey, UserName = user.Username, Email = user.Email, PasswordHash = user.PasswordHash };
}
private static ApplicationUser ToApplicationUser(UserInfo user)
{
return new ApplicationUser { Id = user.UserKey, UserName = user.Username, Email = user.Email, PasswordHash = null };
}
public async Task SetPasswordHashAsync(T user, string passwordHash)
{
await Task.Run(() => user.PasswordHash = passwordHash);
}
public async Task<string> GetPasswordHashAsync(T user)
{
var response = await Task.Run(() => _repository.GetUserByUserName(user.UserName));
return response.PasswordHash;
}
public async Task<bool> HasPasswordAsync(T user)
{
throw new NotImplementedException();
}
public async Task AddToRoleAsync(T user, string roleName)
{
await Task.Run(() => _repository.AddUserToRole(user.UserName, roleName));
}
public async Task RemoveFromRoleAsync(T user, string roleName)
{
throw new NotImplementedException();
}
public async Task<IList<string>> GetRolesAsync(T user)
{
var response = await Task.Run(() => _repository.GetRolesByUser(user.UserName).Select(x => x.RoleName).ToArray());
return response;
}
public async Task<bool> IsInRoleAsync(T user, string roleName)
{
throw new NotImplementedException();
}
public IEnumerable<ApplicationUser> GetAll()
{
var response = _repository.GetUsers().Select(ToApplicationUser);
return response;
}
public async Task<DateTimeOffset> GetLockoutEndDateAsync(T user)
{
throw new NotImplementedException();
}
public async Task SetLockoutEndDateAsync(T user, DateTimeOffset lockoutEnd)
{
throw new NotImplementedException();
}
public async Task<int> IncrementAccessFailedCountAsync(T user)
{
throw new NotImplementedException();
}
public async Task ResetAccessFailedCountAsync(T user)
{
throw new NotImplementedException();
}
public async Task<int> GetAccessFailedCountAsync(T user)
{
var response = await Task.Run(() => 0);
return response;
}
public async Task<bool> GetLockoutEnabledAsync(T user)
{
var response = await Task.Run(() => false);
return response;
}
public async Task SetLockoutEnabledAsync(T user, bool enabled)
{
throw new NotImplementedException();
}
public async Task SetTwoFactorEnabledAsync(T user, bool enabled)
{
throw new NotImplementedException();
}
public async Task<bool> GetTwoFactorEnabledAsync(T user)
{
var response = await Task.Run(() => false);
return response;
}
public async Task AddLoginAsync(T user, UserLoginInfo login)
{
throw new NotImplementedException();
}
public async Task RemoveLoginAsync(T user, UserLoginInfo login)
{
throw new NotImplementedException();
}
public async Task<IList<UserLoginInfo>> GetLoginsAsync(T user)
{
var response = await Task.Run(() => new UserLoginInfo[] { });
return response;
}
public async Task<T> FindAsync(UserLoginInfo login)
{
throw new NotImplementedException();
}
public async Task SetPhoneNumberAsync(T user, string phoneNumber)
{
throw new NotImplementedException();
}
public async Task<string> GetPhoneNumberAsync(T user)
{
throw new NotImplementedException();
}
public async Task<bool> GetPhoneNumberConfirmedAsync(T user)
{
throw new NotImplementedException();
}
public async Task SetPhoneNumberConfirmedAsync(T user, bool confirmed)
{
throw new NotImplementedException();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Nini.Config;
using log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Hypergrid
{
public class HGFriendsServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IUserAgentService m_UserAgentService;
private IFriendsSimConnector m_FriendsLocalSimConnector;
private IHGFriendsService m_TheService;
public HGFriendsServerPostHandler(IHGFriendsService service, IUserAgentService uas, IFriendsSimConnector friendsConn) :
base("POST", "/hgfriends")
{
m_TheService = service;
m_UserAgentService = uas;
m_FriendsLocalSimConnector = friendsConn;
m_log.DebugFormat("[HGFRIENDS HANDLER]: HGFriendsServerPostHandler is On ({0})",
(m_FriendsLocalSimConnector == null ? "robust" : "standalone"));
if (m_TheService == null)
m_log.ErrorFormat("[HGFRIENDS HANDLER]: TheService is null!");
}
public override byte[] Handle(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"].ToString();
switch (method)
{
case "getfriendperms":
return GetFriendPerms(request);
case "newfriendship":
return NewFriendship(request);
case "deletefriendship":
return DeleteFriendship(request);
/* Same as inter-sim */
case "friendship_offered":
return FriendshipOffered(request);
case "validate_friendship_offered":
return ValidateFriendshipOffered(request);
case "statusnotification":
return StatusNotification(request);
/*
case "friendship_approved":
return FriendshipApproved(request);
case "friendship_denied":
return FriendshipDenied(request);
case "friendship_terminated":
return FriendshipTerminated(request);
case "grant_rights":
return GrantRights(request);
*/
}
m_log.DebugFormat("[HGFRIENDS HANDLER]: unknown method {0}", method);
}
catch (Exception e)
{
m_log.DebugFormat("[HGFRIENDS HANDLER]: Exception {0}", e);
}
return FailureResult();
}
#region Method-specific handlers
byte[] GetFriendPerms(Dictionary<string, object> request)
{
if (!VerifyServiceKey(request))
return FailureResult();
UUID principalID = UUID.Zero;
if (request.ContainsKey("PRINCIPALID"))
UUID.TryParse(request["PRINCIPALID"].ToString(), out principalID);
else
{
m_log.WarnFormat("[HGFRIENDS HANDLER]: no principalID in request to get friend perms");
return FailureResult();
}
UUID friendID = UUID.Zero;
if (request.ContainsKey("FRIENDID"))
UUID.TryParse(request["FRIENDID"].ToString(), out friendID);
else
{
m_log.WarnFormat("[HGFRIENDS HANDLER]: no friendID in request to get friend perms");
return FailureResult();
}
int perms = m_TheService.GetFriendPerms(principalID, friendID);
if (perms < 0)
return FailureResult("Friend not found");
return SuccessResult(perms.ToString());
}
byte[] NewFriendship(Dictionary<string, object> request)
{
bool verified = VerifyServiceKey(request);
FriendInfo friend = new FriendInfo(request);
bool success = m_TheService.NewFriendship(friend, verified);
if (success)
return SuccessResult();
else
return FailureResult();
}
byte[] DeleteFriendship(Dictionary<string, object> request)
{
FriendInfo friend = new FriendInfo(request);
string secret = string.Empty;
if (request.ContainsKey("SECRET"))
secret = request["SECRET"].ToString();
if (secret == string.Empty)
return BoolResult(false);
bool success = m_TheService.DeleteFriendship(friend, secret);
return BoolResult(success);
}
byte[] FriendshipOffered(Dictionary<string, object> request)
{
UUID fromID = UUID.Zero;
UUID toID = UUID.Zero;
string message = string.Empty;
string name = string.Empty;
if (!request.ContainsKey("FromID") || !request.ContainsKey("ToID"))
return BoolResult(false);
if (!UUID.TryParse(request["ToID"].ToString(), out toID))
return BoolResult(false);
message = request["Message"].ToString();
if (!UUID.TryParse(request["FromID"].ToString(), out fromID))
return BoolResult(false);
if (request.ContainsKey("FromName"))
name = request["FromName"].ToString();
bool success = m_TheService.FriendshipOffered(fromID, name, toID, message);
return BoolResult(success);
}
byte[] ValidateFriendshipOffered(Dictionary<string, object> request)
{
FriendInfo friend = new FriendInfo(request);
UUID friendID = UUID.Zero;
if (!UUID.TryParse(friend.Friend, out friendID))
return BoolResult(false);
bool success = m_TheService.ValidateFriendshipOffered(friend.PrincipalID, friendID);
return BoolResult(success);
}
byte[] StatusNotification(Dictionary<string, object> request)
{
UUID principalID = UUID.Zero;
if (request.ContainsKey("userID"))
UUID.TryParse(request["userID"].ToString(), out principalID);
else
{
m_log.WarnFormat("[HGFRIENDS HANDLER]: no userID in request to notify");
return FailureResult();
}
bool online = true;
if (request.ContainsKey("online"))
Boolean.TryParse(request["online"].ToString(), out online);
else
{
m_log.WarnFormat("[HGFRIENDS HANDLER]: no online in request to notify");
return FailureResult();
}
List<string> friends = new List<string>();
int i = 0;
foreach (KeyValuePair<string, object> kvp in request)
{
if (kvp.Key.Equals("friend_" + i.ToString()))
{
friends.Add(kvp.Value.ToString());
i++;
}
}
List<UUID> onlineFriends = m_TheService.StatusNotification(friends, principalID, online);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((onlineFriends == null) || ((onlineFriends != null) && (onlineFriends.Count == 0)))
result["RESULT"] = "NULL";
else
{
i = 0;
foreach (UUID f in onlineFriends)
{
result["friend_" + i] = f.ToString();
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
#endregion
#region Misc
private bool VerifyServiceKey(Dictionary<string, object> request)
{
if (!request.ContainsKey("KEY") || !request.ContainsKey("SESSIONID"))
{
m_log.WarnFormat("[HGFRIENDS HANDLER]: ignoring request without Key or SessionID");
return false;
}
if (request["KEY"] == null || request["SESSIONID"] == null)
return false;
string serviceKey = request["KEY"].ToString();
string sessionStr = request["SESSIONID"].ToString();
UUID sessionID;
if (!UUID.TryParse(sessionStr, out sessionID) || serviceKey == string.Empty)
return false;
if (!m_UserAgentService.VerifyAgent(sessionID, serviceKey))
{
m_log.WarnFormat("[HGFRIENDS HANDLER]: Key {0} for session {1} did not match existing key. Ignoring request", serviceKey, sessionID);
return false;
}
m_log.DebugFormat("[HGFRIENDS HANDLER]: Verification ok");
return true;
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "Result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] SuccessResult(string value)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "RESULT", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
XmlElement message = doc.CreateElement("", "Value", "");
message.AppendChild(doc.CreateTextNode(value));
rootElement.AppendChild(message);
return DocToBytes(doc);
}
private byte[] FailureResult()
{
return FailureResult(String.Empty);
}
private byte[] FailureResult(string msg)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "RESULT", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
XmlElement message = doc.CreateElement("", "Message", "");
message.AppendChild(doc.CreateTextNode(msg));
rootElement.AppendChild(message);
return DocToBytes(doc);
}
private byte[] BoolResult(bool value)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "RESULT", "");
result.AppendChild(doc.CreateTextNode(value.ToString()));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
}
#endregion
}
}
| |
/*
** $Id: lauxlib.c,v 1.159.1.3 2008/01/21 13:20:51 roberto Exp $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
#define lauxlib_c
#define LUA_LIB
using System;
using System.IO;
namespace SharpLua
{
using lua_Integer = System.Int32;
using lua_Number = System.Double;
public partial class Lua
{
#if LUA_COMPAT_GETN
public static int luaL_getn(lua_State L, int t);
public static void luaL_setn(lua_State L, int t, int n);
#else
public static int luaL_getn(LuaState L, int i) { return (int)lua_objlen(L, i); }
public static void luaL_setn(LuaState L, int i, int j) { } /* no op! */
#endif
#if LUA_COMPAT_OPENLIB
//#define luaI_openlib luaL_openlib
#endif
/* extra error code for `luaL_load' */
public const int LUA_ERRFILE = (LUA_ERRERR + 1);
public class luaL_Reg
{
public luaL_Reg(CharPtr name, lua_CFunction func)
{
this.name = name;
this.func = func;
}
public CharPtr name;
public lua_CFunction func;
};
/*
** ===============================================================
** some useful macros
** ===============================================================
*/
public static void luaL_argcheck(LuaState L, bool cond, int numarg, string extramsg)
{
if (!cond)
luaL_argerror(L, numarg, extramsg);
}
public static CharPtr luaL_checkstring(LuaState L, int n) { return luaL_checklstring(L, n); }
public static CharPtr luaL_optstring(LuaState L, int n, CharPtr d) { uint len; return luaL_optlstring(L, n, d, out len); }
public static int luaL_checkint(LuaState L, int n) { return (int)luaL_checkinteger(L, n); }
public static int luaL_optint(LuaState L, int n, lua_Integer d) { return (int)luaL_optinteger(L, n, d); }
public static long luaL_checklong(LuaState L, int n) { return luaL_checkinteger(L, n); }
public static long luaL_optlong(LuaState L, int n, lua_Integer d) { return luaL_optinteger(L, n, d); }
public static CharPtr luaL_typename(LuaState L, int i) { return lua_typename(L, lua_type(L, i)); }
//#define luaL_dofile(L, fn) \
// (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))
//#define luaL_dostring(L, s) \
// (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0))
public static void luaL_getmetatable(LuaState L, CharPtr n) { lua_getfield(L, LUA_REGISTRYINDEX, n); }
public delegate T luaL_opt_delegate<T>(LuaState L, int narg);
public static T luaL_opt<T>(LuaState L, luaL_opt_delegate<T> f, int n, T d)
{
return lua_isnoneornil(L, n) ? d : f(L, n);
}
public delegate lua_Integer luaL_opt_delegate_integer(LuaState L, int narg);
public static lua_Integer luaL_opt_integer(LuaState L, luaL_opt_delegate_integer f, int n, lua_Number d)
{
return (lua_Integer)(lua_isnoneornil(L, n) ? d : f(L, (n)));
}
/*
** {======================================================
** Generic Buffer manipulation
** =======================================================
*/
public class luaL_Buffer
{
public int p; /* current position in buffer */
public int lvl; /* number of strings in the stack (level) */
public LuaState L;
public CharPtr buffer = new char[LUAL_BUFFERSIZE];
};
public static void luaL_addchar(luaL_Buffer B, char c)
{
if (B.p >= LUAL_BUFFERSIZE)
luaL_prepbuffer(B);
B.buffer[B.p++] = c;
}
///* compatibility only */
public static void luaL_putchar(luaL_Buffer B, char c) { luaL_addchar(B, c); }
public static void luaL_addsize(luaL_Buffer B, int n) { B.p += n; }
/* }====================================================== */
/* compatibility with ref system */
/* pre-defined references */
public const int LUA_NOREF = (-2);
public const int LUA_REFNIL = (-1);
//#define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \
// (lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0))
//#define lua_unref(L,ref) luaL_unref(L, LUA_REGISTRYINDEX, (ref))
//#define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, (ref))
//#define luaL_reg luaL_Reg
/* This file uses only the official API of Lua.
** Any function declared here could be written as an application function.
*/
//#define lauxlib_c
//#define LUA_LIB
public const int FREELIST_REF = 0; /* free list of references */
/* convert a stack index to positive */
public static int abs_index(LuaState L, int i)
{
return ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : lua_gettop(L) + (i) + 1);
}
/*
** {======================================================
** Error-report functions
** =======================================================
*/
public static int luaL_argerror(LuaState L, int narg, CharPtr extramsg)
{
lua_Debug ar = new lua_Debug();
if (lua_getstack(L, 0, ar) == 0) /* no stack frame? */
return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
lua_getinfo(L, "n", ar);
if (strcmp(ar.namewhat, "method") == 0)
{
narg--; /* do not count `self' */
if (narg == 0) /* error is in the self argument itself? */
return luaL_error(L, "calling " + LUA_QS + " on bad self ({1})",
ar.name, extramsg);
}
if (ar.name == null)
ar.name = "?";
return luaL_error(L, "bad argument #%d to " + LUA_QS + " (%s)",
narg, ar.name, extramsg);
}
public static int luaL_typerror(LuaState L, int narg, CharPtr tname)
{
CharPtr msg = lua_pushfstring(L, "%s expected, got %s",
tname, luaL_typename(L, narg));
return luaL_argerror(L, narg, msg);
}
private static void tag_error(LuaState L, int narg, int tag)
{
luaL_typerror(L, narg, lua_typename(L, tag));
}
public static void luaL_where(LuaState L, int level)
{
lua_Debug ar = new lua_Debug();
if (lua_getstack(L, level, ar) != 0)
{ /* check function at level */
lua_getinfo(L, "Sl", ar); /* get info about it */
if (ar.currentline > 0)
{ /* is there info? */
lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
return;
}
}
lua_pushliteral(L, ""); /* else, no information available... */
}
public static int luaL_error(LuaState L, CharPtr fmt, params object[] p)
{
luaL_where(L, 1);
lua_pushvfstring(L, fmt, p);
lua_concat(L, 2);
return lua_error(L);
}
/* }====================================================== */
public static int luaL_checkoption(LuaState L, int narg, CharPtr def,
CharPtr[] lst)
{
CharPtr name = (def != null) ? luaL_optstring(L, narg, def) :
luaL_checkstring(L, narg);
int i;
for (i = 0; i < lst.Length; i++)
if (strcmp(lst[i], name) == 0)
return i;
return luaL_argerror(L, narg,
lua_pushfstring(L, "invalid option " + LUA_QS, name));
}
public static int luaL_newmetatable(LuaState L, CharPtr tname)
{
lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */
if (!lua_isnil(L, -1)) /* name already in use? */
return 0; /* leave previous value on top, but return 0 */
lua_pop(L, 1);
lua_newtable(L); /* create metatable */
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
return 1;
}
public static object luaL_checkudata(LuaState L, int ud, CharPtr tname)
{
object p = lua_touserdata(L, ud);
if (p != null)
{ /* value is a userdata? */
if (lua_getmetatable(L, ud) != 0)
{ /* does it have a metatable? */
lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */
if (lua_rawequal(L, -1, -2) != 0)
{ /* does it have the correct mt? */
lua_pop(L, 2); /* remove both metatables */
return p;
}
}
}
luaL_typerror(L, ud, tname); /* else error */
return null; /* to avoid warnings */
}
public static void luaL_checkstack(LuaState L, int space, CharPtr mes)
{
if (lua_checkstack(L, space) == 0)
luaL_error(L, "stack overflow (%s)", mes);
}
public static void luaL_checktype(LuaState L, int narg, int t)
{
if (lua_type(L, narg) != t)
tag_error(L, narg, t);
}
public static void luaL_checkany(LuaState L, int narg)
{
if (lua_type(L, narg) == LUA_TNONE)
luaL_argerror(L, narg, "value expected");
}
public static CharPtr luaL_checklstring(LuaState L, int narg) { uint len; return luaL_checklstring(L, narg, out len); }
public static CharPtr luaL_checklstring(LuaState L, int narg, out uint len)
{
CharPtr s = lua_tolstring(L, narg, out len);
if (s == null) tag_error(L, narg, LUA_TSTRING);
return s;
}
public static CharPtr luaL_optlstring(LuaState L, int narg, CharPtr def)
{
uint len; return luaL_optlstring(L, narg, def, out len);
}
public static CharPtr luaL_optlstring(LuaState L, int narg, CharPtr def, out uint len)
{
if (lua_isnoneornil(L, narg))
{
len = (uint)((def != null) ? strlen(def) : 0);
return def;
}
else return luaL_checklstring(L, narg, out len);
}
public static lua_Number luaL_checknumber(LuaState L, int narg)
{
lua_Number d = lua_tonumber(L, narg);
if ((d == 0) && (lua_isnumber(L, narg) == 0)) /* avoid extra test when d is not 0 */
tag_error(L, narg, LUA_TNUMBER);
return d;
}
public static lua_Number luaL_optnumber(LuaState L, int narg, lua_Number def)
{
return luaL_opt(L, luaL_checknumber, narg, def);
}
public static lua_Integer luaL_checkinteger(LuaState L, int narg)
{
lua_Integer d = lua_tointeger(L, narg);
if (d == 0 && lua_isnumber(L, narg) == 0) /* avoid extra test when d is not 0 */
tag_error(L, narg, LUA_TNUMBER);
return d;
}
public static lua_Integer luaL_optinteger(LuaState L, int narg, lua_Integer def)
{
return luaL_opt_integer(L, luaL_checkinteger, narg, def);
}
public static int luaL_getmetafield(LuaState L, int obj, CharPtr event_)
{
if (lua_getmetatable(L, obj) == 0) /* no metatable? */
return 0;
lua_pushstring(L, event_);
lua_rawget(L, -2);
if (lua_isnil(L, -1))
{
lua_pop(L, 2); /* remove metatable and metafield */
return 0;
}
else
{
lua_remove(L, -2); /* remove only metatable */
return 1;
}
}
public static int luaL_callmeta(LuaState L, int obj, CharPtr event_)
{
obj = abs_index(L, obj);
if (luaL_getmetafield(L, obj, event_) == 0) /* no metafield? */
return 0;
lua_pushvalue(L, obj);
lua_call(L, 1, 1);
return 1;
}
public static void luaL_register(LuaState L, CharPtr libname,
luaL_Reg[] l)
{
luaI_openlib(L, libname, l, 0);
}
// we could just take the .Length member here, but let's try
// to keep it as close to the C implementation as possible.
private static int libsize(luaL_Reg[] l)
{
int size = 0;
for (; l[size].name != null; size++) ;
return size;
}
public static void luaI_openlib(LuaState L, CharPtr libname,
luaL_Reg[] l, int nup)
{
if (libname != null)
{
int size = libsize(l);
/* check whether lib already exists */
luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);
lua_getfield(L, -1, libname); /* get _LOADED[libname] */
if (!lua_istable(L, -1))
{ /* not found? */
lua_pop(L, 1); /* remove previous result */
/* try global variable (and create one if it does not exist) */
if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != null)
luaL_error(L, "name conflict for module " + LUA_QS, libname);
lua_pushvalue(L, -1);
lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */
}
lua_remove(L, -2); /* remove _LOADED table */
lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
}
int reg_num = 0;
for (; l[reg_num].name != null; reg_num++)
{
int i;
for (i = 0; i < nup; i++) /* copy upvalues to the top */
lua_pushvalue(L, -nup);
lua_pushcclosure(L, l[reg_num].func, nup);
lua_setfield(L, -(nup + 2), l[reg_num].name);
}
lua_pop(L, nup); /* remove upvalues */
}
/*
** {======================================================
** getn-setn: size for arrays
** =======================================================
*/
#if LUA_COMPAT_GETN
static int checkint (lua_State L, int topop) {
int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1;
lua_pop(L, topop);
return n;
}
static void getsizes (lua_State L) {
lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES");
if (lua_isnil(L, -1)) { /* no `size' table? */
lua_pop(L, 1); /* remove nil */
lua_newtable(L); /* create it */
lua_pushvalue(L, -1); /* `size' will be its own metatable */
lua_setmetatable(L, -2);
lua_pushliteral(L, "kv");
lua_setfield(L, -2, "__mode"); /* metatable(N).__mode = "kv" */
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); /* store in register */
}
}
public static void luaL_setn (lua_State L, int t, int n) {
t = abs_index(L, t);
lua_pushliteral(L, "n");
lua_rawget(L, t);
if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */
lua_pushliteral(L, "n"); /* use it */
lua_pushinteger(L, n);
lua_rawset(L, t);
}
else { /* use `sizes' */
getsizes(L);
lua_pushvalue(L, t);
lua_pushinteger(L, n);
lua_rawset(L, -3); /* sizes[t] = n */
lua_pop(L, 1); /* remove `sizes' */
}
}
public static int luaL_getn (lua_State L, int t) {
int n;
t = abs_index(L, t);
lua_pushliteral(L, "n"); /* try t.n */
lua_rawget(L, t);
if ((n = checkint(L, 1)) >= 0) return n;
getsizes(L); /* else try sizes[t] */
lua_pushvalue(L, t);
lua_rawget(L, -2);
if ((n = checkint(L, 2)) >= 0) return n;
return (int)lua_objlen(L, t);
}
#endif
/* }====================================================== */
public static CharPtr luaL_gsub(LuaState L, CharPtr s, CharPtr p,
CharPtr r)
{
CharPtr wild;
uint l = (uint)strlen(p);
luaL_Buffer b = new luaL_Buffer();
luaL_buffinit(L, b);
while ((wild = strstr(s, p)) != null)
{
luaL_addlstring(b, s, (uint)(wild - s)); /* push prefix */
luaL_addstring(b, r); /* push replacement in place of pattern */
s = wild + l; /* continue after `p' */
}
luaL_addstring(b, s); /* push last suffix */
luaL_pushresult(b);
return lua_tostring(L, -1);
}
public static CharPtr luaL_findtable(LuaState L, int idx,
CharPtr fname, int szhint)
{
CharPtr e;
lua_pushvalue(L, idx);
do
{
e = strchr(fname, '.');
if (e == null) e = fname + strlen(fname);
lua_pushlstring(L, fname, (uint)(e - fname));
lua_rawget(L, -2);
if (lua_isnil(L, -1))
{ /* no such field? */
lua_pop(L, 1); /* remove this nil */
lua_createtable(L, 0, (e == '.' ? 1 : szhint)); /* new table for field */
lua_pushlstring(L, fname, (uint)(e - fname));
lua_pushvalue(L, -2);
lua_settable(L, -4); /* set new table into field */
}
else if (!lua_istable(L, -1))
{ /* field has a non-table value? */
lua_pop(L, 2); /* remove table and value */
return fname; /* return problematic part of the name */
}
lua_remove(L, -2); /* remove previous table */
fname = e + 1;
} while (e == '.');
return null;
}
/*
** {======================================================
** Generic Buffer manipulation
** =======================================================
*/
private static int bufflen(luaL_Buffer B) { return B.p; }
private static int bufffree(luaL_Buffer B) { return LUAL_BUFFERSIZE - bufflen(B); }
public const int LIMIT = LUA_MINSTACK / 2;
private static int emptybuffer(luaL_Buffer B)
{
uint l = (uint)bufflen(B);
if (l == 0) return 0; /* put nothing on stack */
else
{
lua_pushlstring(B.L, B.buffer, l);
B.p = 0;
B.lvl++;
return 1;
}
}
private static void adjuststack(luaL_Buffer B)
{
if (B.lvl > 1)
{
LuaState L = B.L;
int toget = 1; /* number of levels to concat */
uint toplen = lua_strlen(L, -1);
do
{
uint l = lua_strlen(L, -(toget + 1));
if (B.lvl - toget + 1 >= LIMIT || toplen > l)
{
toplen += l;
toget++;
}
else break;
} while (toget < B.lvl);
lua_concat(L, toget);
B.lvl = B.lvl - toget + 1;
}
}
public static CharPtr luaL_prepbuffer(luaL_Buffer B)
{
if (emptybuffer(B) != 0)
adjuststack(B);
return new CharPtr(B.buffer, B.p);
}
public static void luaL_addlstring(luaL_Buffer B, CharPtr s, uint l)
{
while (l-- != 0)
{
char c = s[0];
s = s.next();
luaL_addchar(B, c);
}
}
public static void luaL_addstring(luaL_Buffer B, CharPtr s)
{
luaL_addlstring(B, s, (uint)strlen(s));
}
public static void luaL_pushresult(luaL_Buffer B)
{
emptybuffer(B);
lua_concat(B.L, B.lvl);
B.lvl = 1;
}
public static void luaL_addvalue(luaL_Buffer B)
{
LuaState L = B.L;
uint vl;
CharPtr s = lua_tolstring(L, -1, out vl);
if (vl <= bufffree(B))
{ /* fit into buffer? */
CharPtr dst = new CharPtr(B.buffer.chars, B.buffer.index + B.p);
CharPtr src = new CharPtr(s.chars, s.index);
for (uint i = 0; i < vl; i++)
dst[i] = src[i];
B.p += (int)vl;
lua_pop(L, 1); /* remove from stack */
}
else
{
if (emptybuffer(B) != 0)
lua_insert(L, -2); /* put buffer before new value */
B.lvl++; /* add new value into B stack */
adjuststack(B);
}
}
public static void luaL_buffinit(LuaState L, luaL_Buffer B)
{
B.L = L;
B.p = /*B.buffer*/ 0;
B.lvl = 0;
}
/* }====================================================== */
public static int luaL_ref(LuaState L, int t)
{
int ref_;
t = abs_index(L, t);
if (lua_isnil(L, -1))
{
lua_pop(L, 1); /* remove from stack */
return LUA_REFNIL; /* `nil' has a unique fixed reference */
}
lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
ref_ = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */
lua_pop(L, 1); /* remove it from stack */
if (ref_ != 0)
{ /* any free element? */
lua_rawgeti(L, t, ref_); /* remove it from list */
lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
}
else
{ /* no free elements */
ref_ = (int)lua_objlen(L, t);
ref_++; /* create new reference */
}
lua_rawseti(L, t, ref_);
return ref_;
}
public static void luaL_unref(LuaState L, int t, int ref_)
{
if (ref_ >= 0)
{
t = abs_index(L, t);
lua_rawgeti(L, t, FREELIST_REF);
lua_rawseti(L, t, ref_); /* t[ref] = t[FREELIST_REF] */
lua_pushinteger(L, ref_);
lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
}
}
/*
** {======================================================
** Load functions
** =======================================================
*/
public class LoadF
{
public int extraline;
public Stream f;
public CharPtr buff = new char[LUAL_BUFFERSIZE];
};
public static CharPtr getF(LuaState L, object ud, out uint size)
{
size = 0;
LoadF lf = (LoadF)ud;
//(void)L;
if (lf.extraline != 0)
{
lf.extraline = 0;
size = 1;
return "\n";
}
if (feof(lf.f) != 0) return null;
size = (uint)fread(lf.buff, 1, lf.buff.chars.Length, lf.f);
return (size > 0) ? new CharPtr(lf.buff) : null;
}
private static int errfile(LuaState L, CharPtr what, int fnameindex)
{
CharPtr serr = strerror(errno);
CharPtr filename = lua_tostring(L, fnameindex) + 1;
lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
lua_remove(L, fnameindex);
return LUA_ERRFILE;
}
public static int luaL_loadfile(LuaState L, CharPtr filename)
{
LoadF lf = new LoadF();
int status, readstatus;
int c;
int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
lf.extraline = 0;
if (filename == null)
{
lua_pushliteral(L, "=stdin");
lf.f = stdin;
}
else
{
lua_pushfstring(L, "@%s", filename);
lf.f = fopen(filename, "r");
if (lf.f == null)
return errfile(L, "open", fnameindex);
}
c = getc(lf.f);
if (c == '#')
{ /* Unix exec. file? */
lf.extraline = 1;
while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */
if (c == '\n') c = getc(lf.f);
}
if (c == LUA_SIGNATURE[0] && (filename != null))
{ /* binary file? */
lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
if (lf.f == null)
return errfile(L, "reopen", fnameindex);
/* skip eventual `#!...' */
while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0])
; // do nothing here
lf.extraline = 0;
}
ungetc(c, lf.f);
status = lua_load(L, getF, lf, lua_tostring(L, -1));
readstatus = ferror(lf.f);
if (filename != null)
fclose(lf.f); /* close file (even in case of errors) */
if (readstatus != 0)
{
lua_settop(L, fnameindex); /* ignore results from `lua_load' */
return errfile(L, "read", fnameindex);
}
lua_remove(L, fnameindex);
return status;
}
public class LoadS
{
public CharPtr s;
public uint size;
};
static CharPtr getS(LuaState L, object ud, out uint size)
{
LoadS ls = (LoadS)ud;
//(void)L;
if (ls.size == 0)
{
size = 0;
return null;
}
size = ls.size;
ls.size = 0;
return ls.s;
}
public static int luaL_loadbuffer(LuaState L, CharPtr buff, uint size,
CharPtr name)
{
LoadS ls = new LoadS();
ls.s = new CharPtr(buff);
ls.size = size;
return lua_load(L, getS, ls, name);
}
public static int luaL_loadstring(LuaState L, CharPtr s)
{
return luaL_loadbuffer(L, s, (uint)strlen(s), s);
}
/* }====================================================== */
private static object l_alloc(Type t)
{
return System.Activator.CreateInstance(t);
}
private static int panic(LuaState L)
{
//(void)L; /* to avoid warnings */
fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n",
lua_tostring(L, -1));
return 0;
}
public static LuaState luaL_newstate()
{
LuaState L = lua_newstate(l_alloc, null);
if (L != null)
{
L.initializing = true;
lua_atpanic(L, panic);
L.initializing = false;
}
return L;
}
}
}
| |
namespace Azure.ResourceManager.AppConfiguration
{
public partial class AppConfigurationManagementClient
{
protected AppConfigurationManagementClient() { }
public AppConfigurationManagementClient(string subscriptionId, Azure.Core.TokenCredential tokenCredential, Azure.ResourceManager.AppConfiguration.AppConfigurationManagementClientOptions options = null) { }
public AppConfigurationManagementClient(string subscriptionId, System.Uri endpoint, Azure.Core.TokenCredential tokenCredential, Azure.ResourceManager.AppConfiguration.AppConfigurationManagementClientOptions options = null) { }
public virtual Azure.ResourceManager.AppConfiguration.ConfigurationStoresOperations ConfigurationStores { get { throw null; } }
public virtual Azure.ResourceManager.AppConfiguration.Operations Operations { get { throw null; } }
public virtual Azure.ResourceManager.AppConfiguration.PrivateEndpointConnectionsOperations PrivateEndpointConnections { get { throw null; } }
public virtual Azure.ResourceManager.AppConfiguration.PrivateLinkResourcesOperations PrivateLinkResources { get { throw null; } }
}
public partial class AppConfigurationManagementClientOptions : Azure.Core.ClientOptions
{
public AppConfigurationManagementClientOptions() { }
}
public partial class ConfigurationStoresCreateOperation : Azure.Operation<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>
{
protected ConfigurationStoresCreateOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class ConfigurationStoresDeleteOperation : Azure.Operation<Azure.Response>
{
protected ConfigurationStoresDeleteOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.Response Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class ConfigurationStoresOperations
{
protected ConfigurationStoresOperations() { }
public virtual Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore> Get(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>> GetAsync(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore> List(string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore> ListAsync(string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore> ListByResourceGroup(string resourceGroupName, string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore> ListByResourceGroupAsync(string resourceGroupName, string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.AppConfiguration.Models.ApiKey> ListKeys(string resourceGroupName, string configStoreName, string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.AppConfiguration.Models.ApiKey> ListKeysAsync(string resourceGroupName, string configStoreName, string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.AppConfiguration.Models.KeyValue> ListKeyValue(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.ListKeyValueParameters listKeyValueParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.KeyValue>> ListKeyValueAsync(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.ListKeyValueParameters listKeyValueParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ApiKey> RegenerateKey(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.RegenerateKeyParameters regenerateKeyParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ApiKey>> RegenerateKeyAsync(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.RegenerateKeyParameters regenerateKeyParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.AppConfiguration.ConfigurationStoresCreateOperation StartCreate(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore configStoreCreationParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.AppConfiguration.ConfigurationStoresCreateOperation> StartCreateAsync(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore configStoreCreationParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.AppConfiguration.ConfigurationStoresDeleteOperation StartDelete(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.AppConfiguration.ConfigurationStoresDeleteOperation> StartDeleteAsync(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.AppConfiguration.ConfigurationStoresUpdateOperation StartUpdate(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.ConfigurationStoreUpdateParameters configStoreUpdateParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.AppConfiguration.ConfigurationStoresUpdateOperation> StartUpdateAsync(string resourceGroupName, string configStoreName, Azure.ResourceManager.AppConfiguration.Models.ConfigurationStoreUpdateParameters configStoreUpdateParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class ConfigurationStoresUpdateOperation : Azure.Operation<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>
{
protected ConfigurationStoresUpdateOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.ConfigurationStore>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class Operations
{
protected Operations() { }
public virtual Azure.Response<Azure.ResourceManager.AppConfiguration.Models.NameAvailabilityStatus> CheckNameAvailability(Azure.ResourceManager.AppConfiguration.Models.CheckNameAvailabilityParameters checkNameAvailabilityParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.NameAvailabilityStatus>> CheckNameAvailabilityAsync(Azure.ResourceManager.AppConfiguration.Models.CheckNameAvailabilityParameters checkNameAvailabilityParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.AppConfiguration.Models.OperationDefinition> List(string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.AppConfiguration.Models.OperationDefinition> ListAsync(string skipToken = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class PrivateEndpointConnectionsCreateOrUpdateOperation : Azure.Operation<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection>
{
protected PrivateEndpointConnectionsCreateOrUpdateOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class PrivateEndpointConnectionsDeleteOperation : Azure.Operation<Azure.Response>
{
protected PrivateEndpointConnectionsDeleteOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.Response Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class PrivateEndpointConnectionsOperations
{
protected PrivateEndpointConnectionsOperations() { }
public virtual Azure.Response<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection> Get(string resourceGroupName, string configStoreName, string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection>> GetAsync(string resourceGroupName, string configStoreName, string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection> ListByConfigurationStore(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection> ListByConfigurationStoreAsync(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.AppConfiguration.PrivateEndpointConnectionsCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string configStoreName, string privateEndpointConnectionName, Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection privateEndpointConnection, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.AppConfiguration.PrivateEndpointConnectionsCreateOrUpdateOperation> StartCreateOrUpdateAsync(string resourceGroupName, string configStoreName, string privateEndpointConnectionName, Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnection privateEndpointConnection, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.AppConfiguration.PrivateEndpointConnectionsDeleteOperation StartDelete(string resourceGroupName, string configStoreName, string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.AppConfiguration.PrivateEndpointConnectionsDeleteOperation> StartDeleteAsync(string resourceGroupName, string configStoreName, string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class PrivateLinkResourcesOperations
{
protected PrivateLinkResourcesOperations() { }
public virtual Azure.Response<Azure.ResourceManager.AppConfiguration.Models.PrivateLinkResource> Get(string resourceGroupName, string configStoreName, string groupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.AppConfiguration.Models.PrivateLinkResource>> GetAsync(string resourceGroupName, string configStoreName, string groupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.AppConfiguration.Models.PrivateLinkResource> ListByConfigurationStore(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.AppConfiguration.Models.PrivateLinkResource> ListByConfigurationStoreAsync(string resourceGroupName, string configStoreName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
}
namespace Azure.ResourceManager.AppConfiguration.Models
{
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ActionsRequired : System.IEquatable<Azure.ResourceManager.AppConfiguration.Models.ActionsRequired>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public ActionsRequired(string value) { throw null; }
public static Azure.ResourceManager.AppConfiguration.Models.ActionsRequired None { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ActionsRequired Recreate { get { throw null; } }
public bool Equals(Azure.ResourceManager.AppConfiguration.Models.ActionsRequired other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.AppConfiguration.Models.ActionsRequired left, Azure.ResourceManager.AppConfiguration.Models.ActionsRequired right) { throw null; }
public static implicit operator Azure.ResourceManager.AppConfiguration.Models.ActionsRequired (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.AppConfiguration.Models.ActionsRequired left, Azure.ResourceManager.AppConfiguration.Models.ActionsRequired right) { throw null; }
public override string ToString() { throw null; }
}
public partial class ApiKey
{
internal ApiKey() { }
public string ConnectionString { get { throw null; } }
public string Id { get { throw null; } }
public System.DateTimeOffset? LastModified { get { throw null; } }
public string Name { get { throw null; } }
public bool? ReadOnly { get { throw null; } }
public string Value { get { throw null; } }
}
public partial class CheckNameAvailabilityParameters
{
public CheckNameAvailabilityParameters(string name, Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType type) { }
public string Name { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType Type { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ConfigurationResourceType : System.IEquatable<Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public ConfigurationResourceType(string value) { throw null; }
public static Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType MicrosoftAppConfigurationConfigurationStores { get { throw null; } }
public bool Equals(Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType left, Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType right) { throw null; }
public static implicit operator Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType left, Azure.ResourceManager.AppConfiguration.Models.ConfigurationResourceType right) { throw null; }
public override string ToString() { throw null; }
}
public partial class ConfigurationStore : Azure.ResourceManager.AppConfiguration.Models.Resource
{
public ConfigurationStore(string location, Azure.ResourceManager.AppConfiguration.Models.Sku sku) : base (default(string)) { }
public System.DateTimeOffset? CreationDate { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.EncryptionProperties Encryption { get { throw null; } set { } }
public string Endpoint { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.ResourceIdentity Identity { get { throw null; } set { } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.AppConfiguration.Models.PrivateEndpointConnectionReference> PrivateEndpointConnections { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.ProvisioningState? ProvisioningState { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess? PublicNetworkAccess { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.Sku Sku { get { throw null; } set { } }
}
public partial class ConfigurationStoreUpdateParameters
{
public ConfigurationStoreUpdateParameters() { }
public Azure.ResourceManager.AppConfiguration.Models.EncryptionProperties Encryption { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.ResourceIdentity Identity { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess? PublicNetworkAccess { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.Sku Sku { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ConnectionStatus : System.IEquatable<Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public ConnectionStatus(string value) { throw null; }
public static Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus Approved { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus Disconnected { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus Pending { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus Rejected { get { throw null; } }
public bool Equals(Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus left, Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus right) { throw null; }
public static implicit operator Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus left, Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus right) { throw null; }
public override string ToString() { throw null; }
}
public partial class EncryptionProperties
{
public EncryptionProperties() { }
public Azure.ResourceManager.AppConfiguration.Models.KeyVaultProperties KeyVaultProperties { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct IdentityType : System.IEquatable<Azure.ResourceManager.AppConfiguration.Models.IdentityType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public IdentityType(string value) { throw null; }
public static Azure.ResourceManager.AppConfiguration.Models.IdentityType None { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.IdentityType SystemAssigned { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.IdentityType SystemAssignedUserAssigned { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.IdentityType UserAssigned { get { throw null; } }
public bool Equals(Azure.ResourceManager.AppConfiguration.Models.IdentityType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.AppConfiguration.Models.IdentityType left, Azure.ResourceManager.AppConfiguration.Models.IdentityType right) { throw null; }
public static implicit operator Azure.ResourceManager.AppConfiguration.Models.IdentityType (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.AppConfiguration.Models.IdentityType left, Azure.ResourceManager.AppConfiguration.Models.IdentityType right) { throw null; }
public override string ToString() { throw null; }
}
public partial class KeyValue
{
internal KeyValue() { }
public string ContentType { get { throw null; } }
public string ETag { get { throw null; } }
public string Key { get { throw null; } }
public string Label { get { throw null; } }
public System.DateTimeOffset? LastModified { get { throw null; } }
public bool? Locked { get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, string> Tags { get { throw null; } }
public string Value { get { throw null; } }
}
public partial class KeyVaultProperties
{
public KeyVaultProperties() { }
public string IdentityClientId { get { throw null; } set { } }
public string KeyIdentifier { get { throw null; } set { } }
}
public partial class ListKeyValueParameters
{
public ListKeyValueParameters(string key) { }
public string Key { get { throw null; } }
public string Label { get { throw null; } set { } }
}
public partial class NameAvailabilityStatus
{
internal NameAvailabilityStatus() { }
public string Message { get { throw null; } }
public bool? NameAvailable { get { throw null; } }
public string Reason { get { throw null; } }
}
public partial class OperationDefinition
{
internal OperationDefinition() { }
public Azure.ResourceManager.AppConfiguration.Models.OperationDefinitionDisplay Display { get { throw null; } }
public string Name { get { throw null; } }
}
public partial class OperationDefinitionDisplay
{
internal OperationDefinitionDisplay() { }
public string Description { get { throw null; } }
public string Operation { get { throw null; } }
public string Provider { get { throw null; } }
public string Resource { get { throw null; } }
}
public partial class PrivateEndpoint
{
public PrivateEndpoint() { }
public string Id { get { throw null; } set { } }
}
public partial class PrivateEndpointConnection
{
public PrivateEndpointConnection() { }
public string Id { get { throw null; } }
public string Name { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.PrivateEndpoint PrivateEndpoint { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.PrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.ProvisioningState? ProvisioningState { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class PrivateEndpointConnectionReference
{
internal PrivateEndpointConnectionReference() { }
public string Id { get { throw null; } }
public string Name { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.PrivateEndpoint PrivateEndpoint { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.PrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.ProvisioningState? ProvisioningState { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class PrivateLinkResource
{
internal PrivateLinkResource() { }
public string GroupId { get { throw null; } }
public string Id { get { throw null; } }
public string Name { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> RequiredMembers { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> RequiredZoneNames { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class PrivateLinkServiceConnectionState
{
public PrivateLinkServiceConnectionState() { }
public Azure.ResourceManager.AppConfiguration.Models.ActionsRequired? ActionsRequired { get { throw null; } }
public string Description { get { throw null; } set { } }
public Azure.ResourceManager.AppConfiguration.Models.ConnectionStatus? Status { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ProvisioningState : System.IEquatable<Azure.ResourceManager.AppConfiguration.Models.ProvisioningState>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public ProvisioningState(string value) { throw null; }
public static Azure.ResourceManager.AppConfiguration.Models.ProvisioningState Canceled { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ProvisioningState Creating { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ProvisioningState Deleting { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ProvisioningState Failed { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ProvisioningState Succeeded { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.ProvisioningState Updating { get { throw null; } }
public bool Equals(Azure.ResourceManager.AppConfiguration.Models.ProvisioningState other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.AppConfiguration.Models.ProvisioningState left, Azure.ResourceManager.AppConfiguration.Models.ProvisioningState right) { throw null; }
public static implicit operator Azure.ResourceManager.AppConfiguration.Models.ProvisioningState (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.AppConfiguration.Models.ProvisioningState left, Azure.ResourceManager.AppConfiguration.Models.ProvisioningState right) { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct PublicNetworkAccess : System.IEquatable<Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public PublicNetworkAccess(string value) { throw null; }
public static Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess Disabled { get { throw null; } }
public static Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess Enabled { get { throw null; } }
public bool Equals(Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess left, Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess right) { throw null; }
public static implicit operator Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess (string value) { throw null; }
public static bool operator !=(Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess left, Azure.ResourceManager.AppConfiguration.Models.PublicNetworkAccess right) { throw null; }
public override string ToString() { throw null; }
}
public partial class RegenerateKeyParameters
{
public RegenerateKeyParameters() { }
public string Id { get { throw null; } set { } }
}
public partial class Resource
{
public Resource(string location) { }
public string Id { get { throw null; } }
public string Location { get { throw null; } set { } }
public string Name { get { throw null; } }
public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class ResourceIdentity
{
public ResourceIdentity() { }
public string PrincipalId { get { throw null; } }
public string TenantId { get { throw null; } }
public Azure.ResourceManager.AppConfiguration.Models.IdentityType? Type { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, Azure.ResourceManager.AppConfiguration.Models.UserIdentity> UserAssignedIdentities { get { throw null; } }
}
public partial class Sku
{
public Sku(string name) { }
public string Name { get { throw null; } set { } }
}
public partial class UserIdentity
{
public UserIdentity() { }
public string ClientId { get { throw null; } }
public string PrincipalId { get { throw null; } }
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.PythonTools.Infrastructure;
namespace Microsoft.PythonTools.Interpreter {
public struct PackageVersion : IComparable<PackageVersion>, IEquatable<PackageVersion> {
public static readonly PackageVersion Empty = new PackageVersion(new int[0]);
private static readonly Regex LocalVersionRegex = new Regex(@"^[a-zA-Z0-9][a-zA-Z0-9.]*(?<=[a-zA-Z0-9])$");
private static readonly Regex FullVersionRegex = new Regex(@"^
v?
((?<epoch>\d+)!)?
(?<release>\d+(\.\d+)*)
([.\-_]?(?<preName>a|alpha|b|beta|rc|c|pre|preview)[.\-_]?(?<pre>\d+)?)?
([.\-_]?(post|rev|r)[.\-_]?(?<post>\d+)?|-(?<post>\d+))?
([.\-_]?dev[.\-_]?(?<dev>\d+))?
(\+(?<local>[a-zA-Z0-9][a-zA-Z0-9.\-_]*(?<=[a-zA-Z0-9])))?
$", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private string _normalized;
private PackageVersion(
IEnumerable<int> release,
int epoch = 0,
PackageVersionPreReleaseName preReleaseName = PackageVersionPreReleaseName.None,
int preRelease = 0,
int postRelease = 0,
int devRelease = 0,
string localVersion = null,
string originalForm = null
) : this() {
_normalized = null;
Epoch = epoch;
Release = release.ToArray();
PreReleaseName = preReleaseName;
PreRelease = preReleaseName != PackageVersionPreReleaseName.None ? preRelease : 0;
PostRelease = postRelease;
DevRelease = devRelease;
LocalVersion = localVersion;
OriginalForm = originalForm;
}
public int Epoch { get; set; }
public IList<int> Release { get; private set; }
public PackageVersionPreReleaseName PreReleaseName { get; set; }
public int PreRelease { get; set; }
public int PostRelease { get; set; }
public int DevRelease { get; set; }
public string LocalVersion { get; set; }
public string OriginalForm { get; set; }
public bool IsEmpty => Release == null || Release.Count == 0;
public bool IsFinalRelease {
get {
return PreReleaseName == PackageVersionPreReleaseName.None &&
DevRelease == 0 &&
string.IsNullOrEmpty(LocalVersion);
}
}
private bool Validate(out Exception error) {
error = null;
if (Epoch < 0) {
error = new FormatException("Epoch must be 0 or greater");
return false;
}
if (Release != null && Release.Any(i => i < 0)) {
error = new FormatException("All components of Release must be 0 or greater");
return false;
}
if (PreReleaseName == PackageVersionPreReleaseName.None) {
if (PreRelease != 0) {
error = new FormatException("PreRelease must be 0 when PreReleaseName is None");
return false;
}
} else {
if (PreRelease < 0) {
error = new FormatException("PreRelease must be 0 or greater");
return false;
}
}
if (PostRelease < 0) {
error = new FormatException("PostRelease must be 0 or greater");
return false;
}
if (DevRelease < 0) {
error = new FormatException("DevRelease must be 0 or greater");
return false;
}
if (!string.IsNullOrEmpty(LocalVersion) && !LocalVersionRegex.IsMatch(LocalVersion)) {
error = new FormatException("LocalVersion has invalid characters");
return false;
}
return true;
}
public override string ToString() {
return string.IsNullOrEmpty(OriginalForm) ? NormalizedForm : OriginalForm;
}
public string NormalizedForm {
get {
if (_normalized == null) {
var sb = new StringBuilder();
if (Epoch != 0) {
sb.Append(Epoch);
sb.Append('!');
}
if (Release == null) {
sb.Append("0");
} else {
sb.Append(string.Join(".", Release.Select(i => i.ToString(CultureInfo.InvariantCulture))));
}
if (PreReleaseName != PackageVersionPreReleaseName.None) {
switch (PreReleaseName) {
case PackageVersionPreReleaseName.Alpha:
sb.Append('a');
break;
case PackageVersionPreReleaseName.Beta:
sb.Append('b');
break;
case PackageVersionPreReleaseName.RC:
sb.Append("rc");
break;
default:
Debug.Fail("Unhandled Pep440PreReleaseName value: " + PreReleaseName.ToString());
break;
}
sb.Append(PreRelease);
}
if (PostRelease > 0) {
sb.Append(".post");
sb.Append(PostRelease);
}
if (DevRelease > 0) {
sb.Append(".dev");
sb.Append(DevRelease);
}
if (!string.IsNullOrEmpty(LocalVersion)) {
sb.Append('-');
sb.Append(LocalVersion);
}
_normalized = sb.ToString();
}
return _normalized;
}
}
public override bool Equals(object obj) {
if (obj is PackageVersion) {
return CompareTo((PackageVersion)obj) == 0;
}
return false;
}
public bool Equals(PackageVersion other) {
return CompareTo(other) == 0;
}
public override int GetHashCode() {
return NormalizedForm.GetHashCode();
}
public static bool operator ==(PackageVersion x, PackageVersion y) {
return x.Equals(y);
}
public static bool operator !=(PackageVersion x, PackageVersion y) {
return !x.Equals(y);
}
public int CompareTo(PackageVersion other) {
Exception error;
if (!Validate(out error)) {
throw error;
}
if (!other.Validate(out error)) {
throw new ArgumentException("Invalid version", "other", error);
}
int c = Epoch.CompareTo(other.Epoch);
if (c != 0) {
return c;
}
if (Release != null && other.Release != null) {
for (int i = 0; i < Release.Count || i < other.Release.Count; ++i) {
c = Release.ElementAtOrDefault(i).CompareTo(other.Release.ElementAtOrDefault(i));
if (c != 0) {
return c;
}
}
} else if (Release == null) {
// No release, so we sort earlier if other has one
return other.Release == null ? 0 : -1;
} else {
// We have a release and other doesn't, so we sort later
return 1;
}
if (PreReleaseName != other.PreReleaseName) {
// Regular comparison mishandles None
if (PreReleaseName == PackageVersionPreReleaseName.None) {
return 1;
} else if (other.PreReleaseName == PackageVersionPreReleaseName.None) {
return -1;
}
// Neither value is None, so CompareTo will be correct
return PreReleaseName.CompareTo(other.PreReleaseName);
}
c = PreRelease.CompareTo(other.PreRelease);
if (c != 0) {
return c;
}
c = PostRelease.CompareTo(other.PostRelease);
if (c != 0) {
return c;
}
c = DevRelease.CompareTo(other.DevRelease);
if (c != 0) {
if (DevRelease == 0 || other.DevRelease == 0) {
// When either DevRelease is zero, the sort order needs to
// be reversed.
return -c;
}
return c;
}
if (string.IsNullOrEmpty(LocalVersion)) {
if (string.IsNullOrEmpty(other.LocalVersion)) {
// No local versions, so we are equal
return 0;
}
// other has a local version, so we sort earlier
return -1;
} else if (string.IsNullOrEmpty(other.LocalVersion)) {
// we have a local version, so we sort later
return 1;
}
var lv1 = LocalVersion.Split('.');
var lv2 = other.LocalVersion.Split('.');
for (int i = 0; i < lv1.Length || i < lv2.Length; ++i) {
if (i >= lv1.Length) {
// other has a longer local version, so we sort earlier
return -1;
} else if (i >= lv2.Length) {
// we have a longer local version, so we sort later
return 1;
}
var p1 = lv1[i];
var p2 = lv2[i];
int i1, i2;
if (int.TryParse(p1, NumberStyles.Integer, CultureInfo.InvariantCulture, out i1)) {
if (int.TryParse(p2, NumberStyles.Integer, CultureInfo.InvariantCulture, out i2)) {
c = i1.CompareTo(i2);
} else {
// we have a number and other doesn't, so we sort later
return 1;
}
} else if (int.TryParse(p2, NumberStyles.Integer, CultureInfo.InvariantCulture, out i2)) {
// other has a number and we don't, so we sort earlier
return -1;
} else {
c = string.Compare(p1, p2, StringComparison.OrdinalIgnoreCase);
}
if (c != 0) {
return c;
}
}
// After all that, we are equal!
return 0;
}
public static IEnumerable<PackageVersion> TryParseAll(IEnumerable<string> versions) {
foreach (var s in versions) {
PackageVersion value;
if (TryParse(s, out value)) {
yield return value;
}
}
}
public static bool TryParse(string s, out PackageVersion value) {
Exception error;
return ParseInternal(s, out value, out error);
}
public static PackageVersion? TryParse(string s) {
Exception error;
PackageVersion value;
return ParseInternal(s, out value, out error) ? value : (PackageVersion?)null;
}
public static PackageVersion Parse(string s) {
PackageVersion value;
Exception error;
if (!ParseInternal(s, out value, out error)) {
throw error;
}
return value;
}
private static bool ParseInternal(string s, out PackageVersion value, out Exception error) {
value = default(PackageVersion);
error = null;
if (string.IsNullOrEmpty(s)) {
error = new ArgumentNullException("s");
return false;
}
var trimmed = s.Trim(" \t\n\r\f\v".ToCharArray());
var m = FullVersionRegex.Match(trimmed);
if (!m.Success) {
error = new FormatException(trimmed);
return false;
}
int epoch = 0, pre = 0, dev = 0, post = 0;
string local = null;
var release = new List<int>();
foreach (var v in m.Groups["release"].Value.Split('.')) {
int i;
if (!int.TryParse(v, out i)) {
error = new FormatException("'{0}' is not a valid version".FormatUI(m.Groups["release"].Value));
return false;
}
release.Add(i);
}
if (m.Groups["epoch"].Success) {
if (!int.TryParse(m.Groups["epoch"].Value, out epoch)) {
error = new FormatException("'{0}' is not a number".FormatUI(m.Groups["epoch"].Value));
return false;
}
}
var preName = PackageVersionPreReleaseName.None;
if (m.Groups["preName"].Success) {
switch(m.Groups["preName"].Value.ToLowerInvariant()) {
case "a":
case "alpha":
preName = PackageVersionPreReleaseName.Alpha;
break;
case "b":
case "beta":
preName = PackageVersionPreReleaseName.Beta;
break;
case "rc":
case "c":
case "pre":
case "preview":
preName = PackageVersionPreReleaseName.RC;
break;
default:
error = new FormatException("'{0}' is not a valid prerelease name".FormatUI(preName));
return false;
}
}
if (m.Groups["pre"].Success) {
if (!int.TryParse(m.Groups["pre"].Value, out pre)) {
error = new FormatException("'{0}' is not a number".FormatUI(m.Groups["pre"].Value));
return false;
}
}
if (m.Groups["dev"].Success) {
if (!int.TryParse(m.Groups["dev"].Value, out dev)) {
error = new FormatException("'{0}' is not a number".FormatUI(m.Groups["dev"].Value));
return false;
}
}
if (m.Groups["post"].Success) {
if (!int.TryParse(m.Groups["post"].Value, out post)) {
error = new FormatException("'{0}' is not a number".FormatUI(m.Groups["post"].Value));
return false;
}
}
if (m.Groups["local"].Success) {
local = Regex.Replace(m.Groups["local"].Value, "[^a-zA-Z0-9.]", ".");
}
value = new PackageVersion(
release,
epoch,
preName,
pre,
post,
dev,
local,
s
);
return value.Validate(out error);
}
}
public enum PackageVersionPreReleaseName {
None = 0,
Alpha = 1,
Beta = 2,
RC = 3
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
namespace MLifter.AudioTools.Codecs
{
public partial class CodecSettings : Form
{
Codecs codecs = null;
bool omitsave = false;
/// <summary>
/// Initializes a new instance of the <see cref="CodecSettings"/> class.
/// </summary>
/// <remarks>Documented by Dev02, 2008-04-10</remarks>
public CodecSettings()
{
InitializeComponent();
}
/// <summary>
/// Gets or sets a value indicating whether [show encoder].
/// </summary>
/// <value><c>true</c> if [show encoder]; otherwise, <c>false</c>.</value>
/// <remarks>Documented by Dev02, 2008-04-15</remarks>
public bool ShowEncoder
{
get { return checkBoxShowEncoder.Checked; }
set { checkBoxShowEncoder.Checked = value; }
}
/// <summary>
/// Gets or sets a value indicating whether [show decoder].
/// </summary>
/// <value><c>true</c> if [show decoder]; otherwise, <c>false</c>.</value>
/// <remarks>Documented by Dev02, 2008-04-15</remarks>
public bool ShowDecoder
{
get { return checkBoxShowDecoder.Checked; }
set { checkBoxShowDecoder.Checked = value; }
}
/// <summary>
/// Gets or sets a value indicating whether [minimize windows].
/// </summary>
/// <value><c>true</c> if [minimize windows]; otherwise, <c>false</c>.</value>
/// <remarks>Documented by Dev02, 2008-04-15</remarks>
public bool MinimizeWindows
{
get { return checkBoxMinimizeWindows.Checked; }
set { checkBoxMinimizeWindows.Checked = value; }
}
/// <summary>
/// Sets a value indicating whether to [enable encode settings].
/// </summary>
/// <value>
/// <c>true</c> if [enable encode settings]; otherwise, <c>false</c>.
/// </value>
/// <remarks>Documented by Dev02, 2008-04-15</remarks>
public bool EnableEncodeSettings
{
set { textBoxEncodingApp.Enabled = textBoxEncodingArgs.Enabled = buttonBrowseEncodingApp.Enabled = checkBoxShowEncoder.Enabled = value; }
}
/// <summary>
/// Sets a value indicating whether to [enable decode settings].
/// </summary>
/// <value>
/// <c>true</c> if [enable decode settings]; otherwise, <c>false</c>.
/// </value>
/// <remarks>Documented by Dev02, 2008-04-15</remarks>
public bool EnableDecodeSettings
{
set { textBoxDecodingApp.Enabled = textBoxDecodingArgs.Enabled = buttonBrowseDecodingApp.Enabled = checkBoxShowDecoder.Enabled = value; }
}
/// <summary>
/// Gets or sets the codecs;
/// </summary>
/// <value>The codecs.</value>
/// <remarks>Documented by Dev02, 2008-04-15</remarks>
public Codecs Codecs
{
get { return codecs; }
set { codecs = (Codecs)value.Clone(); }
}
/// <summary>
/// Handles the Load event of the CodecSettings control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-04-10</remarks>
private void CodecSettings_Load(object sender, EventArgs e)
{
//fill codec selection combobox
comboBoxFormat.Items.AddRange(codecs.ToArray());
if (comboBoxFormat.Items.Count > 0)
comboBoxFormat.SelectedIndex = 0;
}
/// <summary>
/// Handles the Click event of the buttonOK control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-04-10</remarks>
private void buttonOK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
/// <summary>
/// Handles the SelectedIndexChanged event of the comboBoxFormat control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-04-10</remarks>
private void comboBoxFormat_SelectedIndexChanged(object sender, EventArgs e)
{
//load new values
if (comboBoxFormat.SelectedItem != null && comboBoxFormat.SelectedItem is Codec)
{
omitsave = true; //omit saving and checking
Codec selected = (Codec)comboBoxFormat.SelectedItem;
textBoxEncodingApp.Text = selected.EncodeApp;
textBoxEncodingArgs.Text = selected.EncodeArgs;
textBoxDecodingApp.Text = selected.DecodeApp;
textBoxDecodingArgs.Text = selected.DecodeArgs;
omitsave = false;
//now save and check text
textBox_TextChanged(this, new EventArgs());
//update groupbox descriptors
groupBoxEncoding.Text = string.Format("Encoding ({0} => {1})", MLifterAudioTools.Properties.Resources.AUDIO_WAVE_EXTENSION, selected.extension);
groupBoxDecoding.Text = string.Format("Decoding ({0} => {1})", selected.extension, MLifterAudioTools.Properties.Resources.AUDIO_WAVE_EXTENSION);
}
}
/// <summary>
/// Handles the Click event of the buttonBrowseEncodingApp control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-04-10</remarks>
private void buttonBrowseEncodingApp_Click(object sender, EventArgs e)
{
BrowseApp(textBoxEncodingApp);
}
/// <summary>
/// Handles the Click event of the buttonBrowseDecodingApp control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-04-10</remarks>
private void buttonBrowseDecodingApp_Click(object sender, EventArgs e)
{
BrowseApp(textBoxDecodingApp);
}
/// <summary>
/// Opens the browser to search an application.
/// </summary>
/// <param name="textbox">The textbox (for the desired path).</param>
/// <remarks>Documented by Dev02, 2008-04-11</remarks>
private void BrowseApp(TextBox textbox)
{
openFileDialogBrowse.InitialDirectory = Application.StartupPath;
DialogResult result = openFileDialogBrowse.ShowDialog();
if (result == DialogResult.OK)
{
string app = openFileDialogBrowse.FileName;
//make path relative, when it is within the application path
if (app.StartsWith(Application.StartupPath, true, System.Globalization.CultureInfo.InvariantCulture))
{
app = app.Remove(0, Application.StartupPath.Length);
if (app.StartsWith(@"\"))
app = app.Remove(0, 1);
}
textbox.Text = app;
}
}
/// <summary>
/// Handles the TextChanged event of the textBox control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-04-11</remarks>
private void textBox_TextChanged(object sender, EventArgs e)
{
//save current values
if (comboBoxFormat.SelectedItem != null && comboBoxFormat.SelectedItem is Codec && !omitsave)
{
Codec selected = (Codec)comboBoxFormat.SelectedItem;
selected.EncodeApp = textBoxEncodingApp.Text;
selected.EncodeArgs = textBoxEncodingArgs.Text;
selected.DecodeApp = textBoxDecodingApp.Text;
selected.DecodeArgs = textBoxDecodingArgs.Text;
//check values
errorProvider.Clear();
if (!selected.CanEncode)
{
string errorstring = "Encoding values are currently not valid: " + selected.EncodeError;
errorProvider.SetError(groupBoxEncoding, errorstring);
}
if (!selected.CanDecode)
{
string errorstring = "Decoding values are currently not valid: " + selected.DecodeError;
errorProvider.SetError(groupBoxDecoding, errorstring);
}
}
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Interception
{
using System.Data.Common;
using System.Data.Entity.Core;
using System.Data.Entity.Core.Common;
using System.Data.Entity.Core.EntityClient;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Infrastructure.Interception;
using System.Data.Entity.SqlServer;
using System.Data.Entity.TestHelpers;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Xunit;
public class CommitFailureTests : FunctionalTestBase
{
private void Execute_commit_failure_test(
Action<Action> verifyInitialization, Action<Action> verifySaveChanges, int expectedBlogs, bool useTransactionHandler,
bool useExecutionStrategy, bool rollbackOnFail)
{
var failingTransactionInterceptorMock = new Mock<FailingTransactionInterceptor> { CallBase = true };
var failingTransactionInterceptor = failingTransactionInterceptorMock.Object;
DbInterception.Add(failingTransactionInterceptor);
if (useTransactionHandler)
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
}
var isSqlAzure = DatabaseTestHelpers.IsSqlAzure(ModelHelpers.BaseConnectionString);
if (useExecutionStrategy)
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key =>
(Func<IDbExecutionStrategy>)
(() => isSqlAzure
? new TestSqlAzureExecutionStrategy()
: (IDbExecutionStrategy)
new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1))));
}
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = rollbackOnFail;
verifyInitialization(() => context.Blogs.Count());
failingTransactionInterceptor.ShouldFailTimes = 0;
Assert.Equal(1, context.Blogs.Count());
failingTransactionInterceptor.ShouldFailTimes = 1;
context.Blogs.Add(new BlogContext.Blog());
verifySaveChanges(() => context.SaveChanges());
var expectedCommitCount = useTransactionHandler
? useExecutionStrategy
? 6
: rollbackOnFail
? 4
: 3
: 4;
failingTransactionInterceptorMock.Verify(
m => m.Committing(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext>()),
isSqlAzure
? Times.AtLeast(expectedCommitCount)
: Times.Exactly(expectedCommitCount));
}
using (var context = new BlogContextCommit())
{
Assert.Equal(expectedBlogs, context.Blogs.Count());
using (var transactionContext = new TransactionContext(context.Database.Connection))
{
using (var infoContext = GetInfoContext(transactionContext))
{
Assert.True(
!infoContext.TableExists("__Transactions")
|| !transactionContext.Transactions.Any());
}
}
}
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 1,
useTransactionHandler: false,
useExecutionStrategy: false,
rollbackOnFail: true);
}
[Fact]
public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 2,
useTransactionHandler: false,
useExecutionStrategy: false,
rollbackOnFail: false);
}
[Fact]
[UseDefaultExecutionStrategy]
public void TransactionHandler_and_no_ExecutionStrategy_rethrows_original_exception_on_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<TimeoutException>(() => c()),
c =>
{
var exception = Assert.Throws<EntityException>(() => c());
Assert.IsType<TimeoutException>(exception.InnerException);
},
expectedBlogs: 1,
useTransactionHandler: true,
useExecutionStrategy: false,
rollbackOnFail: true);
}
[Fact]
public void TransactionHandler_and_no_ExecutionStrategy_does_not_throw_on_false_commit_fail()
{
Execute_commit_failure_test(
c => c(),
c => c(),
expectedBlogs: 2,
useTransactionHandler: true,
useExecutionStrategy: false,
rollbackOnFail: false);
}
[Fact]
public void No_TransactionHandler_and_ExecutionStrategy_throws_CommitFailedException_on_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 1,
useTransactionHandler: false,
useExecutionStrategy: true,
rollbackOnFail: true);
}
[Fact]
public void No_TransactionHandler_and_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 2,
useTransactionHandler: false,
useExecutionStrategy: true,
rollbackOnFail: false);
}
[Fact]
public void TransactionHandler_and_ExecutionStrategy_retries_on_commit_fail()
{
Execute_commit_failure_test(
c => c(),
c => c(),
expectedBlogs: 2,
useTransactionHandler: true,
useExecutionStrategy: true,
rollbackOnFail: true);
}
[Fact]
public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
context => context.SaveChanges());
}
#if !NET40
[Fact]
public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_async()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
context => context.SaveChangesAsync().Wait());
}
#endif
[Fact]
public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_with_custom_TransactionContext()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(c => new MyTransactionContext(c)), null, null));
TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
context =>
{
context.SaveChanges();
using (var infoContext = GetInfoContext(context))
{
Assert.True(infoContext.TableExists("MyTransactions"));
var column = infoContext.Columns.Single(c => c.Name == "Time");
Assert.Equal("datetime2", column.Type);
}
});
}
public class MyTransactionContext : TransactionContext
{
public MyTransactionContext(DbConnection connection)
: base(connection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TransactionRow>()
.ToTable("MyTransactions")
.HasKey(e => e.Id)
.Property(e => e.CreationTime).HasColumnName("Time").HasColumnType("datetime2");
}
}
private void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
Action<BlogContextCommit> runAndVerify)
{
var failingTransactionInterceptorMock = new Mock<FailingTransactionInterceptor> { CallBase = true };
var failingTransactionInterceptor = failingTransactionInterceptorMock.Object;
DbInterception.Add(failingTransactionInterceptor);
var isSqlAzure = DatabaseTestHelpers.IsSqlAzure(ModelHelpers.BaseConnectionString);
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key =>
(Func<IDbExecutionStrategy>)
(() => isSqlAzure
? new TestSqlAzureExecutionStrategy()
: (IDbExecutionStrategy)new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1))));
try
{
using (var context = new BlogContextCommit())
{
failingTransactionInterceptor.ShouldFailTimes = 0;
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
failingTransactionInterceptor.ShouldFailTimes = 2;
failingTransactionInterceptor.ShouldRollBack = false;
context.Blogs.Add(new BlogContext.Blog());
runAndVerify(context);
failingTransactionInterceptorMock.Verify(
m => m.Committing(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext>()),
isSqlAzure
? Times.AtLeast(3)
: Times.Exactly(3));
}
using (var context = new BlogContextCommit())
{
Assert.Equal(2, context.Blogs.Count());
using (var transactionContext = new TransactionContext(context.Database.Connection))
{
using (var infoContext = GetInfoContext(transactionContext))
{
Assert.True(
!infoContext.TableExists("__Transactions")
|| !transactionContext.Transactions.Any());
}
}
}
}
finally
{
DbInterception.Remove(failingTransactionInterceptorMock.Object);
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void CommitFailureHandler_Dispose_does_not_use_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
c.TransactionHandler.Dispose();
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(3));
});
}
[Fact]
public void CommitFailureHandler_Dispose_catches_exceptions()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
using (var transactionContext = new TransactionContext(((EntityConnection)c.Connection).StoreConnection))
{
foreach (var tran in transactionContext.Set<TransactionRow>().ToList())
{
transactionContext.Transactions.Remove(tran);
}
transactionContext.SaveChanges();
}
c.TransactionHandler.Dispose();
});
}
[Fact]
public void CommitFailureHandler_prunes_transactions_after_set_amount()
{
CommitFailureHandler_prunes_transactions_after_set_amount_implementation(false);
}
[Fact]
public void CommitFailureHandler_prunes_transactions_after_set_amount_and_handles_false_failure()
{
CommitFailureHandler_prunes_transactions_after_set_amount_implementation(true);
}
private void CommitFailureHandler_prunes_transactions_after_set_amount_implementation(bool shouldThrow)
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
var transactionHandler = (MyCommitFailureHandler)objectContext.TransactionHandler;
for (var i = 0; i < transactionHandler.PruningLimit; i++)
{
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
}
AssertTransactionHistoryCount(context, transactionHandler.PruningLimit);
if (shouldThrow)
{
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = false;
}
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
AssertTransactionHistoryCount(context, 1);
Assert.Equal(1, transactionHandler.TransactionContext.ChangeTracker.Entries<TransactionRow>().Count());
}
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void CommitFailureHandler_ClearTransactionHistory_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory();
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(4));
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_ClearTransactionHistory_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory());
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistory_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory();
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(4));
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistory_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory());
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
#if !NET40
[Fact]
public void CommitFailureHandler_ClearTransactionHistoryAsync_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait();
executionStrategyMock.Verify(
e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Once());
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_ClearTransactionHistoryAsync_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ExceptionHelpers.UnwrapAggregateExceptions(
() => ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait()));
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistoryAsync_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait();
executionStrategyMock.Verify(
e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Once());
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistoryAsync_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ExceptionHelpers.UnwrapAggregateExceptions(
() => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait()));
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
#endif
private void CommitFailureHandler_with_ExecutionStrategy_test(
Action<ObjectContext, Mock<TestSqlAzureExecutionStrategy>> pruneAndVerify)
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null));
var executionStrategyMock = new Mock<TestSqlAzureExecutionStrategy> { CallBase = true };
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => executionStrategyMock.Object));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
AssertTransactionHistoryCount(context, 1);
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(3));
#if !NET40
executionStrategyMock.Verify(
e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Never());
#endif
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
pruneAndVerify(objectContext, executionStrategyMock);
using (var transactionContext = new TransactionContext(context.Database.Connection))
{
Assert.Equal(0, transactionContext.Transactions.Count());
}
}
}
finally
{
MutableResolver.ClearResolvers();
}
}
private void AssertTransactionHistoryCount(DbContext context, int count)
{
AssertTransactionHistoryCount(((IObjectContextAdapter)context).ObjectContext, count);
}
private void AssertTransactionHistoryCount(ObjectContext context, int count)
{
using (var transactionContext = new TransactionContext(((EntityConnection)context.Connection).StoreConnection))
{
Assert.Equal(count, transactionContext.Transactions.Count());
}
}
public class SimpleExecutionStrategy : IDbExecutionStrategy
{
public bool RetriesOnFailure
{
get { return false; }
}
public virtual void Execute(Action operation)
{
operation();
}
public virtual TResult Execute<TResult>(Func<TResult> operation)
{
return operation();
}
#if !NET40
public virtual Task ExecuteAsync(Func<Task> operation, CancellationToken cancellationToken)
{
return operation();
}
public virtual Task<TResult> ExecuteAsync<TResult>(Func<Task<TResult>> operation, CancellationToken cancellationToken)
{
return operation();
}
#endif
}
public class MyCommitFailureHandler : CommitFailureHandler
{
public MyCommitFailureHandler(Func<DbConnection, TransactionContext> transactionContextFactory)
: base(transactionContextFactory)
{
}
public new void MarkTransactionForPruning(TransactionRow transaction)
{
base.MarkTransactionForPruning(transaction);
}
public new TransactionContext TransactionContext
{
get { return base.TransactionContext; }
}
public new virtual int PruningLimit
{
get { return base.PruningLimit; }
}
}
[Fact]
[UseDefaultExecutionStrategy]
public void CommitFailureHandler_supports_nested_transactions()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
context.Blogs.Add(new BlogContext.Blog());
using (var transaction = context.Database.BeginTransaction())
{
using (var innerContext = new BlogContextCommit())
{
using (var innerTransaction = innerContext.Database.BeginTransaction())
{
Assert.Equal(1, innerContext.Blogs.Count());
innerContext.Blogs.Add(new BlogContext.Blog());
innerContext.SaveChanges();
innerTransaction.Commit();
}
}
context.SaveChanges();
transaction.Commit();
}
}
using (var context = new BlogContextCommit())
{
Assert.Equal(3, context.Blogs.Count());
}
}
finally
{
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new TestSqlAzureExecutionStrategy()));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
}
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(c => new TransactionContextNoInit(c)), null, null));
using (var context = new BlogContextCommit())
{
context.Blogs.Add(new BlogContext.Blog());
Assert.Throws<EntityException>(() => context.SaveChanges());
context.Database.ExecuteSqlCommand(
TransactionalBehavior.DoNotEnsureTransaction,
((IObjectContextAdapter)context).ObjectContext.TransactionHandler.BuildDatabaseInitializationScript());
context.SaveChanges();
}
using (var context = new BlogContextCommit())
{
Assert.Equal(2, context.Blogs.Count());
}
}
finally
{
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database_if_no_migration_generator()
{
var mockDbProviderServiceResolver = new Mock<IDbDependencyResolver>();
mockDbProviderServiceResolver
.Setup(r => r.GetService(It.IsAny<Type>(), It.IsAny<string>()))
.Returns(SqlProviderServices.Instance);
MutableResolver.AddResolver<DbProviderServices>(mockDbProviderServiceResolver.Object);
var mockDbProviderFactoryResolver = new Mock<IDbDependencyResolver>();
mockDbProviderFactoryResolver
.Setup(r => r.GetService(It.IsAny<Type>(), It.IsAny<string>()))
.Returns(SqlClientFactory.Instance);
MutableResolver.AddResolver<DbProviderFactory>(mockDbProviderFactoryResolver.Object);
BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database();
}
[Fact]
public void FromContext_returns_the_current_handler()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
var commitFailureHandler = CommitFailureHandler.FromContext(((IObjectContextAdapter)context).ObjectContext);
Assert.IsType<CommitFailureHandler>(commitFailureHandler);
Assert.Same(commitFailureHandler, CommitFailureHandler.FromContext(context));
}
}
finally
{
MutableResolver.ClearResolvers();
}
}
[Fact]
public void TransactionHandler_is_disposed_even_if_the_context_is_not()
{
var context = new BlogContextCommit();
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
var weakDbContext = new WeakReference(context);
var weakObjectContext = new WeakReference(((IObjectContextAdapter)context).ObjectContext);
var weakTransactionHandler = new WeakReference(((IObjectContextAdapter)context).ObjectContext.TransactionHandler);
context = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weakDbContext.IsAlive);
Assert.False(weakObjectContext.IsAlive);
DbDispatchersHelpers.AssertNoInterceptors();
// Need a second pass as the TransactionHandler is removed from the interceptors in the ObjectContext finalizer
GC.Collect();
Assert.False(weakTransactionHandler.IsAlive);
}
public class TransactionContextNoInit : TransactionContext
{
static TransactionContextNoInit()
{
Database.SetInitializer<TransactionContextNoInit>(null);
}
public TransactionContextNoInit(DbConnection connection)
: base(connection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TransactionRow>()
.ToTable("TransactionContextNoInit");
}
}
public class FailingTransactionInterceptor : IDbTransactionInterceptor
{
private int _timesToFail;
private int _shouldFailTimes;
public int ShouldFailTimes
{
get { return _shouldFailTimes; }
set
{
_shouldFailTimes = value;
_timesToFail = value;
}
}
public bool ShouldRollBack;
public FailingTransactionInterceptor()
{
_timesToFail = ShouldFailTimes;
}
public void ConnectionGetting(DbTransaction transaction, DbTransactionInterceptionContext<DbConnection> interceptionContext)
{
}
public void ConnectionGot(DbTransaction transaction, DbTransactionInterceptionContext<DbConnection> interceptionContext)
{
}
public void IsolationLevelGetting(
DbTransaction transaction, DbTransactionInterceptionContext<IsolationLevel> interceptionContext)
{
}
public void IsolationLevelGot(DbTransaction transaction, DbTransactionInterceptionContext<IsolationLevel> interceptionContext)
{
}
public virtual void Committing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
if (_timesToFail-- > 0)
{
if (ShouldRollBack)
{
transaction.Rollback();
}
else
{
transaction.Commit();
}
interceptionContext.Exception = new TimeoutException();
}
else
{
_timesToFail = ShouldFailTimes;
}
}
public void Committed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
if (interceptionContext.Exception != null)
{
_timesToFail--;
}
}
public void Disposing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void Disposed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void RollingBack(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void RolledBack(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
}
public class BlogContextCommit : BlogContext
{
static BlogContextCommit()
{
Database.SetInitializer<BlogContextCommit>(new BlogInitializer());
}
}
}
}
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic.Utils;
using System.Threading;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents a block that contains a sequence of expressions where variables can be defined.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.BlockExpressionProxy))]
public class BlockExpression : Expression
{
/// <summary>
/// Gets the expressions in this block.
/// </summary>
public ReadOnlyCollection<Expression> Expressions
{
get { return GetOrMakeExpressions(); }
}
/// <summary>
/// Gets the variables defined in this block.
/// </summary>
public ReadOnlyCollection<ParameterExpression> Variables
{
get
{
return GetOrMakeVariables();
}
}
/// <summary>
/// Gets the last expression in this block.
/// </summary>
public Expression Result
{
get
{
Debug.Assert(ExpressionCount > 0);
return GetExpression(ExpressionCount - 1);
}
}
internal BlockExpression()
{
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitBlock(this);
}
/// <summary>
/// Returns the node type of this Expression. Extension nodes should return
/// ExpressionType.Extension when overriding this method.
/// </summary>
/// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.Block; }
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents.
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public override Type Type
{
get { return GetExpression(ExpressionCount - 1).Type; }
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="variables">The <see cref="Variables" /> property of the result.</param>
/// <param name="expressions">The <see cref="Expressions" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public BlockExpression Update(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions)
{
if (variables == Variables && expressions == Expressions)
{
return this;
}
return Expression.Block(Type, variables, expressions);
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual Expression GetExpression(int index)
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual int ExpressionCount
{
get
{
throw ContractUtils.Unreachable;
}
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual ParameterExpression GetVariable(int index)
{
throw ContractUtils.Unreachable;
}
internal virtual int VariableCount
{
get
{
return 0;
}
}
internal virtual ReadOnlyCollection<ParameterExpression> GetOrMakeVariables()
{
return EmptyReadOnlyCollection<ParameterExpression>.Instance;
}
/// <summary>
/// Makes a copy of this node replacing the parameters/args with the provided values. The
/// shape of the parameters/args needs to match the shape of the current block - in other
/// words there should be the same # of parameters and args.
///
/// parameters can be null in which case the existing parameters are used.
///
/// This helper is provided to allow re-writing of nodes to not depend on the specific optimized
/// subclass of BlockExpression which is being used.
/// </summary>
[ExcludeFromCodeCoverage] // Unreachable
internal virtual BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
throw ContractUtils.Unreachable;
}
/// <summary>
/// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T.
///
/// This is similar to the ReturnReadOnly which only takes a single argument. This version
/// supports nodes which hold onto 5 Expressions and puts all of the arguments into the
/// ReadOnlyCollection.
///
/// Ultimately this means if we create the readonly collection we will be slightly more wasteful as we'll
/// have a readonly collection + some fields in the type. The DLR internally avoids accessing anything
/// which would force the readonly collection to be created.
///
/// This is used by BlockExpression5 and MethodCallExpression5.
/// </summary>
internal static ReadOnlyCollection<Expression> ReturnReadOnlyExpressions(BlockExpression provider, ref object collection)
{
Expression tObj = collection as Expression;
if (tObj != null)
{
// otherwise make sure only one readonly collection ever gets exposed
Interlocked.CompareExchange(
ref collection,
new ReadOnlyCollection<Expression>(new BlockExpressionList(provider, tObj)),
tObj
);
}
// and return what is not guaranteed to be a readonly collection
return (ReadOnlyCollection<Expression>)collection;
}
}
#region Specialized Subclasses
internal sealed class Block2 : BlockExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd argument.
internal Block2(Expression arg0, Expression arg1)
{
_arg0 = arg0;
_arg1 = arg1;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
default: throw new InvalidOperationException();
}
}
internal override int ExpressionCount
{
get
{
return 2;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _arg0);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args != null);
Debug.Assert(args.Length == 2);
Debug.Assert(variables == null || variables.Count == 0);
return new Block2(args[0], args[1]);
}
}
internal sealed class Block3 : BlockExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2; // storage for the 2nd and 3rd arguments.
internal Block3(Expression arg0, Expression arg1, Expression arg2)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
default: throw new InvalidOperationException();
}
}
internal override int ExpressionCount
{
get
{
return 3;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _arg0);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args != null);
Debug.Assert(args.Length == 3);
Debug.Assert(variables == null || variables.Count == 0);
return new Block3(args[0], args[1], args[2]);
}
}
internal sealed class Block4 : BlockExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2, _arg3; // storarg for the 2nd, 3rd, and 4th arguments.
internal Block4(Expression arg0, Expression arg1, Expression arg2, Expression arg3)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
case 3: return _arg3;
default: throw new InvalidOperationException();
}
}
internal override int ExpressionCount
{
get
{
return 4;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _arg0);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args != null);
Debug.Assert(args.Length == 4);
Debug.Assert(variables == null || variables.Count == 0);
return new Block4(args[0], args[1], args[2], args[3]);
}
}
internal sealed class Block5 : BlockExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2, _arg3, _arg4; // storage for the 2nd - 5th args.
internal Block5(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
_arg4 = arg4;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
case 3: return _arg3;
case 4: return _arg4;
default: throw new InvalidOperationException();
}
}
internal override int ExpressionCount
{
get
{
return 5;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _arg0);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args != null);
Debug.Assert(args.Length == 5);
Debug.Assert(variables == null || variables.Count == 0);
return new Block5(args[0], args[1], args[2], args[3], args[4]);
}
}
internal class BlockN : BlockExpression
{
private IList<Expression> _expressions; // either the original IList<Expression> or a ReadOnlyCollection if the user has accessed it.
internal BlockN(IList<Expression> expressions)
{
Debug.Assert(expressions.Count != 0);
_expressions = expressions;
}
internal override Expression GetExpression(int index)
{
Debug.Assert(index >= 0 && index < _expressions.Count);
return _expressions[index];
}
internal override int ExpressionCount
{
get
{
return _expressions.Count;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnly(ref _expressions);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(variables == null || variables.Count == 0);
Debug.Assert(args != null);
return new BlockN(args);
}
}
internal class ScopeExpression : BlockExpression
{
private IList<ParameterExpression> _variables; // list of variables or ReadOnlyCollection if the user has accessed the readonly collection
internal ScopeExpression(IList<ParameterExpression> variables)
{
_variables = variables;
}
internal override int VariableCount
{
get
{
return _variables.Count;
}
}
internal override ParameterExpression GetVariable(int index)
{
return _variables[index];
}
internal override ReadOnlyCollection<ParameterExpression> GetOrMakeVariables()
{
return ReturnReadOnly(ref _variables);
}
protected IList<ParameterExpression> VariablesList
{
get
{
return _variables;
}
}
// Used for rewrite of the nodes to either reuse existing set of variables if not rewritten.
internal IList<ParameterExpression> ReuseOrValidateVariables(ReadOnlyCollection<ParameterExpression> variables)
{
if (variables != null && variables != VariablesList)
{
// Need to validate the new variables (uniqueness, not byref)
ValidateVariables(variables, "variables");
return variables;
}
else
{
return VariablesList;
}
}
}
internal sealed class Scope1 : ScopeExpression
{
private object _body;
internal Scope1(IList<ParameterExpression> variables, Expression body)
: this(variables, (object)body)
{
}
private Scope1(IList<ParameterExpression> variables, object body)
: base(variables)
{
_body = body;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_body);
default: throw new InvalidOperationException();
}
}
internal override int ExpressionCount
{
get
{
return 1;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _body);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
if (args == null)
{
Debug.Assert(variables.Count == VariableCount);
ValidateVariables(variables, "variables");
return new Scope1(variables, _body);
}
Debug.Assert(args.Length == 1);
Debug.Assert(variables == null || variables.Count == VariableCount);
return new Scope1(ReuseOrValidateVariables(variables), args[0]);
}
}
internal class ScopeN : ScopeExpression
{
private IList<Expression> _body;
internal ScopeN(IList<ParameterExpression> variables, IList<Expression> body)
: base(variables)
{
_body = body;
}
protected IList<Expression> Body
{
get { return _body; }
}
internal override Expression GetExpression(int index)
{
return _body[index];
}
internal override int ExpressionCount
{
get
{
return _body.Count;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnly(ref _body);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
if (args == null)
{
Debug.Assert(variables.Count == VariableCount);
ValidateVariables(variables, "variables");
return new ScopeN(variables, _body);
}
Debug.Assert(args.Length == ExpressionCount);
Debug.Assert(variables == null || variables.Count == VariableCount);
return new ScopeN(ReuseOrValidateVariables(variables), args);
}
}
internal class ScopeWithType : ScopeN
{
private readonly Type _type;
internal ScopeWithType(IList<ParameterExpression> variables, IList<Expression> expressions, Type type)
: base(variables, expressions)
{
_type = type;
}
public sealed override Type Type
{
get { return _type; }
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
if (args == null)
{
Debug.Assert(variables.Count == VariableCount);
ValidateVariables(variables, "variables");
return new ScopeWithType(variables, Body, _type);
}
Debug.Assert(args.Length == ExpressionCount);
Debug.Assert(variables == null || variables.Count == VariableCount);
return new ScopeWithType(ReuseOrValidateVariables(variables), args, _type);
}
}
#endregion
#region Block List Classes
/// <summary>
/// Provides a wrapper around an IArgumentProvider which exposes the argument providers
/// members out as an IList of Expression. This is used to avoid allocating an array
/// which needs to be stored inside of a ReadOnlyCollection. Instead this type has
/// the same amount of overhead as an array without duplicating the storage of the
/// elements. This ensures that internally we can avoid creating and copying arrays
/// while users of the Expression trees also don't pay a size penalty for this internal
/// optimization. See IArgumentProvider for more general information on the Expression
/// tree optimizations being used here.
/// </summary>
internal class BlockExpressionList : IList<Expression>
{
private readonly BlockExpression _block;
private readonly Expression _arg0;
internal BlockExpressionList(BlockExpression provider, Expression arg0)
{
_block = provider;
_arg0 = arg0;
}
#region IList<Expression> Members
public int IndexOf(Expression item)
{
if (_arg0 == item)
{
return 0;
}
for (int i = 1; i < _block.ExpressionCount; i++)
{
if (_block.GetExpression(i) == item)
{
return i;
}
}
return -1;
}
[ExcludeFromCodeCoverage] // Unreachable
public void Insert(int index, Expression item)
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
public void RemoveAt(int index)
{
throw ContractUtils.Unreachable;
}
public Expression this[int index]
{
get
{
if (index == 0)
{
return _arg0;
}
return _block.GetExpression(index);
}
[ExcludeFromCodeCoverage] // Unreachable
set
{
throw ContractUtils.Unreachable;
}
}
#endregion
#region ICollection<Expression> Members
[ExcludeFromCodeCoverage] // Unreachable
public void Add(Expression item)
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
public void Clear()
{
throw ContractUtils.Unreachable;
}
public bool Contains(Expression item)
{
return IndexOf(item) != -1;
}
public void CopyTo(Expression[] array, int arrayIndex)
{
array[arrayIndex++] = _arg0;
for (int i = 1; i < _block.ExpressionCount; i++)
{
array[arrayIndex++] = _block.GetExpression(i);
}
}
public int Count
{
get { return _block.ExpressionCount; }
}
[ExcludeFromCodeCoverage] // Unreachable
public bool IsReadOnly
{
get
{
throw ContractUtils.Unreachable;
}
}
[ExcludeFromCodeCoverage] // Unreachable
public bool Remove(Expression item)
{
throw ContractUtils.Unreachable;
}
#endregion
#region IEnumerable<Expression> Members
public IEnumerator<Expression> GetEnumerator()
{
yield return _arg0;
for (int i = 1; i < _block.ExpressionCount; i++)
{
yield return _block.GetExpression(i);
}
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
yield return _arg0;
for (int i = 1; i < _block.ExpressionCount; i++)
{
yield return _block.GetExpression(i);
}
}
#endregion
}
#endregion
public partial class Expression
{
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains two expressions and has no variables.
/// </summary>
/// <param name="arg0">The first expression in the block.</param>
/// <param name="arg1">The second expression in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Expression arg0, Expression arg1)
{
RequiresCanRead(arg0, "arg0");
RequiresCanRead(arg1, "arg1");
return new Block2(arg0, arg1);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains three expressions and has no variables.
/// </summary>
/// <param name="arg0">The first expression in the block.</param>
/// <param name="arg1">The second expression in the block.</param>
/// <param name="arg2">The third expression in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2)
{
RequiresCanRead(arg0, "arg0");
RequiresCanRead(arg1, "arg1");
RequiresCanRead(arg2, "arg2");
return new Block3(arg0, arg1, arg2);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains four expressions and has no variables.
/// </summary>
/// <param name="arg0">The first expression in the block.</param>
/// <param name="arg1">The second expression in the block.</param>
/// <param name="arg2">The third expression in the block.</param>
/// <param name="arg3">The fourth expression in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3)
{
RequiresCanRead(arg0, "arg0");
RequiresCanRead(arg1, "arg1");
RequiresCanRead(arg2, "arg2");
RequiresCanRead(arg3, "arg3");
return new Block4(arg0, arg1, arg2, arg3);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains five expressions and has no variables.
/// </summary>
/// <param name="arg0">The first expression in the block.</param>
/// <param name="arg1">The second expression in the block.</param>
/// <param name="arg2">The third expression in the block.</param>
/// <param name="arg3">The fourth expression in the block.</param>
/// <param name="arg4">The fifth expression in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
{
RequiresCanRead(arg0, "arg0");
RequiresCanRead(arg1, "arg1");
RequiresCanRead(arg2, "arg2");
RequiresCanRead(arg3, "arg3");
RequiresCanRead(arg4, "arg4");
return new Block5(arg0, arg1, arg2, arg3, arg4);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables.
/// </summary>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(params Expression[] expressions)
{
ContractUtils.RequiresNotNull(expressions, "expressions");
return GetOptimizedBlockExpression(expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables.
/// </summary>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(IEnumerable<Expression> expressions)
{
return Block(EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type.
/// </summary>
/// <param name="type">The result type of the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Type type, params Expression[] expressions)
{
ContractUtils.RequiresNotNull(expressions, "expressions");
return Block(type, (IEnumerable<Expression>)expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type.
/// </summary>
/// <param name="type">The result type of the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Type type, IEnumerable<Expression> expressions)
{
return Block(type, EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
/// </summary>
/// <param name="variables">The variables in the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(IEnumerable<ParameterExpression> variables, params Expression[] expressions)
{
return Block(variables, (IEnumerable<Expression>)expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
/// </summary>
/// <param name="type">The result type of the block.</param>
/// <param name="variables">The variables in the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, params Expression[] expressions)
{
return Block(type, variables, (IEnumerable<Expression>)expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
/// </summary>
/// <param name="variables">The variables in the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions)
{
ContractUtils.RequiresNotNull(expressions, "expressions");
var variableList = variables.ToReadOnly();
if (variableList.Count == 0)
{
return GetOptimizedBlockExpression(expressions as IReadOnlyList<Expression> ?? expressions.ToReadOnly());
}
var expressionList = expressions.ToReadOnly();
return BlockCore(expressionList.Last().Type, variableList, expressionList);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
/// </summary>
/// <param name="type">The result type of the block.</param>
/// <param name="variables">The variables in the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions)
{
ContractUtils.RequiresNotNull(type, "type");
ContractUtils.RequiresNotNull(expressions, "expressions");
var expressionList = expressions.ToReadOnly();
var variableList = variables.ToReadOnly();
if (variableList.Count == 0)
{
var expressionCount = expressionList.Count;
if (expressionCount != 0)
{
var lastExpression = expressionList[expressionCount - 1];
if (lastExpression.Type == type)
{
return GetOptimizedBlockExpression(expressionList);
}
}
}
return BlockCore(type, variableList, expressionList);
}
private static BlockExpression BlockCore(Type type, ReadOnlyCollection<ParameterExpression> variableList, ReadOnlyCollection<Expression> expressionList)
{
ContractUtils.RequiresNotEmpty(expressionList, "expressions");
RequiresCanRead(expressionList, "expressions");
ValidateVariables(variableList, "variables");
Expression last = expressionList.Last();
if (type != typeof(void))
{
if (!TypeUtils.AreReferenceAssignable(type, last.Type))
{
throw Error.ArgumentTypesMustMatch();
}
}
if (!TypeUtils.AreEquivalent(type, last.Type))
{
return new ScopeWithType(variableList, expressionList, type);
}
else
{
if (expressionList.Count == 1)
{
return new Scope1(variableList, expressionList[0]);
}
else
{
return new ScopeN(variableList, expressionList);
}
}
}
// Checks that all variables are non-null, not byref, and unique.
internal static void ValidateVariables(ReadOnlyCollection<ParameterExpression> varList, string collectionName)
{
if (varList.Count == 0)
{
return;
}
int count = varList.Count;
var set = new Set<ParameterExpression>(count);
for (int i = 0; i < count; i++)
{
ParameterExpression v = varList[i];
if (v == null)
{
throw new ArgumentNullException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}[{1}]", collectionName, set.Count));
}
if (v.IsByRef)
{
throw Error.VariableMustNotBeByRef(v, v.Type);
}
if (set.Contains(v))
{
throw Error.DuplicateVariable(v);
}
set.Add(v);
}
}
private static BlockExpression GetOptimizedBlockExpression(IReadOnlyList<Expression> expressions)
{
switch (expressions.Count)
{
case 2: return Block(expressions[0], expressions[1]);
case 3: return Block(expressions[0], expressions[1], expressions[2]);
case 4: return Block(expressions[0], expressions[1], expressions[2], expressions[3]);
case 5: return Block(expressions[0], expressions[1], expressions[2], expressions[3], expressions[4]);
default:
ContractUtils.RequiresNotEmptyList(expressions, "expressions");
RequiresCanRead(expressions, "expressions");
return new BlockN(expressions as ReadOnlyCollection<Expression> ?? (IList<Expression>)expressions.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.
// Description: Specifies that the whitespace surrounding an element should be trimmed.
using System;
using System.Reflection;
using System.ComponentModel;
using System.Globalization;
using System.Diagnostics;
#if SYSTEM_XAML
using System.Xaml.Replacements;
#endif
#if PBTCOMPILER
namespace MS.Internal.Markup
#elif SYSTEM_XAML
namespace System.Xaml
#else
namespace System.Windows.Markup
#endif
{
/// <summary>
/// Class that provides functionality to obtain a TypeConverter from a property or the
/// type of the property, based on logic similar to TypeDescriptor.GetConverter.
/// </summary>
internal static class TypeConverterHelper
{
private static CultureInfo invariantEnglishUS = CultureInfo.InvariantCulture;
internal static CultureInfo InvariantEnglishUS
{
get
{
return invariantEnglishUS;
}
}
#if !SYSTEM_XAML
internal static MemberInfo GetMemberInfoForPropertyConverter(object dpOrPiOrMi)
{
MemberInfo memberInfo = dpOrPiOrMi as PropertyInfo;
if (memberInfo == null)
{
MethodInfo methodInfo;
#if !PBTCOMPILER
DependencyProperty dp = dpOrPiOrMi as DependencyProperty;
if (dp != null)
{
// While parsing styles or templates, we end up getting a DependencyProperty,
// even for non-attached cases. In this case, we try fetching the CLR
// property info and getting its attributes.
memberInfo = dp.OwnerType.GetProperty(
dp.Name,
BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
// We failed to get a CLR wrapper for the DependencyProperty, so we
// assume that this is an attached property and look for the MethodInfo
// for the static getter.
if (memberInfo == null)
{
// Get the method member that defines the DependencyProperty
memberInfo = dp.OwnerType.GetMethod(
"Get" + dp.Name,
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.FlattenHierarchy);
}
}
else
#endif
if ((methodInfo = dpOrPiOrMi as MethodInfo) != null)
{
// miSetter may not be a MethodInfo when we are dealing with event handlers that
// belong to local assemblies. One such case is encountered when building DrtCompiler.
if (methodInfo.GetParameters().Length == 1)
{
// Use Getter of the attached property
memberInfo = methodInfo;
}
else
{
// Use the Setter of the attached property (if any)
memberInfo = methodInfo.DeclaringType.GetMethod(
"Get" + methodInfo.Name.Substring("Set".Length),
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.FlattenHierarchy);
}
}
}
return memberInfo;
}
internal static Type GetConverterType(MemberInfo memberInfo)
{
Debug.Assert(null != memberInfo, "Null passed for memberInfo to GetConverterType");
Type converterType = null;
// Try looking for the TypeConverter for the type using reflection.
string converterName = ReflectionHelper.GetTypeConverterAttributeData(memberInfo, out converterType);
if (converterType == null)
{
converterType = GetConverterTypeFromName(converterName);
}
return converterType;
}
#endif
internal static Type GetConverterType(Type type)
{
Debug.Assert(null != type, "Null passed for type to GetConverterType");
Type converterType = null;
// Try looking for the TypeConverter for the type using reflection.
string converterName = ReflectionHelper.GetTypeConverterAttributeData(type, out converterType);
if (converterType == null)
{
converterType = GetConverterTypeFromName(converterName);
}
return converterType;
}
private static Type GetConverterTypeFromName(string converterName)
{
Type converterType = null;
if (!string.IsNullOrEmpty(converterName))
{
converterType = ReflectionHelper.GetQualifiedType(converterName);
if (converterType != null)
{
// Validate that this is an accessible type converter.
if (!ReflectionHelper.IsPublicType(converterType))
{
#if PBTCOMPILER
if (!ReflectionHelper.IsInternalType(converterType) ||
!ReflectionHelper.IsInternalAllowedOnType(converterType))
{
#endif
converterType = null;
#if PBTCOMPILER
}
#endif
}
}
}
return converterType;
}
#if !SYSTEM_XAML
internal static Type GetCoreConverterTypeFromCustomType(Type type)
{
Type converterType = null;
if (type.IsEnum)
{
// Need to handle Enums types specially as they require a ctor that
// takes the underlying type, but at compile time we only need to know
// the Type of the Converter and not an actual instance of it.
converterType = typeof(EnumConverter);
}
else if (typeof(Int32).IsAssignableFrom(type))
{
converterType = typeof(Int32Converter);
}
else if (typeof(Int16).IsAssignableFrom(type))
{
converterType = typeof(Int16Converter);
}
else if (typeof(Int64).IsAssignableFrom(type))
{
converterType = typeof(Int64Converter);
}
else if (typeof(UInt32).IsAssignableFrom(type))
{
converterType = typeof(UInt32Converter);
}
else if (typeof(UInt16).IsAssignableFrom(type))
{
converterType = typeof(UInt16Converter);
}
else if (typeof(UInt64).IsAssignableFrom(type))
{
converterType = typeof(UInt64Converter);
}
else if (typeof(Boolean).IsAssignableFrom(type))
{
converterType = typeof(BooleanConverter);
}
else if (typeof(Double).IsAssignableFrom(type))
{
converterType = typeof(DoubleConverter);
}
else if (typeof(Single).IsAssignableFrom(type))
{
converterType = typeof(SingleConverter);
}
else if (typeof(Byte).IsAssignableFrom(type))
{
converterType = typeof(ByteConverter);
}
else if (typeof(SByte).IsAssignableFrom(type))
{
converterType = typeof(SByteConverter);
}
else if (typeof(Char).IsAssignableFrom(type))
{
converterType = typeof(CharConverter);
}
else if (typeof(Decimal).IsAssignableFrom(type))
{
converterType = typeof(DecimalConverter);
}
else if (typeof(TimeSpan).IsAssignableFrom(type))
{
converterType = typeof(TimeSpanConverter);
}
else if (typeof(Guid).IsAssignableFrom(type))
{
converterType = typeof(GuidConverter);
}
else if (typeof(String).IsAssignableFrom(type))
{
converterType = typeof(StringConverter);
}
else if (typeof(CultureInfo).IsAssignableFrom(type))
{
converterType = typeof(CultureInfoConverter);
}
else if (typeof(Type).IsAssignableFrom(type))
{
converterType = typeof(TypeTypeConverter);
}
else if (typeof(DateTime).IsAssignableFrom(type))
{
converterType = typeof(DateTimeConverter2);
}
return converterType;
}
#endif
#if !PBTCOMPILER
private static TypeConverter GetCoreConverterFromCoreType(Type type)
{
TypeConverter typeConverter = null;
if (type == typeof(Int32))
{
typeConverter = new System.ComponentModel.Int32Converter();
}
else if (type == typeof(Int16))
{
typeConverter = new System.ComponentModel.Int16Converter();
}
else if (type == typeof(Int64))
{
typeConverter = new System.ComponentModel.Int64Converter();
}
else if (type == typeof(UInt32))
{
typeConverter = new System.ComponentModel.UInt32Converter();
}
else if (type == typeof(UInt16))
{
typeConverter = new System.ComponentModel.UInt16Converter();
}
else if (type == typeof(UInt64))
{
typeConverter = new System.ComponentModel.UInt64Converter();
}
else if (type == typeof(Boolean))
{
typeConverter = new System.ComponentModel.BooleanConverter();
}
else if (type == typeof(Double))
{
typeConverter = new System.ComponentModel.DoubleConverter();
}
else if (type == typeof(Single))
{
typeConverter = new System.ComponentModel.SingleConverter();
}
else if (type == typeof(Byte))
{
typeConverter = new System.ComponentModel.ByteConverter();
}
else if (type == typeof(SByte))
{
typeConverter = new System.ComponentModel.SByteConverter();
}
else if (type == typeof(Char))
{
typeConverter = new System.ComponentModel.CharConverter();
}
else if (type == typeof(Decimal))
{
typeConverter = new System.ComponentModel.DecimalConverter();
}
else if (type == typeof(TimeSpan))
{
typeConverter = new System.ComponentModel.TimeSpanConverter();
}
else if (type == typeof(Guid))
{
typeConverter = new System.ComponentModel.GuidConverter();
}
else if (type == typeof(String))
{
typeConverter = new System.ComponentModel.StringConverter();
}
else if (type == typeof(CultureInfo))
{
typeConverter = new System.ComponentModel.CultureInfoConverter();
}
#if !SYSTEM_XAML
else if (type == typeof(Type))
{
typeConverter = new System.Windows.Markup.TypeTypeConverter();
}
#else
else if (type == typeof(Type))
{
typeConverter = new System.Xaml.Replacements.TypeTypeConverter();
}
#endif
else if (type == typeof(DateTime))
{
typeConverter = new DateTimeConverter2();
}
else if (ReflectionHelper.IsNullableType(type))
{
typeConverter = new System.ComponentModel.NullableConverter(type);
}
return typeConverter;
}
internal static TypeConverter GetCoreConverterFromCustomType(Type type)
{
TypeConverter typeConverter = null;
if (type.IsEnum)
{
// Need to handle Enums types specially as they require a ctor that
// takes the underlying type.
typeConverter = new System.ComponentModel.EnumConverter(type);
}
else if (typeof(Int32).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.Int32Converter();
}
else if (typeof(Int16).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.Int16Converter();
}
else if (typeof(Int64).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.Int64Converter();
}
else if (typeof(UInt32).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.UInt32Converter();
}
else if (typeof(UInt16).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.UInt16Converter();
}
else if (typeof(UInt64).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.UInt64Converter();
}
else if (typeof(Boolean).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.BooleanConverter();
}
else if (typeof(Double).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.DoubleConverter();
}
else if (typeof(Single).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.SingleConverter();
}
else if (typeof(Byte).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.ByteConverter();
}
else if (typeof(SByte).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.SByteConverter();
}
else if (typeof(Char).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.CharConverter();
}
else if (typeof(Decimal).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.DecimalConverter();
}
else if (typeof(TimeSpan).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.TimeSpanConverter();
}
else if (typeof(Guid).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.GuidConverter();
}
else if (typeof(String).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.StringConverter();
}
else if (typeof(CultureInfo).IsAssignableFrom(type))
{
typeConverter = new System.ComponentModel.CultureInfoConverter();
}
#if !SYSTEM_XAML
else if (typeof(Type).IsAssignableFrom(type))
{
typeConverter = new System.Windows.Markup.TypeTypeConverter();
}
#else
else if (type == typeof(Type))
{
typeConverter = new System.Xaml.Replacements.TypeTypeConverter();
}
#endif
else if (typeof(DateTime).IsAssignableFrom(type))
{
typeConverter = new DateTimeConverter2();
}
else if (typeof(Uri).IsAssignableFrom(type))
{
typeConverter = new System.Xaml.Replacements.TypeUriConverter();
}
return typeConverter;
}
/// <summary>
/// Returns a TypeConverter for the given target Type, otherwise null if not found.
/// First, if the type is one of the known system types, it lookups a table to determine the TypeConverter.
/// Next, it tries to find a TypeConverterAttribute on the type using reflection.
/// Finally, it looks up the table of known typeConverters again if the given type derives from one of the
/// known system types.
/// </summary>
/// <param name="type">The target Type for which to find a TypeConverter.</param>
/// <returns>A TypeConverter for the Type type if found. Null otherwise.</returns>
internal static TypeConverter GetTypeConverter(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
TypeConverter typeConverter = GetCoreConverterFromCoreType(type);
if (typeConverter == null)
{
Type converterType = GetConverterType(type);
if (converterType != null)
{
typeConverter = Activator.CreateInstance(converterType,
BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.Public,
null,
null,
InvariantEnglishUS) as TypeConverter;
}
else
{
typeConverter = GetCoreConverterFromCustomType(type);
}
if (typeConverter == null)
{
typeConverter = new TypeConverter();
}
}
return typeConverter;
}
#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 System;
using System.IO;
using System.Collections;
using System.Text;
using System.Diagnostics;
using System.Xml.Schema;
using System.Xml.XPath;
using MS.Internal.Xml.XPath;
using System.Globalization;
namespace System.Xml
{
// Represents a single node in the document.
[DebuggerDisplay("{debuggerDisplayProxy}")]
public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable
{
internal XmlNode parentNode; //this pointer is reused to save the userdata information, need to prevent internal user access the pointer directly.
internal XmlNode()
{
}
internal XmlNode(XmlDocument doc)
{
if (doc == null)
throw new ArgumentException(SR.Xdom_Node_Null_Doc);
this.parentNode = doc;
}
public virtual XPathNavigator CreateNavigator()
{
XmlDocument thisAsDoc = this as XmlDocument;
if (thisAsDoc != null)
{
return thisAsDoc.CreateNavigator(this);
}
XmlDocument doc = OwnerDocument;
Debug.Assert(doc != null);
return doc.CreateNavigator(this);
}
// Selects the first node that matches the xpath expression
public XmlNode SelectSingleNode(string xpath)
{
XmlNodeList list = SelectNodes(xpath);
// SelectNodes returns null for certain node types
return list != null ? list[0] : null;
}
// Selects the first node that matches the xpath expression and given namespace context.
public XmlNode SelectSingleNode(string xpath, XmlNamespaceManager nsmgr)
{
XPathNavigator xn = (this).CreateNavigator();
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
if (xn == null)
return null;
XPathExpression exp = xn.Compile(xpath);
exp.SetContext(nsmgr);
return new XPathNodeList(xn.Select(exp))[0];
}
// Selects all nodes that match the xpath expression
public XmlNodeList SelectNodes(string xpath)
{
XPathNavigator n = (this).CreateNavigator();
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
if (n == null)
return null;
return new XPathNodeList(n.Select(xpath));
}
// Selects all nodes that match the xpath expression and given namespace context.
public XmlNodeList SelectNodes(string xpath, XmlNamespaceManager nsmgr)
{
XPathNavigator xn = (this).CreateNavigator();
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
if (xn == null)
return null;
XPathExpression exp = xn.Compile(xpath);
exp.SetContext(nsmgr);
return new XPathNodeList(xn.Select(exp));
}
// Gets the name of the node.
public abstract string Name
{
get;
}
// Gets or sets the value of the node.
public virtual string Value
{
get { return null; }
set { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.Xdom_Node_SetVal, NodeType.ToString())); }
}
// Gets the type of the current node.
public abstract XmlNodeType NodeType
{
get;
}
// Gets the parent of this node (for nodes that can have parents).
public virtual XmlNode ParentNode
{
get
{
Debug.Assert(parentNode != null);
if (parentNode.NodeType != XmlNodeType.Document)
{
return parentNode;
}
// Linear lookup through the children of the document
XmlLinkedNode firstChild = parentNode.FirstChild as XmlLinkedNode;
if (firstChild != null)
{
XmlLinkedNode node = firstChild;
do
{
if (node == this)
{
return parentNode;
}
node = node.next;
}
while (node != null
&& node != firstChild);
}
return null;
}
}
// Gets all children of this node.
public virtual XmlNodeList ChildNodes
{
get { return new XmlChildNodes(this); }
}
// Gets the node immediately preceding this node.
public virtual XmlNode PreviousSibling
{
get { return null; }
}
// Gets the node immediately following this node.
public virtual XmlNode NextSibling
{
get { return null; }
}
// Gets a XmlAttributeCollection containing the attributes
// of this node.
public virtual XmlAttributeCollection Attributes
{
get { return null; }
}
// Gets the XmlDocument that contains this node.
public virtual XmlDocument OwnerDocument
{
get
{
Debug.Assert(parentNode != null);
if (parentNode.NodeType == XmlNodeType.Document)
return (XmlDocument)parentNode;
return parentNode.OwnerDocument;
}
}
// Gets the first child of this node.
public virtual XmlNode FirstChild
{
get
{
XmlLinkedNode linkedNode = LastNode;
if (linkedNode != null)
return linkedNode.next;
return null;
}
}
// Gets the last child of this node.
public virtual XmlNode LastChild
{
get { return LastNode; }
}
internal virtual bool IsContainer
{
get { return false; }
}
internal virtual XmlLinkedNode LastNode
{
get { return null; }
set { }
}
internal bool AncestorNode(XmlNode node)
{
XmlNode n = this.ParentNode;
while (n != null && n != this)
{
if (n == node)
return true;
n = n.ParentNode;
}
return false;
}
//trace to the top to find out its parent node.
internal bool IsConnected()
{
XmlNode parent = ParentNode;
while (parent != null && !(parent.NodeType == XmlNodeType.Document))
parent = parent.ParentNode;
return parent != null;
}
// Inserts the specified node immediately before the specified reference node.
public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild)
{
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(SR.Xdom_Node_Insert_Child);
if (refChild == null)
return AppendChild(newChild);
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain);
if (refChild.ParentNode != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Path);
if (newChild == refChild)
return newChild;
XmlDocument childDoc = newChild.OwnerDocument;
XmlDocument thisDoc = OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Context);
if (!CanInsertBefore(newChild, refChild))
throw new InvalidOperationException(SR.Xdom_Node_Insert_Location);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild(newChild);
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment)
{
XmlNode first = newChild.FirstChild;
XmlNode node = first;
if (node != null)
{
newChild.RemoveChild(node);
InsertBefore(node, refChild);
// insert the rest of the children after this one.
InsertAfter(newChild, node);
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
XmlLinkedNode refNode = (XmlLinkedNode)refChild;
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert);
if (args != null)
BeforeEvent(args);
if (refNode == FirstChild)
{
newNode.next = refNode;
LastNode.next = newNode;
newNode.SetParent(this);
if (newNode.IsText)
{
if (refNode.IsText)
{
NestTextNodes(newNode, refNode);
}
}
}
else
{
XmlLinkedNode prevNode = (XmlLinkedNode)refNode.PreviousSibling;
newNode.next = refNode;
prevNode.next = newNode;
newNode.SetParent(this);
if (prevNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(prevNode, newNode);
if (refNode.IsText)
{
NestTextNodes(newNode, refNode);
}
}
else
{
if (refNode.IsText)
{
UnnestTextNodes(prevNode, refNode);
}
}
}
else
{
if (newNode.IsText)
{
if (refNode.IsText)
{
NestTextNodes(newNode, refNode);
}
}
}
}
if (args != null)
AfterEvent(args);
return newNode;
}
// Inserts the specified node immediately after the specified reference node.
public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild)
{
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(SR.Xdom_Node_Insert_Child);
if (refChild == null)
return PrependChild(newChild);
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain);
if (refChild.ParentNode != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Path);
if (newChild == refChild)
return newChild;
XmlDocument childDoc = newChild.OwnerDocument;
XmlDocument thisDoc = OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Context);
if (!CanInsertAfter(newChild, refChild))
throw new InvalidOperationException(SR.Xdom_Node_Insert_Location);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild(newChild);
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment)
{
XmlNode last = refChild;
XmlNode first = newChild.FirstChild;
XmlNode node = first;
while (node != null)
{
XmlNode next = node.NextSibling;
newChild.RemoveChild(node);
InsertAfter(node, last);
last = node;
node = next;
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
XmlLinkedNode refNode = (XmlLinkedNode)refChild;
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert);
if (args != null)
BeforeEvent(args);
if (refNode == LastNode)
{
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
if (refNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
}
}
else
{
XmlLinkedNode nextNode = refNode.next;
newNode.next = nextNode;
refNode.next = newNode;
newNode.SetParent(this);
if (refNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(refNode, newNode);
if (nextNode.IsText)
{
NestTextNodes(newNode, nextNode);
}
}
else
{
if (nextNode.IsText)
{
UnnestTextNodes(refNode, nextNode);
}
}
}
else
{
if (newNode.IsText)
{
if (nextNode.IsText)
{
NestTextNodes(newNode, nextNode);
}
}
}
}
if (args != null)
AfterEvent(args);
return newNode;
}
// Replaces the child node oldChild with newChild node.
public virtual XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild)
{
XmlNode nextNode = oldChild.NextSibling;
RemoveChild(oldChild);
XmlNode node = InsertBefore(newChild, nextNode);
return oldChild;
}
// Removes specified child node.
public virtual XmlNode RemoveChild(XmlNode oldChild)
{
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Remove_Contain);
if (oldChild.ParentNode != this)
throw new ArgumentException(SR.Xdom_Node_Remove_Child);
XmlLinkedNode oldNode = (XmlLinkedNode)oldChild;
string oldNodeValue = oldNode.Value;
XmlNodeChangedEventArgs args = GetEventArgs(oldNode, this, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove);
if (args != null)
BeforeEvent(args);
XmlLinkedNode lastNode = LastNode;
if (oldNode == FirstChild)
{
if (oldNode == lastNode)
{
LastNode = null;
oldNode.next = null;
oldNode.SetParent(null);
}
else
{
XmlLinkedNode nextNode = oldNode.next;
if (nextNode.IsText)
{
if (oldNode.IsText)
{
UnnestTextNodes(oldNode, nextNode);
}
}
lastNode.next = nextNode;
oldNode.next = null;
oldNode.SetParent(null);
}
}
else
{
if (oldNode == lastNode)
{
XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling;
prevNode.next = oldNode.next;
LastNode = prevNode;
oldNode.next = null;
oldNode.SetParent(null);
}
else
{
XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling;
XmlLinkedNode nextNode = oldNode.next;
if (nextNode.IsText)
{
if (prevNode.IsText)
{
NestTextNodes(prevNode, nextNode);
}
else
{
if (oldNode.IsText)
{
UnnestTextNodes(oldNode, nextNode);
}
}
}
prevNode.next = nextNode;
oldNode.next = null;
oldNode.SetParent(null);
}
}
if (args != null)
AfterEvent(args);
return oldChild;
}
// Adds the specified node to the beginning of the list of children of this node.
public virtual XmlNode PrependChild(XmlNode newChild)
{
return InsertBefore(newChild, FirstChild);
}
// Adds the specified node to the end of the list of children of this node.
public virtual XmlNode AppendChild(XmlNode newChild)
{
XmlDocument thisDoc = OwnerDocument;
if (thisDoc == null)
{
thisDoc = this as XmlDocument;
}
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain);
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(SR.Xdom_Node_Insert_Child);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild(newChild);
XmlDocument childDoc = newChild.OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Context);
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment)
{
XmlNode first = newChild.FirstChild;
XmlNode node = first;
while (node != null)
{
XmlNode next = node.NextSibling;
newChild.RemoveChild(node);
AppendChild(node);
node = next;
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict);
if (!CanInsertAfter(newChild, LastChild))
throw new InvalidOperationException(SR.Xdom_Node_Insert_Location);
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert);
if (args != null)
BeforeEvent(args);
XmlLinkedNode refNode = LastNode;
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (refNode == null)
{
newNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
}
else
{
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
if (refNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
}
}
if (args != null)
AfterEvent(args);
return newNode;
}
//the function is provided only at Load time to speed up Load process
internal virtual XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc)
{
XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this);
if (args != null)
doc.BeforeEvent(args);
XmlLinkedNode refNode = LastNode;
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (refNode == null)
{
newNode.next = newNode;
LastNode = newNode;
newNode.SetParentForLoad(this);
}
else
{
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
if (refNode.IsText
&& newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
else
{
newNode.SetParentForLoad(this);
}
}
if (args != null)
doc.AfterEvent(args);
return newNode;
}
internal virtual bool IsValidChildType(XmlNodeType type)
{
return false;
}
internal virtual bool CanInsertBefore(XmlNode newChild, XmlNode refChild)
{
return true;
}
internal virtual bool CanInsertAfter(XmlNode newChild, XmlNode refChild)
{
return true;
}
// Gets a value indicating whether this node has any child nodes.
public virtual bool HasChildNodes
{
get { return LastNode != null; }
}
// Creates a duplicate of this node.
public abstract XmlNode CloneNode(bool deep);
internal virtual void CopyChildren(XmlDocument doc, XmlNode container, bool deep)
{
for (XmlNode child = container.FirstChild; child != null; child = child.NextSibling)
{
AppendChildForLoad(child.CloneNode(deep), doc);
}
}
// DOM Level 2
// Puts all XmlText nodes in the full depth of the sub-tree
// underneath this XmlNode into a "normal" form where only
// markup (e.g., tags, comments, processing instructions, CDATA sections,
// and entity references) separates XmlText nodes, that is, there
// are no adjacent XmlText nodes.
public virtual void Normalize()
{
XmlNode firstChildTextLikeNode = null;
StringBuilder sb = StringBuilderCache.Acquire();
for (XmlNode crtChild = this.FirstChild; crtChild != null;)
{
XmlNode nextChild = crtChild.NextSibling;
switch (crtChild.NodeType)
{
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
{
sb.Append(crtChild.Value);
XmlNode winner = NormalizeWinner(firstChildTextLikeNode, crtChild);
if (winner == firstChildTextLikeNode)
{
this.RemoveChild(crtChild);
}
else
{
if (firstChildTextLikeNode != null)
this.RemoveChild(firstChildTextLikeNode);
firstChildTextLikeNode = crtChild;
}
break;
}
case XmlNodeType.Element:
{
crtChild.Normalize();
goto default;
}
default:
{
if (firstChildTextLikeNode != null)
{
firstChildTextLikeNode.Value = sb.ToString();
firstChildTextLikeNode = null;
}
sb.Remove(0, sb.Length);
break;
}
}
crtChild = nextChild;
}
if (firstChildTextLikeNode != null && sb.Length > 0)
firstChildTextLikeNode.Value = sb.ToString();
StringBuilderCache.Release(sb);
}
private XmlNode NormalizeWinner(XmlNode firstNode, XmlNode secondNode)
{
//first node has the priority
if (firstNode == null)
return secondNode;
Debug.Assert(firstNode.NodeType == XmlNodeType.Text
|| firstNode.NodeType == XmlNodeType.SignificantWhitespace
|| firstNode.NodeType == XmlNodeType.Whitespace
|| secondNode.NodeType == XmlNodeType.Text
|| secondNode.NodeType == XmlNodeType.SignificantWhitespace
|| secondNode.NodeType == XmlNodeType.Whitespace);
if (firstNode.NodeType == XmlNodeType.Text)
return firstNode;
if (secondNode.NodeType == XmlNodeType.Text)
return secondNode;
if (firstNode.NodeType == XmlNodeType.SignificantWhitespace)
return firstNode;
if (secondNode.NodeType == XmlNodeType.SignificantWhitespace)
return secondNode;
if (firstNode.NodeType == XmlNodeType.Whitespace)
return firstNode;
if (secondNode.NodeType == XmlNodeType.Whitespace)
return secondNode;
Debug.Assert(true, "shouldn't have fall through here.");
return null;
}
// Test if the DOM implementation implements a specific feature.
public virtual bool Supports(string feature, string version)
{
if (String.Equals("XML", feature, StringComparison.OrdinalIgnoreCase))
{
if (version == null || version == "1.0" || version == "2.0")
return true;
}
return false;
}
// Gets the namespace URI of this node.
public virtual string NamespaceURI
{
get { return string.Empty; }
}
// Gets or sets the namespace prefix of this node.
public virtual string Prefix
{
get { return string.Empty; }
set { }
}
// Gets the name of the node without the namespace prefix.
public abstract string LocalName
{
get;
}
// Microsoft extensions
// Gets a value indicating whether the node is read-only.
public virtual bool IsReadOnly
{
get
{
XmlDocument doc = OwnerDocument;
return HasReadOnlyParent(this);
}
}
internal static bool HasReadOnlyParent(XmlNode n)
{
while (n != null)
{
switch (n.NodeType)
{
case XmlNodeType.EntityReference:
case XmlNodeType.Entity:
return true;
case XmlNodeType.Attribute:
n = ((XmlAttribute)n).OwnerElement;
break;
default:
n = n.ParentNode;
break;
}
}
return false;
}
// Creates a duplicate of this node.
public virtual XmlNode Clone()
{
return this.CloneNode(true);
}
object ICloneable.Clone()
{
return this.CloneNode(true);
}
// Provides a simple ForEach-style iteration over the
// collection of nodes in this XmlNamedNodeMap.
IEnumerator IEnumerable.GetEnumerator()
{
return new XmlChildEnumerator(this);
}
public IEnumerator GetEnumerator()
{
return new XmlChildEnumerator(this);
}
private void AppendChildText(StringBuilder builder)
{
for (XmlNode child = FirstChild; child != null; child = child.NextSibling)
{
if (child.FirstChild == null)
{
if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA
|| child.NodeType == XmlNodeType.Whitespace || child.NodeType == XmlNodeType.SignificantWhitespace)
builder.Append(child.InnerText);
}
else
{
child.AppendChildText(builder);
}
}
}
// Gets or sets the concatenated values of the node and
// all its children.
public virtual string InnerText
{
get
{
XmlNode fc = FirstChild;
if (fc == null)
{
return string.Empty;
}
if (fc.NextSibling == null)
{
XmlNodeType nodeType = fc.NodeType;
switch (nodeType)
{
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return fc.Value;
}
}
StringBuilder builder = StringBuilderCache.Acquire();
AppendChildText(builder);
return StringBuilderCache.GetStringAndRelease(builder);
}
set
{
XmlNode firstChild = FirstChild;
if (firstChild != null //there is one child
&& firstChild.NextSibling == null // and exactly one
&& firstChild.NodeType == XmlNodeType.Text)//which is a text node
{
//this branch is for perf reason and event fired when TextNode.Value is changed
firstChild.Value = value;
}
else
{
RemoveAll();
AppendChild(OwnerDocument.CreateTextNode(value));
}
}
}
// Gets the markup representing this node and all its children.
public virtual string OuterXml
{
get
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlDOMTextWriter xw = new XmlDOMTextWriter(sw);
try
{
WriteTo(xw);
}
finally
{
xw.Close();
}
return sw.ToString();
}
}
// Gets or sets the markup representing just the children of this node.
public virtual string InnerXml
{
get
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlDOMTextWriter xw = new XmlDOMTextWriter(sw);
try
{
WriteContentTo(xw);
}
finally
{
xw.Close();
}
return sw.ToString();
}
set
{
throw new InvalidOperationException(SR.Xdom_Set_InnerXml);
}
}
public virtual IXmlSchemaInfo SchemaInfo
{
get
{
return XmlDocument.NotKnownSchemaInfo;
}
}
public virtual String BaseURI
{
get
{
XmlNode curNode = this.ParentNode; //save one while loop since if going to here, the nodetype of this node can't be document, entity and entityref
while (curNode != null)
{
XmlNodeType nt = curNode.NodeType;
//EntityReference's children come from the dtd where they are defined.
//we need to investigate the same thing for entity's children if they are defined in an external dtd file.
if (nt == XmlNodeType.EntityReference)
return ((XmlEntityReference)curNode).ChildBaseURI;
if (nt == XmlNodeType.Document
|| nt == XmlNodeType.Entity
|| nt == XmlNodeType.Attribute)
return curNode.BaseURI;
curNode = curNode.ParentNode;
}
return String.Empty;
}
}
// Saves the current node to the specified XmlWriter.
public abstract void WriteTo(XmlWriter w);
// Saves all the children of the node to the specified XmlWriter.
public abstract void WriteContentTo(XmlWriter w);
// Removes all the children and/or attributes
// of the current node.
public virtual void RemoveAll()
{
XmlNode child = FirstChild;
XmlNode sibling = null;
while (child != null)
{
sibling = child.NextSibling;
RemoveChild(child);
child = sibling;
}
}
internal XmlDocument Document
{
get
{
if (NodeType == XmlNodeType.Document)
return (XmlDocument)this;
return OwnerDocument;
}
}
// Looks up the closest xmlns declaration for the given
// prefix that is in scope for the current node and returns
// the namespace URI in the declaration.
public virtual string GetNamespaceOfPrefix(string prefix)
{
string namespaceName = GetNamespaceOfPrefixStrict(prefix);
return namespaceName != null ? namespaceName : string.Empty;
}
internal string GetNamespaceOfPrefixStrict(string prefix)
{
XmlDocument doc = Document;
if (doc != null)
{
prefix = doc.NameTable.Get(prefix);
if (prefix == null)
return null;
XmlNode node = this;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
if (prefix.Length == 0)
{
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
XmlAttribute attr = attrs[iAttr];
if (attr.Prefix.Length == 0)
{
if (Ref.Equal(attr.LocalName, doc.strXmlns))
{
return attr.Value; // found xmlns
}
}
}
}
else
{
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
XmlAttribute attr = attrs[iAttr];
if (Ref.Equal(attr.Prefix, doc.strXmlns))
{
if (Ref.Equal(attr.LocalName, prefix))
{
return attr.Value; // found xmlns:prefix
}
}
else if (Ref.Equal(attr.Prefix, prefix))
{
return attr.NamespaceURI; // found prefix:attr
}
}
}
}
if (Ref.Equal(node.Prefix, prefix))
{
return node.NamespaceURI;
}
node = node.ParentNode;
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
}
else
{
node = node.ParentNode;
}
}
if (Ref.Equal(doc.strXml, prefix))
{ // xmlns:xml
return doc.strReservedXml;
}
else if (Ref.Equal(doc.strXmlns, prefix))
{ // xmlns:xmlns
return doc.strReservedXmlns;
}
}
return null;
}
// Looks up the closest xmlns declaration for the given namespace
// URI that is in scope for the current node and returns
// the prefix defined in that declaration.
public virtual string GetPrefixOfNamespace(string namespaceURI)
{
string prefix = GetPrefixOfNamespaceStrict(namespaceURI);
return prefix != null ? prefix : string.Empty;
}
internal string GetPrefixOfNamespaceStrict(string namespaceURI)
{
XmlDocument doc = Document;
if (doc != null)
{
namespaceURI = doc.NameTable.Add(namespaceURI);
XmlNode node = this;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
XmlAttribute attr = attrs[iAttr];
if (attr.Prefix.Length == 0)
{
if (Ref.Equal(attr.LocalName, doc.strXmlns))
{
if (attr.Value == namespaceURI)
{
return string.Empty; // found xmlns="namespaceURI"
}
}
}
else if (Ref.Equal(attr.Prefix, doc.strXmlns))
{
if (attr.Value == namespaceURI)
{
return attr.LocalName; // found xmlns:prefix="namespaceURI"
}
}
else if (Ref.Equal(attr.NamespaceURI, namespaceURI))
{
return attr.Prefix; // found prefix:attr
// with prefix bound to namespaceURI
}
}
}
if (Ref.Equal(node.NamespaceURI, namespaceURI))
{
return node.Prefix;
}
node = node.ParentNode;
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
}
else
{
node = node.ParentNode;
}
}
if (Ref.Equal(doc.strReservedXml, namespaceURI))
{ // xmlns:xml
return doc.strXml;
}
else if (Ref.Equal(doc.strReservedXmlns, namespaceURI))
{ // xmlns:xmlns
return doc.strXmlns;
}
}
return null;
}
// Retrieves the first child element with the specified name.
public virtual XmlElement this[string name]
{
get
{
for (XmlNode n = FirstChild; n != null; n = n.NextSibling)
{
if (n.NodeType == XmlNodeType.Element && n.Name == name)
return (XmlElement)n;
}
return null;
}
}
// Retrieves the first child element with the specified LocalName and
// NamespaceURI.
public virtual XmlElement this[string localname, string ns]
{
get
{
for (XmlNode n = FirstChild; n != null; n = n.NextSibling)
{
if (n.NodeType == XmlNodeType.Element && n.LocalName == localname && n.NamespaceURI == ns)
return (XmlElement)n;
}
return null;
}
}
internal virtual void SetParent(XmlNode node)
{
if (node == null)
{
this.parentNode = OwnerDocument;
}
else
{
this.parentNode = node;
}
}
internal virtual void SetParentForLoad(XmlNode node)
{
this.parentNode = node;
}
internal static void SplitName(string name, out string prefix, out string localName)
{
int colonPos = name.IndexOf(':'); // ordinal compare
if (-1 == colonPos || 0 == colonPos || name.Length - 1 == colonPos)
{
prefix = string.Empty;
localName = name;
}
else
{
prefix = name.Substring(0, colonPos);
localName = name.Substring(colonPos + 1);
}
}
internal virtual XmlNode FindChild(XmlNodeType type)
{
for (XmlNode child = FirstChild; child != null; child = child.NextSibling)
{
if (child.NodeType == type)
{
return child;
}
}
return null;
}
internal virtual XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action)
{
XmlDocument doc = OwnerDocument;
if (doc != null)
{
if (!doc.IsLoading)
{
if (((newParent != null && newParent.IsReadOnly) || (oldParent != null && oldParent.IsReadOnly)))
throw new InvalidOperationException(SR.Xdom_Node_Modify_ReadOnly);
}
return doc.GetEventArgs(node, oldParent, newParent, oldValue, newValue, action);
}
return null;
}
internal virtual void BeforeEvent(XmlNodeChangedEventArgs args)
{
if (args != null)
OwnerDocument.BeforeEvent(args);
}
internal virtual void AfterEvent(XmlNodeChangedEventArgs args)
{
if (args != null)
OwnerDocument.AfterEvent(args);
}
internal virtual XmlSpace XmlSpace
{
get
{
XmlNode node = this;
XmlElement elem = null;
do
{
elem = node as XmlElement;
if (elem != null && elem.HasAttribute("xml:space"))
{
switch (XmlConvert.TrimString(elem.GetAttribute("xml:space")))
{
case "default":
return XmlSpace.Default;
case "preserve":
return XmlSpace.Preserve;
default:
//should we throw exception if value is otherwise?
break;
}
}
node = node.ParentNode;
}
while (node != null);
return XmlSpace.None;
}
}
internal virtual String XmlLang
{
get
{
XmlNode node = this;
XmlElement elem = null;
do
{
elem = node as XmlElement;
if (elem != null)
{
if (elem.HasAttribute("xml:lang"))
return elem.GetAttribute("xml:lang");
}
node = node.ParentNode;
} while (node != null);
return String.Empty;
}
}
internal virtual XPathNodeType XPNodeType
{
get
{
return (XPathNodeType)(-1);
}
}
internal virtual string XPLocalName
{
get
{
return string.Empty;
}
}
internal virtual string GetXPAttribute(string localName, string namespaceURI)
{
return String.Empty;
}
internal virtual bool IsText
{
get
{
return false;
}
}
public virtual XmlNode PreviousText
{
get
{
return null;
}
}
internal static void NestTextNodes(XmlNode prevNode, XmlNode nextNode)
{
Debug.Assert(prevNode.IsText);
Debug.Assert(nextNode.IsText);
nextNode.parentNode = prevNode;
}
internal static void UnnestTextNodes(XmlNode prevNode, XmlNode nextNode)
{
Debug.Assert(prevNode.IsText);
Debug.Assert(nextNode.IsText);
nextNode.parentNode = prevNode.ParentNode;
}
private object debuggerDisplayProxy { get { return new DebuggerDisplayXmlNodeProxy(this); } }
[DebuggerDisplay("{ToString()}")]
internal readonly struct DebuggerDisplayXmlNodeProxy
{
private readonly XmlNode _node;
public DebuggerDisplayXmlNodeProxy(XmlNode node)
{
_node = node;
}
public override string ToString()
{
XmlNodeType nodeType = _node.NodeType;
string result = nodeType.ToString();
switch (nodeType)
{
case XmlNodeType.Element:
case XmlNodeType.EntityReference:
result += ", Name=\"" + _node.Name + "\"";
break;
case XmlNodeType.Attribute:
case XmlNodeType.ProcessingInstruction:
result += ", Name=\"" + _node.Name + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(_node.Value) + "\"";
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Comment:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.XmlDeclaration:
result += ", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(_node.Value) + "\"";
break;
case XmlNodeType.DocumentType:
XmlDocumentType documentType = (XmlDocumentType)_node;
result += ", Name=\"" + documentType.Name + "\", SYSTEM=\"" + documentType.SystemId + "\", PUBLIC=\"" + documentType.PublicId + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(documentType.InternalSubset) + "\"";
break;
default:
break;
}
return result;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for NetworkInterfacesOperations.
/// </summary>
public static partial class NetworkInterfacesOperationsExtensions
{
/// <summary>
/// The delete netwokInterface operation deletes the specified netwokInterface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
public static void Delete(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName)
{
Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).DeleteAsync(resourceGroupName, networkInterfaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete netwokInterface operation deletes the specified netwokInterface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The delete netwokInterface operation deletes the specified netwokInterface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
public static void BeginDelete(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName)
{
Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).BeginDeleteAsync(resourceGroupName, networkInterfaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete netwokInterface operation deletes the specified netwokInterface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The Get network interface operation retrieves information about the
/// specified network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
public static NetworkInterface Get(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, string expand = default(string))
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).GetAsync(resourceGroupName, networkInterfaceName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get network interface operation retrieves information about the
/// specified network interface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkInterface> GetAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put NetworkInterface operation creates/updates a networkInterface
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update NetworkInterface operation
/// </param>
public static NetworkInterface CreateOrUpdate(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).CreateOrUpdateAsync(resourceGroupName, networkInterfaceName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put NetworkInterface operation creates/updates a networkInterface
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update NetworkInterface operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkInterface> CreateOrUpdateAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put NetworkInterface operation creates/updates a networkInterface
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update NetworkInterface operation
/// </param>
public static NetworkInterface BeginCreateOrUpdate(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, networkInterfaceName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put NetworkInterface operation creates/updates a networkInterface
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update NetworkInterface operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkInterface> BeginCreateOrUpdateAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list network interface operation retrieves information about all
/// network interfaces in a virtual machine from a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
public static IPage<NetworkInterface> ListVirtualMachineScaleSetVMNetworkInterfaces(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListVirtualMachineScaleSetVMNetworkInterfacesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list network interface operation retrieves information about all
/// network interfaces in a virtual machine from a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkInterface>> ListVirtualMachineScaleSetVMNetworkInterfacesAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListVirtualMachineScaleSetVMNetworkInterfacesWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list network interface operation retrieves information about all
/// network interfaces in a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
public static IPage<NetworkInterface> ListVirtualMachineScaleSetNetworkInterfaces(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListVirtualMachineScaleSetNetworkInterfacesAsync(resourceGroupName, virtualMachineScaleSetName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list network interface operation retrieves information about all
/// network interfaces in a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkInterface>> ListVirtualMachineScaleSetNetworkInterfacesAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListVirtualMachineScaleSetNetworkInterfacesWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Get network interface operation retrieves information about the
/// specified network interface in a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
public static NetworkInterface GetVirtualMachineScaleSetNetworkInterface(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string))
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).GetVirtualMachineScaleSetNetworkInterfaceAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get network interface operation retrieves information about the
/// specified network interface in a virtual machine scale set.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkInterface> GetVirtualMachineScaleSetNetworkInterfaceAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetVirtualMachineScaleSetNetworkInterfaceWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List networkInterfaces operation retrieves all the networkInterfaces
/// in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<NetworkInterface> ListAll(this INetworkInterfacesOperations operations)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List networkInterfaces operation retrieves all the networkInterfaces
/// in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkInterface>> ListAllAsync(this INetworkInterfacesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List networkInterfaces operation retrieves all the networkInterfaces
/// in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<NetworkInterface> List(this INetworkInterfacesOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List networkInterfaces operation retrieves all the networkInterfaces
/// in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkInterface>> ListAsync(this INetworkInterfacesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The get effective routetable operation retrieves all the route tables
/// applied on a networkInterface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
public static EffectiveRouteListResult GetEffectiveRouteTable(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).GetEffectiveRouteTableAsync(resourceGroupName, networkInterfaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The get effective routetable operation retrieves all the route tables
/// applied on a networkInterface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EffectiveRouteListResult> GetEffectiveRouteTableAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetEffectiveRouteTableWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The get effective routetable operation retrieves all the route tables
/// applied on a networkInterface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
public static EffectiveRouteListResult BeginGetEffectiveRouteTable(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).BeginGetEffectiveRouteTableAsync(resourceGroupName, networkInterfaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The get effective routetable operation retrieves all the route tables
/// applied on a networkInterface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EffectiveRouteListResult> BeginGetEffectiveRouteTableAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetEffectiveRouteTableWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list effective network security group operation retrieves all the
/// network security groups applied on a networkInterface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
public static EffectiveNetworkSecurityGroupListResult ListEffectiveNetworkSecurityGroups(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListEffectiveNetworkSecurityGroupsAsync(resourceGroupName, networkInterfaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list effective network security group operation retrieves all the
/// network security groups applied on a networkInterface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EffectiveNetworkSecurityGroupListResult> ListEffectiveNetworkSecurityGroupsAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list effective network security group operation retrieves all the
/// network security groups applied on a networkInterface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
public static EffectiveNetworkSecurityGroupListResult BeginListEffectiveNetworkSecurityGroups(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).BeginListEffectiveNetworkSecurityGroupsAsync(resourceGroupName, networkInterfaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list effective network security group operation retrieves all the
/// network security groups applied on a networkInterface.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EffectiveNetworkSecurityGroupListResult> BeginListEffectiveNetworkSecurityGroupsAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list network interface operation retrieves information about all
/// network interfaces in a virtual machine from a virtual machine scale set.
/// </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<NetworkInterface> ListVirtualMachineScaleSetVMNetworkInterfacesNext(this INetworkInterfacesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListVirtualMachineScaleSetVMNetworkInterfacesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list network interface operation retrieves information about all
/// network interfaces in a virtual machine from a virtual machine scale set.
/// </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<NetworkInterface>> ListVirtualMachineScaleSetVMNetworkInterfacesNextAsync(this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListVirtualMachineScaleSetVMNetworkInterfacesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list network interface operation retrieves information about all
/// network interfaces in a virtual machine scale set.
/// </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<NetworkInterface> ListVirtualMachineScaleSetNetworkInterfacesNext(this INetworkInterfacesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListVirtualMachineScaleSetNetworkInterfacesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list network interface operation retrieves information about all
/// network interfaces in a virtual machine scale set.
/// </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<NetworkInterface>> ListVirtualMachineScaleSetNetworkInterfacesNextAsync(this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListVirtualMachineScaleSetNetworkInterfacesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List networkInterfaces operation retrieves all the networkInterfaces
/// in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<NetworkInterface> ListAllNext(this INetworkInterfacesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List networkInterfaces operation retrieves all the networkInterfaces
/// in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkInterface>> ListAllNextAsync(this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List networkInterfaces operation retrieves all the networkInterfaces
/// in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<NetworkInterface> ListNext(this INetworkInterfacesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List networkInterfaces operation retrieves all the networkInterfaces
/// in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkInterface>> ListNextAsync(this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace XenAPI
{
/// <summary>
/// a proxy connects a VM/VIF with a PVS site
/// First published in XenServer 7.1.
/// </summary>
public partial class PVS_proxy : XenObject<PVS_proxy>
{
public PVS_proxy()
{
}
public PVS_proxy(string uuid,
XenRef<PVS_site> site,
XenRef<VIF> VIF,
bool currently_attached,
pvs_proxy_status status)
{
this.uuid = uuid;
this.site = site;
this.VIF = VIF;
this.currently_attached = currently_attached;
this.status = status;
}
/// <summary>
/// Creates a new PVS_proxy from a Proxy_PVS_proxy.
/// </summary>
/// <param name="proxy"></param>
public PVS_proxy(Proxy_PVS_proxy proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(PVS_proxy update)
{
uuid = update.uuid;
site = update.site;
VIF = update.VIF;
currently_attached = update.currently_attached;
status = update.status;
}
internal void UpdateFromProxy(Proxy_PVS_proxy proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
site = proxy.site == null ? null : XenRef<PVS_site>.Create(proxy.site);
VIF = proxy.VIF == null ? null : XenRef<VIF>.Create(proxy.VIF);
currently_attached = (bool)proxy.currently_attached;
status = proxy.status == null ? (pvs_proxy_status) 0 : (pvs_proxy_status)Helper.EnumParseDefault(typeof(pvs_proxy_status), (string)proxy.status);
}
public Proxy_PVS_proxy ToProxy()
{
Proxy_PVS_proxy result_ = new Proxy_PVS_proxy();
result_.uuid = uuid ?? "";
result_.site = site ?? "";
result_.VIF = VIF ?? "";
result_.currently_attached = currently_attached;
result_.status = pvs_proxy_status_helper.ToString(status);
return result_;
}
/// <summary>
/// Creates a new PVS_proxy from a Hashtable.
/// </summary>
/// <param name="table"></param>
public PVS_proxy(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
site = Marshalling.ParseRef<PVS_site>(table, "site");
VIF = Marshalling.ParseRef<VIF>(table, "VIF");
currently_attached = Marshalling.ParseBool(table, "currently_attached");
status = (pvs_proxy_status)Helper.EnumParseDefault(typeof(pvs_proxy_status), Marshalling.ParseString(table, "status"));
}
public bool DeepEquals(PVS_proxy other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._site, other._site) &&
Helper.AreEqual2(this._VIF, other._VIF) &&
Helper.AreEqual2(this._currently_attached, other._currently_attached) &&
Helper.AreEqual2(this._status, other._status);
}
public override string SaveChanges(Session session, string opaqueRef, PVS_proxy server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given PVS_proxy.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static PVS_proxy get_record(Session session, string _pvs_proxy)
{
return new PVS_proxy((Proxy_PVS_proxy)session.proxy.pvs_proxy_get_record(session.uuid, _pvs_proxy ?? "").parse());
}
/// <summary>
/// Get a reference to the PVS_proxy instance with the specified UUID.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PVS_proxy> get_by_uuid(Session session, string _uuid)
{
return XenRef<PVS_proxy>.Create(session.proxy.pvs_proxy_get_by_uuid(session.uuid, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given PVS_proxy.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static string get_uuid(Session session, string _pvs_proxy)
{
return (string)session.proxy.pvs_proxy_get_uuid(session.uuid, _pvs_proxy ?? "").parse();
}
/// <summary>
/// Get the site field of the given PVS_proxy.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static XenRef<PVS_site> get_site(Session session, string _pvs_proxy)
{
return XenRef<PVS_site>.Create(session.proxy.pvs_proxy_get_site(session.uuid, _pvs_proxy ?? "").parse());
}
/// <summary>
/// Get the VIF field of the given PVS_proxy.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static XenRef<VIF> get_VIF(Session session, string _pvs_proxy)
{
return XenRef<VIF>.Create(session.proxy.pvs_proxy_get_vif(session.uuid, _pvs_proxy ?? "").parse());
}
/// <summary>
/// Get the currently_attached field of the given PVS_proxy.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static bool get_currently_attached(Session session, string _pvs_proxy)
{
return (bool)session.proxy.pvs_proxy_get_currently_attached(session.uuid, _pvs_proxy ?? "").parse();
}
/// <summary>
/// Get the status field of the given PVS_proxy.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static pvs_proxy_status get_status(Session session, string _pvs_proxy)
{
return (pvs_proxy_status)Helper.EnumParseDefault(typeof(pvs_proxy_status), (string)session.proxy.pvs_proxy_get_status(session.uuid, _pvs_proxy ?? "").parse());
}
/// <summary>
/// Configure a VM/VIF to use a PVS proxy
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_site">PVS site that we proxy for</param>
/// <param name="_vif">VIF for the VM that needs to be proxied</param>
public static XenRef<PVS_proxy> create(Session session, string _site, string _vif)
{
return XenRef<PVS_proxy>.Create(session.proxy.pvs_proxy_create(session.uuid, _site ?? "", _vif ?? "").parse());
}
/// <summary>
/// Configure a VM/VIF to use a PVS proxy
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_site">PVS site that we proxy for</param>
/// <param name="_vif">VIF for the VM that needs to be proxied</param>
public static XenRef<Task> async_create(Session session, string _site, string _vif)
{
return XenRef<Task>.Create(session.proxy.async_pvs_proxy_create(session.uuid, _site ?? "", _vif ?? "").parse());
}
/// <summary>
/// remove (or switch off) a PVS proxy for this VM
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static void destroy(Session session, string _pvs_proxy)
{
session.proxy.pvs_proxy_destroy(session.uuid, _pvs_proxy ?? "").parse();
}
/// <summary>
/// remove (or switch off) a PVS proxy for this VM
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static XenRef<Task> async_destroy(Session session, string _pvs_proxy)
{
return XenRef<Task>.Create(session.proxy.async_pvs_proxy_destroy(session.uuid, _pvs_proxy ?? "").parse());
}
/// <summary>
/// Return a list of all the PVS_proxys known to the system.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PVS_proxy>> get_all(Session session)
{
return XenRef<PVS_proxy>.Create(session.proxy.pvs_proxy_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the PVS_proxy Records at once, in a single XML RPC call
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PVS_proxy>, PVS_proxy> get_all_records(Session session)
{
return XenRef<PVS_proxy>.Create<Proxy_PVS_proxy>(session.proxy.pvs_proxy_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// PVS site this proxy is part of
/// </summary>
public virtual XenRef<PVS_site> site
{
get { return _site; }
set
{
if (!Helper.AreEqual(value, _site))
{
_site = value;
Changed = true;
NotifyPropertyChanged("site");
}
}
}
private XenRef<PVS_site> _site;
/// <summary>
/// VIF of the VM using the proxy
/// </summary>
public virtual XenRef<VIF> VIF
{
get { return _VIF; }
set
{
if (!Helper.AreEqual(value, _VIF))
{
_VIF = value;
Changed = true;
NotifyPropertyChanged("VIF");
}
}
}
private XenRef<VIF> _VIF;
/// <summary>
/// true = VM is currently proxied
/// </summary>
public virtual bool currently_attached
{
get { return _currently_attached; }
set
{
if (!Helper.AreEqual(value, _currently_attached))
{
_currently_attached = value;
Changed = true;
NotifyPropertyChanged("currently_attached");
}
}
}
private bool _currently_attached;
/// <summary>
/// The run-time status of the proxy
/// </summary>
public virtual pvs_proxy_status status
{
get { return _status; }
set
{
if (!Helper.AreEqual(value, _status))
{
_status = value;
Changed = true;
NotifyPropertyChanged("status");
}
}
}
private pvs_proxy_status _status;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Test.ModuleCore;
namespace CoreXml.Test.XLinq
{
//////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// EventsHelper Class: Used for event registration and notification for all event testing.
/// </summary>
//////////////////////////////////////////////////////////////////////////////////////////////////////
public class EventsHelper : IDisposable
{
private XObject _root;
private EventItem _pending;
private Queue<EventItem> _events;
private IEqualityComparer _nodeComparer = XNode.EqualityComparer;
private XAttributeEqualityComparer<XAttribute> _attributeComparer = new XAttributeEqualityComparer<XAttribute>();
public EventsHelper(XObject x)
{
_root = x;
_root.Changing += new EventHandler<XObjectChangeEventArgs>(Changing);
_root.Changed += new EventHandler<XObjectChangeEventArgs>(Changed);
_events = new Queue<EventItem>();
}
public void RemoveListners()
{
_root.Changing -= new EventHandler<XObjectChangeEventArgs>(Changing);
_root.Changed -= new EventHandler<XObjectChangeEventArgs>(Changed);
}
public void Dispose()
{
this.RemoveListners();
}
public void Changing(object sender, XObjectChangeEventArgs e)
{
if (_pending != null)
throw new NotImplementedException();
_pending = new EventItem((XObject)sender, e);
}
public void Changed(object sender, XObjectChangeEventArgs e)
{
TestLog.Compare(_pending.Sender, sender, "Mismatch in changed and changing events");
TestLog.Compare(_pending.EventArgs, e, "Mismatch in changed and changing events");
_events.Enqueue(_pending);
_pending = null;
}
// If all you care about is number of expected events and not the type
public void Verify(int expectedCount)
{
TestLog.Compare(_events.Count, expectedCount, "Mismatch in expected number of events");
_events.Clear();
}
// Single event of specified type expected
public void Verify(XObjectChange expectedEvent)
{
Verify(expectedEvent, 1);
}
// Number of events of a certain type are expected to be thrown
public void Verify(XObjectChange expectedEvent, int expectedCount)
{
TestLog.Compare(_events.Count, expectedCount, "Mismatch in expected number of events");
while (_events.Count > 0)
{
EventItem item = _events.Dequeue();
TestLog.Compare(item.EventArgs.ObjectChange, expectedEvent, "Event Type Mismatch");
}
}
// Know exactly what events should be thrown and in what order
public void Verify(XObjectChange[] expectedEvents)
{
TestLog.Compare(_events.Count, expectedEvents.Length, "Mismatch in expected number of events");
int i = 0;
while (_events.Count > 0)
{
EventItem item = _events.Dequeue();
TestLog.Compare(item.EventArgs.ObjectChange, expectedEvents[i], "Event Type Mismatch");
i++;
}
}
// Single event and object
public void Verify(XObjectChange expectedEvent, object expectedObject)
{
TestLog.Compare(_events.Count, 1, "Mismatch in expected number of events");
EventItem item = _events.Dequeue();
TestLog.Compare(item.EventArgs.ObjectChange, expectedEvent, "Event Type Mismatch");
TestLog.Compare(item.Sender, (XObject)expectedObject, "Object Mismatch");
}
// Same event for many different objects
public void Verify(XObjectChange expectedEvent, object[] expectedObjects)
{
TestLog.Compare(_events.Count, expectedObjects.Length, "Mismatch in expected number of events");
int i = 0;
while (_events.Count > 0)
{
EventItem item = _events.Dequeue();
TestLog.Compare(item.EventArgs.ObjectChange, expectedEvent, "Event Type Mismatch");
TestLog.Compare(item.Sender, (XObject)expectedObjects[i], "Object Mismatch");
i++;
}
}
// One event for one object
public void Verify(XObjectChange expectedEvent, XObject expectedObject)
{
TestLog.Compare(_events.Count, 1, "Mismatch in expected number of events");
EventItem item = _events.Dequeue();
TestLog.Compare(item.EventArgs.ObjectChange, expectedEvent, "Event Type Mismatch");
if (item.Sender is XAttribute)
TestLog.Compare(_attributeComparer.Equals((XAttribute)item.Sender, (XAttribute)expectedObject), "Attribute Mismatch");
else
TestLog.Compare(_nodeComparer.Equals((XNode)item.Sender, expectedObject), "Node Mismatch");
}
// Same event for many different XNodes
public void Verify(XObjectChange expectedEvent, XObject[] expectedObjects)
{
TestLog.Compare(_events.Count, expectedObjects.Length, "Mismatch in expected number of events");
int i = 0;
while (_events.Count > 0)
{
EventItem item = _events.Dequeue();
TestLog.Compare(item.EventArgs.ObjectChange, expectedEvent, "Event Type Mismatch");
if (item.Sender is XAttribute)
TestLog.Compare(_attributeComparer.Equals((XAttribute)item.Sender, (XAttribute)expectedObjects[i]), "Attribute Mismatch");
else
TestLog.Compare(_nodeComparer.Equals((XNode)item.Sender, expectedObjects[i]), "Node Mismatch");
i++;
}
}
// Different events for different objects
public void Verify(XObjectChange[] expectedEvents, XObject[] expectedObjects)
{
TestLog.Compare(_events.Count, expectedEvents.Length, "Mismatch in expected number of events");
int i = 0;
while (_events.Count > 0)
{
EventItem item = _events.Dequeue();
TestLog.Compare(item.EventArgs.ObjectChange, expectedEvents[i], "Event Type Mismatch");
if (item.Sender is XAttribute)
TestLog.Compare(_attributeComparer.Equals((XAttribute)item.Sender, (XAttribute)expectedObjects[i]), "Attribute Mismatch");
else
TestLog.Compare(_nodeComparer.Equals((XNode)item.Sender, expectedObjects[i]), "Node Mismatch");
i++;
}
}
}
class EventItem
{
private XObject _sender;
private XObjectChangeEventArgs _eventArgs;
public EventItem(XObject sender, XObjectChangeEventArgs eventArgs)
{
_sender = sender;
_eventArgs = eventArgs;
}
public XObject Sender
{
get { return _sender; }
}
public XObjectChangeEventArgs EventArgs
{
get { return _eventArgs; }
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// UndoManager provided by the product team
/// </summary>
//////////////////////////////////////////////////////////////////////////////////////////////////////
public class UndoManager : IDisposable
{
private XObject _root;
private UndoUnit _pending;
private Stack<UndoUnit> _undos;
private Stack<UndoUnit> _redos;
private bool _undoing;
private bool _redoing;
private int _lastGroup;
public UndoManager(XObject root)
{
if (root == null) throw new ArgumentNullException();
_root = root;
_root.Changing += new EventHandler<XObjectChangeEventArgs>(Changing);
_root.Changed += new EventHandler<XObjectChangeEventArgs>(Changed);
_undos = new Stack<UndoUnit>();
_redos = new Stack<UndoUnit>();
}
public void Dispose()
{
_root.Changing -= new EventHandler<XObjectChangeEventArgs>(Changing);
_root.Changed -= new EventHandler<XObjectChangeEventArgs>(Changed);
}
public void Group()
{
if (!_undoing && !_redoing)
{
_redos.Clear();
}
_lastGroup++;
}
public void Undo()
{
try
{
_undoing = true;
if (_undos.Count > 0)
{
Group();
UndoUnit unit;
do
{
unit = _undos.Pop();
unit.Undo();
} while (_undos.Count > 0 && _undos.Peek().Group == unit.Group);
}
}
finally
{
_undoing = false;
}
}
public void Redo()
{
try
{
_redoing = true;
if (_redos.Count > 0)
{
Group();
UndoUnit unit;
do
{
unit = _redos.Pop();
unit.Undo();
} while (_redos.Count > 0 && _redos.Peek().Group == unit.Group);
}
}
finally
{
_redoing = false;
}
}
public override string ToString()
{
return "(" + _lastGroup.ToString() + "):\n" + _root.ToString();
}
void Changing(object sender, XObjectChangeEventArgs e)
{
if (_pending != null) throw new NotImplementedException();
switch (e.ObjectChange)
{
case XObjectChange.Add:
_pending = new AddUnit((XObject)sender);
break;
case XObjectChange.Remove:
XContainer parent = ((XObject)sender).Parent;
if (parent == null)
{
parent = ((XObject)sender).Document;
}
XObject next = null;
if (sender is XNode)
{
next = ((XNode)sender).NextNode;
}
else if (sender is XAttribute)
{
next = ((XAttribute)sender).NextAttribute;
}
_pending = new RemoveUnit((XObject)sender, parent, next);
break;
case XObjectChange.Name:
object name = null;
if (sender is XNode)
{
switch (((XNode)sender).NodeType)
{
case XmlNodeType.Element:
name = ((XElement)sender).Name;
break;
case XmlNodeType.ProcessingInstruction:
name = ((XProcessingInstruction)sender).Target;
break;
default:
throw new NotImplementedException();
}
}
_pending = new NameUnit((XNode)sender, name);
break;
case XObjectChange.Value:
string value = null;
if (sender is XNode)
{
switch (((XNode)sender).NodeType)
{
case XmlNodeType.Element:
value = ((XElement)sender).IsEmpty ? null : string.Empty;
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
value = ((XText)sender).Value;
break;
case XmlNodeType.ProcessingInstruction:
value = ((XProcessingInstruction)sender).Data;
break;
case XmlNodeType.Comment:
value = ((XComment)sender).Value;
break;
default:
throw new NotImplementedException();
}
}
else if (sender is XAttribute)
{
value = ((XAttribute)sender).Value;
}
_pending = new ValueUnit((XObject)sender, value);
break;
}
}
void Changed(object sender, XObjectChangeEventArgs e)
{
_pending.Group = _lastGroup;
if (_undoing)
{
_redos.Push(_pending);
}
else
{
_undos.Push(_pending);
}
_pending = null;
}
}
abstract class UndoUnit
{
private int _group;
public UndoUnit()
{
}
public int Group
{
get { return _group; }
set { _group = value; }
}
public abstract void Undo();
}
class AddUnit : UndoUnit
{
private XObject _sender;
public AddUnit(XObject sender)
{
_sender = sender;
}
public override void Undo()
{
if (_sender is XNode)
{
((XNode)_sender).Remove();
return;
}
if (_sender is XAttribute)
{
((XAttribute)_sender).Remove();
}
}
}
class RemoveUnit : UndoUnit
{
private XObject _sender;
private XContainer _parent;
private XObject _next;
public RemoveUnit(XObject sender, XContainer parent, XObject next)
{
_sender = sender;
_parent = parent;
_next = next;
}
public override void Undo()
{
if (_sender is XNode)
{
if (_next is XNode)
{
((XNode)_next).AddBeforeSelf(((XNode)_sender));
}
else
{
_parent.Add((XNode)_sender);
}
return;
}
if (_sender is XAttribute)
{
_parent.Add((XAttribute)_sender);
}
}
}
class NameUnit : UndoUnit
{
private XNode _sender;
private object _name;
public NameUnit(XNode sender, object name)
{
_sender = sender;
_name = name;
}
public override void Undo()
{
switch (_sender.NodeType)
{
case XmlNodeType.Element:
((XElement)_sender).Name = (XName)_name;
break;
case XmlNodeType.ProcessingInstruction:
((XProcessingInstruction)_sender).Target = (string)_name;
break;
default:
throw new NotImplementedException();
}
}
}
class ValueUnit : UndoUnit
{
private XObject _sender;
private string _value;
public ValueUnit(XObject sender, string value)
{
_sender = sender;
_value = value;
}
public override void Undo()
{
if (_sender is XNode)
{
switch (((XNode)_sender).NodeType)
{
case XmlNodeType.Element:
if (_value == null)
{
((XElement)_sender).RemoveNodes();
}
else
{
((XElement)_sender).Add(string.Empty);
}
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
((XText)_sender).Value = _value;
break;
case XmlNodeType.ProcessingInstruction:
((XProcessingInstruction)_sender).Data = _value;
break;
case XmlNodeType.Comment:
((XComment)_sender).Value = _value;
break;
default:
throw new NotImplementedException();
}
return;
}
if (_sender is XAttribute)
{
((XAttribute)_sender).Value = (string)_value;
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
namespace Multiverse.Base
{
partial class ConfigDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
// public void Layout() {
// int imageWidth = 411;
// int imageHeight = 206;
// int pad = 13;
// logoPicture.Location = new System.Drawing.Point(13, 13);
// renderOptions.Location = new System.Drawing.Point(9, 254);
// renderOptions.Size = new System.Drawing.Size(imageWidth, 153);
//
// attributeListBox.Location = new System.Drawing.Point(7, 20);
// attributeListBox.Size = new System.Drawing.Size(imageWidth - 12, 102);
// int attrValWidth = 212;
// attrValComboBox.Location = new System.Drawing.Point(imageWidth - 4 - attrValWidth, 126);
// attrValComboBox.Size = new System.Drawing.Size(212, 21);
// }
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ConfigDialog));
this.renderOptions = new System.Windows.Forms.GroupBox();
this.aaComboBox = new System.Windows.Forms.ComboBox();
this.aaLabel = new System.Windows.Forms.Label();
this.nvPerfHUDGroupBox = new System.Windows.Forms.GroupBox();
this.nvPerfHUDNoButton = new System.Windows.Forms.RadioButton();
this.nvPerfHUDYesButton = new System.Windows.Forms.RadioButton();
this.vsyncGroupBox = new System.Windows.Forms.GroupBox();
this.vsyncNoButton = new System.Windows.Forms.RadioButton();
this.vsyncYesButton = new System.Windows.Forms.RadioButton();
this.fullScreenGroupBox = new System.Windows.Forms.GroupBox();
this.fullScreenNoButton = new System.Windows.Forms.RadioButton();
this.fullScreenYesButton = new System.Windows.Forms.RadioButton();
this.videoModeComboBox = new System.Windows.Forms.ComboBox();
this.videoModeLabel = new System.Windows.Forms.Label();
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.logoPicture = new System.Windows.Forms.PictureBox();
this.renderSystemLabel = new System.Windows.Forms.Label();
this.renderSystemComboBox = new System.Windows.Forms.ComboBox();
this.renderOptions.SuspendLayout();
this.nvPerfHUDGroupBox.SuspendLayout();
this.vsyncGroupBox.SuspendLayout();
this.fullScreenGroupBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.logoPicture)).BeginInit();
this.SuspendLayout();
//
// renderOptions
//
this.renderOptions.Controls.Add(this.aaComboBox);
this.renderOptions.Controls.Add(this.aaLabel);
this.renderOptions.Controls.Add(this.nvPerfHUDGroupBox);
this.renderOptions.Controls.Add(this.vsyncGroupBox);
this.renderOptions.Controls.Add(this.fullScreenGroupBox);
this.renderOptions.Controls.Add(this.videoModeComboBox);
this.renderOptions.Controls.Add(this.videoModeLabel);
this.renderOptions.Location = new System.Drawing.Point(9, 263);
this.renderOptions.Name = "renderOptions";
this.renderOptions.Size = new System.Drawing.Size(392, 169);
this.renderOptions.TabIndex = 0;
this.renderOptions.TabStop = false;
this.renderOptions.Text = "Rendering System Options";
//
// aaComboBox
//
this.aaComboBox.FormattingEnabled = true;
this.aaComboBox.Location = new System.Drawing.Point(134, 72);
this.aaComboBox.Name = "aaComboBox";
this.aaComboBox.Size = new System.Drawing.Size(243, 21);
this.aaComboBox.TabIndex = 6;
//
// aaLabel
//
this.aaLabel.AutoSize = true;
this.aaLabel.Location = new System.Drawing.Point(45, 75);
this.aaLabel.Name = "aaLabel";
this.aaLabel.Size = new System.Drawing.Size(66, 13);
this.aaLabel.TabIndex = 5;
this.aaLabel.Text = "Anti-aliasing:";
//
// nvPerfHUDGroupBox
//
this.nvPerfHUDGroupBox.Controls.Add(this.nvPerfHUDNoButton);
this.nvPerfHUDGroupBox.Controls.Add(this.nvPerfHUDYesButton);
this.nvPerfHUDGroupBox.Location = new System.Drawing.Point(281, 109);
this.nvPerfHUDGroupBox.Name = "nvPerfHUDGroupBox";
this.nvPerfHUDGroupBox.Size = new System.Drawing.Size(96, 46);
this.nvPerfHUDGroupBox.TabIndex = 4;
this.nvPerfHUDGroupBox.TabStop = false;
this.nvPerfHUDGroupBox.Text = "NVPerfHUD";
//
// nvPerfHUDNoButton
//
this.nvPerfHUDNoButton.AutoSize = true;
this.nvPerfHUDNoButton.Location = new System.Drawing.Point(55, 18);
this.nvPerfHUDNoButton.Name = "nvPerfHUDNoButton";
this.nvPerfHUDNoButton.Size = new System.Drawing.Size(39, 17);
this.nvPerfHUDNoButton.TabIndex = 1;
this.nvPerfHUDNoButton.TabStop = true;
this.nvPerfHUDNoButton.Text = "No";
this.nvPerfHUDNoButton.UseVisualStyleBackColor = true;
this.nvPerfHUDNoButton.CheckedChanged += new System.EventHandler(this.nvPerfHUDNoButton_CheckedChanged);
//
// nvPerfHUDYesButton
//
this.nvPerfHUDYesButton.AutoSize = true;
this.nvPerfHUDYesButton.Location = new System.Drawing.Point(8, 18);
this.nvPerfHUDYesButton.Name = "nvPerfHUDYesButton";
this.nvPerfHUDYesButton.Size = new System.Drawing.Size(43, 17);
this.nvPerfHUDYesButton.TabIndex = 0;
this.nvPerfHUDYesButton.TabStop = true;
this.nvPerfHUDYesButton.Text = "Yes";
this.nvPerfHUDYesButton.UseVisualStyleBackColor = true;
this.nvPerfHUDYesButton.CheckedChanged += new System.EventHandler(this.nvPerfHUDYesButton_CheckedChanged);
//
// vsyncGroupBox
//
this.vsyncGroupBox.Controls.Add(this.vsyncNoButton);
this.vsyncGroupBox.Controls.Add(this.vsyncYesButton);
this.vsyncGroupBox.Location = new System.Drawing.Point(148, 107);
this.vsyncGroupBox.Name = "vsyncGroupBox";
this.vsyncGroupBox.Size = new System.Drawing.Size(96, 48);
this.vsyncGroupBox.TabIndex = 3;
this.vsyncGroupBox.TabStop = false;
this.vsyncGroupBox.Text = "Video Sync";
//
// vsyncNoButton
//
this.vsyncNoButton.AutoSize = true;
this.vsyncNoButton.Location = new System.Drawing.Point(55, 18);
this.vsyncNoButton.Name = "vsyncNoButton";
this.vsyncNoButton.Size = new System.Drawing.Size(39, 17);
this.vsyncNoButton.TabIndex = 1;
this.vsyncNoButton.TabStop = true;
this.vsyncNoButton.Text = "No";
this.vsyncNoButton.UseVisualStyleBackColor = true;
this.vsyncNoButton.CheckedChanged += new System.EventHandler(this.vsyncNoButton_CheckedChanged);
//
// vsyncYesButton
//
this.vsyncYesButton.AutoSize = true;
this.vsyncYesButton.Location = new System.Drawing.Point(8, 18);
this.vsyncYesButton.Name = "vsyncYesButton";
this.vsyncYesButton.Size = new System.Drawing.Size(43, 17);
this.vsyncYesButton.TabIndex = 0;
this.vsyncYesButton.TabStop = true;
this.vsyncYesButton.Text = "Yes";
this.vsyncYesButton.UseVisualStyleBackColor = true;
this.vsyncYesButton.CheckedChanged += new System.EventHandler(this.vsyncYesButton_CheckedChanged);
//
// fullScreenGroupBox
//
this.fullScreenGroupBox.Controls.Add(this.fullScreenNoButton);
this.fullScreenGroupBox.Controls.Add(this.fullScreenYesButton);
this.fullScreenGroupBox.Location = new System.Drawing.Point(15, 107);
this.fullScreenGroupBox.Name = "fullScreenGroupBox";
this.fullScreenGroupBox.Size = new System.Drawing.Size(96, 48);
this.fullScreenGroupBox.TabIndex = 2;
this.fullScreenGroupBox.TabStop = false;
this.fullScreenGroupBox.Text = "Full Screen";
//
// fullScreenNoButton
//
this.fullScreenNoButton.AutoSize = true;
this.fullScreenNoButton.Location = new System.Drawing.Point(55, 18);
this.fullScreenNoButton.Name = "fullScreenNoButton";
this.fullScreenNoButton.Size = new System.Drawing.Size(39, 17);
this.fullScreenNoButton.TabIndex = 1;
this.fullScreenNoButton.TabStop = true;
this.fullScreenNoButton.Text = "No";
this.fullScreenNoButton.UseVisualStyleBackColor = true;
this.fullScreenNoButton.CheckedChanged += new System.EventHandler(this.fullScreenNoButton_CheckedChanged);
//
// fullScreenYesButton
//
this.fullScreenYesButton.AutoSize = true;
this.fullScreenYesButton.Location = new System.Drawing.Point(8, 18);
this.fullScreenYesButton.Name = "fullScreenYesButton";
this.fullScreenYesButton.Size = new System.Drawing.Size(43, 17);
this.fullScreenYesButton.TabIndex = 0;
this.fullScreenYesButton.TabStop = true;
this.fullScreenYesButton.Text = "Yes";
this.fullScreenYesButton.UseVisualStyleBackColor = true;
this.fullScreenYesButton.CheckedChanged += new System.EventHandler(this.fullScreenYesButton_CheckedChanged);
//
// videoModeComboBox
//
this.videoModeComboBox.FormattingEnabled = true;
this.videoModeComboBox.Location = new System.Drawing.Point(134, 33);
this.videoModeComboBox.Margin = new System.Windows.Forms.Padding(0, 3, 3, 3);
this.videoModeComboBox.Name = "videoModeComboBox";
this.videoModeComboBox.Size = new System.Drawing.Size(243, 21);
this.videoModeComboBox.TabIndex = 1;
//
// videoModeLabel
//
this.videoModeLabel.AutoSize = true;
this.videoModeLabel.Location = new System.Drawing.Point(47, 39);
this.videoModeLabel.Margin = new System.Windows.Forms.Padding(3, 3, 1, 3);
this.videoModeLabel.Name = "videoModeLabel";
this.videoModeLabel.Size = new System.Drawing.Size(67, 13);
this.videoModeLabel.TabIndex = 0;
this.videoModeLabel.Text = "Video Mode:";
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(243, 449);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(75, 22);
this.buttonOk.TabIndex = 1;
this.buttonOk.Text = "OK";
this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click);
//
// buttonCancel
//
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Location = new System.Drawing.Point(326, 449);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 22);
this.buttonCancel.TabIndex = 2;
this.buttonCancel.Text = "Cancel";
//
// logoPicture
//
this.logoPicture.Location = new System.Drawing.Point(32, 10);
this.logoPicture.Name = "logoPicture";
this.logoPicture.Size = new System.Drawing.Size(343, 198);
this.logoPicture.TabIndex = 3;
this.logoPicture.TabStop = false;
this.logoPicture.Click += new System.EventHandler(this.f);
//
// renderSystemLabel
//
this.renderSystemLabel.AutoSize = true;
this.renderSystemLabel.Location = new System.Drawing.Point(13, 229);
this.renderSystemLabel.Name = "renderSystemLabel";
this.renderSystemLabel.Size = new System.Drawing.Size(110, 13);
this.renderSystemLabel.TabIndex = 4;
this.renderSystemLabel.Text = "Rendering Subsystem";
//
// renderSystemComboBox
//
this.renderSystemComboBox.FormattingEnabled = true;
this.renderSystemComboBox.Location = new System.Drawing.Point(143, 226);
this.renderSystemComboBox.Name = "renderSystemComboBox";
this.renderSystemComboBox.Size = new System.Drawing.Size(243, 21);
this.renderSystemComboBox.TabIndex = 5;
//
// ConfigDialog
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(492, 557);
this.Controls.Add(this.renderSystemComboBox);
this.Controls.Add(this.renderSystemLabel);
this.Controls.Add(this.logoPicture);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.renderOptions);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "ConfigDialog";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "Multiverse Graphics Configuration";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ConfigDialog_FormClosing);
this.renderOptions.ResumeLayout(false);
this.renderOptions.PerformLayout();
this.nvPerfHUDGroupBox.ResumeLayout(false);
this.nvPerfHUDGroupBox.PerformLayout();
this.vsyncGroupBox.ResumeLayout(false);
this.vsyncGroupBox.PerformLayout();
this.fullScreenGroupBox.ResumeLayout(false);
this.fullScreenGroupBox.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.logoPicture)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox renderOptions;
private System.Windows.Forms.Label videoModeLabel;
private System.Windows.Forms.Button buttonOk;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.ComboBox videoModeComboBox;
private System.Windows.Forms.PictureBox logoPicture;
private System.Windows.Forms.Label renderSystemLabel;
private System.Windows.Forms.ComboBox renderSystemComboBox;
private System.Windows.Forms.GroupBox fullScreenGroupBox;
private System.Windows.Forms.RadioButton fullScreenNoButton;
private System.Windows.Forms.RadioButton fullScreenYesButton;
private System.Windows.Forms.GroupBox nvPerfHUDGroupBox;
private System.Windows.Forms.RadioButton nvPerfHUDNoButton;
private System.Windows.Forms.RadioButton nvPerfHUDYesButton;
private System.Windows.Forms.GroupBox vsyncGroupBox;
private System.Windows.Forms.RadioButton vsyncNoButton;
private System.Windows.Forms.RadioButton vsyncYesButton;
private System.Windows.Forms.ComboBox aaComboBox;
private System.Windows.Forms.Label aaLabel;
}
}
| |
//
// ToolManager.cs
//
// Author:
// Jonathan Pobst <monkey@jpobst.com>
//
// Copyright (c) 2010 Jonathan Pobst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using Gtk;
namespace Pinta.Core
{
public class ToolManager : IEnumerable<BaseTool>
{
int index = -1;
int prev_index = -1;
private List<BaseTool> Tools;
public event EventHandler<ToolEventArgs> ToolAdded;
public event EventHandler<ToolEventArgs> ToolRemoved;
public ToolManager ()
{
Tools = new List<BaseTool> ();
}
public void AddTool (BaseTool tool)
{
tool.ToolItem.Clicked += HandlePbToolItemClicked;
tool.ToolItem.Sensitive = tool.Enabled;
Tools.Add (tool);
Tools.Sort (new ToolSorter ());
OnToolAdded (tool);
if (CurrentTool == null)
SetCurrentTool (tool);
}
public void RemoveInstanceOfTool (System.Type tool_type)
{
foreach (BaseTool tool in Tools) {
if (tool.GetType () == tool_type) {
tool.ToolItem.Clicked -= HandlePbToolItemClicked;
tool.ToolItem.Active = false;
tool.ToolItem.Sensitive = false;
Tools.Remove (tool);
Tools.Sort (new ToolSorter ());
SetCurrentTool (new DummyTool ());
OnToolRemoved (tool);
return;
}
}
}
void HandlePbToolItemClicked (object sender, EventArgs e)
{
ToggleToolButton tb = (ToggleToolButton)sender;
BaseTool t = FindTool (tb.Label);
// Don't let the user unselect the current tool
if (CurrentTool != null && t.Name == CurrentTool.Name) {
if (prev_index != index)
tb.Active = true;
return;
}
SetCurrentTool (t);
}
private BaseTool FindTool (string name)
{
name = name.ToLowerInvariant ();
foreach (BaseTool tool in Tools) {
if (tool.Name.ToLowerInvariant () == name) {
return tool;
}
}
return null;
}
public BaseTool CurrentTool {
get { if (index >= 0) {
return Tools[index];}
else {
DummyTool dummy = new DummyTool ();
SetCurrentTool (dummy);
return dummy;
}
}
}
public BaseTool PreviousTool {
get { return Tools[prev_index]; }
}
public void Commit ()
{
if (CurrentTool != null)
CurrentTool.DoCommit ();
}
public void SetCurrentTool (BaseTool tool)
{
int i = Tools.IndexOf (tool);
if (index == i)
return;
// Unload previous tool if needed
if (index >= 0) {
prev_index = index;
Tools[index].DoClearToolBar (PintaCore.Chrome.ToolToolBar);
Tools[index].DoDeactivated ();
Tools[index].ToolItem.Active = false;
}
// Load new tool
index = i;
tool.ToolItem.Active = true;
tool.DoActivated ();
tool.DoBuildToolBar (PintaCore.Chrome.ToolToolBar);
PintaCore.Workspace.Invalidate ();
PintaCore.Chrome.SetStatusBarText (string.Format (" {0}: {1}", tool.Name, tool.StatusBarText));
}
public bool SetCurrentTool (string tool)
{
BaseTool t = FindTool (tool);
if (t != null) {
SetCurrentTool (t);
return true;
}
return false;
}
public void SetCurrentTool (Gdk.Key shortcut)
{
BaseTool tool = FindNextTool (shortcut);
if (tool != null)
SetCurrentTool (tool);
}
private BaseTool FindNextTool (Gdk.Key shortcut)
{
string key = shortcut.ToString ().ToUpperInvariant ();
// Begin looking at the tool after the current one
for (int i = index + 1; i < Tools.Count; i++) {
if (Tools[i].ShortcutKey.ToString ().ToUpperInvariant () == key)
return Tools[i];
}
// Begin at the beginning and look up to the current tool
for (int i = 0; i < index; i++) {
if (Tools[i].ShortcutKey.ToString ().ToUpperInvariant () == key)
return Tools[i];
}
return null;
}
private void OnToolAdded (BaseTool tool)
{
if (ToolAdded != null)
ToolAdded (this, new ToolEventArgs (tool));
}
private void OnToolRemoved (BaseTool tool)
{
if (ToolRemoved != null)
ToolRemoved (this, new ToolEventArgs (tool));
}
#region IEnumerable<BaseTool> implementation
public IEnumerator<BaseTool> GetEnumerator ()
{
return Tools.GetEnumerator ();
}
#endregion
#region IEnumerable implementation
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
{
return Tools.GetEnumerator ();
}
#endregion
class ToolSorter : Comparer<BaseTool>
{
public override int Compare (BaseTool x, BaseTool y)
{
return x.Priority - y.Priority;
}
}
}
//This tool does nothing, is used when no tools are in toolbox. If used seriously will probably
// throw a zillion exceptions due to missing overrides
public class DummyTool : BaseTool
{
public override string Name { get { return Mono.Unix.Catalog.GetString ("No tool selected."); } }
public override string Icon { get { return Gtk.Stock.MissingImage; } }
public override string StatusBarText { get { return Mono.Unix.Catalog.GetString ("No tool selected."); } }
protected override void OnBuildToolBar (Toolbar tb)
{
tool_label = null;
tool_image = null;
tool_sep = null;
}
}
}
| |
//
// Copyright (C) DataStax 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.Generic;
using System.Linq;
using Cassandra.Mapping;
using Cassandra.Tasks;
using Cassandra.Tests.Mapping.Pocos;
using Cassandra.Tests.Mapping.TestData;
using Moq;
using NUnit.Framework;
namespace Cassandra.Tests.Mapping
{
public class InsertTests : MappingTestBase
{
[Test]
public void InsertAsync_Poco()
{
// Get a "new" user by using the test data from an existing user and changing the primary key
var user = TestDataHelper.GetUserList().First();
var newUser = new InsertUser
{
Id = Guid.NewGuid(),
Name = user.Name,
Age = user.Age,
CreatedDate = user.CreatedDate,
IsActive = user.IsActive,
LastLoginDate = user.LastLoginDate,
LoginHistory = user.LoginHistory,
LuckyNumbers = user.LuckyNumbers,
ChildrenAges = new Dictionary<string, int>(user.ChildrenAges),
FavoriteColor = user.FavoriteColor,
TypeOfUser = user.TypeOfUser,
PreferredContact = user.PreferredContactMethod,
HairColor = user.HairColor
};
var sessionMock = new Mock<ISession>(MockBehavior.Strict);
sessionMock.Setup(s => s.Keyspace).Returns<string>(null);
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>()))
.Returns(TaskHelper.ToTask(new RowSet()))
.Verifiable();
sessionMock
.Setup(s => s.PrepareAsync(It.IsAny<string>()))
.Returns<string>(cql => TaskHelper.ToTask(GetPrepared(cql)))
.Verifiable();
var mappingClient = GetMappingClient(sessionMock);
//Execute Insert and wait
mappingClient.InsertAsync(newUser).Wait(3000);
sessionMock.Verify(s => s.ExecuteAsync(It.Is<BoundStatement>(stmt =>
stmt.QueryValues.Length == TestHelper.ToDictionary(newUser).Count &&
stmt.PreparedStatement.Cql.StartsWith("INSERT INTO users (")
), It.IsAny<string>()), Times.Exactly(1));
sessionMock.Verify();
}
[Test]
public void Insert_Poco()
{
//Just a few props as it is just to test that it runs
var user = TestDataHelper.GetUserList().First();
var newUser = new InsertUser
{
Id = Guid.NewGuid(),
Name = user.Name
};
var sessionMock = new Mock<ISession>(MockBehavior.Strict);
sessionMock.Setup(s => s.Keyspace).Returns<string>(null);
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>()))
.Returns(TaskHelper.ToTask(new RowSet()))
.Verifiable();
sessionMock
.Setup(s => s.PrepareAsync(It.IsAny<string>()))
.Returns<string>(cql => TaskHelper.ToTask(GetPrepared(cql)))
.Verifiable();
var mappingClient = GetMappingClient(sessionMock);
//Execute
mappingClient.Insert(newUser);
sessionMock.Verify(s => s.ExecuteAsync(It.Is<BoundStatement>(stmt =>
stmt.QueryValues.Length == TestHelper.ToDictionary(newUser).Count &&
stmt.PreparedStatement.Cql.StartsWith("INSERT INTO users (")
), It.IsAny<string>()), Times.Exactly(1));
sessionMock.Verify();
}
[Test]
public void InsertAsync_FluentPoco()
{
// Get a "new" user by using the test data from an existing user and changing the primary key
var user = TestDataHelper.GetUserList().First();
var newUser = new FluentUser
{
Id = Guid.NewGuid(),
Name = user.Name,
Age = user.Age,
CreatedDate = user.CreatedDate,
IsActive = user.IsActive,
LastLoginDate = user.LastLoginDate,
LoginHistory = user.LoginHistory,
LuckyNumbers = user.LuckyNumbers,
ChildrenAges = new Dictionary<string, int>(user.ChildrenAges),
FavoriteColor = user.FavoriteColor,
TypeOfUser = user.TypeOfUser,
PreferredContact = user.PreferredContactMethod,
HairColor = user.HairColor
};
var sessionMock = new Mock<ISession>(MockBehavior.Strict);
sessionMock.Setup(s => s.Keyspace).Returns<string>(null);
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>()))
.Returns(TaskHelper.ToTask(new RowSet()))
.Verifiable();
sessionMock
.Setup(s => s.PrepareAsync(It.IsAny<string>()))
.Returns<string>(cql => TaskHelper.ToTask(GetPrepared(cql)))
.Verifiable();
// Insert the new user
var mappingClient = GetMappingClient(sessionMock);
mappingClient.InsertAsync(newUser).Wait(3000);
sessionMock.Verify(s => s.ExecuteAsync(It.Is<BoundStatement>(stmt =>
stmt.QueryValues.Length > 0 &&
stmt.PreparedStatement.Cql.StartsWith("INSERT INTO")
), It.IsAny<string>()), Times.Exactly(1));
sessionMock.Verify();
}
[Test]
public void Insert_Udt()
{
var album = new Album
{
Id = Guid.NewGuid(),
Name = "Images and Words",
PublishingDate = DateTimeOffset.Now,
Songs = new List<Song2>
{
new Song2 {Artist = "Dream Theater", Title = "Pull me under"},
new Song2 {Artist = "Dream Theater", Title = "Under a glass moon"}
}
};
var sessionMock = new Mock<ISession>(MockBehavior.Strict);
sessionMock.Setup(s => s.Keyspace).Returns<string>(null);
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>()))
.Returns(TaskHelper.ToTask(new RowSet()))
.Verifiable();
sessionMock
.Setup(s => s.PrepareAsync(It.IsAny<string>()))
.Returns<string>((cql) => TaskHelper.ToTask(GetPrepared(cql)))
.Verifiable();
var mapper = GetMappingClient(sessionMock);
mapper.Insert(album);
sessionMock.Verify(s => s.ExecuteAsync(It.Is<BoundStatement>(stmt =>
stmt.QueryValues.Length > 0 &&
stmt.PreparedStatement.Cql == "INSERT INTO Album (Id, Name, PublishingDate, Songs) VALUES (?, ?, ?, ?)"
), It.IsAny<string>()), Times.Exactly(1));
sessionMock.Verify();
}
[Test]
public void Insert_Without_Nulls()
{
var album = new Album
{
Id = Guid.NewGuid(),
Name = null,
PublishingDate = DateTimeOffset.Now,
Songs = null
};
var sessionMock = new Mock<ISession>(MockBehavior.Strict);
sessionMock.Setup(s => s.Keyspace).Returns<string>(null);
string query = null;
object[] parameters = null;
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>()))
.Returns(TaskHelper.ToTask(new RowSet()))
.Callback<BoundStatement, string>((stmt, profile) =>
{
query = stmt.PreparedStatement.Cql;
parameters = stmt.QueryValues;
})
.Verifiable();
sessionMock
.Setup(s => s.PrepareAsync(It.IsAny<string>()))
.Returns<string>((cql) => TaskHelper.ToTask(GetPrepared(cql)))
.Verifiable();
var mapper = GetMappingClient(sessionMock);
//with nulls by default
mapper.Insert(album);
Assert.AreEqual("INSERT INTO Album (Id, Name, PublishingDate, Songs) VALUES (?, ?, ?, ?)", query);
CollectionAssert.AreEqual(new object[] { album.Id, null, album.PublishingDate, null }, parameters);
//Without nulls
mapper.Insert(album, false);
Assert.AreEqual("INSERT INTO Album (Id, PublishingDate) VALUES (?, ?)", query);
CollectionAssert.AreEqual(new object[] { album.Id, album.PublishingDate }, parameters);
sessionMock.Verify();
}
[Test]
public void Insert_Poco_Returns_WhenResponse_IsReceived()
{
var newUser = new InsertUser
{
Id = Guid.NewGuid(),
Name = "Dummy"
};
var rowsetReturned = false;
var sessionMock = new Mock<ISession>(MockBehavior.Strict);
sessionMock.Setup(s => s.Keyspace).Returns<string>(null);
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>()))
.Returns(TestHelper.DelayedTask(new RowSet(), 2000).ContinueWith(t =>
{
rowsetReturned = true;
return t.Result;
}))
.Verifiable();
sessionMock
.Setup(s => s.PrepareAsync(It.IsAny<string>()))
.Returns<string>(cql => TaskHelper.ToTask(GetPrepared(cql)))
.Verifiable();
var mappingClient = GetMappingClient(sessionMock);
//Execute
mappingClient.Insert(newUser);
Assert.True(rowsetReturned);
sessionMock.Verify();
}
[Test]
public void InsertIfNotExists_Poco_AppliedInfo_True_Test()
{
//Just a few props as it is just to test that it runs
var user = TestDataHelper.GetUserList().First();
var newUser = new InsertUser
{
Id = Guid.NewGuid(),
Name = user.Name
};
string query = null;
var sessionMock = new Mock<ISession>(MockBehavior.Strict);
sessionMock.Setup(s => s.Keyspace).Returns<string>(null);
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>()))
.Returns(TestHelper.DelayedTask(TestDataHelper.CreateMultipleValuesRowSet(new[] { "[applied]" }, new[] { true })))
.Callback<BoundStatement, string>((b, profile) => query = b.PreparedStatement.Cql)
.Verifiable();
sessionMock
.Setup(s => s.PrepareAsync(It.IsAny<string>()))
.Returns<string>(cql => TaskHelper.ToTask(GetPrepared(cql)))
.Verifiable();
var mappingClient = GetMappingClient(sessionMock);
//Execute
var appliedInfo = mappingClient.InsertIfNotExists(newUser);
sessionMock.Verify();
StringAssert.StartsWith("INSERT INTO users (", query);
StringAssert.EndsWith(") IF NOT EXISTS", query);
Assert.True(appliedInfo.Applied);
}
[Test]
public void InsertIfNotExists_Poco_AppliedInfo_False_Test()
{
//Just a few props as it is just to test that it runs
var user = TestDataHelper.GetUserList().First();
var newUser = new InsertUser
{
Id = Guid.NewGuid(),
Name = user.Name
};
string query = null;
var sessionMock = new Mock<ISession>(MockBehavior.Strict);
sessionMock.Setup(s => s.Keyspace).Returns<string>(null);
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>()))
.Returns(TestHelper.DelayedTask(TestDataHelper.CreateMultipleValuesRowSet(new[] { "[applied]", "userid", "name" }, new object[] { false, newUser.Id, "existing-name" })))
.Callback<BoundStatement, string>((b, profile) => query = b.PreparedStatement.Cql)
.Verifiable();
sessionMock
.Setup(s => s.PrepareAsync(It.IsAny<string>()))
.Returns<string>(cql => TaskHelper.ToTask(GetPrepared(cql)))
.Verifiable();
var mappingClient = GetMappingClient(sessionMock);
//Execute
var appliedInfo = mappingClient.InsertIfNotExists(newUser);
sessionMock.Verify();
StringAssert.StartsWith("INSERT INTO users (", query);
StringAssert.EndsWith(") IF NOT EXISTS", query);
Assert.False(appliedInfo.Applied);
Assert.AreEqual(newUser.Id, appliedInfo.Existing.Id);
Assert.AreEqual("existing-name", appliedInfo.Existing.Name);
}
[Test]
public void Insert_With_Ttl_Test()
{
string query = null;
object[] parameters = null;
var mapper = GetMappingClient(() => TaskHelper.ToTask(RowSet.Empty()), (q, p) =>
{
query = q;
parameters = p;
});
var song = new Song { Id = Guid.NewGuid() };
const int ttl = 600;
mapper.Insert(song, true, ttl);
Assert.AreEqual("INSERT INTO Song (Artist, Id, ReleaseDate, Title) VALUES (?, ?, ?, ?) USING TTL ?", query);
Assert.AreEqual(song.Id, parameters[1]);
Assert.AreEqual(ttl, parameters.Last());
}
[Test]
public void InsertIfNotExists_With_Ttl_Test()
{
string query = null;
object[] parameters = null;
var mapper = GetMappingClient(() => TaskHelper.ToTask(RowSet.Empty()), (q, p) =>
{
query = q;
parameters = p;
});
var song = new Song { Id = Guid.NewGuid(), Title = "t2", ReleaseDate = DateTimeOffset.Now };
const int ttl = 600;
mapper.InsertIfNotExists(song, false, ttl);
Assert.AreEqual("INSERT INTO Song (Id, ReleaseDate, Title) VALUES (?, ?, ?) IF NOT EXISTS USING TTL ?", query);
Assert.AreEqual(song.Id, parameters[0]);
Assert.AreEqual(song.ReleaseDate, parameters[1]);
Assert.AreEqual(song.Title, parameters[2]);
Assert.AreEqual(ttl, parameters[3]);
}
[Test]
public void Insert_SetTimestamp_Test()
{
BoundStatement statement = null;
var sessionMock = new Mock<ISession>(MockBehavior.Strict);
sessionMock.Setup(s => s.Keyspace).Returns<string>(null);
sessionMock.Setup(s => s.Cluster).Returns((ICluster)null);
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>()))
.Returns(TaskHelper.ToTask(new RowSet()))
.Callback<BoundStatement, string>((stmt, profile) => statement = stmt)
.Verifiable();
sessionMock
.Setup(s => s.PrepareAsync(It.IsAny<string>()))
.Returns<string>((cql) => TaskHelper.ToTask(GetPrepared(cql)))
.Verifiable();
var mapper = GetMappingClient(sessionMock);
var song = new Song { Id = Guid.NewGuid(), Title = "t2", ReleaseDate = DateTimeOffset.Now };
var timestamp = DateTimeOffset.Now.Subtract(TimeSpan.FromDays(1));
mapper.Insert(song);
Assert.Null(statement.Timestamp);
mapper.Insert(song, CqlQueryOptions.New().SetTimestamp(timestamp));
Assert.AreEqual(timestamp, statement.Timestamp);
timestamp = DateTimeOffset.Now.Subtract(TimeSpan.FromHours(10));
mapper.InsertIfNotExists(song, CqlQueryOptions.New().SetTimestamp(timestamp));
Assert.AreEqual(timestamp, statement.Timestamp);
}
[Test]
public void Insert_Poco_With_Enum_Collections()
{
string query = null;
object[] parameters = null;
var config = new MappingConfiguration().Define(PocoWithEnumCollections.DefaultMapping);
var mapper = GetMappingClient(() => TaskHelper.ToTask(RowSet.Empty()), (q, p) =>
{
query = q;
parameters = p;
}, config);
var collectionValues = new[] { HairColor.Blonde, HairColor.Gray };
var mapValues = new SortedDictionary<HairColor, TimeUuid>
{
{ HairColor.Brown, TimeUuid.NewId() },
{ HairColor.Red, TimeUuid.NewId() }
};
var expectedCollection = collectionValues.Select(x => (int)x).ToArray();
var expectedMap = mapValues.ToDictionary(kv => (int)kv.Key, kv => (Guid)kv.Value);
var poco = new PocoWithEnumCollections
{
Id = 2L,
List1 = new List<HairColor>(collectionValues),
List2 = collectionValues,
Array1 = collectionValues,
Set1 = new SortedSet<HairColor>(collectionValues),
Set2 = new SortedSet<HairColor>(collectionValues),
Set3 = new HashSet<HairColor>(collectionValues),
Dictionary1 = new Dictionary<HairColor, TimeUuid>(mapValues),
Dictionary2 = mapValues,
Dictionary3 = new SortedDictionary<HairColor, TimeUuid>(mapValues)
};
mapper.Insert(poco, false);
Assert.AreEqual("INSERT INTO tbl1 (array1, id, list1, list2, map1, map2, map3, set1, set2, set3)" +
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", query);
Assert.AreEqual(
new object[]
{
expectedCollection, 2L, expectedCollection, expectedCollection, expectedMap, expectedMap, expectedMap, expectedCollection,
expectedCollection, expectedCollection
}, parameters);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.Diagnostics.Contracts;
using System;
namespace System.IO
{
public class Path
{
#if !SILVERLIGHT && !NETFRAMEWORK_3_5
//
// Summary:
// Combines an array of strings into a path.
//
// Parameters:
// paths:
// An array of parts of the path.
//
// Returns:
// The combined paths.
//
// Exceptions:
// System.ArgumentException:
// One of the strings in the array contains one or more of the invalid characters
// defined in System.IO.Path.GetInvalidPathChars().
//
// System.ArgumentNullException:
// One of the strings in the array is null.
[Pure]
public static string Combine(params string[] paths)
{
Contract.Requires(paths != null);
Contract.Requires(Contract.ForAll(paths, path => path != null));
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
//
// Summary:
// Combines three strings into a path.
//
// Parameters:
// path1:
// The first path to combine.
//
// path2:
// The second path to combine.
//
// path3:
// The third path to combine.
//
// Returns:
// The combined paths.
//
// Exceptions:
// System.ArgumentException:
// path1, path2, or path3 contains one or more of the invalid characters defined
// in System.IO.Path.GetInvalidPathChars().
//
// System.ArgumentNullException:
// path1, path2, or path3 is null.
[Pure]
public static string Combine(string path1, string path2, string path3)
{
Contract.Requires(path1 != null);
Contract.Requires(path2 != null);
Contract.Requires(path3 != null);
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
//
// Summary:
// Combines four strings into a path.
//
// Parameters:
// path1:
// The first path to combine.
//
// path2:
// The second path to combine.
//
// path3:
// The third path to combine.
//
// path4:
// The fourth path to combine.
//
// Returns:
// The combined paths.
//
// Exceptions:
// System.ArgumentException:
// path1, path2, path3, or path4 contains one or more of the invalid characters
// defined in System.IO.Path.GetInvalidPathChars().
//
// System.ArgumentNullException:
// path1, path2, path3, or path4 is null.
[Pure]
public static string Combine(string path1, string path2, string path3, string path4)
{
Contract.Requires(path1 != null);
Contract.Requires(path2 != null);
Contract.Requires(path3 != null);
Contract.Requires(path4 != null);
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
#endif
[Pure]
public static string Combine(string path1, string path2)
{
Contract.Requires(path1 != null);
Contract.Requires(path2 != null);
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length >= path2.Length);
Contract.Ensures(!IsPathRooted(path2) || Contract.Result<string>() == path2);
Contract.Ensures(IsPathRooted(path2) || Contract.Result<string>().Length >= path1.Length + path2.Length);
//This was wrong: Contract.Ensures(Contract.Result<string>().Length >= path1.Length + path2.Length);
//MSDN: If path2 includes a root, path2 is returned
return default(string);
}
[Pure]
public static bool IsPathRooted(string path)
{
Contract.Ensures(!Contract.Result<bool>() || path.Length > 0);
return default(bool);
}
[Pure]
public static bool HasExtension(string path)
{
Contract.Ensures(!Contract.Result<bool>() || path.Length > 0);
return default(bool);
}
[Pure]
public static string GetPathRoot(string path)
{
Contract.Ensures(path == null || Contract.Result<string>().Length <= path.Length);
return default(string);
}
[Pure]
public static string GetFileNameWithoutExtension(string path)
{
Contract.Ensures(path == null || Contract.Result<string>().Length <= path.Length);
return default(string);
}
[Pure]
public static string GetFileName(string path)
{
Contract.Ensures(path == null || Contract.Result<string>().Length <= path.Length);
return default(string);
}
[Pure]
public static string GetFullPath(string path)
{
Contract.Requires(path != null);
Contract.Ensures(Contract.Result<string>() != null);
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
return default(string);
}
[Pure]
public static string GetExtension(string path)
{
Contract.Ensures(path == null || Contract.Result<string>().Length <= path.Length);
return default(string);
}
[Pure]
public static string GetDirectoryName(string path)
{
Contract.Ensures(path == null || Contract.Result<string>().Length <= path.Length);
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurs.");
return default(string);
}
[Pure]
public static string ChangeExtension(string path, string extension)
{
Contract.Ensures(path == null || Contract.Result<string>() != null);
return default(string);
}
#if !SILVERLIGHT
[Pure]
public static char[] GetInvalidFileNameChars()
{
Contract.Ensures(Contract.Result<char[]>() != null);
return default(char[]);
}
#endif
[Pure]
public static char[] GetInvalidPathChars()
{
Contract.Ensures(Contract.Result<char[]>() != null);
return default(char[]);
}
#if !SILVERLIGHT
public static string GetRandomFileName()
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
#endif
public static string GetTempFileName()
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurs, such as no unique temporary file name is available. - or - This method was unable to create a temporary file.");
return default(string);
}
public static string GetTempPath()
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
}
| |
using J2N.Runtime.CompilerServices;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Codecs.PerField
{
/*
* 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 BinaryDocValues = Lucene.Net.Index.BinaryDocValues;
using BytesRef = Lucene.Net.Util.BytesRef;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using IBits = Lucene.Net.Util.IBits;
using IOUtils = Lucene.Net.Util.IOUtils;
using NumericDocValues = Lucene.Net.Index.NumericDocValues;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
using SegmentReadState = Lucene.Net.Index.SegmentReadState;
using SegmentWriteState = Lucene.Net.Index.SegmentWriteState;
using SortedDocValues = Lucene.Net.Index.SortedDocValues;
using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues;
/// <summary>
/// Enables per field docvalues support.
/// <para/>
/// Note, when extending this class, the name (<see cref="DocValuesFormat.Name"/>) is
/// written into the index. In order for the field to be read, the
/// name must resolve to your implementation via <see cref="DocValuesFormat.ForName(string)"/>.
/// This method uses <see cref="IDocValuesFormatFactory.GetDocValuesFormat(string)"/> to resolve format names.
/// See <see cref="DefaultDocValuesFormatFactory"/> for information about how to implement your own <see cref="DocValuesFormat"/>.
/// <para/>
/// Files written by each docvalues format have an additional suffix containing the
/// format name. For example, in a per-field configuration instead of <c>_1.dat</c>
/// filenames would look like <c>_1_Lucene40_0.dat</c>.
/// <para/>
/// @lucene.experimental
/// </summary>
/// <seealso cref="IDocValuesFormatFactory"/>
/// <seealso cref="DefaultDocValuesFormatFactory"/>
[DocValuesFormatName("PerFieldDV40")]
public abstract class PerFieldDocValuesFormat : DocValuesFormat
{
// LUCENENET specific: Removing this static variable, since name is now determined by the DocValuesFormatNameAttribute.
///// <summary>
///// Name of this <seealso cref="PostingsFormat"/>. </summary>
//public static readonly string PER_FIELD_NAME = "PerFieldDV40";
/// <summary>
/// <see cref="FieldInfo"/> attribute name used to store the
/// format name for each field.
/// </summary>
public static readonly string PER_FIELD_FORMAT_KEY = typeof(PerFieldDocValuesFormat).Name + ".format";
/// <summary>
/// <see cref="FieldInfo"/> attribute name used to store the
/// segment suffix name for each field.
/// </summary>
public static readonly string PER_FIELD_SUFFIX_KEY = typeof(PerFieldDocValuesFormat).Name + ".suffix";
/// <summary>
/// Sole constructor. </summary>
public PerFieldDocValuesFormat()
: base()
{
}
public override sealed DocValuesConsumer FieldsConsumer(SegmentWriteState state)
{
return new FieldsWriter(this, state);
}
internal class ConsumerAndSuffix : IDisposable
{
internal DocValuesConsumer Consumer { get; set; }
internal int Suffix { get; set; }
public void Dispose()
{
Consumer.Dispose();
}
}
private class FieldsWriter : DocValuesConsumer
{
private readonly PerFieldDocValuesFormat outerInstance;
internal readonly IDictionary<DocValuesFormat, ConsumerAndSuffix> formats = new Dictionary<DocValuesFormat, ConsumerAndSuffix>();
internal readonly IDictionary<string, int?> suffixes = new Dictionary<string, int?>();
internal readonly SegmentWriteState segmentWriteState;
public FieldsWriter(PerFieldDocValuesFormat outerInstance, SegmentWriteState state)
{
this.outerInstance = outerInstance;
segmentWriteState = state;
}
public override void AddNumericField(FieldInfo field, IEnumerable<long?> values)
{
GetInstance(field).AddNumericField(field, values);
}
public override void AddBinaryField(FieldInfo field, IEnumerable<BytesRef> values)
{
GetInstance(field).AddBinaryField(field, values);
}
public override void AddSortedField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd)
{
GetInstance(field).AddSortedField(field, values, docToOrd);
}
public override void AddSortedSetField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords)
{
GetInstance(field).AddSortedSetField(field, values, docToOrdCount, ords);
}
internal virtual DocValuesConsumer GetInstance(FieldInfo field)
{
DocValuesFormat format = null;
if (field.DocValuesGen != -1)
{
string formatName = field.GetAttribute(PER_FIELD_FORMAT_KEY);
// this means the field never existed in that segment, yet is applied updates
if (formatName != null)
{
format = DocValuesFormat.ForName(formatName);
}
}
if (format == null)
{
format = outerInstance.GetDocValuesFormatForField(field.Name);
}
if (format == null)
{
throw new InvalidOperationException("invalid null DocValuesFormat for field=\"" + field.Name + "\"");
}
string formatName_ = format.Name;
string previousValue = field.PutAttribute(PER_FIELD_FORMAT_KEY, formatName_);
Debug.Assert(field.DocValuesGen != -1 || previousValue == null, "formatName=" + formatName_ + " prevValue=" + previousValue);
int? suffix = null;
ConsumerAndSuffix consumer;
if (!formats.TryGetValue(format, out consumer) || consumer == null)
{
// First time we are seeing this format; create a new instance
if (field.DocValuesGen != -1)
{
string suffixAtt = field.GetAttribute(PER_FIELD_SUFFIX_KEY);
// even when dvGen is != -1, it can still be a new field, that never
// existed in the segment, and therefore doesn't have the recorded
// attributes yet.
if (suffixAtt != null)
{
suffix = Convert.ToInt32(suffixAtt, CultureInfo.InvariantCulture);
}
}
if (suffix == null)
{
// bump the suffix
if (!suffixes.TryGetValue(formatName_, out suffix) || suffix == null)
{
suffix = 0;
}
else
{
suffix = suffix + 1;
}
}
suffixes[formatName_] = suffix;
string segmentSuffix = GetFullSegmentSuffix(segmentWriteState.SegmentSuffix, GetSuffix(formatName_, Convert.ToString(suffix, CultureInfo.InvariantCulture)));
consumer = new ConsumerAndSuffix();
consumer.Consumer = format.FieldsConsumer(new SegmentWriteState(segmentWriteState, segmentSuffix));
consumer.Suffix = suffix.Value; // LUCENENET NOTE: At this point suffix cannot be null
formats[format] = consumer;
}
else
{
// we've already seen this format, so just grab its suffix
Debug.Assert(suffixes.ContainsKey(formatName_));
suffix = consumer.Suffix;
}
previousValue = field.PutAttribute(PER_FIELD_SUFFIX_KEY, Convert.ToString(suffix, CultureInfo.InvariantCulture));
Debug.Assert(field.DocValuesGen != -1 || previousValue == null, "suffix=" + Convert.ToString(suffix, CultureInfo.InvariantCulture) + " prevValue=" + previousValue);
// TODO: we should only provide the "slice" of FIS
// that this DVF actually sees ...
return consumer.Consumer;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Close all subs
IOUtils.Dispose(formats.Values);
}
}
}
internal static string GetSuffix(string formatName, string suffix)
{
return formatName + "_" + suffix;
}
internal static string GetFullSegmentSuffix(string outerSegmentSuffix, string segmentSuffix)
{
if (outerSegmentSuffix.Length == 0)
{
return segmentSuffix;
}
else
{
return outerSegmentSuffix + "_" + segmentSuffix;
}
}
private class FieldsReader : DocValuesProducer
{
private readonly PerFieldDocValuesFormat outerInstance;
// LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java
internal readonly IDictionary<string, DocValuesProducer> fields = new JCG.SortedDictionary<string, DocValuesProducer>(StringComparer.Ordinal);
internal readonly IDictionary<string, DocValuesProducer> formats = new Dictionary<string, DocValuesProducer>();
public FieldsReader(PerFieldDocValuesFormat outerInstance, SegmentReadState readState)
{
this.outerInstance = outerInstance;
// Read _X.per and init each format:
bool success = false;
try
{
// Read field name -> format name
foreach (FieldInfo fi in readState.FieldInfos)
{
if (fi.HasDocValues)
{
string fieldName = fi.Name;
string formatName = fi.GetAttribute(PER_FIELD_FORMAT_KEY);
if (formatName != null)
{
// null formatName means the field is in fieldInfos, but has no docvalues!
string suffix = fi.GetAttribute(PER_FIELD_SUFFIX_KEY);
Debug.Assert(suffix != null);
DocValuesFormat format = DocValuesFormat.ForName(formatName);
string segmentSuffix = GetFullSegmentSuffix(readState.SegmentSuffix, GetSuffix(formatName, suffix));
// LUCENENET: Eliminated extra lookup by using TryGetValue instead of ContainsKey
if (!formats.TryGetValue(segmentSuffix, out DocValuesProducer field))
{
formats[segmentSuffix] = field = format.FieldsProducer(new SegmentReadState(readState, segmentSuffix));
}
fields[fieldName] = field;
}
}
}
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(formats.Values);
}
}
}
internal FieldsReader(PerFieldDocValuesFormat outerInstance, FieldsReader other)
{
this.outerInstance = outerInstance;
IDictionary<DocValuesProducer, DocValuesProducer> oldToNew = new JCG.Dictionary<DocValuesProducer, DocValuesProducer>(IdentityEqualityComparer<DocValuesProducer>.Default);
// First clone all formats
foreach (KeyValuePair<string, DocValuesProducer> ent in other.formats)
{
DocValuesProducer values = ent.Value;
formats[ent.Key] = values;
oldToNew[ent.Value] = values;
}
// Then rebuild fields:
foreach (KeyValuePair<string, DocValuesProducer> ent in other.fields)
{
DocValuesProducer producer;
oldToNew.TryGetValue(ent.Value, out producer);
Debug.Assert(producer != null);
fields[ent.Key] = producer;
}
}
public override NumericDocValues GetNumeric(FieldInfo field)
{
DocValuesProducer producer;
if (fields.TryGetValue(field.Name, out producer) && producer != null)
{
return producer.GetNumeric(field);
}
return null;
}
public override BinaryDocValues GetBinary(FieldInfo field)
{
DocValuesProducer producer;
if (fields.TryGetValue(field.Name, out producer) && producer != null)
{
return producer.GetBinary(field);
}
return null;
}
public override SortedDocValues GetSorted(FieldInfo field)
{
DocValuesProducer producer;
if (fields.TryGetValue(field.Name, out producer) && producer != null)
{
return producer.GetSorted(field);
}
return null;
}
public override SortedSetDocValues GetSortedSet(FieldInfo field)
{
DocValuesProducer producer;
if (fields.TryGetValue(field.Name, out producer) && producer != null)
{
return producer.GetSortedSet(field);
}
return null;
}
public override IBits GetDocsWithField(FieldInfo field)
{
DocValuesProducer producer;
if (fields.TryGetValue(field.Name, out producer) && producer != null)
{
return producer.GetDocsWithField(field);
}
return null;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
IOUtils.Dispose(formats.Values);
}
}
public object Clone()
{
return new FieldsReader(outerInstance, this);
}
public override long RamBytesUsed()
{
long size = 0;
foreach (KeyValuePair<string, DocValuesProducer> entry in formats)
{
size += (entry.Key.Length * RamUsageEstimator.NUM_BYTES_CHAR)
+ entry.Value.RamBytesUsed();
}
return size;
}
public override void CheckIntegrity()
{
foreach (DocValuesProducer format in formats.Values)
{
format.CheckIntegrity();
}
}
}
public override sealed DocValuesProducer FieldsProducer(SegmentReadState state)
{
return new FieldsReader(this, state);
}
/// <summary>
/// Returns the doc values format that should be used for writing
/// new segments of <paramref name="field"/>.
/// <para/>
/// The field to format mapping is written to the index, so
/// this method is only invoked when writing, not when reading.
/// </summary>
public abstract DocValuesFormat GetDocValuesFormatForField(string field);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial class SolutionCrawlerRegistrationService
{
private partial class WorkCoordinator
{
private const int MinimumDelayInMS = 50;
private readonly Registration _registration;
private readonly LogAggregator _logAggregator;
private readonly IAsynchronousOperationListener _listener;
private readonly IOptionService _optionService;
private readonly CancellationTokenSource _shutdownNotificationSource;
private readonly CancellationToken _shutdownToken;
private readonly SimpleTaskQueue _eventProcessingQueue;
// points to processor task
private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor;
private readonly SemanticChangeProcessor _semanticChangeProcessor;
public WorkCoordinator(
IAsynchronousOperationListener listener,
IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders,
Registration registration)
{
_logAggregator = new LogAggregator();
_registration = registration;
_listener = listener;
_optionService = _registration.GetService<IOptionService>();
// event and worker queues
_shutdownNotificationSource = new CancellationTokenSource();
_shutdownToken = _shutdownNotificationSource.Token;
_eventProcessingQueue = new SimpleTaskQueue(TaskScheduler.Default);
var activeFileBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS);
var allFilesWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS);
var entireProjectWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS);
_documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor(
listener, analyzerProviders, _registration,
activeFileBackOffTimeSpanInMS, allFilesWorkerBackOffTimeSpanInMS, entireProjectWorkerBackOffTimeSpanInMS, _shutdownToken);
var semanticBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS);
var projectBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS);
_semanticChangeProcessor = new SemanticChangeProcessor(listener, _registration, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpanInMS, projectBackOffTimeSpanInMS, _shutdownToken);
// if option is on
if (_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler))
{
_registration.Workspace.WorkspaceChanged += OnWorkspaceChanged;
_registration.Workspace.DocumentOpened += OnDocumentOpened;
_registration.Workspace.DocumentClosed += OnDocumentClosed;
}
// subscribe to option changed event after all required fields are set
// otherwise, we can get null exception when running OnOptionChanged handler
_optionService.OptionChanged += OnOptionChanged;
}
public int CorrelationId
{
get { return _registration.CorrelationId; }
}
public void AddAnalyzer(IIncrementalAnalyzer analyzer, bool highPriorityForActiveFile)
{
// add analyzer
_documentAndProjectWorkerProcessor.AddAnalyzer(analyzer, highPriorityForActiveFile);
// and ask to re-analyze whole solution for the given analyzer
var set = _registration.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet();
Reanalyze(analyzer, set);
}
public void Shutdown(bool blockingShutdown)
{
_optionService.OptionChanged -= OnOptionChanged;
// detach from the workspace
_registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged;
_registration.Workspace.DocumentOpened -= OnDocumentOpened;
_registration.Workspace.DocumentClosed -= OnDocumentClosed;
// cancel any pending blocks
_shutdownNotificationSource.Cancel();
_documentAndProjectWorkerProcessor.Shutdown();
SolutionCrawlerLogger.LogWorkCoordinatorShutdown(CorrelationId, _logAggregator);
if (blockingShutdown)
{
var shutdownTask = Task.WhenAll(
_eventProcessingQueue.LastScheduledTask,
_documentAndProjectWorkerProcessor.AsyncProcessorTask,
_semanticChangeProcessor.AsyncProcessorTask);
shutdownTask.Wait(TimeSpan.FromSeconds(5));
if (!shutdownTask.IsCompleted)
{
SolutionCrawlerLogger.LogWorkCoordinatorShutdownTimeout(CorrelationId);
}
}
}
private void OnOptionChanged(object sender, OptionChangedEventArgs e)
{
// if solution crawler got turned off or on.
if (e.Option == InternalSolutionCrawlerOptions.SolutionCrawler)
{
var value = (bool)e.Value;
if (value)
{
_registration.Workspace.WorkspaceChanged += OnWorkspaceChanged;
_registration.Workspace.DocumentOpened += OnDocumentOpened;
_registration.Workspace.DocumentClosed += OnDocumentClosed;
}
else
{
_registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged;
_registration.Workspace.DocumentOpened -= OnDocumentOpened;
_registration.Workspace.DocumentClosed -= OnDocumentClosed;
}
SolutionCrawlerLogger.LogOptionChanged(CorrelationId, value);
return;
}
ReanalyzeOnOptionChange(sender, e);
}
private void ReanalyzeOnOptionChange(object sender, OptionChangedEventArgs e)
{
// otherwise, let each analyzer decide what they want on option change
ISet<DocumentId> set = null;
foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers)
{
if (analyzer.NeedsReanalysisOnOptionChanged(sender, e))
{
set = set ?? _registration.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet();
this.Reanalyze(analyzer, set);
}
}
}
public void Reanalyze(IIncrementalAnalyzer analyzer, ISet<DocumentId> documentIds, bool highPriority = false)
{
var asyncToken = _listener.BeginAsyncOperation("Reanalyze");
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(analyzer, documentIds, highPriority), _shutdownToken).CompletesAsyncOperation(asyncToken);
if (documentIds?.Count > 1)
{
// log big reanalysis request from things like fix all, suppress all or option changes
// we are not interested in 1 file re-analysis request which can happen from like venus typing
SolutionCrawlerLogger.LogReanalyze(CorrelationId, analyzer, documentIds, highPriority);
}
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args)
{
// guard us from cancellation
try
{
ProcessEvents(args, _listener.BeginAsyncOperation("OnWorkspaceChanged"));
}
catch (OperationCanceledException oce)
{
if (NotOurShutdownToken(oce))
{
throw;
}
// it is our cancellation, ignore
}
catch (AggregateException ae)
{
ae = ae.Flatten();
// If we had a mix of exceptions, don't eat it
if (ae.InnerExceptions.Any(e => !(e is OperationCanceledException)) ||
ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken))
{
// We had a cancellation with a different token, so don't eat it
throw;
}
// it is our cancellation, ignore
}
}
private bool NotOurShutdownToken(OperationCanceledException oce)
{
return oce.CancellationToken == _shutdownToken;
}
private void ProcessEvents(WorkspaceChangeEventArgs args, IAsyncToken asyncToken)
{
SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind);
// TODO: add telemetry that record how much it takes to process an event (max, min, average and etc)
switch (args.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
ProcessSolutionEvent(args, asyncToken);
break;
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
case WorkspaceChangeKind.ProjectRemoved:
ProcessProjectEvent(args, asyncToken);
break;
case WorkspaceChangeKind.DocumentAdded:
case WorkspaceChangeKind.DocumentReloaded:
case WorkspaceChangeKind.DocumentChanged:
case WorkspaceChangeKind.DocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
ProcessDocumentEvent(args, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void OnDocumentOpened(object sender, DocumentEventArgs e)
{
var asyncToken = _listener.BeginAsyncOperation("OnDocumentOpened");
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentOpened), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void OnDocumentClosed(object sender, DocumentEventArgs e)
{
var asyncToken = _listener.BeginAsyncOperation("OnDocumentClosed");
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentClosed), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken)
{
switch (e.Kind)
{
case WorkspaceChangeKind.DocumentAdded:
EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, asyncToken);
break;
case WorkspaceChangeKind.DocumentRemoved:
EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, asyncToken);
break;
case WorkspaceChangeKind.DocumentReloaded:
case WorkspaceChangeKind.DocumentChanged:
EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, asyncToken);
break;
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
// If an additional file has changed we need to reanalyze the entire project.
EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void ProcessProjectEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken)
{
switch (e.Kind)
{
case WorkspaceChangeKind.ProjectAdded:
OnProjectAdded(e.NewSolution.GetProject(e.ProjectId));
EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, asyncToken);
break;
case WorkspaceChangeKind.ProjectRemoved:
EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, asyncToken);
break;
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
OnSolutionAdded(e.NewSolution);
EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, asyncToken);
break;
case WorkspaceChangeKind.SolutionRemoved:
EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, asyncToken);
break;
case WorkspaceChangeKind.SolutionCleared:
EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, asyncToken);
break;
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
EnqueueEvent(e.OldSolution, e.NewSolution, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void OnSolutionAdded(Solution solution)
{
var asyncToken = _listener.BeginAsyncOperation("OnSolutionAdded");
_eventProcessingQueue.ScheduleTask(() =>
{
var semanticVersionTrackingService = solution.Workspace.Services.GetService<ISemanticVersionTrackingService>();
if (semanticVersionTrackingService != null)
{
semanticVersionTrackingService.LoadInitialSemanticVersions(solution);
}
}, _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void OnProjectAdded(Project project)
{
var asyncToken = _listener.BeginAsyncOperation("OnProjectAdded");
_eventProcessingQueue.ScheduleTask(() =>
{
var semanticVersionTrackingService = project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>();
if (semanticVersionTrackingService != null)
{
semanticVersionTrackingService.LoadInitialSemanticVersions(project);
}
}, _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemForSolutionAsync(solution, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemForDocumentAsync(solution, documentId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, IAsyncToken asyncToken)
{
// document changed event is the special one.
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private async Task EnqueueWorkItemAsync(Document document, InvocationReasons invocationReasons, SyntaxNode changedMember = null)
{
// we are shutting down
_shutdownToken.ThrowIfCancellationRequested();
var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false);
var currentMember = GetSyntaxPath(changedMember);
// call to this method is serialized. and only this method does the writing.
_documentAndProjectWorkerProcessor.Enqueue(
new WorkItem(document.Id, document.Project.Language, invocationReasons,
isLowPriority, currentMember, _listener.BeginAsyncOperation("WorkItem")));
// enqueue semantic work planner
if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged))
{
// must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later.
// due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual.
_semanticChangeProcessor.Enqueue(document, currentMember);
}
}
private SyntaxPath GetSyntaxPath(SyntaxNode changedMember)
{
// using syntax path might be too expansive since it will be created on every keystroke.
// but currently, we have no other way to track a node between two different tree (even for incrementally parsed one)
if (changedMember == null)
{
return null;
}
return new SyntaxPath(changedMember);
}
private async Task EnqueueWorkItemAsync(Project project, InvocationReasons invocationReasons)
{
foreach (var documentId in project.DocumentIds)
{
var document = project.GetDocument(documentId);
await EnqueueWorkItemAsync(document, invocationReasons).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds, bool highPriority)
{
var solution = _registration.CurrentSolution;
foreach (var documentId in documentIds)
{
var document = solution.GetDocument(documentId);
if (document == null)
{
continue;
}
var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false);
var invocationReasons = highPriority ? InvocationReasons.ReanalyzeHighPriority : InvocationReasons.Reanalyze;
_documentAndProjectWorkerProcessor.Enqueue(
new WorkItem(documentId, document.Project.Language, invocationReasons,
isLowPriority, analyzer, _listener.BeginAsyncOperation("WorkItem")));
}
}
private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution)
{
var solutionChanges = newSolution.GetChanges(oldSolution);
// TODO: Async version for GetXXX methods?
foreach (var addedProject in solutionChanges.GetAddedProjects())
{
await EnqueueWorkItemAsync(addedProject, InvocationReasons.DocumentAdded).ConfigureAwait(false);
}
foreach (var projectChanges in solutionChanges.GetProjectChanges())
{
await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false);
}
foreach (var removedProject in solutionChanges.GetRemovedProjects())
{
await EnqueueWorkItemAsync(removedProject, InvocationReasons.DocumentRemoved).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges)
{
await EnqueueProjectConfigurationChangeWorkItemAsync(projectChanges).ConfigureAwait(false);
foreach (var addedDocumentId in projectChanges.GetAddedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.NewProject.GetDocument(addedDocumentId), InvocationReasons.DocumentAdded).ConfigureAwait(false);
}
foreach (var changedDocumentId in projectChanges.GetChangedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(changedDocumentId), projectChanges.NewProject.GetDocument(changedDocumentId))
.ConfigureAwait(continueOnCapturedContext: false);
}
foreach (var removedDocumentId in projectChanges.GetRemovedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(removedDocumentId), InvocationReasons.DocumentRemoved).ConfigureAwait(false);
}
}
private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges projectChanges)
{
var oldProject = projectChanges.OldProject;
var newProject = projectChanges.NewProject;
// TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document?
var projectConfigurationChange = InvocationReasons.Empty;
if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions))
{
projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged);
}
if (projectChanges.GetAddedMetadataReferences().Any() ||
projectChanges.GetAddedProjectReferences().Any() ||
projectChanges.GetAddedAnalyzerReferences().Any() ||
projectChanges.GetRemovedMetadataReferences().Any() ||
projectChanges.GetRemovedProjectReferences().Any() ||
projectChanges.GetRemovedAnalyzerReferences().Any() ||
!object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions) ||
!object.Equals(oldProject.AssemblyName, newProject.AssemblyName) ||
!object.Equals(oldProject.Name, newProject.Name) ||
!object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions))
{
projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged);
}
if (!projectConfigurationChange.IsEmpty)
{
await EnqueueWorkItemAsync(projectChanges.NewProject, projectConfigurationChange).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument)
{
var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>();
if (differenceService == null)
{
// For languages that don't use a Roslyn syntax tree, they don't export a document difference service.
// The whole document should be considered as changed in that case.
await EnqueueWorkItemAsync(newDocument, InvocationReasons.DocumentChanged).ConfigureAwait(false);
}
else
{
var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false);
if (differenceResult != null)
{
await EnqueueWorkItemAsync(newDocument, differenceResult.ChangeType, differenceResult.ChangedMember).ConfigureAwait(false);
}
}
}
private Task EnqueueWorkItemForDocumentAsync(Solution solution, DocumentId documentId, InvocationReasons invocationReasons)
{
var document = solution.GetDocument(documentId);
return EnqueueWorkItemAsync(document, invocationReasons);
}
private Task EnqueueWorkItemForProjectAsync(Solution solution, ProjectId projectId, InvocationReasons invocationReasons)
{
var project = solution.GetProject(projectId);
return EnqueueWorkItemAsync(project, invocationReasons);
}
private async Task EnqueueWorkItemForSolutionAsync(Solution solution, InvocationReasons invocationReasons)
{
foreach (var projectId in solution.ProjectIds)
{
await EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId)
{
var oldProject = oldSolution.GetProject(projectId);
var newProject = newSolution.GetProject(projectId);
await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false);
}
private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId)
{
var oldProject = oldSolution.GetProject(documentId.ProjectId);
var newProject = newSolution.GetProject(documentId.ProjectId);
await EnqueueWorkItemAsync(oldProject.GetDocument(documentId), newProject.GetDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false);
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> workers)
{
var solution = _registration.CurrentSolution;
var list = new List<WorkItem>();
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
list.Add(new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, false, EmptyAsyncToken.Instance));
}
}
_documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(workers, list);
}
internal void WaitUntilCompletion_ForTestingPurposesOnly()
{
_documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly();
}
}
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="DefaultCodeGenerator.cs" company="Asynkron HB">
// Copyright (C) 2015-2017 Asynkron HB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using FastExpressionCompiler.LightExpression;
using Wire.Extensions;
using Wire.ValueSerializers;
namespace Wire.Compilation
{
public class SerializerCompiler
{
public const string PreallocatedByteBuffer = nameof(PreallocatedByteBuffer);
public void BuildSerializer(Serializer serializer, ObjectSerializer objectSerializer)
{
var type = objectSerializer.Type;
var fields = type.GetFieldInfosForType();
var writer = GetFieldsWriter(serializer, fields,type, out var bufferSize);
var reader = GetFieldsReader(serializer, fields, type);
objectSerializer.Initialize(reader, writer, bufferSize);
}
private ObjectReader GetFieldsReader(Serializer serializer, FieldInfo[] fields,
Type type)
{
var c = new Compiler<ObjectReader>();
var stream = c.Parameter<Stream>("stream");
var session = c.Parameter<DeserializerSession>("session");
var newExpression = c.NewObject(type);
var target = c.Variable("target", type);
var assignNewObjectToTarget = c.WriteVar(target, newExpression);
c.Emit(assignNewObjectToTarget);
if (serializer.Options.PreserveObjectReferences)
{
var trackDeserializedObjectMethod =
typeof(DeserializerSession)
.GetMethod(nameof(DeserializerSession.TrackDeserializedObject))!;
c.EmitCall(trackDeserializedObjectMethod, session, target);
}
var serializers = fields.Select(field => serializer.GetSerializerByType(field.FieldType)).ToArray();
var bufferSize =
serializers.Length != 0 ? serializers.Max(s => s.PreallocatedByteBufferSize) : 0;
if (bufferSize > 0)
EmitBuffer(c, bufferSize, session,
typeof(DeserializerSession).GetMethod(nameof(DeserializerSession.GetBuffer))!);
for (var i = 0; i < fields.Length; i++)
{
var field = fields[i];
var s = serializers[i];
Expression read;
if (field.FieldType.IsWirePrimitive())
{
read = s.EmitReadValue(c, stream, session, field);
}
else
{
// var readMethod = typeof(StreamEx).GetMethod(nameof(StreamEx.ReadObject))!;
// var callReadMethod = c.StaticCall(readMethod, stream, session);
// read = c.Convert(callReadMethod, field.FieldType);
// //
var readMethod = typeof(StreamEx)
.GetMethod(nameof(StreamEx.ReadObjectTyped))!
.MakeGenericMethod(field.FieldType);
read = c.StaticCall(readMethod, stream, session);
}
var assignReadToField = c.WriteField(field, target, read);
c.Emit(assignReadToField);
}
c.Emit(c.Convert(target, typeof(object)));
var del = c.Compile();
#if DEBUG
var tmp = del;
var debug = c.GetLambdaExpression().ToCSharpString();
Console.WriteLine($"{type.Name}----");
Console.WriteLine(debug);
Console.WriteLine($"------------");
object Del(Stream tStream, DeserializerSession tSession)
{
try
{
return tmp(tStream, tSession);
}
catch
{
Console.WriteLine(type);
Console.WriteLine(debug);
throw;
}
}
del = Del;
#endif
return del;
}
private static void EmitBuffer<T>(Compiler<T> c, int bufferSize, Expression session,
MethodInfo getBuffer) where T : class
{
var size = c.Constant(bufferSize);
var buffer = c.Variable<byte[]>(PreallocatedByteBuffer);
var bufferValue = c.Call(getBuffer, session, size);
var assignBuffer = c.WriteVar(buffer, bufferValue);
c.Emit(assignBuffer);
}
//this generates a FieldWriter that writes all fields by unrolling all fields and calling them individually
//no loops involved
private ObjectWriter GetFieldsWriter(Serializer serializer, IEnumerable<FieldInfo> fields,
Type type,
out int bufferSize)
{
var c = new Compiler<ObjectWriter>();
var stream = c.Parameter<Stream>("stream");
var target = c.Parameter<object>("target");
var session = c.Parameter<SerializerSession>("session");
var preserveReferences = c.Constant(serializer.Options.PreserveObjectReferences);
if (serializer.Options.PreserveObjectReferences)
{
var method =
typeof(SerializerSession).GetMethod(nameof(SerializerSession.TrackSerializedObject))!;
c.EmitCall(method, session, target);
}
var fieldsArray = fields.ToArray();
var serializers = fieldsArray.Select(field => serializer.GetSerializerByType(field.FieldType)).ToArray();
bufferSize = serializers.Length != 0 ? serializers.Max(s => s.PreallocatedByteBufferSize) : 0;
if (bufferSize > 0)
EmitBuffer(c, bufferSize, session,
typeof(SerializerSession).GetMethod(nameof(SerializerSession.GetBuffer))!);
for (var i = 0; i < fieldsArray.Length; i++)
{
var field = fieldsArray[i];
//get the serializer for the type of the field
var valueSerializer = serializers[i];
//runtime Get a delegate that reads the content of the given field
var cast = c.CastOrUnbox(target, field.DeclaringType!);
var readField = c.ReadField(field, cast);
//if the type is one of our special primitives, ignore manifest as the content will always only be of this type
if (field.FieldType.IsWirePrimitive())
{
//primitive types does not need to write any manifest, if the field type is known
valueSerializer.EmitWriteValue(c, stream, readField, session);
}
else
{
var converted = c.Convert<object>(readField);
var valueType = field.FieldType;
if (field.FieldType.IsNullable())
{
var nullableType = field.FieldType.GetNullableElement();
valueSerializer = serializer.GetSerializerByType(nullableType);
valueType = nullableType;
}
var vs = c.Constant(valueSerializer);
var vt = c.Constant(valueType);
var method = typeof(StreamEx).GetMethod(nameof(StreamEx.WriteObject))!;
c.EmitStaticCall(method, stream, converted, vt, vs, preserveReferences, session);
}
}
var del = c.Compile();
#if DEBUG
var debug = c.GetLambdaExpression().ToCSharpString();
Console.WriteLine($"{type.Name}----");
Console.WriteLine(debug);
Console.WriteLine($"------------");
var tmp = del;
void Del(Stream tStream, object tObj, SerializerSession tSession)
{
try
{
tmp(tStream, tObj, tSession);
}
catch
{
Console.WriteLine(type);
foreach (var f in fields)
{
Console.WriteLine(f);
}
Console.WriteLine(debug);
throw;
}
}
del = Del;
#endif
return del;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BlendVariableInt32()
{
var test = new SimpleTernaryOpTest__BlendVariableInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__BlendVariableInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] inArray3, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public Vector128<Int32> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToInt32("0xFFFFFFFF", 16) : (int)0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__BlendVariableInt32 testClass)
{
var result = Sse41.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__BlendVariableInt32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
fixed (Vector128<Int32>* pFld3 = &_fld3)
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2)),
Sse2.LoadVector128((Int32*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Int32[] _data3 = new Int32[Op3ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private static Vector128<Int32> _clsVar3;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private Vector128<Int32> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__BlendVariableInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToInt32("0xFFFFFFFF", 16) : (int)0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleTernaryOpTest__BlendVariableInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToInt32("0xFFFFFFFF", 16) : (int)0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToInt32("0xFFFFFFFF", 16) : (int)0); }
_dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.BlendVariable(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.BlendVariable(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.BlendVariable(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
fixed (Vector128<Int32>* pClsVar3 = &_clsVar3)
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Int32*)(pClsVar1)),
Sse2.LoadVector128((Int32*)(pClsVar2)),
Sse2.LoadVector128((Int32*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr);
var result = Sse41.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadVector128((Int32*)(_dataTable.inArray3Ptr));
var result = Sse41.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray3Ptr));
var result = Sse41.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__BlendVariableInt32();
var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__BlendVariableInt32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
fixed (Vector128<Int32>* pFld3 = &test._fld3)
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2)),
Sse2.LoadVector128((Int32*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
fixed (Vector128<Int32>* pFld3 = &_fld3)
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2)),
Sse2.LoadVector128((Int32*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Int32*)(&test._fld1)),
Sse2.LoadVector128((Int32*)(&test._fld2)),
Sse2.LoadVector128((Int32*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, Vector128<Int32> op3, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] inArray3 = new Int32[Op3ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] inArray3 = new Int32[Op3ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] thirdOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((thirdOp[0] != 0) ? secondOp[0] != result[0] : firstOp[0] != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((thirdOp[i] != 0) ? secondOp[i] != result[i] : firstOp[i] != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.BlendVariable)}<Int32>(Vector128<Int32>, Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using CK.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Linq;
using System.Diagnostics.CodeAnalysis;
using CK.CodeGen;
using CK.CodeGen.SimpleParser;
using System.Diagnostics;
namespace CK.CodeGen
{
static class StringMatcherExtensions
{
internal static bool TryMatchCSharpIdentifier( this StringMatcher @this, [NotNullWhen( true )]out string? identifier, bool skipAtSign = false )
{
identifier = null;
if( @this.IsEnd ) return false;
int savedIdx = @this.StartIndex;
bool at = @this.TryMatchChar( '@' );
if( IsValidIdentifierStart( @this.Head ) )
{
while( @this.UncheckedMove( 1 ) && !@this.IsEnd && IsValidIdentifierChar( @this.Head ) ) ;
if( at && skipAtSign ) ++savedIdx;
identifier = @this.Text.Substring( savedIdx, @this.StartIndex - savedIdx );
return true;
}
if( at ) @this.UncheckedMove( -1 );
return false;
}
static bool EatRawCode( this StringMatcher @this, StringBuilder b, bool stopOnComma, bool removeWhiteSpaces = true )
{
int bPos = b.Length;
int depth = 0;
while( !@this.IsEnd
&& (depth != 0 || (@this.Head != ')' && @this.Head != ']' && @this.Head != '}' && (!stopOnComma || @this.Head != ','))) )
{
if( @this.Head == '(' || @this.Head == '[' || @this.Head == '{' )
{
++depth;
b.Append( @this.Head );
@this.UncheckedMove( 1 );
}
else if( @this.Head == ')' || @this.Head == ']' || @this.Head == '}' )
{
--depth;
b.Append( @this.Head );
@this.UncheckedMove( 1 );
}
else if( @this.TryMatchCSharpIdentifier( out var id, skipAtSign: false ) )
{
b.Append( id );
}
else if( @this.TryMatchCSharpString( out var str ) )
{
b.Append( str );
}
else
{
if( !(removeWhiteSpaces && Char.IsWhiteSpace( @this.Head )) ) b.Append( @this.Head );
@this.UncheckedMove( 1 );
}
}
return b.Length > bPos;
}
static bool TryMatchCSharpString( this StringMatcher @this, [NotNullWhen( true )]out string? s )
{
if( @this.TryMatchText( "$@\"" ) )
{
return @this.EatVerbatimString( 3, out s );
}
if( @this.TryMatchText( "@\"" ) )
{
return @this.EatVerbatimString( 2, out s );
}
if( @this.TryMatchChar( '"' ) )
{
return @this.EatString( out s, '"' );
}
if( @this.TryMatchChar( '\'' ) )
{
return @this.EatString( out s, '\'' );
}
s = null;
return false;
}
static bool EatString( this StringMatcher @this, [NotNullWhen( true )]out string? s, char mark )
{
int startIdx = @this.StartIndex - 1;
while( !@this.IsEnd )
{
if( @this.Head == mark )
{
@this.UncheckedMove( 1 );
s = @this.GetText( startIdx, @this.StartIndex - startIdx );
return true;
}
@this.UncheckedMove( @this.Head == '\\' ? 2 : 1 );
}
s = null;
return false;
}
static bool EatVerbatimString( this StringMatcher @this, int start, [NotNullWhen( true )]out string? s )
{
int startIdx = @this.StartIndex - start;
while( !@this.IsEnd )
{
if( @this.Head == '"' )
{
@this.UncheckedMove( 1 );
if( @this.IsEnd ) break;
if (@this.Head == '"')
{
@this.UncheckedMove( 1 );
continue;
}
s = @this.GetText( startIdx, @this.StartIndex - startIdx );
return true;
}
@this.UncheckedMove( 1 );
}
s = null;
return false;
}
internal static bool MatchPotentialAttributes( this StringMatcher @this, out AttributeCollection? attributes )
{
attributes = null;
while( @this.TryMatchAttribute( out var a ) )
{
if( attributes == null ) attributes = new AttributeCollection();
attributes.Ensure( a );
@this.SkipWhiteSpacesAndJSComments();
}
return !@this.IsError;
}
static CodeAttributeTarget MapAttributeTarget( string s )
{
return s switch
{
"assembly" => CodeAttributeTarget.Assembly,
"module" => CodeAttributeTarget.Module,
"field" => CodeAttributeTarget.Field,
"event" => CodeAttributeTarget.Event,
"method" => CodeAttributeTarget.Method,
"param" => CodeAttributeTarget.Param,
"property" => CodeAttributeTarget.Property,
"return" => CodeAttributeTarget.Return,
"type" => CodeAttributeTarget.Type,
_ => CodeAttributeTarget.None,
};
}
internal static bool TryMatchAttribute( this StringMatcher @this, [NotNullWhen( true )]out AttributeSetDefinition? attr )
{
attr = null;
if( !@this.TryMatchChar( '[' ) ) return false;
@this.SkipWhiteSpacesAndJSComments();
if( !@this.TryMatchCSharpIdentifier( out string? targetOrName ) ) return @this.AddError( "Attribute definition expected." );
var target = MapAttributeTarget( targetOrName );
if( target != CodeAttributeTarget.None )
{
if( !@this.MatchChar( ':' ) ) return false;
targetOrName = null;
}
List<AttributeDefinition> attributes = new List<AttributeDefinition>();
do
{
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchTypeName( out TypeName? name, targetOrName ) ) return @this.AddError( "Attribute definition expected." );
targetOrName = null;
if( name.Name.EndsWith( "Attribute", StringComparison.Ordinal ) )
{
name = new TypeName( name.Name.Remove( name.Name.Length - 9 ), name.GenericParameters );
}
var bAttrValue = new StringBuilder();
List<string> values = new List<string>();
@this.SkipWhiteSpacesAndJSComments();
if( @this.TryMatchChar( '(' ) )
{
@this.SkipWhiteSpacesAndJSComments();
while( !@this.TryMatchChar( ')' ) )
{
if( !@this.EatRawCode( bAttrValue, true, true ) ) return @this.SetError( "Values expected." );
values.Add( bAttrValue.ToString() );
bAttrValue.Clear();
// Allow training comma. Don't care.
if( @this.TryMatchChar( ',' ) ) @this.SkipWhiteSpacesAndJSComments();
}
}
attributes.Add( new AttributeDefinition( name, values ) );
@this.SkipWhiteSpacesAndJSComments();
}
while ( @this.TryMatchChar( ',' ) );
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchChar( ']' ) ) return false;
attr = new AttributeSetDefinition( target, attributes );
return true;
}
internal static bool MatchMethodDefinition( this StringMatcher @this, [NotNullWhen( true )] out FunctionDefinition? mDef, out bool hasCodeOpener )
{
mDef = null;
hasCodeOpener = false;
if( !@this.MatchPotentialAttributes( out var attributes ) ) return false;
var startName = CollectModifiersUntilIdentifier( @this, out var modifiers );
modifiers = modifiers.NormalizeMemberProtection();
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchExtendedTypeName( out var returnType, startName ) ) return false;
@this.SkipWhiteSpacesAndJSComments();
bool isIndexer = false;
TypeName? methodName;
if( @this.TryMatchChar( '(' ) )
{
if( returnType.IsTuple ) return @this.SetError( $"Invalid syntax: unexpected tuple {returnType}." );
methodName = returnType.TypeName;
returnType = null;
}
else
{
if( !@this.MatchTypeName( out methodName ) ) return false;
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchChar( '(' ) && !(isIndexer = @this.TryMatchChar( '[' ) ) ) return @this.SetError( "Expected '[' or '('." );
}
Debug.Assert( methodName != null );
var buffer = new StringBuilder();
@this.SkipWhiteSpacesAndJSComments();
List<FunctionDefinition.Parameter> parameters = new List<FunctionDefinition.Parameter>();
while( !@this.TryMatchChar( isIndexer ? ']' : ')' ) )
{
do
{
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchPotentialAttributes( out var pAttr ) ) return false;
FunctionDefinition.ParameterModifier mod = FunctionDefinition.ParameterModifier.None;
if( @this.TryMatchCSharpIdentifier( out var pTypeStart ) )
{
switch( pTypeStart )
{
case "this": mod = FunctionDefinition.ParameterModifier.This; pTypeStart = null; break;
case "params": mod = FunctionDefinition.ParameterModifier.Params; pTypeStart = null; break;
case "out": mod = FunctionDefinition.ParameterModifier.Out; pTypeStart = null; break;
case "ref": mod = FunctionDefinition.ParameterModifier.Ref; pTypeStart = null; break;
case "in": mod = FunctionDefinition.ParameterModifier.In; pTypeStart = null; break;
}
}
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchExtendedTypeName( out var pType, pTypeStart ) ) return false;
@this.SkipWhiteSpacesAndJSComments();
if( !@this.TryMatchCSharpIdentifier( out var pName ) ) return false;
@this.SkipWhiteSpacesAndJSComments();
string? defVal = null;
if( @this.TryMatchChar( '=' ) )
{
if( !@this.EatRawCode( buffer, true, true ) ) return @this.SetError( "Unable to read default value." );
defVal = buffer.ToString();
buffer.Clear();
}
else @this.SkipWhiteSpacesAndJSComments();
parameters.Add( new FunctionDefinition.Parameter( pAttr, mod, pType, pName, defVal ) );
}
while( @this.TryMatchChar( ',' ) );
}
var thisOrBaseCall = FunctionDefinition.CallConstructor.None;
string? thisOrBaseCallParameter = null;
@this.SkipWhiteSpacesAndJSComments();
if( returnType == null )
{
if( @this.TryMatchChar( ':' ) )
{
@this.SkipWhiteSpacesAndJSComments();
if( @this.TryMatchText( "this", StringComparison.Ordinal ) ) thisOrBaseCall = FunctionDefinition.CallConstructor.This;
else if( @this.TryMatchText( "base", StringComparison.Ordinal ) ) thisOrBaseCall = FunctionDefinition.CallConstructor.Base;
if( thisOrBaseCall != FunctionDefinition.CallConstructor.None )
{
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchChar( '(' ) ) return @this.SetError( "this(...) or base(...) : missing '('." );
@this.EatRawCode( buffer, false, false );
thisOrBaseCallParameter = buffer.ToString();
@this.SkipWhiteSpacesAndJSComments();
if( !@this.TryMatchChar( ')' ) ) return @this.SetError( "this(...) or base(...) : missing ')'." );
@this.SkipWhiteSpacesAndJSComments();
}
else return @this.SetError( "this(...) or base(...) expected." );
}
}
buffer.Clear();
List<TypeParameterConstraint>? wheres;
if( !@this.MatchWhereConstraints( out hasCodeOpener, out wheres ) ) return false;
mDef = new FunctionDefinition( attributes, modifiers, returnType, methodName, thisOrBaseCall, thisOrBaseCallParameter, isIndexer, parameters, wheres, buffer );
return true;
}
#region TypeDefinition
internal static string? CollectModifiersUntilIdentifier( this StringMatcher @this, out Modifiers modifiers )
{
modifiers = Modifiers.None;
string? id;
while( @this.TryMatchCSharpIdentifier( out id )
&& ModifiersExtension.ParseAndCombine( ref modifiers, id ) )
{
@this.SkipWhiteSpacesAndJSComments();
}
return id;
}
internal static bool MatchTypeKey( this StringMatcher @this, [NotNullWhen( true )]out string? key )
{
key = null;
if( !@this.MatchPotentialAttributes( out var attributes ) ) return false;
string? head = @this.CollectModifiersUntilIdentifier( out var modifiers );
if( head == "class" || head == "struct" || head == "interface" || head == "enum" )
{
head = null;
}
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchTypeName( out var name, head ) ) return false;
key = name.Key;
return true;
}
internal static bool MatchTypeDefinition( this StringMatcher @this, [NotNullWhen( true )]out TypeDefinition? typeDef, bool isNestedType, out bool hasCodeOpener )
{
typeDef = null;
hasCodeOpener = false;
if( !@this.MatchPotentialAttributes( out var attributes ) ) return false;
TypeDefinition.TypeKind kind;
switch( CollectModifiersUntilIdentifier( @this, out var modifiers ) )
{
case "class": kind = TypeDefinition.TypeKind.Class; break;
case "struct": kind = TypeDefinition.TypeKind.Struct; break;
case "interface": kind = TypeDefinition.TypeKind.Interface; break;
case "enum": kind = TypeDefinition.TypeKind.Enum; break;
default: return @this.SetError( "Expected: class, struct, interface or enum." );
}
modifiers = modifiers.NormalizeForType();
if( isNestedType ) modifiers = modifiers.NormalizeMemberProtection();
else modifiers = modifiers.NormalizeNamespaceProtection();
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchTypeName( out var name ) ) return false;
List<ExtendedTypeName>? baseTypes = null;
@this.SkipWhiteSpacesAndJSComments();
if( @this.TryMatchChar( ':' ) )
{
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchBaseTypesOrConstraints( out baseTypes ) ) return false;
}
@this.SkipWhiteSpacesAndJSComments();
List<TypeParameterConstraint>? wheres;
if( !@this.MatchWhereConstraints( out hasCodeOpener, out wheres ) ) return false;
typeDef = new TypeDefinition( attributes, modifiers, kind, name, baseTypes, wheres );
return true;
}
static bool MatchWhereConstraints( this StringMatcher @this, out bool hasCodeOpener, out List<TypeParameterConstraint>? wheres )
{
hasCodeOpener = false;
wheres = null;
while( !@this.IsEnd && !(hasCodeOpener = (@this.Head == '{' || @this.Head == '=')) )
{
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchTypeParameterConstraint( out var c ) ) return false;
if( wheres == null ) wheres = new List<TypeParameterConstraint>();
else if( wheres.Any( x => x.ParameterName == c.ParameterName ) ) return @this.SetError( $"Duplicate where constraint: where {c.ParameterName}." );
wheres.Add( c );
@this.SkipWhiteSpacesAndJSComments();
}
if( hasCodeOpener )
{
// If we stopped on '{', forwards the head.
@this.TryMatchChar( '{' );
hasCodeOpener = !@this.IsEnd;
}
return true;
}
/// <summary>
/// BaseTypeOrConstraint => TypeName | new()
/// The "new()" is becomes the <see cref="TypeName.Name"/> of a pseudo type name.
/// </summary>
static bool MatchBaseTypeOrConstraint( this StringMatcher @this, [NotNullWhen( true )]out ExtendedTypeName? t )
{
t = null;
if( !@this.TryMatchCSharpIdentifier( out var baseName ) ) return @this.SetError( "Expected identifier." );
if( baseName == "new" )
{
@this.SkipWhiteSpacesAndJSComments();
if( @this.TryMatchChar( '(' ) )
{
@this.SkipWhiteSpacesAndJSComments();
if( @this.TryMatchChar( ')' ) )
{
t = new ExtendedTypeName( new TypeName( "new()", null ) );
return true;
}
}
return @this.SetError( "Invalid new() constraint." );
}
@this.SkipWhiteSpacesAndJSComments();
return @this.MatchExtendedTypeName( out t, baseName );
}
/// <summary>
/// BaseTypesOrConstraints => comma separated MatchBaseTypeOrConstraint.
/// </summary>
static bool MatchBaseTypesOrConstraints( this StringMatcher @this, out List<ExtendedTypeName> types )
{
types = new List<ExtendedTypeName>();
do
{
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchBaseTypeOrConstraint( out var t ) ) return @this.AddError( "Expected base type.", true );
types.Add( t );
@this.SkipWhiteSpacesAndJSComments();
}
while( @this.TryMatchChar( ',' ) );
return true;
}
/// <summary>
/// TypeParameterConstraint => where : BaseTypesOrConstraints
/// </summary>
static bool MatchTypeParameterConstraint( this StringMatcher @this, [NotNullWhen( true )]out TypeParameterConstraint? c )
{
c = null;
if( !@this.TryMatchCSharpIdentifier( out var name ) || name != "where" ) @this.SetError( "Expected where constraint." );
@this.SkipWhiteSpacesAndJSComments();
if( !@this.TryMatchCSharpIdentifier( out name ) ) return false;
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchChar( ':' ) ) return false;
@this.SkipWhiteSpacesAndJSComments();
if( !@this.MatchBaseTypesOrConstraints( out var baseTypes ) ) return false;
c = new TypeParameterConstraint( name, baseTypes );
return true;
}
#endregion
#region TypeName
/// <summary>
/// Relaxed syntax here: we allow empty or single-field tuples (this is not valid)
/// and an ending comma in the list.
/// </summary>
/// <param name="this">This matcher.</param>
/// <param name="type">The tuple type name on success.</param>
/// <returns>True on success, false on error.</returns>
internal static bool TryMatchTupleTypeName( this StringMatcher @this, [NotNullWhen( true )] out TupleTypeName? type )
{
type = null;
if( !@this.TryMatchChar( '(' ) ) return false;
List<TupleTypeName.Field> fields = new List<TupleTypeName.Field>();
while( !@this.TryMatchChar( ')' ) )
{
ExtendedTypeName? fType = null;
string? fName = null;
if( !@this.MatchExtendedTypeName( out fType ) ) return false;
@this.SkipWhiteSpacesAndJSComments();
if( @this.TryMatchCSharpIdentifier( out fName ) ) @this.SkipWhiteSpacesAndJSComments();
fields.Add( new TupleTypeName.Field( fType, fName ) );
if( @this.TryMatchChar( ',' ) ) @this.SkipWhiteSpacesAndJSComments();
}
@this.SkipWhiteSpacesAndJSComments();
type = new TupleTypeName( fields );
return true;
}
internal static bool MatchExtendedTypeName( this StringMatcher @this, [NotNullWhen( true )] out ExtendedTypeName? type, string? knownName = null )
{
type = null;
TupleTypeName? tuple = null;
TypeName? regularType = null;
if( knownName != null || !@this.TryMatchTupleTypeName( out tuple ) )
{
if( @this.MatchTypeName( out regularType, knownName ) )
{
if( regularType.GenericParameters.Count == 1 && (regularType.Name == "Nullable" || regularType.Name == "System.Nullable") )
{
type = regularType.GenericParameters[0].Type.WithNullable( true );
}
}
}
if( type == null )
{
// Nullable<Nullable<...>> cannot exist.
bool isNullable = @this.TryMatchChar( '?' );
if( isNullable ) @this.SkipWhiteSpacesAndJSComments();
if( tuple != null ) type = new ExtendedTypeName( tuple, isNullable );
else if( regularType != null ) type = new ExtendedTypeName( regularType, isNullable );
else return false;
}
List<int>? arrayDim = null;
while( @this.TryMatchChar( '[' ) )
{
if( arrayDim == null ) arrayDim = new List<int>();
int dim = 0;
while( @this.TryMatchChar( ',' ) )
{
++dim;
@this.SkipWhiteSpacesAndJSComments();
}
if( !@this.TryMatchChar( ']' ) ) return @this.SetError( "Closing ']' array." );
arrayDim.Add( dim );
@this.SkipWhiteSpacesAndJSComments();
}
if( arrayDim != null )
{
bool isNullable = @this.TryMatchChar( '?' );
if( isNullable ) @this.SkipWhiteSpacesAndJSComments();
type = new ExtendedTypeName( type, arrayDim, isNullable );
}
return true;
}
internal static bool MatchTypeName( this StringMatcher @this, [NotNullWhen( true )]out TypeName? type, string? knownName = null )
{
type = null;
if( knownName != null
|| @this.TryMatchCSharpIdentifier( out knownName ) )
{
List<TypeName.GenParam>? genArgs = null;
@this.SkipWhiteSpacesAndJSComments();
while( @this.TryMatchChar('.') )
{
@this.SkipWhiteSpacesAndJSComments();
if( !@this.TryMatchCSharpIdentifier( out var sub ) ) return false;
knownName += '.' + sub;
@this.SkipWhiteSpacesAndJSComments();
}
if( @this.TryMatchChar( '<' ) )
{
genArgs = new List<TypeName.GenParam>();
for( ; ; )
{
@this.SkipWhiteSpacesAndJSComments();
if( @this.TryMatchChar( ',' ) )
{
genArgs.Add(TypeName.GenParam.Empty);
continue;
}
if( @this.TryMatchChar( '>' ) )
{
// Handles open generic definition like "G<>" or "G<,>".
genArgs.Add(TypeName.GenParam.Empty);
@this.SkipWhiteSpacesAndJSComments();
break;
}
if( !MatchGenParam( @this, out var genArg ) ) return @this.AddError( "Expected generic type parameter." );
genArgs.Add( genArg.Value );
@this.SkipWhiteSpacesAndJSComments();
if( @this.TryMatchChar( '>' ) )
{
@this.SkipWhiteSpacesAndJSComments();
break;
}
if( @this.TryMatchChar( ',' ) ) continue;
}
}
type = new TypeName( knownName, genArgs );
return true;
}
return @this.SetError( "Type name." );
}
static bool MatchGenParam( StringMatcher @this, [NotNullWhen( true )]out TypeName.GenParam? genArg )
{
genArg = null;
var v = TypeName.GenParam.Variance.None;
if( @this.TryMatchCSharpIdentifier( out string? nameOrVariance ) )
{
if( nameOrVariance == "out" )
{
v = TypeName.GenParam.Variance.Out;
nameOrVariance = null;
@this.SkipWhiteSpacesAndJSComments();
}
else if( nameOrVariance == "in" )
{
v = TypeName.GenParam.Variance.In;
nameOrVariance = null;
@this.SkipWhiteSpacesAndJSComments();
}
}
if( !@this.MatchExtendedTypeName( out var gT, nameOrVariance ) ) return false;
genArg = new TypeName.GenParam( v, gT );
return true;
}
// This is adapted from: https://stackoverflow.com/questions/1829679/how-to-determine-if-a-string-is-a-valid-variable-name
// This has been (heavily) simplified: forgetting about surrogate pairs and UnicodeCategory.Format stuff.
static bool IsValidIdentifierStart( char c )
{
return c == '_'
|| char.IsLetter( c )
|| char.GetUnicodeCategory( c ) == UnicodeCategory.LetterNumber;
}
static bool IsValidIdentifierChar( char c )
{
if( c == '_' || (c >= '0' && c <= '9') || char.IsLetter( c ) ) return true;
switch( char.GetUnicodeCategory( c ) )
{
case UnicodeCategory.LetterNumber:
case UnicodeCategory.DecimalDigitNumber:
case UnicodeCategory.ConnectorPunctuation:
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.SpacingCombiningMark:
return true;
default:
return false;
}
}
}
#endregion
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.InvokeDelegateWithConditionalAccess
{
internal static class Constants
{
public const string Kind = nameof(Kind);
public const string VariableAndIfStatementForm = nameof(VariableAndIfStatementForm);
public const string SingleIfStatementForm = nameof(SingleIfStatementForm);
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class InvokeDelegateWithConditionalAccessAnalyzer : AbstractCodeStyleDiagnosticAnalyzer
{
public InvokeDelegateWithConditionalAccessAnalyzer()
: base(IDEDiagnosticIds.InvokeDelegateWithConditionalAccessId,
new LocalizableResourceString(nameof(CSharpFeaturesResources.Delegate_invocation_can_be_simplified), CSharpFeaturesResources.ResourceManager, typeof(CSharpFeaturesResources)))
{
}
public override bool OpenFileOnly(Workspace workspace) => false;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(SyntaxNodeAction, SyntaxKind.IfStatement);
private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
{
var options = syntaxContext.Options;
var syntaxTree = syntaxContext.Node.SyntaxTree;
var cancellationToken = syntaxContext.CancellationToken;
var optionSet = options.GetDocumentOptionSetAsync(syntaxTree, cancellationToken).GetAwaiter().GetResult();
if (optionSet == null)
{
return;
}
var styleOption = optionSet.GetOption(CSharpCodeStyleOptions.PreferConditionalDelegateCall);
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
return;
}
var severity = styleOption.Notification.Value;
// look for the form "if (a != null)" or "if (null != a)"
var ifStatement = (IfStatementSyntax)syntaxContext.Node;
// ?. is only available in C# 6.0 and above. Don't offer this refactoring
// in projects targetting a lesser version.
if (((CSharpParseOptions)ifStatement.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp6)
{
return;
}
if (!ifStatement.Condition.IsKind(SyntaxKind.NotEqualsExpression))
{
return;
}
if (ifStatement.Else != null)
{
return;
}
// Check for both: "if (...) { a(); }" and "if (...) a();"
var innerStatement = ifStatement.Statement;
if (innerStatement.IsKind(SyntaxKind.Block))
{
var block = (BlockSyntax)innerStatement;
if (block.Statements.Count != 1)
{
return;
}
innerStatement = block.Statements[0];
}
if (!innerStatement.IsKind(SyntaxKind.ExpressionStatement))
{
return;
}
var expressionStatement = (ExpressionStatementSyntax)innerStatement;
// Check that it's of the form: "if (a != null) { a(); }
var invocationExpression = ((ExpressionStatementSyntax)innerStatement).Expression as InvocationExpressionSyntax;
if (invocationExpression == null)
{
return;
}
var condition = (BinaryExpressionSyntax)ifStatement.Condition;
if (TryCheckVariableAndIfStatementForm(
syntaxContext, ifStatement, condition,
expressionStatement, invocationExpression,
severity))
{
return;
}
TryCheckSingleIfStatementForm(
syntaxContext, ifStatement, condition,
expressionStatement, invocationExpression,
severity);
}
private bool TryCheckSingleIfStatementForm(
SyntaxNodeAnalysisContext syntaxContext,
IfStatementSyntax ifStatement,
BinaryExpressionSyntax condition,
ExpressionStatementSyntax expressionStatement,
InvocationExpressionSyntax invocationExpression,
DiagnosticSeverity severity)
{
var cancellationToken = syntaxContext.CancellationToken;
// Look for the form: "if (someExpr != null) someExpr()"
if (condition.Left.IsKind(SyntaxKind.NullLiteralExpression) ||
condition.Right.IsKind(SyntaxKind.NullLiteralExpression))
{
var expr = condition.Left.IsKind(SyntaxKind.NullLiteralExpression)
? condition.Right
: condition.Left;
cancellationToken.ThrowIfCancellationRequested();
if (SyntaxFactory.AreEquivalent(expr, invocationExpression.Expression, topLevel: false))
{
cancellationToken.ThrowIfCancellationRequested();
// Looks good!
var tree = syntaxContext.SemanticModel.SyntaxTree;
var additionalLocations = new List<Location>
{
Location.Create(tree, ifStatement.Span),
Location.Create(tree, expressionStatement.Span)
};
ReportDiagnostics(
syntaxContext, ifStatement, ifStatement,
expressionStatement, severity, additionalLocations,
Constants.SingleIfStatementForm);
return true;
}
}
return false;
}
private void ReportDiagnostics(
SyntaxNodeAnalysisContext syntaxContext,
StatementSyntax firstStatement,
IfStatementSyntax ifStatement,
ExpressionStatementSyntax expressionStatement,
DiagnosticSeverity severity,
List<Location> additionalLocations,
string kind)
{
var tree = syntaxContext.Node.SyntaxTree;
var properties = ImmutableDictionary<string, string>.Empty.Add(
Constants.Kind, kind);
var previousToken = expressionStatement.GetFirstToken().GetPreviousToken();
var nextToken = expressionStatement.GetLastToken().GetNextToken();
// Fade out the code up to the expression statement.
syntaxContext.ReportDiagnostic(Diagnostic.Create(this.UnnecessaryWithSuggestionDescriptor,
Location.Create(tree, TextSpan.FromBounds(firstStatement.SpanStart, previousToken.Span.End)),
additionalLocations, properties));
// Put a diagnostic with the appropriate severity on the expression-statement itself.
syntaxContext.ReportDiagnostic(Diagnostic.Create(
GetDescriptorWithSeverity(severity),
expressionStatement.GetLocation(),
additionalLocations, properties));
// If the if-statement extends past the expression statement, then fade out the rest.
if (nextToken.Span.Start < ifStatement.Span.End)
{
syntaxContext.ReportDiagnostic(Diagnostic.Create(this.UnnecessaryWithSuggestionDescriptor,
Location.Create(tree, TextSpan.FromBounds(nextToken.Span.Start, ifStatement.Span.End)),
additionalLocations, properties));
}
}
private bool TryCheckVariableAndIfStatementForm(
SyntaxNodeAnalysisContext syntaxContext,
IfStatementSyntax ifStatement,
BinaryExpressionSyntax condition,
ExpressionStatementSyntax expressionStatement,
InvocationExpressionSyntax invocationExpression,
DiagnosticSeverity severity)
{
var cancellationToken = syntaxContext.CancellationToken;
cancellationToken.ThrowIfCancellationRequested();
// look for the form "if (a != null)" or "if (null != a)"
if (!ifStatement.Parent.IsKind(SyntaxKind.Block))
{
return false;
}
if (!IsNullCheckExpression(condition.Left, condition.Right) &&
!IsNullCheckExpression(condition.Right, condition.Left))
{
return false;
}
var expression = invocationExpression.Expression;
if (!expression.IsKind(SyntaxKind.IdentifierName))
{
return false;
}
var conditionName = condition.Left is IdentifierNameSyntax
? (IdentifierNameSyntax)condition.Left
: (IdentifierNameSyntax)condition.Right;
var invocationName = (IdentifierNameSyntax)expression;
if (!Equals(conditionName.Identifier.ValueText, invocationName.Identifier.ValueText))
{
return false;
}
// Now make sure the previous statement is "var a = ..."
var parentBlock = (BlockSyntax)ifStatement.Parent;
var ifIndex = parentBlock.Statements.IndexOf(ifStatement);
if (ifIndex == 0)
{
return false;
}
var previousStatement = parentBlock.Statements[ifIndex - 1];
if (!previousStatement.IsKind(SyntaxKind.LocalDeclarationStatement))
{
return false;
}
var localDeclarationStatement = (LocalDeclarationStatementSyntax)previousStatement;
var variableDeclaration = localDeclarationStatement.Declaration;
if (variableDeclaration.Variables.Count != 1)
{
return false;
}
var declarator = variableDeclaration.Variables[0];
if (declarator.Initializer == null)
{
return false;
}
cancellationToken.ThrowIfCancellationRequested();
if (!Equals(declarator.Identifier.ValueText, conditionName.Identifier.ValueText))
{
return false;
}
// Syntactically this looks good. Now make sure that the local is a delegate type.
var semanticModel = syntaxContext.SemanticModel;
var localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator, cancellationToken);
// Ok, we made a local just to check it for null and invoke it. Looks like something
// we can suggest an improvement for!
// But first make sure we're only using the local only within the body of this if statement.
var analysis = semanticModel.AnalyzeDataFlow(localDeclarationStatement, ifStatement);
if (analysis.ReadOutside.Contains(localSymbol) || analysis.WrittenOutside.Contains(localSymbol))
{
return false;
}
// Looks good!
var tree = semanticModel.SyntaxTree;
var additionalLocations = new List<Location>
{
Location.Create(tree, localDeclarationStatement.Span),
Location.Create(tree, ifStatement.Span),
Location.Create(tree, expressionStatement.Span)
};
ReportDiagnostics(syntaxContext,
localDeclarationStatement, ifStatement, expressionStatement,
severity, additionalLocations, Constants.VariableAndIfStatementForm);
return true;
}
private bool IsNullCheckExpression(ExpressionSyntax left, ExpressionSyntax right) =>
left.IsKind(SyntaxKind.IdentifierName) && right.IsKind(SyntaxKind.NullLiteralExpression);
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticDocumentAnalysis;
}
}
| |
using NUnit.Framework;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Opera;
using OpenQA.Selenium.Safari;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace OpenQA.Selenium.Environment
{
public class DriverFactory
{
string driverPath;
private Dictionary<Browser, Type> serviceTypes = new Dictionary<Browser, Type>();
private Dictionary<Browser, Type> optionsTypes = new Dictionary<Browser, Type>();
public DriverFactory(string driverPath)
{
if (string.IsNullOrEmpty(driverPath))
{
this.driverPath = TestContext.CurrentContext.TestDirectory;
}
else
{
this.driverPath = driverPath;
}
this.PopulateServiceTypes();
this.PopulateOptionsTypes();
}
private void PopulateOptionsTypes()
{
this.optionsTypes[Browser.Chrome] = typeof(ChromeOptions);
this.optionsTypes[Browser.Edge] = typeof(EdgeOptions);
this.optionsTypes[Browser.Firefox] = typeof(FirefoxOptions);
this.optionsTypes[Browser.IE] = typeof(InternetExplorerOptions);
this.optionsTypes[Browser.Opera] = typeof(OperaOptions);
this.optionsTypes[Browser.Safari] = typeof(SafariOptions);
}
private void PopulateServiceTypes()
{
this.serviceTypes[Browser.Chrome] = typeof(ChromeDriverService);
this.serviceTypes[Browser.Edge] = typeof(EdgeDriverService);
this.serviceTypes[Browser.Firefox] = typeof(FirefoxDriverService);
this.serviceTypes[Browser.IE] = typeof(InternetExplorerDriverService);
this.serviceTypes[Browser.Opera] = typeof(OperaDriverService);
this.serviceTypes[Browser.Safari] = typeof(SafariDriverService);
}
public event EventHandler<DriverStartingEventArgs> DriverStarting;
public string DriverServicePath
{
get { return this.driverPath; }
}
public IWebDriver CreateDriver(Type driverType)
{
return CreateDriverWithOptions(driverType, null);
}
public IWebDriver CreateDriverWithOptions(Type driverType, DriverOptions driverOptions)
{
Browser browser = Browser.All;
DriverService service = null;
DriverOptions options = null;
List<Type> constructorArgTypeList = new List<Type>();
IWebDriver driver = null;
if (typeof(ChromeDriver).IsAssignableFrom(driverType))
{
browser = Browser.Chrome;
options = GetDriverOptions<ChromeOptions>(driverType, driverOptions);
service = CreateService<ChromeDriverService>(driverType);
}
else if (typeof(InternetExplorerDriver).IsAssignableFrom(driverType))
{
browser = Browser.IE;
options = GetDriverOptions<InternetExplorerOptions>(driverType, driverOptions);
service = CreateService<InternetExplorerDriverService>(driverType);
}
else if (typeof(EdgeDriver).IsAssignableFrom(driverType))
{
browser = Browser.Edge;
options = GetDriverOptions<EdgeOptions>(driverType, driverOptions);
service = CreateService<EdgeDriverService>(driverType);
}
else if (typeof(FirefoxDriver).IsAssignableFrom(driverType))
{
browser = Browser.Firefox;
options = GetDriverOptions<FirefoxOptions>(driverType, driverOptions);
service = CreateService<FirefoxDriverService>(driverType);
}
else if (typeof(SafariDriver).IsAssignableFrom(driverType))
{
browser = Browser.Safari;
options = GetDriverOptions<SafariOptions>(driverType, driverOptions);
service = CreateService<SafariDriverService>(driverType);
}
this.OnDriverLaunching(service, options);
if (browser != Browser.All)
{
constructorArgTypeList.Add(this.serviceTypes[browser]);
constructorArgTypeList.Add(this.optionsTypes[browser]);
ConstructorInfo ctorInfo = driverType.GetConstructor(constructorArgTypeList.ToArray());
if (ctorInfo != null)
{
return (IWebDriver)ctorInfo.Invoke(new object[] { service, options });
}
}
driver = (IWebDriver)Activator.CreateInstance(driverType);
return driver;
}
protected void OnDriverLaunching(DriverService service, DriverOptions options)
{
if (this.DriverStarting != null)
{
DriverStartingEventArgs args = new DriverStartingEventArgs(service, options);
this.DriverStarting(this, args);
}
}
private T GetDriverOptions<T>(Type driverType, DriverOptions overriddenOptions) where T : DriverOptions, new()
{
T options = new T();
Type optionsType = typeof(T);
PropertyInfo defaultOptionsProperty = driverType.GetProperty("DefaultOptions", BindingFlags.Public | BindingFlags.Static);
if (defaultOptionsProperty != null && defaultOptionsProperty.PropertyType == optionsType)
{
options = (T)defaultOptionsProperty.GetValue(null, null);
}
if (overriddenOptions != null)
{
options.PageLoadStrategy = overriddenOptions.PageLoadStrategy;
options.UnhandledPromptBehavior = overriddenOptions.UnhandledPromptBehavior;
options.Proxy = overriddenOptions.Proxy;
}
return options;
}
private T MergeOptions<T>(object baseOptions, DriverOptions overriddenOptions) where T:DriverOptions, new()
{
// If the driver type has a static DefaultOptions property,
// get the value of that property, which should be a valid
// options of the generic type (T). Otherwise, create a new
// instance of the browser-specific options class.
T mergedOptions = new T();
if (baseOptions != null && baseOptions is T)
{
mergedOptions = (T)baseOptions;
}
if (overriddenOptions != null)
{
mergedOptions.PageLoadStrategy = overriddenOptions.PageLoadStrategy;
mergedOptions.UnhandledPromptBehavior = overriddenOptions.UnhandledPromptBehavior;
mergedOptions.Proxy = overriddenOptions.Proxy;
}
return mergedOptions;
}
private T CreateService<T>(Type driverType) where T:DriverService
{
T service = default(T);
Type serviceType = typeof(T);
// If the driver type has a static DefaultService property,
// get the value of that property, which should be a valid
// service of the generic type (T). Otherwise, invoke the
// static CreateDefaultService method on the driver service's
// type, which returns an instance of the type.
PropertyInfo defaultServiceProperty = driverType.GetProperty("DefaultService", BindingFlags.Public | BindingFlags.Static);
if (defaultServiceProperty != null && defaultServiceProperty.PropertyType == serviceType)
{
PropertyInfo servicePathProperty = driverType.GetProperty("ServicePath", BindingFlags.Public | BindingFlags.Static);
if (servicePathProperty != null)
{
servicePathProperty.SetValue(null, this.driverPath);
}
service = (T)defaultServiceProperty.GetValue(null, null);
}
else
{
MethodInfo createDefaultServiceMethod = serviceType.GetMethod("CreateDefaultService", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string) }, null);
if (createDefaultServiceMethod != null && createDefaultServiceMethod.ReturnType == serviceType)
{
service = (T)createDefaultServiceMethod.Invoke(null, new object[] { this.driverPath });
}
}
return service;
}
private object GetDefaultOptions(Type driverType)
{
PropertyInfo info = driverType.GetProperty("DefaultOptions", BindingFlags.Public | BindingFlags.Static);
if (info != null)
{
object propertyValue = info.GetValue(null, null);
return propertyValue;
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Globalization
{
//
// This class implements the Julian calendar. In 48 B.C. Julius Caesar ordered a calendar reform, and this calendar
// is called Julian calendar. It consisted of a solar year of twelve months and of 365 days with an extra day
// every fourth year.
//*
//* Calendar support range:
//* Calendar Minimum Maximum
//* ========== ========== ==========
//* Gregorian 0001/01/01 9999/12/31
//* Julia 0001/01/03 9999/10/19
public class JulianCalendar : Calendar
{
public static readonly int JulianEra = 1;
private const int DatePartYear = 0;
private const int DatePartDayOfYear = 1;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
// Number of days in a non-leap year
private const int JulianDaysPerYear = 365;
// Number of days in 4 years
private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1;
private static readonly int[] s_daysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
private static readonly int[] s_daysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
// Gregorian Calendar 9999/12/31 = Julian Calendar 9999/10/19
// keep it as variable field for serialization compat.
internal int MaxYear = 9999;
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
public JulianCalendar()
{
// There is no system setting of TwoDigitYear max, so set the value here.
twoDigitYearMax = 2029;
}
internal override CalendarId ID
{
get
{
return CalendarId.JULIAN;
}
}
internal static void CheckEraRange(int era)
{
if (era != CurrentEra && era != JulianEra)
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal void CheckYearEraRange(int year, int era)
{
CheckEraRange(era);
if (year <= 0 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxYear));
}
}
internal static void CheckMonthRange(int month)
{
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
}
/*===================================CheckDayRange============================
**Action: Check for if the day value is valid.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** Before calling this method, call CheckYearEraRange()/CheckMonthRange() to make
** sure year/month values are correct.
============================================================================*/
internal static void CheckDayRange(int year, int month, int day)
{
if (year == 1 && month == 1)
{
// The mimimum supported Julia date is Julian 0001/01/03.
if (day < 3)
{
throw new ArgumentOutOfRangeException(null,
SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
bool isLeapYear = (year % 4) == 0;
int[] days = isLeapYear ? s_daysToMonth366 : s_daysToMonth365;
int monthDays = days[month] - days[month - 1];
if (day < 1 || day > monthDays)
{
throw new ArgumentOutOfRangeException(
nameof(day),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
monthDays));
}
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
internal static int GetDatePart(long ticks, int part)
{
// Gregorian 1/1/0001 is Julian 1/3/0001. Remember DateTime(0) is refered to Gregorian 1/1/0001.
// The following line convert Gregorian ticks to Julian ticks.
long julianTicks = ticks + TicksPerDay * 2;
// n = number of days since 1/1/0001
int n = (int)(julianTicks / TicksPerDay);
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / JulianDaysPer4Years;
// n = day number within 4-year period
n -= y4 * JulianDaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / JulianDaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return (y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * JulianDaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3);
int[] days = leapYear ? s_daysToMonth366 : s_daysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = (n >> 5) + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
if (part == DatePartMonth) return (m);
// Return 1-based day-of-month
return (n - days[m - 1] + 1);
}
// Returns the tick count corresponding to the given year, month, and day.
internal static long DateToTicks(int year, int month, int day)
{
int[] days = (year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365;
int y = year - 1;
int n = y * 365 + y / 4 + days[month - 1] + day - 1;
// Gregorian 1/1/0001 is Julian 1/3/0001. n * TicksPerDay is the ticks in JulianCalendar.
// Therefore, we subtract two days in the following to convert the ticks in JulianCalendar
// to ticks in Gregorian calendar.
return ((n - 2) * TicksPerDay);
}
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? s_daysToMonth366 : s_daysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
int[] days = (year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365;
return (days[month] - days[month - 1]);
}
public override int GetDaysInYear(int year, int era)
{
// Year/Era range is done in IsLeapYear().
return (IsLeapYear(year, era) ? 366 : 365);
}
public override int GetEra(DateTime time)
{
return (JulianEra);
}
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
public override int[] Eras
{
get
{
return (new int[] { JulianEra });
}
}
public override int GetMonthsInYear(int year, int era)
{
CheckYearEraRange(year, era);
return (12);
}
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
CheckMonthRange(month);
// Year/Era range check is done in IsLeapYear().
if (IsLeapYear(year, era))
{
CheckDayRange(year, month, day);
return (month == 2 && day == 29);
}
CheckDayRange(year, month, day);
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
CheckYearEraRange(year, era);
return (0);
}
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearEraRange(year, era);
return (year % 4 == 0);
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
CheckDayRange(year, month, day);
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
MillisPerSecond - 1));
}
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
return new DateTime(DateToTicks(year, month, day) + (new TimeSpan(0, hour, minute, second, millisecond)).Ticks);
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
}
public override int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
string.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
1,
MaxYear));
}
return (base.ToFourDigitYear(year));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp;
using System.IO;
using System.Reflection;
using Sannel.House.Generator.Common;
using Sannel.House.Web.Base;
namespace Sannel.House.Generator.Generators
{
public class ControllerGenerator : GeneratorBase
{
private SyntaxToken context = SF.Identifier("context");
public ControllerGenerator()
{
}
private MethodDeclarationSyntax generateGetMethod(string propertyName, Type t, GenerationAttribute ga)
{
var method = SF.MethodDeclaration(SF.GenericName("PagedResults")
.AddTypeArgumentListArguments(SF.ParseTypeName(t.Name)), "internalGetPaged")
.AddModifiers(SF.Token(SyntaxKind.PrivateKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("page")).WithType(SF.ParseTypeName("int")),
SF.Parameter(SF.Identifier("pageSize")).WithType(SF.ParseTypeName("int"))
);
var props = t.GetProperties();
var dm = props.GetSortProperty(out var forward);
var query = SF.Identifier("query");
/*var results = new PagedResults<ApplicationLogEntry>();
if(page <= 0)
{
results.Success = false;
results.Errors.Add("Page must be 1 or greater");
return results;
}
if(pageSize <= 1)
{
results.Success = false;
results.Errors.Add("PageSize must be 1 or greater");
return results;
}
IQueryable<ApplicationLogEntry> query;
query = context.ApplicationLogEntries.OrderByDescending(i => i.CreatedDate);
results.TotalResults = query.LongCount();
results.PageSize = pageSize;
query = query.Skip((page - 1) * results.PageSize).Take(results.PageSize);
results.CurrentPage = page;
results.Data = query;
results.Success = true;
return results;*/
var results = SF.Identifier("results");
var blocks = SF.Block()
.AddStatements(
SF.LocalDeclarationStatement(
Extensions.VariableDeclaration(results.Text,
SF.EqualsValueClause(
SF.ObjectCreationExpression(SF.GenericName("PagedResults")
.AddTypeArgumentListArguments(SF.ParseTypeName(t.Name))
).AddArgumentListArguments()
)
)
).WithLeadingTrivia(SF.Whitespace(Environment.NewLine))
)
.AddStatements(
SF.IfStatement(
SF.BinaryExpression(SyntaxKind.LessThanOrEqualExpression,
SF.IdentifierName("page"),
0.ToLiteral()
),
SF.Block()
.AddStatements(
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
results.Text.MemberAccess("Success"),
false.ToLiteral()
)
),
SF.ExpressionStatement(
SF.InvocationExpression(
results.Text.MemberAccess("Errors", "Add")
).AddArgumentListArguments(SF.Argument("Page must be 1 or greater".ToLiteral()))
),
SF.ReturnStatement(SF.IdentifierName(results))
)
),
SF.IfStatement(
SF.BinaryExpression(SyntaxKind.LessThanOrEqualExpression,
SF.IdentifierName("pageSize"),
0.ToLiteral()
),
SF.Block()
.AddStatements(
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
results.Text.MemberAccess("Success"),
false.ToLiteral()
)
),
SF.ExpressionStatement(
SF.InvocationExpression(
results.Text.MemberAccess("Errors", "Add")
).AddArgumentListArguments(SF.Argument("PageSize must be 1 or greater".ToLiteral()))
),
SF.ReturnStatement(SF.IdentifierName(results))
)
)
)
.AddStatements(
SF.LocalDeclarationStatement(
SF.VariableDeclaration(SF.GenericName("IQueryable")
.AddTypeArgumentListArguments(SF.ParseTypeName(t.Name)))
.AddVariables(SF.VariableDeclarator(query))
)
);
if (dm != null)
{
ExpressionSyntax contextQuery = SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
SF.IdentifierName(context),
SF.IdentifierName(propertyName)
);
if(ga?.GetIncludes?.Length > 0)
{
for(var i = 0; i < ga.GetIncludes.Length; i++)
{
var inc = ga.GetIncludes[i];
if(i == 0)
{
contextQuery = SF.InvocationExpression(
Extensions.MemberAccess(contextQuery,
(i == 0) ? "Include" : "ThenInclude"
)
).AddArgumentListArguments(
SF.Argument(
SF.SimpleLambdaExpression(
SF.Parameter(SF.Identifier("i")),
"i".MemberAccess(inc)
)
)
);
}
}
}
blocks = blocks.AddStatements(SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
SF.IdentifierName(query),
SF.InvocationExpression(
SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
contextQuery,
SF.IdentifierName((forward) ? "OrderBy" : "OrderByDescending")))
.AddArgumentListArguments(
SF.Argument(
SF.SimpleLambdaExpression(
SF.Parameter(SF.Identifier("i")),
SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
SF.IdentifierName("i"),
SF.IdentifierName(dm.Name)
)
)
)
)
)
));
}
else
{
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
SF.IdentifierName(query),
SF.MemberAccessExpression(SyntaxKind.SimpleAssignmentExpression,
SF.IdentifierName("context"),
SF.IdentifierName(propertyName)
)
)
)
);
}
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
results.Text.MemberAccess("TotalResults"),
SF.InvocationExpression(
query.Text.MemberAccess("LongCount")
).AddArgumentListArguments()
)
),
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
results.Text.MemberAccess("PageSize"),
SF.IdentifierName("pageSize")
)
),
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
SF.IdentifierName(query),
SF.InvocationExpression(
SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
SF.InvocationExpression(
query.Text.MemberAccess("Skip")
).AddArgumentListArguments(
SF.Argument(
SF.BinaryExpression(SyntaxKind.MultiplyExpression,
SF.ParenthesizedExpression(
SF.BinaryExpression(SyntaxKind.SubtractExpression,
SF.IdentifierName("page"),
1.ToLiteral()
)
),
results.Text.MemberAccess("PageSize")
)
)
),
SF.IdentifierName("Take")
)
).AddArgumentListArguments(
SF.Argument(results.Text.MemberAccess("PageSize"))
)
)
),
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
results.Text.MemberAccess("CurrentPage"),
SF.IdentifierName("page")
)
),
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
results.Text.MemberAccess("Count"),
SF.InvocationExpression(
query.Text.MemberAccess("Count")
).AddArgumentListArguments()
).ToStatement(),
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
results.Text.MemberAccess("Data"),
SF.InvocationExpression(
Extensions.MemberAccess(
SF.IdentifierName(query),
SF.IdentifierName("AsNoTracking")
)
).AddArgumentListArguments()
)
),
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
results.Text.MemberAccess("Success"),
true.ToLiteral()
)
),
SF.ReturnStatement(SF.IdentifierName(results))
);
/*items = items.Take(results.PageSize).Skip(page * results.PageSize);
results.Data = items;
results.CurrentPage = page;
results.Success = true;
return results;*/
method = method.WithBody(blocks);
return method;
}
private MethodDeclarationSyntax generateGetWithIdMethod(string propertyName, Type t)
{
var props = t.GetProperties();
var key = props.GetKeyProperty();
if (key == null)
{
return null;
}
var method = SF.MethodDeclaration(
SF.GenericName("Result")
.AddTypeArgumentListArguments(
SF.ParseTypeName(t.Name)
),
"internalGet")
.AddModifiers(SF.Token(SyntaxKind.PrivateKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("id")).WithType(SF.ParseTypeName(key.PropertyType.Name))
);
/* private Result<Device> internalGet(Int32 id)
{
var results = new Result<Device>();
var data = context.Devices.FirstOrDefault(i => i.Id == id);
if(data != null)
{
results.Success = true;
results.Data = data;
return results;
}
else
{
results.Success = false;
results.Errors.Add($"Could not find Device with Id {id}");
return results;
}
}
*/
var results = SF.Identifier("results");
var data = SF.Identifier("data");
var blocks = SF.Block().AddStatements(
SF.LocalDeclarationStatement(
Extensions.VariableDeclaration(
results.Text,
SF.EqualsValueClause(
SF.ObjectCreationExpression(
SF.GenericName("Result")
.AddTypeArgumentListArguments(
SF.ParseTypeName(t.Name)
)
).AddArgumentListArguments()
)
)
),
SF.LocalDeclarationStatement(
Extensions.VariableDeclaration(
data.Text,
SF.EqualsValueClause(
context.MemberAccess(propertyName, "FirstOrDefault")
.Invoke(
SF.Argument(
SF.SimpleLambdaExpression(
SF.Parameter(SF.Identifier("i")),
SF.BinaryExpression(SyntaxKind.EqualsExpression,
"i".MemberAccess(key.Name),
SF.IdentifierName("id")
)
)
)
)
)
)
)
);
blocks = blocks.AddStatements(
SF.IfStatement(
SF.BinaryExpression(SyntaxKind.NotEqualsExpression,
data.ToIN(),
SF.LiteralExpression(SyntaxKind.NullLiteralExpression)
),
SF.Block()
.AddStatements(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
results.MemberAccess("Success"),
true.ToLiteral()
).ToStatement(),
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
results.MemberAccess("Data"),
data.ToIN()
).ToStatement(),
SF.ReturnStatement(
results.ToIN()
)
)
).WithElse(
SF.ElseClause(
SF.Block()
.AddStatements(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
results.MemberAccess("Success"),
false.ToLiteral()
).ToStatement(),
results.MemberAccess("Errors", "Add")
.Invoke(
SF.Argument(
$"Could not find {t.Name} with {key.Name} ".ToInterpolatedString(
((StringToken)"id").AsInterpolation()
))
).ToStatement(),
SF.ReturnStatement(
results.ToIN()
)
)
)
)
);
method = method.WithBody(blocks);
return method;
}
private IfStatementSyntax postEmptyStringIfStatment(SyntaxToken data, SyntaxToken result, PropertyInfo info)
{
StringToken token = $"nameof({data.Text}.{info.Name})";
token = token.AsInterpolation();
var istring = token.ToInterpolatedString(" must have a non empty value");
return SF.IfStatement(
SF.InvocationExpression(
Extensions.MemberAccess(
SF.IdentifierName("String"),
SF.IdentifierName("IsNullOrWhiteSpace")
)
).AddArgumentListArguments(
SF.Argument(
Extensions.MemberAccess(
SF.IdentifierName(data),
SF.IdentifierName(info.Name)
)
)
),
SF.Block().AddStatements(
SF.ExpressionStatement(
SF.InvocationExpression(
Extensions.MemberAccess(
Extensions.MemberAccess(
SF.IdentifierName(result),
SF.IdentifierName("Errors")
),
SF.IdentifierName("Add")
)
)
.AddArgumentListArguments(
SF.Argument(istring)
)
),
SF.ReturnStatement(
SF.IdentifierName(result)
)
)
);
}
private IfStatementSyntax postGreaterThenZeroStatment(SyntaxToken data, SyntaxToken result, PropertyInfo requiredInfo)
{
var type = requiredInfo.PropertyType;
StringToken token = $"nameof({data.Text}.{requiredInfo.Name})";
token = token.AsInterpolation();
var istring = token.ToInterpolatedString(" must be greater then 0");
return SF.IfStatement(
SF.BinaryExpression(SyntaxKind.LessThanOrEqualExpression,
Extensions.MemberAccess(
SF.IdentifierName(data),
SF.IdentifierName(requiredInfo.Name)
),
0.ToLiteral()
),
SF.Block().AddStatements(
SF.ExpressionStatement(
SF.InvocationExpression(
Extensions.MemberAccess(
Extensions.MemberAccess(
SF.IdentifierName(result),
SF.IdentifierName("Errors")
),
SF.IdentifierName("Add")
)
)
.AddArgumentListArguments(
SF.Argument(istring)
)
),
SF.ReturnStatement(
SF.IdentifierName(result)
)
)
);
}
private IfStatementSyntax postRequiredIfStatment(SyntaxToken data, SyntaxToken result, PropertyInfo requiredInfo)
{
var type = requiredInfo.PropertyType;
StringToken token = $"nameof({data.Text}.{requiredInfo.Name})";
token = token.AsInterpolation();
var istring = token.ToInterpolatedString(" must not be null");
return SF.IfStatement(
SF.BinaryExpression(SyntaxKind.EqualsExpression,
Extensions.MemberAccess(
SF.IdentifierName(data),
SF.IdentifierName(requiredInfo.Name)
),
SF.LiteralExpression(SyntaxKind.NullLiteralExpression)
),
SF.Block().AddStatements(
SF.ExpressionStatement(
SF.InvocationExpression(
Extensions.MemberAccess(
Extensions.MemberAccess(
SF.IdentifierName(result),
SF.IdentifierName("Errors")
),
SF.IdentifierName("Add")
)
)
.AddArgumentListArguments(
SF.Argument(istring)
)
),
SF.ReturnStatement(
SF.IdentifierName(result)
)
)
);
}
private MethodDeclarationSyntax generatePostMethod(string propertyName, Type t)
{
var props = t.GetProperties();
var data = SF.Identifier("data");
var result = SF.Identifier("result");
var key = props.GetKeyProperty();
if (key == null)
{
return null;
}
var method = SF.MethodDeclaration(SF.GenericName("Result")
.AddTypeArgumentListArguments(SF.ParseTypeName(t.Name))
, "internalPost")
.AddModifiers(SF.Token(SyntaxKind.PrivateKeyword))
.AddParameterListParameters(
SF.Parameter(data)
.WithType(SF.ParseTypeName(t.Name))
);
var blocks = SF.Block();
/*var result = new Result<Device>();
result.Data = device;
result.Success = false;*/
blocks = blocks.AddStatements(
SF.LocalDeclarationStatement(
Extensions.VariableDeclaration(result.Text,
SF.EqualsValueClause(
SF.ObjectCreationExpression(SF.GenericName("Result").AddTypeArgumentListArguments(
SF.ParseTypeName(t.Name)
)).AddArgumentListArguments()
)
)
),
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
Extensions.MemberAccess(
result.Text,
"Data"
),
SF.IdentifierName(data)
)
),
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
Extensions.MemberAccess(
result.Text,
"Success"
),
false.ToLiteral()
)
)
);
/*if (device == null)
{
result.Errors.Add($"{nameof(device)} cannot be null");
return result;
}*/
blocks = blocks.AddStatements(
SF.IfStatement(
SF.BinaryExpression(
SyntaxKind.EqualsExpression,
SF.IdentifierName("data"),
SF.LiteralExpression(
SyntaxKind.NullLiteralExpression)),
SF.Block(
SF.ExpressionStatement(
SF.InvocationExpression(
SF.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SF.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SF.IdentifierName("result"),
SF.IdentifierName("Errors")),
SF.IdentifierName("Add")))
.WithArgumentList(
SF.ArgumentList(
SF.SingletonSeparatedList<ArgumentSyntax>(
SF.Argument(
SF.InterpolatedStringExpression(
SF.Token(SyntaxKind.InterpolatedStringStartToken))
.WithContents(
SF.List<InterpolatedStringContentSyntax>(
new InterpolatedStringContentSyntax[]{
SF.Interpolation(
SF.InvocationExpression(
SF.IdentifierName("nameof"))
.WithArgumentList(
SF.ArgumentList(
SF.SingletonSeparatedList<ArgumentSyntax>(
SF.Argument(
SF.IdentifierName("data")))))),
SF.InterpolatedStringText()
.WithTextToken(
SF.Token(
SF.TriviaList(),
SyntaxKind.InterpolatedStringTextToken,
" cannot be null",
" cannot be null",
SF.TriviaList()))}))))))),
SF.ReturnStatement(
SF.IdentifierName("result"))))
);
var keyType = SF.ParseTypeName(key.PropertyType.Name);
ExpressionSyntax defaultValue = keyType.GetDefaultValue();
if (key.PropertyType == typeof(Guid))
{
var rand = new Random();
defaultValue = rand.LiteralForProperty(key.PropertyType, key.Name);
}
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
Extensions.MemberAccess(
SF.IdentifierName(data),
SF.IdentifierName(key.Name)
),
defaultValue
)
)
);
foreach (var prop in props)
{
if (!prop.ShouldIgnore() && !prop.IsKey())
{
var genAtt = prop.GetGenerationAttribute();
if (genAtt != null)
{
if (genAtt.IsRequired)
{
var @if = postRequiredIfStatment(data, result, prop);
if (@if != null)
{
blocks = blocks.AddStatements(@if);
}
}
if (genAtt.CheckForEmptyString)
{
var @if = postEmptyStringIfStatment(data, result, prop);
if (@if != null)
{
blocks = blocks.AddStatements(@if);
}
}
if (genAtt.GreaterThenZero)
{
var @if = postGreaterThenZeroStatment(data, result, prop);
if (@if != null)
{
blocks = blocks.AddStatements(@if);
}
}
}
}
}
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.InvocationExpression(
SF.IdentifierName("postExtraVerification")
).AddArgumentListArguments(
SF.Argument(SF.IdentifierName(data)),
SF.Argument(SF.IdentifierName(result))
)
),
SF.IfStatement(
SF.BinaryExpression(SyntaxKind.GreaterThanExpression,
Extensions.MemberAccess(
Extensions.MemberAccess(
SF.IdentifierName(result),
SF.IdentifierName("Errors")
),
SF.IdentifierName("Count")
)
,
0.ToLiteral()
),
SF.Block().AddStatements(
SF.ReturnStatement(
SF.IdentifierName(result)
)
)
)
);
foreach (var prop in props)
{
if (!prop.ShouldIgnore() && !prop.IsKey())
{
var genAtt = prop.GetGenerationAttribute();
if (genAtt != null)
{
if (genAtt.IsNow)
{
if (prop.PropertyType == typeof(DateTime))
{
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
Extensions.MemberAccess(
SF.IdentifierName(data),
SF.IdentifierName(prop.Name)
),
Extensions.MemberAccess(
SF.IdentifierName("DateTime"),
SF.IdentifierName("Now")
)
)
)
);
}
if (prop.PropertyType == typeof(DateTimeOffset))
{
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
Extensions.MemberAccess(
SF.IdentifierName(data),
SF.IdentifierName(prop.Name)
),
Extensions.MemberAccess(
SF.IdentifierName("DateTimeOffset"),
SF.IdentifierName("Now")
)
)
)
);
}
}
if (genAtt.ShouldBeCount)
{
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
Extensions.MemberAccess(
SF.IdentifierName(data),
SF.IdentifierName(prop.Name)
),
SF.InvocationExpression(
Extensions.MemberAccess(
Extensions.MemberAccess(
SF.IdentifierName(context),
SF.IdentifierName(propertyName)
),
SF.IdentifierName("Count")
)
).AddArgumentListArguments()
)
)
);
}
}
}
}
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.InvocationExpression(
SF.IdentifierName("postExtraReset")
).AddArgumentListArguments(
SF.Argument(SF.IdentifierName(data))
)
),
SF.ExpressionStatement(
SF.InvocationExpression(
Extensions.MemberAccess(
Extensions.MemberAccess(
SF.IdentifierName(context),
SF.IdentifierName(propertyName)
),
SF.IdentifierName("Add")
)
).AddArgumentListArguments(
SF.Argument(SF.IdentifierName(data))
)
)
);
var ex = SF.Identifier("ex");
blocks = blocks.AddStatements(
SF.TryStatement()
.AddBlockStatements(
SF.ExpressionStatement(
SF.InvocationExpression(
Extensions.MemberAccess(
SF.IdentifierName(context),
SF.IdentifierName("SaveChanges")
)
).AddArgumentListArguments()
)
)
.AddCatches(
SF.CatchClause()
.WithDeclaration(
SF.CatchDeclaration(
SF.ParseTypeName("Exception"),
ex
)
).AddBlockStatements(
SF.IfStatement(
SF.InvocationExpression(
"logger".MemberAccess("IsEnabled")
).AddArgumentListArguments(
SF.Argument("LogLevel".MemberAccess("Error"))
),
SF.ExpressionStatement(
SF.InvocationExpression(
"logger".MemberAccess("LogError")
).AddArgumentListArguments(
SF.Argument("LoggingIds".MemberAccess("PostException")),
SF.Argument(SF.IdentifierName(ex)),
SF.Argument($"Error during {t.Name} Post".ToLiteral())
)
)
),
SF.ExpressionStatement(
SF.InvocationExpression(
Extensions.MemberAccess(
Extensions.MemberAccess(
SF.IdentifierName(result),
SF.IdentifierName("Errors")
),
SF.IdentifierName("Add")
)
).AddArgumentListArguments(
SF.Argument(
Extensions.MemberAccess(
SF.IdentifierName(ex),
SF.IdentifierName("Message")
)
)
)
),
SF.ReturnStatement(
SF.IdentifierName(result)
)
)
)
);
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
Extensions.MemberAccess(
SF.IdentifierName(result),
SF.IdentifierName("Success")
),
true.ToLiteral()
)
),
SF.ReturnStatement(
SF.IdentifierName(result)
)
);
method = method.WithBody(blocks);
return method;
}
private MethodDeclarationSyntax generatePutMethod(string propertyName, Type t)
{
var props = t.GetProperties();
var data = SF.Identifier("data");
var result = SF.Identifier("result");
var key = props.GetKeyProperty();
if (key == null)
{
return null;
}
var method = SF.MethodDeclaration(SF.GenericName("Result")
.AddTypeArgumentListArguments(SF.ParseTypeName(t.Name))
, "internalPut")
.AddModifiers(SF.Token(SyntaxKind.PrivateKeyword))
.AddParameterListParameters(
SF.Parameter(data)
.WithType(SF.ParseTypeName(t.Name))
);
var blocks = SF.Block();
/*var result = new Result<Device>();
result.Data = device;
result.Success = false;*/
blocks = blocks.AddStatements(
SF.LocalDeclarationStatement(
Extensions.VariableDeclaration(result.Text,
SF.EqualsValueClause(
SF.ObjectCreationExpression(SF.GenericName("Result").AddTypeArgumentListArguments(
SF.ParseTypeName(t.Name)
)).AddArgumentListArguments()
)
)
),
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
Extensions.MemberAccess(
result.Text,
"Data"
),
SF.IdentifierName(data)
)
),
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
Extensions.MemberAccess(
result.Text,
"Success"
),
false.ToLiteral()
)
)
);
/*if (device == null)
{
result.Errors.Add($"{nameof(device)} cannot be null");
return result;
}*/
blocks = blocks.AddStatements(
SF.IfStatement(
SF.BinaryExpression(
SyntaxKind.EqualsExpression,
SF.IdentifierName("data"),
SF.LiteralExpression(
SyntaxKind.NullLiteralExpression)),
SF.Block(
SF.ExpressionStatement(
SF.InvocationExpression(
SF.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SF.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SF.IdentifierName("result"),
SF.IdentifierName("Errors")),
SF.IdentifierName("Add")))
.WithArgumentList(
SF.ArgumentList(
SF.SingletonSeparatedList<ArgumentSyntax>(
SF.Argument(
SF.InterpolatedStringExpression(
SF.Token(SyntaxKind.InterpolatedStringStartToken))
.WithContents(
SF.List<InterpolatedStringContentSyntax>(
new InterpolatedStringContentSyntax[]{
SF.Interpolation(
SF.InvocationExpression(
SF.IdentifierName("nameof"))
.WithArgumentList(
SF.ArgumentList(
SF.SingletonSeparatedList<ArgumentSyntax>(
SF.Argument(
SF.IdentifierName("data")))))),
SF.InterpolatedStringText()
.WithTextToken(
SF.Token(
SF.TriviaList(),
SyntaxKind.InterpolatedStringTextToken,
" cannot be null",
" cannot be null",
SF.TriviaList()))}))))))),
SF.ReturnStatement(
SF.IdentifierName("result"))))
);
foreach (var prop in props)
{
if (!prop.ShouldIgnore() && !prop.IsKey())
{
var genAtt = prop.GetGenerationAttribute();
if (genAtt != null)
{
if (genAtt.IsRequired)
{
var @if = postRequiredIfStatment(data, result, prop);
if (@if != null)
{
blocks = blocks.AddStatements(@if);
}
}
if (genAtt.CheckForEmptyString)
{
var @if = postEmptyStringIfStatment(data, result, prop);
if (@if != null)
{
blocks = blocks.AddStatements(@if);
}
}
if (genAtt.GreaterThenZero)
{
var @if = postGreaterThenZeroStatment(data, result, prop);
if (@if != null)
{
blocks = blocks.AddStatements(@if);
}
}
}
}
}
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.InvocationExpression(
SF.IdentifierName("putExtraVerification")
).AddArgumentListArguments(
SF.Argument(SF.IdentifierName(data)),
SF.Argument(SF.IdentifierName(result))
)
),
SF.IfStatement(
SF.BinaryExpression(SyntaxKind.GreaterThanExpression,
Extensions.MemberAccess(
Extensions.MemberAccess(
SF.IdentifierName(result),
SF.IdentifierName("Errors")
),
SF.IdentifierName("Count")
)
,
0.ToLiteral()
),
SF.Block().AddStatements(
SF.ReturnStatement(
SF.IdentifierName(result)
)
)
)
);
var current = SF.Identifier("current");
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.InvocationExpression(
SF.IdentifierName("putExtraReset")
).AddArgumentListArguments(
SF.Argument(SF.IdentifierName(data))
)
),
SF.LocalDeclarationStatement(
Extensions.VariableDeclaration(
current.Text,
SF.EqualsValueClause(
SF.InvocationExpression(
context.Text.MemberAccess(propertyName, "FirstOrDefault")
)
.AddArgumentListArguments(
SF.Argument(
SF.ParenthesizedLambdaExpression(
SF.BinaryExpression(SyntaxKind.EqualsExpression,
"i".MemberAccess(key.Name),
data.Text.MemberAccess("Id")
)
).AddParameterListParameters(
SF.Parameter(SF.Identifier("i"))
)
)
)
)
)
),
SF.IfStatement(
SF.BinaryExpression(SyntaxKind.EqualsExpression,
SF.IdentifierName(current),
SF.LiteralExpression(SyntaxKind.NullLiteralExpression)
),
SF.Block().AddStatements(
SF.ExpressionStatement(
SF.InvocationExpression(
result.Text.MemberAccess("Errors", "Add")
).AddArgumentListArguments(
SF.Argument(
((StringToken)t.Name).ToInterpolatedString(
$" with {key.Name} ",
((StringToken)$"data.{key.Name}").AsInterpolation(),
" was not found")
)
)
),
SF.ReturnStatement(
SF.IdentifierName(result)
)
)
)
);
foreach(var prop in props)
{
if(!prop.ShouldIgnore() && prop.Name != key.Name)
{
if(!prop.CantUpdate())
{
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
current.Text.MemberAccess(prop.Name),
data.Text.MemberAccess(prop.Name)
)
)
);
}
}
}
/*
var current = context.Devices.FirstOrDefault(i => i.Id == data.Id);
if(current == null)
{
result.Errors.Add($"{Device} with {keyname} {id} was not found");
return result;
}
current... = data...
*/
var ex = SF.Identifier("ex");
blocks = blocks.AddStatements(
SF.TryStatement()
.AddBlockStatements(
SF.ExpressionStatement(
SF.InvocationExpression(
Extensions.MemberAccess(
SF.IdentifierName(context),
SF.IdentifierName("SaveChanges")
)
).AddArgumentListArguments()
),
// result.Data = current;
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
result.MemberAccess("Data"),
current.ToIN()
).ToStatement()
)
.AddCatches(
SF.CatchClause()
.WithDeclaration(
SF.CatchDeclaration(
SF.ParseTypeName("Exception"),
ex
)
).AddBlockStatements(
SF.IfStatement(
SF.InvocationExpression(
"logger".MemberAccess("IsEnabled")
).AddArgumentListArguments(
SF.Argument("LogLevel".MemberAccess("Error"))
),
SF.Block().
AddStatements(
SF.ExpressionStatement(
SF.InvocationExpression(
"logger".MemberAccess("LogError")
).AddArgumentListArguments(
SF.Argument("LoggingIds".MemberAccess("PutException")),
SF.Argument(SF.IdentifierName(ex)),
SF.Argument($"Error during {t.Name} Put".ToLiteral())
)
)
)
),
SF.ExpressionStatement(
SF.InvocationExpression(
Extensions.MemberAccess(
Extensions.MemberAccess(
SF.IdentifierName(result),
SF.IdentifierName("Errors")
),
SF.IdentifierName("Add")
)
).AddArgumentListArguments(
SF.Argument(
Extensions.MemberAccess(
SF.IdentifierName(ex),
SF.IdentifierName("Message")
)
)
)
),
SF.ReturnStatement(
SF.IdentifierName(result)
)
)
)
);
blocks = blocks.AddStatements(
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
Extensions.MemberAccess(
SF.IdentifierName(result),
SF.IdentifierName("Success")
),
true.ToLiteral()
)
),
SF.ReturnStatement(
SF.IdentifierName(result)
)
);
method = method.WithBody(blocks);
return method;
}
private MethodDeclarationSyntax generateDeleteMethod(string propertyName, Type t)
{
var props = t.GetProperties();
var keyName = SF.Identifier("key");
var result = SF.Identifier("result");
var data = SF.Identifier("data");
var key = props.GetKeyProperty();
if (key == null)
{
return null;
}
var method = SF.MethodDeclaration(SF.GenericName("Result")
.AddTypeArgumentListArguments(SF.ParseTypeName(t.Name))
, "internalDelete")
.AddModifiers(SF.Token(SyntaxKind.PrivateKeyword))
.AddParameterListParameters(
SF.Parameter(keyName)
.WithType(SF.ParseTypeName(key.PropertyType.Name))
);
var blocks = SF.Block();
blocks = blocks.AddStatements(
SF.LocalDeclarationStatement(
Extensions.VariableDeclaration(result.Text,
SF.EqualsValueClause(
SF.ObjectCreationExpression(SF.GenericName("Result").AddTypeArgumentListArguments(
SF.ParseTypeName(t.Name)
)).AddArgumentListArguments()
)
)
),
SF.LocalDeclarationStatement(
Extensions.VariableDeclaration(
data.Text,
SF.EqualsValueClause(
SF.InvocationExpression(
context.Text.MemberAccess(propertyName, "FirstOrDefault")
).AddArgumentListArguments(
SF.Argument(
SF.ParenthesizedLambdaExpression(
SF.BinaryExpression(SyntaxKind.EqualsExpression,
"i".MemberAccess(key.Name),
SF.IdentifierName(keyName)
)
).AddParameterListParameters(
SF.Parameter(SF.Identifier("i"))
)
)
)
)
)
),
SF.IfStatement(
SF.BinaryExpression(SyntaxKind.NotEqualsExpression,
SF.IdentifierName(data),
SF.LiteralExpression(SyntaxKind.NullLiteralExpression)
),
SF.Block().AddStatements(
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
result.Text.MemberAccess("Data"),
SF.IdentifierName(data)
)
),
SF.ExpressionStatement(
SF.InvocationExpression(SF.IdentifierName("deleteExtraVerification"))
.AddArgumentListArguments(
SF.Argument(
SF.IdentifierName(data)
),
SF.Argument(
SF.IdentifierName(result)
)
)
),
SF.IfStatement(
SF.BinaryExpression(SyntaxKind.GreaterThanExpression,
result.Text.MemberAccess("Errors", "Count"),
0.ToLiteral()
),
SF.Block().AddStatements(
SF.ReturnStatement(SF.IdentifierName(result))
)
),
SF.TryStatement()
.AddBlockStatements(
SF.ExpressionStatement(
SF.InvocationExpression(context.Text.MemberAccess(propertyName, "Remove"))
.AddArgumentListArguments(
SF.Argument(
SF.IdentifierName(data)
)
)
),
SF.ExpressionStatement(
SF.InvocationExpression(context.Text.MemberAccess("SaveChanges"))
.AddArgumentListArguments()
),
SF.ExpressionStatement(
SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
result.Text.MemberAccess("Success"),
true.ToLiteral()
)
),
SF.ReturnStatement(
SF.IdentifierName(result)
)
).AddCatches(
SF.CatchClause()
.WithDeclaration(SF.CatchDeclaration(SF.ParseTypeName("Exception"), SF.Identifier("ex")))
.AddBlockStatements(
SF.IfStatement(
SF.InvocationExpression("logger".MemberAccess("IsEnabled"))
.AddArgumentListArguments(
SF.Argument("LogLevel".MemberAccess("Error"))
),
SF.Block()
.AddStatements(
SF.ExpressionStatement(
SF.InvocationExpression(
"logger".MemberAccess("LogError")
)
.AddArgumentListArguments(
SF.Argument("LoggingIds".MemberAccess("DeleteException")),
SF.Argument(SF.IdentifierName("ex")),
SF.Argument(((StringToken)$"Exception deleting {t.Name} with {key.Name}").ToInterpolatedString(((StringToken)keyName.Text).AsInterpolation())
)
)
)
)
),
SF.ExpressionStatement(
SF.InvocationExpression(
result.Text.MemberAccess("Errors", "Add")
).AddArgumentListArguments(
SF.Argument("ex".MemberAccess("Message"))
)
),
SF.ReturnStatement(
SF.IdentifierName(result)
)
)
)
)),
SF.ExpressionStatement(
SF.InvocationExpression(result.Text.MemberAccess("Errors", "Add"))
.AddArgumentListArguments(
SF.Argument(
((StringToken)"Device with ID ").ToInterpolatedString(((StringToken)keyName.Text).AsInterpolation(),
" was not found")
)
)
),
SF.ReturnStatement(
SF.IdentifierName(result)
)
);
/*
result.Errors.Add($"Device with Id {key} was not found");
return result;
*/
return method.WithBody(blocks);
}
protected override CompilationUnitSyntax internalGenerate(string propertyName, Type t)
{
var fileName = $"{t.Name}Controller";
var unit = SF.CompilationUnit();
unit = unit.AddUsings(SF.UsingDirective(SF.IdentifierName("System"))).WithLeadingTrivia(GetLicenseComment());
unit = unit.AddUsings(SF.UsingDirective(SF.IdentifierName("System.Collections.Generic")));
unit = unit.AddUsings(SF.UsingDirective(SF.IdentifierName("System.Linq")));
unit = unit.AddUsings(SF.UsingDirective(SF.IdentifierName("System.Threading.Tasks")));
unit = unit.AddUsings(SF.UsingDirective(SF.IdentifierName("Microsoft.AspNetCore.Mvc")));
unit = unit.AddUsings(SF.UsingDirective(SF.IdentifierName("Sannel.House.Web.Base")));
unit = unit.AddUsings(SF.UsingDirective(SF.IdentifierName("Sannel.House.Web.Base.Models")));
unit = unit.AddUsings(SF.UsingDirective(SF.IdentifierName("Sannel.House.Web.Base.Interfaces")));
unit = unit.AddUsing("Microsoft.Extensions.Logging");
unit = unit.AddUsing("Microsoft.EntityFrameworkCore");
var ti = t.GetTypeInfo();
var ga = ti.GetCustomAttribute<GenerationAttribute>() ?? new GenerationAttribute();
var @class = SF.ClassDeclaration(fileName).AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.PartialKeyword)).AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("Controller")));
if (ga.ShouldGenerateMethod(GenerationAttribute.ApiCalls.Get))
{
@class = @class.AddMembers(generateGetMethod(propertyName, t, ga));
}
if (ga.ShouldGenerateMethod(GenerationAttribute.ApiCalls.GetWithId))
{
var get2 = generateGetWithIdMethod(propertyName, t);
if (get2 != null)
{
@class = @class.AddMembers(get2);
}
}
if (ga.ShouldGenerateMethod(GenerationAttribute.ApiCalls.Post))
{
var post = generatePostMethod(propertyName, t);
if (post != null)
{
@class = @class.AddMembers(post);
/* partial void postExtraVerification(Device device, Result<Device> result);
partial void postExtraReset(Device device, Result<Device> result);*/
@class = @class.AddMembers(SF.MethodDeclaration(SF.ParseTypeName("void"),
"postExtraVerification")
.AddModifiers(SF.Token(SyntaxKind.PartialKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("data")).WithType(SF.ParseTypeName(t.Name)),
SF.Parameter(SF.Identifier("result")).WithType(
SF.GenericName("Result")
.AddTypeArgumentListArguments(
SF.ParseTypeName(t.Name)
)
)
).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
);
@class = @class.AddMembers(SF.MethodDeclaration(SF.ParseTypeName("void"),
"postExtraReset")
.AddModifiers(SF.Token(SyntaxKind.PartialKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("data")).WithType(SF.ParseTypeName(t.Name))
).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
);
}
}
if (ga.ShouldGenerateMethod(GenerationAttribute.ApiCalls.Put))
{
var put = generatePutMethod(propertyName, t);
if (put != null)
{
@class = @class.AddMembers(put);
@class = @class.AddMembers(SF.MethodDeclaration(SF.ParseTypeName("void"),
"putExtraVerification")
.AddModifiers(SF.Token(SyntaxKind.PartialKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("data")).WithType(SF.ParseTypeName(t.Name)),
SF.Parameter(SF.Identifier("result")).WithType(
SF.GenericName("Result")
.AddTypeArgumentListArguments(
SF.ParseTypeName(t.Name)
)
)
).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
);
@class = @class.AddMembers(SF.MethodDeclaration(SF.ParseTypeName("void"),
"putExtraReset")
.AddModifiers(SF.Token(SyntaxKind.PartialKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("data")).WithType(SF.ParseTypeName(t.Name))
).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
);
}
}
if (ga.ShouldGenerateMethod(GenerationAttribute.ApiCalls.Delete))
{
var delete = generateDeleteMethod(propertyName, t);
if(delete != null)
{
@class = @class.AddMembers(delete);
@class = @class.AddMembers(SF.MethodDeclaration(SF.ParseTypeName("void"),
"deleteExtraVerification")
.AddModifiers(SF.Token(SyntaxKind.PartialKeyword))
.AddParameterListParameters(
SF.Parameter(SF.Identifier("data")).WithType(SF.ParseTypeName(t.Name)),
SF.Parameter(SF.Identifier("result")).WithType(
SF.GenericName("Result")
.AddTypeArgumentListArguments(
SF.ParseTypeName(t.Name)
)
)
).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken))
);
}
}
var namesp = SF.NamespaceDeclaration(SF.ParseName("Sannel.House.Web.Controllers.api"));
namesp = namesp.AddMembers(@class);
var syntax = unit.AddMembers(namesp);
return syntax;
}
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Diagnostics;
using System.Threading;
using dnlib.DotNet.MD;
namespace dnlib.DotNet {
/// <summary>
/// A high-level representation of a row in the ImplMap table
/// </summary>
[DebuggerDisplay("{Module} {Name}")]
public abstract class ImplMap : IMDTokenProvider {
/// <summary>
/// The row id in its table
/// </summary>
protected uint rid;
/// <inheritdoc/>
public MDToken MDToken {
get { return new MDToken(Table.ImplMap, rid); }
}
/// <inheritdoc/>
public uint Rid {
get { return rid; }
set { rid = value; }
}
/// <summary>
/// From column ImplMap.MappingFlags
/// </summary>
public PInvokeAttributes Attributes {
get { return (PInvokeAttributes)attributes; }
set { attributes = (int)value; }
}
/// <summary>Attributes</summary>
protected int attributes;
/// <summary>
/// From column ImplMap.ImportName
/// </summary>
public UTF8String Name {
get { return name; }
set { name = value; }
}
/// <summary>Name</summary>
protected UTF8String name;
/// <summary>
/// From column ImplMap.ImportScope
/// </summary>
public ModuleRef Module {
get { return module; }
set { module = value; }
}
/// <summary/>
protected ModuleRef module;
/// <summary>
/// Modify <see cref="attributes"/> property: <see cref="attributes"/> =
/// (<see cref="attributes"/> & <paramref name="andMask"/>) | <paramref name="orMask"/>.
/// </summary>
/// <param name="andMask">Value to <c>AND</c></param>
/// <param name="orMask">Value to OR</param>
void ModifyAttributes(PInvokeAttributes andMask, PInvokeAttributes orMask) {
#if THREAD_SAFE
int origVal, newVal;
do {
origVal = attributes;
newVal = (origVal & (int)andMask) | (int)orMask;
} while (Interlocked.CompareExchange(ref attributes, newVal, origVal) != origVal);
#else
attributes = (attributes & (int)andMask) | (int)orMask;
#endif
}
/// <summary>
/// Set or clear flags in <see cref="attributes"/>
/// </summary>
/// <param name="set"><c>true</c> if flags should be set, <c>false</c> if flags should
/// be cleared</param>
/// <param name="flags">Flags to set or clear</param>
void ModifyAttributes(bool set, PInvokeAttributes flags) {
#if THREAD_SAFE
int origVal, newVal;
do {
origVal = attributes;
if (set)
newVal = origVal | (int)flags;
else
newVal = origVal & ~(int)flags;
} while (Interlocked.CompareExchange(ref attributes, newVal, origVal) != origVal);
#else
if (set)
attributes |= (int)flags;
else
attributes &= ~(int)flags;
#endif
}
/// <summary>
/// Gets/sets the <see cref="PInvokeAttributes.NoMangle"/> bit
/// </summary>
public bool IsNoMangle {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.NoMangle) != 0; }
set { ModifyAttributes(value, PInvokeAttributes.NoMangle); }
}
/// <summary>
/// Gets/sets the char set
/// </summary>
public PInvokeAttributes CharSet {
get { return (PInvokeAttributes)attributes & PInvokeAttributes.CharSetMask; }
set { ModifyAttributes(~PInvokeAttributes.CharSetMask, value & PInvokeAttributes.CharSetMask); }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.CharSetNotSpec"/> is set
/// </summary>
public bool IsCharSetNotSpec {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.CharSetMask) == PInvokeAttributes.CharSetNotSpec; }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.CharSetAnsi"/> is set
/// </summary>
public bool IsCharSetAnsi {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.CharSetMask) == PInvokeAttributes.CharSetAnsi; }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.CharSetUnicode"/> is set
/// </summary>
public bool IsCharSetUnicode {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.CharSetMask) == PInvokeAttributes.CharSetUnicode; }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.CharSetAuto"/> is set
/// </summary>
public bool IsCharSetAuto {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.CharSetMask) == PInvokeAttributes.CharSetAuto; }
}
/// <summary>
/// Gets/sets best fit
/// </summary>
public PInvokeAttributes BestFit {
get { return (PInvokeAttributes)attributes & PInvokeAttributes.BestFitMask; }
set { ModifyAttributes(~PInvokeAttributes.BestFitMask, value & PInvokeAttributes.BestFitMask); }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.BestFitUseAssem"/> is set
/// </summary>
public bool IsBestFitUseAssem {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitUseAssem; }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.BestFitEnabled"/> is set
/// </summary>
public bool IsBestFitEnabled {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled; }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.BestFitDisabled"/> is set
/// </summary>
public bool IsBestFitDisabled {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitDisabled; }
}
/// <summary>
/// Gets/sets throw on unmappable char
/// </summary>
public PInvokeAttributes ThrowOnUnmappableChar {
get { return (PInvokeAttributes)attributes & PInvokeAttributes.ThrowOnUnmappableCharMask; }
set { ModifyAttributes(~PInvokeAttributes.ThrowOnUnmappableCharMask, value & PInvokeAttributes.ThrowOnUnmappableCharMask); }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.ThrowOnUnmappableCharUseAssem"/> is set
/// </summary>
public bool IsThrowOnUnmappableCharUseAssem {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharUseAssem; }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.ThrowOnUnmappableCharEnabled"/> is set
/// </summary>
public bool IsThrowOnUnmappableCharEnabled {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled; }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.ThrowOnUnmappableCharDisabled"/> is set
/// </summary>
public bool IsThrowOnUnmappableCharDisabled {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharDisabled; }
}
/// <summary>
/// Gets/sets the <see cref="PInvokeAttributes.SupportsLastError"/> bit
/// </summary>
public bool SupportsLastError {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.SupportsLastError) != 0; }
set { ModifyAttributes(value, PInvokeAttributes.SupportsLastError); }
}
/// <summary>
/// Gets/sets calling convention
/// </summary>
public PInvokeAttributes CallConv {
get { return (PInvokeAttributes)attributes & PInvokeAttributes.CallConvMask; }
set { ModifyAttributes(~PInvokeAttributes.CallConvMask, value & PInvokeAttributes.CallConvMask); }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.CallConvWinapi"/> is set
/// </summary>
public bool IsCallConvWinapi {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.CallConvMask) == PInvokeAttributes.CallConvWinapi; }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.CallConvCdecl"/> is set
/// </summary>
public bool IsCallConvCdecl {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.CallConvMask) == PInvokeAttributes.CallConvCdecl; }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.CallConvStdcall"/> is set
/// </summary>
public bool IsCallConvStdcall {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.CallConvMask) == PInvokeAttributes.CallConvStdcall; }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.CallConvThiscall"/> is set
/// </summary>
public bool IsCallConvThiscall {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.CallConvMask) == PInvokeAttributes.CallConvThiscall; }
}
/// <summary>
/// <c>true</c> if <see cref="PInvokeAttributes.CallConvFastcall"/> is set
/// </summary>
public bool IsCallConvFastcall {
get { return ((PInvokeAttributes)attributes & PInvokeAttributes.CallConvMask) == PInvokeAttributes.CallConvFastcall; }
}
/// <summary>
/// Checks whether this <see cref="ImplMap"/> is a certain P/Invoke method
/// </summary>
/// <param name="dllName">Name of the DLL</param>
/// <param name="funcName">Name of the function within the DLL</param>
/// <returns><c>true</c> if it's the specified P/Invoke method, else <c>false</c></returns>
public bool IsPinvokeMethod(string dllName, string funcName) {
if (name != funcName)
return false;
var mod = module;
if (mod == null)
return false;
return GetDllName(dllName).Equals(GetDllName(mod.Name), StringComparison.OrdinalIgnoreCase);
}
static string GetDllName(string dllName) {
if (dllName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
return dllName.Substring(0, dllName.Length - 4);
return dllName;
}
}
/// <summary>
/// An ImplMap row created by the user and not present in the original .NET file
/// </summary>
public class ImplMapUser : ImplMap {
/// <summary>
/// Default constructor
/// </summary>
public ImplMapUser() {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="scope">Scope</param>
/// <param name="name">Name</param>
/// <param name="flags">Flags</param>
public ImplMapUser(ModuleRef scope, UTF8String name, PInvokeAttributes flags) {
this.module = scope;
this.name = name;
this.attributes = (int)flags;
}
}
/// <summary>
/// Created from a row in the ImplMap table
/// </summary>
sealed class ImplMapMD : ImplMap, IMDTokenProviderMD {
readonly uint origRid;
/// <inheritdoc/>
public uint OrigRid {
get { return origRid; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="readerModule">The module which contains this <c>ImplMap</c> row</param>
/// <param name="rid">Row ID</param>
/// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception>
/// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception>
public ImplMapMD(ModuleDefMD readerModule, uint rid) {
#if DEBUG
if (readerModule == null)
throw new ArgumentNullException("readerModule");
if (readerModule.TablesStream.ImplMapTable.IsInvalidRID(rid))
throw new BadImageFormatException(string.Format("ImplMap rid {0} does not exist", rid));
#endif
this.origRid = rid;
this.rid = rid;
uint name;
uint scope = readerModule.TablesStream.ReadImplMapRow(origRid, out this.attributes, out name);
this.name = readerModule.StringsStream.ReadNoNull(name);
this.module = readerModule.ResolveModuleRef(scope);
}
}
}
| |
//! \file ImageBPC.cs
//! \date 2017 Nov 22
//! \brief C's ware bitmap.
//
// Copyright (C) 2017 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace GameRes.Formats.CsWare
{
[Export(typeof(ImageFormat))]
public class BpcFormat : ImageFormat
{
public override string Tag { get { return "BPC"; } }
public override string Description { get { return "C's ware bitmap format"; } }
public override uint Signature { get { return 0x28; } }
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
var header = file.ReadHeader (0x10);
uint width = header.ToUInt32 (4);
uint height = header.ToUInt32 (8);
int bpp = header.ToUInt16 (0xE);
if (bpp != 1 && bpp != 8 && bpp != 24)
return null;
return new ImageMetaData { Width = width, Height = height, BPP = bpp };
}
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var bpc = new BpcReader (file, info);
bpc.Unpack();
return ImageData.CreateFlipped (info, bpc.Format, bpc.Palette, bpc.Data, bpc.Stride);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("BpcFormat.Write not implemented");
}
}
internal sealed class BpcReader
{
IBinaryStream m_input;
int m_width;
int m_height;
int m_bpp;
byte[] m_output;
public BitmapPalette Palette { get; private set; }
public PixelFormat Format { get; private set; }
public byte[] Data { get { return m_output; } }
public int Stride { get { return m_width * m_bpp / 8; } }
public BpcReader (IBinaryStream input, ImageMetaData info)
{
m_input = input;
m_width = (int)info.Width;
m_height = (int)info.Height;
m_bpp = info.BPP;
}
public void Unpack ()
{
m_input.Position = m_input.Signature;
if (m_bpp <= 8)
Palette = ImageFormat.ReadPalette (m_input.AsStream, 1 << m_bpp);
switch (m_bpp)
{
case 1: Unpack1bpp(); break;
case 8: Unpack8bpp(); break;
case 24: Unpack24bpp(); break;
default: throw new InvalidFormatException();
}
}
void Unpack1bpp ()
{
Format = PixelFormats.Indexed1;
m_output = m_input.ReadBytes (m_height * Stride);
}
void Unpack8bpp ()
{
Format = PixelFormats.Indexed8;
m_output = new byte[m_height * m_width];
int packed_size = m_input.ReadInt32();
byte index = 0;
byte ctl = m_input.ReadUInt8();
if (0xF5 == ctl)
index = m_input.ReadUInt8();
var input = m_input.ReadBytes (packed_size);
if (input.Length != packed_size)
throw new InvalidFormatException();
int src = 0;
int dst = 0;
while (src < packed_size)
{
if (input[src] != ctl)
{
m_output[dst++] = input[src++];
}
else if (ctl != 0xF5)
{
int count = input[src+1];
for (int i = 0; i < count; ++i)
m_output[dst++] = input[src-1];
src += 2;
}
else if (input[src+1] == index)
{
int count = input[src+2];
for (int i = 0; i < count; ++i)
m_output[dst++] = input[src-1];
src += 3;
}
else
{
m_output[dst++] = input[src++];
}
}
}
void Unpack24bpp ()
{
Format = PixelFormats.Bgr24;
m_output = new byte[m_height * Stride];
var plane_size = new int[3];
plane_size[0] = m_input.ReadInt32();
plane_size[1] = m_input.ReadInt32();
plane_size[2] = m_input.ReadInt32();
var ctl = m_input.ReadBytes (3);
var pixel = m_input.ReadBytes (3);
var input = m_input.ReadBytes (plane_size.Sum());
int src = 0;
for (int plane = 0; plane < 3; ++plane)
{
int dst = plane;
for (int p = 0; p < plane_size[plane]; ++p)
{
if (ctl[plane] != input[src])
{
m_output[dst] = input[src++];
dst += 3;
}
else if (ctl[plane] != 0xF5)
{
int count = input[src + 1];
for (int i = 0; i < count; ++i)
{
m_output[dst] = input[src - 1];
dst += 3;
}
++p;
src += 2;
}
else if (pixel[plane] == input[src + 1])
{
int count = input[src + 2];
for (int i = 0; i < count; ++i)
{
m_output[dst] = input[src - 1];
dst += 3;
}
p += 2;
src += 3;
}
else
{
m_output[dst] = input[src++];
dst += 3;
}
}
}
}
}
}
| |
using System;
using System.Collections;
using IO = System.IO;
using NBM.Plugin;
using Regex = System.Text.RegularExpressions;
// 9/6/03
/// <summary>
/// Summary description for Conversation.
/// </summary>
public class Conversation : IConversation
{
private Protocol protocol;
private Settings settings;
private ConversationControl control;
private MessageRouter sbRouter;
private void RegisterCodeEvents()
{
sbRouter.AddCodeEvent("MSG", new ResponseReceivedHandler(OnMsgReceived), null);
sbRouter.AddCodeEvent("BYE", new ResponseReceivedHandler(OnByeReceived), null);
sbRouter.AddCodeEvent("JOI", new ResponseReceivedHandler(OnJoinReceived), null);
}
private void OnSwitchBoardRequestResponse(MessageRouter router, Message message, object tag)
{
object[] o = (object[])tag;
Friend friend = (Friend)o[0];
OperationCompleteEvent op = (OperationCompleteEvent)o[1];
Regex.Regex regex = new Regex.Regex(@"SB (?<sbServerIP>\d+\.\d+\.\d+\.\d+):(?<sbServerPort>\d+) CKI (?<hash>.*$)");
Regex.Match match = regex.Match(message.Arguments);
if (match.Success)
{
string sbIP = match.Groups["sbServerIP"].Value;
int sbPort = int.Parse(match.Groups["sbServerPort"].Value);
string conversationID = match.Groups["hash"].Value;
// connect
try
{
Proxy.IConnection conn = this.control.CreateConnection();
conn.Connect("", 0, sbIP, sbPort, Proxy.ConnectionType.Tcp);
sbRouter = new MessageRouter(this.protocol, conn, null, new ResponseReceivedHandler(OnForcedDisconnect));
}
catch
{
op.Execute(new OperationCompleteArgs("Could not connect", true));
return;
}
RegisterCodeEvents();
sbRouter.SendMessage(Message.ConstructMessage("USR", this.settings.Username + " " + conversationID),
new ResponseReceivedHandler(OnSwitchBoardUsrResponse), tag);
}
else
op.Execute(new OperationCompleteArgs("Could not connect", true));
router.RemoveMessageEvent(message);
}
private void OnForcedDisconnect(MessageRouter router, Message message, object tag)
{
// control.ForcedDisconnection();
}
private void OnSwitchBoardUsrResponse(MessageRouter router, Message message, object tag)
{
object[] objs = (object[])tag;
Friend friend = (Friend)objs[0];
OperationCompleteEvent e = (OperationCompleteEvent)objs[1];
this.InviteFriend(friend, e);
router.RemoveMessageEvent(message);
}
private void OnAnswerResponse(MessageRouter router, Message message, object tag)
{
if (message.Arguments == "OK")
{
((OperationCompleteEvent)tag).Execute(new OperationCompleteArgs());
router.RemoveMessageEvent(message);
}
else
{
if (message.Code == "IRO")
{
Regex.Regex regex = new Regex.Regex(
@"(?<userNumber>\d+)\s+(?<totalUsers>\d+)\s+(?<username>\S+)\s+(?<screenName>.*$)"
);
Regex.Match match = regex.Match(message.Arguments);
if (match.Success)
{
string username = match.Groups["username"].Value;
control.FriendJoin(username);
}
}
}
}
private void OnMsgReceived(MessageRouter router, Message message, object tag)
{
// seperate message from all the crap
string actualMessage = message.Body.Substring( message.Body.IndexOf("\r\n\r\n") + 4 );
actualMessage.TrimEnd('\r', '\n');
// locate content type in mime headers
Regex.Regex contentTypeRegex = new Regex.Regex(@"\r\nContent-Type:\s+(?<contentType>[^\;\s]+)");
Regex.Match contentTypeMatch = contentTypeRegex.Match(message.Body);
if (contentTypeMatch.Success)
{
string contentType = contentTypeMatch.Groups["contentType"].Value;
switch (contentType)
{
case "text/x-msmsgscontrol": // user typing notification
{
// get username of typing user
Regex.Regex notifyRegex = new Regex.Regex(@"TypingUser: (?<username>[^\r]+)");
Regex.Match notifyMatch = notifyRegex.Match(message.Body);
if (notifyMatch.Success)
{
this.control.TypingNotification(notifyMatch.Groups["username"].Value);
}
}
return;
case "text/x-msmsgsinvite": // file transfer, netmeeting invitation
return;
}
}
// find user's name
Regex.Regex regex = new Regex.Regex(@"(?<username>\S+)\s+(?<displayName>\S+)\s+\d+");
Regex.Match match = regex.Match(message.Header);
if (match.Success)
{
string username = match.Groups["username"].Value;
string displayName = match.Groups["displayName"].Value;
control.FriendSay(username, actualMessage);
}
}
private void OnByeReceived(MessageRouter router, Message message, object tag)
{
Regex.Regex regex = new Regex.Regex(@"(?<username>\S*)\s*\d*");
Regex.Match match = regex.Match(message.Arguments);
if (match.Success)
{
string username = match.Groups["username"].Value;
control.FriendLeave(username);
}
}
private void OnJoinReceived(MessageRouter router, Message message, object tag)
{
Regex.Regex regex = new Regex.Regex(@"(?<username>\S+)\s+(?<screenName>\S+)");
Regex.Match match = regex.Match(message.Arguments);
if (match.Success)
{
string email = match.Groups["username"].Value;
string screenName = match.Groups["screenName"].Value;
control.FriendJoin(email);
}
}
private void OnSayAck(MessageRouter router, Message message, object tag)
{
switch (message.Code)
{
case "ACK":
((OperationCompleteEvent)tag).Execute(new OperationCompleteArgs());
break;
case "NAK":
((OperationCompleteEvent)tag).Execute(new OperationCompleteArgs("Message could not be sent", false));
break;
default:
((OperationCompleteEvent)tag).Execute(new OperationCompleteArgs("Unknown error occurred", false));
break;
}
}
private void OnInviteFriendComplete(MessageRouter router, Message message, object tag)
{
router.RemoveMessageEvent(message);
}
private void OnJoinAfterInvite(MessageRouter router, Message message, object tag)
{
router.AddCodeEvent("JOI", new ResponseReceivedHandler(OnJoinReceived), null);
OnJoinReceived(router, message, null);
((OperationCompleteEvent)tag).Execute(new OperationCompleteArgs());
}
public Conversation(IProtocol protocol, ConversationControl control, ProtocolSettings settings)
{
this.protocol = (Protocol)protocol;
this.control = control;
this.settings = (Settings)settings;
}
public void Start(Friend friend, OperationCompleteEvent opCompleteEvent)
{
protocol.notifyRouter.SendMessage(Message.ConstructMessage("XFR", "SB"),
new ResponseReceivedHandler(OnSwitchBoardRequestResponse),
new object[] { friend, opCompleteEvent });
}
public void StartByInvitation(Friend friend, OperationCompleteEvent opCompleteEvent, object tag)
{
object[] objs = (object[])tag;
string sbIP = (string)objs[0];
int sbPort = (int)objs[1];
string hash = (string)objs[2];
string sessionID = (string)objs[3];
try
{
Proxy.IConnection conn = this.control.CreateConnection();
conn.Connect("", 0, sbIP, sbPort, Proxy.ConnectionType.Tcp);
sbRouter = new MessageRouter(this.protocol, conn, null, null);
RegisterCodeEvents();
sbRouter.SendMessage(Message.ConstructMessage("ANS",
this.settings.Username + " " + hash + " " + sessionID),
new ResponseReceivedHandler(OnAnswerResponse), opCompleteEvent);
}
catch
{
opCompleteEvent.Execute(new OperationCompleteArgs("Could not connect", true));
}
}
public void End(OperationCompleteEvent opCompleteEvent)
{
if (sbRouter != null)
{
sbRouter.SendMessage(Message.ConstructMessage("OUT", string.Empty, string.Empty, false));
sbRouter.Close();
}
opCompleteEvent.Execute(new OperationCompleteArgs());
}
public void Say(string text, OperationCompleteEvent opCompleteEvent)
{
string mimeHeader = "MIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nX-MMS-IM-Format: FN=Microsoft%20Sans%20Serif; CO=000000; CS=0; PF=22\r\n\r\n";
int length = mimeHeader.Length + text.Length;
sbRouter.SendMessage(Message.ConstructMessage("MSG", "A " + length + "\r\n" + mimeHeader + text), new ResponseReceivedHandler(OnSayAck), opCompleteEvent, false);
}
public void InviteFriend(Friend friend, OperationCompleteEvent opCompleteEvent)
{
sbRouter.AddCodeEvent("JOI", new ResponseReceivedHandler(OnJoinAfterInvite), opCompleteEvent);
sbRouter.SendMessage(Message.ConstructMessage("CAL", friend.Username), new ResponseReceivedHandler(OnInviteFriendComplete), opCompleteEvent);
}
public void SendTypingNotification(OperationCompleteEvent opCompleteEvent)
{
string body = "MIME-Version: 1.0\r\n"
+ "Content-Type: text/x-msmsgscontrol\r\n"
+ "TypingUser: " + this.settings.Username + "\r\n\r\n\r\n";
this.sbRouter.SendMessage( Message.ConstructMessage("MSG", "U " + body.Length, body, true), false );
opCompleteEvent.Execute(new OperationCompleteArgs());
}
public void SendFile(IO.Stream stream, OperationCompleteEvent opCompleteEvent)
{
opCompleteEvent.Execute(new OperationCompleteArgs());
}
}
| |
// 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 searchservice
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// StorageAccounts operations.
/// </summary>
public partial interface IStorageAccounts
{
/// <summary>
/// Checks that account name is valid and is not in use.
/// </summary>
/// <param name='accountName'>
/// The name of the storage account within the specified resource
/// group. Storage account names must be between 3 and 24 characters in
/// length and use numbers and lower-case letters only.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// 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<HttpOperationResponse<CheckNameAvailabilityResult>> CheckNameAvailabilityWithHttpMessagesAsync(StorageAccountCheckNameAvailabilityParameters accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Asynchronously creates a new storage account with the specified
/// parameters. Existing accounts cannot be updated with this API and
/// should instead use the Update Storage Account API. If an account is
/// already created and subsequent PUT request is issued with exact
/// same set of properties, then HTTP 200 would be returned.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource
/// group. Storage account names must be between 3 and 24 characters in
/// length and use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to provide for the created account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// 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<HttpOperationResponse<StorageAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a storage account in Microsoft Azure.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource
/// group. Storage account names must be between 3 and 24 characters in
/// length and use numbers and lower-case letters only.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the properties for the specified storage account including
/// but not limited to name, account type, location, and account
/// status. The ListKeys operation should be used to retrieve storage
/// keys.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource
/// group. Storage account names must be between 3 and 24 characters in
/// length and use numbers and lower-case letters only.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// 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<HttpOperationResponse<StorageAccount>> GetPropertiesWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the account type or tags for a storage account. It can also
/// be used to add a custom domain (note that custom domains cannot be
/// added via the Create operation). Only one custom domain is
/// supported per storage account. In order to replace a custom domain,
/// the old value must be cleared before a new value may be set. To
/// clear a custom domain, simply update the custom domain with empty
/// string. Then call update again with the new cutsom domain name. The
/// update API can only be used to update one of tags, accountType, or
/// customDomain per call. To update multiple of these properties, call
/// the API multiple times with one change per call. This call does not
/// change the storage keys for the account. If you want to change
/// storage account keys, use the RegenerateKey operation. The location
/// and name of the storage account cannot be changed after creation.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource
/// group. Storage account names must be between 3 and 24 characters in
/// length and use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to update on the account. Note that only one
/// property can be changed at a time using this API.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// 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<HttpOperationResponse<StorageAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the access keys for the specified storage account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the storage account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// 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<HttpOperationResponse<StorageAccountKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the storage accounts available under the subscription.
/// Note that storage keys are not returned; use the ListKeys operation
/// for this.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// 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<HttpOperationResponse<StorageAccountListResult>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the storage accounts available under the given resource
/// group. Note that storage keys are not returned; use the ListKeys
/// operation for this.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// 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<HttpOperationResponse<StorageAccountListResult>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Regenerates the access keys for the specified storage account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource
/// group. Storage account names must be between 3 and 24 characters in
/// length and use numbers and lower-case letters only.
/// </param>
/// <param name='regenerateKey'>
/// Specifies name of the key which should be regenerated. key1 or key2
/// for the default keys
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// 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<HttpOperationResponse<StorageAccountKeys>> RegenerateKeyWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/map_unittest_proto3.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf.TestProtos {
/// <summary>Holder for reflection information generated from google/protobuf/map_unittest_proto3.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class MapUnittestProto3Reflection {
#region Descriptor
/// <summary>File descriptor for google/protobuf/map_unittest_proto3.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static MapUnittestProto3Reflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cilnb29nbGUvcHJvdG9idWYvbWFwX3VuaXR0ZXN0X3Byb3RvMy5wcm90bxIR",
"cHJvdG9idWZfdW5pdHRlc3QaJWdvb2dsZS9wcm90b2J1Zi91bml0dGVzdF9w",
"cm90bzMucHJvdG8ilhIKB1Rlc3RNYXASRgoPbWFwX2ludDMyX2ludDMyGAEg",
"AygLMi0ucHJvdG9idWZfdW5pdHRlc3QuVGVzdE1hcC5NYXBJbnQzMkludDMy",
"RW50cnkSRgoPbWFwX2ludDY0X2ludDY0GAIgAygLMi0ucHJvdG9idWZfdW5p",
"dHRlc3QuVGVzdE1hcC5NYXBJbnQ2NEludDY0RW50cnkSSgoRbWFwX3VpbnQz",
"Ml91aW50MzIYAyADKAsyLy5wcm90b2J1Zl91bml0dGVzdC5UZXN0TWFwLk1h",
"cFVpbnQzMlVpbnQzMkVudHJ5EkoKEW1hcF91aW50NjRfdWludDY0GAQgAygL",
"Mi8ucHJvdG9idWZfdW5pdHRlc3QuVGVzdE1hcC5NYXBVaW50NjRVaW50NjRF",
"bnRyeRJKChFtYXBfc2ludDMyX3NpbnQzMhgFIAMoCzIvLnByb3RvYnVmX3Vu",
"aXR0ZXN0LlRlc3RNYXAuTWFwU2ludDMyU2ludDMyRW50cnkSSgoRbWFwX3Np",
"bnQ2NF9zaW50NjQYBiADKAsyLy5wcm90b2J1Zl91bml0dGVzdC5UZXN0TWFw",
"Lk1hcFNpbnQ2NFNpbnQ2NEVudHJ5Ek4KE21hcF9maXhlZDMyX2ZpeGVkMzIY",
"ByADKAsyMS5wcm90b2J1Zl91bml0dGVzdC5UZXN0TWFwLk1hcEZpeGVkMzJG",
"aXhlZDMyRW50cnkSTgoTbWFwX2ZpeGVkNjRfZml4ZWQ2NBgIIAMoCzIxLnBy",
"b3RvYnVmX3VuaXR0ZXN0LlRlc3RNYXAuTWFwRml4ZWQ2NEZpeGVkNjRFbnRy",
"eRJSChVtYXBfc2ZpeGVkMzJfc2ZpeGVkMzIYCSADKAsyMy5wcm90b2J1Zl91",
"bml0dGVzdC5UZXN0TWFwLk1hcFNmaXhlZDMyU2ZpeGVkMzJFbnRyeRJSChVt",
"YXBfc2ZpeGVkNjRfc2ZpeGVkNjQYCiADKAsyMy5wcm90b2J1Zl91bml0dGVz",
"dC5UZXN0TWFwLk1hcFNmaXhlZDY0U2ZpeGVkNjRFbnRyeRJGCg9tYXBfaW50",
"MzJfZmxvYXQYCyADKAsyLS5wcm90b2J1Zl91bml0dGVzdC5UZXN0TWFwLk1h",
"cEludDMyRmxvYXRFbnRyeRJIChBtYXBfaW50MzJfZG91YmxlGAwgAygLMi4u",
"cHJvdG9idWZfdW5pdHRlc3QuVGVzdE1hcC5NYXBJbnQzMkRvdWJsZUVudHJ5",
"EkIKDW1hcF9ib29sX2Jvb2wYDSADKAsyKy5wcm90b2J1Zl91bml0dGVzdC5U",
"ZXN0TWFwLk1hcEJvb2xCb29sRW50cnkSSgoRbWFwX3N0cmluZ19zdHJpbmcY",
"DiADKAsyLy5wcm90b2J1Zl91bml0dGVzdC5UZXN0TWFwLk1hcFN0cmluZ1N0",
"cmluZ0VudHJ5EkYKD21hcF9pbnQzMl9ieXRlcxgPIAMoCzItLnByb3RvYnVm",
"X3VuaXR0ZXN0LlRlc3RNYXAuTWFwSW50MzJCeXRlc0VudHJ5EkQKDm1hcF9p",
"bnQzMl9lbnVtGBAgAygLMiwucHJvdG9idWZfdW5pdHRlc3QuVGVzdE1hcC5N",
"YXBJbnQzMkVudW1FbnRyeRJZChltYXBfaW50MzJfZm9yZWlnbl9tZXNzYWdl",
"GBEgAygLMjYucHJvdG9idWZfdW5pdHRlc3QuVGVzdE1hcC5NYXBJbnQzMkZv",
"cmVpZ25NZXNzYWdlRW50cnkaNAoSTWFwSW50MzJJbnQzMkVudHJ5EgsKA2tl",
"eRgBIAEoBRINCgV2YWx1ZRgCIAEoBToCOAEaNAoSTWFwSW50NjRJbnQ2NEVu",
"dHJ5EgsKA2tleRgBIAEoAxINCgV2YWx1ZRgCIAEoAzoCOAEaNgoUTWFwVWlu",
"dDMyVWludDMyRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4",
"ARo2ChRNYXBVaW50NjRVaW50NjRFbnRyeRILCgNrZXkYASABKAQSDQoFdmFs",
"dWUYAiABKAQ6AjgBGjYKFE1hcFNpbnQzMlNpbnQzMkVudHJ5EgsKA2tleRgB",
"IAEoERINCgV2YWx1ZRgCIAEoEToCOAEaNgoUTWFwU2ludDY0U2ludDY0RW50",
"cnkSCwoDa2V5GAEgASgSEg0KBXZhbHVlGAIgASgSOgI4ARo4ChZNYXBGaXhl",
"ZDMyRml4ZWQzMkVudHJ5EgsKA2tleRgBIAEoBxINCgV2YWx1ZRgCIAEoBzoC",
"OAEaOAoWTWFwRml4ZWQ2NEZpeGVkNjRFbnRyeRILCgNrZXkYASABKAYSDQoF",
"dmFsdWUYAiABKAY6AjgBGjoKGE1hcFNmaXhlZDMyU2ZpeGVkMzJFbnRyeRIL",
"CgNrZXkYASABKA8SDQoFdmFsdWUYAiABKA86AjgBGjoKGE1hcFNmaXhlZDY0",
"U2ZpeGVkNjRFbnRyeRILCgNrZXkYASABKBASDQoFdmFsdWUYAiABKBA6AjgB",
"GjQKEk1hcEludDMyRmxvYXRFbnRyeRILCgNrZXkYASABKAUSDQoFdmFsdWUY",
"AiABKAI6AjgBGjUKE01hcEludDMyRG91YmxlRW50cnkSCwoDa2V5GAEgASgF",
"Eg0KBXZhbHVlGAIgASgBOgI4ARoyChBNYXBCb29sQm9vbEVudHJ5EgsKA2tl",
"eRgBIAEoCBINCgV2YWx1ZRgCIAEoCDoCOAEaNgoUTWFwU3RyaW5nU3RyaW5n",
"RW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ARo0ChJNYXBJ",
"bnQzMkJ5dGVzRW50cnkSCwoDa2V5GAEgASgFEg0KBXZhbHVlGAIgASgMOgI4",
"ARpPChFNYXBJbnQzMkVudW1FbnRyeRILCgNrZXkYASABKAUSKQoFdmFsdWUY",
"AiABKA4yGi5wcm90b2J1Zl91bml0dGVzdC5NYXBFbnVtOgI4ARpgChtNYXBJ",
"bnQzMkZvcmVpZ25NZXNzYWdlRW50cnkSCwoDa2V5GAEgASgFEjAKBXZhbHVl",
"GAIgASgLMiEucHJvdG9idWZfdW5pdHRlc3QuRm9yZWlnbk1lc3NhZ2U6AjgB",
"IkEKEVRlc3RNYXBTdWJtZXNzYWdlEiwKCHRlc3RfbWFwGAEgASgLMhoucHJv",
"dG9idWZfdW5pdHRlc3QuVGVzdE1hcCK8AQoOVGVzdE1lc3NhZ2VNYXASUQoR",
"bWFwX2ludDMyX21lc3NhZ2UYASADKAsyNi5wcm90b2J1Zl91bml0dGVzdC5U",
"ZXN0TWVzc2FnZU1hcC5NYXBJbnQzMk1lc3NhZ2VFbnRyeRpXChRNYXBJbnQz",
"Mk1lc3NhZ2VFbnRyeRILCgNrZXkYASABKAUSLgoFdmFsdWUYAiABKAsyHy5w",
"cm90b2J1Zl91bml0dGVzdC5UZXN0QWxsVHlwZXM6AjgBIuMBCg9UZXN0U2Ft",
"ZVR5cGVNYXASOgoEbWFwMRgBIAMoCzIsLnByb3RvYnVmX3VuaXR0ZXN0LlRl",
"c3RTYW1lVHlwZU1hcC5NYXAxRW50cnkSOgoEbWFwMhgCIAMoCzIsLnByb3Rv",
"YnVmX3VuaXR0ZXN0LlRlc3RTYW1lVHlwZU1hcC5NYXAyRW50cnkaKwoJTWFw",
"MUVudHJ5EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgCIAEoBToCOAEaKwoJTWFw",
"MkVudHJ5EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgCIAEoBToCOAEi5BAKDFRl",
"c3RBcmVuYU1hcBJLCg9tYXBfaW50MzJfaW50MzIYASADKAsyMi5wcm90b2J1",
"Zl91bml0dGVzdC5UZXN0QXJlbmFNYXAuTWFwSW50MzJJbnQzMkVudHJ5EksK",
"D21hcF9pbnQ2NF9pbnQ2NBgCIAMoCzIyLnByb3RvYnVmX3VuaXR0ZXN0LlRl",
"c3RBcmVuYU1hcC5NYXBJbnQ2NEludDY0RW50cnkSTwoRbWFwX3VpbnQzMl91",
"aW50MzIYAyADKAsyNC5wcm90b2J1Zl91bml0dGVzdC5UZXN0QXJlbmFNYXAu",
"TWFwVWludDMyVWludDMyRW50cnkSTwoRbWFwX3VpbnQ2NF91aW50NjQYBCAD",
"KAsyNC5wcm90b2J1Zl91bml0dGVzdC5UZXN0QXJlbmFNYXAuTWFwVWludDY0",
"VWludDY0RW50cnkSTwoRbWFwX3NpbnQzMl9zaW50MzIYBSADKAsyNC5wcm90",
"b2J1Zl91bml0dGVzdC5UZXN0QXJlbmFNYXAuTWFwU2ludDMyU2ludDMyRW50",
"cnkSTwoRbWFwX3NpbnQ2NF9zaW50NjQYBiADKAsyNC5wcm90b2J1Zl91bml0",
"dGVzdC5UZXN0QXJlbmFNYXAuTWFwU2ludDY0U2ludDY0RW50cnkSUwoTbWFw",
"X2ZpeGVkMzJfZml4ZWQzMhgHIAMoCzI2LnByb3RvYnVmX3VuaXR0ZXN0LlRl",
"c3RBcmVuYU1hcC5NYXBGaXhlZDMyRml4ZWQzMkVudHJ5ElMKE21hcF9maXhl",
"ZDY0X2ZpeGVkNjQYCCADKAsyNi5wcm90b2J1Zl91bml0dGVzdC5UZXN0QXJl",
"bmFNYXAuTWFwRml4ZWQ2NEZpeGVkNjRFbnRyeRJXChVtYXBfc2ZpeGVkMzJf",
"c2ZpeGVkMzIYCSADKAsyOC5wcm90b2J1Zl91bml0dGVzdC5UZXN0QXJlbmFN",
"YXAuTWFwU2ZpeGVkMzJTZml4ZWQzMkVudHJ5ElcKFW1hcF9zZml4ZWQ2NF9z",
"Zml4ZWQ2NBgKIAMoCzI4LnByb3RvYnVmX3VuaXR0ZXN0LlRlc3RBcmVuYU1h",
"cC5NYXBTZml4ZWQ2NFNmaXhlZDY0RW50cnkSSwoPbWFwX2ludDMyX2Zsb2F0",
"GAsgAygLMjIucHJvdG9idWZfdW5pdHRlc3QuVGVzdEFyZW5hTWFwLk1hcElu",
"dDMyRmxvYXRFbnRyeRJNChBtYXBfaW50MzJfZG91YmxlGAwgAygLMjMucHJv",
"dG9idWZfdW5pdHRlc3QuVGVzdEFyZW5hTWFwLk1hcEludDMyRG91YmxlRW50",
"cnkSRwoNbWFwX2Jvb2xfYm9vbBgNIAMoCzIwLnByb3RvYnVmX3VuaXR0ZXN0",
"LlRlc3RBcmVuYU1hcC5NYXBCb29sQm9vbEVudHJ5EkkKDm1hcF9pbnQzMl9l",
"bnVtGA4gAygLMjEucHJvdG9idWZfdW5pdHRlc3QuVGVzdEFyZW5hTWFwLk1h",
"cEludDMyRW51bUVudHJ5El4KGW1hcF9pbnQzMl9mb3JlaWduX21lc3NhZ2UY",
"DyADKAsyOy5wcm90b2J1Zl91bml0dGVzdC5UZXN0QXJlbmFNYXAuTWFwSW50",
"MzJGb3JlaWduTWVzc2FnZUVudHJ5GjQKEk1hcEludDMySW50MzJFbnRyeRIL",
"CgNrZXkYASABKAUSDQoFdmFsdWUYAiABKAU6AjgBGjQKEk1hcEludDY0SW50",
"NjRFbnRyeRILCgNrZXkYASABKAMSDQoFdmFsdWUYAiABKAM6AjgBGjYKFE1h",
"cFVpbnQzMlVpbnQzMkVudHJ5EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEo",
"DToCOAEaNgoUTWFwVWludDY0VWludDY0RW50cnkSCwoDa2V5GAEgASgEEg0K",
"BXZhbHVlGAIgASgEOgI4ARo2ChRNYXBTaW50MzJTaW50MzJFbnRyeRILCgNr",
"ZXkYASABKBESDQoFdmFsdWUYAiABKBE6AjgBGjYKFE1hcFNpbnQ2NFNpbnQ2",
"NEVudHJ5EgsKA2tleRgBIAEoEhINCgV2YWx1ZRgCIAEoEjoCOAEaOAoWTWFw",
"Rml4ZWQzMkZpeGVkMzJFbnRyeRILCgNrZXkYASABKAcSDQoFdmFsdWUYAiAB",
"KAc6AjgBGjgKFk1hcEZpeGVkNjRGaXhlZDY0RW50cnkSCwoDa2V5GAEgASgG",
"Eg0KBXZhbHVlGAIgASgGOgI4ARo6ChhNYXBTZml4ZWQzMlNmaXhlZDMyRW50",
"cnkSCwoDa2V5GAEgASgPEg0KBXZhbHVlGAIgASgPOgI4ARo6ChhNYXBTZml4",
"ZWQ2NFNmaXhlZDY0RW50cnkSCwoDa2V5GAEgASgQEg0KBXZhbHVlGAIgASgQ",
"OgI4ARo0ChJNYXBJbnQzMkZsb2F0RW50cnkSCwoDa2V5GAEgASgFEg0KBXZh",
"bHVlGAIgASgCOgI4ARo1ChNNYXBJbnQzMkRvdWJsZUVudHJ5EgsKA2tleRgB",
"IAEoBRINCgV2YWx1ZRgCIAEoAToCOAEaMgoQTWFwQm9vbEJvb2xFbnRyeRIL",
"CgNrZXkYASABKAgSDQoFdmFsdWUYAiABKAg6AjgBGk8KEU1hcEludDMyRW51",
"bUVudHJ5EgsKA2tleRgBIAEoBRIpCgV2YWx1ZRgCIAEoDjIaLnByb3RvYnVm",
"X3VuaXR0ZXN0Lk1hcEVudW06AjgBGmAKG01hcEludDMyRm9yZWlnbk1lc3Nh",
"Z2VFbnRyeRILCgNrZXkYASABKAUSMAoFdmFsdWUYAiABKAsyIS5wcm90b2J1",
"Zl91bml0dGVzdC5Gb3JlaWduTWVzc2FnZToCOAEi5AEKH01lc3NhZ2VDb250",
"YWluaW5nRW51bUNhbGxlZFR5cGUSSgoEdHlwZRgBIAMoCzI8LnByb3RvYnVm",
"X3VuaXR0ZXN0Lk1lc3NhZ2VDb250YWluaW5nRW51bUNhbGxlZFR5cGUuVHlw",
"ZUVudHJ5Gl8KCVR5cGVFbnRyeRILCgNrZXkYASABKAUSQQoFdmFsdWUYAiAB",
"KAsyMi5wcm90b2J1Zl91bml0dGVzdC5NZXNzYWdlQ29udGFpbmluZ0VudW1D",
"YWxsZWRUeXBlOgI4ASIUCgRUeXBlEgwKCFRZUEVfRk9PEAAinQEKH01lc3Nh",
"Z2VDb250YWluaW5nTWFwQ2FsbGVkRW50cnkSTAoFZW50cnkYASADKAsyPS5w",
"cm90b2J1Zl91bml0dGVzdC5NZXNzYWdlQ29udGFpbmluZ01hcENhbGxlZEVu",
"dHJ5LkVudHJ5RW50cnkaLAoKRW50cnlFbnRyeRILCgNrZXkYASABKAUSDQoF",
"dmFsdWUYAiABKAU6AjgBKj8KB01hcEVudW0SEAoMTUFQX0VOVU1fRk9PEAAS",
"EAoMTUFQX0VOVU1fQkFSEAESEAoMTUFQX0VOVU1fQkFaEAJCIPgBAaoCGkdv",
"b2dsZS5Qcm90b2J1Zi5UZXN0UHJvdG9zYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor, },
new pbr::GeneratedCodeInfo(new[] {typeof(global::Google.Protobuf.TestProtos.MapEnum), }, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestMap), global::Google.Protobuf.TestProtos.TestMap.Parser, new[]{ "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapStringString", "MapInt32Bytes", "MapInt32Enum", "MapInt32ForeignMessage" }, null, null, new pbr::GeneratedCodeInfo[] { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestMapSubmessage), global::Google.Protobuf.TestProtos.TestMapSubmessage.Parser, new[]{ "TestMap" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestMessageMap), global::Google.Protobuf.TestProtos.TestMessageMap.Parser, new[]{ "MapInt32Message" }, null, null, new pbr::GeneratedCodeInfo[] { null, }),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestSameTypeMap), global::Google.Protobuf.TestProtos.TestSameTypeMap.Parser, new[]{ "Map1", "Map2" }, null, null, new pbr::GeneratedCodeInfo[] { null, null, }),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestArenaMap), global::Google.Protobuf.TestProtos.TestArenaMap.Parser, new[]{ "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapInt32Enum", "MapInt32ForeignMessage" }, null, null, new pbr::GeneratedCodeInfo[] { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType), global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType.Parser, new[]{ "Type" }, null, new[]{ typeof(global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType.Types.Type) }, new pbr::GeneratedCodeInfo[] { null, }),
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.MessageContainingMapCalledEntry), global::Google.Protobuf.TestProtos.MessageContainingMapCalledEntry.Parser, new[]{ "Entry" }, null, null, new pbr::GeneratedCodeInfo[] { null, })
}));
}
#endregion
}
#region Enums
public enum MapEnum {
MAP_ENUM_FOO = 0,
MAP_ENUM_BAR = 1,
MAP_ENUM_BAZ = 2,
}
#endregion
#region Messages
/// <summary>
/// Tests maps.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestMap : pb::IMessage<TestMap> {
private static readonly pb::MessageParser<TestMap> _parser = new pb::MessageParser<TestMap>(() => new TestMap());
public static pb::MessageParser<TestMap> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public TestMap() {
OnConstruction();
}
partial void OnConstruction();
public TestMap(TestMap other) : this() {
mapInt32Int32_ = other.mapInt32Int32_.Clone();
mapInt64Int64_ = other.mapInt64Int64_.Clone();
mapUint32Uint32_ = other.mapUint32Uint32_.Clone();
mapUint64Uint64_ = other.mapUint64Uint64_.Clone();
mapSint32Sint32_ = other.mapSint32Sint32_.Clone();
mapSint64Sint64_ = other.mapSint64Sint64_.Clone();
mapFixed32Fixed32_ = other.mapFixed32Fixed32_.Clone();
mapFixed64Fixed64_ = other.mapFixed64Fixed64_.Clone();
mapSfixed32Sfixed32_ = other.mapSfixed32Sfixed32_.Clone();
mapSfixed64Sfixed64_ = other.mapSfixed64Sfixed64_.Clone();
mapInt32Float_ = other.mapInt32Float_.Clone();
mapInt32Double_ = other.mapInt32Double_.Clone();
mapBoolBool_ = other.mapBoolBool_.Clone();
mapStringString_ = other.mapStringString_.Clone();
mapInt32Bytes_ = other.mapInt32Bytes_.Clone();
mapInt32Enum_ = other.mapInt32Enum_.Clone();
mapInt32ForeignMessage_ = other.mapInt32ForeignMessage_.Clone();
}
public TestMap Clone() {
return new TestMap(this);
}
/// <summary>Field number for the "map_int32_int32" field.</summary>
public const int MapInt32Int32FieldNumber = 1;
private static readonly pbc::MapField<int, int>.Codec _map_mapInt32Int32_codec
= new pbc::MapField<int, int>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForInt32(16), 10);
private readonly pbc::MapField<int, int> mapInt32Int32_ = new pbc::MapField<int, int>();
public pbc::MapField<int, int> MapInt32Int32 {
get { return mapInt32Int32_; }
}
/// <summary>Field number for the "map_int64_int64" field.</summary>
public const int MapInt64Int64FieldNumber = 2;
private static readonly pbc::MapField<long, long>.Codec _map_mapInt64Int64_codec
= new pbc::MapField<long, long>.Codec(pb::FieldCodec.ForInt64(8), pb::FieldCodec.ForInt64(16), 18);
private readonly pbc::MapField<long, long> mapInt64Int64_ = new pbc::MapField<long, long>();
public pbc::MapField<long, long> MapInt64Int64 {
get { return mapInt64Int64_; }
}
/// <summary>Field number for the "map_uint32_uint32" field.</summary>
public const int MapUint32Uint32FieldNumber = 3;
private static readonly pbc::MapField<uint, uint>.Codec _map_mapUint32Uint32_codec
= new pbc::MapField<uint, uint>.Codec(pb::FieldCodec.ForUInt32(8), pb::FieldCodec.ForUInt32(16), 26);
private readonly pbc::MapField<uint, uint> mapUint32Uint32_ = new pbc::MapField<uint, uint>();
public pbc::MapField<uint, uint> MapUint32Uint32 {
get { return mapUint32Uint32_; }
}
/// <summary>Field number for the "map_uint64_uint64" field.</summary>
public const int MapUint64Uint64FieldNumber = 4;
private static readonly pbc::MapField<ulong, ulong>.Codec _map_mapUint64Uint64_codec
= new pbc::MapField<ulong, ulong>.Codec(pb::FieldCodec.ForUInt64(8), pb::FieldCodec.ForUInt64(16), 34);
private readonly pbc::MapField<ulong, ulong> mapUint64Uint64_ = new pbc::MapField<ulong, ulong>();
public pbc::MapField<ulong, ulong> MapUint64Uint64 {
get { return mapUint64Uint64_; }
}
/// <summary>Field number for the "map_sint32_sint32" field.</summary>
public const int MapSint32Sint32FieldNumber = 5;
private static readonly pbc::MapField<int, int>.Codec _map_mapSint32Sint32_codec
= new pbc::MapField<int, int>.Codec(pb::FieldCodec.ForSInt32(8), pb::FieldCodec.ForSInt32(16), 42);
private readonly pbc::MapField<int, int> mapSint32Sint32_ = new pbc::MapField<int, int>();
public pbc::MapField<int, int> MapSint32Sint32 {
get { return mapSint32Sint32_; }
}
/// <summary>Field number for the "map_sint64_sint64" field.</summary>
public const int MapSint64Sint64FieldNumber = 6;
private static readonly pbc::MapField<long, long>.Codec _map_mapSint64Sint64_codec
= new pbc::MapField<long, long>.Codec(pb::FieldCodec.ForSInt64(8), pb::FieldCodec.ForSInt64(16), 50);
private readonly pbc::MapField<long, long> mapSint64Sint64_ = new pbc::MapField<long, long>();
public pbc::MapField<long, long> MapSint64Sint64 {
get { return mapSint64Sint64_; }
}
/// <summary>Field number for the "map_fixed32_fixed32" field.</summary>
public const int MapFixed32Fixed32FieldNumber = 7;
private static readonly pbc::MapField<uint, uint>.Codec _map_mapFixed32Fixed32_codec
= new pbc::MapField<uint, uint>.Codec(pb::FieldCodec.ForFixed32(13), pb::FieldCodec.ForFixed32(21), 58);
private readonly pbc::MapField<uint, uint> mapFixed32Fixed32_ = new pbc::MapField<uint, uint>();
public pbc::MapField<uint, uint> MapFixed32Fixed32 {
get { return mapFixed32Fixed32_; }
}
/// <summary>Field number for the "map_fixed64_fixed64" field.</summary>
public const int MapFixed64Fixed64FieldNumber = 8;
private static readonly pbc::MapField<ulong, ulong>.Codec _map_mapFixed64Fixed64_codec
= new pbc::MapField<ulong, ulong>.Codec(pb::FieldCodec.ForFixed64(9), pb::FieldCodec.ForFixed64(17), 66);
private readonly pbc::MapField<ulong, ulong> mapFixed64Fixed64_ = new pbc::MapField<ulong, ulong>();
public pbc::MapField<ulong, ulong> MapFixed64Fixed64 {
get { return mapFixed64Fixed64_; }
}
/// <summary>Field number for the "map_sfixed32_sfixed32" field.</summary>
public const int MapSfixed32Sfixed32FieldNumber = 9;
private static readonly pbc::MapField<int, int>.Codec _map_mapSfixed32Sfixed32_codec
= new pbc::MapField<int, int>.Codec(pb::FieldCodec.ForSFixed32(13), pb::FieldCodec.ForSFixed32(21), 74);
private readonly pbc::MapField<int, int> mapSfixed32Sfixed32_ = new pbc::MapField<int, int>();
public pbc::MapField<int, int> MapSfixed32Sfixed32 {
get { return mapSfixed32Sfixed32_; }
}
/// <summary>Field number for the "map_sfixed64_sfixed64" field.</summary>
public const int MapSfixed64Sfixed64FieldNumber = 10;
private static readonly pbc::MapField<long, long>.Codec _map_mapSfixed64Sfixed64_codec
= new pbc::MapField<long, long>.Codec(pb::FieldCodec.ForSFixed64(9), pb::FieldCodec.ForSFixed64(17), 82);
private readonly pbc::MapField<long, long> mapSfixed64Sfixed64_ = new pbc::MapField<long, long>();
public pbc::MapField<long, long> MapSfixed64Sfixed64 {
get { return mapSfixed64Sfixed64_; }
}
/// <summary>Field number for the "map_int32_float" field.</summary>
public const int MapInt32FloatFieldNumber = 11;
private static readonly pbc::MapField<int, float>.Codec _map_mapInt32Float_codec
= new pbc::MapField<int, float>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForFloat(21), 90);
private readonly pbc::MapField<int, float> mapInt32Float_ = new pbc::MapField<int, float>();
public pbc::MapField<int, float> MapInt32Float {
get { return mapInt32Float_; }
}
/// <summary>Field number for the "map_int32_double" field.</summary>
public const int MapInt32DoubleFieldNumber = 12;
private static readonly pbc::MapField<int, double>.Codec _map_mapInt32Double_codec
= new pbc::MapField<int, double>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForDouble(17), 98);
private readonly pbc::MapField<int, double> mapInt32Double_ = new pbc::MapField<int, double>();
public pbc::MapField<int, double> MapInt32Double {
get { return mapInt32Double_; }
}
/// <summary>Field number for the "map_bool_bool" field.</summary>
public const int MapBoolBoolFieldNumber = 13;
private static readonly pbc::MapField<bool, bool>.Codec _map_mapBoolBool_codec
= new pbc::MapField<bool, bool>.Codec(pb::FieldCodec.ForBool(8), pb::FieldCodec.ForBool(16), 106);
private readonly pbc::MapField<bool, bool> mapBoolBool_ = new pbc::MapField<bool, bool>();
public pbc::MapField<bool, bool> MapBoolBool {
get { return mapBoolBool_; }
}
/// <summary>Field number for the "map_string_string" field.</summary>
public const int MapStringStringFieldNumber = 14;
private static readonly pbc::MapField<string, string>.Codec _map_mapStringString_codec
= new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForString(18), 114);
private readonly pbc::MapField<string, string> mapStringString_ = new pbc::MapField<string, string>();
public pbc::MapField<string, string> MapStringString {
get { return mapStringString_; }
}
/// <summary>Field number for the "map_int32_bytes" field.</summary>
public const int MapInt32BytesFieldNumber = 15;
private static readonly pbc::MapField<int, pb::ByteString>.Codec _map_mapInt32Bytes_codec
= new pbc::MapField<int, pb::ByteString>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForBytes(18), 122);
private readonly pbc::MapField<int, pb::ByteString> mapInt32Bytes_ = new pbc::MapField<int, pb::ByteString>();
public pbc::MapField<int, pb::ByteString> MapInt32Bytes {
get { return mapInt32Bytes_; }
}
/// <summary>Field number for the "map_int32_enum" field.</summary>
public const int MapInt32EnumFieldNumber = 16;
private static readonly pbc::MapField<int, global::Google.Protobuf.TestProtos.MapEnum>.Codec _map_mapInt32Enum_codec
= new pbc::MapField<int, global::Google.Protobuf.TestProtos.MapEnum>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForEnum(16, x => (int) x, x => (global::Google.Protobuf.TestProtos.MapEnum) x), 130);
private readonly pbc::MapField<int, global::Google.Protobuf.TestProtos.MapEnum> mapInt32Enum_ = new pbc::MapField<int, global::Google.Protobuf.TestProtos.MapEnum>();
public pbc::MapField<int, global::Google.Protobuf.TestProtos.MapEnum> MapInt32Enum {
get { return mapInt32Enum_; }
}
/// <summary>Field number for the "map_int32_foreign_message" field.</summary>
public const int MapInt32ForeignMessageFieldNumber = 17;
private static readonly pbc::MapField<int, global::Google.Protobuf.TestProtos.ForeignMessage>.Codec _map_mapInt32ForeignMessage_codec
= new pbc::MapField<int, global::Google.Protobuf.TestProtos.ForeignMessage>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.ForeignMessage.Parser), 138);
private readonly pbc::MapField<int, global::Google.Protobuf.TestProtos.ForeignMessage> mapInt32ForeignMessage_ = new pbc::MapField<int, global::Google.Protobuf.TestProtos.ForeignMessage>();
public pbc::MapField<int, global::Google.Protobuf.TestProtos.ForeignMessage> MapInt32ForeignMessage {
get { return mapInt32ForeignMessage_; }
}
public override bool Equals(object other) {
return Equals(other as TestMap);
}
public bool Equals(TestMap other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!MapInt32Int32.Equals(other.MapInt32Int32)) return false;
if (!MapInt64Int64.Equals(other.MapInt64Int64)) return false;
if (!MapUint32Uint32.Equals(other.MapUint32Uint32)) return false;
if (!MapUint64Uint64.Equals(other.MapUint64Uint64)) return false;
if (!MapSint32Sint32.Equals(other.MapSint32Sint32)) return false;
if (!MapSint64Sint64.Equals(other.MapSint64Sint64)) return false;
if (!MapFixed32Fixed32.Equals(other.MapFixed32Fixed32)) return false;
if (!MapFixed64Fixed64.Equals(other.MapFixed64Fixed64)) return false;
if (!MapSfixed32Sfixed32.Equals(other.MapSfixed32Sfixed32)) return false;
if (!MapSfixed64Sfixed64.Equals(other.MapSfixed64Sfixed64)) return false;
if (!MapInt32Float.Equals(other.MapInt32Float)) return false;
if (!MapInt32Double.Equals(other.MapInt32Double)) return false;
if (!MapBoolBool.Equals(other.MapBoolBool)) return false;
if (!MapStringString.Equals(other.MapStringString)) return false;
if (!MapInt32Bytes.Equals(other.MapInt32Bytes)) return false;
if (!MapInt32Enum.Equals(other.MapInt32Enum)) return false;
if (!MapInt32ForeignMessage.Equals(other.MapInt32ForeignMessage)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= MapInt32Int32.GetHashCode();
hash ^= MapInt64Int64.GetHashCode();
hash ^= MapUint32Uint32.GetHashCode();
hash ^= MapUint64Uint64.GetHashCode();
hash ^= MapSint32Sint32.GetHashCode();
hash ^= MapSint64Sint64.GetHashCode();
hash ^= MapFixed32Fixed32.GetHashCode();
hash ^= MapFixed64Fixed64.GetHashCode();
hash ^= MapSfixed32Sfixed32.GetHashCode();
hash ^= MapSfixed64Sfixed64.GetHashCode();
hash ^= MapInt32Float.GetHashCode();
hash ^= MapInt32Double.GetHashCode();
hash ^= MapBoolBool.GetHashCode();
hash ^= MapStringString.GetHashCode();
hash ^= MapInt32Bytes.GetHashCode();
hash ^= MapInt32Enum.GetHashCode();
hash ^= MapInt32ForeignMessage.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
mapInt32Int32_.WriteTo(output, _map_mapInt32Int32_codec);
mapInt64Int64_.WriteTo(output, _map_mapInt64Int64_codec);
mapUint32Uint32_.WriteTo(output, _map_mapUint32Uint32_codec);
mapUint64Uint64_.WriteTo(output, _map_mapUint64Uint64_codec);
mapSint32Sint32_.WriteTo(output, _map_mapSint32Sint32_codec);
mapSint64Sint64_.WriteTo(output, _map_mapSint64Sint64_codec);
mapFixed32Fixed32_.WriteTo(output, _map_mapFixed32Fixed32_codec);
mapFixed64Fixed64_.WriteTo(output, _map_mapFixed64Fixed64_codec);
mapSfixed32Sfixed32_.WriteTo(output, _map_mapSfixed32Sfixed32_codec);
mapSfixed64Sfixed64_.WriteTo(output, _map_mapSfixed64Sfixed64_codec);
mapInt32Float_.WriteTo(output, _map_mapInt32Float_codec);
mapInt32Double_.WriteTo(output, _map_mapInt32Double_codec);
mapBoolBool_.WriteTo(output, _map_mapBoolBool_codec);
mapStringString_.WriteTo(output, _map_mapStringString_codec);
mapInt32Bytes_.WriteTo(output, _map_mapInt32Bytes_codec);
mapInt32Enum_.WriteTo(output, _map_mapInt32Enum_codec);
mapInt32ForeignMessage_.WriteTo(output, _map_mapInt32ForeignMessage_codec);
}
public int CalculateSize() {
int size = 0;
size += mapInt32Int32_.CalculateSize(_map_mapInt32Int32_codec);
size += mapInt64Int64_.CalculateSize(_map_mapInt64Int64_codec);
size += mapUint32Uint32_.CalculateSize(_map_mapUint32Uint32_codec);
size += mapUint64Uint64_.CalculateSize(_map_mapUint64Uint64_codec);
size += mapSint32Sint32_.CalculateSize(_map_mapSint32Sint32_codec);
size += mapSint64Sint64_.CalculateSize(_map_mapSint64Sint64_codec);
size += mapFixed32Fixed32_.CalculateSize(_map_mapFixed32Fixed32_codec);
size += mapFixed64Fixed64_.CalculateSize(_map_mapFixed64Fixed64_codec);
size += mapSfixed32Sfixed32_.CalculateSize(_map_mapSfixed32Sfixed32_codec);
size += mapSfixed64Sfixed64_.CalculateSize(_map_mapSfixed64Sfixed64_codec);
size += mapInt32Float_.CalculateSize(_map_mapInt32Float_codec);
size += mapInt32Double_.CalculateSize(_map_mapInt32Double_codec);
size += mapBoolBool_.CalculateSize(_map_mapBoolBool_codec);
size += mapStringString_.CalculateSize(_map_mapStringString_codec);
size += mapInt32Bytes_.CalculateSize(_map_mapInt32Bytes_codec);
size += mapInt32Enum_.CalculateSize(_map_mapInt32Enum_codec);
size += mapInt32ForeignMessage_.CalculateSize(_map_mapInt32ForeignMessage_codec);
return size;
}
public void MergeFrom(TestMap other) {
if (other == null) {
return;
}
mapInt32Int32_.Add(other.mapInt32Int32_);
mapInt64Int64_.Add(other.mapInt64Int64_);
mapUint32Uint32_.Add(other.mapUint32Uint32_);
mapUint64Uint64_.Add(other.mapUint64Uint64_);
mapSint32Sint32_.Add(other.mapSint32Sint32_);
mapSint64Sint64_.Add(other.mapSint64Sint64_);
mapFixed32Fixed32_.Add(other.mapFixed32Fixed32_);
mapFixed64Fixed64_.Add(other.mapFixed64Fixed64_);
mapSfixed32Sfixed32_.Add(other.mapSfixed32Sfixed32_);
mapSfixed64Sfixed64_.Add(other.mapSfixed64Sfixed64_);
mapInt32Float_.Add(other.mapInt32Float_);
mapInt32Double_.Add(other.mapInt32Double_);
mapBoolBool_.Add(other.mapBoolBool_);
mapStringString_.Add(other.mapStringString_);
mapInt32Bytes_.Add(other.mapInt32Bytes_);
mapInt32Enum_.Add(other.mapInt32Enum_);
mapInt32ForeignMessage_.Add(other.mapInt32ForeignMessage_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
mapInt32Int32_.AddEntriesFrom(input, _map_mapInt32Int32_codec);
break;
}
case 18: {
mapInt64Int64_.AddEntriesFrom(input, _map_mapInt64Int64_codec);
break;
}
case 26: {
mapUint32Uint32_.AddEntriesFrom(input, _map_mapUint32Uint32_codec);
break;
}
case 34: {
mapUint64Uint64_.AddEntriesFrom(input, _map_mapUint64Uint64_codec);
break;
}
case 42: {
mapSint32Sint32_.AddEntriesFrom(input, _map_mapSint32Sint32_codec);
break;
}
case 50: {
mapSint64Sint64_.AddEntriesFrom(input, _map_mapSint64Sint64_codec);
break;
}
case 58: {
mapFixed32Fixed32_.AddEntriesFrom(input, _map_mapFixed32Fixed32_codec);
break;
}
case 66: {
mapFixed64Fixed64_.AddEntriesFrom(input, _map_mapFixed64Fixed64_codec);
break;
}
case 74: {
mapSfixed32Sfixed32_.AddEntriesFrom(input, _map_mapSfixed32Sfixed32_codec);
break;
}
case 82: {
mapSfixed64Sfixed64_.AddEntriesFrom(input, _map_mapSfixed64Sfixed64_codec);
break;
}
case 90: {
mapInt32Float_.AddEntriesFrom(input, _map_mapInt32Float_codec);
break;
}
case 98: {
mapInt32Double_.AddEntriesFrom(input, _map_mapInt32Double_codec);
break;
}
case 106: {
mapBoolBool_.AddEntriesFrom(input, _map_mapBoolBool_codec);
break;
}
case 114: {
mapStringString_.AddEntriesFrom(input, _map_mapStringString_codec);
break;
}
case 122: {
mapInt32Bytes_.AddEntriesFrom(input, _map_mapInt32Bytes_codec);
break;
}
case 130: {
mapInt32Enum_.AddEntriesFrom(input, _map_mapInt32Enum_codec);
break;
}
case 138: {
mapInt32ForeignMessage_.AddEntriesFrom(input, _map_mapInt32ForeignMessage_codec);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestMapSubmessage : pb::IMessage<TestMapSubmessage> {
private static readonly pb::MessageParser<TestMapSubmessage> _parser = new pb::MessageParser<TestMapSubmessage>(() => new TestMapSubmessage());
public static pb::MessageParser<TestMapSubmessage> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public TestMapSubmessage() {
OnConstruction();
}
partial void OnConstruction();
public TestMapSubmessage(TestMapSubmessage other) : this() {
TestMap = other.testMap_ != null ? other.TestMap.Clone() : null;
}
public TestMapSubmessage Clone() {
return new TestMapSubmessage(this);
}
/// <summary>Field number for the "test_map" field.</summary>
public const int TestMapFieldNumber = 1;
private global::Google.Protobuf.TestProtos.TestMap testMap_;
public global::Google.Protobuf.TestProtos.TestMap TestMap {
get { return testMap_; }
set {
testMap_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as TestMapSubmessage);
}
public bool Equals(TestMapSubmessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(TestMap, other.TestMap)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (testMap_ != null) hash ^= TestMap.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (testMap_ != null) {
output.WriteRawTag(10);
output.WriteMessage(TestMap);
}
}
public int CalculateSize() {
int size = 0;
if (testMap_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(TestMap);
}
return size;
}
public void MergeFrom(TestMapSubmessage other) {
if (other == null) {
return;
}
if (other.testMap_ != null) {
if (testMap_ == null) {
testMap_ = new global::Google.Protobuf.TestProtos.TestMap();
}
TestMap.MergeFrom(other.TestMap);
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (testMap_ == null) {
testMap_ = new global::Google.Protobuf.TestProtos.TestMap();
}
input.ReadMessage(testMap_);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestMessageMap : pb::IMessage<TestMessageMap> {
private static readonly pb::MessageParser<TestMessageMap> _parser = new pb::MessageParser<TestMessageMap>(() => new TestMessageMap());
public static pb::MessageParser<TestMessageMap> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[2]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public TestMessageMap() {
OnConstruction();
}
partial void OnConstruction();
public TestMessageMap(TestMessageMap other) : this() {
mapInt32Message_ = other.mapInt32Message_.Clone();
}
public TestMessageMap Clone() {
return new TestMessageMap(this);
}
/// <summary>Field number for the "map_int32_message" field.</summary>
public const int MapInt32MessageFieldNumber = 1;
private static readonly pbc::MapField<int, global::Google.Protobuf.TestProtos.TestAllTypes>.Codec _map_mapInt32Message_codec
= new pbc::MapField<int, global::Google.Protobuf.TestProtos.TestAllTypes>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.TestAllTypes.Parser), 10);
private readonly pbc::MapField<int, global::Google.Protobuf.TestProtos.TestAllTypes> mapInt32Message_ = new pbc::MapField<int, global::Google.Protobuf.TestProtos.TestAllTypes>();
public pbc::MapField<int, global::Google.Protobuf.TestProtos.TestAllTypes> MapInt32Message {
get { return mapInt32Message_; }
}
public override bool Equals(object other) {
return Equals(other as TestMessageMap);
}
public bool Equals(TestMessageMap other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!MapInt32Message.Equals(other.MapInt32Message)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= MapInt32Message.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
mapInt32Message_.WriteTo(output, _map_mapInt32Message_codec);
}
public int CalculateSize() {
int size = 0;
size += mapInt32Message_.CalculateSize(_map_mapInt32Message_codec);
return size;
}
public void MergeFrom(TestMessageMap other) {
if (other == null) {
return;
}
mapInt32Message_.Add(other.mapInt32Message_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
mapInt32Message_.AddEntriesFrom(input, _map_mapInt32Message_codec);
break;
}
}
}
}
}
/// <summary>
/// Two map fields share the same entry default instance.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestSameTypeMap : pb::IMessage<TestSameTypeMap> {
private static readonly pb::MessageParser<TestSameTypeMap> _parser = new pb::MessageParser<TestSameTypeMap>(() => new TestSameTypeMap());
public static pb::MessageParser<TestSameTypeMap> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[3]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public TestSameTypeMap() {
OnConstruction();
}
partial void OnConstruction();
public TestSameTypeMap(TestSameTypeMap other) : this() {
map1_ = other.map1_.Clone();
map2_ = other.map2_.Clone();
}
public TestSameTypeMap Clone() {
return new TestSameTypeMap(this);
}
/// <summary>Field number for the "map1" field.</summary>
public const int Map1FieldNumber = 1;
private static readonly pbc::MapField<int, int>.Codec _map_map1_codec
= new pbc::MapField<int, int>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForInt32(16), 10);
private readonly pbc::MapField<int, int> map1_ = new pbc::MapField<int, int>();
public pbc::MapField<int, int> Map1 {
get { return map1_; }
}
/// <summary>Field number for the "map2" field.</summary>
public const int Map2FieldNumber = 2;
private static readonly pbc::MapField<int, int>.Codec _map_map2_codec
= new pbc::MapField<int, int>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForInt32(16), 18);
private readonly pbc::MapField<int, int> map2_ = new pbc::MapField<int, int>();
public pbc::MapField<int, int> Map2 {
get { return map2_; }
}
public override bool Equals(object other) {
return Equals(other as TestSameTypeMap);
}
public bool Equals(TestSameTypeMap other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!Map1.Equals(other.Map1)) return false;
if (!Map2.Equals(other.Map2)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= Map1.GetHashCode();
hash ^= Map2.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
map1_.WriteTo(output, _map_map1_codec);
map2_.WriteTo(output, _map_map2_codec);
}
public int CalculateSize() {
int size = 0;
size += map1_.CalculateSize(_map_map1_codec);
size += map2_.CalculateSize(_map_map2_codec);
return size;
}
public void MergeFrom(TestSameTypeMap other) {
if (other == null) {
return;
}
map1_.Add(other.map1_);
map2_.Add(other.map2_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
map1_.AddEntriesFrom(input, _map_map1_codec);
break;
}
case 18: {
map2_.AddEntriesFrom(input, _map_map2_codec);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestArenaMap : pb::IMessage<TestArenaMap> {
private static readonly pb::MessageParser<TestArenaMap> _parser = new pb::MessageParser<TestArenaMap>(() => new TestArenaMap());
public static pb::MessageParser<TestArenaMap> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[4]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public TestArenaMap() {
OnConstruction();
}
partial void OnConstruction();
public TestArenaMap(TestArenaMap other) : this() {
mapInt32Int32_ = other.mapInt32Int32_.Clone();
mapInt64Int64_ = other.mapInt64Int64_.Clone();
mapUint32Uint32_ = other.mapUint32Uint32_.Clone();
mapUint64Uint64_ = other.mapUint64Uint64_.Clone();
mapSint32Sint32_ = other.mapSint32Sint32_.Clone();
mapSint64Sint64_ = other.mapSint64Sint64_.Clone();
mapFixed32Fixed32_ = other.mapFixed32Fixed32_.Clone();
mapFixed64Fixed64_ = other.mapFixed64Fixed64_.Clone();
mapSfixed32Sfixed32_ = other.mapSfixed32Sfixed32_.Clone();
mapSfixed64Sfixed64_ = other.mapSfixed64Sfixed64_.Clone();
mapInt32Float_ = other.mapInt32Float_.Clone();
mapInt32Double_ = other.mapInt32Double_.Clone();
mapBoolBool_ = other.mapBoolBool_.Clone();
mapInt32Enum_ = other.mapInt32Enum_.Clone();
mapInt32ForeignMessage_ = other.mapInt32ForeignMessage_.Clone();
}
public TestArenaMap Clone() {
return new TestArenaMap(this);
}
/// <summary>Field number for the "map_int32_int32" field.</summary>
public const int MapInt32Int32FieldNumber = 1;
private static readonly pbc::MapField<int, int>.Codec _map_mapInt32Int32_codec
= new pbc::MapField<int, int>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForInt32(16), 10);
private readonly pbc::MapField<int, int> mapInt32Int32_ = new pbc::MapField<int, int>();
public pbc::MapField<int, int> MapInt32Int32 {
get { return mapInt32Int32_; }
}
/// <summary>Field number for the "map_int64_int64" field.</summary>
public const int MapInt64Int64FieldNumber = 2;
private static readonly pbc::MapField<long, long>.Codec _map_mapInt64Int64_codec
= new pbc::MapField<long, long>.Codec(pb::FieldCodec.ForInt64(8), pb::FieldCodec.ForInt64(16), 18);
private readonly pbc::MapField<long, long> mapInt64Int64_ = new pbc::MapField<long, long>();
public pbc::MapField<long, long> MapInt64Int64 {
get { return mapInt64Int64_; }
}
/// <summary>Field number for the "map_uint32_uint32" field.</summary>
public const int MapUint32Uint32FieldNumber = 3;
private static readonly pbc::MapField<uint, uint>.Codec _map_mapUint32Uint32_codec
= new pbc::MapField<uint, uint>.Codec(pb::FieldCodec.ForUInt32(8), pb::FieldCodec.ForUInt32(16), 26);
private readonly pbc::MapField<uint, uint> mapUint32Uint32_ = new pbc::MapField<uint, uint>();
public pbc::MapField<uint, uint> MapUint32Uint32 {
get { return mapUint32Uint32_; }
}
/// <summary>Field number for the "map_uint64_uint64" field.</summary>
public const int MapUint64Uint64FieldNumber = 4;
private static readonly pbc::MapField<ulong, ulong>.Codec _map_mapUint64Uint64_codec
= new pbc::MapField<ulong, ulong>.Codec(pb::FieldCodec.ForUInt64(8), pb::FieldCodec.ForUInt64(16), 34);
private readonly pbc::MapField<ulong, ulong> mapUint64Uint64_ = new pbc::MapField<ulong, ulong>();
public pbc::MapField<ulong, ulong> MapUint64Uint64 {
get { return mapUint64Uint64_; }
}
/// <summary>Field number for the "map_sint32_sint32" field.</summary>
public const int MapSint32Sint32FieldNumber = 5;
private static readonly pbc::MapField<int, int>.Codec _map_mapSint32Sint32_codec
= new pbc::MapField<int, int>.Codec(pb::FieldCodec.ForSInt32(8), pb::FieldCodec.ForSInt32(16), 42);
private readonly pbc::MapField<int, int> mapSint32Sint32_ = new pbc::MapField<int, int>();
public pbc::MapField<int, int> MapSint32Sint32 {
get { return mapSint32Sint32_; }
}
/// <summary>Field number for the "map_sint64_sint64" field.</summary>
public const int MapSint64Sint64FieldNumber = 6;
private static readonly pbc::MapField<long, long>.Codec _map_mapSint64Sint64_codec
= new pbc::MapField<long, long>.Codec(pb::FieldCodec.ForSInt64(8), pb::FieldCodec.ForSInt64(16), 50);
private readonly pbc::MapField<long, long> mapSint64Sint64_ = new pbc::MapField<long, long>();
public pbc::MapField<long, long> MapSint64Sint64 {
get { return mapSint64Sint64_; }
}
/// <summary>Field number for the "map_fixed32_fixed32" field.</summary>
public const int MapFixed32Fixed32FieldNumber = 7;
private static readonly pbc::MapField<uint, uint>.Codec _map_mapFixed32Fixed32_codec
= new pbc::MapField<uint, uint>.Codec(pb::FieldCodec.ForFixed32(13), pb::FieldCodec.ForFixed32(21), 58);
private readonly pbc::MapField<uint, uint> mapFixed32Fixed32_ = new pbc::MapField<uint, uint>();
public pbc::MapField<uint, uint> MapFixed32Fixed32 {
get { return mapFixed32Fixed32_; }
}
/// <summary>Field number for the "map_fixed64_fixed64" field.</summary>
public const int MapFixed64Fixed64FieldNumber = 8;
private static readonly pbc::MapField<ulong, ulong>.Codec _map_mapFixed64Fixed64_codec
= new pbc::MapField<ulong, ulong>.Codec(pb::FieldCodec.ForFixed64(9), pb::FieldCodec.ForFixed64(17), 66);
private readonly pbc::MapField<ulong, ulong> mapFixed64Fixed64_ = new pbc::MapField<ulong, ulong>();
public pbc::MapField<ulong, ulong> MapFixed64Fixed64 {
get { return mapFixed64Fixed64_; }
}
/// <summary>Field number for the "map_sfixed32_sfixed32" field.</summary>
public const int MapSfixed32Sfixed32FieldNumber = 9;
private static readonly pbc::MapField<int, int>.Codec _map_mapSfixed32Sfixed32_codec
= new pbc::MapField<int, int>.Codec(pb::FieldCodec.ForSFixed32(13), pb::FieldCodec.ForSFixed32(21), 74);
private readonly pbc::MapField<int, int> mapSfixed32Sfixed32_ = new pbc::MapField<int, int>();
public pbc::MapField<int, int> MapSfixed32Sfixed32 {
get { return mapSfixed32Sfixed32_; }
}
/// <summary>Field number for the "map_sfixed64_sfixed64" field.</summary>
public const int MapSfixed64Sfixed64FieldNumber = 10;
private static readonly pbc::MapField<long, long>.Codec _map_mapSfixed64Sfixed64_codec
= new pbc::MapField<long, long>.Codec(pb::FieldCodec.ForSFixed64(9), pb::FieldCodec.ForSFixed64(17), 82);
private readonly pbc::MapField<long, long> mapSfixed64Sfixed64_ = new pbc::MapField<long, long>();
public pbc::MapField<long, long> MapSfixed64Sfixed64 {
get { return mapSfixed64Sfixed64_; }
}
/// <summary>Field number for the "map_int32_float" field.</summary>
public const int MapInt32FloatFieldNumber = 11;
private static readonly pbc::MapField<int, float>.Codec _map_mapInt32Float_codec
= new pbc::MapField<int, float>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForFloat(21), 90);
private readonly pbc::MapField<int, float> mapInt32Float_ = new pbc::MapField<int, float>();
public pbc::MapField<int, float> MapInt32Float {
get { return mapInt32Float_; }
}
/// <summary>Field number for the "map_int32_double" field.</summary>
public const int MapInt32DoubleFieldNumber = 12;
private static readonly pbc::MapField<int, double>.Codec _map_mapInt32Double_codec
= new pbc::MapField<int, double>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForDouble(17), 98);
private readonly pbc::MapField<int, double> mapInt32Double_ = new pbc::MapField<int, double>();
public pbc::MapField<int, double> MapInt32Double {
get { return mapInt32Double_; }
}
/// <summary>Field number for the "map_bool_bool" field.</summary>
public const int MapBoolBoolFieldNumber = 13;
private static readonly pbc::MapField<bool, bool>.Codec _map_mapBoolBool_codec
= new pbc::MapField<bool, bool>.Codec(pb::FieldCodec.ForBool(8), pb::FieldCodec.ForBool(16), 106);
private readonly pbc::MapField<bool, bool> mapBoolBool_ = new pbc::MapField<bool, bool>();
public pbc::MapField<bool, bool> MapBoolBool {
get { return mapBoolBool_; }
}
/// <summary>Field number for the "map_int32_enum" field.</summary>
public const int MapInt32EnumFieldNumber = 14;
private static readonly pbc::MapField<int, global::Google.Protobuf.TestProtos.MapEnum>.Codec _map_mapInt32Enum_codec
= new pbc::MapField<int, global::Google.Protobuf.TestProtos.MapEnum>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForEnum(16, x => (int) x, x => (global::Google.Protobuf.TestProtos.MapEnum) x), 114);
private readonly pbc::MapField<int, global::Google.Protobuf.TestProtos.MapEnum> mapInt32Enum_ = new pbc::MapField<int, global::Google.Protobuf.TestProtos.MapEnum>();
public pbc::MapField<int, global::Google.Protobuf.TestProtos.MapEnum> MapInt32Enum {
get { return mapInt32Enum_; }
}
/// <summary>Field number for the "map_int32_foreign_message" field.</summary>
public const int MapInt32ForeignMessageFieldNumber = 15;
private static readonly pbc::MapField<int, global::Google.Protobuf.TestProtos.ForeignMessage>.Codec _map_mapInt32ForeignMessage_codec
= new pbc::MapField<int, global::Google.Protobuf.TestProtos.ForeignMessage>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.ForeignMessage.Parser), 122);
private readonly pbc::MapField<int, global::Google.Protobuf.TestProtos.ForeignMessage> mapInt32ForeignMessage_ = new pbc::MapField<int, global::Google.Protobuf.TestProtos.ForeignMessage>();
public pbc::MapField<int, global::Google.Protobuf.TestProtos.ForeignMessage> MapInt32ForeignMessage {
get { return mapInt32ForeignMessage_; }
}
public override bool Equals(object other) {
return Equals(other as TestArenaMap);
}
public bool Equals(TestArenaMap other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!MapInt32Int32.Equals(other.MapInt32Int32)) return false;
if (!MapInt64Int64.Equals(other.MapInt64Int64)) return false;
if (!MapUint32Uint32.Equals(other.MapUint32Uint32)) return false;
if (!MapUint64Uint64.Equals(other.MapUint64Uint64)) return false;
if (!MapSint32Sint32.Equals(other.MapSint32Sint32)) return false;
if (!MapSint64Sint64.Equals(other.MapSint64Sint64)) return false;
if (!MapFixed32Fixed32.Equals(other.MapFixed32Fixed32)) return false;
if (!MapFixed64Fixed64.Equals(other.MapFixed64Fixed64)) return false;
if (!MapSfixed32Sfixed32.Equals(other.MapSfixed32Sfixed32)) return false;
if (!MapSfixed64Sfixed64.Equals(other.MapSfixed64Sfixed64)) return false;
if (!MapInt32Float.Equals(other.MapInt32Float)) return false;
if (!MapInt32Double.Equals(other.MapInt32Double)) return false;
if (!MapBoolBool.Equals(other.MapBoolBool)) return false;
if (!MapInt32Enum.Equals(other.MapInt32Enum)) return false;
if (!MapInt32ForeignMessage.Equals(other.MapInt32ForeignMessage)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= MapInt32Int32.GetHashCode();
hash ^= MapInt64Int64.GetHashCode();
hash ^= MapUint32Uint32.GetHashCode();
hash ^= MapUint64Uint64.GetHashCode();
hash ^= MapSint32Sint32.GetHashCode();
hash ^= MapSint64Sint64.GetHashCode();
hash ^= MapFixed32Fixed32.GetHashCode();
hash ^= MapFixed64Fixed64.GetHashCode();
hash ^= MapSfixed32Sfixed32.GetHashCode();
hash ^= MapSfixed64Sfixed64.GetHashCode();
hash ^= MapInt32Float.GetHashCode();
hash ^= MapInt32Double.GetHashCode();
hash ^= MapBoolBool.GetHashCode();
hash ^= MapInt32Enum.GetHashCode();
hash ^= MapInt32ForeignMessage.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
mapInt32Int32_.WriteTo(output, _map_mapInt32Int32_codec);
mapInt64Int64_.WriteTo(output, _map_mapInt64Int64_codec);
mapUint32Uint32_.WriteTo(output, _map_mapUint32Uint32_codec);
mapUint64Uint64_.WriteTo(output, _map_mapUint64Uint64_codec);
mapSint32Sint32_.WriteTo(output, _map_mapSint32Sint32_codec);
mapSint64Sint64_.WriteTo(output, _map_mapSint64Sint64_codec);
mapFixed32Fixed32_.WriteTo(output, _map_mapFixed32Fixed32_codec);
mapFixed64Fixed64_.WriteTo(output, _map_mapFixed64Fixed64_codec);
mapSfixed32Sfixed32_.WriteTo(output, _map_mapSfixed32Sfixed32_codec);
mapSfixed64Sfixed64_.WriteTo(output, _map_mapSfixed64Sfixed64_codec);
mapInt32Float_.WriteTo(output, _map_mapInt32Float_codec);
mapInt32Double_.WriteTo(output, _map_mapInt32Double_codec);
mapBoolBool_.WriteTo(output, _map_mapBoolBool_codec);
mapInt32Enum_.WriteTo(output, _map_mapInt32Enum_codec);
mapInt32ForeignMessage_.WriteTo(output, _map_mapInt32ForeignMessage_codec);
}
public int CalculateSize() {
int size = 0;
size += mapInt32Int32_.CalculateSize(_map_mapInt32Int32_codec);
size += mapInt64Int64_.CalculateSize(_map_mapInt64Int64_codec);
size += mapUint32Uint32_.CalculateSize(_map_mapUint32Uint32_codec);
size += mapUint64Uint64_.CalculateSize(_map_mapUint64Uint64_codec);
size += mapSint32Sint32_.CalculateSize(_map_mapSint32Sint32_codec);
size += mapSint64Sint64_.CalculateSize(_map_mapSint64Sint64_codec);
size += mapFixed32Fixed32_.CalculateSize(_map_mapFixed32Fixed32_codec);
size += mapFixed64Fixed64_.CalculateSize(_map_mapFixed64Fixed64_codec);
size += mapSfixed32Sfixed32_.CalculateSize(_map_mapSfixed32Sfixed32_codec);
size += mapSfixed64Sfixed64_.CalculateSize(_map_mapSfixed64Sfixed64_codec);
size += mapInt32Float_.CalculateSize(_map_mapInt32Float_codec);
size += mapInt32Double_.CalculateSize(_map_mapInt32Double_codec);
size += mapBoolBool_.CalculateSize(_map_mapBoolBool_codec);
size += mapInt32Enum_.CalculateSize(_map_mapInt32Enum_codec);
size += mapInt32ForeignMessage_.CalculateSize(_map_mapInt32ForeignMessage_codec);
return size;
}
public void MergeFrom(TestArenaMap other) {
if (other == null) {
return;
}
mapInt32Int32_.Add(other.mapInt32Int32_);
mapInt64Int64_.Add(other.mapInt64Int64_);
mapUint32Uint32_.Add(other.mapUint32Uint32_);
mapUint64Uint64_.Add(other.mapUint64Uint64_);
mapSint32Sint32_.Add(other.mapSint32Sint32_);
mapSint64Sint64_.Add(other.mapSint64Sint64_);
mapFixed32Fixed32_.Add(other.mapFixed32Fixed32_);
mapFixed64Fixed64_.Add(other.mapFixed64Fixed64_);
mapSfixed32Sfixed32_.Add(other.mapSfixed32Sfixed32_);
mapSfixed64Sfixed64_.Add(other.mapSfixed64Sfixed64_);
mapInt32Float_.Add(other.mapInt32Float_);
mapInt32Double_.Add(other.mapInt32Double_);
mapBoolBool_.Add(other.mapBoolBool_);
mapInt32Enum_.Add(other.mapInt32Enum_);
mapInt32ForeignMessage_.Add(other.mapInt32ForeignMessage_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
mapInt32Int32_.AddEntriesFrom(input, _map_mapInt32Int32_codec);
break;
}
case 18: {
mapInt64Int64_.AddEntriesFrom(input, _map_mapInt64Int64_codec);
break;
}
case 26: {
mapUint32Uint32_.AddEntriesFrom(input, _map_mapUint32Uint32_codec);
break;
}
case 34: {
mapUint64Uint64_.AddEntriesFrom(input, _map_mapUint64Uint64_codec);
break;
}
case 42: {
mapSint32Sint32_.AddEntriesFrom(input, _map_mapSint32Sint32_codec);
break;
}
case 50: {
mapSint64Sint64_.AddEntriesFrom(input, _map_mapSint64Sint64_codec);
break;
}
case 58: {
mapFixed32Fixed32_.AddEntriesFrom(input, _map_mapFixed32Fixed32_codec);
break;
}
case 66: {
mapFixed64Fixed64_.AddEntriesFrom(input, _map_mapFixed64Fixed64_codec);
break;
}
case 74: {
mapSfixed32Sfixed32_.AddEntriesFrom(input, _map_mapSfixed32Sfixed32_codec);
break;
}
case 82: {
mapSfixed64Sfixed64_.AddEntriesFrom(input, _map_mapSfixed64Sfixed64_codec);
break;
}
case 90: {
mapInt32Float_.AddEntriesFrom(input, _map_mapInt32Float_codec);
break;
}
case 98: {
mapInt32Double_.AddEntriesFrom(input, _map_mapInt32Double_codec);
break;
}
case 106: {
mapBoolBool_.AddEntriesFrom(input, _map_mapBoolBool_codec);
break;
}
case 114: {
mapInt32Enum_.AddEntriesFrom(input, _map_mapInt32Enum_codec);
break;
}
case 122: {
mapInt32ForeignMessage_.AddEntriesFrom(input, _map_mapInt32ForeignMessage_codec);
break;
}
}
}
}
}
/// <summary>
/// Previously, message containing enum called Type cannot be used as value of
/// map field.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class MessageContainingEnumCalledType : pb::IMessage<MessageContainingEnumCalledType> {
private static readonly pb::MessageParser<MessageContainingEnumCalledType> _parser = new pb::MessageParser<MessageContainingEnumCalledType>(() => new MessageContainingEnumCalledType());
public static pb::MessageParser<MessageContainingEnumCalledType> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[5]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public MessageContainingEnumCalledType() {
OnConstruction();
}
partial void OnConstruction();
public MessageContainingEnumCalledType(MessageContainingEnumCalledType other) : this() {
type_ = other.type_.Clone();
}
public MessageContainingEnumCalledType Clone() {
return new MessageContainingEnumCalledType(this);
}
/// <summary>Field number for the "type" field.</summary>
public const int TypeFieldNumber = 1;
private static readonly pbc::MapField<int, global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType>.Codec _map_type_codec
= new pbc::MapField<int, global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType.Parser), 10);
private readonly pbc::MapField<int, global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType> type_ = new pbc::MapField<int, global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType>();
public pbc::MapField<int, global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType> Type {
get { return type_; }
}
public override bool Equals(object other) {
return Equals(other as MessageContainingEnumCalledType);
}
public bool Equals(MessageContainingEnumCalledType other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!Type.Equals(other.Type)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= Type.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
type_.WriteTo(output, _map_type_codec);
}
public int CalculateSize() {
int size = 0;
size += type_.CalculateSize(_map_type_codec);
return size;
}
public void MergeFrom(MessageContainingEnumCalledType other) {
if (other == null) {
return;
}
type_.Add(other.type_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
type_.AddEntriesFrom(input, _map_type_codec);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the MessageContainingEnumCalledType message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
public enum Type {
TYPE_FOO = 0,
}
}
#endregion
}
/// <summary>
/// Previously, message cannot contain map field called "entry".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class MessageContainingMapCalledEntry : pb::IMessage<MessageContainingMapCalledEntry> {
private static readonly pb::MessageParser<MessageContainingMapCalledEntry> _parser = new pb::MessageParser<MessageContainingMapCalledEntry>(() => new MessageContainingMapCalledEntry());
public static pb::MessageParser<MessageContainingMapCalledEntry> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[6]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public MessageContainingMapCalledEntry() {
OnConstruction();
}
partial void OnConstruction();
public MessageContainingMapCalledEntry(MessageContainingMapCalledEntry other) : this() {
entry_ = other.entry_.Clone();
}
public MessageContainingMapCalledEntry Clone() {
return new MessageContainingMapCalledEntry(this);
}
/// <summary>Field number for the "entry" field.</summary>
public const int EntryFieldNumber = 1;
private static readonly pbc::MapField<int, int>.Codec _map_entry_codec
= new pbc::MapField<int, int>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForInt32(16), 10);
private readonly pbc::MapField<int, int> entry_ = new pbc::MapField<int, int>();
public pbc::MapField<int, int> Entry {
get { return entry_; }
}
public override bool Equals(object other) {
return Equals(other as MessageContainingMapCalledEntry);
}
public bool Equals(MessageContainingMapCalledEntry other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!Entry.Equals(other.Entry)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= Entry.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
entry_.WriteTo(output, _map_entry_codec);
}
public int CalculateSize() {
int size = 0;
size += entry_.CalculateSize(_map_entry_codec);
return size;
}
public void MergeFrom(MessageContainingMapCalledEntry other) {
if (other == null) {
return;
}
entry_.Add(other.entry_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
entry_.AddEntriesFrom(input, _map_entry_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
#region License
//
// Copyright (c) 2018, Fluent Migrator 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.
//
#endregion
using System.Collections.Generic;
namespace FluentMigrator.Builders
{
/// <summary>
/// This class provides a common location for logic pertaining to setting and maintaining
/// expressions for expression builders which manipulate the the ColumnDefinition.
/// </summary>
/// <remarks>
/// This is a support class for the migrator framework and is not intended for external use.
/// TODO: make this internal, and the change assmebly info so InternalsVisibleTo is set for the test assemblies.
/// </remarks>
public class ColumnExpressionBuilderHelper
{
private readonly Dictionary<ColumnDefinition, ExistingRowsData> _existingRowsDataByColumn;
private readonly IColumnExpressionBuilder _builder;
private readonly IMigrationContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="ColumnExpressionBuilderHelper"/> class.
/// </summary>
/// <remarks>
/// This constructor exists only to ease creating mock objects.
/// </remarks>
protected ColumnExpressionBuilderHelper() { }
/// <summary>
/// Initializes a new instance of the <see cref="ColumnExpressionBuilderHelper"/> class.
/// </summary>
/// <param name="builder">The expression builder</param>
/// <param name="context">The migration context</param>
public ColumnExpressionBuilderHelper(IColumnExpressionBuilder builder, IMigrationContext context)
{
_builder = builder;
_context = context;
_existingRowsDataByColumn = new Dictionary<ColumnDefinition, ExistingRowsData>();
}
/// <summary>
/// Either updates the IsNullable flag on the column, or creates/removes the SetNotNull expression, depending
/// on whether the column has a 'Set existing rows' expression.
/// </summary>
public virtual void SetNullable(bool isNullable)
{
var column = _builder.Column;
ExistingRowsData exRowExpr;
if (_existingRowsDataByColumn.TryGetValue(column, out exRowExpr))
{
if (exRowExpr.SetExistingRowsExpression != null)
{
if (isNullable)
{
//Remove additional expression to set column to not null.
_context.Expressions.Remove(exRowExpr.SetColumnNotNullableExpression);
exRowExpr.SetColumnNotNullableExpression = null;
}
else
{
//Add expression to set column to not null.
//If it already exists, just leave it.
if (exRowExpr.SetColumnNotNullableExpression == null)
{
//stuff that matters shouldn't change at this point, so we're free to make a
//copy of the col def.
//TODO: make a SetColumnNotNullExpression, which just takes the bare minimum, rather
//than modifying column with all parameters.
ColumnDefinition notNullColDef = (ColumnDefinition)column.Clone();
notNullColDef.ModificationType = ColumnModificationType.Alter;
notNullColDef.IsNullable = false;
exRowExpr.SetColumnNotNullableExpression = new AlterColumnExpression
{
Column = notNullColDef,
TableName = _builder.TableName,
SchemaName = _builder.SchemaName
};
_context.Expressions.Add(exRowExpr.SetColumnNotNullableExpression);
}
}
//Setting column explicitly to nullable, as the actual nullable value
//will be set by the SetColumnNotNullableExpression after the column is created and populated.
column.IsNullable = true;
return;
}
}
//At this point, we know there's no existing row expression, so just pass it onto the
//underlying column.
column.IsNullable = isNullable;
}
/// <summary>
/// Adds the existing row default value. If the column has a value for IsNullable, this will also
/// call SetNullable to create the expression, and will then set the column IsNullable to false.
/// </summary>
public virtual void SetExistingRowsTo(object existingRowValue)
{
//TODO: validate that 'value' isn't set to null for non nullable columns. If set to
//null, maybe just remove the expressions?.. not sure of best way to handle this.
var column = _builder.Column;
if (column.ModificationType == ColumnModificationType.Create)
{
//ensure an UpdateDataExpression is created and cached for this column
ExistingRowsData exRowExpr;
if (!_existingRowsDataByColumn.TryGetValue(column, out exRowExpr))
{
exRowExpr = new ExistingRowsData();
_existingRowsDataByColumn.Add(column, exRowExpr);
}
if (exRowExpr.SetExistingRowsExpression == null)
{
exRowExpr.SetExistingRowsExpression = new UpdateDataExpression
{
TableName = _builder.TableName,
SchemaName = _builder.SchemaName,
IsAllRows = true,
};
_context.Expressions.Add(exRowExpr.SetExistingRowsExpression);
//Call SetNullable, to ensure that not-null columns are correctly set to
//not null after existing rows have data populated.
SetNullable(column.IsNullable ?? true);
}
exRowExpr.SetExistingRowsExpression.Set = new List<KeyValuePair<string, object>> {
new KeyValuePair<string, object>(column.Name, existingRowValue)
};
}
}
/// <summary>
/// Creates a new CREATE INDEX expression to create a new unique index
/// </summary>
/// <param name="indexName">The new name of the index</param>
public virtual void Unique(string indexName)
{
var column = _builder.Column;
column.IsUnique = true;
var index = new CreateIndexExpression
{
Index = new IndexDefinition
{
Name = indexName,
SchemaName = _builder.SchemaName,
TableName = _builder.TableName,
IsUnique = true
}
};
index.Index.Columns.Add(new IndexColumnDefinition
{
Name = _builder.Column.Name
});
_context.Expressions.Add(index);
}
/// <summary>
/// Creates a new CREATE INDEX expression
/// </summary>
/// <param name="indexName">The index name</param>
public virtual void Indexed(string indexName)
{
_builder.Column.IsIndexed = true;
var index = new CreateIndexExpression
{
Index = new IndexDefinition
{
Name = indexName,
SchemaName = _builder.SchemaName,
TableName = _builder.TableName
}
};
index.Index.Columns.Add(new IndexColumnDefinition
{
Name = _builder.Column.Name
});
_context.Expressions.Add(index);
}
/// <summary>
/// For each distinct column which has an existing row default, an instance of this
/// will be stored in the _expressionsByColumn.
/// </summary>
private class ExistingRowsData
{
public UpdateDataExpression SetExistingRowsExpression;
public AlterColumnExpression SetColumnNotNullableExpression;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.