context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* 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.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client.Tests;
using Apache.Geode.Client;
using QueryStatics = Apache.Geode.Client.Tests.QueryStatics;
using QueryCategory = Apache.Geode.Client.Tests.QueryCategory;
using QueryStrings = Apache.Geode.Client.Tests.QueryStrings;
[TestFixture]
[Category("group1")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientRemoteParamQueryStructSetTests : ThinClientRegionSteps
{
#region Private members
private UnitProcess m_client1;
private UnitProcess m_client2;
private static string[] QueryRegionNames = { "Portfolios", "Positions", "Portfolios2",
"Portfolios3" };
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
return new ClientBase[] { m_client1, m_client2 };
}
[TestFixtureSetUp]
public override void InitTests()
{
base.InitTests();
}
[TearDown]
public override void EndTest()
{
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServers();
base.EndTest();
}
[SetUp]
public override void InitTest()
{
m_client1.Call(InitClient);
m_client2.Call(InitClient);
}
#region Functions invoked by the tests
public void InitClient()
{
CacheHelper.Init();
Serializable.RegisterTypeGeneric(Portfolio.CreateDeserializable, CacheHelper.DCache);
Serializable.RegisterTypeGeneric(Position.CreateDeserializable, CacheHelper.DCache);
Serializable.RegisterPdxType(Apache.Geode.Client.Tests.PortfolioPdx.CreateDeserializable);
Serializable.RegisterPdxType(Apache.Geode.Client.Tests.PositionPdx.CreateDeserializable);
}
public void StepOne(string locators, bool isPdx)
{
m_isPdx = isPdx;
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[0], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[1], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[2], true, true,
null, locators, "__TESTPOOL1_", true);
CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[3], true, true,
null, locators, "__TESTPOOL1_", true);
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
Apache.Geode.Client.RegionAttributes<object, object> regattrs = region.Attributes;
region.CreateSubRegion(QueryRegionNames[1], regattrs);
}
public void StepTwo(bool isPdx)
{
m_isPdx = isPdx;
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]);
IRegion<object, object> subRegion0 = (IRegion<object, object>)region0.GetSubRegion(QueryRegionNames[1]);
IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(QueryRegionNames[1]);
IRegion<object, object> region2 = CacheHelper.GetRegion<object, object>(QueryRegionNames[2]);
IRegion<object, object> region3 = CacheHelper.GetRegion<object, object>(QueryRegionNames[3]);
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
Util.Log("SetSize {0}, NumSets {1}.", qh.PortfolioSetSize,
qh.PortfolioNumSets);
if (!m_isPdx)
{
qh.PopulatePortfolioData(region0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePositionData(subRegion0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePositionData(region1, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioData(region2, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioData(region3, qh.PortfolioSetSize,
qh.PortfolioNumSets);
}
else
{
qh.PopulatePortfolioPdxData(region0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePositionPdxData(subRegion0, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePositionPdxData(region1, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioPdxData(region2, qh.PortfolioSetSize,
qh.PortfolioNumSets);
qh.PopulatePortfolioPdxData(region3, qh.PortfolioSetSize,
qh.PortfolioNumSets);
}
}
public void StepThreePQSS()
{
bool ErrorOccurred = false;
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.StructSetParamQueries)
{
if (qrystr.Category == QueryCategory.Unsupported)
{
Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
qryIdx++;
continue;
}
Util.Log("Evaluating query index {0}. {1}", qryIdx, qrystr.Query);
if (m_isPdx == true)
{
if (qryIdx == 16)
{
Util.Log("Skipping query index {0} for pdx because it has function.", qryIdx);
qryIdx++;
continue;
}
}
Query<object> query = qs.NewQuery<object>(qrystr.Query);
//Populate the param list, paramList for parameterized query
object[] paramList = new object[QueryStatics.NoOfQueryParamSS[qryIdx]];
Int32 numVal = 0;
for (Int32 ind = 0; ind < QueryStatics.NoOfQueryParamSS[qryIdx]; ind++)
{
//Util.Log("NIL::PQRS:: QueryStatics.QueryParamSetSS[{0},{1}] = {2}", qryIdx, ind, QueryStatics.QueryParamSetSS[qryIdx, ind]);
try
{
numVal = Convert.ToInt32(QueryStatics.QueryParamSetSS[qryIdx][ind]);
paramList[ind] = numVal;
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind]);
}
catch (FormatException)
{
//Console.WriteLine("Param string is not a sequence of digits.");
paramList[ind] = (System.String)QueryStatics.QueryParamSetSS[qryIdx][ind];
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind].ToString());
}
}
ISelectResults<object> results = query.Execute(paramList);
int expectedRowCount = qh.IsExpectedRowsConstantPQSS(qryIdx) ?
QueryStatics.StructSetPQRowCounts[qryIdx] : QueryStatics.StructSetPQRowCounts[qryIdx] * qh.PortfolioNumSets;
if (!qh.VerifySS(results, expectedRowCount, QueryStatics.StructSetPQFieldCounts[qryIdx]))
{
ErrorOccurred = true;
Util.Log("Query verify failed for query index {0}.", qryIdx);
qryIdx++;
continue;
}
StructSet<object> ss = results as StructSet<object>;
if (ss == null)
{
Util.Log("Zero records found for query index {0}, continuing.", qryIdx);
qryIdx++;
continue;
}
uint rows = 0;
Int32 fields = 0;
foreach (Struct si in ss)
{
rows++;
fields = (Int32)si.Length;
}
Util.Log("Query index {0} has {1} rows and {2} fields.", qryIdx, rows, fields);
qryIdx++;
}
Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
}
public void StepFourPQSS()
{
bool ErrorOccurred = false;
QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
int qryIdx = 0;
foreach (QueryStrings qrystr in QueryStatics.StructSetParamQueries)
{
if (qrystr.Category != QueryCategory.Unsupported)
{
qryIdx++;
continue;
}
Util.Log("Evaluating unsupported query index {0}.", qryIdx);
Query<object> query = qs.NewQuery<object>(qrystr.Query);
//Populate the param list
object[] paramList = new object[QueryStatics.NoOfQueryParamSS[qryIdx]];
Int32 numVal = 0;
for (Int32 ind = 0; ind < QueryStatics.NoOfQueryParamSS[qryIdx]; ind++)
{
//Util.Log("NIL::PQRS:: QueryStatics.QueryParamSetSS[{0},{1}] = {2}", qryIdx, ind, QueryStatics.QueryParamSetSS[qryIdx, ind]);
try
{
numVal = Convert.ToInt32(QueryStatics.QueryParamSetSS[qryIdx][ind]);
paramList[ind] = numVal;
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind]);
}
catch (FormatException)
{
//Console.WriteLine("Param string is not a sequence of digits.");
paramList[ind] = (System.String)QueryStatics.QueryParamSetSS[qryIdx][ind];
//Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind].ToString());
}
}
try
{
ISelectResults<object> results = query.Execute(paramList);
Util.Log("Query exception did not occur for index {0}.", qryIdx);
ErrorOccurred = true;
qryIdx++;
}
catch (GeodeException)
{
// ok, exception expected, do nothing.
qryIdx++;
}
catch (Exception)
{
Util.Log("Query unexpected exception occurred for index {0}.", qryIdx);
ErrorOccurred = true;
qryIdx++;
}
}
Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur.");
}
public void KillServer()
{
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
}
public delegate void KillServerDelegate();
#endregion
void runRemoteParamQuerySS()
{
CacheHelper.SetupJavaServers(true, "remotequeryN.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client2.Call(StepOne, CacheHelper.Locators, m_isPdx);
Util.Log("StepOne complete.");
m_client2.Call(StepTwo, m_isPdx);
Util.Log("StepTwo complete.");
m_client2.Call(StepThreePQSS);
Util.Log("StepThree complete.");
m_client2.Call(StepFourPQSS);
Util.Log("StepFour complete.");
//m_client2.Call(GetAllRegionQuery);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
}
static bool m_isPdx = false;
[Test]
public void RemoteParamQuerySSWithoutPdx()
{
m_isPdx = false;
runRemoteParamQuerySS();
}
[Test]
public void RemoteParamQuerySSWithPdx()
{
m_isPdx = true;
runRemoteParamQuerySS();
}
}
}
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System;
using BEPUphysics;
using BEPUutilities;
using BEPUphysics.CollisionShapes.ConvexShapes;
using BEPUphysics.Entities;
using BEPUphysics.BroadPhaseEntries.MobileCollidables;
using BEPUphysics.BroadPhaseEntries;
using BEPUphysics.CollisionRuleManagement;
namespace Voxalia.Shared.Collision
{
public class CollisionResult
{
public bool Hit;
/// <summary>
/// The impact normal. Warning: not normalized!
/// </summary>
public Location Normal;
public Location Position;
public Entity HitEnt;
}
/// <summary>
/// Helper code for tracing collision.
/// </summary>
public class CollisionUtil
{
public Space World;
public static CollisionGroup NonSolid = new CollisionGroup();
public static CollisionGroup Solid = new CollisionGroup();
public static CollisionGroup Player = new CollisionGroup();
public static CollisionGroup Item = new CollisionGroup();
public static CollisionGroup Water = new CollisionGroup();
public static CollisionGroup WorldSolid = new CollisionGroup();
public static CollisionGroup Character = new CollisionGroup();
public bool ShouldCollide(BroadPhaseEntry entry)
{
if (entry.CollisionRules.Group == NonSolid || entry.CollisionRules.Group == Water)
{
return false;
}
return true;
}
public CollisionUtil(Space world)
{
World = world;
// NonSolid Vs. Solid,NonSolid,WorldSolid (All)
CollisionGroup.DefineCollisionRule(NonSolid, WorldSolid, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(WorldSolid, NonSolid, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(NonSolid, NonSolid, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(NonSolid, Solid, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(Solid, NonSolid, CollisionRule.NoBroadPhase);
// Player Vs. NonSolid,Player
CollisionGroup.DefineCollisionRule(Player, NonSolid, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(NonSolid, Player, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(Player, Player, CollisionRule.NoBroadPhase);
// Item Vs. NonSolid (All)
CollisionGroup.DefineCollisionRule(Item, NonSolid, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(NonSolid, Item, CollisionRule.NoBroadPhase);
// Water Vs. NonSolid,Solid,Player,Item (All)
CollisionGroup.DefineCollisionRule(Water, NonSolid, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(NonSolid, Water, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(Water, Solid, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(Solid, Water, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(Water, Player, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(Player, Water, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(Water, Item, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(Item, Water, CollisionRule.NoBroadPhase);
// Non-player Character Vs. NonSolid,Item,Water
CollisionGroup.DefineCollisionRule(Character, NonSolid, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(NonSolid, Character, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(Character, Water, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(Water, Character, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(Character, Item, CollisionRule.NoBroadPhase);
CollisionGroup.DefineCollisionRule(Item, Character, CollisionRule.NoBroadPhase);
}
public CollisionResult CuboidLineTrace(Location halfsize, Location start, Location end, Func<BroadPhaseEntry, bool> filter = null)
{
BoxShape shape = new BoxShape((double)halfsize.X * 2f, (double)halfsize.Y * 2f, (double)halfsize.Z * 2f);
return CuboidLineTrace(shape, start, end, filter);
}
/// <summary>
/// Returns information on what a cuboid-shaped line trace would collide with, if anything.
/// </summary>
/// <param name="start">The start of the line.</param>
/// <param name="end">The end of the line.</param>
/// <param name="filter">The collision filter, input a BEPU BroadPhaseEntry and output whether collision should be allowed.</param>
/// <returns>The collision details.</returns>
public CollisionResult CuboidLineTrace(ConvexShape shape, Location start, Location end, Func<BroadPhaseEntry, bool> filter = null)
{
Vector3 e = new Vector3((double)(end.X - start.X), (double)(end.Y - start.Y), (double)(end.Z - start.Z));
RigidTransform rt = new RigidTransform(new Vector3((double)start.X, (double)start.Y, (double)start.Z));
RayCastResult rcr;
bool hit;
if (filter == null)
{
hit = World.ConvexCast(shape, ref rt, ref e, out rcr);
}
else
{
hit = World.ConvexCast(shape, ref rt, ref e, filter, out rcr);
}
CollisionResult cr = new CollisionResult();
cr.Hit = hit;
if (hit)
{
cr.Normal = new Location(rcr.HitData.Normal);
cr.Position = new Location(rcr.HitData.Location);
if (rcr.HitObject is EntityCollidable)
{
cr.HitEnt = ((EntityCollidable)rcr.HitObject).Entity;
}
else
{
cr.HitEnt = null; // Impacted static world
}
}
else
{
cr.Normal = Location.Zero;
cr.Position = end;
cr.HitEnt = null;
}
return cr;
}
/// <summary>
/// Returns information on what a line trace would collide with, if anything.
/// </summary>
/// <param name="start">The start of the line.</param>
/// <param name="end">The end of the line.</param>
/// <param name="filter">The collision filter, input a BEPU BroadPhaseEntry and output whether collision should be allowed.</param>
/// <returns>The collision details.</returns>
public CollisionResult RayTrace(Location start, Location end, Func<BroadPhaseEntry, bool> filter = null)
{
double len = (end - start).Length();
Ray ray = new Ray(start.ToBVector(), ((end - start) / len).ToBVector());
RayCastResult rcr;
bool hit;
if (filter == null)
{
hit = World.RayCast(ray, (double)len, out rcr);
}
else
{
hit = World.RayCast(ray, (double)len, filter, out rcr);
}
CollisionResult cr = new CollisionResult();
cr.Hit = hit;
if (hit)
{
cr.Normal = new Location(rcr.HitData.Normal);
cr.Position = new Location(rcr.HitData.Location);
if (rcr.HitObject is EntityCollidable)
{
cr.HitEnt = ((EntityCollidable)rcr.HitObject).Entity;
}
else
{
cr.HitEnt = null; // Impacted static world
}
}
else
{
cr.Normal = Location.Zero;
cr.Position = end;
cr.HitEnt = null;
}
return cr;
}
/// <summary>
/// Returns whether a box contains (intersects with) another box.
/// </summary>
/// <param name="elow">The low point for box 1.</param>
/// <param name="ehigh">The high point for box 1.</param>
/// <param name="Low">The low point for box 2.</param>
/// <param name="High">The high point for box 2.</param>
/// <returns>whether there is intersection.</returns>
public static bool BoxContainsBox(Location elow, Location ehigh, Location Low, Location High)
{
return Low.X <= ehigh.X && Low.Y <= ehigh.Y && Low.Z <= ehigh.Z &&
High.X >= elow.X && High.Y >= elow.Y && High.Z >= elow.Z;
}
/// <summary>
/// Returns whether a box contains a point.
/// </summary>
/// <param name="elow">The low point for the box.</param>
/// <param name="ehigh">The high point for the box.</param>
/// <param name="point">The point to check.</param>
/// <returns>whether there is intersection.</returns>
public static bool BoxContainsPoint(Location elow, Location ehigh, Location point)
{
return point.X <= ehigh.X && point.Y <= ehigh.Y && point.Z <= ehigh.Z &&
point.X >= elow.X && point.Y >= elow.Y && point.Z >= elow.Z;
}
/// <summary>
/// Runs a collision check between two AABB objects.
/// </summary>
/// <param name="Position">The block's position.</param>
/// <param name="Mins">The block's mins.</param>
/// <param name="Maxs">The block's maxs.</param>
/// <param name="Mins2">The moving object's mins.</param>
/// <param name="Maxs2">The moving object's maxs.</param>
/// <param name="start">The starting location of the moving object.</param>
/// <param name="end">The ending location of the moving object.</param>
/// <param name="normal">The normal of the hit, or NaN if none.</param>
/// <returns>The location of the hit, or NaN if none.</returns>
public static Location AABBClosestBox(Location Position, Location Mins, Location Maxs, Location Mins2, Location Maxs2, Location start, Location end, out Location normal)
{
Location velocity = end - start;
Location RealMins = Position + Mins;
Location RealMaxs = Position + Maxs;
Location RealMins2 = start + Mins2;
Location RealMaxs2 = start + Maxs2;
double xInvEntry, yInvEntry, zInvEntry;
double xInvExit, yInvExit, zInvExit;
if (end.X >= start.X)
{
xInvEntry = RealMins.X - RealMaxs2.X;
xInvExit = RealMaxs.X - RealMins2.X;
}
else
{
xInvEntry = RealMaxs.X - RealMins2.X;
xInvExit = RealMins.X - RealMaxs2.X;
}
if (end.Y >= start.Y)
{
yInvEntry = RealMins.Y - RealMaxs2.Y;
yInvExit = RealMaxs.Y - RealMins2.Y;
}
else
{
yInvEntry = RealMaxs.Y - RealMins2.Y;
yInvExit = RealMins.Y - RealMaxs2.Y;
}
if (end.Z >= start.Z)
{
zInvEntry = RealMins.Z - RealMaxs2.Z;
zInvExit = RealMaxs.Z - RealMins2.Z;
}
else
{
zInvEntry = RealMaxs.Z - RealMins2.Z;
zInvExit = RealMins.Z - RealMaxs2.Z;
}
double xEntry, yEntry, zEntry;
double xExit, yExit, zExit;
if (velocity.X == 0f)
{
xEntry = xInvEntry / 0.00000000000000000000000000000001f;
xExit = xInvExit / 0.00000000000000000000000000000001f;
}
else
{
xEntry = xInvEntry / velocity.X;
xExit = xInvExit / velocity.X;
}
if (velocity.Y == 0f)
{
yEntry = yInvEntry / 0.00000000000000000000000000000001f;
yExit = yInvExit / 0.00000000000000000000000000000001f;
}
else
{
yEntry = yInvEntry / velocity.Y;
yExit = yInvExit / velocity.Y;
}
if (velocity.Z == 0f)
{
zEntry = zInvEntry / 0.00000000000000000000000000000001f;
zExit = zInvExit / 0.00000000000000000000000000000001f;
}
else
{
zEntry = zInvEntry / velocity.Z;
zExit = zInvExit / velocity.Z;
}
double entryTime = Math.Max(Math.Max(xEntry, yEntry), zEntry);
double exitTime = Math.Min(Math.Min(xExit, yExit), zExit);
if (entryTime > exitTime || (xEntry < 0.0f && yEntry < 0.0f && zEntry < 0.0f) || xEntry > 1.0f || yEntry > 1.0f || zEntry > 1.0f)
{
normal = Location.NaN;
return Location.NaN;
}
else
{
if (zEntry >= xEntry && zEntry >= yEntry)
{
if (zInvEntry < 0)
{
normal = new Location(0, 0, 1);
}
else
{
normal = new Location(0, 0, -1);
}
}
else if (xEntry >= zEntry && xEntry >= yEntry)
{
if (xInvEntry < 0)
{
normal = new Location(1, 0, 0);
}
else
{
normal = new Location(-1, 0, 0);
}
}
else
{
if (yInvEntry < 0)
{
normal = new Location(0, 1, 0);
}
else
{
normal = new Location(0, -1, 0);
}
}
Location res = start + (end - start) * entryTime;
return new Location(res.X, res.Y, res.Z);
}
}
/// <summary>
/// Runs a collision check between an AABB and a ray.
/// </summary>
/// <param name="Position">The block's position.</param>
/// <param name="Mins">The block's mins.</param>
/// <param name="Maxs">The block's maxs.</param>
/// <param name="start">The starting location of the ray.</param>
/// <param name="end">The ending location of the ray.</param>
/// <param name="normal">The normal of the hit, or NaN if none.</param>
/// <returns>The location of the hit, or NaN if none.</returns>
public static Location RayTraceBox(Location Position, Location Mins, Location Maxs, Location start, Location end, out Location normal)
{
Location velocity = end - start;
Location RealMins = Position + Mins;
Location RealMaxs = Position + Maxs;
double xInvEntry, yInvEntry, zInvEntry;
double xInvExit, yInvExit, zInvExit;
if (end.X >= start.X)
{
xInvEntry = RealMins.X - start.X;
xInvExit = RealMaxs.X - start.X;
}
else
{
xInvEntry = RealMaxs.X - start.X;
xInvExit = RealMins.X - start.X;
}
if (end.Y >= start.Y)
{
yInvEntry = RealMins.Y - start.Y;
yInvExit = RealMaxs.Y - start.Y;
}
else
{
yInvEntry = RealMaxs.Y - start.Y;
yInvExit = RealMins.Y - start.Y;
}
if (end.Z >= start.Z)
{
zInvEntry = RealMins.Z - start.Z;
zInvExit = RealMaxs.Z - start.Z;
}
else
{
zInvEntry = RealMaxs.Z - start.Z;
zInvExit = RealMins.Z - start.Z;
}
double xEntry, yEntry, zEntry;
double xExit, yExit, zExit;
if (velocity.X == 0f)
{
xEntry = xInvEntry / 0.00000000000000000000000000000001f;
xExit = xInvExit / 0.00000000000000000000000000000001f;
}
else
{
xEntry = xInvEntry / velocity.X;
xExit = xInvExit / velocity.X;
}
if (velocity.Y == 0f)
{
yEntry = yInvEntry / 0.00000000000000000000000000000001f;
yExit = yInvExit / 0.00000000000000000000000000000001f;
}
else
{
yEntry = yInvEntry / velocity.Y;
yExit = yInvExit / velocity.Y;
}
if (velocity.Z == 0f)
{
zEntry = zInvEntry / 0.00000000000000000000000000000001f;
zExit = zInvExit / 0.00000000000000000000000000000001f;
}
else
{
zEntry = zInvEntry / velocity.Z;
zExit = zInvExit / velocity.Z;
}
double entryTime = Math.Max(Math.Max(xEntry, yEntry), zEntry);
double exitTime = Math.Min(Math.Min(xExit, yExit), zExit);
if (entryTime > exitTime || (xEntry < 0.0f && yEntry < 0.0f && zEntry < 0.0f) || xEntry > 1.0f || yEntry > 1.0f || zEntry > 1.0f)
{
normal = Location.NaN;
return Location.NaN;
}
else
{
if (zEntry >= xEntry && zEntry >= yEntry)
{
if (zInvEntry < 0)
{
normal = new Location(0, 0, 1);
}
else
{
normal = new Location(0, 0, -1);
}
}
else if (xEntry >= zEntry && xEntry >= yEntry)
{
if (xInvEntry < 0)
{
normal = new Location(1, 0, 0);
}
else
{
normal = new Location(-1, 0, 0);
}
}
else
{
if (yInvEntry < 0)
{
normal = new Location(0, 1, 0);
}
else
{
normal = new Location(0, -1, 0);
}
}
Location res = start + (end - start) * entryTime;
return new Location(res.X, res.Y, res.Z);
}
}
/// <summary>
/// Gets the lowest point of two points.
/// </summary>
/// <param name="one">The first point.</param>
/// <param name="two">The second point.</param>
/// <returns>The lowest point.</returns>
public static Location GetLow(Location one, Location two)
{
return new Location(one.X < two.X ? one.X : two.X,
one.Y < two.Y ? one.Y : two.Y,
one.Z < two.Z ? one.Z : two.Z);
}
/// <summary>
/// Gets the highest point of two points.
/// </summary>
/// <param name="one">The first point.</param>
/// <param name="two">The second point.</param>
/// <returns>The highest point.</returns>
public static Location GetHigh(Location one, Location two)
{
return new Location(one.X > two.X ? one.X : two.X,
one.Y > two.Y ? one.Y : two.Y,
one.Z > two.Z ? one.Z : two.Z);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.Collections.Specialized;
using Microsoft.DirectX;
using Voyage.Terraingine.DataInterfacing;
using Voyage.Terraingine.DXViewport;
using Voyage.LuaNetInterface;
namespace Voyage.Terraingine
{
/// <summary>
/// A user control for manipulating terrain vertices.
/// </summary>
public class VertexManipulation : System.Windows.Forms.UserControl
{
#region Data Members
private DataInterfacing.ViewportInterface _viewport;
private DataInterfacing.DataManipulation _terrainData;
private NameValueCollection _verticesAlgorithms;
private DXViewport.Viewport _dx;
private bool _updateData;
private TerrainViewport _owner;
private System.Windows.Forms.GroupBox grpVertexName;
private System.Windows.Forms.Button btnVertices_Name;
private System.Windows.Forms.TextBox txtVertices_Name;
private System.Windows.Forms.GroupBox grpVertexDimensions;
private System.Windows.Forms.CheckBox chkVertices_GridSize;
private System.Windows.Forms.NumericUpDown numVertices_RowDistance;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.NumericUpDown numVertices_ColumnDistance;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.CheckBox chkVertices_GridDimensions;
private System.Windows.Forms.NumericUpDown numVertices_Columns;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.NumericUpDown numVertices_Rows;
private System.Windows.Forms.GroupBox grpVertexCreation;
private System.Windows.Forms.Button btnVertices_Create;
private System.Windows.Forms.GroupBox grpVertexSelection;
private System.Windows.Forms.CheckBox chkFalloff;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown numSoft;
private System.Windows.Forms.RadioButton radSoft;
private System.Windows.Forms.Button btnVertexSelection;
private System.Windows.Forms.RadioButton radSingle;
private System.Windows.Forms.GroupBox grpVertexAlgorithms;
private System.Windows.Forms.Button btnVertices_LoadAlgorithm;
private System.Windows.Forms.Button btnVertices_RunAlgorithm;
private System.Windows.Forms.ListBox lstVertices_Algorithms;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.NumericUpDown numMaxHeight;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.NumericUpDown numVertexHeight;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
#endregion
#region Properties
/// <summary>
/// Gets or sets whether the control allows data updates.
/// </summary>
public bool EnableDataUpdates
{
get { return _updateData; }
set { _updateData = value; }
}
/// <summary>
/// Gets the vertex movement button.
/// </summary>
public Button EnableVertexMovement
{
get { return btnVertexSelection; }
}
/// <summary>
/// Sets the soft selection value shown in the display.
/// </summary>
public float SoftSelectionDistance
{
set { numSoft.Value = Convert.ToDecimal( value ); }
}
#endregion
#region Basic Data Methods
/// <summary>
/// Creates a vertex manipulation user control.
/// </summary>
public VertexManipulation()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Initializes the control's data members.
/// </summary>
/// <param name="owner">The TerrainViewport that contains the control.</param>
public void Initialize( TerrainViewport owner )
{
// Shortcut variables for the DirectX viewport and the terrain data
_owner = owner;
_viewport = owner.MainViewport;
_terrainData = owner.MainViewport.TerrainData;
_dx = owner.MainViewport.DXViewport;
// Initialize the control-specific data
_verticesAlgorithms = new NameValueCollection();
_updateData = true;
// Register tooltips
ToolTip t = new ToolTip();
// Terrain Creation group tooltips
t.SetToolTip( btnVertices_Create, "Create a piece of terrain (Ctrl+N)" );
// Terrain Name group tooltips
t.SetToolTip( btnVertices_Name, "Change the name of the terrain" );
// Vertex Selection group tooltips
t.SetToolTip( btnVertexSelection, "Enable or disable vertex movement" );
t.SetToolTip( radSingle, "Move vertices without blending" );
t.SetToolTip( radSoft, "Move vertices with blending" );
t.SetToolTip( chkFalloff, "Blend nearby vertices with falloff weighting" );
// Algorithms group tooltips
t.SetToolTip( btnVertices_RunAlgorithm, "Run the selected vertex manipulation algorithm" );
t.SetToolTip( btnVertices_LoadAlgorithm, "Load a new vertex manipulation algorithm" );
// Modify Terrain Dimensions group tooltips
t.SetToolTip( chkVertices_GridDimensions, "Keep rows and columns the same value" );
t.SetToolTip( chkVertices_GridSize, "Keep height and width the same value" );
}
/// <summary>
/// Sets all control displays to their default values.
/// </summary>
public void RestoreDefaults()
{
// Begin restoring defaults
_updateData = false;
// Restore defaults to Terrain Creation group
grpVertexCreation.Enabled = true;
// Restore defaults to Vertex Selection group
grpVertexSelection.Enabled = false;
radSingle.Checked = true;
numSoft.Value = Convert.ToDecimal( 0.2f );
chkFalloff.Checked = true;
if ( btnVertexSelection.BackColor == Color.FromKnownColor( KnownColor.ControlLight ) )
btnVertexSelection_Click( this, new System.EventArgs() );
// Restore defaults to Vertex Algorithms group
grpVertexAlgorithms.Enabled = false;
lstVertices_Algorithms.SelectedIndex = -1;
btnVertices_RunAlgorithm.Enabled = false;
// Restore defaults to Vertex Dimensions group
grpVertexDimensions.Enabled = false;
numVertices_Rows.Value = 5;
numVertices_Columns.Value = 5;
chkVertices_GridDimensions.Checked = true;
numVertices_ColumnDistance.Value = 1;
numVertices_RowDistance.Value = 1;
chkVertices_GridSize.Checked = true;
numMaxHeight.Value = 1;
// Restore defaults to Vertex Name group
grpVertexName.Enabled = false;
txtVertices_Name.Text = "";
// Finished restoring defaults
_updateData = true;
}
#endregion
#region Event Methods
/// <summary>
/// Creates a piece of terrain.
/// </summary>
private void btnVertices_Create_Click(object sender, System.EventArgs e)
{
CreateTerrainDialog();
}
/// <summary>
/// Updates the name of the current TerrainPage.
/// </summary>
private void txtVertices_Name_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if ( e.KeyCode == Keys.Enter )
UpdateTerrainName();
}
/// <summary>
/// Updates the name of the current TerrainPage.
/// </summary>
private void btnVertices_Name_Click(object sender, System.EventArgs e)
{
UpdateTerrainName();
}
/// <summary>
/// Enables or disables vertex selection.
/// </summary>
private void btnVertexSelection_Click(object sender, System.EventArgs e)
{
if ( btnVertexSelection.BackColor == Color.FromKnownColor( KnownColor.Control ) )
btnVertexSelection_Click( true );
else
btnVertexSelection_Click( false );
}
/// <summary>
/// Disables soft selection.
/// </summary>
private void radSingle_CheckedChanged(object sender, System.EventArgs e)
{
if ( radSingle.Checked )
EnableSoftSelection( false );
}
/// <summary>
/// Enables soft selection.
/// </summary>
private void radSoft_CheckedChanged(object sender, System.EventArgs e)
{
if ( radSoft.Checked )
EnableSoftSelection( true );
}
/// <summary>
/// Updates the soft selection distance.
/// </summary>
private void numSoft_ValueChanged(object sender, System.EventArgs e)
{
numSoft_ValueChanged();
}
/// <summary>
/// Updates whether soft selection uses falloff.
/// </summary>
private void chkFalloff_CheckedChanged(object sender, System.EventArgs e)
{
chkFalloff_CheckedChanged();
}
/// <summary>
/// Changes the height of the selected vertices.
/// </summary>
private void numVertexHeight_ValueChanged(object sender, System.EventArgs e)
{
numVertexHeight_ValueChanged();
}
/// <summary>
/// Changes the height of the selected vertices.
/// </summary>
private void numVertexHeight_Leave(object sender, System.EventArgs e)
{
numVertexHeight_ValueChanged();
}
/// <summary>
/// Enables the vertex manipulation "Run Algorithm" button if an item is selected.
/// </summary>
private void lstVertices_Algorithms_SelectedIndexChanged(object sender, System.EventArgs e)
{
lstVertices_Algorithms_SelectedIndexChanged();
}
/// <summary>
/// Runs the vertex manipulation "Run Algorithm" button if an item is being clicked.
/// </summary>
private void lstVertices_Algorithms_DoubleClick(object sender, System.EventArgs e)
{
lstVertices_Algorithms_DoubleClick();
}
/// <summary>
/// Runs the selected vertex manipulation algorithm.
/// </summary>
private void btnVertices_RunAlgorithm_Click(object sender, System.EventArgs e)
{
btnVertices_RunAlgorithm_Click();
}
/// <summary>
/// Loads a new vertex manipulation plug-in.
/// </summary>
private void btnVertices_LoadAlgorithm_Click(object sender, System.EventArgs e)
{
LoadAlgorithm();
}
/// <summary>
/// Changes the number of rows in the TerrainPatch.
/// </summary>
private void numVertices_Rows_Leave(object sender, System.EventArgs e)
{
if ( _updateData )
ChangeGridSize();
}
/// <summary>
/// Changes the number of rows in the TerrainPatch.
/// </summary>
private void numVertices_Rows_ValueChanged(object sender, System.EventArgs e)
{
numVertices_Rows_ValueChanged();
}
/// <summary>
/// Changes the number of columns in the TerrainPatch.
/// </summary>
private void numVertices_Columns_Leave(object sender, System.EventArgs e)
{
if ( _updateData )
ChangeGridSize();
}
/// <summary>
/// Changes the number of columns in the TerrainPatch.
/// </summary>
private void numVertices_Columns_ValueChanged(object sender, System.EventArgs e)
{
numVertices_Columns_ValueChanged();
}
/// <summary>
/// Changes whether the number of rows and the number of columns in the TerrainPatch must be equal.
/// </summary>
private void chkVertices_GridDimensions_CheckedChanged(object sender, System.EventArgs e)
{
chkVertices_GridDimensions_CheckedChanged();
}
/// <summary>
/// Changes the distance between columns in the TerrainPatch.
/// </summary>
private void numVertices_ColumnDistance_ValueChanged(object sender, System.EventArgs e)
{
if ( _updateData )
ChangeGridDimensions();
}
/// <summary>
/// Changes the distance between columns in the TerrainPatch.
/// </summary>
private void numVertices_ColumnDistance_Leave(object sender, System.EventArgs e)
{
numVertices_ColumnDistance_Leave();
}
/// <summary>
/// Changes the distance between columns in the TerrainPatch.
/// </summary>
private void numVertices_RowDistance_ValueChanged(object sender, System.EventArgs e)
{
if ( _updateData )
ChangeGridDimensions();
}
/// <summary>
/// Changes the distance between columns in the TerrainPatch.
/// </summary>
private void numVertices_RowDistance_Leave(object sender, System.EventArgs e)
{
numVertices_RowDistance_Leave();
}
/// <summary>
/// Changes whether the distance between rows and the distance between columns
/// in the TerrainPatch must be equal.
/// </summary>
private void chkVertices_GridSize_CheckedChanged(object sender, System.EventArgs e)
{
chkVertices_GridSize_CheckedChanged();
}
/// <summary>
/// Changes the maximum vertex height of the TerrainPatch.
/// </summary>
private void numMaxHeight_ValueChanged(object sender, System.EventArgs e)
{
numMaxHeight_ValueChanged();
}
/// <summary>
/// Changes the maximum vertex height of the TerrainPatch.
/// </summary>
private void numMaxHeight_Leave(object sender, System.EventArgs e)
{
numMaxHeight_ValueChanged();
}
#endregion
#region Terrain Creation
/// <summary>
/// Creates a piece of terrain using the TerrainCreation dialog.
/// </summary>
public void CreateTerrainDialog()
{
TerrainCreation create = new TerrainCreation();
Point parLoc = _owner.GetFormCenter();
Point p = new Point( parLoc.X - create.Width / 2, parLoc.Y - create.Height / 2 );
create.Location = p;
grpVertexCreation.Enabled = false;
create.Show();
while ( create.Created )
{
_viewport.PreRender();
if ( _viewport.BeginRender() )
{
_viewport.RenderSceneElements();
_viewport.EndRender();
}
create.OnApplicationIdle( this, new EventArgs() );
Application.DoEvents();
}
if ( create.Accepted )
( (MainForm) _owner ).LoadTerrain( create.MainViewport.TerrainData.TerrainPage );
else
grpVertexCreation.Enabled = true;
}
/// <summary>
/// Loads a TerrainPage into the program.
/// </summary>
/// <param name="name">The name of the TerrainPage.</param>
public void LoadTerrain( string name )
{
RestoreDefaults();
txtVertices_Name.Text = name;
EnableTerrainEditing( true );
}
#endregion
#region Terrain Page Name
/// <summary>
/// Updates the name of the current TerrainPage.
/// </summary>
public void UpdateTerrainName()
{
if ( _updateData )
_terrainData.TerrainPage.Name = txtVertices_Name.Text;
}
#endregion
#region Vertex Selection
/// <summary>
/// Enables or disables vertex selection.
/// </summary>
/// <param name="enable">Whether to enable vertex selection.</param>
public void btnVertexSelection_Click( bool enable )
{
if ( enable )
{
btnVertexSelection.BackColor = Color.FromKnownColor( KnownColor.ControlLight );
_terrainData.EnableVertexMovement = true;
_terrainData.BufferObjects.ShowSelectedVertices = true;
_dx.Camera.CurrentMovement = QuaternionCamera.MovementType.None;
radSingle.Enabled = true;
radSoft.Enabled = true;
numSoft.Enabled = true;
chkFalloff.Enabled = true;
}
else
{
btnVertexSelection.BackColor = Color.FromKnownColor( KnownColor.Control );
_terrainData.EnableVertexMovement = false;
_terrainData.BufferObjects.ShowSelectedVertices = false;
radSingle.Enabled = false;
radSoft.Enabled = false;
numSoft.Enabled = false;
chkFalloff.Enabled = false;
}
}
/// <summary>
/// Updates the soft selection distance.
/// </summary>
public void numSoft_ValueChanged()
{
if ( _updateData )
{
float result = ( float ) numSoft.Value;
_terrainData.SoftSelectionDistanceSquared = result * result;
_terrainData.TerrainPage.TerrainPatch.RefreshVertices = true;
}
}
/// <summary>
/// Updates whether soft selection uses falloff.
/// </summary>
public void chkFalloff_CheckedChanged()
{
if ( _updateData )
{
_terrainData.Falloff = chkFalloff.Checked;
_terrainData.TerrainPage.TerrainPatch.RefreshVertices = true;
}
}
/// <summary>
/// Changes the height of the selected vertices.
/// </summary>
public void numVertexHeight_ValueChanged()
{
if ( _updateData )
{
_terrainData.SetVertexHeight( (float) numVertexHeight.Value, false );
}
}
/// <summary>
/// Enables or disables soft selection.
/// </summary>
/// <param name="enable">Whether to enable soft selection.</param>
[LuaFunctionAttribute( "EnableSoftSelection", "Enables or disables soft selection.",
"Whether to enable soft selection." )]
public void EnableSoftSelection( bool enable )
{
if ( _updateData )
{
_terrainData.SoftSelection = enable;
_terrainData.TerrainPage.TerrainPatch.RefreshVertices = true;
}
}
/// <summary>
/// Enables or disables vertex selection.
/// </summary>
/// <param name="enable">Whether to enable vertex selection.</param>
[LuaFunctionAttribute( "EnableVertexSelection", "Enables or disables vertex selection.",
"Whether to enable vertex selection." )]
public void EnableVertexSelection( bool enable )
{
if ( enable && btnVertexSelection.BackColor == Color.FromKnownColor( KnownColor.Control ) )
btnVertexSelection_Click( this, new System.EventArgs() );
else if ( !enable && btnVertexSelection.BackColor == Color.FromKnownColor( KnownColor.ControlLight ) )
btnVertexSelection_Click( this, new System.EventArgs() );
}
#endregion
#region Algorithms
/// <summary>
/// Enables the vertex manipulation "Run Algorithm" button if an item is selected.
/// </summary>
public void lstVertices_Algorithms_SelectedIndexChanged()
{
if ( lstVertices_Algorithms.SelectedIndex > -1 )
btnVertices_RunAlgorithm.Enabled = true;
else
btnVertices_RunAlgorithm.Enabled = false;
}
/// <summary>
/// Runs the vertex manipulation "Run Algorithm" button if an item is being clicked.
/// </summary>
public void lstVertices_Algorithms_DoubleClick()
{
if ( lstVertices_Algorithms.SelectedIndex > -1 )
{
btnVertices_RunAlgorithm.Enabled = true;
btnVertices_RunAlgorithm_Click();
}
else
btnVertices_RunAlgorithm.Enabled = false;
}
/// <summary>
/// Runs the selected vertex manipulation algorithm.
/// </summary>
public void btnVertices_RunAlgorithm_Click()
{
if ( lstVertices_Algorithms.SelectedIndex > -1 )
_terrainData.RunPlugIn( lstVertices_Algorithms.SelectedIndex,
DataInterfacing.PlugIns.PlugInTypes.Vertices, _owner );
}
/// <summary>
/// Loads the list of vertex manipulation algorithms.
/// </summary>
public void LoadAlgorithms()
{
_verticesAlgorithms.Clear();
lstVertices_Algorithms.Items.Clear();
for ( int i = 0; i < _terrainData.PlugIns.VertexPlugIns.Count; i++ )
_verticesAlgorithms.Add( i.ToString(),
( (PlugIn) _terrainData.PlugIns.VertexPlugIns[i] ).GetName() );
foreach ( string key in _verticesAlgorithms.Keys )
lstVertices_Algorithms.Items.Add( _verticesAlgorithms.GetValues( key )[0] );
lstVertices_Algorithms.SelectedIndex = -1;
}
/// <summary>
/// Runs the vertex manipulation plug-in specified.
/// </summary>
/// <param name="name">The name of the plug-in to run.</param>
[LuaFunctionAttribute( "RunPlugIn", "Runs the vertex manipulation plug-in specified.",
"The name of the plug-in to run." )]
public void RunAlgorithm( string name )
{
bool found = false;
int count = 0;
while ( !found && lstVertices_Algorithms.Items[count].ToString() != name )
count++;
if ( found )
_terrainData.RunPlugIn( count, DataInterfacing.PlugIns.PlugInTypes.Vertices, _owner );
else
MessageBox.Show( "Vertex manipulation plug-in " + name + " could not be found! " );
}
/// <summary>
/// Runs the vertex manipulation plug-in specified in automatic mode.
/// </summary>
/// <param name="name">The name of the plug-in to run.</param>
/// <param name="filename">The name of the file to load into the plug-in.</param>
[LuaFunctionAttribute( "RunAutoPlugIn",
"Runs the vertex manipulation plug-in specified in automatic mode.",
"The name of the plug-in to run.", "The name of the file to load into the plug-in." )]
public void RunAutoAlgorithm( string name, string filename )
{
bool found = false;
int count = 0;
while ( !found && lstVertices_Algorithms.Items[count].ToString() != name )
count++;
if ( found )
_terrainData.RunPlugInAuto( count, DataInterfacing.PlugIns.PlugInTypes.Vertices,
_owner, filename );
else
MessageBox.Show( "Vertex manipulation plug-in " + name + " could not be found! " );
}
/// <summary>
/// Loads a new vertex manipulation plug-in.
/// </summary>
[LuaFunctionAttribute( "LoadPlugIn", "Loads a new vertex manipulation plug-in." )]
public void LoadAlgorithm()
{
_terrainData.LoadPlugIn( DataInterfacing.PlugIns.PlugInTypes.Vertices );
LoadAlgorithms();
}
#endregion
#region Modify Terrain Dimensions
/// <summary>
/// Changes the number of rows in the TerrainPatch.
/// </summary>
public void numVertices_Rows_ValueChanged()
{
if ( _updateData )
{
if ( chkVertices_GridDimensions.Checked )
{
_updateData = false;
numVertices_Columns.Value = numVertices_Rows.Value;
_updateData = true;
}
ChangeGridSize();
}
}
/// <summary>
/// Changes the number of columns in the TerrainPatch.
/// </summary>
public void numVertices_Columns_ValueChanged()
{
if ( _updateData )
{
if ( chkVertices_GridDimensions.Checked )
{
_updateData = false;
numVertices_Rows.Value = numVertices_Columns.Value;
_updateData = true;
}
ChangeGridSize();
}
}
/// <summary>
/// Changes whether the number of rows and the number of columns in the TerrainPatch must be equal.
/// </summary>
public void chkVertices_GridDimensions_CheckedChanged()
{
if ( _updateData && chkVertices_GridDimensions.Checked )
{
_updateData = false;
numVertices_Columns.Value = numVertices_Rows.Value;
_updateData = true;
ChangeGridSize();
}
}
/// <summary>
/// Changes the distance between columns in the TerrainPatch.
/// </summary>
public void numVertices_ColumnDistance_Leave()
{
if ( _updateData )
{
if ( chkVertices_GridSize.Checked )
{
_updateData = false;
numVertices_RowDistance.Value = numVertices_ColumnDistance.Value;
_updateData = true;
}
ChangeGridDimensions();
}
}
/// <summary>
/// Changes the distance between columns in the TerrainPatch.
/// </summary>
public void numVertices_RowDistance_Leave()
{
if ( _updateData )
{
if ( chkVertices_GridSize.Checked )
{
_updateData = false;
numVertices_ColumnDistance.Value = numVertices_RowDistance.Value;
_updateData = true;
}
ChangeGridDimensions();
}
}
/// <summary>
/// Changes whether the distance between rows and the distance between columns
/// in the TerrainPatch must be equal.
/// </summary>
public void chkVertices_GridSize_CheckedChanged()
{
if ( _updateData && chkVertices_GridSize.Checked )
{
_updateData = false;
numVertices_ColumnDistance.Value = numVertices_RowDistance.Value;
_updateData = true;
ChangeGridDimensions();
}
}
/// <summary>
/// Changes the maximum vertex height of the TerrainPatch.
/// </summary>
public void numMaxHeight_ValueChanged()
{
if ( _updateData )
{
_terrainData.UpdateMaximumTerrainHeight( (float) numMaxHeight.Value );
numVertexHeight.Maximum = numMaxHeight.Value;
}
}
/// <summary>
/// Activates the Maximum Vertex Height numeric.
/// </summary>
public void UpdateMaximumVertexHeight()
{
Vector3[] positions = _terrainData.TerrainPage.TerrainPatch.GetSelectedVertexPositions();
if ( positions.Length > 0 )
{
numVertexHeight.Enabled = true;
numVertexHeight.Value = Convert.ToDecimal( positions[0].Y );
}
else
{
_updateData = false;
numVertexHeight.Value = 0;
numVertexHeight.Enabled = false;
_updateData = true;
}
}
/// <summary>
/// Updates the maximum allowed vertex height in a TerrainPage.
/// </summary>
/// <param name="height">The maximum allowed vertex height.</param>
[LuaFunctionAttribute( "SetMaximumVertexHeight",
"Updates the maximum allowed vertex height in a TerrainPage.",
"The maximum allowed vertex height." )]
public void UpdateMaximumVertexHeight( float height )
{
_terrainData.UpdateMaximumTerrainHeight( height );
UpdateMaximumVertexHeight();
}
/// <summary>
/// Changes the size of the TerrainPatch grid.
/// </summary>
public void ChangeGridSize()
{
if ( _terrainData.TerrainPage != null )
{
if ( Convert.ToInt32( numVertices_Rows.Value ) != _terrainData.TerrainPage.TerrainPatch.Rows ||
Convert.ToInt32( numVertices_Columns.Value ) != _terrainData.TerrainPage.TerrainPatch.Columns )
{
string message = "By changing the number of vertex rows or columns, " +
"all vertices will be reset to their default positions.\n\n" +
"This means that all modifications of vertex positions will be overwritten.";
DialogResult result = MessageBox.Show( message,
"Data Will Be Lost!",
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning );
if ( result == DialogResult.OK )
_terrainData.UpdateTerrainSize( Convert.ToInt32( numVertices_Rows.Value ),
Convert.ToInt32( numVertices_Columns.Value ) );
else if ( result == DialogResult.Cancel )
{
_updateData = false;
numVertices_Rows.Value = _terrainData.TerrainPage.TerrainPatch.Rows;
numVertices_Columns.Value = _terrainData.TerrainPage.TerrainPatch.Columns;
_updateData = true;
}
}
}
}
/// <summary>
/// Changes the distance dimensions of the TerrainPatch.
/// </summary>
public void ChangeGridDimensions()
{
if ( _terrainData.TerrainPage != null )
{
if ( _terrainData.TerrainPage.TerrainPatch.Height != (float) numVertices_RowDistance.Value ||
_terrainData.TerrainPage.TerrainPatch.Width != (float) numVertices_ColumnDistance.Value )
{
_terrainData.UpdateTerrainDimensions( ( float ) numVertices_RowDistance.Value,
( float ) numVertices_ColumnDistance.Value );
if ( numVertices_RowDistance.Value > numVertices_ColumnDistance.Value )
_dx.Camera.FollowDistance = (float) numVertices_RowDistance.Value * 2f;
else
_dx.Camera.FollowDistance = (float) numVertices_ColumnDistance.Value * 2f;
_viewport.InitializeCamera();
}
}
}
#endregion
#region Other Terrain Functions
/// <summary>
/// Enables or disables the vertex editing tab group controls.
/// </summary>
/// <param name="enable">Whether to enable the tab group controls.</param>
[LuaFunctionAttribute( "EnableTerrainEditing",
"Enables or disables the vertex editing tab group controls.",
"Whether to enable the tab group controls." )]
public void EnableTerrainEditing( bool enable )
{
if ( !enable && btnVertexSelection.BackColor == Color.FromKnownColor( KnownColor.ControlLight ) )
btnVertexSelection_Click( this, new System.EventArgs() );
grpVertexCreation.Enabled = !enable;
grpVertexSelection.Enabled = enable;
grpVertexAlgorithms.Enabled = enable;
grpVertexDimensions.Enabled = enable;
grpVertexName.Enabled = enable;
if ( _terrainData.TerrainPage != null )
{
_updateData = false;
numVertices_Rows.Value = Convert.ToDecimal( _terrainData.TerrainPage.TerrainPatch.Rows );
numVertices_Columns.Value = Convert.ToDecimal( _terrainData.TerrainPage.TerrainPatch.Columns );
numVertices_RowDistance.Value =
Convert.ToDecimal( _terrainData.TerrainPage.TerrainPatch.Height );
numVertices_ColumnDistance.Value =
Convert.ToDecimal( _terrainData.TerrainPage.TerrainPatch.Width );
numMaxHeight.Value = Convert.ToDecimal( _terrainData.TerrainPage.MaximumVertexHeight );
_updateData = true;
if ( numVertices_Rows.Value == numVertices_Columns.Value )
chkVertices_GridDimensions.Checked = true;
else
chkVertices_GridDimensions.Checked = false;
if ( numVertices_RowDistance.Value == numVertices_ColumnDistance.Value )
chkVertices_GridSize.Checked = true;
else
chkVertices_GridSize.Checked = false;
if ( _terrainData.TerrainPage.TerrainPatch.Height >
_terrainData.TerrainPage.TerrainPatch.Width )
_dx.Camera.FollowDistance = _terrainData.TerrainPage.TerrainPatch.Height * 2.0f;
else
_dx.Camera.FollowDistance = _terrainData.TerrainPage.TerrainPatch.Width * 2.0f;
}
}
/// <summary>
/// Updates the control states.
/// </summary>
public void UpdateStates()
{
float val;
_updateData = false;
if ( _terrainData.TerrainPage != null )
{
// Update terrain editing
EnableTerrainEditing( true );
// Update terrain name
txtVertices_Name.Text = _terrainData.TerrainPage.Name;
// Enable soft selection
if ( _terrainData.SoftSelection )
{
radSingle.Checked = false;
radSoft.Checked = true;
}
else
{
radSingle.Checked = true;
radSoft.Checked = false;
}
// Update soft selection distance
val = (float) Math.Sqrt( (double) _terrainData.SoftSelectionDistanceSquared );
numSoft.Value = Convert.ToDecimal( val );
// Enable falloff
if ( _terrainData.Falloff )
chkFalloff.Checked = true;
else
chkFalloff.Checked = false;
// Update grid size
numVertices_Rows.Value = _terrainData.TerrainPage.TerrainPatch.Rows;
numVertices_Columns.Value = _terrainData.TerrainPage.TerrainPatch.Columns;
// Update grid dimensions
numVertices_RowDistance.Value =
Convert.ToDecimal( _terrainData.TerrainPage.TerrainPatch.Height );
numVertices_ColumnDistance.Value =
Convert.ToDecimal( _terrainData.TerrainPage.TerrainPatch.Width );
// Update maximum vertex height
numMaxHeight.Value = Convert.ToDecimal( _terrainData.TerrainPage.MaximumVertexHeight );
}
else
{
// Update terrain editing
EnableTerrainEditing( false );
// Update terrain name
txtVertices_Name.Text = "";
}
_updateData = true;
}
#endregion
#region Lua-Specific Functions
/// <summary>
/// Copies the currently selected vertex data (copies first selected vertex only).
/// </summary>
[LuaFunctionAttribute( "CopyVertex",
"Copies the currently selected vertex data (copies first selected vertex only)." )]
public void CopyVertex()
{
_terrainData.CopySelectedVertexPosition();
}
/// <summary>
/// Pastes copied vertex data onto the currently selected vertex (pastes one vertex only).
/// </summary>
[LuaFunctionAttribute( "PasteVertex",
"Pastes copied vertex data onto the currently selected vertex (pastes one vertex only)." )]
public void PasteVertex()
{
_terrainData.SetVertexHeight( _terrainData.VertexPositionCopy, true );
}
/// <summary>
/// Selects all vertices in the TerrainPage.
/// </summary>
[LuaFunctionAttribute( "SelectAllVertices", "Selects all vertices in the TerrainPage." )]
public void SelectAllVertices()
{
bool[] selected = new bool[_terrainData.TerrainPage.TerrainPatch.NumVertices];
for ( int i = 0; i < selected.Length; i++ )
selected[i] = true;
_terrainData.TerrainPage.TerrainPatch.SelectedVertices = selected;
_terrainData.TerrainPage.TerrainPatch.AreVerticesSelected = true;
}
/// <summary>
/// Selects the non-selected vertices and un-selects currently selected vertices.
/// </summary>
[LuaFunctionAttribute( "SelectInverseVertices",
"Selects the non-selected vertices and un-selects currently selected vertices." )]
public void SelectInverseVertices()
{
bool[] selected = _terrainData.TerrainPage.TerrainPatch.SelectedVertices;
for ( int i = 0; i < selected.Length; i++ )
selected[i] = !selected[i];
_terrainData.TerrainPage.TerrainPatch.SelectedVertices = selected;
_terrainData.TerrainPage.TerrainPatch.AreVerticesSelected = true;
}
/// <summary>
/// Selects the specified vertex.
/// </summary>
/// <param name="vertex">Index of the vertex.</param>
/// <param name="endSelection">Whether to enable clearing selected vertices if one is not selected.</param>
[LuaFunctionAttribute( "SelectVertexByIndex", "Selects the specified vertex.",
"Index of the vertex.", "Whether to enable clearing selected vertices if one is not selected." )]
public void SelectVertex( int vertex, bool endSelection )
{
_terrainData.SelectVertex( vertex, endSelection );
}
/// <summary>
/// Selects the specified vertex.
/// </summary>
/// <param name="row">Row of the vertex.</param>
/// <param name="column">Column of the vertex.</param>
/// <param name="endSelection">Whether to enable clearing selected vertices if one is not selected.</param>
[LuaFunctionAttribute( "SelectVertex", "Selects the specified vertex.",
"Row of the vertex.", "Column of the vertex.",
"Whether to enable clearing selected vertices if one is not selected." )]
public void SelectVertex( int row, int column, bool endSelection )
{
SelectVertex( _terrainData.TerrainPage.TerrainPatch.Rows * row + column, endSelection );
}
/// <summary>
/// Moves the selected vertices.
/// </summary>
/// <param name="distChange">The change in distance to move selected vertices.</param>
[LuaFunctionAttribute( "MoveVertices", "Moves the selected vertices.",
"The change in distance to move selected vertices." )]
public void MoveVertices( float distChange )
{
_terrainData.MoveVertices( false, distChange );
_terrainData.MoveVertices( true, 0.0f );
}
/// <summary>
/// Sets the soft selection distance for terrain movement.
/// </summary>
/// <param name="distance">The soft selection distance.</param>
[LuaFunctionAttribute( "SetSoftSelectionDistance", "Sets the soft selection distance.",
"The soft selection distance." )]
public void SetSoftSelectionDistance( float distance )
{
_updateData = false;
numSoft.Value = Convert.ToDecimal( distance );
_updateData = true;
_terrainData.SoftSelectionDistanceSquared = distance * distance;
_terrainData.TerrainPage.TerrainPatch.RefreshVertices = true;
}
/// <summary>
/// Enables or disables falloff.
/// </summary>
/// <param name="enable">Whether to enable or disable falloff.</param>
[LuaFunctionAttribute( "EnableFalloff", "Enables or disables falloff.",
"Whether to enable or disable falloff." )]
public void EnableFalloff( bool enable )
{
_updateData = false;
chkFalloff.Checked = enable;
_updateData = true;
_terrainData.Falloff = chkFalloff.Checked;
_terrainData.TerrainPage.TerrainPatch.RefreshVertices = true;
}
#endregion
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.grpVertexName = new System.Windows.Forms.GroupBox();
this.btnVertices_Name = new System.Windows.Forms.Button();
this.txtVertices_Name = new System.Windows.Forms.TextBox();
this.grpVertexDimensions = new System.Windows.Forms.GroupBox();
this.numMaxHeight = new System.Windows.Forms.NumericUpDown();
this.label6 = new System.Windows.Forms.Label();
this.chkVertices_GridSize = new System.Windows.Forms.CheckBox();
this.numVertices_RowDistance = new System.Windows.Forms.NumericUpDown();
this.label4 = new System.Windows.Forms.Label();
this.numVertices_ColumnDistance = new System.Windows.Forms.NumericUpDown();
this.label5 = new System.Windows.Forms.Label();
this.chkVertices_GridDimensions = new System.Windows.Forms.CheckBox();
this.numVertices_Columns = new System.Windows.Forms.NumericUpDown();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.numVertices_Rows = new System.Windows.Forms.NumericUpDown();
this.grpVertexCreation = new System.Windows.Forms.GroupBox();
this.btnVertices_Create = new System.Windows.Forms.Button();
this.grpVertexSelection = new System.Windows.Forms.GroupBox();
this.chkFalloff = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.numSoft = new System.Windows.Forms.NumericUpDown();
this.radSoft = new System.Windows.Forms.RadioButton();
this.btnVertexSelection = new System.Windows.Forms.Button();
this.radSingle = new System.Windows.Forms.RadioButton();
this.grpVertexAlgorithms = new System.Windows.Forms.GroupBox();
this.btnVertices_LoadAlgorithm = new System.Windows.Forms.Button();
this.btnVertices_RunAlgorithm = new System.Windows.Forms.Button();
this.lstVertices_Algorithms = new System.Windows.Forms.ListBox();
this.label7 = new System.Windows.Forms.Label();
this.numVertexHeight = new System.Windows.Forms.NumericUpDown();
this.grpVertexName.SuspendLayout();
this.grpVertexDimensions.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numMaxHeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numVertices_RowDistance)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numVertices_ColumnDistance)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numVertices_Columns)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numVertices_Rows)).BeginInit();
this.grpVertexCreation.SuspendLayout();
this.grpVertexSelection.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numSoft)).BeginInit();
this.grpVertexAlgorithms.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numVertexHeight)).BeginInit();
this.SuspendLayout();
//
// grpVertexName
//
this.grpVertexName.Controls.Add(this.btnVertices_Name);
this.grpVertexName.Controls.Add(this.txtVertices_Name);
this.grpVertexName.Enabled = false;
this.grpVertexName.Location = new System.Drawing.Point(8, 64);
this.grpVertexName.Name = "grpVertexName";
this.grpVertexName.Size = new System.Drawing.Size(160, 72);
this.grpVertexName.TabIndex = 10;
this.grpVertexName.TabStop = false;
this.grpVertexName.Text = "Terrain Page Name:";
//
// btnVertices_Name
//
this.btnVertices_Name.Location = new System.Drawing.Point(8, 40);
this.btnVertices_Name.Name = "btnVertices_Name";
this.btnVertices_Name.Size = new System.Drawing.Size(144, 23);
this.btnVertices_Name.TabIndex = 1;
this.btnVertices_Name.Text = "Update Terrain Name";
this.btnVertices_Name.Click += new System.EventHandler(this.btnVertices_Name_Click);
//
// txtVertices_Name
//
this.txtVertices_Name.Location = new System.Drawing.Point(8, 16);
this.txtVertices_Name.Name = "txtVertices_Name";
this.txtVertices_Name.Size = new System.Drawing.Size(144, 20);
this.txtVertices_Name.TabIndex = 0;
this.txtVertices_Name.Text = "";
this.txtVertices_Name.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtVertices_Name_KeyUp);
//
// grpVertexDimensions
//
this.grpVertexDimensions.Controls.Add(this.numMaxHeight);
this.grpVertexDimensions.Controls.Add(this.label6);
this.grpVertexDimensions.Controls.Add(this.chkVertices_GridSize);
this.grpVertexDimensions.Controls.Add(this.numVertices_RowDistance);
this.grpVertexDimensions.Controls.Add(this.label4);
this.grpVertexDimensions.Controls.Add(this.numVertices_ColumnDistance);
this.grpVertexDimensions.Controls.Add(this.label5);
this.grpVertexDimensions.Controls.Add(this.chkVertices_GridDimensions);
this.grpVertexDimensions.Controls.Add(this.numVertices_Columns);
this.grpVertexDimensions.Controls.Add(this.label3);
this.grpVertexDimensions.Controls.Add(this.label2);
this.grpVertexDimensions.Controls.Add(this.numVertices_Rows);
this.grpVertexDimensions.Enabled = false;
this.grpVertexDimensions.Location = new System.Drawing.Point(8, 512);
this.grpVertexDimensions.Name = "grpVertexDimensions";
this.grpVertexDimensions.Size = new System.Drawing.Size(160, 216);
this.grpVertexDimensions.TabIndex = 9;
this.grpVertexDimensions.TabStop = false;
this.grpVertexDimensions.Text = "Modify Terrain Dimensions";
//
// numMaxHeight
//
this.numMaxHeight.DecimalPlaces = 3;
this.numMaxHeight.Increment = new System.Decimal(new int[] {
1,
0,
0,
196608});
this.numMaxHeight.Location = new System.Drawing.Point(40, 184);
this.numMaxHeight.Maximum = new System.Decimal(new int[] {
100000,
0,
0,
0});
this.numMaxHeight.Name = "numMaxHeight";
this.numMaxHeight.Size = new System.Drawing.Size(104, 20);
this.numMaxHeight.TabIndex = 20;
this.numMaxHeight.Value = new System.Decimal(new int[] {
1,
0,
0,
0});
this.numMaxHeight.ValueChanged += new System.EventHandler(this.numMaxHeight_ValueChanged);
this.numMaxHeight.Leave += new System.EventHandler(this.numMaxHeight_Leave);
//
// label6
//
this.label6.Location = new System.Drawing.Point(8, 168);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(136, 16);
this.label6.TabIndex = 19;
this.label6.Text = "Maximum Vertex Height:";
//
// chkVertices_GridSize
//
this.chkVertices_GridSize.Checked = true;
this.chkVertices_GridSize.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkVertices_GridSize.Location = new System.Drawing.Point(16, 136);
this.chkVertices_GridSize.Name = "chkVertices_GridSize";
this.chkVertices_GridSize.Size = new System.Drawing.Size(112, 16);
this.chkVertices_GridSize.TabIndex = 18;
this.chkVertices_GridSize.Text = "Lock Terrain Size";
this.chkVertices_GridSize.CheckedChanged += new System.EventHandler(this.chkVertices_GridSize_CheckedChanged);
//
// numVertices_RowDistance
//
this.numVertices_RowDistance.DecimalPlaces = 2;
this.numVertices_RowDistance.Increment = new System.Decimal(new int[] {
1,
0,
0,
131072});
this.numVertices_RowDistance.Location = new System.Drawing.Point(72, 112);
this.numVertices_RowDistance.Maximum = new System.Decimal(new int[] {
1000,
0,
0,
0});
this.numVertices_RowDistance.Minimum = new System.Decimal(new int[] {
1,
0,
0,
131072});
this.numVertices_RowDistance.Name = "numVertices_RowDistance";
this.numVertices_RowDistance.Size = new System.Drawing.Size(56, 20);
this.numVertices_RowDistance.TabIndex = 17;
this.numVertices_RowDistance.Value = new System.Decimal(new int[] {
10,
0,
0,
65536});
this.numVertices_RowDistance.ValueChanged += new System.EventHandler(this.numVertices_RowDistance_ValueChanged);
this.numVertices_RowDistance.Leave += new System.EventHandler(this.numVertices_RowDistance_Leave);
//
// label4
//
this.label4.Location = new System.Drawing.Point(16, 112);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(40, 23);
this.label4.TabIndex = 16;
this.label4.Text = "Width:";
//
// numVertices_ColumnDistance
//
this.numVertices_ColumnDistance.DecimalPlaces = 2;
this.numVertices_ColumnDistance.Increment = new System.Decimal(new int[] {
1,
0,
0,
131072});
this.numVertices_ColumnDistance.Location = new System.Drawing.Point(72, 88);
this.numVertices_ColumnDistance.Maximum = new System.Decimal(new int[] {
1000,
0,
0,
0});
this.numVertices_ColumnDistance.Minimum = new System.Decimal(new int[] {
1,
0,
0,
131072});
this.numVertices_ColumnDistance.Name = "numVertices_ColumnDistance";
this.numVertices_ColumnDistance.Size = new System.Drawing.Size(56, 20);
this.numVertices_ColumnDistance.TabIndex = 15;
this.numVertices_ColumnDistance.Value = new System.Decimal(new int[] {
100,
0,
0,
131072});
this.numVertices_ColumnDistance.ValueChanged += new System.EventHandler(this.numVertices_ColumnDistance_ValueChanged);
this.numVertices_ColumnDistance.Leave += new System.EventHandler(this.numVertices_ColumnDistance_Leave);
//
// label5
//
this.label5.Location = new System.Drawing.Point(16, 88);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(48, 23);
this.label5.TabIndex = 14;
this.label5.Text = "Height:";
//
// chkVertices_GridDimensions
//
this.chkVertices_GridDimensions.Checked = true;
this.chkVertices_GridDimensions.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkVertices_GridDimensions.Location = new System.Drawing.Point(16, 64);
this.chkVertices_GridDimensions.Name = "chkVertices_GridDimensions";
this.chkVertices_GridDimensions.Size = new System.Drawing.Size(136, 16);
this.chkVertices_GridDimensions.TabIndex = 10;
this.chkVertices_GridDimensions.Text = "Lock Grid Dimensions";
this.chkVertices_GridDimensions.CheckedChanged += new System.EventHandler(this.chkVertices_GridDimensions_CheckedChanged);
//
// numVertices_Columns
//
this.numVertices_Columns.Location = new System.Drawing.Point(72, 40);
this.numVertices_Columns.Maximum = new System.Decimal(new int[] {
1000,
0,
0,
0});
this.numVertices_Columns.Minimum = new System.Decimal(new int[] {
2,
0,
0,
0});
this.numVertices_Columns.Name = "numVertices_Columns";
this.numVertices_Columns.Size = new System.Drawing.Size(56, 20);
this.numVertices_Columns.TabIndex = 7;
this.numVertices_Columns.Value = new System.Decimal(new int[] {
5,
0,
0,
0});
this.numVertices_Columns.ValueChanged += new System.EventHandler(this.numVertices_Columns_ValueChanged);
this.numVertices_Columns.Leave += new System.EventHandler(this.numVertices_Columns_Leave);
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 40);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(56, 23);
this.label3.TabIndex = 8;
this.label3.Text = "Columns:";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(40, 23);
this.label2.TabIndex = 6;
this.label2.Text = "Rows:";
//
// numVertices_Rows
//
this.numVertices_Rows.Location = new System.Drawing.Point(72, 16);
this.numVertices_Rows.Maximum = new System.Decimal(new int[] {
1000,
0,
0,
0});
this.numVertices_Rows.Minimum = new System.Decimal(new int[] {
2,
0,
0,
0});
this.numVertices_Rows.Name = "numVertices_Rows";
this.numVertices_Rows.Size = new System.Drawing.Size(56, 20);
this.numVertices_Rows.TabIndex = 5;
this.numVertices_Rows.Value = new System.Decimal(new int[] {
5,
0,
0,
0});
this.numVertices_Rows.ValueChanged += new System.EventHandler(this.numVertices_Rows_ValueChanged);
this.numVertices_Rows.Leave += new System.EventHandler(this.numVertices_Rows_Leave);
//
// grpVertexCreation
//
this.grpVertexCreation.Controls.Add(this.btnVertices_Create);
this.grpVertexCreation.Location = new System.Drawing.Point(8, 8);
this.grpVertexCreation.Name = "grpVertexCreation";
this.grpVertexCreation.Size = new System.Drawing.Size(160, 48);
this.grpVertexCreation.TabIndex = 8;
this.grpVertexCreation.TabStop = false;
this.grpVertexCreation.Text = "Terrain Creation";
//
// btnVertices_Create
//
this.btnVertices_Create.Location = new System.Drawing.Point(8, 16);
this.btnVertices_Create.Name = "btnVertices_Create";
this.btnVertices_Create.Size = new System.Drawing.Size(144, 23);
this.btnVertices_Create.TabIndex = 0;
this.btnVertices_Create.Text = "Create Terrain";
this.btnVertices_Create.Click += new System.EventHandler(this.btnVertices_Create_Click);
//
// grpVertexSelection
//
this.grpVertexSelection.Controls.Add(this.numVertexHeight);
this.grpVertexSelection.Controls.Add(this.label7);
this.grpVertexSelection.Controls.Add(this.chkFalloff);
this.grpVertexSelection.Controls.Add(this.label1);
this.grpVertexSelection.Controls.Add(this.numSoft);
this.grpVertexSelection.Controls.Add(this.radSoft);
this.grpVertexSelection.Controls.Add(this.btnVertexSelection);
this.grpVertexSelection.Controls.Add(this.radSingle);
this.grpVertexSelection.Enabled = false;
this.grpVertexSelection.Location = new System.Drawing.Point(8, 144);
this.grpVertexSelection.Name = "grpVertexSelection";
this.grpVertexSelection.Size = new System.Drawing.Size(160, 192);
this.grpVertexSelection.TabIndex = 6;
this.grpVertexSelection.TabStop = false;
this.grpVertexSelection.Text = "Vertex Selection";
//
// chkFalloff
//
this.chkFalloff.Checked = true;
this.chkFalloff.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkFalloff.Enabled = false;
this.chkFalloff.Location = new System.Drawing.Point(16, 120);
this.chkFalloff.Name = "chkFalloff";
this.chkFalloff.TabIndex = 5;
this.chkFalloff.Text = "Use Falloff";
this.chkFalloff.CheckedChanged += new System.EventHandler(this.chkFalloff_CheckedChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 96);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 23);
this.label1.TabIndex = 4;
this.label1.Text = "Distance:";
//
// numSoft
//
this.numSoft.DecimalPlaces = 3;
this.numSoft.Enabled = false;
this.numSoft.Increment = new System.Decimal(new int[] {
1,
0,
0,
196608});
this.numSoft.Location = new System.Drawing.Point(80, 96);
this.numSoft.Name = "numSoft";
this.numSoft.Size = new System.Drawing.Size(72, 20);
this.numSoft.TabIndex = 3;
this.numSoft.ValueChanged += new System.EventHandler(this.numSoft_ValueChanged);
//
// radSoft
//
this.radSoft.Enabled = false;
this.radSoft.Location = new System.Drawing.Point(8, 64);
this.radSoft.Name = "radSoft";
this.radSoft.Size = new System.Drawing.Size(136, 24);
this.radSoft.TabIndex = 2;
this.radSoft.Text = "Blend Nearby Vertices";
this.radSoft.Click += new System.EventHandler(this.radSoft_CheckedChanged);
//
// btnVertexSelection
//
this.btnVertexSelection.BackColor = System.Drawing.SystemColors.Control;
this.btnVertexSelection.Location = new System.Drawing.Point(8, 16);
this.btnVertexSelection.Name = "btnVertexSelection";
this.btnVertexSelection.Size = new System.Drawing.Size(144, 24);
this.btnVertexSelection.TabIndex = 0;
this.btnVertexSelection.Text = "Enable Vertex Selection";
this.btnVertexSelection.Click += new System.EventHandler(this.btnVertexSelection_Click);
//
// radSingle
//
this.radSingle.Checked = true;
this.radSingle.Enabled = false;
this.radSingle.Location = new System.Drawing.Point(8, 40);
this.radSingle.Name = "radSingle";
this.radSingle.TabIndex = 1;
this.radSingle.TabStop = true;
this.radSingle.Text = "Single Vertex";
this.radSingle.Click += new System.EventHandler(this.radSingle_CheckedChanged);
//
// grpVertexAlgorithms
//
this.grpVertexAlgorithms.Controls.Add(this.btnVertices_LoadAlgorithm);
this.grpVertexAlgorithms.Controls.Add(this.btnVertices_RunAlgorithm);
this.grpVertexAlgorithms.Controls.Add(this.lstVertices_Algorithms);
this.grpVertexAlgorithms.Enabled = false;
this.grpVertexAlgorithms.Location = new System.Drawing.Point(8, 344);
this.grpVertexAlgorithms.Name = "grpVertexAlgorithms";
this.grpVertexAlgorithms.Size = new System.Drawing.Size(160, 160);
this.grpVertexAlgorithms.TabIndex = 7;
this.grpVertexAlgorithms.TabStop = false;
this.grpVertexAlgorithms.Text = "Algorithms";
//
// btnVertices_LoadAlgorithm
//
this.btnVertices_LoadAlgorithm.Location = new System.Drawing.Point(8, 128);
this.btnVertices_LoadAlgorithm.Name = "btnVertices_LoadAlgorithm";
this.btnVertices_LoadAlgorithm.Size = new System.Drawing.Size(144, 23);
this.btnVertices_LoadAlgorithm.TabIndex = 2;
this.btnVertices_LoadAlgorithm.Text = "Load New Algorithm";
this.btnVertices_LoadAlgorithm.Click += new System.EventHandler(this.btnVertices_LoadAlgorithm_Click);
//
// btnVertices_RunAlgorithm
//
this.btnVertices_RunAlgorithm.Enabled = false;
this.btnVertices_RunAlgorithm.Location = new System.Drawing.Point(8, 96);
this.btnVertices_RunAlgorithm.Name = "btnVertices_RunAlgorithm";
this.btnVertices_RunAlgorithm.Size = new System.Drawing.Size(144, 23);
this.btnVertices_RunAlgorithm.TabIndex = 1;
this.btnVertices_RunAlgorithm.Text = "Run Algorithm";
this.btnVertices_RunAlgorithm.Click += new System.EventHandler(this.btnVertices_RunAlgorithm_Click);
//
// lstVertices_Algorithms
//
this.lstVertices_Algorithms.Location = new System.Drawing.Point(8, 16);
this.lstVertices_Algorithms.Name = "lstVertices_Algorithms";
this.lstVertices_Algorithms.Size = new System.Drawing.Size(144, 69);
this.lstVertices_Algorithms.TabIndex = 0;
this.lstVertices_Algorithms.DoubleClick += new System.EventHandler(this.lstVertices_Algorithms_DoubleClick);
this.lstVertices_Algorithms.SelectedIndexChanged += new System.EventHandler(this.lstVertices_Algorithms_SelectedIndexChanged);
//
// label7
//
this.label7.Location = new System.Drawing.Point(8, 152);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(112, 32);
this.label7.TabIndex = 6;
this.label7.Text = "Current Vertex Height:";
//
// numVertexHeight
//
this.numVertexHeight.DecimalPlaces = 3;
this.numVertexHeight.Enabled = false;
this.numVertexHeight.Increment = new System.Decimal(new int[] {
1,
0,
0,
196608});
this.numVertexHeight.Location = new System.Drawing.Point(88, 160);
this.numVertexHeight.Name = "numVertexHeight";
this.numVertexHeight.Size = new System.Drawing.Size(64, 20);
this.numVertexHeight.TabIndex = 7;
this.numVertexHeight.ValueChanged += new System.EventHandler(this.numVertexHeight_ValueChanged);
this.numVertexHeight.Leave += new System.EventHandler(this.numVertexHeight_Leave);
//
// VertexManipulation
//
this.Controls.Add(this.grpVertexName);
this.Controls.Add(this.grpVertexDimensions);
this.Controls.Add(this.grpVertexCreation);
this.Controls.Add(this.grpVertexSelection);
this.Controls.Add(this.grpVertexAlgorithms);
this.Name = "VertexManipulation";
this.Size = new System.Drawing.Size(176, 736);
this.grpVertexName.ResumeLayout(false);
this.grpVertexDimensions.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numMaxHeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numVertices_RowDistance)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numVertices_ColumnDistance)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numVertices_Columns)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numVertices_Rows)).EndInit();
this.grpVertexCreation.ResumeLayout(false);
this.grpVertexSelection.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numSoft)).EndInit();
this.grpVertexAlgorithms.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numVertexHeight)).EndInit();
this.ResumeLayout(false);
}
#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 Lucene.Net.Support;
using NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using MaxFieldLength = Lucene.Net.Index.IndexWriter.MaxFieldLength;
using QueryParser = Lucene.Net.QueryParsers.QueryParser;
using Directory = Lucene.Net.Store.Directory;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using TimeExceededException = Lucene.Net.Search.TimeLimitingCollector.TimeExceededException;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Search
{
/// <summary> Tests the {@link TimeLimitingCollector}. This test checks (1) search
/// correctness (regardless of timeout), (2) expected timeout behavior,
/// and (3) a sanity test with multiple searching threads.
/// </summary>
[TestFixture]
public class TestTimeLimitingCollector:LuceneTestCase
{
private class AnonymousClassThread:ThreadClass
{
public AnonymousClassThread(bool withTimeout, System.Collections.BitArray success, int num, TestTimeLimitingCollector enclosingInstance)
{
InitBlock(withTimeout, success, num, enclosingInstance);
}
private void InitBlock(bool withTimeout, System.Collections.BitArray success, int num, TestTimeLimitingCollector enclosingInstance)
{
this.withTimeout = withTimeout;
this.success = success;
this.num = num;
this.enclosingInstance = enclosingInstance;
}
private bool withTimeout;
private System.Collections.BitArray success;
private int num;
private TestTimeLimitingCollector enclosingInstance;
public TestTimeLimitingCollector Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
override public void Run()
{
if (withTimeout)
{
Enclosing_Instance.DoTestTimeout(true, true);
}
else
{
Enclosing_Instance.DoTestSearch();
}
lock (success.SyncRoot)
{
success.Set(num, true);
}
}
}
private const int SLOW_DOWN = 47;
private static readonly long TIME_ALLOWED = 17 * SLOW_DOWN; // so searches can find about 17 docs.
// max time allowed is relaxed for multithreading tests.
// the multithread case fails when setting this to 1 (no slack) and launching many threads (>2000).
// but this is not a real failure, just noise.
private const double MULTI_THREAD_SLACK = 7;
private const int N_DOCS = 3000;
private const int N_THREADS = 50;
private Searcher searcher;
private System.String FIELD_NAME = "body";
private Query query;
/*public TestTimeLimitingCollector(System.String name):base(name)
{
}*/
/// <summary> initializes searcher with a document set</summary>
[SetUp]
public override void SetUp()
{
base.SetUp();
System.String[] docText = new System.String[]{"docThatNeverMatchesSoWeCanRequireLastDocCollectedToBeGreaterThanZero", "one blah three", "one foo three multiOne", "one foobar three multiThree", "blueberry pancakes", "blueberry pie", "blueberry strudel", "blueberry pizza"};
Directory directory = new RAMDirectory();
IndexWriter iw = new IndexWriter(directory, new WhitespaceAnalyzer(), true, MaxFieldLength.UNLIMITED);
for (int i = 0; i < N_DOCS; i++)
{
Add(docText[i % docText.Length], iw);
}
iw.Close();
searcher = new IndexSearcher(directory, true);
System.String qtxt = "one";
// start from 1, so that the 0th doc never matches
for (int i = 0; i < docText.Length; i++)
{
qtxt += (' ' + docText[i]); // large query so that search will be longer
}
QueryParser queryParser = new QueryParser(Util.Version.LUCENE_CURRENT, FIELD_NAME, new WhitespaceAnalyzer());
query = queryParser.Parse(qtxt);
// warm the searcher
searcher.Search(query, null, 1000);
}
[TearDown]
public override void TearDown()
{
searcher.Close();
base.TearDown();
}
private void Add(System.String value_Renamed, IndexWriter iw)
{
Document d = new Document();
d.Add(new Field(FIELD_NAME, value_Renamed, Field.Store.NO, Field.Index.ANALYZED));
iw.AddDocument(d);
}
private void Search(Collector collector)
{
searcher.Search(query, collector);
}
/// <summary> test search correctness with no timeout</summary>
[Test]
public virtual void TestSearch()
{
DoTestSearch();
}
private void DoTestSearch()
{
int totalResults = 0;
int totalTLCResults = 0;
try
{
MyHitCollector myHc = new MyHitCollector(this);
Search(myHc);
totalResults = myHc.HitCount();
myHc = new MyHitCollector(this);
long oneHour = 3600000;
Collector tlCollector = CreateTimedCollector(myHc, oneHour, false);
Search(tlCollector);
totalTLCResults = myHc.HitCount();
}
catch (System.Exception e)
{
System.Console.Error.WriteLine(e.StackTrace);
Assert.IsTrue(false, "Unexpected exception: " + e); //==fail
}
Assert.AreEqual(totalResults, totalTLCResults, "Wrong number of results!");
}
private Collector CreateTimedCollector(MyHitCollector hc, long timeAllowed, bool greedy)
{
TimeLimitingCollector res = new TimeLimitingCollector(hc, timeAllowed);
res.IsGreedy = greedy; // set to true to make sure at least one doc is collected.
return res;
}
/// <summary> Test that timeout is obtained, and soon enough!</summary>
[Test]
public virtual void TestTimeoutGreedy()
{
DoTestTimeout(false, true);
}
/// <summary> Test that timeout is obtained, and soon enough!</summary>
[Test]
public virtual void TestTimeoutNotGreedy()
{
DoTestTimeout(false, false);
}
private void DoTestTimeout(bool multiThreaded, bool greedy)
{
// setup
MyHitCollector myHc = new MyHitCollector(this);
myHc.SetSlowDown(SLOW_DOWN);
Collector tlCollector = CreateTimedCollector(myHc, TIME_ALLOWED, greedy);
// search
TimeExceededException timoutException = null;
try
{
Search(tlCollector);
}
catch (TimeExceededException x)
{
timoutException = x;
}
catch (System.Exception e)
{
Assert.IsTrue(false, "Unexpected exception: " + e); //==fail
}
// must get exception
Assert.IsNotNull(timoutException, "Timeout expected!");
// greediness affect last doc collected
int exceptionDoc = timoutException.LastDocCollected;
int lastCollected = myHc.GetLastDocCollected();
Assert.IsTrue(exceptionDoc > 0, "doc collected at timeout must be > 0!");
if (greedy)
{
Assert.IsTrue(exceptionDoc == lastCollected, "greedy=" + greedy + " exceptionDoc=" + exceptionDoc + " != lastCollected=" + lastCollected);
Assert.IsTrue(myHc.HitCount() > 0, "greedy, but no hits found!");
}
else
{
Assert.IsTrue(exceptionDoc > lastCollected, "greedy=" + greedy + " exceptionDoc=" + exceptionDoc + " not > lastCollected=" + lastCollected);
}
// verify that elapsed time at exception is within valid limits
Assert.AreEqual(timoutException.TimeAllowed, TIME_ALLOWED);
// a) Not too early
Assert.IsTrue(timoutException.TimeElapsed > TIME_ALLOWED - TimeLimitingCollector.Resolution, "elapsed=" + timoutException.TimeElapsed + " <= (allowed-resolution)=" + (TIME_ALLOWED - TimeLimitingCollector.Resolution));
// b) Not too late.
// This part is problematic in a busy test system, so we just print a warning.
// We already verified that a timeout occurred, we just can't be picky about how long it took.
if (timoutException.TimeElapsed > MaxTime(multiThreaded))
{
System.Console.Out.WriteLine("Informative: timeout exceeded (no action required: most probably just " + " because the test machine is slower than usual): " + "lastDoc=" + exceptionDoc + " ,&& allowed=" + timoutException.TimeAllowed + " ,&& elapsed=" + timoutException.TimeElapsed + " >= " + MaxTimeStr(multiThreaded));
}
}
private long MaxTime(bool multiThreaded)
{
long res = 2 * TimeLimitingCollector.Resolution + TIME_ALLOWED + SLOW_DOWN; // some slack for less noise in this test
if (multiThreaded)
{
res = (long) (res * MULTI_THREAD_SLACK); // larger slack
}
return res;
}
private System.String MaxTimeStr(bool multiThreaded)
{
System.String s = "( " + "2*resolution + TIME_ALLOWED + SLOW_DOWN = " + "2*" + TimeLimitingCollector.Resolution + " + " + TIME_ALLOWED + " + " + SLOW_DOWN + ")";
if (multiThreaded)
{
s = MULTI_THREAD_SLACK + " * " + s;
}
return MaxTime(multiThreaded) + " = " + s;
}
/// <summary> Test timeout behavior when resolution is modified. </summary>
[Test]
public virtual void TestModifyResolution()
{
try
{
// increase and test
uint resolution = 20 * TimeLimitingCollector.DEFAULT_RESOLUTION; //400
TimeLimitingCollector.Resolution = resolution;
Assert.AreEqual(resolution, TimeLimitingCollector.Resolution);
DoTestTimeout(false, true);
// decrease much and test
resolution = 5;
TimeLimitingCollector.Resolution = resolution;
Assert.AreEqual(resolution, TimeLimitingCollector.Resolution);
DoTestTimeout(false, true);
// return to default and test
resolution = TimeLimitingCollector.DEFAULT_RESOLUTION;
TimeLimitingCollector.Resolution = resolution;
Assert.AreEqual(resolution, TimeLimitingCollector.Resolution);
DoTestTimeout(false, true);
}
finally
{
TimeLimitingCollector.Resolution = TimeLimitingCollector.DEFAULT_RESOLUTION;
}
}
/// <summary> Test correctness with multiple searching threads.</summary>
[Test]
public virtual void TestSearchMultiThreaded()
{
DoTestMultiThreads(false);
}
/// <summary> Test correctness with multiple searching threads.</summary>
[Test]
public virtual void TestTimeoutMultiThreaded()
{
DoTestMultiThreads(true);
}
private void DoTestMultiThreads(bool withTimeout)
{
ThreadClass[] threadArray = new ThreadClass[N_THREADS];
System.Collections.BitArray success = new System.Collections.BitArray((N_THREADS % 64 == 0?N_THREADS / 64:N_THREADS / 64 + 1) * 64);
for (int i = 0; i < threadArray.Length; ++i)
{
int num = i;
threadArray[num] = new AnonymousClassThread(withTimeout, success, num, this);
}
for (int i = 0; i < threadArray.Length; ++i)
{
threadArray[i].Start();
}
for (int i = 0; i < threadArray.Length; ++i)
{
threadArray[i].Join();
}
Assert.AreEqual(N_THREADS, BitSetSupport.Cardinality(success), "some threads failed!");
}
// counting collector that can slow down at collect().
private class MyHitCollector:Collector
{
public MyHitCollector(TestTimeLimitingCollector enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(TestTimeLimitingCollector enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private TestTimeLimitingCollector enclosingInstance;
public TestTimeLimitingCollector Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private System.Collections.BitArray bits = new System.Collections.BitArray(64);
private int slowdown = 0;
private int lastDocCollected = - 1;
private int docBase = 0;
/// <summary> amount of time to wait on each collect to simulate a long iteration</summary>
public virtual void SetSlowDown(int milliseconds)
{
slowdown = milliseconds;
}
public virtual int HitCount()
{
return BitSetSupport.Cardinality(bits);
}
public virtual int GetLastDocCollected()
{
return lastDocCollected;
}
public override void SetScorer(Scorer scorer)
{
// scorer is not needed
}
public override void Collect(int doc)
{
int docId = doc + docBase;
if (slowdown > 0)
{
try
{
System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * slowdown));
}
catch (System.Threading.ThreadInterruptedException ie)
{
throw;
}
}
System.Diagnostics.Debug.Assert(docId >= 0, "base=" + docBase + " doc=" + doc);
bits.Length = Math.Max(bits.Length, docId + 1);
bits.Set(docId, true);
lastDocCollected = docId;
}
public override void SetNextReader(IndexReader reader, int base_Renamed)
{
docBase = base_Renamed;
}
public override bool AcceptsDocsOutOfOrder
{
get { return false; }
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenMetaverse;
using log4net;
namespace OpenSim.Region.CoreModules.World.Estate
{
public class EstateRequestHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected XEstateModule m_EstateModule;
protected Object m_RequestLock = new Object();
public EstateRequestHandler(XEstateModule fmodule)
: base("POST", "/estate")
{
m_EstateModule = fmodule;
}
protected override byte[] ProcessRequest(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("[XESTATE HANDLER]: query String: {0}", body);
try
{
lock (m_RequestLock)
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"].ToString();
request.Remove("METHOD");
try
{
m_EstateModule.InInfoUpdate = false;
switch (method)
{
case "update_covenant":
return UpdateCovenant(request);
case "update_estate":
return UpdateEstate(request);
case "estate_message":
return EstateMessage(request);
case "teleport_home_one_user":
return TeleportHomeOneUser(request);
case "teleport_home_all_users":
return TeleportHomeAllUsers(request);
}
}
finally
{
m_EstateModule.InInfoUpdate = false;
}
}
}
catch (Exception e)
{
m_log.Debug("[XESTATE]: Exception {0}" + e.ToString());
}
return FailureResult();
}
byte[] TeleportHomeAllUsers(Dictionary<string, object> request)
{
UUID PreyID = UUID.Zero;
int EstateID = 0;
if (!request.ContainsKey("EstateID"))
return FailureResult();
if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID))
return FailureResult();
foreach (Scene s in m_EstateModule.Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == EstateID)
{
s.ForEachScenePresence(delegate(ScenePresence p) {
if (p != null && !p.IsChildAgent)
{
p.ControllingClient.SendTeleportStart(16);
s.TeleportClientHome(p.ControllingClient.AgentId, p.ControllingClient);
}
});
}
}
return SuccessResult();
}
byte[] TeleportHomeOneUser(Dictionary<string, object> request)
{
UUID PreyID = UUID.Zero;
int EstateID = 0;
if (!request.ContainsKey("PreyID") ||
!request.ContainsKey("EstateID"))
{
return FailureResult();
}
if (!UUID.TryParse(request["PreyID"].ToString(), out PreyID))
return FailureResult();
if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID))
return FailureResult();
foreach (Scene s in m_EstateModule.Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == EstateID)
{
ScenePresence p = s.GetScenePresence(PreyID);
if (p != null && !p.IsChildAgent)
{
p.ControllingClient.SendTeleportStart(16);
s.TeleportClientHome(PreyID, p.ControllingClient);
}
}
}
return SuccessResult();
}
byte[] EstateMessage(Dictionary<string, object> request)
{
UUID FromID = UUID.Zero;
string FromName = String.Empty;
string Message = String.Empty;
int EstateID = 0;
if (!request.ContainsKey("FromID") ||
!request.ContainsKey("FromName") ||
!request.ContainsKey("Message") ||
!request.ContainsKey("EstateID"))
{
return FailureResult();
}
if (!UUID.TryParse(request["FromID"].ToString(), out FromID))
return FailureResult();
if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID))
return FailureResult();
FromName = request["FromName"].ToString();
Message = request["Message"].ToString();
foreach (Scene s in m_EstateModule.Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == EstateID)
{
IDialogModule dm = s.RequestModuleInterface<IDialogModule>();
if (dm != null)
{
dm.SendNotificationToUsersInRegion(FromID, FromName,
Message);
}
}
}
return SuccessResult();
}
byte[] UpdateCovenant(Dictionary<string, object> request)
{
UUID CovenantID = UUID.Zero;
int EstateID = 0;
if (!request.ContainsKey("CovenantID") || !request.ContainsKey("EstateID"))
return FailureResult();
if (!UUID.TryParse(request["CovenantID"].ToString(), out CovenantID))
return FailureResult();
if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID))
return FailureResult();
foreach (Scene s in m_EstateModule.Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == (uint)EstateID)
s.RegionInfo.RegionSettings.Covenant = CovenantID;
}
return SuccessResult();
}
byte[] UpdateEstate(Dictionary<string, object> request)
{
int EstateID = 0;
if (!request.ContainsKey("EstateID"))
return FailureResult();
if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID))
return FailureResult();
foreach (Scene s in m_EstateModule.Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == (uint)EstateID)
s.ReloadEstateData();
}
return SuccessResult();
}
private byte[] FailureResult()
{
return BoolResult(false);
}
private byte[] SuccessResult()
{
return BoolResult(true);
}
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();
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using NUnit.Framework;
using QuantConnect.Algorithm;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Tests.Common.Securities;
using QuantConnect.Tests.Engine.DataFeeds;
namespace QuantConnect.Tests.Common
{
public class OrderTargetsByMarginImpactTests
{
[TestCase(false)]
[TestCase(true)]
public void LessThanLotSizeIsIgnored_NoHoldings(bool targetIsDelta)
{
var algorithm = GetAlgorithm();
var collection = new[] {new PortfolioTarget(Symbols.AAPL, 0.9m)};
var result = collection.OrderTargetsByMarginImpact(algorithm, targetIsDelta).ToList();
Assert.AreEqual(0, result.Count);
}
[TestCase(false)]
[TestCase(true)]
public void LessThanLotSizeIsIgnored_WithHoldings(bool targetIsDelta)
{
var algorithm = GetAlgorithm(holdings:1m);
var collection = new[] { new PortfolioTarget(Symbols.AAPL, 1.9m) };
var result = collection.OrderTargetsByMarginImpact(algorithm, targetIsDelta).ToList();
if (targetIsDelta)
{
Assert.AreEqual(1, result.Count);
Assert.AreEqual(1.9m, result[0].Quantity);
}
else
{
Assert.AreEqual(0, result.Count);
}
}
[Test]
public void SecurityWithNoDataIsIgnored()
{
var algorithm = GetAlgorithm();
// SPY won't have any data and should be ignored
algorithm.AddEquity(Symbols.SPY.Value);
var collection = new[] {new PortfolioTarget(Symbols.SPY, 5000m),
new PortfolioTarget(Symbols.AAPL, 1m)};
var result = collection.OrderTargetsByMarginImpact(algorithm).ToList();
Assert.AreEqual(1, result.Count);
Assert.AreEqual(1m, result[0].Quantity);
}
[Test]
public void NoExistingHoldings()
{
var algorithm = GetAlgorithm();
var spy = algorithm.AddEquity(Symbols.SPY.Value);
Update(spy, 1);
var collection = new[] {new PortfolioTarget(Symbols.SPY, 5m),
new PortfolioTarget(Symbols.AAPL, 1m)};
var result = collection.OrderTargetsByMarginImpact(algorithm).ToList();
Assert.AreEqual(2, result.Count);
// highest order value first
Assert.AreEqual(5m, result[0].Quantity);
Assert.AreEqual(1m, result[1].Quantity);
}
[TestCase(OrderDirection.Buy, false)]
[TestCase(OrderDirection.Sell, false)]
[TestCase(OrderDirection.Buy, true)]
[TestCase(OrderDirection.Sell, true)]
public void ReducingPosition(OrderDirection direction, bool targetIsDelta)
{
var algorithm = GetAlgorithm(direction == OrderDirection.Sell ? 2 : -2);
var spy = algorithm.AddEquity(Symbols.SPY.Value);
Update(spy, 1);
var target = direction == OrderDirection.Sell ? -1 : 1;
var collection = new[] {new PortfolioTarget(Symbols.SPY, 5m),
new PortfolioTarget(Symbols.AAPL, target)};
var result = collection.OrderTargetsByMarginImpact(algorithm, targetIsDelta).ToList();
Assert.AreEqual(2, result.Count);
// target reducing the position first
Assert.AreEqual(target, result[0].Quantity);
Assert.AreEqual(5m, result[1].Quantity);
}
[TestCase(OrderDirection.Buy, false)]
[TestCase(OrderDirection.Sell, false)]
[TestCase(OrderDirection.Buy, true)]
[TestCase(OrderDirection.Sell, true)]
public void ReducingPositionDeltaEffect(OrderDirection direction, bool targetIsDelta)
{
var algorithm = GetAlgorithm(direction == OrderDirection.Sell ? 2 : -2);
var spy = algorithm.AddEquity(Symbols.SPY.Value);
Update(spy, 1);
var target = direction == OrderDirection.Sell ? -2.5m : 2.5m;
var collection = new[] {new PortfolioTarget(Symbols.SPY, 5m),
new PortfolioTarget(Symbols.AAPL, target)};
var result = collection.OrderTargetsByMarginImpact(algorithm, targetIsDelta).ToList();
Assert.AreEqual(2, result.Count);
if (targetIsDelta)
{
// target reducing the position first
Assert.AreEqual(target, result[0].Quantity);
Assert.AreEqual(5m, result[1].Quantity);
}
else
{
Assert.AreEqual(5m, result[0].Quantity);
Assert.AreEqual(target, result[1].Quantity);
}
}
[TestCase(OrderDirection.Buy, false)]
[TestCase(OrderDirection.Sell, false)]
[TestCase(OrderDirection.Buy, true)]
[TestCase(OrderDirection.Sell, true)]
public void IncreasePosition(OrderDirection direction, bool targetIsDelta)
{
var value = direction == OrderDirection.Sell ? -1 : 1;
var algorithm = GetAlgorithm(value);
var spy = algorithm.AddEquity(Symbols.SPY.Value);
Update(spy, 1);
var collection = new[] {new PortfolioTarget(Symbols.SPY, 20m),
new PortfolioTarget(Symbols.AAPL, value * 21m)};
var result = collection.OrderTargetsByMarginImpact(algorithm, targetIsDelta).ToList();
Assert.AreEqual(2, result.Count);
if (targetIsDelta)
{
// AAPL is increasing the position by 21
Assert.AreEqual(Symbols.AAPL, result[0].Symbol);
Assert.AreEqual(Symbols.SPY, result[1].Symbol);
}
else
{
Assert.AreEqual(Symbols.SPY, result[0].Symbol);
// target with the least order value, AAPL is increasing the position by 11
Assert.AreEqual(Symbols.AAPL, result[1].Symbol);
}
}
[TestCase(OrderDirection.Buy, false)]
[TestCase(OrderDirection.Sell, false)]
[TestCase(OrderDirection.Buy, true)]
[TestCase(OrderDirection.Sell, true)]
public void RoundQuantityInOrderTargets(OrderDirection direction, bool targetIsDelta)
{
var value = direction == OrderDirection.Sell ? -1 : 1;
var algorithm = GetAlgorithm(value);
var spy = algorithm.AddEquity(Symbols.SPY.Value);
Update(spy, 1);
var collection = new[] {new PortfolioTarget(Symbols.SPY, 20m),
new PortfolioTarget(Symbols.AAPL, value * 20.1m)};
var result = collection.OrderTargetsByMarginImpact(algorithm, targetIsDelta).ToList();
Assert.AreEqual(2, result.Count);
// Since the order value is the same SPY comes first because of its the first in collection.
Assert.AreEqual(Symbols.SPY, result[0].Symbol);
Assert.AreEqual(Symbols.AAPL, result[1].Symbol);
}
private static void Update(Security security, decimal close)
{
security.SetMarketPrice(new TradeBar
{
Time = DateTime.Now,
Symbol = security.Symbol,
Open = close,
High = close,
Low = close,
Close = close
});
}
private QCAlgorithm GetAlgorithm(decimal? holdings = null)
{
var algorithm = new AlgorithmStub();
algorithm.Transactions.SetOrderProcessor(new FakeOrderProcessor());
var aapl = algorithm.AddEquity(Symbols.AAPL.Value);
Update(aapl, 1);
if (holdings != null)
{
aapl.Holdings.SetHoldings(10, holdings.Value);
}
algorithm.SetFinishedWarmingUp();
return algorithm;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
namespace System
{
[Immutable]
public class String
{
[System.Runtime.CompilerServices.IndexerName("Char")]
public char this [int index]
{
get
CodeContract.Requires(0 <= index && index < this.Length);
}
public int Length
{
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
get
CodeContract.Ensures(result >= 0);
}
[Pure] [GlobalAccess(false)] [Escapes(true,false)]
public CharEnumerator GetEnumerator () {
CodeContract.Ensures(result.IsNew);
CodeContract.Ensures(CodeContract.Result<CharEnumerator>() != null);
return default(CharEnumerator);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public TypeCode GetTypeCode () {
return default(TypeCode);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String IsInterned (String! str) {
CodeContract.Requires(str != null);
CodeContract.Ensures(result != null ==> result.Length == str.Length);
CodeContract.Ensures(result != null ==> str.Equals(result));
return default(String);
}
public static String Intern (String! str) {
CodeContract.Requires(str != null);
CodeContract.Ensures(result.Length == str.Length);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Concat (String[]! values) {
CodeContract.Requires(values != null);
//CodeContract.Ensures(result.Length == Sum({ String s in values); s.Length }));
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Concat (String str0, String str1, String str2, String str3) {
CodeContract.Ensures(result.Length ==
(str0 == null ? 0 : str0.Length) +
(str1 == null ? 0 : str1.Length) +
(str2 == null ? 0 : str2.Length) +
(str3 == null ? 0 : str3.Length);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Concat (String str0, String str1, String str2) {
CodeContract.Ensures(result.Length ==
(str0 == null ? 0 : str0.Length) +
(str1 == null ? 0 : str1.Length) +
(str2 == null ? 0 : str2.Length);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Concat (String str0, String str1) {
CodeContract.Ensures(result.Length ==
(str0 == null ? 0 : str0.Length) +
(str1 == null ? 0 : str1.Length);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Concat (object[]! args) {
CodeContract.Requires(args != null);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Concat (object arg0, object arg1, object arg2, object arg3) {
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Concat (object arg0, object arg1, object arg2) {
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Concat (object arg0, object arg1) {
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Concat (object arg0) {
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Copy (String! str) {
CodeContract.Requires(str != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Format (IFormatProvider provider, String format, object[]! args) {
CodeContract.Requires(format != null);
CodeContract.Requires(args != null);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Format (String format, object[] args) {
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Format (String format, object arg0, object arg1, object arg2) {
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Format (String format, object arg0, object arg1) {
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Format (String format, object arg0) {
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String Remove (int index, int count) {
CodeContract.Requires(0 <= index);
CodeContract.Requires(index + count <= Length);
CodeContract.Ensures(result.Length == this.Length - count);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String Replace (String oldValue, String newValue) {
CodeContract.Requires(oldValue != null);
CodeContract.Requires(oldValue.Length > 0);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String Replace (char oldChar, char newChar) {
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String Insert (int startIndex, String value) {
CodeContract.Requires(value != null);
CodeContract.Requires(0 <= startIndex);
CodeContract.Requires(startIndex <= this.Length);
CodeContract.Ensures(result.Length == this.Length + value.Length);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String Trim () {
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String ToUpper (System.Globalization.CultureInfo! culture) {
CodeContract.Requires(culture != null);
CodeContract.Ensures(result.Length == this.Length); // Are there languages for which this isn't true?!?
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String ToUpper () {
CodeContract.Ensures(result.Length == this.Length);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String ToLower (System.Globalization.CultureInfo! culture) {
CodeContract.Requires(culture != null);
CodeContract.Ensures(result.Length == this.Length);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String ToLower () {
CodeContract.Ensures(result.Length == this.Length);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String ToLowerInvariant() {
CodeContract.Ensures(result.Length == this.Length);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public bool StartsWith (String! value) {
CodeContract.Requires(value != null);
CodeContract.Ensures(result ==> value.Length <= this.Length);
return default(bool);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String PadRight (int totalWidth, char paddingChar) {
CodeContract.Requires(totalWidth >= 0);
CodeContract.Ensures(result.Length == totalWidth);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String PadRight (int totalWidth) {
CodeContract.Requires(totalWidth >= 0);
CodeContract.Ensures(result.Length == totalWidth);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String PadLeft (int totalWidth, char paddingChar) {
CodeContract.Requires(totalWidth >= 0);
CodeContract.Ensures(result.Length == totalWidth);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String PadLeft (int totalWidth) {
CodeContract.Requires(totalWidth >= 0);
CodeContract.Ensures(result.Length == totalWidth);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int LastIndexOf (String! value, int startIndex, int count) {
CodeContract.Requires(value != null);
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Requires(startIndex + count <= Length);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int LastIndexOf (String! value, int startIndex) {
CodeContract.Requires(value != null);
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(startIndex <= Length);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int LastIndexOf (String! value) {
CodeContract.Requires(value != null);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int LastIndexOfAny (char[]! anyOf, int startIndex, int count) {
CodeContract.Requires(anyOf != null);
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Requires(startIndex + count <= Length);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int LastIndexOfAny (char[]! anyOf, int startIndex) {
CodeContract.Requires(anyOf != null);
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(startIndex <= Length);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int LastIndexOfAny (char[]! anyOf) {
CodeContract.Requires(anyOf != null);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int LastIndexOf (char arg0, int startIndex, int count) {
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Requires(startIndex + count <= Length);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int LastIndexOf (char value, int startIndex) {
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(startIndex <= Length);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int LastIndexOf (char value) {
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int IndexOf (String! value, int startIndex, int count) {
CodeContract.Requires(value != null);
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Requires(startIndex + count <= Length);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int IndexOf (String! value, int startIndex) {
CodeContract.Requires(value != null);
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(startIndex <= Length);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int IndexOf (String! value) {
CodeContract.Requires(value != null);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int IndexOfAny (char[]! anyOf, int startIndex, int count) {
CodeContract.Requires(anyOf != null);
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Requires(startIndex + count <= Length);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int IndexOfAny (char[]! anyOf, int startIndex) {
CodeContract.Requires(anyOf != null);
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(startIndex <= Length);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int IndexOfAny (char[]! anyOf) {
CodeContract.Requires(anyOf != null);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int IndexOf (char arg0, int startIndex, int count) {
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Requires(startIndex + count <= Length);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int IndexOf (char value, int startIndex) {
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(startIndex <= Length);
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int IndexOf (char value) {
CodeContract.Ensures(-1 <= result && result < this.Length);
return default(int);
}
public static readonly string/*!*/ Empty = "";
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public bool EndsWith (String! value) {
CodeContract.Requires(value != null);
return default(bool);
}
public static int CompareOrdinal (String strA, int indexA, String strB, int indexB, int length) {
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static int CompareOrdinal (String strA, String strB) {
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int CompareTo (String strB) {
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public int CompareTo (object value) {
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static int Compare (String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo! culture) {
CodeContract.Requires(culture != null);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static int Compare (String strA, int indexA, String strB, int indexB, int length, bool ignoreCase) {
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static int Compare(string strA, string strB, StringComparison comparisonType) {
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType) {
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static int Compare (String strA, int indexA, String strB, int indexB, int length) {
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static int Compare (String strA, String strB, bool ignoreCase, System.Globalization.CultureInfo! culture) {
CodeContract.Requires(culture != null);
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static int Compare (String strA, String strB, bool ignoreCase) {
return default(int);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static int Compare (String strA, String strB) {
return default(int);
}
public String (char c, int count) {
CodeContract.Ensures(this.Length == count);
return default(String);
}
public String (char[] array) // maybe null
CodeContract.Ensures(array == null ==> this.Length == 0);
CodeContract.Ensures(array != null ==> this.Length == array.Length);
public String (char[]! value, int startIndex, int length) {
CodeContract.Requires(value != null);
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(length >= 0);
CodeContract.Requires(startIndex + length <= value.Length);
CodeContract.Ensures(this.Length == length);
/* These should all be pointer arguments
return default(String);
}
public String (ref SByte arg0, int arg1, int arg2, System.Text.Encoding arg3) {
return default(String);
}
public String (ref SByte arg0, int arg1, int arg2) {
return default(String);
}
public String (ref SByte arg0) {
return default(String);
}
public String (ref char arg0, int arg1, int arg2) {
return default(String);
}
public String (ref char arg0) {
*/
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String TrimEnd (params char[] trimChars) { // maybe null
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String TrimStart (params char[] trimChars) { // maybe null
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String Trim (params char[] trimChars) { // maybe null
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String Substring (int startIndex, int length) {
CodeContract.Requires(0 <= startIndex);
CodeContract.Requires(0 <= length);
CodeContract.Requires(startIndex + length <= this.Length);
CodeContract.Ensures(result.Length == length);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String Substring (int startIndex) {
CodeContract.Requires(0 <= startIndex);
CodeContract.Requires(startIndex <= this.Length);
CodeContract.Ensures(result.Length == this.Length - startIndex);
CodeContract.Ensures(CodeContract.Result<String>() != null);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String![] Split (char[] arg0, int arg1) {
//CodeContract.Ensures(Forall {int i in (0:result.Length)); result[i] != null});
CodeContract.Ensures(CodeContract.Result<String![]>() != null);
return default(String![]);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public String![] Split (char[] separator) {
//CodeContract.Ensures(Forall {int i in (0:result.Length)); result[i] != null});
CodeContract.Ensures(CodeContract.Result<String![]>() != null);
return default(String![]);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public string![] Split(char[] separator, StringSplitOptions options) {
CodeContract.Ensures(CodeContract.Result<string![]>() != null);
return default(string![]);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public string![] Split(string[] separator, StringSplitOptions options) {
CodeContract.Ensures(CodeContract.Result<string![]>() != null);
return default(string![]);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public string![] Split(char[] separator, int count, StringSplitOptions options) {
CodeContract.Ensures(CodeContract.Result<string![]>() != null);
return default(string![]);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public string![] Split(string[] separator, int count, StringSplitOptions options) {
CodeContract.Ensures(CodeContract.Result<string![]>() != null);
return default(string![]);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public char[] ToCharArray (int startIndex, int length) {
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(startIndex <= this.Length);
CodeContract.Requires(startIndex + length <= this.Length);
CodeContract.Requires(length >= 0);
CodeContract.Ensures(CodeContract.Result<char[]>() != null);
return default(char[]);
}
[Pure][Reads(ReadsAttribute.Reads.Owned)]
public char[] ToCharArray () {
CodeContract.Ensures(CodeContract.Result<char[]>() != null);
return default(char[]);
}
public void CopyTo (int sourceIndex, char[]! destination, int destinationIndex, int count) {
CodeContract.Requires(destination != null);
CodeContract.Requires(count >= 0);
CodeContract.Requires(sourceIndex >= 0);
CodeContract.Requires(count <= (this.Length - sourceIndex));
CodeContract.Requires(destinationIndex <= (destination.Length - count));
CodeContract.Requires(destinationIndex >= 0);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static bool operator != (String a, String b) {
return default(bool);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static bool operator == (String a, String b) {
return default(bool);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static bool Equals (String a, String b) {
CodeContract.Ensures(a != null && (object)a == (object)b ==> result);
return default(bool);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)][RecursionTermination(10)]
public bool Equals (String arg0) {
CodeContract.Ensures((object)this == (object)arg0 ==> result);
CodeContract.Ensures(result ==> this.Length == arg0.Length);
return default(bool);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Join (String separator, String[]! value, int startIndex, int count) {
CodeContract.Requires(value != null);
CodeContract.Requires(startIndex >= 0);
CodeContract.Requires(count >= 0);
CodeContract.Requires(startIndex + count <= value.Length);
return default(String);
}
[Pure][Reads(ReadsAttribute.Reads.Nothing)]
public static String Join (String separator, String[]! value) {
CodeContract.Requires(value != null);
return default(String);
}
}
}
| |
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 ChessGame.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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
/// <summary>
/// Tests that apply to the filesystem/cache portions of the X509 infrastructure on Unix implementations.
/// </summary>
[Collection("X509Filesystem")]
public static class X509FilesystemTests
{
private static bool RunManualTests { get; } = TestEnvironmentConfiguration.RunManualTests;
[OuterLoop]
// This test is a bit too flaky to be on in the normal run, even for OuterLoop.
// It can fail due to networking problems, and due to the filesystem interactions it doesn't
// have strong isolation from other tests (even in different processes).
[ConditionalFact(nameof(RunManualTests))]
public static void VerifyCrlCache()
{
string crlDirectory = PersistedFiles.GetUserFeatureDirectory("cryptography", "crls");
string crlFile = Path.Combine(crlDirectory,MicrosoftDotComRootCrlFilename);
Directory.CreateDirectory(crlDirectory);
File.Delete(crlFile);
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var unrelated = new X509Certificate2(TestData.DssCer))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(unrelated);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
// The very start of the CRL period.
chain.ChainPolicy.VerificationTime = new DateTime(2015, 6, 17, 0, 0, 0, DateTimeKind.Utc);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EndCertificateOnly;
chain.ChainPolicy.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority;
bool valid = chain.Build(microsoftDotComIssuer);
Assert.True(valid, "Precondition: Chain builds with no revocation checks");
int initialErrorCount = chain.ChainStatus.Length;
Assert.InRange(initialErrorCount, 0, 1);
if (initialErrorCount > 0)
{
Assert.Equal(X509ChainStatusFlags.UntrustedRoot, chain.ChainStatus[0].Status);
}
chainHolder.DisposeChainElements();
chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
valid = chain.Build(microsoftDotComIssuer);
Assert.False(valid, "Chain should not build validly");
Assert.Equal(initialErrorCount + 1, chain.ChainStatus.Length);
Assert.Equal(X509ChainStatusFlags.RevocationStatusUnknown, chain.ChainStatus[0].Status);
File.WriteAllText(crlFile, MicrosoftDotComRootCrlPem, Encoding.ASCII);
chainHolder.DisposeChainElements();
valid = chain.Build(microsoftDotComIssuer);
Assert.True(valid, "Chain should build validly now");
Assert.Equal(initialErrorCount, chain.ChainStatus.Length);
}
}
[Fact]
public static void X509Store_OpenExisting_Fails()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
// Since the directory was explicitly deleted already, this should fail.
Assert.Throws<CryptographicException>(
() => store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly));
});
}
[Fact]
private static void X509Store_AddReadOnly()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadOnly);
// Adding a certificate when the store is ReadOnly should fail:
Assert.Throws<CryptographicException>(() => store.Add(cert));
// Since we haven't done anything yet, we shouldn't have polluted the hard drive.
Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
}
});
}
[Fact]
private static void X509Store_AddClosed()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
// Adding a certificate when the store is closed should fail:
Assert.Throws<CryptographicException>(() => store.Add(cert));
// Since we haven't done anything yet, we shouldn't have polluted the hard drive.
Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddOne()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
using (var coll = new ImportedCollection(store.Certificates))
{
X509Certificate2Collection storeCerts = coll.Collection;
Assert.Equal(1, storeCerts.Count);
using (X509Certificate2 storeCert = storeCerts[0])
{
Assert.Equal(cert, storeCert);
Assert.NotSame(cert, storeCert);
}
}
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddOneAfterUpgrade()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadOnly);
// Adding a certificate when the store is ReadOnly should fail:
Assert.Throws<CryptographicException>(() => store.Add(cert));
// Since we haven't done anything yet, we shouldn't have polluted the hard drive.
Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
// Calling Open on an open store changes the access rights:
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
using (var coll = new ImportedCollection(store.Certificates))
{
X509Certificate2Collection storeCerts = coll.Collection;
Assert.Equal(1, storeCerts.Count);
using (X509Certificate2 storeCert = storeCerts[0])
{
Assert.Equal(cert, storeCert);
Assert.NotSame(cert, storeCert);
}
}
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_DowngradePermissions()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
// Ensure that ReadWrite took effect.
store.Add(certA);
store.Open(OpenFlags.ReadOnly);
// Adding a certificate when the store is ReadOnly should fail:
Assert.Throws<CryptographicException>(() => store.Add(certB));
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddAfterDispose()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
// Dispose returns the store to the pre-opened state.
store.Dispose();
// Adding a certificate when the store is closed should fail:
Assert.Throws<CryptographicException>(() => store.Add(certB));
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddAndClear()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
store.Remove(cert);
// The directory should still exist.
Assert.True(Directory.Exists(storeDirectory), "Store Directory Still Exists");
Assert.Equal(0, Directory.GetFiles(storeDirectory).Length);
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddDuplicate()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
using (var certClone = new X509Certificate2(cert.RawData))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
store.Add(certClone);
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddTwo()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(2, Directory.GetFiles(storeDirectory).Length);
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
X509Certificate2[] expectedCerts = { certA, certB };
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddTwo_UpgradePrivateKey()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certAPrivate = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
using (var certAPublic = new X509Certificate2(certAPrivate.RawData))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certAPublic);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
string[] storeFiles = Directory.GetFiles(storeDirectory);
Assert.Equal(2, storeFiles.Length);
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
X509Certificate2[] expectedCerts = { certAPublic, certB };
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (before)");
storeCert.Dispose();
}
store.Add(certAPrivate);
// It replaces the existing file, the names should be unaffected.
Assert.Equal(storeFiles, Directory.GetFiles(storeDirectory));
storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
bool foundCertA = false;
foreach (X509Certificate2 storeCert in storeCerts)
{
// The public instance and private instance are .Equal
if (storeCert.Equals(certAPublic))
{
Assert.True(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (affected cert)");
foundCertA = true;
}
else
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (other cert)");
}
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
Assert.True(foundCertA, "foundCertA");
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddTwo_UpgradePrivateKey_NoDowngrade()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certAPrivate = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
using (var certAPublic = new X509Certificate2(certAPrivate.RawData))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certAPublic);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
X509Certificate2[] expectedCerts = { certAPublic, certB };
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (before)");
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
// Add the private (checked in X509Store_AddTwo_UpgradePrivateKey)
store.Add(certAPrivate);
// Then add the public again, which shouldn't do anything.
store.Add(certAPublic);
storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
bool foundCertA = false;
foreach (X509Certificate2 storeCert in storeCerts)
{
if (storeCert.Equals(certAPublic))
{
Assert.True(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (affected cert)");
foundCertA = true;
}
else
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (other cert)");
}
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
Assert.True(foundCertA, "foundCertA");
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_DistinctCollections()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(2, Directory.GetFiles(storeDirectory).Length);
X509Certificate2Collection storeCertsA = store.Certificates;
X509Certificate2Collection storeCertsB = store.Certificates;
Assert.NotSame(storeCertsA, storeCertsB);
Assert.Equal(storeCertsA.Count, storeCertsB.Count);
foreach (X509Certificate2 collACert in storeCertsA)
{
int bIndex = storeCertsB.IndexOf(collACert);
Assert.InRange(bIndex, 0, storeCertsB.Count);
X509Certificate2 collBCert = storeCertsB[bIndex];
// Equal is implied by IndexOf working.
Assert.NotSame(collACert, collBCert);
storeCertsB.RemoveAt(bIndex);
collACert.Dispose();
collBCert.Dispose();
}
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_Add4_Remove1()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
using (var certBClone = new X509Certificate2(certB.RawData))
using (var certC = new X509Certificate2(TestData.ECDsa256Certificate))
using (var certD = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
store.Add(certC);
store.Add(certD);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(4, Directory.GetFiles(storeDirectory).Length);
X509Certificate2[] expectedCerts = { certA, certB, certC, certD };
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(4, storeCerts.Count);
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
store.Remove(certBClone);
Assert.Equal(3, Directory.GetFiles(storeDirectory).Length);
expectedCerts = new[] { certA, certC, certD };
storeCerts = store.Certificates;
Assert.Equal(3, storeCerts.Count);
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
}
});
}
[Theory]
[OuterLoop(/* Alters user/machine state */)]
[InlineData(false)]
[InlineData(true)]
private static void X509Store_MultipleObjects(bool matchCase)
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
using (var certC = new X509Certificate2(TestData.ECDsa256Certificate))
using (var certD = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
string newName = store.Name;
if (!matchCase)
{
newName = newName.ToUpperInvariant();
Assert.NotEqual(store.Name, newName);
}
using (X509Store storeClone = new X509Store(newName, store.Location))
{
storeClone.Open(OpenFlags.ReadWrite);
AssertEqualContents(store, storeClone);
store.Add(certC);
// The object was added to store, but should show up in both objects
// after re-reading the Certificates property
AssertEqualContents(store, storeClone);
// Now add one to storeClone to prove bidirectionality.
storeClone.Add(certD);
AssertEqualContents(store, storeClone);
}
}
});
}
[Fact]
[OuterLoop( /* Alters user/machine state */)]
private static void X509Store_FiltersDuplicateOnLoad()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
// Emulate a race condition of parallel adds with the following flow
// AdderA: Notice [thumbprint].pfx is available, create it (0 bytes)
// AdderB: Notice [thumbprint].pfx already exists, but can't be read, move to [thumbprint].1.pfx
// AdderA: finish write
// AdderB: finish write
string[] files = Directory.GetFiles(storeDirectory, "*.pfx");
Assert.Equal(1, files.Length);
string srcFile = files[0];
string baseName = Path.GetFileNameWithoutExtension(srcFile);
string destFile = Path.Combine(storeDirectory, srcFile + ".1.pfx");
File.Copy(srcFile, destFile);
using (var coll = new ImportedCollection(store.Certificates))
{
Assert.Equal(1, coll.Collection.Count);
Assert.Equal(certA, coll.Collection[0]);
}
// Also check that remove removes both files.
store.Remove(certA);
string[] filesAfter = Directory.GetFiles(storeDirectory, "*.pfx");
Assert.Equal(0, filesAfter.Length);
}
});
}
private static void AssertEqualContents(X509Store storeA, X509Store storeB)
{
Assert.NotSame(storeA, storeB);
using (var storeATracker = new ImportedCollection(storeA.Certificates))
using (var storeBTracker = new ImportedCollection(storeB.Certificates))
{
X509Certificate2Collection storeACerts = storeATracker.Collection;
X509Certificate2Collection storeBCerts = storeBTracker.Collection;
Assert.Equal(storeACerts.OfType<X509Certificate2>(), storeBCerts.OfType<X509Certificate2>());
}
}
private static void RunX509StoreTest(Action<X509Store, string> testAction)
{
string certStoresFeaturePath = PersistedFiles.GetUserFeatureDirectory("cryptography", "x509stores");
string storeName = "TestStore" + Guid.NewGuid().ToString("N");
string storeDirectory = Path.Combine(certStoresFeaturePath, storeName.ToLowerInvariant());
if (Directory.Exists(storeDirectory))
{
Directory.Delete(storeDirectory, true);
}
try
{
using (X509Store store = new X509Store(storeName, StoreLocation.CurrentUser))
{
testAction(store, storeDirectory);
}
}
finally
{
try
{
if (Directory.Exists(storeDirectory))
{
Directory.Delete(storeDirectory, true);
}
}
catch
{
// Don't allow any (additional?) I/O errors to propagate.
}
}
}
// `openssl crl -in [MicrosoftDotComRootCrlPem] -noout -hash`.[SHA-256(CDPURL)[0..4].ToHex()].crl
private const string MicrosoftDotComRootCrlFilename = "b204d74a.daa2bce5.crl";
// This CRL was downloaded 2015-08-31 20:31 PDT
// It is valid from Jun 17 00:00:00 2015 GMT to Sep 30 23:59:59 2015 GMT
private const string MicrosoftDotComRootCrlPem =
@"-----BEGIN X509 CRL-----
MIICETCB+jANBgkqhkiG9w0BAQUFADCByjELMAkGA1UEBhMCVVMxFzAVBgNVBAoT
DlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3Jr
MTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3Jp
emVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQ
cmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzUXDTE1MDYxNzAwMDAw
MFoXDTE1MDkzMDIzNTk1OVowDQYJKoZIhvcNAQEFBQADggEBAFxqobObEqKNSAe+
A9cHCYI7sw+Vc8HuE7E+VZc6ni3a2UHiprYuXDsvD18+cyv/nFSLpLqLmExZrsf/
dzH8GH2HgBTt5aO/nX08EBrDgcjHo9b0VI6ZuOOaEeS0NsRh28Jupfn1Xwcsbdw9
nVh1OaExpHwxgg7pJr4pXzaAjbl3b4QfCPyTd5aaOQOEmqvJtRrMwCna4qQ3p4r6
QYe19/pXqK9my7lSmH1vZ0CmNvQeNPmnx+YmFXYTBgap+Xi2cs6GX/qI04CDzjWi
sm6L0+S1Zx2wMhiYOi0JvrRizf+rIyKkDbPMoYEyXZqcCwSnv6mJQY81vmKRKU5N
WKo2mLw=
-----END X509 CRL-----";
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.ComponentModel;
namespace Azure.Data.Tables.Models
{
/// <summary> Error codes returned by the service. </summary>
public readonly partial struct TableErrorCode : IEquatable<TableErrorCode>
{
private readonly string _value;
/// <summary> Determines if two <see cref="TableErrorCode"/> values are the same. </summary>
/// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
public TableErrorCode(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
private const string AuthorizationResourceTypeMismatchValue = "AuthorizationResourceTypeMismatch";
private const string AuthorizationPermissionMismatchValue = "AuthorizationPermissionMismatch";
private const string XMethodNotUsingPostValue = "XMethodNotUsingPost";
private const string XMethodIncorrectValueValue = "XMethodIncorrectValue";
private const string XMethodIncorrectCountValue = "XMethodIncorrectCount";
private const string TableHasNoPropertiesValue = "TableHasNoProperties";
private const string DuplicatePropertiesSpecifiedValue = "DuplicatePropertiesSpecified";
private const string TableHasNoSuchPropertyValue = "TableHasNoSuchProperty";
private const string DuplicateKeyPropertySpecifiedValue = "DuplicateKeyPropertySpecified";
private const string TableAlreadyExistsValue = "TableAlreadyExists";
private const string TableNotFoundValue = "TableNotFound";
private const string ResourceNotFoundValue = "ResourceNotFound";
private const string EntityNotFoundValue = "EntityNotFound";
private const string EntityAlreadyExistsValue = "EntityAlreadyExists";
private const string PartitionKeyNotSpecifiedValue = "PartitionKeyNotSpecified";
private const string OperatorInvalidValue = "OperatorInvalid";
private const string UpdateConditionNotSatisfiedValue = "UpdateConditionNotSatisfied";
private const string PropertiesNeedValueValue = "PropertiesNeedValue";
private const string PartitionKeyPropertyCannotBeUpdatedValue = "PartitionKeyPropertyCannotBeUpdated";
private const string TooManyPropertiesValue = "TooManyProperties";
private const string EntityTooLargeValue = "EntityTooLarge";
private const string PropertyValueTooLargeValue = "PropertyValueTooLarge";
private const string KeyValueTooLargeValue = "KeyValueTooLarge";
private const string InvalidValueTypeValue = "InvalidValueType";
private const string TableBeingDeletedValue = "TableBeingDeleted";
private const string PrimaryKeyPropertyIsInvalidTypeValue = "PrimaryKeyPropertyIsInvalidType";
private const string PropertyNameTooLongValue = "PropertyNameTooLong";
private const string PropertyNameInvalidValue = "PropertyNameInvalid";
private const string InvalidDuplicateRowValue = "InvalidDuplicateRow";
private const string CommandsInBatchActOnDifferentPartitionsValue = "CommandsInBatchActOnDifferentPartitions";
private const string JsonFormatNotSupportedValue = "JsonFormatNotSupported";
private const string AtomFormatNotSupportedValue = "AtomFormatNotSupported";
private const string JsonVerboseFormatNotSupportedValue = "JsonVerboseFormatNotSupported";
private const string MediaTypeNotSupportedValue = "MediaTypeNotSupported";
private const string MethodNotAllowedValue = "MethodNotAllowed";
private const string ContentLengthExceededValue = "ContentLengthExceeded";
private const string AccountIopsLimitExceededValue = "AccountIOPSLimitExceeded";
private const string CannotCreateTableWithIopsGreaterThanMaxAllowedPerTableValue = "CannotCreateTableWithIOPSGreaterThanMaxAllowedPerTable";
private const string PerTableIopsIncrementLimitReachedValue = "PerTableIOPSIncrementLimitReached";
private const string PerTableIopsDecrementLimitReachedValue = "PerTableIOPSDecrementLimitReached";
private const string SettingIopsForATableInProvisioningNotAllowedValue = "SettingIOPSForATableInProvisioningNotAllowed";
private const string PartitionKeyEqualityComparisonExpectedValue = "PartitionKeyEqualityComparisonExpected";
private const string PartitionKeySpecifiedMoreThanOnceValue = "PartitionKeySpecifiedMoreThanOnce";
private const string InvalidInputValue = "InvalidInput";
private const string NotImplementedValue = "NotImplemented";
private const string OperationTimedOutValue = "OperationTimedOut";
private const string OutOfRangeInputValue = "OutOfRangeInput";
private const string ForbiddenValue = "Forbidden";
/// <summary> AuthorizationResourceTypeMismatch. </summary>
public static TableErrorCode AuthorizationResourceTypeMismatch { get; } = new TableErrorCode(AuthorizationResourceTypeMismatchValue);
/// <summary> XMethodNotUsingPost. </summary>
public static TableErrorCode XMethodNotUsingPost { get; } = new TableErrorCode(XMethodNotUsingPostValue);
/// <summary> XMethodIncorrectValue. </summary>
public static TableErrorCode XMethodIncorrectValue { get; } = new TableErrorCode(XMethodIncorrectValueValue);
/// <summary> XMethodIncorrectCount. </summary>
public static TableErrorCode XMethodIncorrectCount { get; } = new TableErrorCode(XMethodIncorrectCountValue);
/// <summary> TableHasNoProperties. </summary>
public static TableErrorCode TableHasNoProperties { get; } = new TableErrorCode(TableHasNoPropertiesValue);
/// <summary> DuplicatePropertiesSpecified. </summary>
public static TableErrorCode DuplicatePropertiesSpecified { get; } = new TableErrorCode(DuplicatePropertiesSpecifiedValue);
/// <summary> TableHasNoSuchProperty. </summary>
public static TableErrorCode TableHasNoSuchProperty { get; } = new TableErrorCode(TableHasNoSuchPropertyValue);
/// <summary> DuplicateKeyPropertySpecified. </summary>
public static TableErrorCode DuplicateKeyPropertySpecified { get; } = new TableErrorCode(DuplicateKeyPropertySpecifiedValue);
/// <summary> TableAlreadyExists. </summary>
public static TableErrorCode TableAlreadyExists { get; } = new TableErrorCode(TableAlreadyExistsValue);
/// <summary> TableNotFound.</summary>
public static TableErrorCode TableNotFound { get; } = new TableErrorCode(TableNotFoundValue);
/// <summary> TableNotFound. </summary>
public static TableErrorCode ResourceNotFound { get; } = new TableErrorCode(ResourceNotFoundValue);
/// <summary> EntityNotFound. </summary>
public static TableErrorCode EntityNotFound { get; } = new TableErrorCode(EntityNotFoundValue);
/// <summary> EntityAlreadyExists. </summary>
public static TableErrorCode EntityAlreadyExists { get; } = new TableErrorCode(EntityAlreadyExistsValue);
/// <summary> PartitionKeyNotSpecified. </summary>
public static TableErrorCode PartitionKeyNotSpecified { get; } = new TableErrorCode(PartitionKeyNotSpecifiedValue);
/// <summary> OperatorInvalid. </summary>
public static TableErrorCode OperatorInvalid { get; } = new TableErrorCode(OperatorInvalidValue);
/// <summary> UpdateConditionNotSatisfied. </summary>
public static TableErrorCode UpdateConditionNotSatisfied { get; } = new TableErrorCode(UpdateConditionNotSatisfiedValue);
/// <summary> PropertiesNeedValue. </summary>
public static TableErrorCode PropertiesNeedValue { get; } = new TableErrorCode(PropertiesNeedValueValue);
/// <summary> PartitionKeyPropertyCannotBeUpdated. </summary>
public static TableErrorCode PartitionKeyPropertyCannotBeUpdated { get; } = new TableErrorCode(PartitionKeyPropertyCannotBeUpdatedValue);
/// <summary> TooManyProperties. </summary>
public static TableErrorCode TooManyProperties { get; } = new TableErrorCode(TooManyPropertiesValue);
/// <summary> EntityTooLarge. </summary>
public static TableErrorCode EntityTooLarge { get; } = new TableErrorCode(EntityTooLargeValue);
/// <summary> PropertyValueTooLarge. </summary>
public static TableErrorCode PropertyValueTooLarge { get; } = new TableErrorCode(PropertyValueTooLargeValue);
/// <summary> KeyValueTooLarge. </summary>
public static TableErrorCode KeyValueTooLarge { get; } = new TableErrorCode(KeyValueTooLargeValue);
/// <summary> InvalidValueType. </summary>
public static TableErrorCode InvalidValueType { get; } = new TableErrorCode(InvalidValueTypeValue);
/// <summary> TableBeingDeleted. </summary>
public static TableErrorCode TableBeingDeleted { get; } = new TableErrorCode(TableBeingDeletedValue);
/// <summary> PrimaryKeyPropertyIsInvalidType. </summary>
public static TableErrorCode PrimaryKeyPropertyIsInvalidType { get; } = new TableErrorCode(PrimaryKeyPropertyIsInvalidTypeValue);
/// <summary> PropertyNameTooLong. </summary>
public static TableErrorCode PropertyNameTooLong { get; } = new TableErrorCode(PropertyNameTooLongValue);
/// <summary> PropertyNameInvalid. </summary>
public static TableErrorCode PropertyNameInvalid { get; } = new TableErrorCode(PropertyNameInvalidValue);
/// <summary> InvalidDuplicateRow. </summary>
public static TableErrorCode InvalidDuplicateRow { get; } = new TableErrorCode(InvalidDuplicateRowValue);
/// <summary> CommandsInBatchActOnDifferentPartitions. </summary>
public static TableErrorCode CommandsInBatchActOnDifferentPartitions { get; } = new TableErrorCode(CommandsInBatchActOnDifferentPartitionsValue);
/// <summary> JsonFormatNotSupported. </summary>
public static TableErrorCode JsonFormatNotSupported { get; } = new TableErrorCode(JsonFormatNotSupportedValue);
/// <summary> AtomFormatNotSupported. </summary>
public static TableErrorCode AtomFormatNotSupported { get; } = new TableErrorCode(AtomFormatNotSupportedValue);
/// <summary> JsonVerboseFormatNotSupported. </summary>
public static TableErrorCode JsonVerboseFormatNotSupported { get; } = new TableErrorCode(JsonVerboseFormatNotSupportedValue);
/// <summary> MediaTypeNotSupported. </summary>
public static TableErrorCode MediaTypeNotSupported { get; } = new TableErrorCode(MediaTypeNotSupportedValue);
/// <summary> MethodNotAllowed. </summary>
public static TableErrorCode MethodNotAllowed { get; } = new TableErrorCode(MethodNotAllowedValue);
/// <summary> ContentLengthExceeded. </summary>
public static TableErrorCode ContentLengthExceeded { get; } = new TableErrorCode(ContentLengthExceededValue);
/// <summary> AccountIOPSLimitExceeded. </summary>
public static TableErrorCode AccountIOPSLimitExceeded { get; } = new TableErrorCode(AccountIopsLimitExceededValue);
/// <summary> CannotCreateTableWithIOPSGreaterThanMaxAllowedPerTable. </summary>
public static TableErrorCode CannotCreateTableWithIOPSGreaterThanMaxAllowedPerTable { get; } = new TableErrorCode(CannotCreateTableWithIopsGreaterThanMaxAllowedPerTableValue);
/// <summary> PerTableIOPSIncrementLimitReached. </summary>
public static TableErrorCode PerTableIOPSIncrementLimitReached { get; } = new TableErrorCode(PerTableIopsIncrementLimitReachedValue);
/// <summary> PerTableIOPSDecrementLimitReached. </summary>
public static TableErrorCode PerTableIOPSDecrementLimitReached { get; } = new TableErrorCode(PerTableIopsDecrementLimitReachedValue);
/// <summary> SettingIOPSForATableInProvisioningNotAllowed. </summary>
public static TableErrorCode SettingIOPSForATableInProvisioningNotAllowed { get; } = new TableErrorCode(SettingIopsForATableInProvisioningNotAllowedValue);
/// <summary> PartitionKeyEqualityComparisonExpected. </summary>
public static TableErrorCode PartitionKeyEqualityComparisonExpected { get; } = new TableErrorCode(PartitionKeyEqualityComparisonExpectedValue);
/// <summary> PartitionKeySpecifiedMoreThanOnce. </summary>
public static TableErrorCode PartitionKeySpecifiedMoreThanOnce { get; } = new TableErrorCode(PartitionKeySpecifiedMoreThanOnceValue);
/// <summary> InvalidInput. </summary>
public static TableErrorCode InvalidInput { get; } = new TableErrorCode(InvalidInputValue);
/// <summary> NotImplemented. </summary>
public static TableErrorCode NotImplemented { get; } = new TableErrorCode(NotImplementedValue);
/// <summary> OperationTimedOut. </summary>
public static TableErrorCode OperationTimedOut { get; } = new TableErrorCode(OperationTimedOutValue);
/// <summary> OutOfRangeInput. </summary>
public static TableErrorCode OutOfRangeInput { get; } = new TableErrorCode(OutOfRangeInputValue);
/// <summary> Forbidden. </summary>
public static TableErrorCode Forbidden { get; } = new TableErrorCode(ForbiddenValue);
/// <summary> AuthorizationPermissionMismatch. </summary>
public static TableErrorCode AuthorizationPermissionMismatch { get; } = new TableErrorCode(AuthorizationPermissionMismatchValue);
/// <summary> Determines if two <see cref="TableErrorCode"/> values are the same. </summary>
public static bool operator ==(TableErrorCode left, TableErrorCode right) => left.Equals(right);
/// <summary> Determines if two <see cref="TableErrorCode"/> values are not the same. </summary>
public static bool operator !=(TableErrorCode left, TableErrorCode right) => !left.Equals(right);
/// <summary> Converts a string to a <see cref="TableErrorCode"/>. </summary>
public static implicit operator TableErrorCode(string value) => new TableErrorCode(value);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => obj is TableErrorCode other && Equals(other);
/// <inheritdoc />
public bool Equals(TableErrorCode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
/// <inheritdoc />
public override string ToString() => _value;
}
}
| |
// This source code is dual-licensed under the Apache License, version
// 2.0, and the Mozilla Public License, version 1.1.
//
// The APL v2.0:
//
//---------------------------------------------------------------------------
// Copyright (C) 2007-2014 GoPivotal, 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.
//---------------------------------------------------------------------------
//
// The MPL v1.1:
//
//---------------------------------------------------------------------------
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (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.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
// the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is RabbitMQ.
//
// The Initial Developer of the Original Code is GoPivotal, Inc.
// Copyright (c) 2007-2014 GoPivotal, Inc. All rights reserved.
//---------------------------------------------------------------------------
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Collections.Generic;
using RabbitMQ.Client.Impl;
using RabbitMQ.Client.Framing.Impl;
using RabbitMQ.Client.Exceptions;
namespace RabbitMQ.Client
{
///<summary>Main entry point to the RabbitMQ .NET AMQP client
///API. Constructs IConnection instances.</summary>
///<remarks>
///<para>
/// A simple example of connecting to a broker:
///</para>
///<example><code>
/// IConnectionFactory factory = new ConnectionFactory();
/// //
/// // The next six lines are optional:
/// factory.UserName = ConnectionFactory.DefaultUser;
/// factory.Password = ConnectionFactory.DefaultPass;
/// factory.VirtualHost = ConnectionFactory.DefaultVHost;
/// factory.HostName = hostName;
/// factory.Port = AmqpTcpEndpoint.UseDefaultPort;
/// //
/// IConnection conn = factory.CreateConnection();
/// //
/// IModel ch = conn.CreateModel();
/// //
/// // ... use ch's IModel methods ...
/// //
/// ch.Close(Constants.ReplySuccess, "Closing the channel");
/// conn.Close(Constants.ReplySuccess, "Closing the connection");
///</code></example>
///<para>
///The same example, written more compactly with AMQP URIs:
///</para>
///<example><code>
/// ConnectionFactory factory = new ConnectionFactory();
/// factory.Uri = "amqp://localhost";
/// IConnection conn = factory.CreateConnection();
/// ...
///</code></example>
///<para>
/// Please see also the API overview and tutorial in the User Guide.
///</para>
///<para>
///Note that the Uri property takes a string representation of an
///AMQP URI. Omitted URI parts will take default values. The
///host part of the URI cannot be omitted and URIs of the form
///"amqp://foo/" (note the trailling slash) also represent the
///default virtual host. The latter issue means that virtual
///hosts with an empty name are not addressable. </para></remarks>
public class ConnectionFactory : ConnectionFactoryBase, IConnectionFactory
{
/// <summary>Default user name (value: "guest")</summary>
public const string DefaultUser = "guest"; // PLEASE KEEP THIS MATCHING THE DOC ABOVE
/// <summary>Default password (value: "guest")</summary>
public const string DefaultPass = "guest"; // PLEASE KEEP THIS MATCHING THE DOC ABOVE
/// <summary>Default virtual host (value: "/")</summary>
public const string DefaultVHost = "/"; // PLEASE KEEP THIS MATCHING THE DOC ABOVE
/// <summary> Default value for the desired maximum channel
/// number, with zero meaning unlimited (value: 0)</summary>
public const ushort DefaultChannelMax = 0; // PLEASE KEEP THIS MATCHING THE DOC ABOVE
/// <summary>Default value for the desired maximum frame size,
/// with zero meaning unlimited (value: 0)</summary>
public const uint DefaultFrameMax = 0; // PLEASE KEEP THIS MATCHING THE DOC ABOVE
/// <summary>Default value for desired heartbeat interval, in
/// seconds, with zero meaning none (value: 0)</summary>
public const ushort DefaultHeartbeat = 0; // PLEASE KEEP THIS MATCHING THE DOC ABOVE
/// <summary> Default value for connection attempt timeout,
/// in milliseconds</summary>
public const int DefaultConnectionTimeout = 30 * 1000;
///<summary> Default SASL auth mechanisms to use.</summary>
public static AuthMechanismFactory[] DefaultAuthMechanisms =
new AuthMechanismFactory[] { new PlainMechanismFactory() };
private string m_username = DefaultUser;
/// <summary>Username to use when authenticating to the server</summary>
public string UserName
{
get { return m_username; }
set { m_username = value; }
}
private string m_password = DefaultPass;
/// <summary>Password to use when authenticating to the server</summary>
public string Password
{
get { return m_password; }
set { m_password = value; }
}
private string m_vhost = DefaultVHost;
/// <summary>Virtual host to access during this connection</summary>
public string VirtualHost
{
get { return m_vhost; }
set { m_vhost = value; }
}
private ushort m_requestedChannelMax = DefaultChannelMax;
/// <summary>Maximum channel number to ask for</summary>
public ushort RequestedChannelMax
{
get { return m_requestedChannelMax; }
set { m_requestedChannelMax = value; }
}
private uint m_requestedFrameMax = DefaultFrameMax;
/// <summary>Frame-max parameter to ask for (in bytes)</summary>
public uint RequestedFrameMax
{
get { return m_requestedFrameMax; }
set { m_requestedFrameMax = value; }
}
private ushort m_requestedHeartbeat = DefaultHeartbeat;
/// <summary>Heartbeat setting to request (in seconds)</summary>
public ushort RequestedHeartbeat
{
get { return m_requestedHeartbeat; }
set { m_requestedHeartbeat = value; }
}
/// <summary>Timeout setting for connection attempts (in milliseconds)</summary>
public int RequestedConnectionTimeout = DefaultConnectionTimeout;
private bool m_useBackgroundThreadsForIO = false;
/// <summary>
/// When set to true, background threads will be used for I/O and heartbeats.
/// </summary>
public bool UseBackgroundThreadsForIO
{
get { return m_useBackgroundThreadsForIO; }
set { m_useBackgroundThreadsForIO = value; }
}
private IDictionary<string, object> m_clientProperties =
Connection.DefaultClientProperties();
/// <summary>Dictionary of client properties to be sent to the
/// server</summary>
public IDictionary<string, object> ClientProperties
{
get { return m_clientProperties; }
set { m_clientProperties = value; }
}
///<summary>Ssl options setting</summary>
public SslOption Ssl = new SslOption();
/// <summary>
/// Set to true to enable automatic connection recovery.
/// </summary>
public bool AutomaticRecoveryEnabled = false;
/// <summary>
/// Set to true to make automatic connection recovery also recover
/// topology (exchanges, queues, bindings, etc).
/// </summary>
public bool TopologyRecoveryEnabled = true;
/// <summary>
/// Amount of time client will wait for before re-trying
/// to recover connection.
/// </summary>
public TimeSpan NetworkRecoveryInterval = TimeSpan.FromSeconds(5);
///<summary>The host to connect to</summary>
public String HostName = "localhost";
///<summary>The port to connect on.
/// AmqpTcpEndpoint.UseDefaultPort indicates the default for
/// the protocol should be used.</summary>
public int Port = AmqpTcpEndpoint.UseDefaultPort;
///<summary> SASL auth mechanisms to use.</summary>
public AuthMechanismFactory[] AuthMechanisms = DefaultAuthMechanisms;
///<summary>The AMQP protocol to be used. Currently 0-9-1.</summary>
public IProtocol Protocol = Protocols.DefaultProtocol;
///<summary>The AMQP connection target</summary>
public AmqpTcpEndpoint Endpoint
{
get
{
return new AmqpTcpEndpoint(HostName, Port, Ssl);
}
set
{
Port = value.Port;
HostName = value.HostName;
Ssl = value.Ssl;
}
}
///<summary>Set connection parameters using the amqp or amqps scheme</summary>
public Uri uri
{
set { SetUri(value); }
}
///<summary>Set connection parameters using the amqp or amqps scheme</summary>
public String Uri
{
set { SetUri(new Uri(value, UriKind.Absolute)); }
}
///<summary>Construct a fresh instance, with all fields set to
///their respective defaults.</summary>
public ConnectionFactory() { }
public IFrameHandler CreateFrameHandler()
{
IProtocol p = Protocols.DefaultProtocol;
return p.CreateFrameHandler(Endpoint,
SocketFactory,
RequestedConnectionTimeout);
}
///<summary>Create a connection to the specified endpoint.</summary>
public virtual IConnection CreateConnection()
{
IConnection conn = null;
try
{
if(this.AutomaticRecoveryEnabled)
{
AutorecoveringConnection ac = new AutorecoveringConnection(this);
ac.init();
conn = ac;
} else
{
IProtocol p = Protocols.DefaultProtocol;
conn = p.CreateConnection(this, false, this.CreateFrameHandler());
}
} catch (Exception e)
{
throw new BrokerUnreachableException(e);
}
return conn;
}
///<summary>Given a list of mechanism names supported by the
///server, select a preferred mechanism, or null if we have
///none in common.</summary>
public AuthMechanismFactory AuthMechanismFactory(string[] mechs) {
// Our list is in order of preference, the server one is not.
foreach (AuthMechanismFactory f in AuthMechanisms) {
if (((IList<string>)mechs).Contains(f.Name)) {
return f;
}
}
return null;
}
private void SetUri(Uri uri)
{
Endpoint = new AmqpTcpEndpoint();
if ("amqp".CompareTo(uri.Scheme.ToLower()) == 0) {
// nothing special to do
} else if ("amqps".CompareTo(uri.Scheme.ToLower()) == 0) {
Ssl.Enabled = true;
Ssl.AcceptablePolicyErrors =
SslPolicyErrors.RemoteCertificateNameMismatch;
Port = AmqpTcpEndpoint.DefaultAmqpSslPort;
} else {
throw new ArgumentException("Wrong scheme in AMQP URI: " +
uri.Scheme);
}
string host = uri.Host;
if (!String.IsNullOrEmpty(host)) {
HostName = host;
}
Ssl.ServerName = HostName;
int port = uri.Port;
if (port != -1) {
Port = port;
}
string userInfo = uri.UserInfo;
if (!String.IsNullOrEmpty(userInfo)) {
string[] userPass = userInfo.Split(':');
if (userPass.Length > 2) {
throw new ArgumentException("Bad user info in AMQP " +
"URI: " + userInfo);
}
UserName = UriDecode(userPass[0]);
if (userPass.Length == 2) {
Password = UriDecode(userPass[1]);
}
}
/* C# automatically changes URIs into a canonical form
that has at least the path segment "/". */
if (uri.Segments.Length > 2) {
throw new ArgumentException("Multiple segments in " +
"path of AMQP URI: " +
String.Join(", ", uri.Segments));
} else if (uri.Segments.Length == 2) {
VirtualHost = UriDecode(uri.Segments[1]);
}
}
//<summary>Unescape a string, protecting '+'.</summary>
private string UriDecode(string uri) {
return System.Uri.UnescapeDataString(uri.Replace("+", "%2B"));
}
}
}
| |
//Copyright 2019 Esri
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using System.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Core.Geometry;
using ArcGIS.Core.Data;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Editing.Templates;
using ArcGIS.Desktop.Core.Geoprocessing;
using ArcGIS.Desktop.Core;
namespace ConstructingGeometries
{
/// <summary>
/// This sample provide four buttons showing the construction of geometry types of type MapPoint, Multipoint, Polyline, and Polygon and shows how to:
/// * Construct and manipulate geometries
/// * Use GeometryEngine functionality
/// * Search and retrieve features
/// </summary>
/// <remarks>
/// 1. Download the Community Sample data (see under the 'Resources' section for downloading sample data)
/// 1. Make sure that the Sample data is unzipped in c:\data
/// 1. The project used for this sample is 'C:\Data\FeatureTest\FeatureTest.aprx'
/// 1. In Visual Studio click the Build menu. Then select Build Solution.
/// 1. Click Start button to open ArcGIS Pro.
/// 1. ArcGIS Pro will open, select the FeatureTest.aprx project
/// 1. Click on the ADD-IN tab and make sure that your active map contains Setup/point/multipoint/line/polygon features buttons as shown below.
/// 
/// 1. Click on Setup button to enable the create point and create multipoint buttons
/// 
/// 1. Click the createPoints button to create random points over the current extent of the map
/// 1. The map extent shows the random created points and also enables create polylines button
/// 
/// 1. Click the createPolylines button to create random lines the current extent of the map
/// 1. The map extent shows the random lines and also enables create polygons button
/// 
/// 1. Click the createPolygons button to create random polygon over the current extent of the map
/// 
/// </remarks>
internal class ConstructingGeometriesModule : Module
{
private static ConstructingGeometriesModule _this = null;
/// <summary>
/// Retrieve the singleton instance to this module here
/// </summary>
public static ConstructingGeometriesModule Current
{
get
{
return _this ?? (_this = (ConstructingGeometriesModule)FrameworkApplication.FindModule("ConstructingGeometries_Module"));
}
}
#region Overrides
/// <summary>
/// Called by Framework when ArcGIS Pro is closing
/// </summary>
/// <returns>False to prevent Pro from closing, otherwise True</returns>
protected override bool CanUnload()
{
//TODO - add your business logic
//return false to ~cancel~ Application close
return true;
}
/// <summary>
/// Generic implementation of ExecuteCommand to allow calls to
/// <see cref="FrameworkApplication.ExecuteCommand"/> to execute commands in
/// your Module.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
protected override Func<Task> ExecuteCommand(string id)
{
//TODO: replace generic implementation with custom logic
//etc as needed for your Module
var command = FrameworkApplication.GetPlugInWrapper(id) as ICommand;
if (command == null)
return () => Task.FromResult(0);
if (!command.CanExecute(null))
return () => Task.FromResult(0);
return () =>
{
command.Execute(null); // if it is a tool, execute will set current tool
return Task.FromResult(0);
};
}
#endregion Overrides
/// <summary>
/// The method ensures that there are point, multipoint, line, and polygon layers in the map of the active view.
/// In case the layer is missing, then a default feature class will be created in the default geodatabase of the project.
/// </summary>
public static async void PrepareTheSample()
{
var pointLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(lyr => lyr.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPoint).FirstOrDefault();
if (pointLayer == null)
{
await CreateLayer("sdk_points", "POINT");
}
var multiPointLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(lyr => lyr.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryMultipoint).FirstOrDefault();
if (multiPointLayer == null)
{
await CreateLayer("sdk_multipoints", "MULTIPOINT");
}
var polylineLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(lyr => lyr.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolyline).FirstOrDefault();
if (polylineLayer == null)
{
await CreateLayer("sdk_polyline", "POLYLINE");
}
var polygonLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(lyr => lyr.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolygon).FirstOrDefault();
if (polygonLayer == null)
{
await CreateLayer("sdk_polygon", "POLYGON");
}
}
/// <summary>
/// Create a feature class in the default geodatabase of the project.
/// </summary>
/// <param name="featureclassName">Name of the feature class to be created.</param>
/// <param name="featureclassType">Type of feature class to be created. Options are:
/// <list type="bullet">
/// <item>POINT</item>
/// <item>MULTIPOINT</item>
/// <item>POLYLINE</item>
/// <item>POLYGON</item></list></param>
/// <returns></returns>
private static async Task CreateLayer(string featureclassName, string featureclassType)
{
List<object> arguments = new List<object>
{
// store the results in the default geodatabase
CoreModule.CurrentProject.DefaultGeodatabasePath,
// name of the feature class
featureclassName,
// type of geometry
featureclassType,
// no template
"",
// no z values
"DISABLED",
// no m values
"DISABLED"
};
await QueuedTask.Run(() =>
{
// spatial reference
arguments.Add(SpatialReferenceBuilder.CreateSpatialReference(3857));
});
IGPResult result = await Geoprocessing.ExecuteToolAsync("CreateFeatureclass_management", Geoprocessing.MakeValueArray(arguments.ToArray()));
}
}
/// <summary>
/// Extension methods to generate random coordinates within a given extent.
/// </summary>
public static class RandomExtension
{
/// <summary>
/// Generate a random double number between the min and max values.
/// </summary>
/// <param name="random">Instance of a random class.</param>
/// <param name="minValue">The min value for the potential range.</param>
/// <param name="maxValue">The max value for the potential range.</param>
/// <returns>Random number between min and max</returns>
/// <remarks>The random result number will always be less than the max number.</remarks>
public static double NextDouble(this Random random, double minValue, double maxValue)
{
return random.NextDouble() * (maxValue - minValue) + minValue;
}
/// <summary>
/// /Generate a random coordinate (only x,y values) within the provided envelope.
/// </summary>
/// <param name="random">Instance of a random class.</param>
/// <param name="withinThisExtent">Area of interest in which the random coordinate will be created.</param>
/// <returns>A coordinate with random values (only x,y values) within the extent.</returns>
public static Coordinate2D NextCoordinate2D(this Random random, Envelope withinThisExtent)
{
return new Coordinate2D(random.NextDouble(withinThisExtent.XMin, withinThisExtent.XMax),
random.NextDouble(withinThisExtent.YMin, withinThisExtent.YMax));
}
/// <summary>
/// /Generate a random coordinate 3D (containing x,y,z values) within the provided envelope.
/// </summary>
/// <param name="random">Instance of a random class.</param>
/// <param name="withinThisExtent">Area of interest in which the random coordinate will be created.</param>
/// <returns>A coordinate with random values 3D (containing x,y,z values) within the extent.</returns>
public static Coordinate3D NextCoordinate3D(this Random random, Envelope withinThisExtent)
{
return new Coordinate3D(random.NextDouble(withinThisExtent.XMin, withinThisExtent.XMax),
random.NextDouble(withinThisExtent.YMin, withinThisExtent.YMax), 0);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using SecurityConsultantCore.Domain.Basic;
namespace SecurityConsultantCore.Pathfinding
{
public class TwoDPathFinderFast : I2DPathFinder
{
private readonly List<PathFinderNode> _closedNodes = new List<PathFinderNode>();
// Heap variables are initializated to default, but I like to do it anyway
private readonly ExpandedPathfindingGrid _grid;
private readonly PriorityQueueB<int> _openNodes;
private bool _shouldStop;
private readonly PathFinderNodeFast[] mCalcGrid;
private int mCloseNodeCounter;
private byte mCloseNodeValue = 2;
private readonly sbyte[,] mDirection = new sbyte[4, 2] {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
private int mEndLocation;
private bool mFound;
private readonly ushort mGridX;
private readonly ushort mGridXMinus1;
private readonly ushort mGridY;
private readonly ushort mGridYLog2;
//Promoted local variables to member variables to avoid recreation between calls
private int mH;
private int mLocation;
private ushort mLocationX;
private ushort mLocationY;
private int mNewG;
private int mNewLocation;
private ushort mNewLocationX;
private ushort mNewLocationY;
private byte mOpenNodeValue = 1;
public TwoDPathFinderFast(ExpandedPathfindingGrid grid)
{
if (grid == null)
throw new Exception("Grid cannot be null");
_grid = grid;
mGridX = (ushort) (_grid.GetWidth() + 1);
mGridY = (ushort) (_grid.GetHeight() + 1);
mGridXMinus1 = (ushort) (mGridX - 1);
mGridYLog2 = (ushort) Math.Log(mGridY, 2);
// This should be done at the constructor, for now we leave it here.
if ((Math.Log(mGridX, 2) != (int) Math.Log(mGridX, 2)) ||
(Math.Log(mGridY, 2) != (int) Math.Log(mGridY, 2)))
throw new Exception("Invalid Grid, size in X and Y must be power of 2");
if ((mCalcGrid == null) || (mCalcGrid.Length != mGridX*mGridY))
mCalcGrid = new PathFinderNodeFast[mGridX*mGridY];
_openNodes = new PriorityQueueB<int>(new ComparePFNodeMatrix(mCalcGrid));
}
public void CancelSearch()
{
_shouldStop = true;
}
public List<PathFinderNode> BeginPathSearch(XY start, XY end)
{
lock (this)
{
// Is faster if we don't clear the matrix, just assign different values for open and close and ignore the rest
// I could have user Array.Clear() but using unsafe code is faster, no much but it is.
//fixed (PathFinderNodeFast* pGrid = tmpGrid)
// ZeroMemory((byte*) pGrid, sizeof(PathFinderNodeFast) * 1000000);
mFound = false;
_shouldStop = false;
mCloseNodeCounter = 0;
mOpenNodeValue += 2;
mCloseNodeValue += 2;
_openNodes.Clear();
_closedNodes.Clear();
mLocation = (start.Y << mGridYLog2) + start.X;
mEndLocation = (end.Y << mGridYLog2) + end.X;
mCalcGrid[mLocation].G = 0;
mCalcGrid[mLocation].F = 2;
mCalcGrid[mLocation].PX = (ushort) start.X;
mCalcGrid[mLocation].PY = (ushort) start.Y;
mCalcGrid[mLocation].Status = mOpenNodeValue;
_openNodes.Push(mLocation);
while ((_openNodes.Count > 0) && !_shouldStop)
{
mLocation = _openNodes.Pop();
//Is it in closed list? means this node was already processed
if (mCalcGrid[mLocation].Status == mCloseNodeValue)
continue;
mLocationX = (ushort) (mLocation & mGridXMinus1);
mLocationY = (ushort) (mLocation >> mGridYLog2);
if (mLocation == mEndLocation)
{
mCalcGrid[mLocation].Status = mCloseNodeValue;
mFound = true;
break;
}
//Lets calculate each successors
for (var i = 0; i < 4; i++)
{
mNewLocationX = (ushort) (mLocationX + mDirection[i, 0]);
mNewLocationY = (ushort) (mLocationY + mDirection[i, 1]);
mNewLocation = (mNewLocationY << mGridYLog2) + mNewLocationX;
if ((mNewLocationX >= mGridX) || (mNewLocationY >= mGridY))
continue;
// Unbreakeable?
if (_grid[mNewLocationX, mNewLocationY] == 0)
continue;
mNewG = mCalcGrid[mLocation].G + _grid[mNewLocationX, mNewLocationY];
//Is it open or closed?
if ((mCalcGrid[mNewLocation].Status == mOpenNodeValue) ||
(mCalcGrid[mNewLocation].Status == mCloseNodeValue))
if (mCalcGrid[mNewLocation].G <= mNewG)
continue;
mCalcGrid[mNewLocation].PX = mLocationX;
mCalcGrid[mNewLocation].PY = mLocationY;
mCalcGrid[mNewLocation].G = mNewG;
mH = 2*(Math.Abs(mNewLocationX - end.X) + Math.Abs(mNewLocationY - end.Y));
mCalcGrid[mNewLocation].F = mNewG + mH;
_openNodes.Push(mNewLocation);
mCalcGrid[mNewLocation].Status = mOpenNodeValue;
}
mCloseNodeCounter++;
mCalcGrid[mLocation].Status = mCloseNodeValue;
}
if (mFound)
{
_closedNodes.Clear();
var posX = end.X;
var posY = end.Y;
var fNodeTmp = mCalcGrid[(end.Y << mGridYLog2) + end.X];
PathFinderNode fNode;
fNode.F = fNodeTmp.F;
fNode.G = fNodeTmp.G;
fNode.H = 0;
fNode.PX = fNodeTmp.PX;
fNode.PY = fNodeTmp.PY;
fNode.X = end.X;
fNode.Y = end.Y;
while ((fNode.X != fNode.PX) || (fNode.Y != fNode.PY))
{
_closedNodes.Add(fNode);
posX = fNode.PX;
posY = fNode.PY;
fNodeTmp = mCalcGrid[(posY << mGridYLog2) + posX];
fNode.F = fNodeTmp.F;
fNode.G = fNodeTmp.G;
fNode.H = 0;
fNode.PX = fNodeTmp.PX;
fNode.PY = fNodeTmp.PY;
fNode.X = posX;
fNode.Y = posY;
}
_closedNodes.Add(fNode);
return _closedNodes;
}
return null;
}
}
[DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
public static extern unsafe bool ZeroMemory(byte* destination, int length);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct PathFinderNodeFast
{
public int F; // f = gone + heuristic
public int G;
public ushort PX; // Parent
public ushort PY;
public byte Status;
}
internal class ComparePFNodeMatrix : IComparer<int>
{
private readonly PathFinderNodeFast[] mMatrix;
public ComparePFNodeMatrix(PathFinderNodeFast[] matrix)
{
mMatrix = matrix;
}
public int Compare(int a, int b)
{
if (mMatrix[a].F > mMatrix[b].F)
return 1;
if (mMatrix[a].F < mMatrix[b].F)
return -1;
return 0;
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using org.swyn.foundation.utils;
using tdbgui;
namespace tdbadmin
{
/// <summary>
/// Suppliertype Form.
/// </summary>
public class FSup : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox TDB_abgrp;
private System.Windows.Forms.Button TDB_ab_clr;
private System.Windows.Forms.Button TDB_ab_sel;
private System.Windows.Forms.Button TDB_ab_exit;
private System.Windows.Forms.Button TDB_ab_del;
private System.Windows.Forms.Button TDB_ab_upd;
private System.Windows.Forms.Button TDB_ab_ins;
private System.Windows.Forms.Label tdb_e_id;
private System.Windows.Forms.TextBox tdb_e_bez;
private System.Windows.Forms.TextBox tdb_e_text;
private System.Windows.Forms.Label tdb_l_text;
private System.Windows.Forms.Label tdb_l_bez;
private System.Windows.Forms.Label tdb_l_id;
private System.Windows.Forms.TextBox tdb_e_code;
private System.Windows.Forms.Label tdb_l_code;
private System.Windows.Forms.ComboBox Dlt_e_sta;
private System.Windows.Forms.Label Dlt_l_sta;
private System.Windows.Forms.NumericUpDown Dlt_e_level;
private System.Windows.Forms.NumericUpDown Dlt_e_anz;
private System.Windows.Forms.Label Dlt_l_anz;
private System.Windows.Forms.Label Dlt_l_level;
private System.Windows.Forms.CheckBox Dlt_e_ishost;
private System.Windows.Forms.Label Dlt_e_host;
private System.Windows.Forms.Label Dlt_l_host;
private System.Windows.Forms.ComboBox Dlt_e_parent;
private System.Windows.Forms.Label Dlt_l_parent;
private System.Windows.Forms.Label Dlt_l_dltt;
private System.Windows.Forms.Button Dlt_e_sel;
private System.Windows.Forms.Label Dlt_e_dltt;
private System.Windows.Forms.Label Dlt_e_kat;
private bool ishost;
private tdbgui.GUIsup dlt;
private int guikatid;
private int guidlttid;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public FSup()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
dlt = new tdbgui.GUIsup();
ishost = false;
guikatid = -1;
guidlttid = -1;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.Dlt_e_kat = new System.Windows.Forms.Label();
this.Dlt_e_dltt = new System.Windows.Forms.Label();
this.Dlt_e_sel = new System.Windows.Forms.Button();
this.Dlt_l_level = new System.Windows.Forms.Label();
this.Dlt_l_anz = new System.Windows.Forms.Label();
this.Dlt_e_anz = new System.Windows.Forms.NumericUpDown();
this.Dlt_e_level = new System.Windows.Forms.NumericUpDown();
this.Dlt_l_dltt = new System.Windows.Forms.Label();
this.Dlt_l_sta = new System.Windows.Forms.Label();
this.Dlt_e_sta = new System.Windows.Forms.ComboBox();
this.tdb_e_code = new System.Windows.Forms.TextBox();
this.tdb_l_code = new System.Windows.Forms.Label();
this.Dlt_e_ishost = new System.Windows.Forms.CheckBox();
this.Dlt_e_host = new System.Windows.Forms.Label();
this.Dlt_l_host = new System.Windows.Forms.Label();
this.Dlt_e_parent = new System.Windows.Forms.ComboBox();
this.Dlt_l_parent = new System.Windows.Forms.Label();
this.tdb_e_id = new System.Windows.Forms.Label();
this.tdb_e_bez = new System.Windows.Forms.TextBox();
this.tdb_e_text = new System.Windows.Forms.TextBox();
this.tdb_l_text = new System.Windows.Forms.Label();
this.tdb_l_bez = new System.Windows.Forms.Label();
this.tdb_l_id = new System.Windows.Forms.Label();
this.TDB_abgrp = new System.Windows.Forms.GroupBox();
this.TDB_ab_clr = new System.Windows.Forms.Button();
this.TDB_ab_sel = new System.Windows.Forms.Button();
this.TDB_ab_exit = new System.Windows.Forms.Button();
this.TDB_ab_del = new System.Windows.Forms.Button();
this.TDB_ab_upd = new System.Windows.Forms.Button();
this.TDB_ab_ins = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.Dlt_e_anz)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Dlt_e_level)).BeginInit();
this.TDB_abgrp.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.Dlt_e_kat);
this.groupBox1.Controls.Add(this.Dlt_e_dltt);
this.groupBox1.Controls.Add(this.Dlt_e_sel);
this.groupBox1.Controls.Add(this.Dlt_l_level);
this.groupBox1.Controls.Add(this.Dlt_l_anz);
this.groupBox1.Controls.Add(this.Dlt_e_anz);
this.groupBox1.Controls.Add(this.Dlt_e_level);
this.groupBox1.Controls.Add(this.Dlt_l_dltt);
this.groupBox1.Controls.Add(this.Dlt_l_sta);
this.groupBox1.Controls.Add(this.Dlt_e_sta);
this.groupBox1.Controls.Add(this.tdb_e_code);
this.groupBox1.Controls.Add(this.tdb_l_code);
this.groupBox1.Controls.Add(this.Dlt_e_ishost);
this.groupBox1.Controls.Add(this.Dlt_e_host);
this.groupBox1.Controls.Add(this.Dlt_l_host);
this.groupBox1.Controls.Add(this.Dlt_e_parent);
this.groupBox1.Controls.Add(this.Dlt_l_parent);
this.groupBox1.Controls.Add(this.tdb_e_id);
this.groupBox1.Controls.Add(this.tdb_e_bez);
this.groupBox1.Controls.Add(this.tdb_e_text);
this.groupBox1.Controls.Add(this.tdb_l_text);
this.groupBox1.Controls.Add(this.tdb_l_bez);
this.groupBox1.Controls.Add(this.tdb_l_id);
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox1.Location = new System.Drawing.Point(0, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(608, 397);
this.groupBox1.TabIndex = 13;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Description";
//
// Dlt_e_kat
//
this.Dlt_e_kat.Location = new System.Drawing.Point(224, 256);
this.Dlt_e_kat.Name = "Dlt_e_kat";
this.Dlt_e_kat.Size = new System.Drawing.Size(352, 16);
this.Dlt_e_kat.TabIndex = 29;
//
// Dlt_e_dltt
//
this.Dlt_e_dltt.Location = new System.Drawing.Point(224, 240);
this.Dlt_e_dltt.Name = "Dlt_e_dltt";
this.Dlt_e_dltt.Size = new System.Drawing.Size(352, 16);
this.Dlt_e_dltt.TabIndex = 28;
//
// Dlt_e_sel
//
this.Dlt_e_sel.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(192)), ((System.Byte)(255)));
this.Dlt_e_sel.Location = new System.Drawing.Point(136, 240);
this.Dlt_e_sel.Name = "Dlt_e_sel";
this.Dlt_e_sel.Size = new System.Drawing.Size(75, 32);
this.Dlt_e_sel.TabIndex = 5;
this.Dlt_e_sel.Text = "Select";
this.Dlt_e_sel.Click += new System.EventHandler(this.Dlt_e_sel_Click);
//
// Dlt_l_level
//
this.Dlt_l_level.Location = new System.Drawing.Point(360, 306);
this.Dlt_l_level.Name = "Dlt_l_level";
this.Dlt_l_level.Size = new System.Drawing.Size(40, 17);
this.Dlt_l_level.TabIndex = 26;
this.Dlt_l_level.Text = "Level";
//
// Dlt_l_anz
//
this.Dlt_l_anz.Location = new System.Drawing.Point(8, 304);
this.Dlt_l_anz.Name = "Dlt_l_anz";
this.Dlt_l_anz.TabIndex = 25;
this.Dlt_l_anz.Text = "Capacity";
//
// Dlt_e_anz
//
this.Dlt_e_anz.Location = new System.Drawing.Point(136, 304);
this.Dlt_e_anz.Maximum = new System.Decimal(new int[] {
1000,
0,
0,
0});
this.Dlt_e_anz.Name = "Dlt_e_anz";
this.Dlt_e_anz.Size = new System.Drawing.Size(56, 20);
this.Dlt_e_anz.TabIndex = 7;
this.Dlt_e_anz.Value = new System.Decimal(new int[] {
1,
0,
0,
0});
//
// Dlt_e_level
//
this.Dlt_e_level.Location = new System.Drawing.Point(408, 304);
this.Dlt_e_level.Maximum = new System.Decimal(new int[] {
1000,
0,
0,
0});
this.Dlt_e_level.Name = "Dlt_e_level";
this.Dlt_e_level.Size = new System.Drawing.Size(56, 20);
this.Dlt_e_level.TabIndex = 8;
this.Dlt_e_level.Value = new System.Decimal(new int[] {
1,
0,
0,
0});
//
// Dlt_l_dltt
//
this.Dlt_l_dltt.Location = new System.Drawing.Point(8, 240);
this.Dlt_l_dltt.Name = "Dlt_l_dltt";
this.Dlt_l_dltt.Size = new System.Drawing.Size(100, 32);
this.Dlt_l_dltt.TabIndex = 22;
this.Dlt_l_dltt.Text = "Supliertype / Category";
//
// Dlt_l_sta
//
this.Dlt_l_sta.Location = new System.Drawing.Point(8, 280);
this.Dlt_l_sta.Name = "Dlt_l_sta";
this.Dlt_l_sta.Size = new System.Drawing.Size(112, 23);
this.Dlt_l_sta.TabIndex = 21;
this.Dlt_l_sta.Text = "Best place attribute";
//
// Dlt_e_sta
//
this.Dlt_e_sta.Location = new System.Drawing.Point(136, 280);
this.Dlt_e_sta.Name = "Dlt_e_sta";
this.Dlt_e_sta.Size = new System.Drawing.Size(456, 21);
this.Dlt_e_sta.TabIndex = 6;
//
// tdb_e_code
//
this.tdb_e_code.Location = new System.Drawing.Point(136, 64);
this.tdb_e_code.Name = "tdb_e_code";
this.tdb_e_code.Size = new System.Drawing.Size(456, 20);
this.tdb_e_code.TabIndex = 1;
this.tdb_e_code.Text = "";
//
// tdb_l_code
//
this.tdb_l_code.Location = new System.Drawing.Point(8, 64);
this.tdb_l_code.Name = "tdb_l_code";
this.tdb_l_code.TabIndex = 16;
this.tdb_l_code.Text = "Code";
//
// Dlt_e_ishost
//
this.Dlt_e_ishost.Location = new System.Drawing.Point(488, 184);
this.Dlt_e_ishost.Name = "Dlt_e_ishost";
this.Dlt_e_ishost.TabIndex = 4;
this.Dlt_e_ishost.Text = "Top / Root ?";
this.Dlt_e_ishost.CheckedChanged += new System.EventHandler(this.Dlt_e_ishost_CheckedChanged);
//
// Dlt_e_host
//
this.Dlt_e_host.Location = new System.Drawing.Point(136, 208);
this.Dlt_e_host.Name = "Dlt_e_host";
this.Dlt_e_host.Size = new System.Drawing.Size(448, 23);
this.Dlt_e_host.TabIndex = 13;
//
// Dlt_l_host
//
this.Dlt_l_host.Location = new System.Drawing.Point(8, 208);
this.Dlt_l_host.Name = "Dlt_l_host";
this.Dlt_l_host.Size = new System.Drawing.Size(104, 23);
this.Dlt_l_host.TabIndex = 12;
this.Dlt_l_host.Text = "Root Supplier";
//
// Dlt_e_parent
//
this.Dlt_e_parent.Location = new System.Drawing.Point(136, 184);
this.Dlt_e_parent.Name = "Dlt_e_parent";
this.Dlt_e_parent.Size = new System.Drawing.Size(344, 21);
this.Dlt_e_parent.TabIndex = 3;
//
// Dlt_l_parent
//
this.Dlt_l_parent.Location = new System.Drawing.Point(8, 184);
this.Dlt_l_parent.Name = "Dlt_l_parent";
this.Dlt_l_parent.TabIndex = 10;
this.Dlt_l_parent.Text = "Parent";
//
// tdb_e_id
//
this.tdb_e_id.Location = new System.Drawing.Point(136, 24);
this.tdb_e_id.Name = "tdb_e_id";
this.tdb_e_id.Size = new System.Drawing.Size(64, 16);
this.tdb_e_id.TabIndex = 9;
//
// tdb_e_bez
//
this.tdb_e_bez.Location = new System.Drawing.Point(136, 40);
this.tdb_e_bez.Name = "tdb_e_bez";
this.tdb_e_bez.Size = new System.Drawing.Size(456, 20);
this.tdb_e_bez.TabIndex = 0;
this.tdb_e_bez.Text = "";
//
// tdb_e_text
//
this.tdb_e_text.Location = new System.Drawing.Point(136, 88);
this.tdb_e_text.Multiline = true;
this.tdb_e_text.Name = "tdb_e_text";
this.tdb_e_text.Size = new System.Drawing.Size(456, 88);
this.tdb_e_text.TabIndex = 2;
this.tdb_e_text.Text = "";
//
// tdb_l_text
//
this.tdb_l_text.Location = new System.Drawing.Point(8, 120);
this.tdb_l_text.Name = "tdb_l_text";
this.tdb_l_text.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.tdb_l_text.TabIndex = 4;
this.tdb_l_text.Text = "Description";
//
// tdb_l_bez
//
this.tdb_l_bez.Location = new System.Drawing.Point(8, 39);
this.tdb_l_bez.Name = "tdb_l_bez";
this.tdb_l_bez.TabIndex = 2;
this.tdb_l_bez.Text = "Title";
//
// tdb_l_id
//
this.tdb_l_id.Location = new System.Drawing.Point(8, 21);
this.tdb_l_id.Name = "tdb_l_id";
this.tdb_l_id.TabIndex = 1;
this.tdb_l_id.Text = "ID";
//
// TDB_abgrp
//
this.TDB_abgrp.Controls.Add(this.TDB_ab_clr);
this.TDB_abgrp.Controls.Add(this.TDB_ab_sel);
this.TDB_abgrp.Controls.Add(this.TDB_ab_exit);
this.TDB_abgrp.Controls.Add(this.TDB_ab_del);
this.TDB_abgrp.Controls.Add(this.TDB_ab_upd);
this.TDB_abgrp.Controls.Add(this.TDB_ab_ins);
this.TDB_abgrp.Dock = System.Windows.Forms.DockStyle.Bottom;
this.TDB_abgrp.Location = new System.Drawing.Point(0, 344);
this.TDB_abgrp.Name = "TDB_abgrp";
this.TDB_abgrp.Size = new System.Drawing.Size(608, 53);
this.TDB_abgrp.TabIndex = 15;
this.TDB_abgrp.TabStop = false;
this.TDB_abgrp.Text = "Actions";
//
// TDB_ab_clr
//
this.TDB_ab_clr.Dock = System.Windows.Forms.DockStyle.Right;
this.TDB_ab_clr.Location = new System.Drawing.Point(455, 16);
this.TDB_ab_clr.Name = "TDB_ab_clr";
this.TDB_ab_clr.Size = new System.Drawing.Size(75, 34);
this.TDB_ab_clr.TabIndex = 13;
this.TDB_ab_clr.Text = "Clear";
this.TDB_ab_clr.Click += new System.EventHandler(this.TDB_ab_clr_Click);
//
// TDB_ab_sel
//
this.TDB_ab_sel.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(192)), ((System.Byte)(255)));
this.TDB_ab_sel.Dock = System.Windows.Forms.DockStyle.Left;
this.TDB_ab_sel.Location = new System.Drawing.Point(228, 16);
this.TDB_ab_sel.Name = "TDB_ab_sel";
this.TDB_ab_sel.Size = new System.Drawing.Size(80, 34);
this.TDB_ab_sel.TabIndex = 12;
this.TDB_ab_sel.Text = "Select";
this.TDB_ab_sel.Click += new System.EventHandler(this.TDB_ab_sel_Click);
//
// TDB_ab_exit
//
this.TDB_ab_exit.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(192)), ((System.Byte)(192)));
this.TDB_ab_exit.Dock = System.Windows.Forms.DockStyle.Right;
this.TDB_ab_exit.Location = new System.Drawing.Point(530, 16);
this.TDB_ab_exit.Name = "TDB_ab_exit";
this.TDB_ab_exit.Size = new System.Drawing.Size(75, 34);
this.TDB_ab_exit.TabIndex = 14;
this.TDB_ab_exit.Text = "Exit";
this.TDB_ab_exit.Click += new System.EventHandler(this.TDB_ab_exit_Click);
//
// TDB_ab_del
//
this.TDB_ab_del.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192)));
this.TDB_ab_del.Dock = System.Windows.Forms.DockStyle.Left;
this.TDB_ab_del.Location = new System.Drawing.Point(153, 16);
this.TDB_ab_del.Name = "TDB_ab_del";
this.TDB_ab_del.Size = new System.Drawing.Size(75, 34);
this.TDB_ab_del.TabIndex = 11;
this.TDB_ab_del.Text = "Delete";
this.TDB_ab_del.Click += new System.EventHandler(this.TDB_ab_del_Click);
//
// TDB_ab_upd
//
this.TDB_ab_upd.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192)));
this.TDB_ab_upd.Dock = System.Windows.Forms.DockStyle.Left;
this.TDB_ab_upd.Location = new System.Drawing.Point(78, 16);
this.TDB_ab_upd.Name = "TDB_ab_upd";
this.TDB_ab_upd.Size = new System.Drawing.Size(75, 34);
this.TDB_ab_upd.TabIndex = 10;
this.TDB_ab_upd.Text = "Update";
this.TDB_ab_upd.Click += new System.EventHandler(this.TDB_ab_upd_Click);
//
// TDB_ab_ins
//
this.TDB_ab_ins.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192)));
this.TDB_ab_ins.Dock = System.Windows.Forms.DockStyle.Left;
this.TDB_ab_ins.Location = new System.Drawing.Point(3, 16);
this.TDB_ab_ins.Name = "TDB_ab_ins";
this.TDB_ab_ins.Size = new System.Drawing.Size(75, 34);
this.TDB_ab_ins.TabIndex = 9;
this.TDB_ab_ins.Text = "Insert";
this.TDB_ab_ins.Click += new System.EventHandler(this.TDB_ab_ins_Click);
//
// FSup
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(608, 397);
this.Controls.Add(this.TDB_abgrp);
this.Controls.Add(this.groupBox1);
this.Name = "FSup";
this.Text = "Supplier";
this.Load += new System.EventHandler(this.FSup_Load);
this.groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.Dlt_e_anz)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.Dlt_e_level)).EndInit();
this.TDB_abgrp.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
#region Form callbacks
private void TDB_ab_sel_Click(object sender, System.EventArgs e)
{
SelTreeForm Fsel = new SelTreeForm();
dlt.SelTree(Fsel.GetTV);
Fsel.Accept += new EventHandler(TDB_ab_sel_Click_Return);
Fsel.ShowDialog(this);
}
void TDB_ab_sel_Click_Return(object sender, EventArgs e)
{
int id = -1, rows = 0;
SelTreeForm Fsel = (SelTreeForm)sender;
id = Fsel.GetID;
dlt.Get(id, ref rows);
this.tdb_e_code.Text = dlt.ObjCode;
this.tdb_e_id.Text = dlt.ObjId.ToString();
this.tdb_e_bez.Text = dlt.ObjBez;
this.tdb_e_text.Text = dlt.ObjText;
if (dlt.ObjParentId == -1)
{
this.Dlt_e_parent.SelectedValue = -1;
this.Dlt_e_ishost.CheckState = CheckState.Checked;
this.Dlt_e_parent.Visible = false;
ishost = true;
}
else
{
this.Dlt_e_parent.SelectedValue = dlt.ObjParentId;
this.Dlt_e_ishost.CheckState = CheckState.Unchecked;
this.Dlt_e_parent.Visible = true;
ishost = false;
}
tdb.Sup dlt2 = new tdb.Sup();
this.Dlt_e_host.Text = dlt2.GetBez(dlt.ObjHost);
this.Dlt_e_anz.Value = dlt.ObjCapacity;
this.Dlt_e_level.Value = dlt.ObjLevel;
guikatid = dlt.ObjCategory;
guidlttid = dlt.ObjSuptype;
this.Dlt_e_dltt.Text = dlt.ObjSupT;
this.Dlt_e_kat.Text = dlt.ObjCatT;
}
private void TDB_ab_exit_Click(object sender, System.EventArgs e)
{
Close();
}
private void TDB_ab_ins_Click(object sender, System.EventArgs e)
{
dlt.InsUpd(true, tdb_e_bez.Text, tdb_e_text.Text, tdb_e_code.Text,
(int)this.Dlt_e_parent.SelectedValue, ishost, this.guikatid,
this.guidlttid, (int)this.Dlt_e_sta.SelectedValue,
(int)this.Dlt_e_level.Value, (int)this.Dlt_e_anz.Value);
tdb_e_id.Text = dlt.ObjId.ToString();
}
private void TDB_ab_upd_Click(object sender, System.EventArgs e)
{
dlt.InsUpd(false, tdb_e_bez.Text, tdb_e_text.Text, tdb_e_code.Text,
(int)this.Dlt_e_parent.SelectedValue, ishost, this.guikatid,
this.guidlttid, (int)this.Dlt_e_sta.SelectedValue,
(int)this.Dlt_e_level.Value, (int)this.Dlt_e_anz.Value);
}
private void TDB_ab_del_Click(object sender, System.EventArgs e)
{
int rows = 0;
dlt.Get(Convert.ToInt32(tdb_e_id.Text), ref rows);
dlt.Delete();
}
private void TDB_ab_clr_Click(object sender, System.EventArgs e)
{
tdb_e_id.Text = "";
tdb_e_bez.Text = "";
tdb_e_text.Text = "";
Dlt_e_host.Text = "";
Dlt_e_kat.Text = "";
Dlt_e_dltt.Text = "";
}
private void FSup_Load(object sender, System.EventArgs e)
{
dlt.ObjOptional = true;
dlt.SetCombo(this.Dlt_e_parent);
tdbgui.GUIsta sta = new tdbgui.GUIsta();
sta.ObjTyp = tdb.StatusTypes.stadlt;
sta.SetCombo(this.Dlt_e_sta);
}
private void Dlt_e_ishost_CheckedChanged(object sender, System.EventArgs e)
{
if (this.Dlt_e_ishost.CheckState == CheckState.Checked)
{
this.Dlt_e_parent.Visible = false;
ishost = true;
}
else
{
this.Dlt_e_parent.Visible = true;
ishost = false;
}
}
private void Dlt_e_sel_Click(object sender, System.EventArgs e)
{
tdbgui.GUIcat cat = new tdbgui.GUIcat();
SelForm Fsel = new SelForm();
cat.Sel(Fsel.GetLV);
Fsel.Accept += new EventHandler(Dlt_e_sel_Return);
Fsel.ShowDialog(this);
}
void Dlt_e_sel_Return(object sender, EventArgs e)
{
SelForm Fsel = (SelForm)sender;
System.Windows.Forms.ListView sellv;
sellv = Fsel.GetLV;
ListViewItem lvitem = null;
if(sellv.SelectedItems.Count > 0)
lvitem = sellv.SelectedItems[0];
ListViewItem.ListViewSubItem LVSubItem = null;
if(lvitem != null)
{
LVSubItem = lvitem.SubItems[0];
guikatid = Convert.ToInt32(LVSubItem.Text);
LVSubItem = lvitem.SubItems[1];
this.Dlt_e_kat.Text = LVSubItem.Text;
LVSubItem = lvitem.SubItems[2];
guidlttid = Convert.ToInt32(LVSubItem.Text);
LVSubItem = lvitem.SubItems[3];
this.Dlt_e_dltt.Text = LVSubItem.Text;
}
}
#endregion
}
}
| |
/*
Copyright 2012 Michael Edwards
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//-CRE-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Glass.Mapper.Profilers;
using Glass.Mapper.Sc.Profilers;
using RazorEngine.Templating;
using Sitecore.Web.UI;
using System.Web.UI;
using Sitecore.Data.Items;
using System.Web.Mvc;
namespace Glass.Mapper.Sc.Razor.Web.Ui
{
/// <summary>
/// Class AbstractRazorControl
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class AbstractRazorControl<T> : WebControl, IRazorControl, Sitecore.Layouts.IExpandable
{
IPerformanceProfiler _profiler = new SitecoreProfiler();
/// <summary>
/// Gets or sets the profiler.
/// </summary>
/// <value>
/// The profiler.
/// </value>
public IPerformanceProfiler Profiler
{
get{
return _profiler;
}
set
{
_profiler = value;
}
}
private ISitecoreContext _sitecoreContext;
/// <summary>
/// Gets the view manager.
/// </summary>
/// <value>
/// The view manager.
/// </value>
public ViewManager ViewManager { get; private set; }
///// <summary>
///// A list of placeholders to render on the page.
///// </summary>
///// <value>The placeholders.</value>
//public IEnumerable<string> Placeholders
//{
// get;
// set;
//}
/// <summary>
/// View data
/// </summary>
/// <value>The view data.</value>
public ViewDataDictionary ViewData { get; private set; }
/// <summary>
/// The path to the Razor view
/// </summary>
/// <value>The view.</value>
public CachedView View
{
get;
set;
}
/// <summary>
/// The name of the Glass Context to use
/// </summary>
/// <value>The name of the context.</value>
public string ContextName
{
get;
set;
}
/// <summary>
/// The model to pass to the Razor view.
/// </summary>
/// <value>The model.</value>
public T Model
{
get;
private set;
}
/// <summary>
/// Gets the sitecore service.
/// </summary>
/// <value>The sitecore service.</value>
public ISitecoreContext SitecoreContext
{
get
{
if (_sitecoreContext == null)
{
if (ContextName.IsNotNullOrEmpty())
{
_sitecoreContext = new SitecoreContext(ContextName)
{
Profiler = Profiler
};
}
else
{
_sitecoreContext = new SitecoreContext
{
Profiler = Profiler
};
}
}
return _sitecoreContext;
}
}
/// <summary>
/// Gives access to the GlassHtml helper class
/// </summary>
public IGlassHtml GlassHtml { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="AbstractRazorControl{T}"/> class.
/// </summary>
public AbstractRazorControl()
{
ViewData = new ViewDataDictionary();
ViewManager = new ViewManager();
GlassHtml = new GlassHtml(SitecoreContext);
}
/// <summary>
/// Put your logic to create your model here
/// </summary>
/// <returns>`0.</returns>
public abstract T GetModel();
/// <summary>
/// Returns either the data source item or if no data source is specified the context item
/// </summary>
/// <returns>Item.</returns>
protected Item GetDataSourceOrContextItem()
{
return DataSource.IsNullOrEmpty() ? Sitecore.Context.Item :
Sitecore.Context.Database.GetItem(DataSource);
}
/// <summary>
/// Get caching identifier. Must be implemented by controls that supports caching.
/// </summary>
/// <returns>System.String.</returns>
/// <remarks>If an empty string is returned, the control will not be cached.</remarks>
protected override string GetCachingID()
{
return View.Name;
}
/// <summary>
/// Sends server control content to a provided <see cref="T:System.Web.UI.HtmlTextWriter"></see> object, which writes the content to be rendered on the client.
/// </summary>
/// <param name="output">The <see cref="T:System.Web.UI.HtmlTextWriter"></see> object that receives the server control content.</param>
/// <exception cref="Glass.Mapper.Sc.Razor.RazorException"></exception>
/// <remarks>When developing custom server controls, you can override this method to generate content for an ASP.NET page.</remarks>
protected override void DoRender(HtmlTextWriter output)
{
try
{
Profiler.Start("Razor engine {0}".Formatted(View.Name));
Profiler.Start("Get Model");
Model = GetModel();
Profiler.End("Get Model");
Profiler.Start("Create Template");
var template =
RazorEngine.Razor.GetTemplate(View.ViewContent, Model, View.Name) as ITemplateBase;
Profiler.End("Create Template");
Profiler.Start("Configure Template");
template.Configure(SitecoreContext, ViewData, this);
Profiler.End("Configure Template");
Profiler.Start("Run Template");
((RazorEngine.Templating.ITemplate) template).Run(new ExecuteContext(), output);
Profiler.End("Run Template");
}
catch (TemplateCompilationException ex)
{
var errors = new StringBuilder();
ex.Errors.ForEach(x =>
{
errors.AppendLine("File: {0}".Formatted(View));
errors.AppendLine(x.ErrorText);
});
// throw new RazorException(errors.ToString());
WriteException(output, ex);
}
catch (Exception ex)
{
WriteException(output, ex);
}
finally
{
Profiler.End("Razor engine {0}".Formatted(View));
}
}
private void WriteException(HtmlTextWriter output, Exception ex)
{
if (!GlassRazorSettings.CatchExceptions)
{
throw ex;
}
output.Write("<h1>Glass Razor Rendering Exception</h1>");
output.Write("<p>View: {0}</p>".Formatted(View.Name));
Exception subEx = ex;
while (subEx != null)
{
output.Write("<p>{0}</p>".Formatted(subEx.Message));
output.Write("<pre>{0}</pre>".Formatted(subEx.StackTrace));
subEx = subEx.InnerException;
}
Sitecore.Diagnostics.Log.Error("Glass Razor Rendering Error {0}".Formatted(View), ex, this);
}
/// <summary>
/// Expands this instance.
/// </summary>
public void Expand()
{
if (View.Placeholders != null)
{
foreach (var placeHolderName in View.Placeholders)
{
var holder = new Sitecore.Web.UI.WebControls.Placeholder();
holder.Key = placeHolderName.ToLower();
Controls.Add(holder);
}
}
Controls.Cast<Control>().Where(x => x is Sitecore.Layouts.IExpandable)
.Cast<Sitecore.Layouts.IExpandable>().ToList().ForEach(x => x.Expand());
}
/// <summary>
/// Converts rendering parameters to a concrete type. Use this method if you have defined the template ID on the
/// model configuration.
/// </summary>
/// <typeparam name="TK"></typeparam>
/// <returns></returns>
public virtual TK GetRenderingParameters<TK>() where TK : class
{
return GlassHtml.GetRenderingParameters<TK>(Parameters);
}
}
}
| |
// 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 Microsoft.Build.Framework;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Microsoft.Build.Shared;
using System.IO;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public class SGen_Tests
{
internal class SGenExtension : SGen
{
internal string CommandLine()
{
return base.GenerateCommandLineCommands();
}
}
[Fact]
public void KeyFileQuotedOnCommandLineIfNecessary()
{
SGenExtension sgen = new SGenExtension();
sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
sgen.BuildAssemblyPath = "C:\\SomeFolder\\MyAsm.dll";
sgen.ShouldGenerateSerializer = true;
sgen.UseProxyTypes = false;
// This should result in a nested, quoted parameter on
// the command line, which ultimately looks like this:
//
// /compiler:"/keyfile:\"c:\Some Folder\MyKeyFile.snk\""
//
sgen.KeyFile = "c:\\Some Folder\\MyKeyFile.snk";
string commandLine = sgen.CommandLine();
Assert.True(commandLine.IndexOf("/compiler:\"/keyfile:\\\"" + sgen.KeyFile + "\\\"\"", StringComparison.OrdinalIgnoreCase) >= 0);
}
[Fact]
public void TestKeepFlagTrue()
{
SGenExtension sgen = new SGenExtension();
sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
sgen.BuildAssemblyPath = "C:\\SomeFolder\\MyAsm.dll";
sgen.ShouldGenerateSerializer = true;
sgen.UseProxyTypes = false;
sgen.UseKeep = true;
string commandLine = sgen.CommandLine();
Assert.True(commandLine.IndexOf("/keep", StringComparison.OrdinalIgnoreCase) >= 0);
}
[Fact]
public void TestKeepFlagFalse()
{
SGenExtension sgen = new SGenExtension();
sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
sgen.BuildAssemblyPath = "C:\\SomeFolder\\MyAsm.dll";
sgen.ShouldGenerateSerializer = true;
sgen.UseProxyTypes = false;
sgen.UseKeep = false;
string commandLine = sgen.CommandLine();
Assert.True(commandLine.IndexOf("/keep", StringComparison.OrdinalIgnoreCase) < 0);
}
[Fact]
public void TestInputChecks1()
{
MockEngine engine = new MockEngine();
SGenExtension sgen = new SGenExtension();
sgen.BuildEngine = engine;
sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" + Path.GetInvalidPathChars()[0];
sgen.BuildAssemblyPath = "C:\\SomeFolder\\MyAsm.dll";
sgen.ShouldGenerateSerializer = true;
sgen.UseProxyTypes = false;
// This should result in a quoted parameter...
sgen.KeyFile = "c:\\Some Folder\\MyKeyFile.snk";
string commandLine = sgen.CommandLine();
Assert.Equal(1, engine.Errors);
}
[Fact]
public void TestInputChecks2()
{
MockEngine engine = new MockEngine();
SGenExtension sgen = new SGenExtension();
sgen.BuildEngine = engine;
sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
sgen.BuildAssemblyPath = "C:\\SomeFolder\\MyAsm.dll" + Path.GetInvalidPathChars()[0];
sgen.ShouldGenerateSerializer = true;
sgen.UseProxyTypes = false;
// This should result in a quoted parameter...
sgen.KeyFile = "c:\\Some Folder\\MyKeyFile.snk";
string commandLine = sgen.CommandLine();
Assert.Equal(1, engine.Errors);
}
[Fact]
public void TestInputChecks3()
{
Assert.Throws<ArgumentNullException>(() =>
{
MockEngine engine = new MockEngine();
SGenExtension sgen = new SGenExtension();
sgen.BuildEngine = engine;
sgen.BuildAssemblyName = null;
sgen.BuildAssemblyPath = "C:\\SomeFolder\\MyAsm.dll";
sgen.ShouldGenerateSerializer = true;
sgen.UseProxyTypes = false;
// This should result in a quoted parameter...
sgen.KeyFile = "c:\\Some Folder\\MyKeyFile.snk";
string commandLine = sgen.CommandLine();
}
);
}
[Fact]
public void TestInputChecks4()
{
Assert.Throws<ArgumentNullException>(() =>
{
MockEngine engine = new MockEngine();
SGenExtension sgen = new SGenExtension();
sgen.BuildEngine = engine;
sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
sgen.BuildAssemblyPath = null;
sgen.ShouldGenerateSerializer = true;
sgen.UseProxyTypes = false;
// This should result in a quoted parameter...
sgen.KeyFile = "c:\\Some Folder\\MyKeyFile.snk";
string commandLine = sgen.CommandLine();
}
);
}
[Fact]
public void TestInputPlatform()
{
SGenExtension sgen = new SGenExtension();
sgen.Platform = "x86";
sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
sgen.BuildAssemblyPath = NativeMethodsShared.IsUnixLike
? "/SomeFolder/MyAsm.dll"
: "C:\\SomeFolder\\MyAsm.dll";
sgen.ShouldGenerateSerializer = true;
string commandLine = sgen.CommandLine();
string targetCommandLine = "/assembly:\"" + sgen.BuildAssemblyPath + Path.DirectorySeparatorChar
+ "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\" /compiler:/platform:x86";
Assert.Equal(targetCommandLine, commandLine);
}
[Fact]
public void TestInputTypes()
{
SGenExtension sgen = new SGenExtension();
sgen.Types = new string[] { "System.String", "System.Boolean" };
sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
sgen.BuildAssemblyPath = NativeMethodsShared.IsUnixLike
? "/SomeFolder/MyAsm.dll"
: "C:\\SomeFolder\\MyAsm.dll";
sgen.ShouldGenerateSerializer = true;
string commandLine = sgen.CommandLine();
string targetCommandLine = "/assembly:\"" + sgen.BuildAssemblyPath + Path.DirectorySeparatorChar
+ "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\" /type:System.String /type:System.Boolean";
Assert.Equal(targetCommandLine, commandLine);
}
[Fact]
public void TestInputEmptyTypesAndPlatform()
{
SGenExtension sgen = new SGenExtension();
sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
sgen.BuildAssemblyPath = NativeMethodsShared.IsUnixLike ? "/SomeFolder/MyAsm.dll" : "C:\\SomeFolder\\MyAsm.dll";
sgen.ShouldGenerateSerializer = true;
string commandLine = sgen.CommandLine();
string targetCommandLine = "/assembly:\"" + sgen.BuildAssemblyPath + Path.DirectorySeparatorChar
+ "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\"";
Assert.Equal(targetCommandLine, commandLine);
}
[Fact]
public void TestNullReferences()
{
SGenExtension sgen = new SGenExtension();
sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
sgen.BuildAssemblyPath = "C:\\SomeFolder\\MyAsm.dll";
sgen.ShouldGenerateSerializer = true;
sgen.UseProxyTypes = false;
sgen.UseKeep = false;
sgen.References = null;
string commandLine = sgen.CommandLine();
Assert.True(commandLine.IndexOf("/reference:", StringComparison.OrdinalIgnoreCase) < 0);
}
[Fact]
public void TestEmptyReferences()
{
SGenExtension sgen = new SGenExtension();
sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
sgen.BuildAssemblyPath = "C:\\SomeFolder\\MyAsm.dll";
sgen.ShouldGenerateSerializer = true;
sgen.UseProxyTypes = false;
sgen.UseKeep = false;
sgen.References = new string[]{ };
string commandLine = sgen.CommandLine();
Assert.True(commandLine.IndexOf("/reference:", StringComparison.OrdinalIgnoreCase) < 0);
}
[Fact]
public void TestReferencesCommandLine()
{
SGenExtension sgen = new SGenExtension();
sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
sgen.BuildAssemblyPath = "C:\\SomeFolder\\MyAsm.dll";
sgen.ShouldGenerateSerializer = true;
sgen.UseProxyTypes = false;
sgen.UseKeep = false;
sgen.References = new string[]{ "C:\\SomeFolder\\reference1.dll", "C:\\SomeFolder\\reference2.dll" };
string commandLine = sgen.CommandLine();
string targetCommandLine = "/assembly:\"" + sgen.BuildAssemblyPath + Path.DirectorySeparatorChar
+ "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\" /reference:\"C:\\SomeFolder\\reference1.dll,C:\\SomeFolder\\reference2.dll\"";
Assert.Equal(targetCommandLine, commandLine);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Xml;
using System.Linq;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Security;
// The interface is a perf optimization.
// Only KeyValuePairAdapter should implement the interface.
internal interface IKeyValuePairAdapter { }
//Special Adapter class to serialize KeyValuePair as Dictionary needs it when polymorphism is involved
[DataContract(Namespace = "http://schemas.datacontract.org/2004/07/System.Collections.Generic")]
internal class KeyValuePairAdapter<K, T> : IKeyValuePairAdapter
{
private K _kvpKey;
private T _kvpValue;
public KeyValuePairAdapter(KeyValuePair<K, T> kvPair)
{
_kvpKey = kvPair.Key;
_kvpValue = kvPair.Value;
}
[DataMember(Name = "key")]
public K Key
{
get { return _kvpKey; }
set { _kvpKey = value; }
}
[DataMember(Name = "value")]
public T Value
{
get
{
return _kvpValue;
}
set
{
_kvpValue = value;
}
}
internal KeyValuePair<K, T> GetKeyValuePair()
{
return new KeyValuePair<K, T>(_kvpKey, _kvpValue);
}
internal static KeyValuePairAdapter<K, T> GetKeyValuePairAdapter(KeyValuePair<K, T> kvPair)
{
return new KeyValuePairAdapter<K, T>(kvPair);
}
}
#if USE_REFEMIT
public interface IKeyValue
#else
internal interface IKeyValue
#endif
{
object Key { get; set; }
object Value { get; set; }
}
[DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
#if USE_REFEMIT
public struct KeyValue<K, V> : IKeyValue
#else
internal struct KeyValue<K, V> : IKeyValue
#endif
{
private K _key;
private V _value;
internal KeyValue(K key, V value)
{
_key = key;
_value = value;
}
[DataMember(IsRequired = true)]
public K Key
{
get { return _key; }
set { _key = value; }
}
[DataMember(IsRequired = true)]
public V Value
{
get { return _value; }
set { _value = value; }
}
object IKeyValue.Key
{
get { return _key; }
set { _key = (K)value; }
}
object IKeyValue.Value
{
get { return _value; }
set { _value = (V)value; }
}
}
#if uapaot
public enum CollectionKind : byte
#else
internal enum CollectionKind : byte
#endif
{
None,
GenericDictionary,
Dictionary,
GenericList,
GenericCollection,
List,
GenericEnumerable,
Collection,
Enumerable,
Array,
}
#if USE_REFEMIT || uapaot
public sealed class CollectionDataContract : DataContract
#else
internal sealed class CollectionDataContract : DataContract
#endif
{
private XmlDictionaryString _collectionItemName;
private XmlDictionaryString _childElementNamespace;
private DataContract _itemContract;
private CollectionDataContractCriticalHelper _helper;
public CollectionDataContract(CollectionKind kind) : base(new CollectionDataContractCriticalHelper(kind))
{
InitCollectionDataContract(this);
}
internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type))
{
InitCollectionDataContract(this);
}
private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private CollectionDataContract(Type type, string invalidCollectionInSharedContractMessage) : base(new CollectionDataContractCriticalHelper(type, invalidCollectionInSharedContractMessage))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private void InitCollectionDataContract(DataContract sharedTypeContract)
{
_helper = base.Helper as CollectionDataContractCriticalHelper;
_collectionItemName = _helper.CollectionItemName;
if (_helper.Kind == CollectionKind.Dictionary || _helper.Kind == CollectionKind.GenericDictionary)
{
_itemContract = _helper.ItemContract;
}
_helper.SharedTypeContract = sharedTypeContract;
}
private static Type[] KnownInterfaces
{
get
{ return CollectionDataContractCriticalHelper.KnownInterfaces; }
}
internal CollectionKind Kind
{
get
{ return _helper.Kind; }
}
public Type ItemType
{
get
{ return _helper.ItemType; }
set { _helper.ItemType = value; }
}
public DataContract ItemContract
{
get
{
return _itemContract ?? _helper.ItemContract;
}
set
{
_itemContract = value;
_helper.ItemContract = value;
}
}
internal DataContract SharedTypeContract
{
get
{ return _helper.SharedTypeContract; }
}
public string ItemName
{
get
{ return _helper.ItemName; }
set
{ _helper.ItemName = value; }
}
public XmlDictionaryString CollectionItemName
{
get { return _collectionItemName; }
set { _collectionItemName = value; }
}
public string KeyName
{
get
{ return _helper.KeyName; }
set
{ _helper.KeyName = value; }
}
public string ValueName
{
get
{ return _helper.ValueName; }
set
{ _helper.ValueName = value; }
}
internal bool IsDictionary
{
get { return KeyName != null; }
}
public XmlDictionaryString ChildElementNamespace
{
get
{
if (_childElementNamespace == null)
{
lock (this)
{
if (_childElementNamespace == null)
{
if (_helper.ChildElementNamespace == null && !IsDictionary)
{
XmlDictionaryString tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary());
Interlocked.MemoryBarrier();
_helper.ChildElementNamespace = tempChildElementNamespace;
}
_childElementNamespace = _helper.ChildElementNamespace;
}
}
}
return _childElementNamespace;
}
}
internal bool IsItemTypeNullable
{
get { return _helper.IsItemTypeNullable; }
set { _helper.IsItemTypeNullable = value; }
}
internal bool IsConstructorCheckRequired
{
get
{ return _helper.IsConstructorCheckRequired; }
set
{ _helper.IsConstructorCheckRequired = value; }
}
internal MethodInfo GetEnumeratorMethod
{
get
{ return _helper.GetEnumeratorMethod; }
}
internal MethodInfo AddMethod
{
get
{ return _helper.AddMethod; }
}
internal ConstructorInfo Constructor
{
get
{ return _helper.Constructor; }
}
public override DataContractDictionary KnownDataContracts
{
get
{ return _helper.KnownDataContracts; }
set
{ _helper.KnownDataContracts = value; }
}
internal string InvalidCollectionInSharedContractMessage
{
get
{ return _helper.InvalidCollectionInSharedContractMessage; }
}
#if uapaot
[RemovableFeature(ReflectionBasedSerializationFeature.Name)]
#endif
private XmlFormatCollectionWriterDelegate CreateXmlFormatWriterDelegate()
{
return new XmlFormatWriterGenerator().GenerateCollectionWriter(this);
}
#if uapaot
private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate;
public XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
#else
internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
#endif
{
get
{
#if uapaot
if (DataContractSerializer.Option == SerializationOption.CodeGenOnly
|| (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatWriterDelegate != null))
{
return _xmlFormatWriterDelegate;
}
#endif
if (_helper.XmlFormatWriterDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatWriterDelegate == null)
{
XmlFormatCollectionWriterDelegate tempDelegate = CreateXmlFormatWriterDelegate();
Interlocked.MemoryBarrier();
_helper.XmlFormatWriterDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatWriterDelegate;
}
set
{
#if uapaot
_xmlFormatWriterDelegate = value;
#endif
}
}
#if uapaot
[RemovableFeature(ReflectionBasedSerializationFeature.Name)]
#endif
private XmlFormatCollectionReaderDelegate CreateXmlFormatReaderDelegate()
{
return new XmlFormatReaderGenerator().GenerateCollectionReader(this);
}
#if uapaot
private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate;
public XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
#else
internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
#endif
{
get
{
#if uapaot
if (DataContractSerializer.Option == SerializationOption.CodeGenOnly
|| (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatReaderDelegate != null))
{
return _xmlFormatReaderDelegate;
}
#endif
if (_helper.XmlFormatReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatReaderDelegate == null)
{
XmlFormatCollectionReaderDelegate tempDelegate = CreateXmlFormatReaderDelegate();
Interlocked.MemoryBarrier();
_helper.XmlFormatReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatReaderDelegate;
}
set
{
#if uapaot
_xmlFormatReaderDelegate = value;
#endif
}
}
#if uapaot
[RemovableFeature(ReflectionBasedSerializationFeature.Name)]
#endif
private XmlFormatGetOnlyCollectionReaderDelegate CreateXmlFormatGetOnlyCollectionReaderDelegate()
{
return new XmlFormatReaderGenerator().GenerateGetOnlyCollectionReader(this);
}
#if uapaot
private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate;
public XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
#else
internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
#endif
{
get
{
#if uapaot
if (DataContractSerializer.Option == SerializationOption.CodeGenOnly
|| (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatGetOnlyCollectionReaderDelegate != null))
{
return _xmlFormatGetOnlyCollectionReaderDelegate;
}
#endif
if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null)
{
if (UnderlyingType.IsInterface && (Kind == CollectionKind.Enumerable || Kind == CollectionKind.Collection || Kind == CollectionKind.GenericEnumerable))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType))));
}
if (Kind != CollectionKind.Array && AddMethod == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType))));
}
XmlFormatGetOnlyCollectionReaderDelegate tempDelegate = CreateXmlFormatGetOnlyCollectionReaderDelegate();
Interlocked.MemoryBarrier();
_helper.XmlFormatGetOnlyCollectionReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatGetOnlyCollectionReaderDelegate;
}
set
{
#if uapaot
_xmlFormatGetOnlyCollectionReaderDelegate = value;
#endif
}
}
internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
_helper.IncrementCollectionCount(xmlWriter, obj, context);
}
internal IEnumerator GetEnumeratorForCollection(object obj)
{
return _helper.GetEnumeratorForCollection(obj);
}
internal Type GetCollectionElementType()
{
return _helper.GetCollectionElementType();
}
private class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private static Type[] s_knownInterfaces;
private Type _itemType;
private bool _isItemTypeNullable;
private CollectionKind _kind;
private readonly MethodInfo _getEnumeratorMethod, _addMethod;
private readonly ConstructorInfo _constructor;
private DataContract _itemContract;
private DataContract _sharedTypeContract;
private DataContractDictionary _knownDataContracts;
private bool _isKnownTypeAttributeChecked;
private string _itemName;
private bool _itemNameSetExplicit;
private XmlDictionaryString _collectionItemName;
private string _keyName;
private string _valueName;
private XmlDictionaryString _childElementNamespace;
private string _invalidCollectionInSharedContractMessage;
private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate;
private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate;
private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate;
private bool _isConstructorCheckRequired = false;
internal static Type[] KnownInterfaces
{
get
{
if (s_knownInterfaces == null)
{
// Listed in priority order
s_knownInterfaces = new Type[]
{
Globals.TypeOfIDictionaryGeneric,
Globals.TypeOfIDictionary,
Globals.TypeOfIListGeneric,
Globals.TypeOfICollectionGeneric,
Globals.TypeOfIList,
Globals.TypeOfIEnumerableGeneric,
Globals.TypeOfICollection,
Globals.TypeOfIEnumerable
};
}
return s_knownInterfaces;
}
}
private void Init(CollectionKind kind, Type itemType, CollectionDataContractAttribute collectionContractAttribute)
{
_kind = kind;
if (itemType != null)
{
_itemType = itemType;
_isItemTypeNullable = DataContract.IsTypeNullable(itemType);
bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary);
string itemName = null, keyName = null, valueName = null;
if (collectionContractAttribute != null)
{
if (collectionContractAttribute.IsItemNameSetExplicitly)
{
if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractItemName, DataContract.GetClrTypeFullName(UnderlyingType))));
itemName = DataContract.EncodeLocalName(collectionContractAttribute.ItemName);
_itemNameSetExplicit = true;
}
if (collectionContractAttribute.IsKeyNameSetExplicitly)
{
if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType))));
if (!isDictionary)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName)));
keyName = DataContract.EncodeLocalName(collectionContractAttribute.KeyName);
}
if (collectionContractAttribute.IsValueNameSetExplicitly)
{
if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType))));
if (!isDictionary)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName)));
valueName = DataContract.EncodeLocalName(collectionContractAttribute.ValueName);
}
}
XmlDictionary dictionary = isDictionary ? new XmlDictionary(5) : new XmlDictionary(3);
this.Name = dictionary.Add(this.StableName.Name);
this.Namespace = dictionary.Add(this.StableName.Namespace);
_itemName = itemName ?? DataContract.GetStableName(DataContract.UnwrapNullableType(itemType)).Name;
_collectionItemName = dictionary.Add(_itemName);
if (isDictionary)
{
_keyName = keyName ?? Globals.KeyLocalName;
_valueName = valueName ?? Globals.ValueLocalName;
}
}
if (collectionContractAttribute != null)
{
this.IsReference = collectionContractAttribute.IsReference;
}
}
internal CollectionDataContractCriticalHelper(CollectionKind kind)
: base()
{
Init(kind, null, null);
}
// array
internal CollectionDataContractCriticalHelper(Type type) : base(type)
{
if (type == Globals.TypeOfArray)
type = Globals.TypeOfObjectArray;
if (type.GetArrayRank() > 1)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SupportForMultidimensionalArraysNotPresent)));
this.StableName = DataContract.GetStableName(type);
Init(CollectionKind.Array, type.GetElementType(), null);
}
// collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(type)
{
if (getEnumeratorMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type))));
if (addMethod == null && !type.IsInterface)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(type))));
if (itemType == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type))));
CollectionDataContractAttribute collectionContractAttribute;
this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute);
Init(kind, itemType, collectionContractAttribute);
_getEnumeratorMethod = getEnumeratorMethod;
_addMethod = addMethod;
_constructor = constructor;
}
// collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
: this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)
{
_isConstructorCheckRequired = isConstructorCheckRequired;
}
internal CollectionDataContractCriticalHelper(Type type, string invalidCollectionInSharedContractMessage) : base(type)
{
Init(CollectionKind.Collection, null /*itemType*/, null);
_invalidCollectionInSharedContractMessage = invalidCollectionInSharedContractMessage;
}
internal CollectionKind Kind
{
get { return _kind; }
}
internal Type ItemType
{
get { return _itemType; }
set { _itemType = value; }
}
internal DataContract ItemContract
{
get
{
if (_itemContract == null && UnderlyingType != null)
{
if (IsDictionary)
{
if (string.CompareOrdinal(KeyName, ValueName) == 0)
{
DataContract.ThrowInvalidDataContractException(
SR.Format(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName),
UnderlyingType);
}
_itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName });
// Ensure that DataContract gets added to the static DataContract cache for dictionary items
DataContract.GetDataContract(ItemType);
}
else
{
_itemContract = DataContract.GetDataContractFromGeneratedAssembly(ItemType);
if (_itemContract == null)
{
_itemContract = DataContract.GetDataContract(ItemType);
}
}
}
return _itemContract;
}
set
{
_itemContract = value;
}
}
internal DataContract SharedTypeContract
{
get { return _sharedTypeContract; }
set { _sharedTypeContract = value; }
}
internal string ItemName
{
get { return _itemName; }
set { _itemName = value; }
}
internal bool IsConstructorCheckRequired
{
get { return _isConstructorCheckRequired; }
set { _isConstructorCheckRequired = value; }
}
public XmlDictionaryString CollectionItemName
{
get { return _collectionItemName; }
}
internal string KeyName
{
get { return _keyName; }
set { _keyName = value; }
}
internal string ValueName
{
get { return _valueName; }
set { _valueName = value; }
}
internal bool IsDictionary => KeyName != null;
public XmlDictionaryString ChildElementNamespace
{
get { return _childElementNamespace; }
set { _childElementNamespace = value; }
}
internal bool IsItemTypeNullable
{
get { return _isItemTypeNullable; }
set { _isItemTypeNullable = value; }
}
internal MethodInfo GetEnumeratorMethod => _getEnumeratorMethod;
internal MethodInfo AddMethod => _addMethod;
internal ConstructorInfo Constructor => _constructor;
internal override DataContractDictionary KnownDataContracts
{
get
{
if (!_isKnownTypeAttributeChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isKnownTypeAttributeChecked)
{
_knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);
Interlocked.MemoryBarrier();
_isKnownTypeAttributeChecked = true;
}
}
}
return _knownDataContracts;
}
set
{ _knownDataContracts = value; }
}
internal string InvalidCollectionInSharedContractMessage => _invalidCollectionInSharedContractMessage;
internal bool ItemNameSetExplicit => _itemNameSetExplicit;
internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
{
get { return _xmlFormatWriterDelegate; }
set { _xmlFormatWriterDelegate = value; }
}
internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
{
get { return _xmlFormatReaderDelegate; }
set { _xmlFormatReaderDelegate = value; }
}
internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
{
get { return _xmlFormatGetOnlyCollectionReaderDelegate; }
set { _xmlFormatGetOnlyCollectionReaderDelegate = value; }
}
private delegate void IncrementCollectionCountDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context);
private IncrementCollectionCountDelegate _incrementCollectionCountDelegate = null;
private static void DummyIncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { }
internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
if (_incrementCollectionCountDelegate == null)
{
switch (Kind)
{
case CollectionKind.Collection:
case CollectionKind.List:
case CollectionKind.Dictionary:
{
_incrementCollectionCountDelegate = (x, o, c) =>
{
c.IncrementCollectionCount(x, (ICollection)o);
};
}
break;
case CollectionKind.GenericCollection:
case CollectionKind.GenericList:
{
var buildIncrementCollectionCountDelegate = BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(ItemType);
_incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>());
}
break;
case CollectionKind.GenericDictionary:
{
var buildIncrementCollectionCountDelegate = BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(ItemType.GetGenericArguments()));
_incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>());
}
break;
default:
// Do nothing.
_incrementCollectionCountDelegate = DummyIncrementCollectionCount;
break;
}
}
_incrementCollectionCountDelegate(xmlWriter, obj, context);
}
private static MethodInfo s_buildIncrementCollectionCountDelegateMethod;
private static MethodInfo BuildIncrementCollectionCountDelegateMethod
{
get
{
if (s_buildIncrementCollectionCountDelegateMethod == null)
{
s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers);
}
return s_buildIncrementCollectionCountDelegateMethod;
}
}
private static IncrementCollectionCountDelegate BuildIncrementCollectionCountDelegate<T>()
{
return (xmlwriter, obj, context) =>
{
context.IncrementCollectionCountGeneric<T>(xmlwriter, (ICollection<T>)obj);
};
}
private delegate IEnumerator CreateGenericDictionaryEnumeratorDelegate(IEnumerator enumerator);
private CreateGenericDictionaryEnumeratorDelegate _createGenericDictionaryEnumeratorDelegate;
internal IEnumerator GetEnumeratorForCollection(object obj)
{
IEnumerator enumerator = ((IEnumerable)obj).GetEnumerator();
if (Kind == CollectionKind.GenericDictionary)
{
if (_createGenericDictionaryEnumeratorDelegate == null)
{
var keyValueTypes = ItemType.GetGenericArguments();
var buildCreateGenericDictionaryEnumerator = BuildCreateGenericDictionaryEnumerato.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]);
_createGenericDictionaryEnumeratorDelegate = (CreateGenericDictionaryEnumeratorDelegate)buildCreateGenericDictionaryEnumerator.Invoke(null, Array.Empty<object>());
}
enumerator = _createGenericDictionaryEnumeratorDelegate(enumerator);
}
else if (Kind == CollectionKind.Dictionary)
{
enumerator = new DictionaryEnumerator(((IDictionary)obj).GetEnumerator());
}
return enumerator;
}
internal Type GetCollectionElementType()
{
Type enumeratorType = null;
if (Kind == CollectionKind.GenericDictionary)
{
Type[] keyValueTypes = ItemType.GetGenericArguments();
enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes);
}
else if (Kind == CollectionKind.Dictionary)
{
enumeratorType = Globals.TypeOfDictionaryEnumerator;
}
else
{
enumeratorType = GetEnumeratorMethod.ReturnType;
}
MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
if (getCurrentMethod == null)
{
if (enumeratorType.IsInterface)
{
getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod;
}
else
{
Type ienumeratorInterface = Globals.TypeOfIEnumerator;
if (Kind == CollectionKind.GenericDictionary || Kind == CollectionKind.GenericCollection || Kind == CollectionKind.GenericEnumerable)
{
Type[] interfaceTypes = enumeratorType.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
if (interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric
&& interfaceType.GetGenericArguments()[0] == ItemType)
{
ienumeratorInterface = interfaceType;
break;
}
}
}
getCurrentMethod = GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
}
}
Type elementType = getCurrentMethod.ReturnType;
return elementType;
}
private static MethodInfo s_buildCreateGenericDictionaryEnumerator;
private static MethodInfo BuildCreateGenericDictionaryEnumerato
{
get
{
if (s_buildCreateGenericDictionaryEnumerator == null)
{
s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers);
}
return s_buildCreateGenericDictionaryEnumerator;
}
}
private static CreateGenericDictionaryEnumeratorDelegate BuildCreateGenericDictionaryEnumerator<K, V>()
{
return (enumerator) =>
{
return new GenericDictionaryEnumerator<K, V>((IEnumerator<KeyValuePair<K, V>>)enumerator);
};
}
}
private DataContract GetSharedTypeContract(Type type)
{
if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
{
return this;
}
if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return new ClassDataContract(type);
}
return null;
}
internal static bool IsCollectionInterface(Type type)
{
if (type.IsGenericType)
type = type.GetGenericTypeDefinition();
return ((IList<Type>)KnownInterfaces).Contains(type);
}
internal static bool IsCollection(Type type)
{
Type itemType;
return IsCollection(type, out itemType);
}
internal static bool IsCollection(Type type, out Type itemType)
{
return IsCollectionHelper(type, out itemType, true /*constructorRequired*/);
}
internal static bool IsCollection(Type type, bool constructorRequired)
{
Type itemType;
return IsCollectionHelper(type, out itemType, constructorRequired);
}
private static bool IsCollectionHelper(Type type, out Type itemType, bool constructorRequired)
{
if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null)
{
itemType = type.GetElementType();
return true;
}
DataContract dataContract;
return IsCollectionOrTryCreate(type, false /*tryCreate*/, out dataContract, out itemType, constructorRequired);
}
internal static bool TryCreate(Type type, out DataContract dataContract)
{
Type itemType;
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, true /*constructorRequired*/);
}
internal static bool CreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
{
Type itemType;
if (type.IsArray)
{
dataContract = new CollectionDataContract(type);
return true;
}
else
{
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
}
}
internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
{
dataContract = DataContract.GetDataContractFromGeneratedAssembly(type);
if (dataContract == null)
{
Type itemType;
if (type.IsArray)
{
dataContract = new CollectionDataContract(type);
return true;
}
else
{
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
}
}
else
{
if (dataContract is CollectionDataContract)
{
return true;
}
else
{
dataContract = null;
return false;
}
}
}
internal static MethodInfo GetTargetMethodWithName(string name, Type type, Type interfaceType)
{
Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
return t?.GetMethod(name);
}
private static bool IsArraySegment(Type t)
{
return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
}
private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract dataContract, out Type itemType, bool constructorRequired)
{
dataContract = null;
itemType = Globals.TypeOfObject;
if (DataContract.GetBuiltInDataContract(type) != null)
{
return HandleIfInvalidCollection(type, tryCreate, false/*hasCollectionDataContract*/, false/*isBaseTypeCollection*/,
SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract);
}
MethodInfo addMethod, getEnumeratorMethod;
bool hasCollectionDataContract = IsCollectionDataContract(type);
Type baseType = type.BaseType;
bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject
&& baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false;
if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection,
SR.CollectionTypeCannotHaveDataContract, null, ref dataContract);
}
if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) || IsArraySegment(type))
{
return false;
}
if (!Globals.TypeOfIEnumerable.IsAssignableFrom(type))
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection,
SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
}
if (type.IsInterface)
{
Type interfaceTypeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
Type[] knownInterfaces = KnownInterfaces;
for (int i = 0; i < knownInterfaces.Length; i++)
{
if (knownInterfaces[i] == interfaceTypeToCheck)
{
addMethod = null;
if (type.IsGenericType)
{
Type[] genericArgs = type.GetGenericArguments();
if (interfaceTypeToCheck == Globals.TypeOfIDictionaryGeneric)
{
itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs);
addMethod = type.GetMethod(Globals.AddMethodName);
getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName);
}
else
{
itemType = genericArgs[0];
// ICollection<T> has AddMethod
var collectionType = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType);
if (collectionType.IsAssignableFrom(type))
{
addMethod = collectionType.GetMethod(Globals.AddMethodName);
}
getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName);
}
}
else
{
if (interfaceTypeToCheck == Globals.TypeOfIDictionary)
{
itemType = typeof(KeyValue<object, object>);
addMethod = type.GetMethod(Globals.AddMethodName);
}
else
{
itemType = Globals.TypeOfObject;
// IList has AddMethod
if (interfaceTypeToCheck == Globals.TypeOfIList)
{
addMethod = type.GetMethod(Globals.AddMethodName);
}
}
getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName);
}
if (tryCreate)
dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/);
return true;
}
}
}
ConstructorInfo defaultCtor = null;
if (!type.IsValueType)
{
defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>());
if (defaultCtor == null && constructorRequired)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/,
SR.CollectionTypeDoesNotHaveDefaultCtor, null, ref dataContract);
}
}
Type knownInterfaceType = null;
CollectionKind kind = CollectionKind.None;
bool multipleDefinitions = false;
Type[] interfaceTypes = type.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
Type interfaceTypeToCheck = interfaceType.IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType;
Type[] knownInterfaces = KnownInterfaces;
for (int i = 0; i < knownInterfaces.Length; i++)
{
if (knownInterfaces[i] == interfaceTypeToCheck)
{
CollectionKind currentKind = (CollectionKind)(i + 1);
if (kind == CollectionKind.None || currentKind < kind)
{
kind = currentKind;
knownInterfaceType = interfaceType;
multipleDefinitions = false;
}
else if ((kind & currentKind) == currentKind)
multipleDefinitions = true;
break;
}
}
}
if (kind == CollectionKind.None)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection,
SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
}
if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable)
{
if (multipleDefinitions)
knownInterfaceType = Globals.TypeOfIEnumerable;
itemType = knownInterfaceType.IsGenericType ? knownInterfaceType.GetGenericArguments()[0] : Globals.TypeOfObject;
GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType },
false /*addMethodOnInterface*/,
out getEnumeratorMethod, out addMethod);
if (addMethod == null)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/,
SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), ref dataContract);
}
if (tryCreate)
dataContract = new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
}
else
{
if (multipleDefinitions)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/,
SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract);
}
Type[] addMethodTypeArray = null;
switch (kind)
{
case CollectionKind.GenericDictionary:
addMethodTypeArray = knownInterfaceType.GetGenericArguments();
bool isOpenGeneric = knownInterfaceType.IsGenericTypeDefinition
|| (addMethodTypeArray[0].IsGenericParameter && addMethodTypeArray[1].IsGenericParameter);
itemType = isOpenGeneric ? Globals.TypeOfKeyValue : Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray);
break;
case CollectionKind.Dictionary:
addMethodTypeArray = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
itemType = Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray);
break;
case CollectionKind.GenericList:
case CollectionKind.GenericCollection:
addMethodTypeArray = knownInterfaceType.GetGenericArguments();
itemType = addMethodTypeArray[0];
break;
case CollectionKind.List:
itemType = Globals.TypeOfObject;
addMethodTypeArray = new Type[] { itemType };
break;
}
if (tryCreate)
{
GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray,
true /*addMethodOnInterface*/,
out getEnumeratorMethod, out addMethod);
dataContract = DataContract.GetDataContractFromGeneratedAssembly(type);
if (dataContract == null)
{
dataContract = new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
}
}
}
return true;
}
internal static bool IsCollectionDataContract(Type type)
{
return type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false);
}
private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string param, ref DataContract dataContract)
{
if (hasCollectionDataContract)
{
if (tryCreate)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionDataContract, DataContract.GetClrTypeFullName(type)), param)));
return true;
}
if (createContractWithException)
{
if (tryCreate)
dataContract = new CollectionDataContract(type, GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param));
return true;
}
return false;
}
private static string GetInvalidCollectionMessage(string message, string nestedMessage, string param)
{
return (param == null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param);
}
private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo addMethod, ref MethodInfo getEnumeratorMethod)
{
Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
if (t != null)
{
addMethod = t.GetMethod(Globals.AddMethodName) ?? addMethod;
getEnumeratorMethod = t.GetMethod(Globals.GetEnumeratorMethodName) ?? getEnumeratorMethod;
}
}
private static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo getEnumeratorMethod, out MethodInfo addMethod)
{
addMethod = getEnumeratorMethod = null;
if (addMethodOnInterface)
{
addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public, addMethodTypeArray);
if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0])
{
FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod);
if (addMethod == null)
{
Type[] parentInterfaceTypes = interfaceType.GetInterfaces();
// The for loop below depeneds on the order for the items in parentInterfaceTypes, which
// doesnt' seem right. But it's the behavior of DCS on the full framework.
// Sorting the array to make sure the behavior is consistent with Desktop's.
Array.Sort(parentInterfaceTypes, (x, y) => string.Compare(x.FullName, y.FullName));
foreach (Type parentInterfaceType in parentInterfaceTypes)
{
if (IsKnownInterface(parentInterfaceType))
{
FindCollectionMethodsOnInterface(type, parentInterfaceType, ref addMethod, ref getEnumeratorMethod);
if (addMethod == null)
{
break;
}
}
}
}
}
}
else
{
// GetMethod returns Add() method with parameter closest matching T in assignability/inheritance chain
addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, addMethodTypeArray);
if (addMethod == null)
return;
}
if (getEnumeratorMethod == null)
{
getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType))
{
Type ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault();
if (ienumerableInterface == null)
ienumerableInterface = Globals.TypeOfIEnumerable;
getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface);
}
}
}
private static bool IsKnownInterface(Type type)
{
Type typeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
foreach (Type knownInterfaceType in KnownInterfaces)
{
if (typeToCheck == knownInterfaceType)
{
return true;
}
}
return false;
}
internal override DataContract GetValidContract(SerializationMode mode)
{
if (InvalidCollectionInSharedContractMessage != null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage));
return this;
}
internal override DataContract GetValidContract()
{
if (this.IsConstructorCheckRequired)
{
CheckConstructor();
}
return this;
}
private void CheckConstructor()
{
if (this.Constructor == null)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionTypeDoesNotHaveDefaultCtor, DataContract.GetClrTypeFullName(this.UnderlyingType))));
}
else
{
this.IsConstructorCheckRequired = false;
}
}
internal override bool IsValidContract(SerializationMode mode)
{
return (InvalidCollectionInSharedContractMessage == null);
}
/// <SecurityNote>
/// Review - calculates whether this collection requires MemberAccessPermission for deserialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForRead(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ItemType != null && !IsTypeVisible(ItemType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(ItemType)),
securityException));
}
return true;
}
if (ConstructorRequiresMemberAccess(Constructor))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractNoPublicConstructor,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.AddMethod))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractAddMethodNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.AddMethod.Name),
securityException));
}
return true;
}
return false;
}
/// <SecurityNote>
/// Review - calculates whether this collection requires MemberAccessPermission for serialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForWrite(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ItemType != null && !IsTypeVisible(ItemType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(ItemType)),
securityException));
}
return true;
}
return false;
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
XmlFormatWriterDelegate(xmlWriter, obj, context, this);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
xmlReader.Read();
object o = null;
if (context.IsGetOnlyCollection)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
#if uapaot
if (XmlFormatGetOnlyCollectionReaderDelegate == null)
{
throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, UnderlyingType.ToString()));
}
#endif
XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
}
else
{
o = XmlFormatReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
}
xmlReader.ReadEndElement();
return o;
}
internal class DictionaryEnumerator : IEnumerator<KeyValue<object, object>>
{
private IDictionaryEnumerator _enumerator;
public DictionaryEnumerator(IDictionaryEnumerator enumerator)
{
_enumerator = enumerator;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public KeyValue<object, object> Current
{
get { return new KeyValue<object, object>(_enumerator.Key, _enumerator.Value); }
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
_enumerator.Reset();
}
}
internal class GenericDictionaryEnumerator<K, V> : IEnumerator<KeyValue<K, V>>
{
private IEnumerator<KeyValuePair<K, V>> _enumerator;
public GenericDictionaryEnumerator(IEnumerator<KeyValuePair<K, V>> enumerator)
{
_enumerator = enumerator;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public KeyValue<K, V> Current
{
get
{
KeyValuePair<K, V> current = _enumerator.Current;
return new KeyValue<K, V>(current.Key, current.Value);
}
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
_enumerator.Reset();
}
}
}
}
| |
namespace RealArtists.ChargeBee.Models {
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using RealArtists.ChargeBee.Api;
using RealArtists.ChargeBee.Filters.Enums;
using RealArtists.ChargeBee.Internal;
public class CouponActions : ApiResourceActions {
public CouponActions(ChargeBeeApi api) : base(api) { }
public Coupon.CreateRequest Create() {
string url = BuildUrl("coupons");
return new Coupon.CreateRequest(Api, url, HttpMethod.Post);
}
public Coupon.CouponListRequest List() {
string url = BuildUrl("coupons");
return new Coupon.CouponListRequest(Api, url);
}
public EntityRequest<Type> Retrieve(string id) {
string url = BuildUrl("coupons", id);
return new EntityRequest<Type>(Api, url, HttpMethod.Get);
}
public EntityRequest<Type> Delete(string id) {
string url = BuildUrl("coupons", id, "delete");
return new EntityRequest<Type>(Api, url, HttpMethod.Post);
}
public Coupon.CopyRequest Copy() {
string url = BuildUrl("coupons", "copy");
return new Coupon.CopyRequest(Api, url, HttpMethod.Post);
}
public EntityRequest<Type> Unarchive(string id) {
string url = BuildUrl("coupons", id, "unarchive");
return new EntityRequest<Type>(Api, url, HttpMethod.Post);
}
}
public class Coupon : Resource {
public string Id {
get { return GetValue<string>("id", true); }
}
public string Name {
get { return GetValue<string>("name", true); }
}
public string InvoiceName {
get { return GetValue<string>("invoice_name", false); }
}
public DiscountTypeEnum DiscountType {
get { return GetEnum<DiscountTypeEnum>("discount_type", true); }
}
public double? DiscountPercentage {
get { return GetValue<double?>("discount_percentage", false); }
}
public int? DiscountAmount {
get { return GetValue<int?>("discount_amount", false); }
}
public string CurrencyCode {
get { return GetValue<string>("currency_code", false); }
}
public DurationTypeEnum DurationType {
get { return GetEnum<DurationTypeEnum>("duration_type", true); }
}
public int? DurationMonth {
get { return GetValue<int?>("duration_month", false); }
}
public DateTime? ValidTill {
get { return GetDateTime("valid_till", false); }
}
public int? MaxRedemptions {
get { return GetValue<int?>("max_redemptions", false); }
}
public StatusEnum? Status {
get { return GetEnum<StatusEnum>("status", false); }
}
public ApplyOnEnum ApplyOn {
get { return GetEnum<ApplyOnEnum>("apply_on", true); }
}
public PlanConstraintEnum PlanConstraint {
get { return GetEnum<PlanConstraintEnum>("plan_constraint", true); }
}
public AddonConstraintEnum AddonConstraint {
get { return GetEnum<AddonConstraintEnum>("addon_constraint", true); }
}
public DateTime CreatedAt {
get { return (DateTime)GetDateTime("created_at", true); }
}
public DateTime? ArchivedAt {
get { return GetDateTime("archived_at", false); }
}
public long? ResourceVersion {
get { return GetValue<long?>("resource_version", false); }
}
public DateTime? UpdatedAt {
get { return GetDateTime("updated_at", false); }
}
public List<string> PlanIds {
get { return GetList<string>("plan_ids"); }
}
public List<string> AddonIds {
get { return GetList<string>("addon_ids"); }
}
public int? Redemptions {
get { return GetValue<int?>("redemptions", false); }
}
public string InvoiceNotes {
get { return GetValue<string>("invoice_notes", false); }
}
public JToken MetaData {
get { return GetJToken("meta_data", false); }
}
public class CreateRequest : EntityRequest<CreateRequest> {
public CreateRequest(ChargeBeeApi api, string url, HttpMethod method)
: base(api, url, method) {
}
public CreateRequest Id(string id) {
_params.Add("id", id);
return this;
}
public CreateRequest Name(string name) {
_params.Add("name", name);
return this;
}
public CreateRequest InvoiceName(string invoiceName) {
_params.AddOpt("invoice_name", invoiceName);
return this;
}
public CreateRequest DiscountType(Coupon.DiscountTypeEnum discountType) {
_params.Add("discount_type", discountType);
return this;
}
public CreateRequest DiscountAmount(int discountAmount) {
_params.AddOpt("discount_amount", discountAmount);
return this;
}
public CreateRequest CurrencyCode(string currencyCode) {
_params.AddOpt("currency_code", currencyCode);
return this;
}
public CreateRequest DiscountPercentage(double discountPercentage) {
_params.AddOpt("discount_percentage", discountPercentage);
return this;
}
public CreateRequest ApplyOn(Coupon.ApplyOnEnum applyOn) {
_params.Add("apply_on", applyOn);
return this;
}
public CreateRequest PlanConstraint(PlanConstraintEnum planConstraint) {
_params.AddOpt("plan_constraint", planConstraint);
return this;
}
public CreateRequest AddonConstraint(AddonConstraintEnum addonConstraint) {
_params.AddOpt("addon_constraint", addonConstraint);
return this;
}
public CreateRequest PlanIds(List<string> planIds) {
_params.AddOpt("plan_ids", planIds);
return this;
}
public CreateRequest AddonIds(List<string> addonIds) {
_params.AddOpt("addon_ids", addonIds);
return this;
}
public CreateRequest DurationType(Coupon.DurationTypeEnum durationType) {
_params.Add("duration_type", durationType);
return this;
}
public CreateRequest DurationMonth(int durationMonth) {
_params.AddOpt("duration_month", durationMonth);
return this;
}
public CreateRequest ValidTill(long validTill) {
_params.AddOpt("valid_till", validTill);
return this;
}
public CreateRequest MaxRedemptions(int maxRedemptions) {
_params.AddOpt("max_redemptions", maxRedemptions);
return this;
}
public CreateRequest InvoiceNotes(string invoiceNotes) {
_params.AddOpt("invoice_notes", invoiceNotes);
return this;
}
public CreateRequest MetaData(JToken metaData) {
_params.AddOpt("meta_data", metaData);
return this;
}
public CreateRequest Status(Coupon.StatusEnum status) {
_params.AddOpt("status", status);
return this;
}
}
public class CouponListRequest : ListRequestBase<CouponListRequest> {
public CouponListRequest(ChargeBeeApi api, string url)
: base(api, url) {
}
public StringFilter<CouponListRequest> Id() {
return new StringFilter<CouponListRequest>("id", this).SupportsMultiOperators(true);
}
public StringFilter<CouponListRequest> Name() {
return new StringFilter<CouponListRequest>("name", this).SupportsMultiOperators(true);
}
public EnumFilter<Coupon.DiscountTypeEnum, CouponListRequest> DiscountType() {
return new EnumFilter<Coupon.DiscountTypeEnum, CouponListRequest>("discount_type", this);
}
public EnumFilter<Coupon.DurationTypeEnum, CouponListRequest> DurationType() {
return new EnumFilter<Coupon.DurationTypeEnum, CouponListRequest>("duration_type", this);
}
public EnumFilter<Coupon.StatusEnum, CouponListRequest> Status() {
return new EnumFilter<Coupon.StatusEnum, CouponListRequest>("status", this);
}
public EnumFilter<Coupon.ApplyOnEnum, CouponListRequest> ApplyOn() {
return new EnumFilter<Coupon.ApplyOnEnum, CouponListRequest>("apply_on", this);
}
public TimestampFilter<CouponListRequest> CreatedAt() {
return new TimestampFilter<CouponListRequest>("created_at", this);
}
public TimestampFilter<CouponListRequest> UpdatedAt() {
return new TimestampFilter<CouponListRequest>("updated_at", this);
}
public CouponListRequest SortByCreatedAt(SortOrderEnum order) {
_params.AddOpt("sort_by[" + order.ToString().ToLower() + "]", "created_at");
return this;
}
}
public class CopyRequest : EntityRequest<CopyRequest> {
public CopyRequest(ChargeBeeApi api, string url, HttpMethod method)
: base(api, url, method) {
}
public CopyRequest FromSite(string fromSite) {
_params.Add("fro_site", fromSite);
return this;
}
public CopyRequest IdAtFromSite(string idAtFromSite) {
_params.Add("id_at_fro_site", idAtFromSite);
return this;
}
public CopyRequest Id(string id) {
_params.AddOpt("id", id);
return this;
}
public CopyRequest ForSiteMerging(bool forSiteMerging) {
_params.AddOpt("for_site_merging", forSiteMerging);
return this;
}
}
public enum DiscountTypeEnum {
Unknown,
[Description("fixed_amount")]
FixedAmount,
[Description("percentage")]
Percentage,
}
public enum DurationTypeEnum {
Unknown,
[Description("one_time")]
OneTime,
[Description("forever")]
Forever,
[Description("limited_period")]
LimitedPeriod,
}
public enum StatusEnum {
Unknown,
[Description("active")]
Active,
[Description("expired")]
Expired,
[Description("archived")]
Archived,
[Description("deleted")]
Deleted,
}
public enum ApplyOnEnum {
Unknown,
[Description("invoice_amount")]
InvoiceAmount,
[Description("each_specified_item")]
EachSpecifiedItem,
}
public enum PlanConstraintEnum {
Unknown,
[Description("none")]
None,
[Description("all")]
All,
[Description("specific")]
Specific,
[Description("not_applicable")]
NotApplicable,
}
public enum AddonConstraintEnum {
Unknown,
[Description("none")]
None,
[Description("all")]
All,
[Description("specific")]
Specific,
[Description("not_applicable")]
NotApplicable,
}
}
}
| |
// Copyright 2012 Xamarin Inc
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using SQLite;
using HtmlAgilityPack;
using Mono.Cecil;
namespace macdoc
{
public class AppleDocMerger
{
public class Options
{
// Default options
public Options ()
{
ImportSamples = true;
QuickSummaries = true;
CancellationToken = System.Threading.CancellationToken.None;
}
// Instruct the merger to take samples from a known repository and use them while merging to replace inline apple samples
// If true, when we encounter a obj-c sample we try to get it's equivalent from sample repository (user point of view)
// If false, we register it as a new sample (xamarinista point of view)
public bool ImportSamples { get; set; }
// Tell where to find or create the samples repository
public string SamplesRepositoryPath { get; set; }
// If true, it extracts the first sentence from the remarks and sticks it in the summary.
public bool QuickSummaries { get; set; }
// Where the Apple documentation is stored
public string DocBase { get; set; }
// Unused
public bool DebugDocs { get; set; }
// This is an abstraction over a .zip or a raw directory of ecma doc archive
public IMdocArchive MonodocArchive { get; set; }
// Point to a Cecil version of the MonoTouch|MonoMac|... assembly
public AssemblyDefinition Assembly { get; set; }
// Depending on the above assembly, the namespace prefix is stored there
public string BaseAssemblyNamespace { get; set; }
// People can supply a callback that will be called when a new file is being processed
public Action<string> MergingPathCallback { get; set; }
// Token used to end prematurely the process if needed
public CancellationToken CancellationToken { get; set; }
}
class ProcessingContext
{
public string CurrentAppleDocPath { get; set; }
public TypeDefinition CurrentProcessedType { get; set; }
}
Options options;
SampleRepository samples;
Dictionary<string, TypeDefinition> assemblyTypesLookup;
int numOfMissingAppleDocumentation;
string exportAttributeFullName;
Action<string> pathCallback;
static ProcessingContext context;
// This is a cache of the apple documentation path (value) corresponding to a type name (key)
Dictionary<string, string> docPaths = new Dictionary<string, string> ();
// Cache of precreated Apple documentation XML
Dictionary<string, XElement> loadedAppleDocs = new Dictionary<string, XElement> ();
static Regex selectorInHref = new Regex ("(?<type>[^/]+)/(?<selector>[^/]+)$");
static Regex propertyAttrs = new Regex (@"^@property\((?<attrs>[^)]*)\)");
// We use Apple own documentation database to locate the right documentation file
SQLiteConnection db;
Dictionary<string, Func<XElement, bool, object>> HtmlToMdocElementMapping;
public AppleDocMerger (Options options)
{
this.options = options;
if (options.Assembly == null)
throw new ArgumentNullException ("options.Assembly");
if (string.IsNullOrEmpty (options.BaseAssemblyNamespace))
throw new ArgumentNullException ("options.BaseAssemblyNamespace");
assemblyTypesLookup = new Dictionary<string, TypeDefinition> ();
foreach (var t in GetTypes (options.Assembly)) {
if (assemblyTypesLookup.ContainsKey (t.Name))
Console.WriteLine ("Duplicated name {0} between {1} and {2}", t.Name, t.FullName, assemblyTypesLookup[t.Name].FullName);
else
assemblyTypesLookup[t.Name] = t;
}
if (options.MonodocArchive == null)
throw new ArgumentNullException ("options.MonodocArchive");
if (string.IsNullOrEmpty (options.DocBase) || !Directory.Exists (options.DocBase))
throw new ArgumentException ("DocBase isn't valid", "options.DocBase");
var dbPath = Path.Combine (options.DocBase, "..", "..", "docSet.dsidx");
if (!File.Exists (dbPath))
throw new ArgumentException ("DocBase doesn't contain a valid database file", "options.DocBase");
db = new SQLiteConnection (dbPath);
var samplesPath = string.IsNullOrEmpty (options.SamplesRepositoryPath) ? Path.Combine (options.DocBase, "samples.zip") : options.SamplesRepositoryPath;
if (options.ImportSamples && !File.Exists (samplesPath))
throw new ArgumentException ("We were asked to import samples but repository doesn't exist", samplesPath);
samples = File.Exists (samplesPath) ? SampleRepository.LoadFrom (samplesPath) : new SampleRepository (samplesPath);
pathCallback = options.MergingPathCallback;
HtmlToMdocElementMapping = new Dictionary<string, Func<XElement, bool, object>> {
{ "section",(e, i) => new [] {new XElement ("para", HtmlToMdoc ((XElement)e.FirstNode))}.Concat (HtmlToMdoc (e.Nodes ().Skip (1), i)) },
{ "a", (e, i) => ConvertLink (e, i) },
{ "code", (e, i) => ConvertCode (e, i) },
{ "div", (e, i) => ConvertDiv (e, i) },
{ "em", (e, i) => new XElement ("i", HtmlToMdoc (e.Nodes (), i)) },
{ "li", (e, i) => new XElement ("item", new XElement ("term", HtmlToMdoc (e.Nodes (), i))) },
{ "ol", (e, i) => new XElement ("list", new XAttribute ("type", "number"), HtmlToMdoc (e.Nodes ())) },
{ "p", (e, i) => new XElement ("para", HtmlToMdoc (e.Nodes (), i)) },
{ "span", (e, i) => HtmlToMdoc (e.Nodes (), i) },
{ "strong", (e, i) => new XElement ("i", HtmlToMdoc (e.Nodes (), i)) },
{ "tt", (e, i) => new XElement ("c", HtmlToMdoc (e.Nodes (), i)) },
{ "ul", (e, i) => new XElement ("list", new XAttribute ("type", "bullet"), HtmlToMdoc (e.Nodes ())) },
};
}
public void MergeDocumentation ()
{
Console.WriteLine ("Starting merge");
var baseNamespace = options.BaseAssemblyNamespace;
var nso = options.Assembly.MainModule.GetType (baseNamespace + ".Foundation.NSObject");
exportAttributeFullName = baseNamespace + ".Foundation.ExportAttribute";
if (nso == null)
throw new ApplicationException (string.Format ("Incomplete {0} assembly", baseNamespace));
foreach (var t in GetTypes (options.Assembly)) {
if (t.IsNotPublic || t.IsNested)
continue;
if (options.CancellationToken.IsCancellationRequested)
break;
/*if (debug != null && t.FullName != debug)
continue;*/
if (t == nso || GenerateAncestorChain (t).Contains (nso)) {
try {
ProcessNSO (t);
} catch (Exception e){
Console.WriteLine ("Problem with {0} {1}", t.FullName, e);
}
Console.WriteLine ("Processed {0}", t.Name);
}
}
// Only clean up if we are doing a full scan
if (!options.ImportSamples)
samples.Close (!options.DebugDocs);
if (numOfMissingAppleDocumentation > 90) {
throw new ApplicationException (string.Format ("Too many types were not found on this run ({0}), should be around 60-70 (mostly CoreImage, 3 UIKits, 2 CoreAnimation, 1 Foundation, 1 Bluetooth, 1 iAd",
numOfMissingAppleDocumentation));
}
}
IEnumerable<TypeDefinition> GenerateAncestorChain (TypeDefinition type)
{
var t = type;
while (t.BaseType != null && (t = t.BaseType.Resolve ()) != null && t.FullName != options.Assembly.MainModule.TypeSystem.Object.FullName)
yield return t;
}
public void ProcessNSO (TypeDefinition t)
{
if (context == null)
context = new ProcessingContext ();
context.CurrentProcessedType = t;
var appledocpath = GetRealAppleDocPath (t);
if (appledocpath == null) {
Console.WriteLine ("No apple doc for {0} found", t.FullName);
return;
}
AdvertiseNewPath (appledocpath);
string xmldocpath = GetMdocPath (t);
if (!File.Exists (xmldocpath)) {
Console.WriteLine ("DOC REGEN PENDING for type: {0}", t.FullName);
return;
}
XDocument xmldoc;
using (var f = File.OpenText (xmldocpath))
xmldoc = XDocument.Load (f);
//Console.WriteLine ("Opened {0}", appledocpath);
var appledocs = LoadAppleDocumentation (appledocpath);
var typeRemarks = xmldoc.Element ("Type").Element ("Docs").Element ("remarks");
var typeSummary = xmldoc.Element ("Type").Element ("Docs").Element ("summary");
if (typeRemarks != null || (options.QuickSummaries && typeSummary != null)) {
if (typeRemarks.Value == "To be added.")
typeRemarks.Value = "";
var overview = ExtractTypeOverview (appledocs);
typeRemarks.Add (overview);
if (overview != null && options.QuickSummaries && typeSummary.Value == "To be added."){
foreach (var x in (System.Collections.IEnumerable) overview){
var xe = x as XElement;
if (xe == null)
continue;
if (xe.Name == "para"){
var value = xe.Value;
var dot = value.IndexOf ('.');
if (dot == -1)
typeSummary.Value = value;
else
typeSummary.Value = value.Substring (0, dot+1);
break;
}
}
}
}
foreach (var method in t.Methods.Where (m => m.IsPublic)) {
bool prop = method.IsSpecialName;
// Skip methods from the base class
if (method.DeclaringType != t)
continue;
//var attrs = method.GetCustomAttributes (export_attribute_type, true);
if (!method.HasCustomAttributes)
continue;
var attrs = method.CustomAttributes;
var selector = GetSelector (attrs);
if (selector == null) {
if (method.Name != ".ctor")
Console.WriteLine ("Null selector for {0}::{1}", t.FullName, method.Name);
continue;
}
if (selector == "init")
continue;
bool overrides =
(method.Attributes & MethodAttributes.Virtual) != 0 &&
(method.Attributes & MethodAttributes.NewSlot) == 0;
string keyFormat = "<h3 class=\"verytight\">{0}</h3>";
string key = string.Format (keyFormat, selector);
var mDoc = GetAppleMemberDocs (t, selector);
if (mDoc == null){
// Don't report known issues
if (!AppleDocKnownIssues.IsKnown (t.Name, selector) &&
// don't report property setters
!(prop && method.Name.StartsWith ("set_")) &&
// don't report overriding methods
!overrides) {
Console.WriteLine ("While getting Apple Doc");
ReportProblem (t, appledocpath, selector, key);
}
continue;
}
//Console.WriteLine ("Contents at {0}", p);
//
// Now, plug the docs
//
var member = GetMdocMember (xmldoc, selector);
if (member == null){
Console.WriteLine ("DOC REGEN PENDING for {0}.{1}", method.DeclaringType.Name, selector);
continue;
}
//
// Summary
//
var summaryNode = member.XPathSelectElement ("Docs/summary");
if (summaryNode.Value == "To be added."){
var summary = ExtractSummary (mDoc);
if (summary == null)
ReportProblem (t, appledocpath, selector, key);
summaryNode.Value = "";
summaryNode.Add (summary);
}
VerifyArgumentSemantic (mDoc, member, t, selector);
//
// Wipe out the value if it says "to be added"
//
var valueNode = member.XPathSelectElement ("Docs/value");
if (valueNode != null){
if (valueNode.Value == "To be added.")
valueNode.Value = "";
}
//
// Merge parameters
//
var eParamNodes = member.XPathSelectElements ("Docs/param").GetEnumerator ();
//Console.WriteLine ("{0}", selector);
var eAppleParams= ExtractParams (mDoc).GetEnumerator ();
for ( ; eParamNodes.MoveNext () && eAppleParams.MoveNext (); ) {
eParamNodes.Current.Value = "";
eParamNodes.Current.Add (eAppleParams.Current);
}
//
// Only extract the return value if there is a return in the type
//
var return_type = member.XPathSelectElement ("ReturnValue/ReturnType");
if (return_type != null && return_type.Value != "System.Void" && member.XPathSelectElement ("MemberType").Value == "Method") {
//Console.WriteLine ("Scanning for return {0} {1}", t.FullName, selector);
var ret = ExtractReturn (mDoc);
if (ret == null && !AppleDocKnownIssues.IsKnownMissingReturnValue (t, selector))
Console.WriteLine ("Problem extracting a return value for type=\"{0}\" selector=\"{1}\"", t.FullName, selector);
else {
var retNode = prop
? member.XPathSelectElement ("Docs/value")
: member.XPathSelectElement ("Docs/returns");
if (retNode != null && ret != null){
retNode.Value = "";
retNode.Add (ret);
}
}
}
var remarks = ExtractDiscussion (mDoc);
if (remarks != null){
var remarksNode = member.XPathSelectElement ("Docs/remarks");
if (remarksNode.Value == "To be added.")
remarksNode.Value = "";
remarksNode.Add (remarks);
}
}
var s = new XmlWriterSettings () {
Indent = true,
Encoding = Encoding.UTF8,
OmitXmlDeclaration = true,
NewLineChars = Environment.NewLine
};
using (var output = File.CreateText (xmldocpath)){
var xmlw = XmlWriter.Create (output, s);
xmldoc.Save (xmlw);
output.WriteLine ();
}
}
string GetSelector (IEnumerable<CustomAttribute> attrs)
{
return attrs
.Where (attr => attr != null
&& attr.HasConstructorArguments
&& attr.AttributeType.FullName.Equals (exportAttributeFullName, StringComparison.InvariantCultureIgnoreCase))
.Select (attr => attr.ConstructorArguments[0].Value.ToString ()).FirstOrDefault ();
}
// Extract the path from Apple's Database
public string GetAppleDocFor (TypeDefinition t)
{
var path = db.CreateCommand ("select zkpath from znode join ztoken on znode.z_pk == ztoken.zparentnode where ztoken.ztokenname like \"" + t.Name + "\"").ExecuteScalar<string> ();
return Path.Combine (options.DocBase, "..", path);
}
public void ReportProblem (TypeDefinition t, string docpath, string selector, string key)
{
Console.WriteLine (t);
Console.WriteLine (" Error: did not find selector \"{0}\"", selector);
Console.WriteLine (" File: {0}", docpath);
Console.WriteLine (" key: {0}", key);
Console.WriteLine ();
}
object ConvertLink (XElement e, bool insideFormat)
{
var href = e.Attribute ("href");
if (href == null){
return "";
}
var m = selectorInHref.Match (href.Value);
if (!m.Success)
return "";
var selType = m.Groups ["type"].Value;
var selector = m.Groups ["selector"].Value;
TypeDefinition type = null;
if (assemblyTypesLookup.TryGetValue (selType, out type)) {
var typedocpath = GetMdocPath (type);
if (File.Exists (typedocpath)) {
XDocument typedocs;
using (var f = File.OpenText (typedocpath))
typedocs = XDocument.Load (f);
var member = GetMdocMember (typedocs, selector);
if (member != null)
return new XElement ("see",
new XAttribute ("cref", CreateCref (typedocs, member)));
}
}
if (!href.Value.StartsWith ("#")) {
var r = Path.GetFullPath (Path.Combine (Path.GetDirectoryName (context.CurrentAppleDocPath), href.Value));
href.Value = r.Replace (options.DocBase, "http://developer.apple.com/iphone/library/documentation");
}
return insideFormat
? e
: new XElement ("format",
new XAttribute ("type", "text/html"), e);
}
string CreateCref (XDocument typedocs, XElement member)
{
var cref = new StringBuilder ();
var memberType = member.Element ("MemberType").Value;
switch (memberType) {
case "Constructor": cref.Append ("C"); break;
case "Event": cref.Append ("E"); break;
case "Field": cref.Append ("F"); break;
case "Method": cref.Append ("M"); break;
case "Property": cref.Append ("P"); break;
default:
throw new InvalidOperationException (string.Format ("Unsupported member type '{0}' for member {1}.{2}.",
memberType,
typedocs.Root.Attribute ("FullName").Value,
member.Attribute("MemberName").Value));
}
cref.Append (":");
cref.Append (typedocs.Root.Attribute ("FullName").Value);
if (memberType != "Constructor") {
cref.Append (".");
cref.Append (member.Attribute ("MemberName").Value.Replace (".", "#"));
}
var p = member.Element ("Parameters");
if (p != null && p.Descendants ().Any ()) {
cref.Append ("(");
bool first = true;
var ps = p.Descendants ();
foreach (var pi in ps) {
cref.AppendFormat ("{0}{1}", first ? "" : ",", pi.Attribute ("Type").Value);
first = false;
}
cref.Append (")");
}
return cref.ToString ();
}
XElement ConvertCode (XElement e, bool insideFormat)
{
if (e.Value == "YES")
return new XElement ("see", new XAttribute ("langword", "true"));
if (e.Value == "NO")
return new XElement ("see", new XAttribute ("langword", "false"));
if (e.Value == "nil")
return new XElement ("see", new XAttribute ("langword", "null"));
return new XElement ("c", HtmlToMdoc (e.Nodes (), insideFormat));
}
// This method checks if the div is a code sample and if it's the case process it in a special way.
// if it's not the case it just delegate to HtmlToMdoc
object ConvertDiv (XElement e, bool insideFormat)
{
var cls = e.Attribute ("class");
if (cls == null || !cls.Value.Contains ("codesample"))
return HtmlToMdoc (e.Nodes (), insideFormat);
string content = e.Descendants ("tr").Select (tr => tr.Value).Aggregate ((l1, l2) => l1 + Environment.NewLine + l2);
XElement result = null;
if (options.ImportSamples) {
SampleDesc desc;
string snippet = samples.GetSampleFromContent (content, out desc);
result = new XElement ("example", new XElement ("code", new XAttribute ("lang", desc.Language), new XAttribute (XNamespace.Xml + "space", "preserve"), snippet));
Console.WriteLine ("Imported sample {0}", desc.ID);
} else {
var id = samples.RegisterSample (content, new SampleDesc { DocumentationFilePath = context.CurrentAppleDocPath, Language = "obj-c", FullTypeName = context.CurrentProcessedType.FullName } );
result = new XElement ("sample", new XAttribute ("external-id", id));
}
return result;
}
IEnumerable<object> HtmlToMdoc (IEnumerable<XNode> rest)
{
return HtmlToMdoc (rest, false);
}
IEnumerable<object> HtmlToMdoc (IEnumerable<XNode> rest, bool insideFormat)
{
foreach (var e in rest)
yield return HtmlToMdoc (e, insideFormat);
}
object HtmlToMdoc (XElement e)
{
return HtmlToMdoc (e, false);
}
object HtmlToMdoc (XNode n, bool insideFormat)
{
// Try to intelligently convert HTML into mdoc(5).
object r = null;
var e = n as XElement;
if (e != null && HtmlToMdocElementMapping.ContainsKey (e.Name.LocalName))
r = HtmlToMdocElementMapping [e.Name.LocalName] (e, insideFormat);
else if (e != null && !insideFormat)
r = new XElement ("format",
new XAttribute ("type", "text/html"),
HtmlToMdoc (e, true));
else if (e != null)
r = new XElement (e.Name,
e.Attributes (),
HtmlToMdoc (e.Nodes (), insideFormat));
else
r = n;
return r;
}
object HtmlToMdoc (XElement e, IEnumerable<XElement> rest)
{
return HtmlToMdoc (new[]{e}.Concat (rest).Cast<XNode> (), false);
}
class XElementDocumentOrderComparer : IComparer<XElement>
{
public static readonly IComparer<XElement> Default = new XElementDocumentOrderComparer ();
public int Compare (XElement a, XElement b)
{
if (object.ReferenceEquals (a, b))
return 0;
if (a.IsBefore (b))
return -1;
return 1;
}
}
XElement FirstInDocument (params XElement[] elements)
{
IEnumerable<XElement> e = elements;
return FirstInDocument (e);
}
XElement FirstInDocument (IEnumerable<XElement> elements)
{
return elements
.Where (e => e != null)
.OrderBy (e => e, XElementDocumentOrderComparer.Default)
.FirstOrDefault ();
}
public object ExtractTypeOverview (XElement appledocs)
{
var overview = appledocs.Descendants("h2").Where(e => e.Value == "Overview").FirstOrDefault();
if (overview == null)
return null;
var end = FirstInDocument (
GetDocSections (appledocs)
.Concat (new[]{
overview.ElementsAfterSelf ().Descendants ("hr").FirstOrDefault ()
}));
if (end == null)
return null;
var contents = overview.ElementsAfterSelf().Where(e => e.IsBefore(end));
return HtmlToMdoc (contents.FirstOrDefault (), contents.Skip (1));
}
IEnumerable<XElement> GetDocSections (XElement appledocs)
{
foreach (var e in appledocs.Descendants ("h2")) {
if (e.Value == "Class Methods" ||
e.Value == "Instance Methods" ||
e.Value == "Properties")
yield return e;
}
}
public object ExtractSummary (XElement member)
{
try {
return HtmlToMdoc (member.ElementsAfterSelf ("p").First ());
} catch {
return null;
}
}
public object ExtractSection (XElement member)
{
try {
return HtmlToMdoc (member.ElementsAfterSelf ("section").First ());
} catch {
return null;
}
}
XElement GetMemberDocEnd (XElement member)
{
return FirstInDocument (
member.ElementsAfterSelf ("h3").FirstOrDefault (),
member.ElementsAfterSelf ("hr").FirstOrDefault ());
}
IEnumerable<XElement> ExtractSection (XElement member, string section)
{
return from x in member.ElementsAfterSelf ("div")
let h5 = x.Descendants ("h5").FirstOrDefault (e => e.Value == section)
where h5 != null
from j in h5.ElementsAfterSelf () select j;
}
public IEnumerable<object> ExtractParams (XElement member)
{
var param = ExtractSection (member, "Parameters");
if (param == null || !param.Any ()){
return new object[0];
}
return param.Elements ("dd").Select (d => HtmlToMdoc (d));
}
public object ExtractReturn (XElement member)
{
var e = ExtractSection (member, "Return Value");
if (e == null)
return null;
return HtmlToMdoc (e.Cast<XNode> ());
}
public object ExtractDiscussion (XElement member)
{
var discussion = from x in member.ElementsAfterSelf ("div")
let h5 = x.Descendants ("h5").FirstOrDefault (e => e.Value == "Discussion")
where h5 != null
from j in h5.ElementsAfterSelf () select j;
return HtmlToMdoc (discussion.Cast<XNode> ());
}
string GetMdocPath (TypeDefinition t)
{
return options.MonodocArchive.GetPathForType (t);
}
XElement GetMdocMember (XDocument mdoc, string selector)
{
var exportAttr = options.BaseAssemblyNamespace + ".Foundation.Export(\"" + selector + "\"";
return
(from m in mdoc.XPathSelectElements ("Type/Members/Member")
where m.Descendants ("Attributes").Descendants ("Attribute").Descendants ("AttributeName")
.Where (n => n.Value.StartsWith (exportAttr) ||
n.Value.StartsWith ("get: " + exportAttr) ||
n.Value.StartsWith ("set: " + exportAttr)).Any ()
select m
).FirstOrDefault ();
}
string FixAppleDocPath (TypeDefinition t, string appledocpath)
{
var indexContent = File.ReadAllText (appledocpath);
if (indexContent.IndexOf ("<meta id=\"refresh\"") != -1) {
var p = indexContent.IndexOf ("0; URL=");
if (p == -1) {
Interlocked.Increment (ref numOfMissingAppleDocumentation);
Console.WriteLine ("Error, got an index.html file but can not find its refresh page for {0} and {1}", t.Name, appledocpath);
return appledocpath;
}
p += 7;
var l = indexContent.IndexOf ("\"", p);
appledocpath = Path.Combine (Path.GetDirectoryName (appledocpath), indexContent.Substring (p, l-p));
docPaths[t.FullName] = appledocpath;
return appledocpath;
}
return appledocpath;
}
string GetRealAppleDocPath (TypeDefinition t)
{
string appledocpath = null;
if (docPaths.ContainsKey (t.FullName)) {
appledocpath = docPaths[t.FullName];
if (appledocpath == null)
return null;
} else {
appledocpath = GetAppleDocFor (t);
if (appledocpath == null || !File.Exists (appledocpath)){
Interlocked.Increment (ref numOfMissingAppleDocumentation);
return null;
}
appledocpath = FixAppleDocPath (t, appledocpath);
}
context.CurrentAppleDocPath = appledocpath;
return appledocpath;
}
void VerifyArgumentSemantic (XElement mDoc, XElement member, TypeDefinition t, string selector)
{
// ArgumentSemantic validation
XElement code;
var codeDeclaration = mDoc.ElementsAfterSelf ("pre").FirstOrDefault ();
if (codeDeclaration == null || codeDeclaration.Attribute ("class") == null ||
codeDeclaration.Attribute ("class").Value != "declaration" ||
(code = codeDeclaration.Elements ("code").FirstOrDefault ()) == null)
return;
var decl = code.Value;
var m = propertyAttrs.Match (decl);
string attrs;
if (!m.Success || string.IsNullOrEmpty (attrs = m.Groups ["attrs"].Value))
return;
string semantic = null;
if (attrs.Contains ("assign"))
semantic = "ArgumentSemantic.Assign";
else if (attrs.Contains ("copy"))
semantic = "ArgumentSemantic.Copy";
else if (attrs.Contains ("retain"))
semantic = "ArgumentSemantic.Retain";
if (semantic != null &&
!member.XPathSelectElements ("Attributes/Attribute/AttributeName").Any (a => a.Value.Contains (semantic))) {
Console.WriteLine ("Missing [Export (\"{0}\", {1})] on Type={2} Member='{3}'", selector, semantic, t.FullName,
member.XPathSelectElement ("MemberSignature[@Language='C#']").Attribute ("Value").Value);
}
}
public XElement GetAppleMemberDocs(TypeDefinition t, string selector)
{
foreach (var appledocs in GetAppleDocumentationSources (t)) {
var mDoc = appledocs.Descendants ("h3").Where (e => e.Value == selector).FirstOrDefault ();
if (mDoc == null) {
// Many read-only properties have an 'is' prefix on the selector
// (which is removed on the docs), so try w/o the prefix, e.g.
// @property(getter=isDoubleSided) BOOL doubleSided;
var newSelector = char.ToLower (selector [2]) + selector.Substring (3);
mDoc = appledocs.Descendants ("h3").Where (e => e.Value == newSelector).FirstOrDefault ();
}
if (mDoc != null)
return mDoc;
}
return null;
}
public IEnumerable<XElement> GetAppleDocumentationSources (TypeDefinition t)
{
string path = GetRealAppleDocPath (t);
if (path != null)
yield return LoadAppleDocumentation (path);
foreach (var ancestor in GenerateAncestorChain (t)) {
path = GetRealAppleDocPath (ancestor);
if (path != null)
yield return LoadAppleDocumentation (path);
}
}
public XElement LoadAppleDocumentation (string path)
{
XElement appledocs;
if (loadedAppleDocs.TryGetValue (path, out appledocs))
return appledocs;
var doc = new HtmlDocument();
doc.Load (path, Encoding.UTF8);
doc.OptionOutputAsXml = true;
var sw = new StringWriter ();
doc.Save (sw);
//doc.Save ("/tmp/foo-" + Path.GetFileName (path));
// minor global fixups
var contents = sw.ToString ()
.Replace ("&#160;", " ")
.Replace ("&#8211;", "-")
.Replace ("&#xA0;", " ")
.Replace ("&nbsp;", " ");
// HtmlDocument wraps the <html/> with a <span/>; skip the <span/>.
appledocs = XElement.Parse (contents).Elements().First();
// remove the xmlns element from everything...
foreach (var e in appledocs.DescendantsAndSelf ()) {
e.Name = XName.Get (e.Name.LocalName);
}
loadedAppleDocs [path] = appledocs;
return appledocs;
}
// Only let one thread at a time advertise a new path
void AdvertiseNewPath (string path)
{
Action<string> callback;
if (pathCallback == null || (callback = Interlocked.Exchange (ref pathCallback, null)) == null)
return;
callback (path);
pathCallback = callback;
}
IEnumerable<TypeDefinition> GetTypes (AssemblyDefinition assembly)
{
return assembly.MainModule.Types;
}
}
}
| |
using System;
using Csla;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERLevel;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G09_Region_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="G09_Region_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="G08_Region"/> collection.
/// </remarks>
[Serializable]
public partial class G09_Region_ReChild : BusinessBase<G09_Region_ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name");
/// <summary>
/// Gets or sets the Cities Child Name.
/// </summary>
/// <value>The Cities Child Name.</value>
public string Region_Child_Name
{
get { return GetProperty(Region_Child_NameProperty); }
set { SetProperty(Region_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G09_Region_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G09_Region_ReChild"/> object.</returns>
internal static G09_Region_ReChild NewG09_Region_ReChild()
{
return DataPortal.CreateChild<G09_Region_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="G09_Region_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="region_ID2">The Region_ID2 parameter of the G09_Region_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="G09_Region_ReChild"/> object.</returns>
internal static G09_Region_ReChild GetG09_Region_ReChild(int region_ID2)
{
return DataPortal.FetchChild<G09_Region_ReChild>(region_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G09_Region_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G09_Region_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G09_Region_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="G09_Region_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="region_ID2">The Region ID2.</param>
protected void Child_Fetch(int region_ID2)
{
var args = new DataPortalHookArgs(region_ID2);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IG09_Region_ReChildDal>();
var data = dal.Fetch(region_ID2);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Loads a <see cref="G09_Region_ReChild"/> object from the given <see cref="G09_Region_ReChildDto"/>.
/// </summary>
/// <param name="data">The G09_Region_ReChildDto to use.</param>
private void Fetch(G09_Region_ReChildDto data)
{
// Value properties
LoadProperty(Region_Child_NameProperty, data.Region_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="G09_Region_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(G08_Region parent)
{
var dto = new G09_Region_ReChildDto();
dto.Parent_Region_ID = parent.Region_ID;
dto.Region_Child_Name = Region_Child_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IG09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G09_Region_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(G08_Region parent)
{
if (!IsDirty)
return;
var dto = new G09_Region_ReChildDto();
dto.Parent_Region_ID = parent.Region_ID;
dto.Region_Child_Name = Region_Child_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IG09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="G09_Region_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(G08_Region parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IG09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Region_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Math.Raw;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Math.EC.Custom.Sec
{
internal class SecP160R2FieldElement
: ECFieldElement
{
public static readonly BigInteger Q = SecP160R2Curve.q;
protected internal readonly uint[] x;
public SecP160R2FieldElement(BigInteger x)
{
if (x == null || x.SignValue < 0 || x.CompareTo(Q) >= 0)
throw new ArgumentException("value invalid for SecP160R2FieldElement", "x");
this.x = SecP160R2Field.FromBigInteger(x);
}
public SecP160R2FieldElement()
{
this.x = Nat160.Create();
}
protected internal SecP160R2FieldElement(uint[] x)
{
this.x = x;
}
public override bool IsZero
{
get { return Nat160.IsZero(x); }
}
public override bool IsOne
{
get { return Nat160.IsOne(x); }
}
public override bool TestBitZero()
{
return Nat160.GetBit(x, 0) == 1;
}
public override BigInteger ToBigInteger()
{
return Nat160.ToBigInteger(x);
}
public override string FieldName
{
get { return "SecP160R2Field"; }
}
public override int FieldSize
{
get { return Q.BitLength; }
}
public override ECFieldElement Add(ECFieldElement b)
{
uint[] z = Nat160.Create();
SecP160R2Field.Add(x, ((SecP160R2FieldElement)b).x, z);
return new SecP160R2FieldElement(z);
}
public override ECFieldElement AddOne()
{
uint[] z = Nat160.Create();
SecP160R2Field.AddOne(x, z);
return new SecP160R2FieldElement(z);
}
public override ECFieldElement Subtract(ECFieldElement b)
{
uint[] z = Nat160.Create();
SecP160R2Field.Subtract(x, ((SecP160R2FieldElement)b).x, z);
return new SecP160R2FieldElement(z);
}
public override ECFieldElement Multiply(ECFieldElement b)
{
uint[] z = Nat160.Create();
SecP160R2Field.Multiply(x, ((SecP160R2FieldElement)b).x, z);
return new SecP160R2FieldElement(z);
}
public override ECFieldElement Divide(ECFieldElement b)
{
// return Multiply(b.invert());
uint[] z = Nat160.Create();
Mod.Invert(SecP160R2Field.P, ((SecP160R2FieldElement)b).x, z);
SecP160R2Field.Multiply(z, x, z);
return new SecP160R2FieldElement(z);
}
public override ECFieldElement Negate()
{
uint[] z = Nat160.Create();
SecP160R2Field.Negate(x, z);
return new SecP160R2FieldElement(z);
}
public override ECFieldElement Square()
{
uint[] z = Nat160.Create();
SecP160R2Field.Square(x, z);
return new SecP160R2FieldElement(z);
}
public override ECFieldElement Invert()
{
// return new SecP160R2FieldElement(ToBigInteger().modInverse(Q));
uint[] z = Nat160.Create();
Mod.Invert(SecP160R2Field.P, x, z);
return new SecP160R2FieldElement(z);
}
// D.1.4 91
/**
* return a sqrt root - the routine verifies that the calculation returns the right value - if
* none exists it returns null.
*/
public override ECFieldElement Sqrt()
{
/*
* Raise this element to the exponent 2^158 - 2^30 - 2^12 - 2^10 - 2^7 - 2^6 - 2^5 - 2^1 - 2^0
*
* Breaking up the exponent's binary representation into "repunits", we get: { 127 1s } { 1
* 0s } { 17 1s } { 1 0s } { 1 1s } { 1 0s } { 2 1s } { 3 0s } { 3 1s } { 1 0s } { 1 1s }
*
* Therefore we need an Addition chain containing 1, 2, 3, 17, 127 (the lengths of the repunits)
* We use: [1], [2], [3], 4, 7, 14, [17], 31, 62, 124, [127]
*/
uint[] x1 = this.x;
if (Nat160.IsZero(x1) || Nat160.IsOne(x1))
{
return this;
}
uint[] x2 = Nat160.Create();
SecP160R2Field.Square(x1, x2);
SecP160R2Field.Multiply(x2, x1, x2);
uint[] x3 = Nat160.Create();
SecP160R2Field.Square(x2, x3);
SecP160R2Field.Multiply(x3, x1, x3);
uint[] x4 = Nat160.Create();
SecP160R2Field.Square(x3, x4);
SecP160R2Field.Multiply(x4, x1, x4);
uint[] x7 = Nat160.Create();
SecP160R2Field.SquareN(x4, 3, x7);
SecP160R2Field.Multiply(x7, x3, x7);
uint[] x14 = x4;
SecP160R2Field.SquareN(x7, 7, x14);
SecP160R2Field.Multiply(x14, x7, x14);
uint[] x17 = x7;
SecP160R2Field.SquareN(x14, 3, x17);
SecP160R2Field.Multiply(x17, x3, x17);
uint[] x31 = Nat160.Create();
SecP160R2Field.SquareN(x17, 14, x31);
SecP160R2Field.Multiply(x31, x14, x31);
uint[] x62 = x14;
SecP160R2Field.SquareN(x31, 31, x62);
SecP160R2Field.Multiply(x62, x31, x62);
uint[] x124 = x31;
SecP160R2Field.SquareN(x62, 62, x124);
SecP160R2Field.Multiply(x124, x62, x124);
uint[] x127 = x62;
SecP160R2Field.SquareN(x124, 3, x127);
SecP160R2Field.Multiply(x127, x3, x127);
uint[] t1 = x127;
SecP160R2Field.SquareN(t1, 18, t1);
SecP160R2Field.Multiply(t1, x17, t1);
SecP160R2Field.SquareN(t1, 2, t1);
SecP160R2Field.Multiply(t1, x1, t1);
SecP160R2Field.SquareN(t1, 3, t1);
SecP160R2Field.Multiply(t1, x2, t1);
SecP160R2Field.SquareN(t1, 6, t1);
SecP160R2Field.Multiply(t1, x3, t1);
SecP160R2Field.SquareN(t1, 2, t1);
SecP160R2Field.Multiply(t1, x1, t1);
uint[] t2 = x2;
SecP160R2Field.Square(t1, t2);
return Nat160.Eq(x1, t2) ? new SecP160R2FieldElement(t1) : null;
}
public override bool Equals(object obj)
{
return Equals(obj as SecP160R2FieldElement);
}
public override bool Equals(ECFieldElement other)
{
return Equals(other as SecP160R2FieldElement);
}
public virtual bool Equals(SecP160R2FieldElement other)
{
if (this == other)
return true;
if (null == other)
return false;
return Nat160.Eq(x, other.x);
}
public override int GetHashCode()
{
return Q.GetHashCode() ^ Arrays.GetHashCode(x, 0, 5);
}
}
}
#endif
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Represents logging target.
/// </summary>
[NLogConfigurationItem]
public abstract class Target : ISupportsInitialize, IDisposable
{
private object lockObject = new object();
private List<Layout> allLayouts;
private Exception initializeException;
/// <summary>
/// Gets or sets the name of the target.
/// </summary>
/// <docgen category='General Options' order='10' />
public string Name { get; set; }
/// <summary>
/// Gets the object which can be used to synchronize asynchronous operations that must rely on the .
/// </summary>
protected object SyncRoot
{
get { return this.lockObject; }
}
/// <summary>
/// Gets the logging configuration this target is part of.
/// </summary>
protected LoggingConfiguration LoggingConfiguration { get; private set; }
/// <summary>
/// Gets a value indicating whether the target has been initialized.
/// </summary>
protected bool IsInitialized { get; private set; }
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
{
this.Initialize(configuration);
}
/// <summary>
/// Closes this instance.
/// </summary>
void ISupportsInitialize.Close()
{
this.Close();
}
/// <summary>
/// Closes the target.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public void Flush(AsyncContinuation asyncContinuation)
{
if (asyncContinuation == null)
{
throw new ArgumentNullException("asyncContinuation");
}
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
asyncContinuation(null);
return;
}
asyncContinuation = AsyncHelpers.PreventMultipleCalls(asyncContinuation);
try
{
this.FlushAsync(asyncContinuation);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
asyncContinuation(exception);
}
}
}
/// <summary>
/// Calls the <see cref="Layout.Precalculate"/> on each volatile layout
/// used by this target.
/// </summary>
/// <param name="logEvent">
/// The log event.
/// </param>
public void PrecalculateVolatileLayouts(LogEventInfo logEvent)
{
lock (this.SyncRoot)
{
if (this.IsInitialized)
{
foreach (Layout l in this.allLayouts)
{
l.Precalculate(logEvent);
}
}
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var targetAttribute = (TargetAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(TargetAttribute));
if (targetAttribute != null)
{
return targetAttribute.Name + " Target[" + (this.Name ?? "(unnamed)") + "]";
}
return this.GetType().Name;
}
/// <summary>
/// Writes the log to the target.
/// </summary>
/// <param name="logEvent">Log event to write.</param>
public void WriteAsyncLogEvent(AsyncLogEventInfo logEvent)
{
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
logEvent.Continuation(null);
return;
}
if (this.initializeException != null)
{
logEvent.Continuation(this.CreateInitException());
return;
}
var wrappedContinuation = AsyncHelpers.PreventMultipleCalls(logEvent.Continuation);
try
{
this.Write(logEvent.LogEvent.WithContinuation(wrappedContinuation));
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
wrappedContinuation(exception);
}
}
}
/// <summary>
/// Writes the array of log events.
/// </summary>
/// <param name="logEvents">The log events.</param>
public void WriteAsyncLogEvents(params AsyncLogEventInfo[] logEvents)
{
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
foreach (var ev in logEvents)
{
ev.Continuation(null);
}
return;
}
if (this.initializeException != null)
{
foreach (var ev in logEvents)
{
ev.Continuation(this.CreateInitException());
}
return;
}
var wrappedEvents = new AsyncLogEventInfo[logEvents.Length];
for (int i = 0; i < logEvents.Length; ++i)
{
wrappedEvents[i] = logEvents[i].LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(logEvents[i].Continuation));
}
try
{
this.Write(wrappedEvents);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
// in case of synchronous failure, assume that nothing is running asynchronously
foreach (var ev in wrappedEvents)
{
ev.Continuation(exception);
}
}
}
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal void Initialize(LoggingConfiguration configuration)
{
lock (this.SyncRoot)
{
this.LoggingConfiguration = configuration;
if (!this.IsInitialized)
{
PropertyHelper.CheckRequiredParameters(this);
this.IsInitialized = true;
try
{
this.InitializeTarget();
this.initializeException = null;
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
this.initializeException = exception;
InternalLogger.Error("Error initializing target {0} {1}.", this, exception);
throw;
}
}
}
}
/// <summary>
/// Closes this instance.
/// </summary>
internal void Close()
{
lock (this.SyncRoot)
{
this.LoggingConfiguration = null;
if (this.IsInitialized)
{
this.IsInitialized = false;
try
{
if (this.initializeException == null)
{
// if Init succeeded, call Close()
this.CloseTarget();
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error closing target {0} {1}.", this, exception);
throw;
}
}
}
}
internal void WriteAsyncLogEvents(AsyncLogEventInfo[] logEventInfos, AsyncContinuation continuation)
{
if (logEventInfos.Length == 0)
{
continuation(null);
}
else
{
var wrappedLogEventInfos = new AsyncLogEventInfo[logEventInfos.Length];
int remaining = logEventInfos.Length;
for (int i = 0; i < logEventInfos.Length; ++i)
{
AsyncContinuation originalContinuation = logEventInfos[i].Continuation;
AsyncContinuation wrappedContinuation = ex =>
{
originalContinuation(ex);
if (0 == Interlocked.Decrement(ref remaining))
{
continuation(null);
}
};
wrappedLogEventInfos[i] = logEventInfos[i].LogEvent.WithContinuation(wrappedContinuation);
}
this.WriteAsyncLogEvents(wrappedLogEventInfos);
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.CloseTarget();
}
}
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
protected virtual void InitializeTarget()
{
this.GetAllLayouts();
}
/// <summary>
/// Closes the target and releases any unmanaged resources.
/// </summary>
protected virtual void CloseTarget()
{
}
/// <summary>
/// Flush any pending log messages asynchronously (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected virtual void FlushAsync(AsyncContinuation asyncContinuation)
{
asyncContinuation(null);
}
/// <summary>
/// Writes logging event to the log target.
/// classes.
/// </summary>
/// <param name="logEvent">
/// Logging event to be written out.
/// </param>
protected virtual void Write(LogEventInfo logEvent)
{
// do nothing
}
/// <summary>
/// Writes log event to the log target. Must be overridden in inheriting
/// classes.
/// </summary>
/// <param name="logEvent">Log event to be written out.</param>
protected virtual void Write(AsyncLogEventInfo logEvent)
{
try
{
this.Write(logEvent.LogEvent);
logEvent.Continuation(null);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
logEvent.Continuation(exception);
}
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected virtual void Write(AsyncLogEventInfo[] logEvents)
{
for (int i = 0; i < logEvents.Length; ++i)
{
this.Write(logEvents[i]);
}
}
private Exception CreateInitException()
{
return new NLogRuntimeException("Target " + this + " failed to initialize.", this.initializeException);
}
private void GetAllLayouts()
{
this.allLayouts = new List<Layout>(ObjectGraphScanner.FindReachableObjects<Layout>(this));
InternalLogger.Trace("{0} has {1} layouts", this, this.allLayouts.Count);
}
}
}
| |
//
// Copyright (c) 2004-2018 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.
//
#if MONO
namespace NLog.Internal.FileAppenders
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml;
using NLog;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using Mono.Unix;
using Mono.Unix.Native;
/// <summary>
/// Provides a multiprocess-safe atomic file appends while
/// keeping the files open.
/// </summary>
/// <remarks>
/// On Unix you can get all the appends to be atomic, even when multiple
/// processes are trying to write to the same file, because setting the file
/// pointer to the end of the file and appending can be made one operation.
/// </remarks>
internal class UnixMultiProcessFileAppender : BaseMutexFileAppender
{
private UnixStream _file;
public static readonly IFileAppenderFactory TheFactory = new Factory();
private class Factory : IFileAppenderFactory
{
BaseFileAppender IFileAppenderFactory.Open(string fileName, ICreateFileParameters parameters)
{
return new UnixMultiProcessFileAppender(fileName, parameters);
}
}
public UnixMultiProcessFileAppender(string fileName, ICreateFileParameters parameters) : base(fileName, parameters)
{
UnixFileInfo fileInfo = null;
bool fileExists = false;
try
{
fileInfo = new UnixFileInfo(fileName);
fileExists = fileInfo.Exists;
}
catch
{
}
int fd = Syscall.open(fileName, OpenFlags.O_CREAT | OpenFlags.O_WRONLY | OpenFlags.O_APPEND, (FilePermissions)(6 | (6 << 3) | (6 << 6)));
if (fd == -1)
{
if (Stdlib.GetLastError() == Errno.ENOENT && parameters.CreateDirs)
{
string dirName = Path.GetDirectoryName(fileName);
if (!Directory.Exists(dirName) && parameters.CreateDirs)
Directory.CreateDirectory(dirName);
fd = Syscall.open(fileName, OpenFlags.O_CREAT | OpenFlags.O_WRONLY | OpenFlags.O_APPEND, (FilePermissions)(6 | (6 << 3) | (6 << 6)));
}
}
if (fd == -1)
UnixMarshal.ThrowExceptionForLastError();
try
{
_file = new UnixStream(fd, true);
long filePosition = _file.Position;
if (fileExists || filePosition > 0)
{
if (fileInfo != null)
{
CreationTimeUtc = FileCharacteristicsHelper.ValidateFileCreationTime(fileInfo, (f) => File.GetCreationTimeUtc(f.FullName), (f) => { f.Refresh(); return f.LastStatusChangeTimeUtc; }, (f) => DateTime.UtcNow).Value;
}
else
{
CreationTimeUtc = FileCharacteristicsHelper.ValidateFileCreationTime(fileName, (f) => File.GetCreationTimeUtc(f), (f) => DateTime.UtcNow).Value;
}
}
else
{
// We actually created the file and eventually concurrent processes
CreationTimeUtc = DateTime.UtcNow;
File.SetCreationTimeUtc(FileName, CreationTimeUtc);
}
}
catch
{
Syscall.close(fd);
throw;
}
}
/// <summary>
/// Writes the specified bytes.
/// </summary>
/// <param name="bytes">The bytes array.</param>
/// <param name="offset">The bytes array offset.</param>
/// <param name="count">The number of bytes.</param>
public override void Write(byte[] bytes, int offset, int count)
{
if (_file == null)
return;
_file.Write(bytes, offset, count);
}
/// <summary>
/// Closes this instance.
/// </summary>
public override void Close()
{
if (_file == null)
return;
InternalLogger.Trace("Closing '{0}'", FileName);
try
{
_file?.Close();
}
catch (Exception ex)
{
// Swallow exception as the file-stream now is in final state (broken instead of closed)
InternalLogger.Warn(ex, "Failed to close file '{0}'", FileName);
System.Threading.Thread.Sleep(1); // Artificial delay to avoid hammering a bad file location
}
finally
{
_file = null;
}
}
/// <summary>
/// Gets the creation time for a file associated with the appender. The time returned is in Coordinated Universal
/// Time [UTC] standard.
/// </summary>
/// <returns>The file creation time.</returns>
public override DateTime? GetFileCreationTimeUtc()
{
return CreationTimeUtc; // File is kept open, so creation time is static
}
/// <summary>
/// Gets the last time the file associated with the appeander is written. The time returned is in Coordinated
/// Universal Time [UTC] standard.
/// </summary>
/// <returns>The time the file was last written to.</returns>
public override DateTime? GetFileLastWriteTimeUtc()
{
FileInfo fileInfo = new FileInfo(FileName);
if (!fileInfo.Exists)
return null;
return fileInfo.LastWriteTime;
}
/// <summary>
/// Gets the length in bytes of the file associated with the appeander.
/// </summary>
/// <returns>A long value representing the length of the file in bytes.</returns>
public override long? GetFileLength()
{
FileInfo fileInfo = new FileInfo(FileName);
if (!fileInfo.Exists)
return null;
return fileInfo.Length;
}
public override void Flush()
{
// do nothing, the stream is always flushed
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Orleans.Concurrency;
using Orleans.Runtime;
using Orleans.Serialization;
namespace Orleans.Streams
{
[Serializable]
[Immutable]
internal class StreamImpl<T> : IStreamIdentity, IAsyncStream<T>, IStreamControl, ISerializable, IOnDeserialized
{
private readonly StreamId streamId;
private readonly bool isRewindable;
[NonSerialized]
private IInternalStreamProvider provider;
[NonSerialized]
private volatile IInternalAsyncBatchObserver<T> producerInterface;
[NonSerialized]
private IInternalAsyncObservable<T> consumerInterface;
[NonSerialized]
private readonly object initLock; // need the lock since the same code runs in the provider on the client and in the silo.
[NonSerialized]
private IRuntimeClient runtimeClient;
internal StreamId StreamId { get { return streamId; } }
public bool IsRewindable { get { return isRewindable; } }
public Guid Guid { get { return streamId.Guid; } }
public string Namespace { get { return streamId.Namespace; } }
public string ProviderName { get { return streamId.ProviderName; } }
// IMPORTANT: This constructor needs to be public for Json deserialization to work.
public StreamImpl()
{
initLock = new object();
}
internal StreamImpl(StreamId streamId, IInternalStreamProvider provider, bool isRewindable, IRuntimeClient runtimeClient)
{
if (null == streamId)
throw new ArgumentNullException(nameof(streamId));
if (null == provider)
throw new ArgumentNullException(nameof(provider));
if (null == runtimeClient)
throw new ArgumentNullException(nameof(runtimeClient));
this.streamId = streamId;
this.provider = provider;
producerInterface = null;
consumerInterface = null;
initLock = new object();
this.isRewindable = isRewindable;
this.runtimeClient = runtimeClient;
}
public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer)
{
return GetConsumerInterface().SubscribeAsync(observer, null);
}
public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer, StreamSequenceToken token,
StreamFilterPredicate filterFunc = null,
object filterData = null)
{
return GetConsumerInterface().SubscribeAsync(observer, token, filterFunc, filterData);
}
public async Task Cleanup(bool cleanupProducers, bool cleanupConsumers)
{
// Cleanup producers
if (cleanupProducers && producerInterface != null)
{
await producerInterface.Cleanup();
producerInterface = null;
}
// Cleanup consumers
if (cleanupConsumers && consumerInterface != null)
{
await consumerInterface.Cleanup();
consumerInterface = null;
}
}
public Task OnNextAsync(T item, StreamSequenceToken token = null)
{
return GetProducerInterface().OnNextAsync(item, token);
}
public Task OnNextBatchAsync(IEnumerable<T> batch, StreamSequenceToken token = null)
{
return GetProducerInterface().OnNextBatchAsync(batch, token);
}
public Task OnCompletedAsync()
{
return GetProducerInterface().OnCompletedAsync();
}
public Task OnErrorAsync(Exception ex)
{
return GetProducerInterface().OnErrorAsync(ex);
}
internal Task<StreamSubscriptionHandle<T>> ResumeAsync(
StreamSubscriptionHandle<T> handle,
IAsyncObserver<T> observer,
StreamSequenceToken token)
{
return GetConsumerInterface().ResumeAsync(handle, observer, token);
}
public Task<IList<StreamSubscriptionHandle<T>>> GetAllSubscriptionHandles()
{
return GetConsumerInterface().GetAllSubscriptions();
}
internal Task UnsubscribeAsync(StreamSubscriptionHandle<T> handle)
{
return GetConsumerInterface().UnsubscribeAsync(handle);
}
internal IAsyncBatchObserver<T> GetProducerInterface()
{
if (producerInterface != null) return producerInterface;
lock (initLock)
{
if (producerInterface != null)
return producerInterface;
if (provider == null)
provider = GetStreamProvider();
producerInterface = provider.GetProducerInterface<T>(this);
}
return producerInterface;
}
internal IInternalAsyncObservable<T> GetConsumerInterface()
{
if (consumerInterface == null)
{
lock (initLock)
{
if (consumerInterface == null)
{
if (provider == null)
provider = GetStreamProvider();
consumerInterface = provider.GetConsumerInterface<T>(this);
}
}
}
return consumerInterface;
}
private IInternalStreamProvider GetStreamProvider()
{
return this.runtimeClient.CurrentStreamProviderManager.GetProvider(streamId.ProviderName) as IInternalStreamProvider;
}
#region IComparable<IAsyncStream<T>> Members
public int CompareTo(IAsyncStream<T> other)
{
var o = other as StreamImpl<T>;
return o == null ? 1 : streamId.CompareTo(o.streamId);
}
#endregion
#region IEquatable<IAsyncStream<T>> Members
public virtual bool Equals(IAsyncStream<T> other)
{
var o = other as StreamImpl<T>;
return o != null && streamId.Equals(o.streamId);
}
#endregion
public override bool Equals(object obj)
{
var o = obj as StreamImpl<T>;
return o != null && streamId.Equals(o.streamId);
}
public override int GetHashCode()
{
return streamId.GetHashCode();
}
public override string ToString()
{
return streamId.ToString();
}
#region ISerializable Members
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Use the AddValue method to specify serialized values.
info.AddValue("StreamId", streamId, typeof(StreamId));
info.AddValue("IsRewindable", isRewindable, typeof(bool));
}
// The special constructor is used to deserialize values.
protected StreamImpl(SerializationInfo info, StreamingContext context)
{
// Reset the property value using the GetValue method.
streamId = (StreamId)info.GetValue("StreamId", typeof(StreamId));
isRewindable = info.GetBoolean("IsRewindable");
initLock = new object();
var serializerContext = context.Context as ISerializerContext;
((IOnDeserialized)this).OnDeserialized(serializerContext);
}
void IOnDeserialized.OnDeserialized(ISerializerContext context)
{
this.runtimeClient = context?.AdditionalContext as IRuntimeClient;
}
#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 Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Metadata;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
/// <summary>
/// Debugger type proxy expansion.
/// </summary>
/// <remarks>
/// May include <see cref="System.Collections.IEnumerable"/> and
/// <see cref="System.Collections.Generic.IEnumerable{T}"/> as special cases.
/// (The proxy is not declared by an attribute, but is known to debugger.)
/// </remarks>
internal sealed class DebuggerTypeProxyExpansion : Expansion
{
internal static Expansion CreateExpansion(
ResultProvider resultProvider,
DkmInspectionContext inspectionContext,
string name,
TypeAndCustomInfo typeDeclaringMemberAndInfoOpt,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
bool childShouldParenthesize,
string fullName,
string childFullNamePrefix,
ReadOnlyCollection<string> formatSpecifiers,
DkmEvaluationResultFlags flags,
string editableValue)
{
Debug.Assert((inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) == 0);
// Note: The native EE uses the proxy type, even for
// null instances, so statics on the proxy type are
// displayed. That case is not supported currently.
if (!value.IsNull)
{
var proxyType = value.Type.GetProxyType();
if (proxyType != null)
{
if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.ShowValueRaw) != 0)
{
var rawView = CreateRawView(resultProvider, inspectionContext, declaredTypeAndInfo, value);
Debug.Assert(rawView != null);
return rawView;
}
DkmClrValue proxyValue;
try
{
proxyValue = value.InstantiateProxyType(inspectionContext, proxyType);
}
catch
{
proxyValue = null;
}
if (proxyValue != null)
{
return new DebuggerTypeProxyExpansion(
inspectionContext,
proxyValue,
name,
typeDeclaringMemberAndInfoOpt,
declaredTypeAndInfo,
value,
childShouldParenthesize,
fullName,
childFullNamePrefix,
formatSpecifiers,
flags,
editableValue,
resultProvider.Formatter);
}
}
}
return null;
}
private readonly EvalResultDataItem _proxyItem;
private readonly string _name;
private readonly TypeAndCustomInfo _typeDeclaringMemberAndInfoOpt;
private readonly TypeAndCustomInfo _declaredTypeAndInfo;
private readonly DkmClrValue _value;
private readonly bool _childShouldParenthesize;
private readonly string _fullName;
private readonly string _childFullNamePrefix;
private readonly ReadOnlyCollection<string> _formatSpecifiers;
private readonly DkmEvaluationResultFlags _flags;
private readonly string _editableValue;
private DebuggerTypeProxyExpansion(
DkmInspectionContext inspectionContext,
DkmClrValue proxyValue,
string name,
TypeAndCustomInfo typeDeclaringMemberAndInfoOpt,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
bool childShouldParenthesize,
string fullName,
string childFullNamePrefix,
ReadOnlyCollection<string> formatSpecifiers,
DkmEvaluationResultFlags flags,
string editableValue,
Formatter formatter)
{
Debug.Assert(proxyValue != null);
var proxyType = proxyValue.Type.GetLmrType();
var proxyTypeAndInfo = new TypeAndCustomInfo(proxyType);
var proxyMembers = MemberExpansion.CreateExpansion(
inspectionContext,
proxyTypeAndInfo,
proxyValue,
ExpansionFlags.IncludeBaseMembers,
TypeHelpers.IsPublic,
formatter);
if (proxyMembers != null)
{
string proxyMemberFullNamePrefix = null;
if (childFullNamePrefix != null)
{
bool sawInvalidIdentifier;
var proxyTypeName = formatter.GetTypeName(proxyTypeAndInfo, escapeKeywordIdentifiers: true, sawInvalidIdentifier: out sawInvalidIdentifier);
if (!sawInvalidIdentifier)
{
proxyMemberFullNamePrefix = formatter.GetObjectCreationExpression(proxyTypeName, childFullNamePrefix);
}
}
_proxyItem = new EvalResultDataItem(
ExpansionKind.Default,
name: string.Empty,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: proxyTypeAndInfo,
parent: null,
value: proxyValue,
displayValue: null,
expansion: proxyMembers,
childShouldParenthesize: false,
fullName: null,
childFullNamePrefixOpt: proxyMemberFullNamePrefix,
formatSpecifiers: Formatter.NoFormatSpecifiers,
category: default(DkmEvaluationResultCategory),
flags: default(DkmEvaluationResultFlags),
editableValue: null,
inspectionContext: inspectionContext);
}
_name = name;
_typeDeclaringMemberAndInfoOpt = typeDeclaringMemberAndInfoOpt;
_declaredTypeAndInfo = declaredTypeAndInfo;
_value = value;
_childShouldParenthesize = childShouldParenthesize;
_fullName = fullName;
_childFullNamePrefix = childFullNamePrefix;
_formatSpecifiers = formatSpecifiers;
_flags = flags;
_editableValue = editableValue;
}
internal override void GetRows(
ResultProvider resultProvider,
ArrayBuilder<EvalResultDataItem> rows,
DkmInspectionContext inspectionContext,
EvalResultDataItem parent,
DkmClrValue value,
int startIndex,
int count,
bool visitAll,
ref int index)
{
if (_proxyItem != null)
{
_proxyItem.Expansion.GetRows(resultProvider, rows, inspectionContext, _proxyItem, _proxyItem.Value, startIndex, count, visitAll, ref index);
}
if (InRange(startIndex, count, index))
{
rows.Add(this.CreateRawViewRow(resultProvider, inspectionContext));
}
index++;
}
private EvalResultDataItem CreateRawViewRow(
ResultProvider resultProvider,
DkmInspectionContext inspectionContext)
{
return new EvalResultDataItem(
ExpansionKind.RawView,
_name,
_typeDeclaringMemberAndInfoOpt,
_declaredTypeAndInfo,
parent: null,
value: _value,
displayValue: null,
expansion: CreateRawView(resultProvider, inspectionContext, _declaredTypeAndInfo, _value),
childShouldParenthesize: _childShouldParenthesize,
fullName: _fullName,
childFullNamePrefixOpt: _childFullNamePrefix,
formatSpecifiers: Formatter.AddFormatSpecifier(_formatSpecifiers, "raw"),
category: DkmEvaluationResultCategory.Data,
flags: _flags | DkmEvaluationResultFlags.ReadOnly,
editableValue: _editableValue,
inspectionContext: inspectionContext);
}
private static Expansion CreateRawView(
ResultProvider resultProvider,
DkmInspectionContext inspectionContext,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value)
{
return resultProvider.GetTypeExpansion(inspectionContext, declaredTypeAndInfo, value, ExpansionFlags.IncludeBaseMembers);
}
}
}
| |
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Sounds
//--------------------------------------------------------------------------
datablock SFXProfile(LurkerFireSound)
{
filename = "art/sound/weapons/wpn_lurker_fire";
description = AudioClose3D;
preload = true;
};
datablock SFXProfile(LurkerReloadSound)
{
filename = "art/sound/weapons/wpn_lurker_reload";
description = AudioClose3D;
preload = true;
};
datablock SFXProfile(LurkerIdleSound)
{
filename = "art/sound/weapons/wpn_lurker_idle";
description = AudioClose3D;
preload = true;
};
datablock SFXProfile(LurkerSwitchinSound)
{
filename = "art/sound/weapons/wpn_lurker_switchin";
description = AudioClose3D;
preload = true;
};
datablock SFXProfile(LurkerGrenadeFireSound)
{
filename = "art/sound/weapons/wpn_lurker_grenadelaunch";
description = AudioClose3D;
preload = true;
};
datablock SFXPlayList(LurkerFireSoundList)
{
// Use a looped description so the list playback will loop.
description = AudioClose3D;
track[ 0 ] = LurkerFireSound;
};
/*datablock SFXProfile(BulletImpactSound)
{
filename = "art/sound/weapons/SCARFIRE";
description = AudioClose3D;
preload = true;
};*/
// ----------------------------------------------------------------------------
// Particles
// ----------------------------------------------------------------------------
datablock ParticleData(GunFireSmoke)
{
textureName = "art/particles/smoke";
dragCoefficient = 0;
gravityCoefficient = "-1";
windCoefficient = 0;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 500;
lifetimeVarianceMS = 200;
spinRandomMin = -180.0;
spinRandomMax = 180.0;
useInvAlpha = true;
colors[0] = "0.795276 0.795276 0.795276 0.692913";
colors[1] = "0.866142 0.866142 0.866142 0.346457";
colors[2] = "0.897638 0.834646 0.795276 0";
sizes[0] = "0.399805";
sizes[1] = "1.19941";
sizes[2] = "1.69993";
times[0] = 0.0;
times[1] = "0.498039";
times[2] = 1.0;
animTexName = "art/particles/smoke";
};
datablock ParticleEmitterData(GunFireSmokeEmitter)
{
ejectionPeriodMS = 20;
periodVarianceMS = 10;
ejectionVelocity = "0";
velocityVariance = "0";
thetaMin = "0";
thetaMax = "0";
lifetimeMS = 250;
particles = "GunFireSmoke";
blendStyle = "NORMAL";
softParticles = "0";
originalName = "GunFireSmokeEmitter";
alignParticles = "0";
orientParticles = "0";
};
datablock ParticleData(BulletDirtDust)
{
textureName = "art/particles/impact";
dragCoefficient = "1";
gravityCoefficient = "-0.100122";
windCoefficient = 0;
inheritedVelFactor = 0.0;
constantAcceleration = "-0.83";
lifetimeMS = 800;
lifetimeVarianceMS = 300;
spinRandomMin = -180.0;
spinRandomMax = 180.0;
useInvAlpha = true;
colors[0] = "0.496063 0.393701 0.299213 0.692913";
colors[1] = "0.692913 0.614173 0.535433 0.346457";
colors[2] = "0.897638 0.84252 0.795276 0";
sizes[0] = "0.997986";
sizes[1] = "2";
sizes[2] = "2.5";
times[0] = 0.0;
times[1] = "0.498039";
times[2] = 1.0;
animTexName = "art/particles/impact";
};
datablock ParticleEmitterData(BulletDirtDustEmitter)
{
ejectionPeriodMS = 20;
periodVarianceMS = 10;
ejectionVelocity = "1";
velocityVariance = 1.0;
thetaMin = 0.0;
thetaMax = 180.0;
lifetimeMS = 250;
particles = "BulletDirtDust";
blendStyle = "NORMAL";
};
//-----------------------------------------------------------------------------
// Explosion
//-----------------------------------------------------------------------------
datablock ExplosionData(BulletDirtExplosion)
{
soundProfile = BulletImpactSound;
lifeTimeMS = 65;
// Volume particles
particleEmitter = BulletDirtDustEmitter;
particleDensity = 4;
particleRadius = 0.3;
// Point emission
emitter[0] = BulletDirtSprayEmitter;
emitter[1] = BulletDirtSprayEmitter;
emitter[2] = BulletDirtRocksEmitter;
};
//--------------------------------------------------------------------------
// Shell ejected during reload.
//-----------------------------------------------------------------------------
datablock DebrisData(BulletShell)
{
shapeFile = "art/shapes/weapons/shared/RifleShell.DAE";
lifetime = 6.0;
minSpinSpeed = 300.0;
maxSpinSpeed = 400.0;
elasticity = 0.65;
friction = 0.05;
numBounces = 5;
staticOnMaxBounce = true;
snapOnMaxBounce = false;
ignoreWater = true;
fade = true;
};
//-----------------------------------------------------------------------------
// Projectile Object
//-----------------------------------------------------------------------------
datablock LightDescription( BulletProjectileLightDesc )
{
color = "0.0 0.5 0.7";
range = 3.0;
};
datablock ProjectileData( BulletProjectile )
{
projectileShapeName = "";
directDamage = 5;
radiusDamage = 0;
damageRadius = 0.5;
areaImpulse = 0.5;
impactForce = 1;
explosion = BulletDirtExplosion;
decal = BulletHoleDecal;
muzzleVelocity = 120;
velInheritFactor = 1;
armingDelay = 0;
lifetime = 992;
fadeDelay = 1472;
bounceElasticity = 0;
bounceFriction = 0;
isBallistic = false;
gravityMod = 1;
};
function BulletProjectile::onCollision(%this,%obj,%col,%fade,%pos,%normal)
{
// Apply impact force from the projectile.
// Apply damage to the object all shape base objects
if ( %col.getType() & $TypeMasks::GameBaseObjectType )
%col.damage(%obj,%pos,%this.directDamage,"BulletProjectile");
}
//-----------------------------------------------------------------------------
// Ammo Item
//-----------------------------------------------------------------------------
datablock ItemData(LurkerClip)
{
// Mission editor category
category = "AmmoClip";
// Add the Ammo namespace as a parent. The ammo namespace provides
// common ammo related functions and hooks into the inventory system.
className = "AmmoClip";
// Basic Item properties
shapeFile = "art/shapes/weapons/Lurker/TP_Lurker.DAE";
mass = 1;
elasticity = 0.2;
friction = 0.6;
// Dynamic properties defined by the scripts
pickUpName = "Lurker clip";
count = 1;
maxInventory = 10;
};
datablock ItemData(LurkerAmmo)
{
// Mission editor category
category = "Ammo";
// Add the Ammo namespace as a parent. The ammo namespace provides
// common ammo related functions and hooks into the inventory system.
className = "Ammo";
// Basic Item properties
shapeFile = "art/shapes/weapons/Lurker/TP_Lurker.DAE";
mass = 1;
elasticity = 0.2;
friction = 0.6;
// Dynamic properties defined by the scripts
pickUpName = "Lurker ammo";
maxInventory = 30;
clip = LurkerClip;
};
//--------------------------------------------------------------------------
// Weapon Item. This is the item that exists in the world, i.e. when it's
// been dropped, thrown or is acting as re-spawnable item. When the weapon
// is mounted onto a shape, the LurkerWeaponImage is used.
//-----------------------------------------------------------------------------
datablock ItemData(Lurker)
{
// Mission editor category
category = "Weapon";
// Hook into Item Weapon class hierarchy. The weapon namespace
// provides common weapon handling functions in addition to hooks
// into the inventory system.
className = "Weapon";
// Basic Item properties
shapeFile = "art/shapes/weapons/Lurker/TP_Lurker.DAE";
mass = 1;
elasticity = 0.2;
friction = 0.6;
emap = true;
// Dynamic properties defined by the scripts
PreviewImage = 'lurker.png';
pickUpName = "Lurker rifle";
description = "Lurker";
image = LurkerWeaponImage;
reticle = "crossHair";
};
datablock ShapeBaseImageData(LurkerWeaponImage)
{
// Basic Item properties
shapeFile = "art/shapes/weapons/Lurker/TP_Lurker.DAE";
shapeFileFP = "art/shapes/weapons/Lurker/FP_Lurker.DAE";
emap = true;
imageAnimPrefix = "Rifle";
imageAnimPrefixFP = "Rifle";
// Specify mount point & offset for 3rd person, and eye offset
// for first person rendering.
mountPoint = 0;
firstPerson = true;
useEyeNode = true;
animateOnServer = true;
// When firing from a point offset from the eye, muzzle correction
// will adjust the muzzle vector to point to the eye LOS point.
// Since this weapon doesn't actually fire from the muzzle point,
// we need to turn this off.
correctMuzzleVector = true;
// Add the WeaponImage namespace as a parent, WeaponImage namespace
// provides some hooks into the inventory system.
class = "WeaponImage";
className = "WeaponImage";
// Projectiles and Ammo.
item = Lurker;
ammo = LurkerAmmo;
clip = LurkerClip;
projectile = BulletProjectile;
projectileType = Projectile;
projectileSpread = "0.005";
altProjectile = GrenadeLauncherProjectile;
altProjectileSpread = "0.02";
casing = BulletShell;
shellExitDir = "1.0 0.3 1.0";
shellExitOffset = "0.15 -0.56 -0.1";
shellExitVariance = 15.0;
shellVelocity = 3.0;
// Weapon lights up while firing
lightType = "WeaponFireLight";
lightColor = "0.992126 0.968504 0.708661 1";
lightRadius = "4";
lightDuration = "100";
lightBrightness = 2;
// Shake camera while firing.
shakeCamera = false;
camShakeFreq = "0 0 0";
camShakeAmp = "0 0 0";
// Images have a state system which controls how the animations
// are run, which sounds are played, script callbacks, etc. This
// state system is downloaded to the client so that clients can
// predict state changes and animate accordingly. The following
// system supports basic ready->fire->reload transitions as
// well as a no-ammo->dryfire idle state.
useRemainderDT = true;
// Initial start up state
stateName[0] = "Preactivate";
stateTransitionOnLoaded[0] = "Activate";
stateTransitionOnNoAmmo[0] = "NoAmmo";
// Activating the gun. Called when the weapon is first
// mounted and there is ammo.
stateName[1] = "Activate";
stateTransitionGeneric0In[1] = "SprintEnter";
stateTransitionOnTimeout[1] = "Ready";
stateTimeoutValue[1] = 0.5;
stateSequence[1] = "switch_in";
stateSound[1] = LurkerSwitchinSound;
// Ready to fire, just waiting for the trigger
stateName[2] = "Ready";
stateTransitionGeneric0In[2] = "SprintEnter";
stateTransitionOnMotion[2] = "ReadyMotion";
stateTransitionOnTimeout[2] = "ReadyFidget";
stateTimeoutValue[2] = 10;
stateWaitForTimeout[2] = false;
stateScaleAnimation[2] = false;
stateScaleAnimationFP[2] = false;
stateTransitionOnNoAmmo[2] = "NoAmmo";
stateTransitionOnTriggerDown[2] = "Fire";
stateSequence[2] = "idle";
// Same as Ready state but plays a fidget sequence
stateName[3] = "ReadyFidget";
stateTransitionGeneric0In[3] = "SprintEnter";
stateTransitionOnMotion[3] = "ReadyMotion";
stateTransitionOnTimeout[3] = "Ready";
stateTimeoutValue[3] = 6;
stateWaitForTimeout[3] = false;
stateTransitionOnNoAmmo[3] = "NoAmmo";
stateTransitionOnTriggerDown[3] = "Fire";
stateSequence[3] = "idle_fidget1";
stateSound[3] = LurkerIdleSound;
// Ready to fire with player moving
stateName[4] = "ReadyMotion";
stateTransitionGeneric0In[4] = "SprintEnter";
stateTransitionOnNoMotion[4] = "Ready";
stateWaitForTimeout[4] = false;
stateScaleAnimation[4] = false;
stateScaleAnimationFP[4] = false;
stateSequenceTransitionIn[4] = true;
stateSequenceTransitionOut[4] = true;
stateTransitionOnNoAmmo[4] = "NoAmmo";
stateTransitionOnTriggerDown[4] = "Fire";
stateSequence[4] = "run";
// Fire the weapon. Calls the fire script which does
// the actual work.
stateName[5] = "Fire";
stateTransitionGeneric0In[5] = "SprintEnter";
stateTransitionOnTimeout[5] = "NewRound";
stateTimeoutValue[5] = 0.15;
stateFire[5] = true;
stateRecoil[5] = "";
stateAllowImageChange[5] = false;
stateSequence[5] = "fire";
stateScaleAnimation[5] = false;
stateSequenceNeverTransition[5] = true;
stateSequenceRandomFlash[5] = true; // use muzzle flash sequence
stateScript[5] = "onFire";
stateSound[5] = LurkerFireSoundList;
stateEmitter[5] = GunFireSmokeEmitter;
stateEmitterTime[5] = 0.025;
// Put another round into the chamber if one is available
stateName[6] = "NewRound";
stateTransitionGeneric0In[6] = "SprintEnter";
stateTransitionOnNoAmmo[6] = "NoAmmo";
stateTransitionOnTimeout[6] = "Ready";
stateWaitForTimeout[6] = "0";
stateTimeoutValue[6] = 0.05;
stateAllowImageChange[6] = false;
stateEjectShell[6] = true;
// No ammo in the weapon, just idle until something
// shows up. Play the dry fire sound if the trigger is
// pulled.
stateName[7] = "NoAmmo";
stateTransitionGeneric0In[7] = "SprintEnter";
stateTransitionOnMotion[7] = "NoAmmoMotion";
stateTransitionOnAmmo[7] = "ReloadClip";
stateTimeoutValue[7] = 0.1; // Slight pause to allow script to run when trigger is still held down from Fire state
stateScript[7] = "onClipEmpty";
stateSequence[7] = "idle";
stateScaleAnimation[7] = false;
stateScaleAnimationFP[7] = false;
stateTransitionOnTriggerDown[7] = "DryFire";
stateName[8] = "NoAmmoMotion";
stateTransitionGeneric0In[8] = "SprintEnter";
stateTransitionOnNoMotion[8] = "NoAmmo";
stateWaitForTimeout[8] = false;
stateScaleAnimation[8] = false;
stateScaleAnimationFP[8] = false;
stateSequenceTransitionIn[8] = true;
stateSequenceTransitionOut[8] = true;
stateTransitionOnTriggerDown[8] = "DryFire";
stateTransitionOnAmmo[8] = "ReloadClip";
stateSequence[8] = "run";
// No ammo dry fire
stateName[9] = "DryFire";
stateTransitionGeneric0In[9] = "SprintEnter";
stateTransitionOnAmmo[9] = "ReloadClip";
stateWaitForTimeout[9] = "0";
stateTimeoutValue[9] = 0.7;
stateTransitionOnTimeout[9] = "NoAmmo";
stateScript[9] = "onDryFire";
stateSound[9] = MachineGunDryFire;
// Play the reload clip animation
stateName[10] = "ReloadClip";
stateTransitionGeneric0In[10] = "SprintEnter";
stateTransitionOnTimeout[10] = "Ready";
stateWaitForTimeout[10] = true;
stateTimeoutValue[10] = 3.0;
stateReload[10] = true;
stateSequence[10] = "reload";
stateShapeSequence[10] = "Reload";
stateScaleShapeSequence[10] = true;
stateSound[10] = LurkerReloadSound;
// Start Sprinting
stateName[11] = "SprintEnter";
stateTransitionGeneric0Out[11] = "SprintExit";
stateTransitionOnTimeout[11] = "Sprinting";
stateWaitForTimeout[11] = false;
stateTimeoutValue[11] = 0.5;
stateWaitForTimeout[11] = false;
stateScaleAnimation[11] = false;
stateScaleAnimationFP[11] = false;
stateSequenceTransitionIn[11] = true;
stateSequenceTransitionOut[11] = true;
stateAllowImageChange[11] = false;
stateSequence[11] = "sprint";
// Sprinting
stateName[12] = "Sprinting";
stateTransitionGeneric0Out[12] = "SprintExit";
stateWaitForTimeout[12] = false;
stateScaleAnimation[12] = false;
stateScaleAnimationFP[12] = false;
stateSequenceTransitionIn[12] = true;
stateSequenceTransitionOut[12] = true;
stateAllowImageChange[12] = false;
stateSequence[12] = "sprint";
// Stop Sprinting
stateName[13] = "SprintExit";
stateTransitionGeneric0In[13] = "SprintEnter";
stateTransitionOnTimeout[13] = "Ready";
stateWaitForTimeout[13] = false;
stateTimeoutValue[13] = 0.5;
stateSequenceTransitionIn[13] = true;
stateSequenceTransitionOut[13] = true;
stateAllowImageChange[13] = false;
stateSequence[13] = "sprint";
};
//--------------------------------------------------------------------------
// Lurker Grenade Launcher
//--------------------------------------------------------------------------
datablock ItemData(LurkerGrenadeAmmo)
{
// Mission editor category
category = "Ammo";
// Add the Ammo namespace as a parent. The ammo namespace provides
// common ammo related functions and hooks into the inventory system.
className = "Ammo";
// Basic Item properties
shapeFile = "art/shapes/weapons/Lurker/TP_Lurker.DAE";
mass = 1;
elasticity = 0.2;
friction = 0.6;
// Dynamic properties defined by the scripts
pickUpName = "Lurker grenade ammo";
maxInventory = 20;
};
datablock ItemData(LurkerGrenadeLauncher)
{
// Mission editor category
category = "Weapon";
// Hook into Item Weapon class hierarchy. The weapon namespace
// provides common weapon handling functions in addition to hooks
// into the inventory system.
className = "Weapon";
// Basic Item properties
shapeFile = "art/shapes/weapons/Lurker/TP_Lurker.DAE";
mass = 1;
elasticity = 0.2;
friction = 0.6;
emap = true;
// Dynamic properties defined by the scripts
PreviewImage = 'lurker.png';
pickUpName = "a Lurker grenade launcher";
description = "Lurker Grenade Launcher";
image = LurkerGrenadeLauncherImage;
reticle = "crossHair";
};
datablock ShapeBaseImageData(LurkerGrenadeLauncherImage)
{
// Basic Item properties
shapeFile = "art/shapes/weapons/Lurker/TP_Lurker.DAE";
shapeFileFP = "art/shapes/weapons/Lurker/FP_Lurker.DAE";
emap = true;
imageAnimPrefix = "Rifle";
imageAnimPrefixFP = "Rifle";
// Specify mount point & offset for 3rd person, and eye offset
// for first person rendering.
mountPoint = 0;
firstPerson = true;
useEyeNode = true;
animateOnServer = true;
// When firing from a point offset from the eye, muzzle correction
// will adjust the muzzle vector to point to the eye LOS point.
// Since this weapon doesn't actually fire from the muzzle point,
// we need to turn this off.
correctMuzzleVector = true;
// Add the WeaponImage namespace as a parent, WeaponImage namespace
// provides some hooks into the inventory system.
class = "WeaponImage";
className = "WeaponImage";
// Projectiles and Ammo.
item = LurkerGrenadeLauncher;
ammo = LurkerGrenadeAmmo;
projectile = GrenadeLauncherProjectile;
projectileType = Projectile;
projectileSpread = "0.02";
// Weapon lights up while firing
lightType = "WeaponFireLight";
lightColor = "0.992126 0.968504 0.708661 1";
lightRadius = "4";
lightDuration = "100";
lightBrightness = 2;
// Shake camera while firing.
shakeCamera = false;
camShakeFreq = "0 0 0";
camShakeAmp = "0 0 0";
// Images have a state system which controls how the animations
// are run, which sounds are played, script callbacks, etc. This
// state system is downloaded to the client so that clients can
// predict state changes and animate accordingly. The following
// system supports basic ready->fire->reload transitions as
// well as a no-ammo->dryfire idle state.
useRemainderDT = true;
// Initial start up state
stateName[0] = "Preactivate";
stateTransitionOnLoaded[0] = "Activate";
stateTransitionOnNoAmmo[0] = "NoAmmo";
// Activating the gun. Called when the weapon is first
// mounted and there is ammo.
stateName[1] = "Activate";
stateTransitionGeneric0In[1] = "SprintEnter";
stateTransitionOnTimeout[1] = "Ready";
stateTimeoutValue[1] = 0.5;
stateSequence[1] = "switch_in";
stateSound[1] = LurkerSwitchinSound;
// Ready to fire, just waiting for the trigger
stateName[2] = "Ready";
stateTransitionGeneric0In[2] = "SprintEnter";
stateTransitionOnMotion[2] = "ReadyMotion";
stateTransitionOnTimeout[2] = "ReadyFidget";
stateTimeoutValue[2] = 10;
stateWaitForTimeout[2] = false;
stateScaleAnimation[2] = false;
stateScaleAnimationFP[2] = false;
stateTransitionOnNoAmmo[2] = "NoAmmo";
stateTransitionOnTriggerDown[2] = "Fire";
stateSequence[2] = "idle";
// Same as Ready state but plays a fidget sequence
stateName[3] = "ReadyFidget";
stateTransitionGeneric0In[3] = "SprintEnter";
stateTransitionOnMotion[3] = "ReadyMotion";
stateTransitionOnTimeout[3] = "Ready";
stateTimeoutValue[3] = 6;
stateWaitForTimeout[3] = false;
stateTransitionOnNoAmmo[3] = "NoAmmo";
stateTransitionOnTriggerDown[3] = "Fire";
stateSequence[3] = "idle_fidget1";
stateSound[3] = LurkerIdleSound;
// Ready to fire with player moving
stateName[4] = "ReadyMotion";
stateTransitionGeneric0In[4] = "SprintEnter";
stateTransitionOnNoMotion[4] = "Ready";
stateWaitForTimeout[4] = false;
stateScaleAnimation[4] = false;
stateScaleAnimationFP[4] = false;
stateSequenceTransitionIn[4] = true;
stateSequenceTransitionOut[4] = true;
stateTransitionOnNoAmmo[4] = "NoAmmo";
stateTransitionOnTriggerDown[4] = "Fire";
stateSequence[4] = "run";
// Fire the weapon. Calls the fire script which does
// the actual work.
stateName[5] = "Fire";
stateTransitionGeneric0In[5] = "SprintEnter";
stateTransitionOnTimeout[5] = "NewRound";
stateTimeoutValue[5] = 1.2;
stateFire[5] = true;
stateRecoil[5] = "";
stateAllowImageChange[5] = false;
stateSequence[5] = "fire_alt";
stateScaleAnimation[5] = true;
stateSequenceNeverTransition[5] = true;
stateSequenceRandomFlash[5] = true; // use muzzle flash sequence
stateScript[5] = "onFire";
stateSound[5] = LurkerGrenadeFireSound;
stateEmitter[5] = GunFireSmokeEmitter;
stateEmitterTime[5] = 0.025;
stateEjectShell[5] = true;
// Put another round into the chamber
stateName[6] = "NewRound";
stateTransitionGeneric0In[6] = "SprintEnter";
stateTransitionOnNoAmmo[6] = "NoAmmo";
stateTransitionOnTimeout[6] = "Ready";
stateWaitForTimeout[6] = "0";
stateTimeoutValue[6] = 0.05;
stateAllowImageChange[6] = false;
// No ammo in the weapon, just idle until something
// shows up. Play the dry fire sound if the trigger is
// pulled.
stateName[7] = "NoAmmo";
stateTransitionGeneric0In[7] = "SprintEnter";
stateTransitionOnMotion[7] = "NoAmmoReadyMotion";
stateTransitionOnAmmo[7] = "ReloadClip";
stateTimeoutValue[7] = 0.1; // Slight pause to allow script to run when trigger is still held down from Fire state
stateScript[7] = "onClipEmpty";
stateSequence[7] = "idle";
stateScaleAnimation[7] = false;
stateScaleAnimationFP[7] = false;
stateTransitionOnTriggerDown[7] = "DryFire";
stateName[8] = "NoAmmoReadyMotion";
stateTransitionGeneric0In[8] = "SprintEnter";
stateTransitionOnNoMotion[8] = "NoAmmo";
stateWaitForTimeout[8] = false;
stateScaleAnimation[8] = false;
stateScaleAnimationFP[8] = false;
stateSequenceTransitionIn[8] = true;
stateSequenceTransitionOut[8] = true;
stateTransitionOnAmmo[8] = "ReloadClip";
stateTransitionOnTriggerDown[8] = "DryFire";
stateSequence[8] = "run";
// No ammo dry fire
stateName[9] = "DryFire";
stateTransitionGeneric0In[9] = "SprintEnter";
stateTimeoutValue[9] = 1.0;
stateTransitionOnTimeout[9] = "NoAmmo";
stateScript[9] = "onDryFire";
// Play the reload clip animation
stateName[10] = "ReloadClip";
stateTransitionGeneric0In[10] = "SprintEnter";
stateTransitionOnTimeout[10] = "Ready";
stateWaitForTimeout[10] = true;
stateTimeoutValue[10] = 3.0;
stateReload[10] = true;
stateSequence[10] = "reload";
stateShapeSequence[10] = "Reload";
stateScaleShapeSequence[10] = true;
// Start Sprinting
stateName[11] = "SprintEnter";
stateTransitionGeneric0Out[11] = "SprintExit";
stateTransitionOnTimeout[11] = "Sprinting";
stateWaitForTimeout[11] = false;
stateTimeoutValue[11] = 0.5;
stateWaitForTimeout[11] = false;
stateScaleAnimation[11] = false;
stateScaleAnimationFP[11] = false;
stateSequenceTransitionIn[11] = true;
stateSequenceTransitionOut[11] = true;
stateAllowImageChange[11] = false;
stateSequence[11] = "sprint";
// Sprinting
stateName[12] = "Sprinting";
stateTransitionGeneric0Out[12] = "SprintExit";
stateWaitForTimeout[12] = false;
stateScaleAnimation[12] = false;
stateScaleAnimationFP[12] = false;
stateSequenceTransitionIn[12] = true;
stateSequenceTransitionOut[12] = true;
stateAllowImageChange[12] = false;
stateSequence[12] = "sprint";
// Stop Sprinting
stateName[13] = "SprintExit";
stateTransitionGeneric0In[13] = "SprintEnter";
stateTransitionOnTimeout[13] = "Ready";
stateWaitForTimeout[13] = false;
stateTimeoutValue[13] = 0.5;
stateSequenceTransitionIn[13] = true;
stateSequenceTransitionOut[13] = true;
stateAllowImageChange[13] = false;
stateSequence[13] = "sprint";
};
| |
// 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
{
public static partial class Console
{
public static System.ConsoleColor BackgroundColor { get { return default(System.ConsoleColor); } set { } }
public static void Beep() { }
public static int BufferHeight { get { return default(int); } set { } }
public static int BufferWidth { get { return default(int); } set { } }
public static event System.ConsoleCancelEventHandler CancelKeyPress { add { } remove { } }
public static void Clear() { }
public static int CursorLeft { get { return default(int); } set { } }
public static int CursorTop { get { return default(int); } set { } }
public static bool CursorVisible { get { return default(bool); } set { } }
public static System.IO.TextWriter Error { get { return default(System.IO.TextWriter); } }
public static System.ConsoleColor ForegroundColor { get { return default(System.ConsoleColor); } set { } }
public static bool IsErrorRedirected { get { return false; } }
public static bool IsInputRedirected { get { return false; } }
public static bool IsOutputRedirected { get { return false; } }
public static System.IO.TextReader In { get { return default(System.IO.TextReader); } }
public static bool KeyAvailable { get { return default(bool); }}
public static int LargestWindowWidth { get { return default(int); } }
public static int LargestWindowHeight { get { return default(int); }}
public static System.IO.Stream OpenStandardError() { return default(System.IO.Stream); }
public static System.IO.Stream OpenStandardInput() { return default(System.IO.Stream); }
public static System.IO.Stream OpenStandardOutput() { return default(System.IO.Stream); }
public static System.IO.TextWriter Out { get { return default(System.IO.TextWriter); } }
public static int Read() { return default(int); }
public static ConsoleKeyInfo ReadKey() { return default(ConsoleKeyInfo); }
public static ConsoleKeyInfo ReadKey(bool intercept) { return default(ConsoleKeyInfo); }
public static string ReadLine() { return default(string); }
public static void ResetColor() { }
public static void SetBufferSize(int width, int height) { }
public static void SetCursorPosition(int left, int top) { }
public static void SetError(System.IO.TextWriter newError) { }
public static void SetIn(System.IO.TextReader newIn) { }
public static void SetOut(System.IO.TextWriter newOut) { }
public static string Title { get { return default(string); } set { } }
public static int WindowHeight { get { return default(int); } set { } }
public static int WindowWidth { get { return default(int); } set { } }
public static int WindowLeft { get { return default(int); } set { } }
public static int WindowTop { get { return default(int); } set { } }
public static void Write(bool value) { }
public static void Write(char value) { }
public static void Write(char[] buffer) { }
public static void Write(char[] buffer, int index, int count) { }
public static void Write(decimal value) { }
public static void Write(double value) { }
public static void Write(int value) { }
public static void Write(long value) { }
public static void Write(object value) { }
public static void Write(float value) { }
public static void Write(string value) { }
public static void Write(string format, object arg0) { }
public static void Write(string format, object arg0, object arg1) { }
public static void Write(string format, object arg0, object arg1, object arg2) { }
public static void Write(string format, params object[] arg) { }
[System.CLSCompliantAttribute(false)]
public static void Write(uint value) { }
[System.CLSCompliantAttribute(false)]
public static void Write(ulong value) { }
public static void WriteLine() { }
public static void WriteLine(bool value) { }
public static void WriteLine(char value) { }
public static void WriteLine(char[] buffer) { }
public static void WriteLine(char[] buffer, int index, int count) { }
public static void WriteLine(decimal value) { }
public static void WriteLine(double value) { }
public static void WriteLine(int value) { }
public static void WriteLine(long value) { }
public static void WriteLine(object value) { }
public static void WriteLine(float value) { }
public static void WriteLine(string value) { }
public static void WriteLine(string format, object arg0) { }
public static void WriteLine(string format, object arg0, object arg1) { }
public static void WriteLine(string format, object arg0, object arg1, object arg2) { }
public static void WriteLine(string format, params object[] arg) { }
[System.CLSCompliantAttribute(false)]
public static void WriteLine(uint value) { }
[System.CLSCompliantAttribute(false)]
public static void WriteLine(ulong value) { }
}
public sealed partial class ConsoleCancelEventArgs : System.EventArgs
{
internal ConsoleCancelEventArgs() { }
public bool Cancel { get { return default(bool); } set { } }
public System.ConsoleSpecialKey SpecialKey { get { return default(System.ConsoleSpecialKey); } }
}
public delegate void ConsoleCancelEventHandler(object sender, System.ConsoleCancelEventArgs e);
public enum ConsoleColor
{
Black = 0,
Blue = 9,
Cyan = 11,
DarkBlue = 1,
DarkCyan = 3,
DarkGray = 8,
DarkGreen = 2,
DarkMagenta = 5,
DarkRed = 4,
DarkYellow = 6,
Gray = 7,
Green = 10,
Magenta = 13,
Red = 12,
White = 15,
Yellow = 14,
}
public partial struct ConsoleKeyInfo
{
public ConsoleKeyInfo(char keyChar, ConsoleKey key, bool shift, bool alt, bool control) { }
public char KeyChar { get { return default(char); } }
public ConsoleKey Key { get { return default(ConsoleKey); } }
public ConsoleModifiers Modifiers { get { return default(ConsoleModifiers); ; } }
}
public enum ConsoleKey
{
Backspace = 0x8,
Tab = 0x9,
Clear = 0xC,
Enter = 0xD,
Pause = 0x13,
Escape = 0x1B,
Spacebar = 0x20,
PageUp = 0x21,
PageDown = 0x22,
End = 0x23,
Home = 0x24,
LeftArrow = 0x25,
UpArrow = 0x26,
RightArrow = 0x27,
DownArrow = 0x28,
Select = 0x29,
Print = 0x2A,
Execute = 0x2B,
PrintScreen = 0x2C,
Insert = 0x2D,
Delete = 0x2E,
Help = 0x2F,
D0 = 0x30, // 0 through 9
D1 = 0x31,
D2 = 0x32,
D3 = 0x33,
D4 = 0x34,
D5 = 0x35,
D6 = 0x36,
D7 = 0x37,
D8 = 0x38,
D9 = 0x39,
A = 0x41,
B = 0x42,
C = 0x43,
D = 0x44,
E = 0x45,
F = 0x46,
G = 0x47,
H = 0x48,
I = 0x49,
J = 0x4A,
K = 0x4B,
L = 0x4C,
M = 0x4D,
N = 0x4E,
O = 0x4F,
P = 0x50,
Q = 0x51,
R = 0x52,
S = 0x53,
T = 0x54,
U = 0x55,
V = 0x56,
W = 0x57,
X = 0x58,
Y = 0x59,
Z = 0x5A,
Sleep = 0x5F,
NumPad0 = 0x60,
NumPad1 = 0x61,
NumPad2 = 0x62,
NumPad3 = 0x63,
NumPad4 = 0x64,
NumPad5 = 0x65,
NumPad6 = 0x66,
NumPad7 = 0x67,
NumPad8 = 0x68,
NumPad9 = 0x69,
Multiply = 0x6A,
Add = 0x6B,
Separator = 0x6C,
Subtract = 0x6D,
Decimal = 0x6E,
Divide = 0x6F,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7A,
F12 = 0x7B,
F13 = 0x7C,
F14 = 0x7D,
F15 = 0x7E,
F16 = 0x7F,
F17 = 0x80,
F18 = 0x81,
F19 = 0x82,
F20 = 0x83,
F21 = 0x84,
F22 = 0x85,
F23 = 0x86,
F24 = 0x87,
Oem1 = 0xBA,
OemPlus = 0xBB,
OemComma = 0xBC,
OemMinus = 0xBD,
OemPeriod = 0xBE,
Oem2 = 0xBF,
Oem3 = 0xC0,
Oem4 = 0xDB,
Oem5 = 0xDC,
Oem6 = 0xDD,
Oem7 = 0xDE,
Oem8 = 0xDF,
OemClear = 0xFE,
}
[Flags]
public enum ConsoleModifiers
{
Alt = 1,
Shift = 2,
Control = 4
}
public enum ConsoleSpecialKey
{
ControlBreak = 1,
ControlC = 0,
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Internal.IL;
using Internal.JitInterface;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysisFramework;
namespace ILCompiler
{
public class CompilationOptions
{
public IReadOnlyDictionary<string, string> InputFilePaths;
public IReadOnlyDictionary<string, string> ReferenceFilePaths;
public string OutputFilePath;
public string SystemModuleName;
public TargetOS TargetOS;
public TargetArchitecture TargetArchitecture;
public bool MultiFile;
public bool IsCppCodeGen;
public bool NoLineNumbers;
public string DgmlLog;
public bool FullLog;
public bool Verbose;
}
public partial class Compilation : ICompilationRootProvider
{
private readonly CompilerTypeSystemContext _typeSystemContext;
private readonly CompilationOptions _options;
private readonly TypeInitialization _typeInitManager;
private NodeFactory _nodeFactory;
private DependencyAnalyzerBase<NodeFactory> _dependencyGraph;
private NameMangler _nameMangler = null;
private ILCompiler.CppCodeGen.CppWriter _cppWriter = null;
private CompilationModuleGroup _compilationModuleGroup;
public Compilation(CompilationOptions options)
{
_options = options;
_typeSystemContext = new CompilerTypeSystemContext(new TargetDetails(options.TargetArchitecture, options.TargetOS));
_typeSystemContext.InputFilePaths = options.InputFilePaths;
_typeSystemContext.ReferenceFilePaths = options.ReferenceFilePaths;
_typeSystemContext.SetSystemModule(_typeSystemContext.GetModuleForSimpleName(options.SystemModuleName));
_nameMangler = new NameMangler(this);
_typeInitManager = new TypeInitialization();
if (options.MultiFile)
{
_compilationModuleGroup = new MultiFileCompilationModuleGroup(_typeSystemContext, this);
}
else
{
_compilationModuleGroup = new SingleFileCompilationModuleGroup(_typeSystemContext, this);
}
}
public CompilerTypeSystemContext TypeSystemContext
{
get
{
return _typeSystemContext;
}
}
public NameMangler NameMangler
{
get
{
return _nameMangler;
}
}
public NodeFactory NodeFactory
{
get
{
return _nodeFactory;
}
}
public TextWriter Log
{
get;
set;
}
internal bool IsCppCodeGen
{
get
{
return _options.IsCppCodeGen;
}
}
internal CompilationOptions Options
{
get
{
return _options;
}
}
private ILProvider _methodILCache = new ILProvider();
public MethodIL GetMethodIL(MethodDesc method)
{
// Flush the cache when it grows too big
if (_methodILCache.Count > 1000)
_methodILCache= new ILProvider();
return _methodILCache.GetMethodIL(method);
}
private CorInfoImpl _corInfo;
public void CompileSingleFile()
{
NodeFactory.NameMangler = NameMangler;
_nodeFactory = new NodeFactory(_typeSystemContext, _typeInitManager, _compilationModuleGroup, _options.IsCppCodeGen);
// Choose which dependency graph implementation to use based on the amount of logging requested.
if (_options.DgmlLog == null)
{
// No log uses the NoLogStrategy
_dependencyGraph = new DependencyAnalyzer<NoLogStrategy<NodeFactory>, NodeFactory>(_nodeFactory, null);
}
else
{
if (_options.FullLog)
{
// Full log uses the full log strategy
_dependencyGraph = new DependencyAnalyzer<FullGraphLogStrategy<NodeFactory>, NodeFactory>(_nodeFactory, null);
}
else
{
// Otherwise, use the first mark strategy
_dependencyGraph = new DependencyAnalyzer<FirstMarkLogStrategy<NodeFactory>, NodeFactory>(_nodeFactory, null);
}
}
_nodeFactory.AttachToDependencyGraph(_dependencyGraph);
_compilationModuleGroup.AddWellKnownTypes();
_compilationModuleGroup.AddCompilationRoots();
if (!_options.IsCppCodeGen && !_options.MultiFile)
{
// TODO: build a general purpose way to hook up pieces that would be part of the core library
// if factoring of the core library respected how things are, versus how they would be in
// a magic world (future customers of this mechanism will be interop and serialization).
var refExec = _typeSystemContext.GetModuleForSimpleName("System.Private.Reflection.Execution");
var exec = refExec.GetKnownType("Internal.Reflection.Execution", "ReflectionExecution");
AddCompilationRoot(exec.GetStaticConstructor(), "Reflection execution");
}
if (_options.IsCppCodeGen)
{
_cppWriter = new CppCodeGen.CppWriter(this);
_dependencyGraph.ComputeDependencyRoutine += CppCodeGenComputeDependencyNodeDependencies;
var nodes = _dependencyGraph.MarkedNodeList;
_cppWriter.OutputCode(nodes, _compilationModuleGroup.StartupCodeMain);
}
else
{
_corInfo = new CorInfoImpl(this);
_dependencyGraph.ComputeDependencyRoutine += ComputeDependencyNodeDependencies;
var nodes = _dependencyGraph.MarkedNodeList;
ObjectWriter.EmitObject(_options.OutputFilePath, nodes, _nodeFactory);
}
if (_options.DgmlLog != null)
{
using (FileStream dgmlOutput = new FileStream(_options.DgmlLog, FileMode.Create))
{
DgmlWriter.WriteDependencyGraphToStream(dgmlOutput, _dependencyGraph);
dgmlOutput.Flush();
}
}
}
#region ICompilationRootProvider implementation
public void AddCompilationRoot(MethodDesc method, string reason, string exportName = null)
{
var methodEntryPoint = _nodeFactory.MethodEntrypoint(method);
_dependencyGraph.AddRoot(methodEntryPoint, reason);
if (exportName != null)
_nodeFactory.NodeAliases.Add(methodEntryPoint, exportName);
}
public void AddCompilationRoot(TypeDesc type, string reason)
{
_dependencyGraph.AddRoot(_nodeFactory.ConstructedTypeSymbol(type), reason);
}
#endregion
private void ComputeDependencyNodeDependencies(List<DependencyNodeCore<NodeFactory>> obj)
{
foreach (MethodCodeNode methodCodeNodeNeedingCode in obj)
{
MethodDesc method = methodCodeNodeNeedingCode.Method;
string methodName = method.ToString();
Log.WriteLine("Compiling " + methodName);
var methodIL = GetMethodIL(method);
if (methodIL == null)
return;
try
{
_corInfo.CompileMethod(methodCodeNodeNeedingCode);
}
catch (Exception e)
{
Log.WriteLine("*** " + method + ": " + e.Message);
// Call the __not_yet_implemented method
DependencyAnalysis.X64.X64Emitter emit = new DependencyAnalysis.X64.X64Emitter(_nodeFactory);
emit.Builder.RequireAlignment(_nodeFactory.Target.MinimumFunctionAlignment);
emit.Builder.DefinedSymbols.Add(methodCodeNodeNeedingCode);
emit.EmitLEAQ(emit.TargetRegister.Arg0, _nodeFactory.StringIndirection(method.ToString()));
DependencyAnalysis.X64.AddrMode loadFromArg0 =
new DependencyAnalysis.X64.AddrMode(emit.TargetRegister.Arg0, null, 0, 0, DependencyAnalysis.X64.AddrModeSize.Int64);
emit.EmitMOV(emit.TargetRegister.Arg0, ref loadFromArg0);
emit.EmitMOV(emit.TargetRegister.Arg0, ref loadFromArg0);
emit.EmitLEAQ(emit.TargetRegister.Arg1, _nodeFactory.StringIndirection(e.Message));
DependencyAnalysis.X64.AddrMode loadFromArg1 =
new DependencyAnalysis.X64.AddrMode(emit.TargetRegister.Arg1, null, 0, 0, DependencyAnalysis.X64.AddrModeSize.Int64);
emit.EmitMOV(emit.TargetRegister.Arg1, ref loadFromArg1);
emit.EmitMOV(emit.TargetRegister.Arg1, ref loadFromArg1);
emit.EmitJMP(_nodeFactory.ExternSymbol("__not_yet_implemented"));
methodCodeNodeNeedingCode.SetCode(emit.Builder.ToObjectData());
continue;
}
}
}
private void CppCodeGenComputeDependencyNodeDependencies(List<DependencyNodeCore<NodeFactory>> obj)
{
foreach (CppMethodCodeNode methodCodeNodeNeedingCode in obj)
{
_cppWriter.CompileMethod(methodCodeNodeNeedingCode);
}
}
public DelegateCreationInfo GetDelegateCtor(TypeDesc delegateType, MethodDesc target)
{
return DelegateCreationInfo.Create(delegateType, target, _nodeFactory);
}
/// <summary>
/// Gets an object representing the static data for RVA mapped fields from the PE image.
/// </summary>
public ObjectNode GetFieldRvaData(FieldDesc field)
{
if (field.GetType() == typeof(Internal.IL.Stubs.PInvokeLazyFixupField))
{
var pInvokeFixup = (Internal.IL.Stubs.PInvokeLazyFixupField)field;
PInvokeMetadata metadata = pInvokeFixup.PInvokeMetadata;
return _nodeFactory.PInvokeMethodFixup(metadata.Module, metadata.Name);
}
else
{
return _nodeFactory.ReadOnlyDataBlob(NameMangler.GetMangledFieldName(field),
((EcmaField)field).GetFieldRvaData(), _typeSystemContext.Target.PointerSize);
}
}
public bool HasLazyStaticConstructor(TypeDesc type)
{
return _typeInitManager.HasLazyStaticConstructor(type);
}
public MethodDebugInformation GetDebugInfo(MethodIL methodIL)
{
// This method looks odd right now, but it's an extensibility point that lets us generate
// fake debugging information for things that don't have physical symbols.
return methodIL.GetDebugInfo();
}
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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 Alphaleonis.Win32.Filesystem;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Directory = Alphaleonis.Win32.Filesystem.Directory;
using File = Alphaleonis.Win32.Filesystem.File;
using Path = Alphaleonis.Win32.Filesystem.Path;
namespace AlphaFS.UnitTest
{
/// <summary>This is a test class for Shell32 and is intended to contain all Shell32 Unit Tests.</summary>
[TestClass]
public class AlphaFS_Shell32Test
{
#region DumpGetAssociation
private void DumpGetAssociation(bool isLocal)
{
Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network);
string path = isLocal ? UnitTestConstants.SysRoot : Path.LocalToUnc(UnitTestConstants.SysRoot);
Console.WriteLine("\nInput Directory Path: [{0}]\n", path);
int cnt = 0;
foreach (string file in Directory.EnumerateFiles(path))
{
string association = Shell32.GetFileAssociation(file);
string contentType = Shell32.GetFileContentType(file);
string defaultIconPath = Shell32.GetFileDefaultIcon(file);
string friendlyAppName = Shell32.GetFileFriendlyAppName(file);
string friendlyDocName = Shell32.GetFileFriendlyDocName(file);
string openWithApp = Shell32.GetFileOpenWithAppName(file);
string verbCommand = Shell32.GetFileVerbCommand(file);
Console.WriteLine("\t#{0:000}\t[{1}]\n", ++cnt, file);
Console.WriteLine("\t\tGetFileAssociation() : [{0}]", association);
Console.WriteLine("\t\tGetFileContentType() : [{0}]", contentType);
Console.WriteLine("\t\tGetFileDefaultIcon() : [{0}]", defaultIconPath);
Console.WriteLine("\t\tGetFileFriendlyAppName(): [{0}]", friendlyAppName);
Console.WriteLine("\t\tGetFileFriendlyDocName(): [{0}]", friendlyDocName);
Console.WriteLine("\t\tGetFileOpenWithAppName(): [{0}]", openWithApp);
Console.WriteLine("\t\tGetFileVerbCommand() : [{0}]", verbCommand);
UnitTestConstants.StopWatcher(true);
Shell32Info shell32Info = Shell32.GetShell32Info(file);
string report = UnitTestConstants.Reporter(true);
string cmd = "print";
verbCommand = shell32Info.GetVerbCommand(cmd);
Console.WriteLine("\n\t\tShell32Info.GetVerbCommand(\"{0}\"): [{1}]", cmd, verbCommand);
UnitTestConstants.Dump(shell32Info, -15);
Console.WriteLine("\n\t{0}\n\n", report);
}
Console.WriteLine("\n");
Assert.IsTrue(cnt > 0, "No entries enumerated.");
}
#endregion // DumpGetAssociation
private void DumpPathFileExists(string path, bool doesExist)
{
Console.WriteLine("\n\tPath: [{0}]\n", path);
bool fileExists = Shell32.PathFileExists(path);
Console.WriteLine("\t\tShell32.PathFileExists() == [{0}]: {1}\t\t[{2}]", doesExist ? UnitTestConstants.TextTrue : UnitTestConstants.TextFalse, doesExist == fileExists, path);
Console.WriteLine("\t\tFile.Exists() == [{0}]: {1}\t\t[{2}]", doesExist ? UnitTestConstants.TextTrue : UnitTestConstants.TextFalse, doesExist == File.Exists(path), path);
Console.WriteLine("\t\tDirectory.Exists() == [{0}]: {1}\t\t[{2}]", doesExist ? UnitTestConstants.TextTrue : UnitTestConstants.TextFalse, doesExist == Directory.Exists(path), path);
if (doesExist)
Assert.IsTrue(fileExists);
if (!doesExist)
Assert.IsTrue(!fileExists);
}
#region GetFileAssociation
[TestMethod]
public void GetFileAssociation()
{
Console.WriteLine("Filesystem.Shell32.GetFileAssociation()");
DumpGetAssociation(true);
DumpGetAssociation(false);
}
#endregion // GetFileAssociation
#region GetFileIcon
[TestMethod]
public void GetFileIcon()
{
Console.WriteLine("Filesystem.Shell32.GetFileIcon()");
Console.WriteLine("\nInput File Path: [{0}]\n", UnitTestConstants.NotepadExe);
Console.WriteLine("Example usage:");
Console.WriteLine("\n\tIntPtr icon = Shell32.GetFileIcon(file, FileAttributes.SmallIcon | FileAttributes.AddOverlays);");
IntPtr icon = Shell32.GetFileIcon(UnitTestConstants.NotepadExe, Shell32.FileAttributes.SmallIcon | Shell32.FileAttributes.AddOverlays);
Console.WriteLine("\n\tIcon Handle: [{0}]", icon);
Assert.IsTrue(icon != IntPtr.Zero, "Failed retrieving icon for: [{0}]", UnitTestConstants.NotepadExe);
}
#endregion // GetFileIcon
#region PathCreateFromUrl
[TestMethod]
public void PathCreateFromUrl()
{
Console.WriteLine("Filesystem.Shell32.PathCreateFromUrl()");
string urlPath = Shell32.UrlCreateFromPath(UnitTestConstants.AppData);
string filePath = Shell32.PathCreateFromUrl(urlPath);
Console.WriteLine("\n\tDirectory : [{0}]", UnitTestConstants.AppData);
Console.WriteLine("\n\tShell32.UrlCreateFromPath(): [{0}]", urlPath);
Console.WriteLine("\n\tShell32.PathCreateFromUrl() == [{0}]\n", filePath);
bool startsWith = urlPath.StartsWith("file:///");
bool equalsAppData = filePath.Equals(UnitTestConstants.AppData);
Console.WriteLine("\n\turlPath.StartsWith(\"file:///\") == [{0}]: {1}", UnitTestConstants.TextTrue, startsWith);
Console.WriteLine("\n\tfilePath.Equals(AppData) == [{0}]: {1}\n", UnitTestConstants.TextTrue, equalsAppData);
Assert.IsTrue(startsWith);
Assert.IsTrue(equalsAppData);
}
#endregion // PathCreateFromUrl
#region PathCreateFromUrlAlloc
[TestMethod]
public void PathCreateFromUrlAlloc()
{
Console.WriteLine("Filesystem.Shell32.PathCreateFromUrlAlloc()");
string urlPath = Shell32.UrlCreateFromPath(UnitTestConstants.AppData);
string filePath = Shell32.PathCreateFromUrlAlloc(urlPath);
Console.WriteLine("\n\tDirectory : [{0}]", UnitTestConstants.AppData);
Console.WriteLine("\n\tShell32.UrlCreateFromPath(): [{0}]", urlPath);
Console.WriteLine("\n\tShell32.PathCreateFromUrlAlloc() == [{0}]\n", filePath);
bool startsWith = urlPath.StartsWith("file:///");
bool equalsAppData = filePath.Equals(UnitTestConstants.AppData);
Console.WriteLine("\n\turlPath.StartsWith(\"file:///\") == [{0}]: {1}", UnitTestConstants.TextTrue, startsWith);
Console.WriteLine("\n\tfilePath.Equals(AppData) == [{0}]: {1}\n", UnitTestConstants.TextTrue, equalsAppData);
Assert.IsTrue(startsWith);
Assert.IsTrue(equalsAppData);
}
#endregion // PathCreateFromUrlAlloc
#region PathFileExists
[TestMethod]
public void PathFileExists()
{
Console.WriteLine("Filesystem.Shell32.PathFileExists()");
string path = UnitTestConstants.SysRoot;
DumpPathFileExists(path, true);
DumpPathFileExists(Path.LocalToUnc(path), true);
DumpPathFileExists("BlaBlaBla", false);
DumpPathFileExists(Path.Combine(UnitTestConstants.SysRoot, "BlaBlaBla"), false);
int cnt = 0;
UnitTestConstants.StopWatcher(true);
foreach (string file in Directory.EnumerateFiles(UnitTestConstants.SysRoot))
{
bool fileExists = Shell32.PathFileExists(file);
Console.WriteLine("\t#{0:000}\tShell32.PathFileExists() == [{1}]: {2}\t\t[{3}]", ++cnt, UnitTestConstants.TextTrue, fileExists, file);
Assert.IsTrue(fileExists);
}
Console.WriteLine("\n\t{0}\n", UnitTestConstants.Reporter(true));
}
#endregion // PathFileExists
#region UrlCreateFromPath
[TestMethod]
public void UrlCreateFromPath()
{
Console.WriteLine("Filesystem.Shell32.UrlCreateFromPath()");
PathCreateFromUrl();
PathCreateFromUrlAlloc();
}
#endregion // UrlCreateFromPath
#region UrlIs
[TestMethod]
public void UrlIs()
{
Console.WriteLine("Filesystem.Shell32.UrlIs()");
string urlPath = Shell32.UrlCreateFromPath(UnitTestConstants.AppData);
string filePath = Shell32.PathCreateFromUrlAlloc(urlPath);
bool isFileUrl1 = Shell32.UrlIsFileUrl(urlPath);
bool isFileUrl2 = Shell32.UrlIsFileUrl(filePath);
bool isNoHistory = Shell32.UrlIs(filePath, Shell32.UrlType.IsNoHistory);
bool isOpaque = Shell32.UrlIs(filePath, Shell32.UrlType.IsOpaque);
Console.WriteLine("\n\tDirectory: [{0}]", UnitTestConstants.AppData);
Console.WriteLine("\n\tShell32.UrlCreateFromPath() == IsFileUrl == [{0}] : {1}\t\t[{2}]", UnitTestConstants.TextTrue, isFileUrl1, urlPath);
Console.WriteLine("\n\tShell32.PathCreateFromUrlAlloc() == IsFileUrl == [{0}]: {1}\t\t[{2}]", UnitTestConstants.TextFalse, isFileUrl2, filePath);
Console.WriteLine("\n\tShell32.UrlIsFileUrl() == [{0}]: {1}\t\t[{2}]", UnitTestConstants.TextTrue, isFileUrl1, urlPath);
Console.WriteLine("\n\tShell32.UrlIsNoHistory() == [{0}]: {1}\t\t[{2}]", UnitTestConstants.TextTrue, isNoHistory, urlPath);
Console.WriteLine("\n\tShell32.UrlIsOpaque() == [{0}]: {1}\t\t[{2}]", UnitTestConstants.TextTrue, isOpaque, urlPath);
Assert.IsTrue(isFileUrl1);
Assert.IsTrue(isFileUrl2 == false);
}
#endregion // UrlIs
}
}
| |
//
// Tracker.cs
//
// Authors:
// Gregor Burger burger.gregor@gmail.com
//
// Copyright (C) 2006 Gregor Burger
//
// 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.Net;
using System.Web;
using System.Text;
using System.Diagnostics;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;
using OctoTorrent.Common;
using OctoTorrent.BEncoding;
using OctoTorrent.Tracker.Listeners;
namespace OctoTorrent.Tracker
{
public class Tracker : IEnumerable<SimpleTorrentManager>, IDisposable
{
#region Static BEncodedStrings
internal static readonly BEncodedString PeersKey = "peers";
internal static readonly BEncodedString IntervalKey = "interval";
internal static readonly BEncodedString MinIntervalKey = "min interval";
internal static readonly BEncodedString TrackerIdKey = "tracker id";
internal static readonly BEncodedString CompleteKey = "complete";
internal static readonly BEncodedString Incomplete = "incomplete";
internal static readonly BEncodedString PeerIdKey = "peer id";
internal static readonly BEncodedString Port = "port";
internal static readonly BEncodedString Ip = "ip";
#endregion Static BEncodedStrings
#region Events
public event EventHandler<AnnounceEventArgs> PeerAnnounced;
public event EventHandler<ScrapeEventArgs> PeerScraped;
public event EventHandler<TimedOutEventArgs> PeerTimedOut;
#endregion Events
#region Fields
private bool allowScrape;
private bool allowNonCompact;
private bool allowUnregisteredTorrents;
private TimeSpan announceInterval;
private bool disposed;
private TimeSpan minAnnounceInterval;
private RequestMonitor monitor;
private TimeSpan timeoutInterval;
private Dictionary<InfoHash, SimpleTorrentManager> torrents;
private BEncodedString trackerId;
#endregion Fields
#region Properties
public bool AllowNonCompact
{
get { return allowNonCompact; }
set { allowNonCompact = value; }
}
public bool AllowScrape
{
get { return allowScrape; }
set { allowScrape = value; }
}
public bool AllowUnregisteredTorrents
{
get { return allowUnregisteredTorrents; }
set { allowUnregisteredTorrents = value; }
}
public TimeSpan AnnounceInterval
{
get { return announceInterval; }
set { announceInterval = value; }
}
public int Count
{
get { return torrents.Count; }
}
public bool Disposed
{
get { return disposed; }
}
public TimeSpan MinAnnounceInterval
{
get { return minAnnounceInterval; }
set { minAnnounceInterval = value; }
}
public RequestMonitor Requests
{
get { return monitor; }
}
public TimeSpan TimeoutInterval
{
get { return timeoutInterval; }
set { timeoutInterval = value; }
}
public BEncodedString TrackerId
{
get { return trackerId; }
}
#endregion Properties
#region Constructors
/// <summary>
/// Creates a new tracker
/// </summary>
public Tracker()
: this(new BEncodedString("monotorrent-tracker"))
{
}
public Tracker(BEncodedString trackerId)
{
allowNonCompact = true;
allowScrape = true;
monitor = new RequestMonitor();
torrents = new Dictionary<InfoHash, SimpleTorrentManager>();
this.trackerId = trackerId;
announceInterval = TimeSpan.FromMinutes(45);
minAnnounceInterval = TimeSpan.FromMinutes(10);
timeoutInterval = TimeSpan.FromMinutes(50);
Client.ClientEngine.MainLoop.QueueTimeout(TimeSpan.FromSeconds(1), delegate {
Requests.Tick();
return !disposed;
});
}
#endregion Constructors
#region Methods
public bool Add(ITrackable trackable)
{
return Add(trackable, new IPAddressComparer());
}
public bool Add(ITrackable trackable, IPeerComparer comparer)
{
CheckDisposed();
if (trackable == null)
throw new ArgumentNullException("trackable");
lock (torrents)
{
if (torrents.ContainsKey(trackable.InfoHash))
return false;
torrents.Add(trackable.InfoHash, new SimpleTorrentManager(trackable, comparer, this));
}
Debug.WriteLine(string.Format("Tracking Torrent: {0}", trackable.Name));
return true;
}
private void CheckDisposed()
{
if (disposed)
throw new ObjectDisposedException(GetType().Name);
}
public bool Contains(ITrackable trackable)
{
CheckDisposed();
if (trackable == null)
throw new ArgumentNullException("trackable");
lock (torrents)
return torrents.ContainsKey(trackable.InfoHash);
}
public SimpleTorrentManager GetManager(ITrackable trackable)
{
CheckDisposed();
if (trackable == null)
throw new ArgumentNullException("trackable");
SimpleTorrentManager value;
lock (torrents)
if (torrents.TryGetValue(trackable.InfoHash, out value))
return value;
return null;
}
public IEnumerator<SimpleTorrentManager> GetEnumerator()
{
CheckDisposed();
lock (torrents)
return new List<SimpleTorrentManager>(this.torrents.Values).GetEnumerator();
}
public bool IsRegistered(ListenerBase listener)
{
CheckDisposed();
if (listener == null)
throw new ArgumentNullException("listener");
return listener.Tracker == this;
}
private void ListenerReceivedAnnounce(object sender, AnnounceParameters e)
{
if (disposed)
{
e.Response.Add(RequestParameters.FailureKey, (BEncodedString)"The tracker has been shut down");
return;
}
monitor.AnnounceReceived();
SimpleTorrentManager manager;
// Check to see if we're monitoring the requested torrent
lock (torrents)
{
if (!torrents.TryGetValue(e.InfoHash, out manager))
{
if (AllowUnregisteredTorrents)
{
Add(new InfoHashTrackable(BitConverter.ToString(e.InfoHash.Hash), e.InfoHash));
manager = torrents[e.InfoHash];
}
else
{
e.Response.Add(RequestParameters.FailureKey, (BEncodedString)"The requested torrent is not registered with this tracker");
return;
}
}
}
// If a non-compact response is expected and we do not allow non-compact responses
// bail out
if (!AllowNonCompact && !e.HasRequestedCompact)
{
e.Response.Add(RequestParameters.FailureKey, (BEncodedString)"This tracker does not support non-compact responses");
return;
}
lock (manager)
{
// Update the tracker with the peers information. This adds the peer to the tracker,
// updates it's information or removes it depending on the context
manager.Update(e);
// Clear any peers who haven't announced within the allowed timespan and may be inactive
manager.ClearZombiePeers(DateTime.Now.Add(-TimeoutInterval));
// Fulfill the announce request
manager.GetPeers(e.Response, e.NumberWanted, e.HasRequestedCompact);
}
e.Response.Add(Tracker.IntervalKey, new BEncodedNumber((int)AnnounceInterval.TotalSeconds));
e.Response.Add(Tracker.MinIntervalKey, new BEncodedNumber((int)MinAnnounceInterval.TotalSeconds));
e.Response.Add(Tracker.TrackerIdKey, trackerId); // FIXME: Is this right?
e.Response.Add(Tracker.CompleteKey, new BEncodedNumber(manager.Complete));
e.Response.Add(Tracker.Incomplete, new BEncodedNumber(manager.Incomplete));
//FIXME is this the right behaivour
//if (par.TrackerId == null)
// par.TrackerId = "monotorrent-tracker";
}
private void ListenerReceivedScrape(object sender, ScrapeParameters e)
{
if (disposed)
{
e.Response.Add(RequestParameters.FailureKey, (BEncodedString)"The tracker has been shut down");
return;
}
monitor.ScrapeReceived();
if (!AllowScrape)
{
e.Response.Add(RequestParameters.FailureKey, (BEncodedString)"This tracker does not allow scraping");
return;
}
if (e.InfoHashes.Count == 0)
{
e.Response.Add(RequestParameters.FailureKey, (BEncodedString)"You must specify at least one infohash when scraping this tracker");
return;
}
List<SimpleTorrentManager> managers = new List<SimpleTorrentManager>();
BEncodedDictionary files = new BEncodedDictionary();
for (int i = 0; i < e.InfoHashes.Count; i++)
{
SimpleTorrentManager manager;
if (!torrents.TryGetValue(e.InfoHashes[i], out manager))
continue;
managers.Add(manager);
BEncodedDictionary dict = new BEncodedDictionary();
dict.Add("complete",new BEncodedNumber( manager.Complete));
dict.Add("downloaded", new BEncodedNumber(manager.Downloaded));
dict.Add("incomplete", new BEncodedNumber(manager.Incomplete));
dict.Add("name", new BEncodedString(manager.Trackable.Name));
files.Add(e.InfoHashes[i].ToHex (), dict);
}
RaisePeerScraped(new ScrapeEventArgs(managers));
e.Response.Add("files", files);
}
internal void RaisePeerAnnounced(AnnounceEventArgs e)
{
EventHandler<AnnounceEventArgs> h = PeerAnnounced;
if (h != null)
h(this, e);
}
internal void RaisePeerScraped(ScrapeEventArgs e)
{
EventHandler<ScrapeEventArgs> h = PeerScraped;
if (h != null)
h(this, e);
}
internal void RaisePeerTimedOut(TimedOutEventArgs e)
{
EventHandler<TimedOutEventArgs> h = PeerTimedOut;
if (h != null)
h(this, e);
}
public void RegisterListener(ListenerBase listener)
{
CheckDisposed();
if (listener == null)
throw new ArgumentNullException("listener");
if (listener.Tracker != null)
throw new TorrentException("The listener is registered to a different Tracker");
listener.Tracker = this;
listener.AnnounceReceived += new EventHandler<AnnounceParameters>(ListenerReceivedAnnounce);
listener.ScrapeReceived += new EventHandler<ScrapeParameters>(ListenerReceivedScrape);
}
public void Remove(ITrackable trackable)
{
CheckDisposed();
if (trackable == null)
throw new ArgumentNullException("trackable");
lock (torrents)
torrents.Remove(trackable.InfoHash);
}
public void UnregisterListener(ListenerBase listener)
{
CheckDisposed();
if (listener == null)
throw new ArgumentNullException("listener");
if (listener.Tracker != this)
throw new TorrentException("The listener is not registered with this tracker");
listener.Tracker = null;
listener.AnnounceReceived -= new EventHandler<AnnounceParameters>(ListenerReceivedAnnounce);
listener.ScrapeReceived -= new EventHandler<ScrapeParameters>(ListenerReceivedScrape);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion Methods
public void Dispose()
{
if (disposed)
return;
disposed = true;
}
}
}
| |
using UnityEngine.EventSystems;
namespace UnityEngine.UI
{
[RequireComponent(typeof(Canvas))]
[ExecuteInEditMode]
[AddComponentMenu("Layout/Canvas Scaler", 101)]
public class CanvasScaler : UIBehaviour
{
public enum ScaleMode { ConstantPixelSize, ScaleWithScreenSize, ConstantPhysicalSize }
[Tooltip("Determines how UI elements in the Canvas are scaled.")]
[SerializeField] private ScaleMode m_UiScaleMode = ScaleMode.ConstantPixelSize;
public ScaleMode uiScaleMode { get { return m_UiScaleMode; } set { m_UiScaleMode = value; } }
[Tooltip("If a sprite has this 'Pixels Per Unit' setting, then one pixel in the sprite will cover one unit in the UI.")]
[SerializeField] protected float m_ReferencePixelsPerUnit = 100;
public float referencePixelsPerUnit { get { return m_ReferencePixelsPerUnit; } set { m_ReferencePixelsPerUnit = value; } }
// Constant Pixel Size settings
[Tooltip("Scales all UI elements in the Canvas by this factor.")]
[SerializeField] protected float m_ScaleFactor = 1;
public float scaleFactor { get { return m_ScaleFactor; } set { m_ScaleFactor = value; } }
// Scale With Screen Size settings
public enum ScreenMatchMode { MatchWidthOrHeight = 0, Expand = 1, Shrink = 2 }
[Tooltip("The resolution the UI layout is designed for. If the screen resolution is larger, the UI will be scaled up, and if it's smaller, the UI will be scaled down. This is done in accordance with the Screen Match Mode.")]
[SerializeField] protected Vector2 m_ReferenceResolution = new Vector2(800, 600);
public Vector2 referenceResolution { get { return m_ReferenceResolution; } set { m_ReferenceResolution = value; } }
[Tooltip("A mode used to scale the canvas area if the aspect ratio of the current resolution doesn't fit the reference resolution.")]
[SerializeField] protected ScreenMatchMode m_ScreenMatchMode = ScreenMatchMode.MatchWidthOrHeight;
public ScreenMatchMode screenMatchMode { get { return m_ScreenMatchMode; } set { m_ScreenMatchMode = value; } }
[Tooltip("Determines if the scaling is using the width or height as reference, or a mix in between.")]
[Range(0, 1)]
[SerializeField] protected float m_MatchWidthOrHeight = 0;
public float matchWidthOrHeight { get { return m_MatchWidthOrHeight; } set { m_MatchWidthOrHeight = value; } }
// The log base doesn't have any influence on the results whatsoever, as long as the same base is used everywhere.
private const float kLogBase = 2;
// Constant Physical Size settings
public enum Unit { Centimeters, Millimeters, Inches, Points, Picas }
[Tooltip("The physical unit to specify positions and sizes in.")]
[SerializeField] protected Unit m_PhysicalUnit = Unit.Points;
public Unit physicalUnit { get { return m_PhysicalUnit; } set { m_PhysicalUnit = value; } }
[Tooltip("The DPI to assume if the screen DPI is not known.")]
[SerializeField] protected float m_FallbackScreenDPI = 96;
public float fallbackScreenDPI { get { return m_FallbackScreenDPI; } set { m_FallbackScreenDPI = value; } }
[Tooltip("The pixels per inch to use for sprites that have a 'Pixels Per Unit' setting that matches the 'Reference Pixels Per Unit' setting.")]
[SerializeField] protected float m_DefaultSpriteDPI = 96;
public float defaultSpriteDPI { get { return m_DefaultSpriteDPI; } set { m_DefaultSpriteDPI = value; } }
// World Canvas settings
[Tooltip("The amount of pixels per unit to use for dynamically created bitmaps in the UI, such as Text.")]
[SerializeField] protected float m_DynamicPixelsPerUnit = 1;
public float dynamicPixelsPerUnit { get { return m_DynamicPixelsPerUnit; } set { m_DynamicPixelsPerUnit = value; } }
// General variables
private Canvas m_Canvas;
[System.NonSerialized]
private float m_PrevScaleFactor = 1;
[System.NonSerialized]
private float m_PrevReferencePixelsPerUnit = 100;
protected CanvasScaler() { }
protected override void OnEnable()
{
base.OnEnable();
m_Canvas = GetComponent<Canvas>();
Handle();
}
protected override void OnDisable()
{
SetScaleFactor(1);
SetReferencePixelsPerUnit(100);
base.OnDisable();
}
protected virtual void Update()
{
Handle();
}
protected virtual void Handle()
{
if (m_Canvas == null || !m_Canvas.isRootCanvas)
return;
if (m_Canvas.renderMode == RenderMode.WorldSpace)
{
HandleWorldCanvas();
return;
}
switch (m_UiScaleMode)
{
case ScaleMode.ConstantPixelSize: HandleConstantPixelSize(); break;
case ScaleMode.ScaleWithScreenSize: HandleScaleWithScreenSize(); break;
case ScaleMode.ConstantPhysicalSize: HandleConstantPhysicalSize(); break;
}
}
protected virtual void HandleWorldCanvas()
{
SetScaleFactor(m_DynamicPixelsPerUnit);
SetReferencePixelsPerUnit(m_ReferencePixelsPerUnit);
}
protected virtual void HandleConstantPixelSize()
{
SetScaleFactor(m_ScaleFactor);
SetReferencePixelsPerUnit(m_ReferencePixelsPerUnit);
}
protected virtual void HandleScaleWithScreenSize()
{
Vector2 screenSize = new Vector2(Screen.width, Screen.height);
float scaleFactor = 0;
switch (m_ScreenMatchMode)
{
case ScreenMatchMode.MatchWidthOrHeight:
{
// We take the log of the relative width and height before taking the average.
// Then we transform it back in the original space.
// the reason to transform in and out of logarithmic space is to have better behavior.
// If one axis has twice resolution and the other has half, it should even out if widthOrHeight value is at 0.5.
// In normal space the average would be (0.5 + 2) / 2 = 1.25
// In logarithmic space the average is (-1 + 1) / 2 = 0
float logWidth = Mathf.Log(screenSize.x / m_ReferenceResolution.x, kLogBase);
float logHeight = Mathf.Log(screenSize.y / m_ReferenceResolution.y, kLogBase);
float logWeightedAverage = Mathf.Lerp(logWidth, logHeight, m_MatchWidthOrHeight);
scaleFactor = Mathf.Pow(kLogBase, logWeightedAverage);
break;
}
case ScreenMatchMode.Expand:
{
scaleFactor = Mathf.Min(screenSize.x / m_ReferenceResolution.x, screenSize.y / m_ReferenceResolution.y);
break;
}
case ScreenMatchMode.Shrink:
{
scaleFactor = Mathf.Max(screenSize.x / m_ReferenceResolution.x, screenSize.y / m_ReferenceResolution.y);
break;
}
}
SetScaleFactor(scaleFactor);
SetReferencePixelsPerUnit(m_ReferencePixelsPerUnit);
}
protected virtual void HandleConstantPhysicalSize()
{
float currentDpi = Screen.dpi;
float dpi = (currentDpi == 0 ? m_FallbackScreenDPI : currentDpi);
float targetDPI = 1;
switch (m_PhysicalUnit)
{
case Unit.Centimeters: targetDPI = 2.54f; break;
case Unit.Millimeters: targetDPI = 25.4f; break;
case Unit.Inches: targetDPI = 1; break;
case Unit.Points: targetDPI = 72; break;
case Unit.Picas: targetDPI = 6; break;
}
SetScaleFactor(dpi / targetDPI);
SetReferencePixelsPerUnit(m_ReferencePixelsPerUnit * targetDPI / m_DefaultSpriteDPI);
}
protected void SetScaleFactor(float scaleFactor)
{
if (scaleFactor == m_PrevScaleFactor)
return;
m_Canvas.scaleFactor = scaleFactor;
m_PrevScaleFactor = scaleFactor;
}
protected void SetReferencePixelsPerUnit(float referencePixelsPerUnit)
{
if (referencePixelsPerUnit == m_PrevReferencePixelsPerUnit)
return;
m_Canvas.referencePixelsPerUnit = referencePixelsPerUnit;
m_PrevReferencePixelsPerUnit = referencePixelsPerUnit;
}
}
}
| |
// 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 System;
using System.Diagnostics;
using System.IO;
using Xunit;
namespace System.IO.Tests
{
public class FileStream_Dispose : FileSystemTest
{
[Fact]
public void CanDispose()
{
new FileStream(GetTestFilePath(), FileMode.Create).Dispose();
}
[Fact]
public void DisposeClosesHandle()
{
SafeFileHandle handle;
using(FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
handle = fs.SafeFileHandle;
}
Assert.True(handle.IsClosed);
}
[Fact]
public void HandlesMultipleDispose()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
fs.Dispose();
fs.Dispose();
} // disposed as we leave using
}
private class MyFileStream : FileStream
{
public MyFileStream(string path, FileMode mode)
: base(path, mode)
{ }
public MyFileStream(SafeFileHandle handle, FileAccess access, Action<bool> disposeMethod) : base(handle, access)
{
DisposeMethod = disposeMethod;
}
public Action<bool> DisposeMethod { get; set; }
protected override void Dispose(bool disposing)
{
Action<bool> disposeMethod = DisposeMethod;
if (disposeMethod != null)
disposeMethod(disposing);
base.Dispose(disposing);
}
}
[Fact]
public void Dispose_CallsVirtualDisposeTrueArg_ThrowsDuringFlushWriteBuffer_DisposeThrows()
{
RemoteInvoke(() =>
{
string fileName = GetTestFilePath();
using (FileStream fscreate = new FileStream(fileName, FileMode.Create))
{
fscreate.WriteByte(0);
}
bool writeDisposeInvoked = false;
Action<bool> writeDisposeMethod = _ => writeDisposeInvoked = true;
using (var fsread = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
Action act = () => // separate method to avoid JIT lifetime-extension issues
{
using (var fswrite = new MyFileStream(fsread.SafeFileHandle, FileAccess.Write, writeDisposeMethod))
{
fswrite.WriteByte(0);
// Normal dispose should call Dispose(true). Throws due to FS trying to flush write buffer
Assert.Throws<UnauthorizedAccessException>(() => fswrite.Dispose());
Assert.True(writeDisposeInvoked, "Expected Dispose(true) to be called from Dispose()");
writeDisposeInvoked = false;
// Only throws on first Dispose call
fswrite.Dispose();
Assert.True(writeDisposeInvoked, "Expected Dispose(true) to be called from Dispose()");
writeDisposeInvoked = false;
}
Assert.True(writeDisposeInvoked, "Expected Dispose(true) to be called from Dispose() again");
writeDisposeInvoked = false;
};
act();
for (int i = 0; i < 2; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
Assert.False(writeDisposeInvoked, "Expected finalizer to have been suppressed");
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Missing fix for https://github.com/dotnet/coreclr/pull/16250")]
public void NoDispose_CallsVirtualDisposeFalseArg_ThrowsDuringFlushWriteBuffer_FinalizerWontThrow()
{
RemoteInvoke(() =>
{
string fileName = GetTestFilePath();
using (FileStream fscreate = new FileStream(fileName, FileMode.Create))
{
fscreate.WriteByte(0);
}
bool writeDisposeInvoked = false;
Action<bool> writeDisposeMethod = (disposing) =>
{
writeDisposeInvoked = true;
Assert.False(disposing, "Expected false arg to Dispose(bool)");
};
using (var fsread = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
Action act = () => // separate method to avoid JIT lifetime-extension issues
{
var fswrite = new MyFileStream(fsread.SafeFileHandle, FileAccess.Write, writeDisposeMethod);
fswrite.WriteByte(0);
};
act();
// Dispose is not getting called here.
// instead, make sure finalizer gets called and doesnt throw exception
for (int i = 0; i < 2; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
Assert.True(writeDisposeInvoked, "Expected finalizer to be invoked but not throw exception");
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void Dispose_CallsVirtualDispose_TrueArg()
{
bool disposeInvoked = false;
Action act = () => // separate method to avoid JIT lifetime-extension issues
{
using (MyFileStream fs = new MyFileStream(GetTestFilePath(), FileMode.Create))
{
fs.DisposeMethod = (disposing) =>
{
disposeInvoked = true;
Assert.True(disposing, "Expected true arg to Dispose(bool)");
};
// Normal dispose should call Dispose(true)
fs.Dispose();
Assert.True(disposeInvoked, "Expected Dispose(true) to be called from Dispose()");
disposeInvoked = false;
}
// Second dispose leaving the using should still call dispose
Assert.True(disposeInvoked, "Expected Dispose(true) to be called from Dispose() again");
disposeInvoked = false;
};
act();
// Make sure we suppressed finalization
for (int i = 0; i < 2; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
Assert.False(disposeInvoked, "Expected finalizer to have been suppressed");
}
[Fact]
public void Finalizer_CallsVirtualDispose_FalseArg()
{
bool disposeInvoked = false;
Action act = () => // separate method to avoid JIT lifetime-extension issues
{
var fs2 = new MyFileStream(GetTestFilePath(), FileMode.Create)
{
DisposeMethod = (disposing) =>
{
disposeInvoked = true;
Assert.False(disposing, "Expected false arg to Dispose(bool)");
}
};
};
act();
for (int i = 0; i < 2; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
Assert.True(disposeInvoked, "Expected finalizer to be invoked and set called");
}
[Fact]
public void DisposeFlushesWriteBuffer()
{
string fileName = GetTestFilePath();
using(FileStream fs = new FileStream(fileName, FileMode.Create))
{
fs.Write(TestBuffer, 0, TestBuffer.Length);
}
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
{
byte[] buffer = new byte[TestBuffer.Length];
Assert.Equal(buffer.Length, fs.Length);
fs.Read(buffer, 0, buffer.Length);
Assert.Equal(TestBuffer, buffer);
}
}
[Fact]
public void FinalizeFlushesWriteBuffer()
{
string fileName = GetTestFilePath();
// use a separate method to be sure that fs isn't rooted at time of GC.
Action leakFs = () =>
{
// we must specify useAsync:false, otherwise the finalizer just kicks off an async write.
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, useAsync: false);
fs.Write(TestBuffer, 0, TestBuffer.Length);
fs = null;
};
leakFs();
GC.Collect();
GC.WaitForPendingFinalizers();
using (FileStream fsr = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
{
byte[] buffer = new byte[TestBuffer.Length];
Assert.Equal(buffer.Length, fsr.Length);
fsr.Read(buffer, 0, buffer.Length);
Assert.Equal(TestBuffer, buffer);
}
}
}
}
| |
// form_StringControl.cs
//
// Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Review documentation at http://www.yourothermind.com for updated implementation notes, license updates
// or other general information/
//
// Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW
// Full source code: https://github.com/BrentKnowles/YourOtherMind
//###
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CoreUtilities
{
/// <summary>
/// Form_ string control.
///
/// Allow user to enter strings in a particular order.
/// </summary>
public class form_StringControl :Form
{
#region interfaceelements
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton buttonAdd;
private System.Windows.Forms.ToolStripButton buttonRemove;
private ListBox ListOfStrings;
private System.Windows.Forms.Panel panel1;
// set during constructor
private Icon FormIcon;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox textBox1;
#endregion
public form_StringControl (Icon formIcon)
{
FormIcon = formIcon;
this.Icon = FormIcon;
InitializeComponent();
}
#region Component Designer generated code
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.buttonAdd = new System.Windows.Forms.ToolStripButton();
this.buttonRemove = new System.Windows.Forms.ToolStripButton();
this.panel1 = new System.Windows.Forms.Panel();
this.ListOfStrings = new ListBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.toolStrip1.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// toolStrip1
//
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.buttonAdd,
this.buttonRemove});
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(293, 25);
this.toolStrip1.TabIndex = 1;
this.toolStrip1.Text = "toolStrip1";
//
// buttonAdd
//
//this.buttonAdd.Image = global::CoreUtilities.UserControls.add;
this.buttonAdd.ImageTransparentColor = System.Drawing.Color.Magenta;
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(95, 22);
this.buttonAdd.Text = "Add New Item";
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// buttonRemove
//
//this.buttonRemove.Image = global::CoreUtilities.UserControls.delete;
this.buttonRemove.ImageTransparentColor = System.Drawing.Color.Magenta;
this.buttonRemove.Name = "buttonRemove";
this.buttonRemove.Size = new System.Drawing.Size(135, 22);
this.buttonRemove.Text = "Remove Selected Item";
this.buttonRemove.Click += new System.EventHandler(this.buttonRemove_Click);
//
// panel1
//
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Controls.Add(this.ListOfStrings);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 25);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(293, 293);
this.panel1.TabIndex = 3;
//
// treeView1
//
this.ListOfStrings.AllowDrop = true;
this.ListOfStrings.Dock = System.Windows.Forms.DockStyle.Fill;
this.ListOfStrings.Location = new System.Drawing.Point(0, 0);
this.ListOfStrings.Name = "ListOfStrings";
this.ListOfStrings.Size = new System.Drawing.Size(291, 291);
this.ListOfStrings.TabIndex = 2;
this.ListOfStrings.DoubleClick += new System.EventHandler(this.treeView1_DoubleClick);
//
// button2
//
this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button2.Location = new System.Drawing.Point(211, 302);
this.button2.Dock = DockStyle.Bottom;
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "Cancel";
this.button2.UseVisualStyleBackColor = true;
//
// button1
//
this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
this.button1.Dock = DockStyle.Bottom;
this.button1.Location = new System.Drawing.Point(130, 302);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "OK";
this.button1.UseVisualStyleBackColor = true;
//
// textBox1
//
this.textBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
this.textBox1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.textBox1.Location = new System.Drawing.Point(0, 263);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(298, 33);
this.textBox1.TabIndex = 3;
this.textBox1.Text = "(CONSTRUCTOR)If you press OK after modifying column definitions any data in the current table " +
"will be deleted.";
// this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(400,400);
this.Controls.Add (button1);
this.Controls.Add (button2);
this.Controls.Add (textBox1);
this.Controls.Add(this.panel1);
this.Controls.Add(this.toolStrip1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "STRING BUIlDER";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
// this.Text = "Add Text";
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
#region methods
public string[] Strings
{
get
{
string[] s = new string[ListOfStrings.Items.Count];
int nCount = -1;
foreach (object o in ListOfStrings.Items)
{
nCount++;
s[nCount] = o.ToString();
}
return s;
}
set
{
if (value != null)
{
// build the treeview
ListOfStrings.Items.Clear ();
foreach (string s in value)
{
ListOfStrings.Items.Add(s);
}
}
}
}
private bool bSorted=false;
/// <summary>
/// // if IsSorted == true then try and place it in the correct place
/// </summary>
///
public bool IsSorted
{
get { return bSorted; }
set { bSorted = value; }
}
private void buttonAdd_Click(object sender, EventArgs e)
{
form_AddTextString addText = new form_AddTextString(FormIcon);
if (addText.ShowDialog() == DialogResult.OK)
{
/* TreeNode[] found = treeView1.Nodes.Find(addText.textBox.Text,true);
if ( found.Length > 0)
{
Messag eBox.Show("Strings in list must be unique");
return;
}*/
if (addText.textBox.Text == " " || addText.textBox.Text == "")
{
NewMessage.Show("Cannot add blank strings");
return;
}
if (IsSorted == false || ListOfStrings.Items.Count == 0)
{
ListOfStrings.Items.Add(addText.textBox.Text);
}
else
if (IsSorted == true)
{
string sText = addText.textBox.Text;
int i = 0;
int nIndex = -1;
for (i = 0; i < ListOfStrings.Items.Count; i++)
{
if (ListOfStrings.Items[i].ToString ().CompareTo(sText) >= 0 )
{
nIndex = i;
break;
}
}
if (nIndex != -1)
ListOfStrings.Items.Insert(nIndex, sText);
else
{
ListOfStrings.Items.Add(addText.textBox.Text);
}
}
// if IsSorted == true then try and place it in the correct place
}
}
/// <summary>
/// delete selected node
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemove_Click(object sender, EventArgs e)
{
if (NewMessage.Show(Loc.Instance.GetString("Warning"), Loc.Instance.GetString("Remove this Item?"), MessageBoxButtons.YesNo, null)
== DialogResult.Yes)
{
if (ListOfStrings.SelectedItem != null)
{
ListOfStrings.Items.Remove (ListOfStrings.SelectedItem);
}
}
}
/// <summary>
/// returns the number of tree nodes selected
/// </summary>
public int NumberOfSelected
{
get { if (ListOfStrings.SelectedItem != null) return 1; else return 0; }
}
/// <summary>
/// returns the strings that are selected
/// </summary>
public string[] SelectedStrings
{
get { return new string[1] { ListOfStrings.SelectedItem.ToString ()}; }
}
private void treeView1_DoubleClick(object sender, EventArgs e)
{
// send event to calling form that double clicked occured
// only applicable when being used for keywords
if (DataChanged != null)
{
DataChanged(null, null);
}
}
// Class that contains the data for
// the alarm event. Derives from System.EventArgs.
// THIS CLASS CAN BE USED FOR MOST OF MY CUSTOM EVENTS
public class CustomEventArgs : EventArgs
{
private string sMessage;
//Constructor.
//
public CustomEventArgs(string sMessage)
{
this.sMessage = sMessage;
}
public string Message
{
get { return sMessage; }
}
}
// Delegate declaration.
// This delegate can be used for most of my custom events
public delegate void CustomEventHandler(object sender, CustomEventArgs e);
// A custom event
public virtual event CustomEventHandler DataChanged;
// The protected OnAlarm method raises the event by invoking
// the delegates. The sender is always this, the current instance
// of the class.
//
protected void OnDataChange(CustomEventArgs e)
{
if (DataChanged != null)
{
// Invokes the delegates.
DataChanged(this, e);
}
}
}
#endregion
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// List Email
///<para>SObject Name: ListEmail</para>
///<para>Custom Object: False</para>
///</summary>
public class SfListEmail : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "ListEmail"; }
}
///<summary>
/// List Email ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Owner ID
/// <para>Name: OwnerId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "ownerId")]
public string OwnerId { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Name
/// <para>Name: Name</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Last Viewed Date
/// <para>Name: LastViewedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastViewedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastViewedDate { get; set; }
///<summary>
/// Last Referenced Date
/// <para>Name: LastReferencedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastReferencedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastReferencedDate { get; set; }
///<summary>
/// Subject
/// <para>Name: Subject</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "subject")]
public string Subject { get; set; }
///<summary>
/// Html Body
/// <para>Name: HtmlBody</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "htmlBody")]
public string HtmlBody { get; set; }
///<summary>
/// Text Body
/// <para>Name: TextBody</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "textBody")]
public string TextBody { get; set; }
///<summary>
/// From Name
/// <para>Name: FromName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "fromName")]
public string FromName { get; set; }
///<summary>
/// From Address
/// <para>Name: FromAddress</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "fromAddress")]
public string FromAddress { get; set; }
///<summary>
/// Status
/// <para>Name: Status</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "status")]
public string Status { get; set; }
///<summary>
/// Has Attachment
/// <para>Name: HasAttachment</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "hasAttachment")]
[Updateable(false), Createable(false)]
public bool? HasAttachment { get; set; }
///<summary>
/// Scheduled Date
/// <para>Name: ScheduledDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "scheduledDate")]
public DateTimeOffset? ScheduledDate { get; set; }
///<summary>
/// Total Sent
/// <para>Name: TotalSent</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "totalSent")]
[Updateable(false), Createable(false)]
public int? TotalSent { get; set; }
///<summary>
/// Campaign ID
/// <para>Name: CampaignId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "campaignId")]
public string CampaignId { get; set; }
///<summary>
/// ReferenceTo: Campaign
/// <para>RelationshipName: Campaign</para>
///</summary>
[JsonProperty(PropertyName = "campaign")]
[Updateable(false), Createable(false)]
public SfCampaign Campaign { get; set; }
///<summary>
/// Is Tracked
/// <para>Name: IsTracked</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isTracked")]
[Updateable(false), Createable(false)]
public bool? IsTracked { get; set; }
}
}
| |
using System;
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace com.google.zxing.qrcode.encoder
{
/// <summary>
/// @author Satoru Takabayashi
/// @author Daniel Switkin
/// @author Sean Owen
/// </summary>
internal sealed class MaskUtil
{
// Penalty weights from section 6.8.2.1
private const int N1 = 3;
private const int N2 = 3;
private const int N3 = 40;
private const int N4 = 10;
private MaskUtil()
{
// do nothing
}
/// <summary>
/// Apply mask penalty rule 1 and return the penalty. Find repetitive cells with the same color and
/// give penalty to them. Example: 00000 or 11111.
/// </summary>
internal static int applyMaskPenaltyRule1(ByteMatrix matrix)
{
return applyMaskPenaltyRule1Internal(matrix, true) + applyMaskPenaltyRule1Internal(matrix, false);
}
/// <summary>
/// Apply mask penalty rule 2 and return the penalty. Find 2x2 blocks with the same color and give
/// penalty to them. This is actually equivalent to the spec's rule, which is to find MxN blocks and give a
/// penalty proportional to (M-1)x(N-1), because this is the number of 2x2 blocks inside such a block.
/// </summary>
internal static int applyMaskPenaltyRule2(ByteMatrix matrix)
{
int penalty = 0;
sbyte[][] array = matrix.Array;
int width = matrix.Width;
int height = matrix.Height;
for (int y = 0; y < height - 1; y++)
{
for (int x = 0; x < width - 1; x++)
{
int value = array[y][x];
if (value == array[y][x + 1] && value == array[y + 1][x] && value == array[y + 1][x + 1])
{
penalty++;
}
}
}
return N2 * penalty;
}
/// <summary>
/// Apply mask penalty rule 3 and return the penalty. Find consecutive cells of 00001011101 or
/// 10111010000, and give penalty to them. If we find patterns like 000010111010000, we give
/// penalties twice (i.e. 40 * 2).
/// </summary>
internal static int applyMaskPenaltyRule3(ByteMatrix matrix)
{
int penalty = 0;
sbyte[][] array = matrix.Array;
int width = matrix.Width;
int height = matrix.Height;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// Tried to simplify following conditions but failed.
if (x + 6 < width && array[y][x] == 1 && array[y][x + 1] == 0 && array[y][x + 2] == 1 && array[y][x + 3] == 1 && array[y][x + 4] == 1 && array[y][x + 5] == 0 && array[y][x + 6] == 1 && ((x + 10 < width && array[y][x + 7] == 0 && array[y][x + 8] == 0 && array[y][x + 9] == 0 && array[y][x + 10] == 0) || (x - 4 >= 0 && array[y][x - 1] == 0 && array[y][x - 2] == 0 && array[y][x - 3] == 0 && array[y][x - 4] == 0)))
{
penalty += N3;
}
if (y + 6 < height && array[y][x] == 1 && array[y + 1][x] == 0 && array[y + 2][x] == 1 && array[y + 3][x] == 1 && array[y + 4][x] == 1 && array[y + 5][x] == 0 && array[y + 6][x] == 1 && ((y + 10 < height && array[y + 7][x] == 0 && array[y + 8][x] == 0 && array[y + 9][x] == 0 && array[y + 10][x] == 0) || (y - 4 >= 0 && array[y - 1][x] == 0 && array[y - 2][x] == 0 && array[y - 3][x] == 0 && array[y - 4][x] == 0)))
{
penalty += N3;
}
}
}
return penalty;
}
/// <summary>
/// Apply mask penalty rule 4 and return the penalty. Calculate the ratio of dark cells and give
/// penalty if the ratio is far from 50%. It gives 10 penalty for 5% distance.
/// </summary>
internal static int applyMaskPenaltyRule4(ByteMatrix matrix)
{
int numDarkCells = 0;
sbyte[][] array = matrix.Array;
int width = matrix.Width;
int height = matrix.Height;
for (int y = 0; y < height; y++)
{
sbyte[] arrayY = array[y];
for (int x = 0; x < width; x++)
{
if (arrayY[x] == 1)
{
numDarkCells++;
}
}
}
int numTotalCells = matrix.Height * matrix.Width;
double darkRatio = (double) numDarkCells / numTotalCells;
int fivePercentVariances = (int)(Math.Abs(darkRatio - 0.5) * 20.0); // * 100.0 / 5.0
return fivePercentVariances * N4;
}
/// <summary>
/// Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask
/// pattern conditions.
/// </summary>
internal static bool getDataMaskBit(int maskPattern, int x, int y)
{
int intermediate;
int temp;
switch (maskPattern)
{
case 0:
intermediate = (y + x) & 0x1;
break;
case 1:
intermediate = y & 0x1;
break;
case 2:
intermediate = x % 3;
break;
case 3:
intermediate = (y + x) % 3;
break;
case 4:
intermediate = (((int)((uint)y >> 1)) + (x / 3)) & 0x1;
break;
case 5:
temp = y * x;
intermediate = (temp & 0x1) + (temp % 3);
break;
case 6:
temp = y * x;
intermediate = ((temp & 0x1) + (temp % 3)) & 0x1;
break;
case 7:
temp = y * x;
intermediate = ((temp % 3) + ((y + x) & 0x1)) & 0x1;
break;
default:
throw new System.ArgumentException("Invalid mask pattern: " + maskPattern);
}
return intermediate == 0;
}
/// <summary>
/// Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both
/// vertical and horizontal orders respectively.
/// </summary>
private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix, bool isHorizontal)
{
int penalty = 0;
int iLimit = isHorizontal ? matrix.Height : matrix.Width;
int jLimit = isHorizontal ? matrix.Width : matrix.Height;
sbyte[][] array = matrix.Array;
for (int i = 0; i < iLimit; i++)
{
int numSameBitCells = 0;
int prevBit = -1;
for (int j = 0; j < jLimit; j++)
{
int bit = isHorizontal ? array[i][j] : array[j][i];
if (bit == prevBit)
{
numSameBitCells++;
}
else
{
if (numSameBitCells >= 5)
{
penalty += N1 + (numSameBitCells - 5);
}
numSameBitCells = 1; // Include the cell itself.
prevBit = bit;
}
}
if (numSameBitCells > 5)
{
penalty += N1 + (numSameBitCells - 5);
}
}
return penalty;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="PrintControllerWithStatusDialog.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Diagnostics;
using System;
using System.Threading;
using System.Drawing;
using Microsoft.Win32;
using System.ComponentModel;
using System.Drawing.Printing;
using System.Security;
using System.Security.Permissions;
/// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class PrintControllerWithStatusDialog : PrintController {
private PrintController underlyingController;
private PrintDocument document;
private BackgroundThread backgroundThread;
private int pageNumber;
private string dialogTitle;
/// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog.PrintControllerWithStatusDialog"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public PrintControllerWithStatusDialog(PrintController underlyingController)
: this(underlyingController, SR.GetString(SR.PrintControllerWithStatusDialog_DialogTitlePrint)) {
}
/// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog.PrintControllerWithStatusDialog1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public PrintControllerWithStatusDialog(PrintController underlyingController, string dialogTitle) {
this.underlyingController = underlyingController;
this.dialogTitle = dialogTitle;
}
/// <include file='doc\PreviewPrintController.uex' path='docs/doc[@for="PreviewPrintController.IsPreview"]/*' />
/// <devdoc>
/// <para>
/// This is new public property which notifies if this controller is used for PrintPreview.. so get the underlying Controller
/// and return its IsPreview Property.
/// </para>
/// </devdoc>
public override bool IsPreview {
get {
if (underlyingController != null)
{
return underlyingController.IsPreview;
}
return false;
}
}
/// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog.OnStartPrint"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Implements StartPrint by delegating to the underlying controller.
/// </para>
/// </devdoc>
public override void OnStartPrint(PrintDocument document, PrintEventArgs e) {
base.OnStartPrint(document, e);
this.document = document;
pageNumber = 1;
if (SystemInformation.UserInteractive) {
backgroundThread = new BackgroundThread(this); // starts running & shows dialog automatically
}
// OnStartPrint does the security check... lots of
// extra setup to make sure that we tear down
// correctly...
//
try {
underlyingController.OnStartPrint(document, e);
}
catch {
if (backgroundThread != null) {
backgroundThread.Stop();
}
throw;
}
finally {
if (backgroundThread != null && backgroundThread.canceled) {
e.Cancel = true;
}
}
}
/// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog.OnStartPage"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Implements StartPage by delegating to the underlying controller.
/// </para>
/// </devdoc>
public override Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e) {
base.OnStartPage(document, e);
if (backgroundThread != null) {
backgroundThread.UpdateLabel();
}
Graphics result = underlyingController.OnStartPage(document, e);
if (backgroundThread != null && backgroundThread.canceled){
e.Cancel = true;
}
return result;
}
/// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog.OnEndPage"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Implements EndPage by delegating to the underlying controller.
/// </para>
/// </devdoc>
public override void OnEndPage(PrintDocument document, PrintPageEventArgs e) {
underlyingController.OnEndPage(document, e);
if (backgroundThread != null && backgroundThread.canceled) {
e.Cancel = true;
}
pageNumber++;
base.OnEndPage(document, e);
}
/// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog.OnEndPrint"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Implements EndPrint by delegating to the underlying controller.
/// </para>
/// </devdoc>
public override void OnEndPrint(PrintDocument document, PrintEventArgs e) {
underlyingController.OnEndPrint(document, e);
if (backgroundThread != null && backgroundThread.canceled) {
e.Cancel = true;
}
if (backgroundThread != null) {
backgroundThread.Stop();
}
base.OnEndPrint(document, e);
}
private class BackgroundThread {
private PrintControllerWithStatusDialog parent;
private StatusDialog dialog;
private Thread thread;
internal bool canceled = false;
private bool alreadyStopped = false;
// Called from any thread
internal BackgroundThread(PrintControllerWithStatusDialog parent) {
this.parent = parent;
// Calling Application.DoEvents() from within a paint event causes all sorts of problems,
// so we need to put the dialog on its own thread.
thread = new Thread(new ThreadStart(Run));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
// on correct thread
[
UIPermission(SecurityAction.Assert, Window=UIPermissionWindow.AllWindows),
SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.UnmanagedCode),
]
private void Run() {
// SECREVIEW : need all permissions to make the window not get adorned...
//
try {
lock (this) {
if (alreadyStopped) {
return;
}
dialog = new StatusDialog(this, parent.dialogTitle);
ThreadUnsafeUpdateLabel();
dialog.Visible = true;
}
if (!alreadyStopped) {
Application.Run(dialog);
}
}
finally {
lock (this) {
if (dialog != null) {
dialog.Dispose();
dialog = null;
}
}
}
}
// Called from any thread
internal void Stop() {
lock (this) {
if (dialog != null && dialog.IsHandleCreated) {
dialog.BeginInvoke(new MethodInvoker(dialog.Close));
return;
}
alreadyStopped = true;
}
}
// on correct thread
private void ThreadUnsafeUpdateLabel() {
// "page {0} of {1}"
dialog.label1.Text = SR.GetString(SR.PrintControllerWithStatusDialog_NowPrinting,
parent.pageNumber, parent.document.DocumentName);
}
// Called from any thread
internal void UpdateLabel() {
if (dialog != null && dialog.IsHandleCreated) {
dialog.BeginInvoke(new MethodInvoker(ThreadUnsafeUpdateLabel));
// Don't wait for a response
}
}
}
private class StatusDialog : Form {
internal Label label1;
private Button button1;
private BackgroundThread backgroundThread;
internal StatusDialog(BackgroundThread backgroundThread, string dialogTitle) {
InitializeComponent();
this.backgroundThread = backgroundThread;
this.Text = dialogTitle;
this.MinimumSize = Size;
}
/// <devdoc>
/// Tells whether the current resources for this dll have been
/// localized for a RTL language.
/// </devdoc>
private static bool IsRTLResources {
get {
return SR.GetString(SR.RTL) != "RTL_False";
}
}
private void InitializeComponent() {
if (IsRTLResources)
{
this.RightToLeft = RightToLeft.Yes;
}
this.label1 = new Label();
this.button1 = new Button();
label1.Location = new Point(8, 16);
label1.TextAlign = ContentAlignment.MiddleCenter;
label1.Size = new Size(240, 64);
label1.TabIndex = 1;
label1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
button1.Size = new Size(75, 23);
button1.TabIndex = 0;
button1.Text = SR.GetString(SR.PrintControllerWithStatusDialog_Cancel);
button1.Location = new Point(88, 88);
button1.Anchor = AnchorStyles.Bottom;
button1.Click += new EventHandler(button1_Click);
this.AutoScaleDimensions = new Size(6, 13);
this.AutoScaleMode = AutoScaleMode.Font;
this.MaximizeBox = false;
this.ControlBox = false;
this.MinimizeBox = false;
this.ClientSize = new Size(256, 122);
this.CancelButton = button1;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Controls.Add(label1);
this.Controls.Add(button1);
}
private void button1_Click(object sender, System.EventArgs e) {
button1.Enabled = false;
label1.Text = SR.GetString(SR.PrintControllerWithStatusDialog_Canceling);
backgroundThread.canceled = true;
}
}
}
}
| |
using DevExpress.Internal;
using DevExpress.Mvvm.DataAnnotations;
using DevExpress.Mvvm.Native;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace DevExpress.Mvvm.Native {
public static class ViewModelSourceHelper {
public static Type GetProxyType(Type type) {
return DevExpress.Mvvm.POCO.ViewModelSource.GetPOCOType(type);
}
public static object Create(Type type) {
return DevExpress.Mvvm.POCO.ViewModelSource.Create(type);
}
public static bool IsPOCOViewModelType(Type type) {
return DevExpress.Mvvm.POCO.ViewModelSource.IsPOCOViewModelType(type);
}
public static ConstructorInfo FindConstructorWithAllOptionalParameters(Type type) {
return DevExpress.Mvvm.POCO.ViewModelSource.FindConstructorWithAllOptionalParameters(type);
}
}
}
namespace DevExpress.Mvvm.POCO {
public interface IPOCOViewModel {
void RaisePropertyChanged(string propertyName);
}
public class ViewModelSource {
#region error messages
internal const string Error_ObjectDoesntImplementIPOCOViewModel = "Object doesn't implement IPOCOViewModel.";
internal const string Error_CommandNotFound = "Command not found: {0}.";
internal const string Error_CommandNotAsync = "Command is not async";
const string Error_ConstructorNotFound = "Constructor not found.";
const string Error_TypeHasNoCtors = "Type has no accessible constructors: {0}.";
const string Error_SealedClass = "Cannot create dynamic class for the sealed class: {0}.";
const string Error_InternalClass = "Cannot create dynamic class for the internal class: {0}.";
const string Error_TypeImplementsIPOCOViewModel = "Type cannot implement IPOCOViewModel: {0}.";
const string Error_RaisePropertyChangedMethodNotFound = "Class already supports INotifyPropertyChanged, but RaisePropertyChanged(string) method not found: {0}.";
const string Error_PropertyIsNotVirual = "Cannot make non-virtual property bindable: {0}.";
const string Error_PropertyHasInternalSetter = "Cannot make property with internal setter bindable: {0}.";
const string Error_PropertyHasNoSetter = "Cannot make property without setter bindable: {0}.";
const string Error_PropertyHasNoGetter = "Cannot make property without public getter bindable: {0}.";
const string Error_PropertyIsFinal = "Cannot override final property: {0}.";
const string Error_MoreThanOnePropertyChangedMethod = "More than one property changed method: {0}.";
const string Error_PropertyChangedMethodShouldBePublicOrProtected = "Property changed method should be public or protected: {0}.";
const string Error_PropertyChangedCantHaveMoreThanOneParameter = "Property changed method cannot have more than one parameter: {0}.";
const string Error_PropertyChangedCantHaveReturnType = "Property changed method cannot have return type: {0}.";
const string Error_PropertyChangedMethodArgumentTypeShouldMatchPropertyType = "Property changed method argument type should match property type: {0}.";
const string Error_PropertyChangedMethodNotFound = "Property changed method not found: {0}.";
const string Error_MemberWithSameCommandNameAlreadyExists = "Member with the same command name already exists: {0}.";
const string Error_PropertyTypeShouldBeServiceType = "Service properties should have an interface type: {0}.";
const string Error_CantAccessProperty = "Cannot access property: {0}.";
const string Error_PropertyIsNotVirtual = "Property is not virtual: {0}.";
const string Error_PropertyHasSetter = "Property with setter cannot be Service Property: {0}.";
const string Error_ConstructorExpressionCanReferOnlyToItsArguments = "Constructor expression can refer only to its arguments.";
const string Error_ConstructorExpressionCanOnlyBeOfNewExpressionType = "Constructor expression can only be of NewExpression type.";
const string Error_IDataErrorInfoAlreadyImplemented = "The IDataErrorInfo interface is already implemented.";
#endregion
static readonly Dictionary<Type, ICustomAttributeBuilderProvider> attributeBuilderProviders = new Dictionary<Type, ICustomAttributeBuilderProvider>();
static ViewModelSource() {
RegisterAttributeBuilderProvider(new DisplayAttributeBuilderProvider());
#if !SILVERLIGHT
RegisterAttributeBuilderProvider(new DisplayNameAttributeBuilderProvider());
RegisterAttributeBuilderProvider(new ScaffoldColumnAttributeBuilderProvider());
#endif
}
static void RegisterAttributeBuilderProvider(ICustomAttributeBuilderProvider provider) {
attributeBuilderProviders[provider.AttributeType] = provider;
}
static readonly Dictionary<Type, Type> types = new Dictionary<Type, Type>();
static readonly Dictionary<Assembly, ModuleBuilder> builders = new Dictionary<Assembly, ModuleBuilder>();
static readonly Dictionary<Type, object> Factories = new Dictionary<Type, object>();
public static T Create<T>() where T : class, new() {
return Factory(() => new T())();
}
public static T Create<T>(Expression<Func<T>> constructorExpression) where T : class {
ValidateCtorExpression(constructorExpression, false);
var actualAxpression = GetCtorExpression(constructorExpression, typeof(T), false);
return Expression.Lambda<Func<T>>(actualAxpression).Compile()();
}
#region GetFactory
public static Func<TResult> Factory<TResult>(Expression<Func<TResult>> constructorExpression) where TResult : class {
return GetFactoryCore(constructorExpression, typeof(TResult));
}
public static Func<T1, TResult> Factory<T1, TResult>(Expression<Func<T1, TResult>> constructorExpression) where TResult : class {
return GetFactoryCore(constructorExpression, typeof(TResult));
}
public static Func<T1, T2, TResult> Factory<T1, T2, TResult>(Expression<Func<T1, T2, TResult>> constructorExpression) where TResult : class {
return GetFactoryCore(constructorExpression, typeof(TResult));
}
public static Func<T1, T2, T3, TResult> Factory<T1, T2, T3, TResult>(Expression<Func<T1, T2, T3, TResult>> constructorExpression) where TResult : class {
return GetFactoryCore(constructorExpression, typeof(TResult));
}
public static Func<T1, T2, T3, T4, TResult> Factory<T1, T2, T3, T4, TResult>(Expression<Func<T1, T2, T3, T4, TResult>> constructorExpression) where TResult : class {
return GetFactoryCore(constructorExpression, typeof(TResult));
}
public static Func<T1, T2, T3, T4, T5, TResult> Factory<T1, T2, T3, T4, T5, TResult>(Expression<Func<T1, T2, T3, T4, T5, TResult>> constructorExpression) where TResult : class {
return GetFactoryCore(constructorExpression, typeof(TResult));
}
public static Func<T1, T2, T3, T4, T5, T6, TResult> Factory<T1, T2, T3, T4, T5, T6, TResult>(Expression<Func<T1, T2, T3, T4, T5, T6, TResult>> constructorExpression) where TResult : class {
return GetFactoryCore(constructorExpression, typeof(TResult));
}
public static Func<T1, T2, T3, T4, T5, T6, T7, TResult> Factory<T1, T2, T3, T4, T5, T6, T7, TResult>(Expression<Func<T1, T2, T3, T4, T5, T6, T7, TResult>> constructorExpression) where TResult : class {
return GetFactoryCore(constructorExpression, typeof(TResult));
}
public static Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> Factory<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult>> constructorExpression) where TResult : class {
return GetFactoryCore(constructorExpression, typeof(TResult));
}
public static Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> Factory<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>(Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>> constructorExpression) where TResult : class {
return GetFactoryCore(constructorExpression, typeof(TResult));
}
public static Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult> Factory<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>(Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>> constructorExpression) where TResult : class {
return GetFactoryCore(constructorExpression, typeof(TResult));
}
#endregion
#region helpers
static TDelegate GetFactoryCore<TDelegate>(Expression<TDelegate> constructorExpression, Type resultType) {
ValidateCtorExpression(constructorExpression, true);
return GetFactoryCore<TDelegate>(() => CreateFactory(constructorExpression, resultType));
}
internal static TDelegate GetFactoryCore<TDelegate>(Func<TDelegate> createFactoryDelegate) {
return (TDelegate)Factories.GetOrAdd(typeof(TDelegate), () => createFactoryDelegate());
}
static TDelegate CreateFactory<TDelegate>(Expression<TDelegate> constructorExpression, Type resultType) {
var actualAxpression = GetCtorExpression(constructorExpression, resultType, true);
return Expression.Lambda<TDelegate>(actualAxpression, constructorExpression.Parameters).Compile();
}
static void ValidateCtorExpression(LambdaExpression constructorExpression, bool useOnlyParameters) {
NewExpression newExpression = constructorExpression.Body as NewExpression;
if(newExpression != null) {
if(useOnlyParameters) {
foreach(var item in newExpression.Arguments) {
if(!(item is ParameterExpression))
throw new ViewModelSourceException(Error_ConstructorExpressionCanReferOnlyToItsArguments);
}
}
return;
}
if(!useOnlyParameters) {
MemberInitExpression memberInitExpression = constructorExpression.Body as MemberInitExpression;
if(memberInitExpression != null) {
return;
}
}
throw new ViewModelSourceException(Error_ConstructorExpressionCanOnlyBeOfNewExpressionType);
}
static Expression GetCtorExpression(LambdaExpression constructorExpression, Type resultType, bool useOnlyParameters) {
Type type = GetPOCOType(resultType);
NewExpression newExpression = constructorExpression.Body as NewExpression;
if(newExpression != null) {
return GetNewExpression(type, newExpression);
}
MemberInitExpression memberInitExpression = constructorExpression.Body as MemberInitExpression;
if(memberInitExpression != null) {
return Expression.MemberInit(GetNewExpression(type, memberInitExpression.NewExpression), memberInitExpression.Bindings);
}
throw new ArgumentException("constructorExpression");
}
static NewExpression GetNewExpression(Type type, NewExpression newExpression) {
var actualCtor = GetConstructor(type, newExpression.Constructor.GetParameters().Select(x => x.ParameterType).ToArray());
return Expression.New(actualCtor, newExpression.Arguments);
}
internal static object Create(Type type) {
Type pocoType = GetPOCOType(type);
var defaultCtor = pocoType.GetConstructor(new Type[0]);
if(defaultCtor != null)
return defaultCtor.Invoke(null);
defaultCtor = FindConstructorWithAllOptionalParameters(type);
if(defaultCtor != null)
return pocoType.GetConstructor(defaultCtor.GetParameters().Select(x => x.ParameterType).ToArray()).Invoke(defaultCtor.GetParameters().Select(x => x.DefaultValue).ToArray());
return Activator.CreateInstance(GetPOCOType(type));
}
internal static ConstructorInfo FindConstructorWithAllOptionalParameters(Type type) {
return type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.FirstOrDefault(x => (x.Attributes.HasFlag(MethodAttributes.Public) || x.Attributes.HasFlag(MethodAttributes.Family)) && x.GetParameters().All(y => y.IsOptional));
}
public static Type GetPOCOType(Type type) {
return types.GetOrAdd(type, () => CreateType(type));
}
internal static ConstructorInfo GetConstructor(Type proxyType, Type[] argsTypes) {
var ctor = proxyType.GetConstructor(argsTypes ?? Type.EmptyTypes);
if(ctor == null)
throw new ViewModelSourceException(Error_ConstructorNotFound);
return ctor;
}
static bool CanAccessFromDescendant(MethodBase method) {
return method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly;
}
internal static bool IsPOCOViewModelType(Type type) {
try {
if(!CheckType(type, false))
return false;
if(type.GetCustomAttributes(typeof(POCOViewModelAttribute), true).Any())
return true;
if(GetCommandMethods(type).Any() && !type.GetProperties().Where(x => typeof(ICommand).IsAssignableFrom(x.PropertyType)).Any())
return true;
if(GetBindableProperties(type).Any() && !typeof(INotifyPropertyChanged).IsAssignableFrom(type))
return true;
return false;
} catch {
return false;
}
}
#endregion
static Type CreateType(Type type) {
CheckType(type, true);
ModuleBuilder moduleBuilder = GetModuleBuilder(type.Assembly);
TypeBuilder typeBuilder = CreateTypeBuilder(moduleBuilder, type);
BuildConstructors(type, typeBuilder);
var raisePropertyChangedMethod = ImplementINotifyPropertyChanged(type, typeBuilder);
ImplementIPOCOViewModel(typeBuilder, raisePropertyChangedMethod);
BuildBindableProperties(type, typeBuilder, raisePropertyChangedMethod);
BuildCommands(type, typeBuilder);
ImplementISupportServices(type, typeBuilder);
ImplementISupportParentViewModel(type, typeBuilder);
BuildServiceProperties(type, typeBuilder);
ImplementIDataErrorInfo(type, typeBuilder);
return typeBuilder.CreateType();
}
static MethodBuilder BuildExplicitStringGetterOverride(TypeBuilder typeBuilder, string propertyName, MethodInfo methodToCall, Type interfaceType, Type argument = null) {
MethodAttributes methodAttributes =
MethodAttributes.Private
| MethodAttributes.Virtual
| MethodAttributes.Final
| MethodAttributes.HideBySig
| MethodAttributes.NewSlot
| MethodAttributes.SpecialName;
var method = typeBuilder.DefineMethod(interfaceType.FullName + ".get_" + propertyName,
methodAttributes,
typeof(string), argument != null ? new[] { argument } : Type.EmptyTypes);
ILGenerator gen = method.GetILGenerator();
if(methodToCall != null) {
gen.Emit(OpCodes.Ldarg_0);
if(argument != null)
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Call, methodToCall);
} else {
gen.Emit(OpCodes.Ldsfld, typeof(string).GetField("Empty"));
}
gen.Emit(OpCodes.Ret);
typeBuilder.DefineMethodOverride(method, interfaceType.GetProperty(propertyName).GetGetMethod());
return method;
}
static bool ShouldImplementIDataErrorInfo(Type type) {
var pocoViewModelAttr = (POCOViewModelAttribute)type.GetCustomAttributes(typeof(POCOViewModelAttribute), false).FirstOrDefault();
bool implement = pocoViewModelAttr == null ? false : pocoViewModelAttr.ImplementIDataErrorInfo;
if(type.GetInterfaces().Contains(typeof(IDataErrorInfo)) && implement)
throw new ViewModelSourceException(Error_IDataErrorInfoAlreadyImplemented);
return implement;
}
static void ImplementIDataErrorInfo(Type type, TypeBuilder typeBuilder) {
if(!ShouldImplementIDataErrorInfo(type))
return;
var errorGetter = BuildExplicitStringGetterOverride(typeBuilder, "Error", null, typeof(IDataErrorInfo));
var errorProperty = typeBuilder.DefineProperty("Error", PropertyAttributes.None, typeof(string), new Type[0]);
errorProperty.SetGetMethod(errorGetter);
var indexerGetterImpl = typeof(IDataErrorInfoHelper).GetMethod("GetErrorText", BindingFlags.Public | BindingFlags.Static);
var indexerGetter = BuildExplicitStringGetterOverride(typeBuilder, "Item", indexerGetterImpl, typeof(IDataErrorInfo), typeof(string));
var indexer = typeBuilder.DefineProperty("Item", PropertyAttributes.None, typeof(string), new[] { typeof(string) });
indexer.SetGetMethod(indexerGetter);
ConstructorInfo ciDefaultMemberAttribute = typeof(DefaultMemberAttribute).GetConstructor(new Type[] { typeof(string) });
CustomAttributeBuilder abDefaultMemberAttribute = new CustomAttributeBuilder(ciDefaultMemberAttribute, new object[] { "Item" });
typeBuilder.SetCustomAttribute(abDefaultMemberAttribute);
}
private static bool CheckType(Type type, bool @throw) {
if(!type.IsPublic && !type.IsNestedPublic)
return ReturnFalseOrThrow(@throw, Error_InternalClass, type);
if(type.IsSealed)
return ReturnFalseOrThrow(@throw, Error_SealedClass, type);
if(typeof(IPOCOViewModel).IsAssignableFrom(type))
return ReturnFalseOrThrow(@throw, Error_TypeImplementsIPOCOViewModel, type);
return true;
}
static ModuleBuilder GetModuleBuilder(Assembly assembly) {
return builders.GetOrAdd(assembly, () => CreateBuilder());
}
static ModuleBuilder CreateBuilder() {
var assemblyName = new AssemblyName();
assemblyName.Name = AssemblyInfo.SRAssemblyXpfMvvm + ".DynamicTypes." + Guid.NewGuid().ToString();
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
return assemblyBuilder.DefineDynamicModule(assemblyName.Name, false);
}
#region constructors
static void BuildConstructors(Type type, TypeBuilder typeBuilder) {
var ctors = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(x => CanAccessFromDescendant(x)).ToArray();
if(!ctors.Any()) {
throw new ViewModelSourceException(string.Format(Error_TypeHasNoCtors, type.Name));
}
foreach(ConstructorInfo constructor in ctors) {
BuildConstructor(typeBuilder, constructor);
}
}
static ConstructorBuilder BuildConstructor(TypeBuilder type, ConstructorInfo baseConstructor) {
MethodAttributes methodAttributes =
MethodAttributes.Public;
var parameters = baseConstructor.GetParameters();
ConstructorBuilder method = type.DefineConstructor(methodAttributes, CallingConventions.Standard, parameters.Select(x => x.ParameterType).ToArray());
ILGenerator gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
for(int i = 0; i < parameters.Length; i++) {
gen.Emit(OpCodes.Ldarg_S, i + 1);
}
gen.Emit(OpCodes.Call, baseConstructor);
gen.Emit(OpCodes.Ret);
return method;
}
#endregion
#region bindable properties
static void BuildBindableProperties(Type type, TypeBuilder typeBuilder, MethodInfo raisePropertyChangedMethod) {
foreach(var propertyInfo in GetBindableProperties(type)) {
var getter = BuildBindablePropertyGetter(typeBuilder, propertyInfo.GetGetMethod());
typeBuilder.DefineMethodOverride(getter, propertyInfo.GetGetMethod());
MethodInfo propertyChangedMethod = GetPropertyChangedMethod(type, propertyInfo, "Changed", x => x.OnPropertyChangedMethodName, x => x.OnPropertyChangedMethod);
MethodInfo propertyChangingMethod = GetPropertyChangedMethod(type, propertyInfo, "Changing", x => x.OnPropertyChangingMethodName, x => x.OnPropertyChangingMethod);
var setter = BuildBindablePropertySetter(typeBuilder, raisePropertyChangedMethod, propertyInfo, propertyChangedMethod, propertyChangingMethod);
typeBuilder.DefineMethodOverride(setter, propertyInfo.GetSetMethod(true));
var newProperty = typeBuilder.DefineProperty(propertyInfo.Name, PropertyAttributes.None, propertyInfo.PropertyType, new Type[0]);
newProperty.SetGetMethod(getter);
newProperty.SetSetMethod(setter);
}
}
static IEnumerable<PropertyInfo> GetBindableProperties(Type type) {
return type.GetProperties().Where(x => IsBindableProperty(x));
}
static bool IsBindableProperty(PropertyInfo propertyInfo) {
var bindable = GetBindablePropertyAttribute(propertyInfo);
if(bindable != null && !bindable.IsBindable)
return false;
var getMethod = propertyInfo.GetGetMethod();
var setMethod = propertyInfo.GetSetMethod(true);
if(getMethod == null)
return ReturnFalseOrThrow(bindable, Error_PropertyHasNoGetter, propertyInfo);
if(!getMethod.IsVirtual)
return ReturnFalseOrThrow(bindable, Error_PropertyIsNotVirual, propertyInfo);
if(getMethod.IsFinal)
return ReturnFalseOrThrow(bindable, Error_PropertyIsFinal, propertyInfo);
if(setMethod == null)
return ReturnFalseOrThrow(bindable, Error_PropertyHasNoSetter, propertyInfo);
if(setMethod.IsAssembly)
return ReturnFalseOrThrow(bindable, Error_PropertyHasInternalSetter, propertyInfo);
if(!(IsAutoImplemented(propertyInfo)))
return bindable != null && bindable.IsBindable;
return true;
}
static BindablePropertyAttribute GetBindablePropertyAttribute(PropertyInfo propertyInfo) {
return GetAttribute<BindablePropertyAttribute>(propertyInfo);
}
static MethodInfo GetPropertyChangedMethod(Type type, PropertyInfo propertyInfo, string methodNameSuffix, Func<BindablePropertyAttribute, string> getMethodName, Func<BindablePropertyAttribute, MethodInfo> getMethod) {
var bindable = GetBindablePropertyAttribute(propertyInfo);
if(bindable != null && getMethod(bindable) != null) {
CheckOnChangedMethod(getMethod(bindable), propertyInfo.PropertyType);
return getMethod(bindable);
}
bool hasCustomPropertyChangedMethodName = bindable != null && !string.IsNullOrEmpty(getMethodName(bindable));
if(!hasCustomPropertyChangedMethodName && !(IsAutoImplemented(propertyInfo)))
return null;
string onChangedMethodName = hasCustomPropertyChangedMethodName ? getMethodName(bindable) : "On" + propertyInfo.Name + methodNameSuffix;
MethodInfo[] changedMethods = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.Name == onChangedMethodName).ToArray();
if(changedMethods.Length > 1)
throw new ViewModelSourceException(string.Format(Error_MoreThanOnePropertyChangedMethod, propertyInfo.Name));
if(hasCustomPropertyChangedMethodName && !changedMethods.Any())
throw new ViewModelSourceException(string.Format(Error_PropertyChangedMethodNotFound, onChangedMethodName));
changedMethods.FirstOrDefault().Do(x => CheckOnChangedMethod(x, propertyInfo.PropertyType));
return changedMethods.FirstOrDefault();
}
static void CheckOnChangedMethod(MethodInfo method, Type propertyType) {
if(!CanAccessFromDescendant(method)) {
throw new ViewModelSourceException(string.Format(Error_PropertyChangedMethodShouldBePublicOrProtected, method.Name));
}
if(method.GetParameters().Length >= 2) {
throw new ViewModelSourceException(string.Format(Error_PropertyChangedCantHaveMoreThanOneParameter, method.Name));
}
if(method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType != propertyType) {
throw new ViewModelSourceException(string.Format(Error_PropertyChangedMethodArgumentTypeShouldMatchPropertyType, method.Name));
}
if(method.ReturnType != typeof(void)) {
throw new ViewModelSourceException(string.Format(Error_PropertyChangedCantHaveReturnType, method.Name));
}
}
static bool IsAutoImplemented(PropertyInfo property) {
if(property.GetGetMethod().GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any())
return true;
if(property.GetSetMethod(true).GetParameters().Single().Name != "AutoPropertyValue")
return false;
FieldInfo field = property.DeclaringType.GetField("_" + property.Name, BindingFlags.Instance | BindingFlags.NonPublic);
return field != null && field.FieldType == property.PropertyType && field.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any();
}
static MethodBuilder BuildBindablePropertyGetter(TypeBuilder type, MethodInfo originalGetter) {
MethodAttributes methodAttributes =
MethodAttributes.Public
| MethodAttributes.Virtual
| MethodAttributes.HideBySig;
MethodBuilder method = type.DefineMethod(originalGetter.Name, methodAttributes);
method.SetReturnType(originalGetter.ReturnType);
ILGenerator gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Call, originalGetter);
gen.Emit(OpCodes.Ret);
return method;
}
static MethodBuilder BuildBindablePropertySetter(TypeBuilder type, MethodInfo raisePropertyChangedMethod, PropertyInfo property, MethodInfo propertyChangedMethod, MethodInfo propertyChangingMethod) {
var setMethod = property.GetSetMethod(true);
MethodAttributes methodAttributes =
(setMethod.IsPublic ? MethodAttributes.Public : MethodAttributes.Family)
| MethodAttributes.Virtual
| MethodAttributes.HideBySig;
MethodBuilder method = type.DefineMethod(setMethod.Name, methodAttributes);
Expression<Action> equalsExpression = () => object.Equals(null, null);
method.SetReturnType(typeof(void));
method.SetParameters(property.PropertyType);
bool shouldBoxValues = property.PropertyType.IsValueType;
ILGenerator gen = method.GetILGenerator();
gen.DeclareLocal(property.PropertyType);
Label returnLabel = gen.DefineLabel();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Call, property.GetGetMethod());
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Ldloc_0);
if(shouldBoxValues)
gen.Emit(OpCodes.Box, property.PropertyType);
gen.Emit(OpCodes.Ldarg_1);
if(shouldBoxValues)
gen.Emit(OpCodes.Box, property.PropertyType);
gen.Emit(OpCodes.Call, ExpressionHelper.GetMethod(equalsExpression));
gen.Emit(OpCodes.Brtrue_S, returnLabel);
if(propertyChangingMethod != null) {
gen.Emit(OpCodes.Ldarg_0);
if(propertyChangingMethod.GetParameters().Length == 1)
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Call, propertyChangingMethod);
}
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Call, setMethod);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldstr, property.Name);
gen.Emit(OpCodes.Call, raisePropertyChangedMethod);
if(propertyChangedMethod != null) {
gen.Emit(OpCodes.Ldarg_0);
if(propertyChangedMethod.GetParameters().Length == 1)
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Call, propertyChangedMethod);
}
gen.MarkLabel(returnLabel);
gen.Emit(OpCodes.Ret);
return method;
}
#endregion
#region INotifyPropertyChanged implementation
static MethodBuilder BuildGetPropertyChangedHelperMethod(TypeBuilder type) {
FieldBuilder propertyChangedHelperField = type.DefineField("propertyChangedHelper", typeof(PropertyChangedHelper), FieldAttributes.Private);
MethodAttributes methodAttributes =
MethodAttributes.Private
| MethodAttributes.HideBySig;
MethodBuilder method = type.DefineMethod("GetHelper", methodAttributes);
Expression<Func<PropertyChangedHelper>> createHelperExpression = () => new PropertyChangedHelper();
ConstructorInfo helperCtor = ExpressionHelper.GetConstructor(createHelperExpression);
method.SetReturnType(typeof(PropertyChangedHelper));
ILGenerator gen = method.GetILGenerator();
gen.DeclareLocal(typeof(PropertyChangedHelper));
Label returnLabel = gen.DefineLabel();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, propertyChangedHelperField);
gen.Emit(OpCodes.Dup);
gen.Emit(OpCodes.Brtrue_S, returnLabel);
gen.Emit(OpCodes.Pop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Newobj, helperCtor);
gen.Emit(OpCodes.Dup);
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Stfld, propertyChangedHelperField);
gen.Emit(OpCodes.Ldloc_0);
gen.MarkLabel(returnLabel);
gen.Emit(OpCodes.Ret);
return method;
}
static MethodBuilder BuildRaisePropertyChangedMethod(TypeBuilder type, MethodInfo getHelperMethod) {
MethodAttributes methodAttributes =
MethodAttributes.Family
| MethodAttributes.HideBySig;
MethodBuilder method = type.DefineMethod("RaisePropertyChanged", methodAttributes);
Expression<Action> onPropertyChangedExpression = () => new PropertyChangedHelper().OnPropertyChanged(null, null);
method.SetReturnType(typeof(void));
method.SetParameters(typeof(String));
ILGenerator gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Call, getHelperMethod);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Callvirt, ExpressionHelper.GetMethod(onPropertyChangedExpression));
gen.Emit(OpCodes.Ret);
return method;
}
static MethodInfo ImplementINotifyPropertyChanged(Type baseType, TypeBuilder typeBuilder) {
MethodInfo raisePropertyChangedMethod;
if(typeof(INotifyPropertyChanged).IsAssignableFrom(baseType)) {
raisePropertyChangedMethod = baseType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
.FirstOrDefault(x => {
var parameters = x.GetParameters();
return x.Name == "RaisePropertyChanged" && CanAccessFromDescendant(x) && parameters.Length == 1 && parameters[0].ParameterType == typeof(string) && !parameters[0].IsOut && !parameters[0].ParameterType.IsByRef;
});
if(raisePropertyChangedMethod == null)
throw new ViewModelSourceException(string.Format(Error_RaisePropertyChangedMethodNotFound, baseType.Name));
} else {
var getHelperMethod = BuildGetPropertyChangedHelperMethod(typeBuilder);
raisePropertyChangedMethod = BuildRaisePropertyChangedMethod(typeBuilder, getHelperMethod);
var addHandler = BuildAddRemovePropertyChangedHandler(typeBuilder, getHelperMethod, "add", () => new PropertyChangedHelper().AddHandler(null));
typeBuilder.DefineMethodOverride(addHandler, typeof(INotifyPropertyChanged).GetMethod("add_PropertyChanged"));
var removeHandler = BuildAddRemovePropertyChangedHandler(typeBuilder, getHelperMethod, "remove", () => new PropertyChangedHelper().RemoveHandler(null));
typeBuilder.DefineMethodOverride(removeHandler, typeof(INotifyPropertyChanged).GetMethod("remove_PropertyChanged"));
}
return raisePropertyChangedMethod;
}
static MethodBuilder BuildAddRemovePropertyChangedHandler(TypeBuilder type, MethodInfo getHelperMethod, string methodName, Expression<Action> addRemoveHandlerExpression) {
MethodAttributes methodAttributes =
MethodAttributes.Private
| MethodAttributes.Virtual
| MethodAttributes.Final
| MethodAttributes.HideBySig
| MethodAttributes.NewSlot;
MethodBuilder method = type.DefineMethod(typeof(INotifyPropertyChanged).FullName + "." + methodName + "_PropertyChanged", methodAttributes);
method.SetReturnType(typeof(void));
method.SetParameters(typeof(PropertyChangedEventHandler));
ILGenerator gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Call, getHelperMethod);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Callvirt, ExpressionHelper.GetMethod(addRemoveHandlerExpression));
gen.Emit(OpCodes.Ret);
return method;
}
#endregion
#region IPOCOViewModel implementation
static void ImplementIPOCOViewModel(TypeBuilder typeBuilder, MethodInfo raisePropertyChangedMethod) {
var raisePropertyChangedMethodImplementation = BuildIPOCOViewModel_RaisePropertyChangedMethod(typeBuilder, raisePropertyChangedMethod);
IPOCOViewModel pocoViewModel = null;
Expression<Action> raisePropertyChangedExpression = () => pocoViewModel.RaisePropertyChanged(null);
typeBuilder.DefineMethodOverride(raisePropertyChangedMethodImplementation, ExpressionHelper.GetMethod(raisePropertyChangedExpression));
}
static MethodBuilder BuildIPOCOViewModel_RaisePropertyChangedMethod(TypeBuilder type, MethodInfo raisePropertyChangedMethod) {
MethodAttributes methodAttributes =
MethodAttributes.Private
| MethodAttributes.Virtual
| MethodAttributes.Final
| MethodAttributes.HideBySig
| MethodAttributes.NewSlot;
MethodBuilder method = type.DefineMethod("DevExpress.Mvvm.Native.IPOCOViewModel.RaisePropertyChanged", methodAttributes);
method.SetReturnType(typeof(void));
method.SetParameters(typeof(String));
ILGenerator gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Call, raisePropertyChangedMethod);
gen.Emit(OpCodes.Ret);
return method;
}
#endregion
static TypeBuilder CreateTypeBuilder(ModuleBuilder module, Type baseType) {
List<Type> interfaces = new List<Type>(new[] {
typeof(INotifyPropertyChanged),
typeof(IPOCOViewModel),
typeof(ISupportServices),
typeof(ISupportParentViewModel) });
if(ShouldImplementIDataErrorInfo(baseType)) {
interfaces.Add(typeof(IDataErrorInfo));
}
string typeName = baseType.Name + "_" + Guid.NewGuid().ToString().Replace('-', '_');
return module.DefineType(typeName, TypeAttributes.Public, baseType, interfaces.ToArray());
}
static T GetAttribute<T>(MemberInfo member) where T : Attribute {
return MetadataHelper.GetAttribute<T>(member);
}
static bool ReturnFalseOrThrow(Attribute attribute, string text, PropertyInfo property) {
if(attribute != null)
throw new ViewModelSourceException(string.Format(text, property.Name));
return false;
}
static bool ReturnFalseOrThrow(bool @throw, string text, Type type) {
if(@throw)
throw new ViewModelSourceException(string.Format(text, type.Name));
return false;
}
#region commands
static void BuildCommands(Type type, TypeBuilder typeBuilder) {
MethodInfo[] methods = GetCommandMethods(type).ToArray();
foreach(var commandMethod in methods) {
CommandAttribute attribute = ViewModelBase.GetAttribute<CommandAttribute>(commandMethod);
bool isAsyncCommand = commandMethod.ReturnType == typeof(Task);
string commandName = GetCommandName(commandMethod);
if(type.GetMember(commandName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public).Any() || methods.Any(x => GetCommandName(x) == commandName && x != commandMethod))
throw new ViewModelSourceException(string.Format(Error_MemberWithSameCommandNameAlreadyExists, commandName));
MethodInfo canExecuteMethod = GetCanExecuteMethod(type, commandMethod);
bool? useCommandManager = attribute != null ? attribute.GetUseCommandManager() : null;
var getMethod = BuildGetCommandMethod(typeBuilder, commandMethod, canExecuteMethod, commandName, useCommandManager, isAsyncCommand);
PropertyBuilder commandProperty = typeBuilder.DefineProperty(commandName,
PropertyAttributes.None,
getMethod.ReturnType,
null);
commandProperty.SetGetMethod(getMethod);
BuildCommandPropertyAttributes(commandProperty, commandMethod);
}
}
static IEnumerable<MethodInfo> GetCommandMethods(Type type) {
return type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic).Where(x => IsCommandMethod(type, x));
}
static bool IsCommandMethod(Type type, MethodInfo method) {
CommandAttribute attribute = ViewModelBase.GetAttribute<CommandAttribute>(method);
if(attribute != null && !attribute.IsCommand)
return false;
if(attribute == null) {
if(!method.IsPublic)
return false;
} else {
if(!CanAccessFromDescendant(method))
throw new ViewModelSourceException(string.Format(ViewModelBase.Error_MethodShouldBePublic, method.Name));
}
string commandName = GetCommandName(method);
if(method.IsSpecialName || method.DeclaringType == typeof(object) || type.GetProperty(commandName) != null)
return false;
if((method.ReturnType != typeof(void) && method.ReturnType != typeof(Task)) && attribute == null)
return false;
if(!ViewModelBase.ValidateCommandMethodParameters(method, x => new ViewModelSourceException(x)))
return false;
return true;
}
internal static string GetCommandName(MethodInfo method) {
CommandAttribute commandAttribute = ViewModelBase.GetAttribute<CommandAttribute>(method);
return (commandAttribute != null && !string.IsNullOrEmpty(commandAttribute.Name)) ? commandAttribute.Name : ViewModelBase.GetCommandName(method);
}
static MethodInfo GetCanExecuteMethod(Type type, MethodInfo method) {
return ViewModelBase.GetCanExecuteMethod(type, method, ViewModelBase.GetAttribute<CommandAttribute>(method), x => new ViewModelSourceException(x));
}
static MethodBuilder BuildGetCommandMethod(TypeBuilder type, MethodInfo commandMethod, MethodInfo canExecuteMethod, string commandName, bool? useCommandManager, bool isAsyncCommand) {
bool hasParameter = commandMethod.GetParameters().Length == 1;
bool isCommandMethodReturnTypeVoid = commandMethod.ReturnType == typeof(void);
Type commandMethodReturnType = commandMethod.ReturnType;
Type parameterType = hasParameter ? commandMethod.GetParameters()[0].ParameterType : null;
Type commandPropertyType = isAsyncCommand ?
hasParameter ? typeof(AsyncCommand<>).MakeGenericType(parameterType) : typeof(AsyncCommand)
: hasParameter ? typeof(DelegateCommand<>).MakeGenericType(parameterType) : typeof(ICommand);
var commandField = type.DefineField("_" + commandName, commandPropertyType, FieldAttributes.Private);
MethodAttributes methodAttributes =
MethodAttributes.Public | MethodAttributes.SpecialName
| MethodAttributes.HideBySig;
MethodBuilder method = type.DefineMethod("get_" + commandName, methodAttributes);
ConstructorInfo actionConstructor = (hasParameter ?
(isCommandMethodReturnTypeVoid ? typeof(Action<>).MakeGenericType(parameterType) : typeof(Func<,>).MakeGenericType(parameterType, commandMethodReturnType)) :
(isCommandMethodReturnTypeVoid ? typeof(Action) : typeof(Func<>).MakeGenericType(commandMethodReturnType)))
.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(Object), typeof(IntPtr) }, null);
ConstructorInfo funcConstructor = (hasParameter ? typeof(Func<,>).MakeGenericType(parameterType, typeof(bool)) : typeof(Func<bool>)).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(Object), typeof(IntPtr) }, null);
MethodInfo createCommandMethod;
if(isAsyncCommand)
createCommandMethod = hasParameter ?
AsyncCommandFactory.GetGenericMethodWithResult(parameterType, commandMethodReturnType, useCommandManager != null)
: AsyncCommandFactory.GetSimpleMethodWithResult(commandMethodReturnType, useCommandManager != null);
else
createCommandMethod = hasParameter ?
(isCommandMethodReturnTypeVoid ?
DelegateCommandFactory.GetGenericMethodWithoutResult(parameterType, useCommandManager != null)
: DelegateCommandFactory.GetGenericMethodWithResult(parameterType, commandMethodReturnType, useCommandManager != null))
: (isCommandMethodReturnTypeVoid ?
DelegateCommandFactory.GetSimpleMethodWithoutResult(useCommandManager != null)
: DelegateCommandFactory.GetSimpleMethodWithResult(commandMethodReturnType, useCommandManager != null));
method.SetReturnType(commandPropertyType);
ILGenerator gen = method.GetILGenerator();
gen.DeclareLocal(commandPropertyType);
Label returnLabel = gen.DefineLabel();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, commandField);
gen.Emit(OpCodes.Dup);
gen.Emit(OpCodes.Brtrue_S, returnLabel);
gen.Emit(OpCodes.Pop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldftn, commandMethod);
gen.Emit(OpCodes.Newobj, actionConstructor);
if(canExecuteMethod != null) {
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldftn, canExecuteMethod);
gen.Emit(OpCodes.Newobj, funcConstructor);
} else {
gen.Emit(OpCodes.Ldnull);
}
if(isAsyncCommand) {
AsyncCommandAttribute attribute = ViewModelBase.GetAttribute<AsyncCommandAttribute>(commandMethod);
bool allowMultipleExecution=attribute != null ? attribute.AllowMultipleExecution : false;
gen.Emit(allowMultipleExecution ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
}
if(useCommandManager != null)
gen.Emit(useCommandManager.Value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
gen.Emit(OpCodes.Call, createCommandMethod);
gen.Emit(OpCodes.Dup);
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Stfld, commandField);
gen.Emit(OpCodes.Ldloc_0);
gen.MarkLabel(returnLabel);
gen.Emit(OpCodes.Ret);
return method;
}
static void BuildCommandPropertyAttributes(PropertyBuilder commandProperty, MethodInfo commandMethod) {
foreach(Attribute attribute in MetadataHelper.GetAllAttributes(commandMethod)) {
ICustomAttributeBuilderProvider provider;
if(attributeBuilderProviders.TryGetValue(attribute.GetType(), out provider))
commandProperty.SetCustomAttribute(provider.CreateAttributeBuilder(attribute));
}
}
#endregion
#region services
static void ImplementISupportServices(Type type, TypeBuilder typeBuilder) {
if(typeof(ISupportServices).IsAssignableFrom(type))
return;
Expression<Func<ISupportServices, IServiceContainer>> getServiceContainerExpression = x => x.ServiceContainer;
var getter = ExpressionHelper.GetArgumentPropertyStrict(getServiceContainerExpression).GetGetMethod();
FieldBuilder serviceContainerField = typeBuilder.DefineField("serviceContainer", typeof(IServiceContainer), FieldAttributes.Private);
var getServiceContainerMethod = BuildGetServiceContainerMethod(typeBuilder, serviceContainerField, getter.Name);
typeBuilder.DefineMethodOverride(getServiceContainerMethod, getter);
}
static MethodBuilder BuildGetServiceContainerMethod(TypeBuilder type, FieldInfo serviceContainerField, string getServiceContainerMethodName) {
MethodAttributes methodAttributes =
MethodAttributes.Private
| MethodAttributes.Virtual
| MethodAttributes.Final
| MethodAttributes.HideBySig
| MethodAttributes.NewSlot;
MethodBuilder method = type.DefineMethod(typeof(ISupportServices).FullName + "." + getServiceContainerMethodName, methodAttributes);
Expression<Func<ServiceContainer>> serviceContainerCtorExpression = () => new ServiceContainer(null);
method.SetReturnType(typeof(IServiceContainer));
ILGenerator gen = method.GetILGenerator();
gen.DeclareLocal(typeof(IServiceContainer));
Label returnLabel = gen.DefineLabel();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, serviceContainerField);
gen.Emit(OpCodes.Dup);
gen.Emit(OpCodes.Brtrue_S, returnLabel);
gen.Emit(OpCodes.Pop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Newobj, ExpressionHelper.GetConstructor(serviceContainerCtorExpression));
gen.Emit(OpCodes.Dup);
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Stfld, serviceContainerField);
gen.Emit(OpCodes.Ldloc_0);
gen.MarkLabel(returnLabel);
gen.Emit(OpCodes.Ret);
return method;
}
static void BuildServiceProperties(Type type, TypeBuilder typeBuilder) {
var serviceProperties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(x => IsServiceProperty(x)).ToArray();
foreach(var propertyInfo in serviceProperties) {
ServicePropertyAttribute attribute = GetAttribute<ServicePropertyAttribute>(propertyInfo);
bool required = DataAnnotationsAttributeHelper.HasRequiredAttribute(propertyInfo);
var getter = BuildGetServicePropertyMethod(typeBuilder, propertyInfo, attribute.With(x => x.Key), attribute.Return(x => x.SearchMode, () => default(ServiceSearchMode)), required);
typeBuilder.DefineMethodOverride(getter, propertyInfo.GetGetMethod(true));
var newProperty = typeBuilder.DefineProperty(propertyInfo.Name, PropertyAttributes.None, propertyInfo.PropertyType, Type.EmptyTypes);
newProperty.SetGetMethod(getter);
}
}
static bool IsServiceProperty(PropertyInfo property) {
ServicePropertyAttribute attribute = GetAttribute<ServicePropertyAttribute>(property);
if(attribute != null && !attribute.IsServiceProperty)
return false;
if(!property.PropertyType.Name.EndsWith("Service") && attribute == null)
return false;
if(!property.PropertyType.IsInterface)
return ReturnFalseOrThrow(attribute, Error_PropertyTypeShouldBeServiceType, property);
var getter = property.GetGetMethod(true);
if(!CanAccessFromDescendant(getter))
return ReturnFalseOrThrow(attribute, Error_CantAccessProperty, property);
if(!getter.IsVirtual)
return ReturnFalseOrThrow(attribute, Error_PropertyIsNotVirtual, property);
if(getter.IsFinal)
return ReturnFalseOrThrow(attribute, Error_PropertyIsFinal, property);
if(property.GetSetMethod(true) != null)
return ReturnFalseOrThrow(attribute, Error_PropertyHasSetter, property);
return true;
}
static MethodBuilder BuildGetServicePropertyMethod(TypeBuilder type, PropertyInfo property, string serviceName, ServiceSearchMode searchMode, bool required) {
var getMethod = property.GetGetMethod(true);
MethodAttributes methodAttributes =
(getMethod.IsPublic ? MethodAttributes.Public : MethodAttributes.Family)
| MethodAttributes.Virtual
| MethodAttributes.HideBySig;
MethodBuilder method = type.DefineMethod(getMethod.Name, methodAttributes);
method.SetReturnType(property.PropertyType);
ILGenerator gen = method.GetILGenerator();
if(required)
EmitGetRequiredServicePropertyMethod(property.PropertyType, serviceName, searchMode, gen);
else
EmitGetOptionalServicePropertyMethod(property.PropertyType, serviceName, searchMode, gen);
return method;
}
static void EmitGetOptionalServicePropertyMethod(Type serviceType, string serviceName, ServiceSearchMode searchMode, ILGenerator gen) {
Expression<Func<ISupportServices, IServiceContainer>> serviceContainerPropertyExpression = x => x.ServiceContainer;
Type[] getServiceMethodParams = string.IsNullOrEmpty(serviceName) ? new Type[] { typeof(ServiceSearchMode) } : new Type[] { typeof(string), typeof(ServiceSearchMode) };
MethodInfo getServiceMethod = typeof(IServiceContainer).GetMethod("GetService", BindingFlags.Instance | BindingFlags.Public, null, getServiceMethodParams, null).MakeGenericMethod(serviceType);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Callvirt, ExpressionHelper.GetArgumentPropertyStrict(serviceContainerPropertyExpression).GetGetMethod());
if(!string.IsNullOrEmpty(serviceName))
gen.Emit(OpCodes.Ldstr, serviceName);
gen.Emit(OpCodes.Ldc_I4_S, (int)searchMode);
gen.Emit(OpCodes.Callvirt, getServiceMethod);
gen.Emit(OpCodes.Ret);
}
static void EmitGetRequiredServicePropertyMethod(Type serviceType, string serviceName, ServiceSearchMode searchMode, ILGenerator gen) {
Expression<Func<ISupportServices, IServiceContainer>> serviceContainerPropertyExpression = x => x.ServiceContainer;
Type[] getServiceMethodParams = string.IsNullOrEmpty(serviceName) ? new Type[] { typeof(IServiceContainer), typeof(ServiceSearchMode) } : new Type[] { typeof(IServiceContainer), typeof(string), typeof(ServiceSearchMode) };
MethodInfo getServiceMethod = typeof(ServiceContainerExtensions).GetMethod("GetRequiredService", BindingFlags.Static | BindingFlags.Public, null, getServiceMethodParams, null).MakeGenericMethod(serviceType);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Callvirt, ExpressionHelper.GetArgumentPropertyStrict(serviceContainerPropertyExpression).GetGetMethod());
if(!string.IsNullOrEmpty(serviceName))
gen.Emit(OpCodes.Ldstr, serviceName);
gen.Emit(OpCodes.Ldc_I4_S, (int)searchMode);
gen.Emit(OpCodes.Call, getServiceMethod);
gen.Emit(OpCodes.Ret);
}
#endregion
#region ISupportParentViewModel
static void ImplementISupportParentViewModel(Type type, TypeBuilder typeBuilder) {
if(typeof(ISupportParentViewModel).IsAssignableFrom(type))
return;
Expression<Func<ISupportParentViewModel, object>> parentViewModelPropertyExpression = x => x.ParentViewModel;
var getter = ExpressionHelper.GetArgumentPropertyStrict(parentViewModelPropertyExpression).GetGetMethod();
var setter = ExpressionHelper.GetArgumentPropertyStrict(parentViewModelPropertyExpression).GetSetMethod();
FieldBuilder parentViewModelField = typeBuilder.DefineField("parentViewModel", typeof(object), FieldAttributes.Private);
var getMethod = BuildGetParentViewModelMethod(typeBuilder, parentViewModelField, getter.Name);
var setMethod = BuildSetParentViewModelMethod(typeBuilder, parentViewModelField, setter.Name);
typeBuilder.DefineMethodOverride(getMethod, getter);
typeBuilder.DefineMethodOverride(setMethod, setter);
}
static MethodBuilder BuildSetParentViewModelMethod(TypeBuilder type, FieldBuilder parentViewModelField, string setterName) {
System.Reflection.MethodAttributes methodAttributes =
MethodAttributes.Private
| MethodAttributes.Virtual
| MethodAttributes.Final
| MethodAttributes.HideBySig
| MethodAttributes.NewSlot;
MethodBuilder method = type.DefineMethod(typeof(ISupportParentViewModel).FullName + "." + setterName, methodAttributes);
method.SetReturnType(typeof(void));
method.SetParameters(typeof(object));
ILGenerator gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Stfld, parentViewModelField);
gen.Emit(OpCodes.Ret);
return method;
}
static MethodBuilder BuildGetParentViewModelMethod(TypeBuilder type, FieldBuilder parentViewModelField, string getterName) {
System.Reflection.MethodAttributes methodAttributes =
MethodAttributes.Private
| MethodAttributes.Virtual
| MethodAttributes.Final
| MethodAttributes.HideBySig
| MethodAttributes.NewSlot;
MethodBuilder method = type.DefineMethod(typeof(ISupportParentViewModel).FullName + "." + getterName, methodAttributes);
method.SetReturnType(typeof(object));
ILGenerator gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, parentViewModelField);
gen.Emit(OpCodes.Ret);
return method;
}
#endregion
}
#if !SILVERLIGHT
[Serializable]
#endif
public class ViewModelSourceException : Exception {
public ViewModelSourceException() { }
public ViewModelSourceException(string message)
: base(message) {
}
}
#pragma warning disable 612,618
public static class POCOViewModelExtensions {
public static bool IsInDesignMode(this object viewModel) {
return ViewModelBase.IsInDesignMode;
}
public static void RaisePropertiesChanged(this object viewModel) {
IPOCOViewModel pocoViewModel = GetPOCOViewModel(viewModel);
pocoViewModel.RaisePropertyChanged(string.Empty);
}
public static void RaisePropertyChanged<T, TProperty>(this T viewModel, Expression<Func<T, TProperty>> propertyExpression) {
IPOCOViewModel pocoViewModel = GetPOCOViewModel(viewModel);
pocoViewModel.RaisePropertyChanged(BindableBase.GetPropertyNameFast(propertyExpression));
}
public static IDelegateCommand GetCommand<T>(this T viewModel, Expression<Action<T>> methodExpression) {
return GetCommandCore(viewModel, methodExpression);
}
public static T SetParentViewModel<T>(this T viewModel, object parentViewModel) {
((ISupportParentViewModel)viewModel).ParentViewModel = parentViewModel;
return viewModel;
}
public static T GetParentViewModel<T>(this object viewModel) where T : class {
return (T)((ISupportParentViewModel)viewModel).ParentViewModel;
}
public static IAsyncCommand GetAsyncCommand<T>(this T viewModel, Expression<Func<T, Task>> methodExpression) {
return GetAsyncCommandCore(viewModel, methodExpression);
}
public static void RaiseCanExecuteChanged<T>(this T viewModel, Expression<Action<T>> methodExpression) {
RaiseCanExecuteChangedCore(viewModel, methodExpression);
}
#if !SILVERLIGHT
public static void UpdateFunctionBinding<T>(this T viewModel, Expression<Action<T>> methodExpression) {
UpdateFunctionBehaviorCore(viewModel, methodExpression);
}
public static void UpdateMethodToCommandCanExecute<T>(this T viewModel, Expression<Action<T>> methodExpression) {
UpdateFunctionBehaviorCore(viewModel, methodExpression);
}
static void UpdateFunctionBehaviorCore<T>(this T viewModel, Expression<Action<T>> methodExpression) {
string methodName = ExpressionHelper.GetMethod(methodExpression).Name;
GetPOCOViewModel(viewModel).RaisePropertyChanged(methodName);
}
#endif
#region GetService methods
public static TService GetService<TService>(this object viewModel) where TService : class {
return GetServiceContainer(viewModel).GetService<TService>();
}
public static TService GetService<TService>(this object viewModel, string key) where TService : class {
return GetServiceContainer(viewModel).GetService<TService>(key);
}
public static TService GetRequiredService<TService>(this object viewModel) where TService : class {
return ServiceContainerExtensions.GetRequiredService<TService>(GetServiceContainer(viewModel));
}
public static TService GetRequiredService<TService>(this object viewModel, string key) where TService : class {
return ServiceContainerExtensions.GetRequiredService<TService>(GetServiceContainer(viewModel), key);
}
static IServiceContainer GetServiceContainer(object viewModel) {
GetPOCOViewModel(viewModel);
return ((ISupportServices)viewModel).ServiceContainer;
}
#endregion
[Obsolete("This method is obsolete. Use the GetAsyncCommand method instead.")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public static bool GetShouldCancel<T>(this T viewModel, Expression<Func<T, Task>> methodExpression) {
return GetAsyncCommand(viewModel, methodExpression).ShouldCancel;
}
[Obsolete("This method is obsolete. Use the GetAsyncCommand method instead.")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public static bool GetIsExecuting<T>(this T viewModel, Expression<Func<T, Task>> methodExpression) {
return GetAsyncCommand(viewModel, methodExpression).IsExecuting;
}
internal static void RaiseCanExecuteChangedCore(object viewModel, LambdaExpression methodExpression) {
IDelegateCommand command = GetCommandCore(viewModel, methodExpression);
command.RaiseCanExecuteChanged();
}
static IAsyncCommand GetAsyncCommandCore(object viewModel, LambdaExpression methodExpression) {
GetPOCOViewModel(viewModel);
ICommand command = GetCommandCore(viewModel, methodExpression);
if(!(command is IAsyncCommand))
throw new ViewModelSourceException(ViewModelSource.Error_CommandNotAsync);
return (IAsyncCommand)command;
}
static IDelegateCommand GetCommandCore(object viewModel, LambdaExpression methodExpression) {
GetPOCOViewModel(viewModel);
MethodInfo method = ExpressionHelper.GetMethod(methodExpression);
string commandName = ViewModelSource.GetCommandName(method);
PropertyInfo property = viewModel.GetType().GetProperty(commandName);
if(property == null)
throw new ViewModelSourceException(string.Format(ViewModelSource.Error_CommandNotFound, commandName));
return property.GetValue(viewModel, null) as IDelegateCommand;
}
static IPOCOViewModel GetPOCOViewModel<T>(T viewModel) {
IPOCOViewModel pocoViewModel = viewModel as IPOCOViewModel;
if(pocoViewModel == null)
throw new ViewModelSourceException(ViewModelSource.Error_ObjectDoesntImplementIPOCOViewModel);
return pocoViewModel;
}
}
#pragma warning restore 612,618
#region ViewModelSource<T>
public static class ViewModelSource<T> {
static TDelegate GetFactoryByTypes<TDelegate>(Func<Type[]> getTypesDelegate) {
return ViewModelSource.GetFactoryCore<TDelegate>(() => {
Type[] types = getTypesDelegate();
var ctor = ViewModelSource.GetConstructor(ViewModelSource.GetPOCOType(typeof(T)), types);
ParameterExpression[] parameters = types.Select(x => Expression.Parameter(x)).ToArray();
return Expression.Lambda<TDelegate>(Expression.New(ctor, parameters), parameters).Compile();
});
}
public static T Create() {
return GetFactoryByTypes<Func<T>>(() => Type.EmptyTypes)();
}
public static T Create<T1>(T1 param1) {
return GetFactoryByTypes<Func<T1, T>>(() => new[] { typeof(T1) })
(param1);
}
public static T Create<T1, T2>(T1 param1, T2 param2) {
return GetFactoryByTypes<Func<T1, T2, T>>(() => new[] { typeof(T1), typeof(T2) })
(param1, param2);
}
public static T Create<T1, T2, T3>(T1 param1, T2 param2, T3 param3) {
return GetFactoryByTypes<Func<T1, T2, T3, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3) })
(param1, param2, param3);
}
public static T Create<T1, T2, T3, T4>(T1 param1, T2 param2, T3 param3, T4 param4) {
return GetFactoryByTypes<Func<T1, T2, T3, T4, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) })
(param1, param2, param3, param4);
}
public static T Create<T1, T2, T3, T4, T5>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5) {
return GetFactoryByTypes<Func<T1, T2, T3, T4, T5, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) })
(param1, param2, param3, param4, param5);
}
public static T Create<T1, T2, T3, T4, T5, T6>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6) {
return GetFactoryByTypes<Func<T1, T2, T3, T4, T5, T6, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) })
(param1, param2, param3, param4, param5, param6);
}
public static T Create<T1, T2, T3, T4, T5, T6, T7>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7) {
return GetFactoryByTypes<Func<T1, T2, T3, T4, T5, T6, T7, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) })
(param1, param2, param3, param4, param5, param6, param7);
}
public static T Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8) {
return GetFactoryByTypes<Func<T1, T2, T3, T4, T5, T6, T7, T8, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8) })
(param1, param2, param3, param4, param5, param6, param7, param8);
}
public static T Create<T1, T2, T3, T4, T5, T6, T7, T8, T9>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8, T9 param9) {
return GetFactoryByTypes<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9) })
(param1, param2, param3, param4, param5, param6, param7, param8, param9);
}
public static T Create<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8, T9 param9, T10 param10) {
return GetFactoryByTypes<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10) })
(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10);
}
}
#endregion
}
| |
/*
* @(#) InkSource.cs 1.0 06-08-2007 author: Manoj Prasad
*************************************************************************
* Copyright (c) 2008 Hewlett-Packard Development Company, L.P.
* 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.
**************************************************************************/
/************************************************************************
* SVN MACROS
*
* $Revision: 244 $
* $Author: mnab $
* $LastChangedDate: 2008-07-04 13:57:50 +0530 (Fri, 04 Jul 2008) $
************************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace InkML
{
/// <summary>
///
/// </summary>
public class InkSource : InkElement
{
#region Fields
private string id;
private string manufacturer;
private string model;
private string serialNo;
private string specificationRef;
private string description;
private TraceFormat traceFormat;
private Definitions definitions;
/// <summary>
/// Gets/Sets the 'id' attribute of the InkSource Element
/// </summary>
public string Id
{
get { return id; }
set
{
if (!definitions.ContainsID(value))
{
id = value;
definitions.AddInkSource(this);
}
else
{
throw new Exception("ID Exists.");
}
}
}
/// <summary>
/// Gets/Sets the 'manufacturer' attribute of the InkSource Element
/// </summary>
public string Manufacturer
{
get { return manufacturer; }
set { manufacturer = value; }
}
/// <summary>
/// Gets/Sets the 'model' attribute of the InkSource Element
/// </summary>
public string Model
{
get { return model; }
set { model = value; }
}
/// <summary>
/// Gets/Sets the 'serialNo' attribute of the InkSource Element
/// </summary>
public string SerialNo
{
get { return serialNo; }
set { serialNo = value; }
}
/// <summary>
/// Gets/Sets the 'specificationRef' attribute of the InkSource Element
/// </summary>
public string SpecificationRef
{
get { return specificationRef; }
set { specificationRef = value; }
}
/// <summary>
/// Gets/Sets the 'desc' attribute of the InkSource Element
/// </summary>
public string Description
{
get { return description; }
set { description = value; }
}
/// <summary>
/// Gets/Sets the traceFormat element of the InkSource Element
/// </summary>
public TraceFormat TraceFormat
{
get { return traceFormat; }
set
{
if (value != null)
{
traceFormat = value;
}
else
{
throw new Exception("Invalid Assignment Error.");
}
}
}
#endregion Fields
#region Contructors
public InkSource(Definitions defs)
{
base.TagName = "inkSource";
this.definitions = defs;
}
public InkSource(Definitions defs, XmlElement element)
: this(defs)
{
ParseElement(element);
}
public InkSource(Definitions defs, string Id, TraceFormat traceFormat)
: this(defs)
{
this.id = Id;
this.traceFormat = traceFormat;
}
#endregion Contructors
#region override Functions ParseElement and ToInkML
/// <summary>
/// Function to Parse a xmkelement and fill inksource details
/// </summary>
/// <param name="element">Xml Element to be Parsed</param>
public override void ParseElement(XmlElement element)
{
if (element.LocalName.Equals("inkSource"))
{
id = element.GetAttribute("id");
if (id == "")
id = element.GetAttribute("id", "http://www.w3.org/XML/1998/namespace");
if (id.Equals(""))
{
throw new Exception("Required Field ID not present.");
}
else
{
definitions.AddInkSource(this);
}
manufacturer = element.GetAttribute("manufacturer");
model = element.GetAttribute("model");
serialNo = element.GetAttribute("serialNo");
specificationRef = element.GetAttribute("specificationRef");
description = element.GetAttribute("description");
bool found = false;
foreach (XmlElement item in element)
{
if (item.LocalName == "traceFormat")
{
this.traceFormat = new TraceFormat(definitions, item);
found = true;
break;
}
}
if (!found)
{
throw new Exception("TraceFormat element Required.");
}
}
else
{
throw new Exception("Invalid Element Name.");
}
}
/// <summary>
/// Function to convert InkSource object to xml Element
/// </summary>
/// <param name="inkDocument">Ink Document</param>
/// <returns>Ink Source Xml Element</returns>
public override XmlElement ToInkML(XmlDocument inkDocument)
{
XmlElement result = inkDocument.CreateElement("inkSource");
result.SetAttribute("id", id);
if (!manufacturer.Equals(""))
{
result.SetAttribute("manufacturer", manufacturer);
}
if (!model.Equals(""))
{
result.SetAttribute("model", model);
}
if (!serialNo.Equals(""))
{
result.SetAttribute("serialNo", serialNo);
}
if (!specificationRef.Equals(""))
{
result.SetAttribute("specificationRef", specificationRef);
}
if (!description.Equals(""))
{
result.SetAttribute("description", description);
}
if (traceFormat.Id.Equals(""))
{
result.AppendChild(traceFormat.ToInkML(inkDocument));
}
else
{
XmlElement temp = inkDocument.CreateElement("traceFormat");
temp.SetAttribute("hRef", "#" + id);
result.AppendChild(temp);
}
return result;
}
#endregion override Functions ParseElement and ToInkML
}
}
| |
using Dotnet.Script.Core;
using Dotnet.Script.Core.Commands;
using Dotnet.Script.Core.Versioning;
using Dotnet.Script.DependencyModel.Environment;
using Dotnet.Script.DependencyModel.Logging;
using McMaster.Extensions.CommandLineUtils;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Threading.Tasks;
namespace Dotnet.Script
{
public static class Program
{
private const string DebugFlagShort = "-d";
private const string DebugFlagLong = "--debug";
public static int Main(string[] args)
{
try
{
return Wain(args);
}
catch (Exception e)
{
if (e is AggregateException aggregateEx)
{
e = aggregateEx.Flatten().InnerException;
}
if (e is CompilationErrorException || e is ScriptRuntimeException)
{
// no need to write out anything as the upstream services will report that
return 0x1;
}
// Be verbose (stack trace) in debug mode otherwise brief
var error = args.Any(arg => arg == DebugFlagShort
|| arg == DebugFlagLong)
? e.ToString()
: e.GetBaseException().Message;
Console.Error.WriteLine(error);
return 0x1;
}
}
public static Func<string, bool, LogFactory> CreateLogFactory
= (verbosity, debugMode) => LogHelper.CreateLogFactory(debugMode ? "debug" : verbosity);
private static int Wain(string[] args)
{
var app = new CommandLineApplication()
{
UnrecognizedArgumentHandling = UnrecognizedArgumentHandling.CollectAndContinue,
ExtendedHelpText = "Starting without a path to a CSX file or a command, starts the REPL (interactive) mode."
};
var file = app.Argument("script", "Path to CSX script");
var interactive = app.Option("-i | --interactive", "Execute a script and drop into the interactive mode afterwards.", CommandOptionType.NoValue);
var configuration = app.Option("-c | --configuration <configuration>", "Configuration to use for running the script [Release/Debug] Default is \"Debug\"", CommandOptionType.SingleValue);
var packageSources = app.Option("-s | --sources <SOURCE>", "Specifies a NuGet package source to use when resolving NuGet packages.", CommandOptionType.MultipleValue);
var debugMode = app.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);
var verbosity = app.Option("--verbosity", " Set the verbosity level of the command. Allowed values are t[trace], d[ebug], i[nfo], w[arning], e[rror], and c[ritical].", CommandOptionType.SingleValue);
var nocache = app.Option("--no-cache", "Disable caching (Restore and Dll cache)", CommandOptionType.NoValue);
var isolatedLoadContext = app.Option("--isolated-load-context", "Use isolated assembly load context", CommandOptionType.NoValue);
var infoOption = app.Option("--info", "Displays environmental information", CommandOptionType.NoValue);
var argsBeforeDoubleHyphen = args.TakeWhile(a => a != "--").ToArray();
var argsAfterDoubleHyphen = args.SkipWhile(a => a != "--").Skip(1).ToArray();
const string helpOptionTemplate = "-? | -h | --help";
app.HelpOption(helpOptionTemplate);
app.VersionOption("-v | --version", () => new VersionProvider().GetCurrentVersion().Version);
app.Command("eval", c =>
{
c.Description = "Execute CSX code.";
var code = c.Argument("code", "Code to execute.");
var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for the code compiler. Defaults to current directory.", CommandOptionType.SingleValue);
c.HelpOption(helpOptionTemplate);
c.OnExecuteAsync(async (cancellationToken) =>
{
var source = code.Value;
if (string.IsNullOrWhiteSpace(source))
{
if (Console.IsInputRedirected)
{
source = await Console.In.ReadToEndAsync();
}
else
{
c.ShowHelp();
return 0;
}
}
var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
var options = new ExecuteCodeCommandOptions(source, cwd.Value(), app.RemainingArguments.Concat(argsAfterDoubleHyphen).ToArray(), configuration.ValueEquals("release", StringComparison.OrdinalIgnoreCase) ? OptimizationLevel.Release : OptimizationLevel.Debug, nocache.HasValue(), packageSources.Values?.ToArray());
return await new ExecuteCodeCommand(ScriptConsole.Default, logFactory).Execute<int>(options);
});
});
app.Command("init", c =>
{
c.Description = "Creates a sample script along with the launch.json file needed to launch and debug the script.";
var fileName = c.Argument("filename", "(Optional) The name of the sample script file to be created during initialization. Defaults to 'main.csx'");
var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for initialization. Defaults to current directory.", CommandOptionType.SingleValue);
c.HelpOption(helpOptionTemplate);
c.OnExecute(() =>
{
var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
new InitCommand(logFactory).Execute(new InitCommandOptions(fileName.Value, cwd.Value()));
return 0;
});
});
app.Command("new", c =>
{
c.Description = "Creates a new script file";
var fileNameArgument = c.Argument("filename", "The script file name");
var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory the new script file to be created. Defaults to current directory.", CommandOptionType.SingleValue);
c.HelpOption(helpOptionTemplate);
c.OnExecute(() =>
{
var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
var scaffolder = new Scaffolder(logFactory);
if (fileNameArgument.Value == null)
{
c.ShowHelp();
return 0;
}
scaffolder.CreateNewScriptFile(fileNameArgument.Value, cwd.Value() ?? Directory.GetCurrentDirectory());
return 0;
});
});
// windows only
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// on windows we have command to register .csx files to be executed by dotnet-script
app.Command("register", c =>
{
c.Description = "Register .csx file handler to enable running scripts directly";
c.HelpOption(helpOptionTemplate);
c.OnExecute(() =>
{
var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
var scaffolder = new Scaffolder(logFactory);
scaffolder.RegisterFileHandler();
});
});
}
app.Command("publish", c =>
{
c.Description = "Creates a self contained executable or DLL from a script";
var fileNameArgument = c.Argument("filename", "The script file name");
var publishDirectoryOption = c.Option("-o |--output", "Directory where the published executable should be placed. Defaults to a 'publish' folder in the current directory.", CommandOptionType.SingleValue);
var dllName = c.Option("-n |--name", "The name for the generated DLL (executable not supported at this time). Defaults to the name of the script.", CommandOptionType.SingleValue);
var dllOption = c.Option("--dll", "Publish to a .dll instead of an executable.", CommandOptionType.NoValue);
var commandConfig = c.Option("-c | --configuration <configuration>", "Configuration to use for publishing the script [Release/Debug]. Default is \"Debug\"", CommandOptionType.SingleValue);
var runtime = c.Option("-r |--runtime", "The runtime used when publishing the self contained executable. Defaults to your current runtime.", CommandOptionType.SingleValue);
c.HelpOption(helpOptionTemplate);
c.OnExecute(() =>
{
if (fileNameArgument.Value == null)
{
c.ShowHelp();
return 0;
}
var options = new PublishCommandOptions
(
new ScriptFile(fileNameArgument.Value),
publishDirectoryOption.Value(),
dllName.Value(),
dllOption.HasValue() ? PublishType.Library : PublishType.Executable,
commandConfig.ValueEquals("release", StringComparison.OrdinalIgnoreCase) ? OptimizationLevel.Release : OptimizationLevel.Debug,
packageSources.Values?.ToArray(),
runtime.Value() ?? ScriptEnvironment.Default.RuntimeIdentifier,
nocache.HasValue()
);
var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
new PublishCommand(ScriptConsole.Default, logFactory).Execute(options);
return 0;
});
});
app.Command("exec", c =>
{
c.Description = "Run a script from a DLL.";
var dllPath = c.Argument("dll", "Path to DLL based script");
var commandDebugMode = c.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);
c.HelpOption(helpOptionTemplate);
c.OnExecuteAsync(async (cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(dllPath.Value))
{
c.ShowHelp();
return 0;
}
var options = new ExecuteLibraryCommandOptions
(
dllPath.Value,
app.RemainingArguments.Concat(argsAfterDoubleHyphen).ToArray(),
nocache.HasValue()
);
var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
return await new ExecuteLibraryCommand(ScriptConsole.Default, logFactory).Execute<int>(options);
});
});
app.OnExecuteAsync(async (cancellationToken) =>
{
int exitCode = 0;
var scriptFile = new ScriptFile(file.Value);
var optimizationLevel = configuration.ValueEquals("release", StringComparison.OrdinalIgnoreCase) ? OptimizationLevel.Release : OptimizationLevel.Debug;
var scriptArguments = app.RemainingArguments.Concat(argsAfterDoubleHyphen).ToArray();
var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
if (infoOption.HasValue())
{
var environmentReporter = new EnvironmentReporter(logFactory);
await environmentReporter.ReportInfo();
return 0;
}
AssemblyLoadContext assemblyLoadContext = null;
if (isolatedLoadContext.HasValue())
assemblyLoadContext = new ScriptAssemblyLoadContext();
if (scriptFile.HasValue)
{
if (interactive.HasValue())
{
return await RunInteractiveWithSeed(file.Value, logFactory, scriptArguments, packageSources.Values?.ToArray(), assemblyLoadContext);
}
var fileCommandOptions = new ExecuteScriptCommandOptions
(
new ScriptFile(file.Value),
scriptArguments,
optimizationLevel,
packageSources.Values?.ToArray(),
interactive.HasValue(),
nocache.HasValue()
)
{
AssemblyLoadContext = assemblyLoadContext
};
var fileCommand = new ExecuteScriptCommand(ScriptConsole.Default, logFactory);
return await fileCommand.Run<int, CommandLineScriptGlobals>(fileCommandOptions);
}
else
{
await RunInteractive(!nocache.HasValue(), logFactory, packageSources.Values?.ToArray(), assemblyLoadContext);
}
return exitCode;
});
return app.Execute(argsBeforeDoubleHyphen);
}
private static async Task<int> RunInteractive(bool useRestoreCache, LogFactory logFactory, string[] packageSources, AssemblyLoadContext assemblyLoadContext)
{
var options = new ExecuteInteractiveCommandOptions(null, Array.Empty<string>(), packageSources)
{
AssemblyLoadContext = assemblyLoadContext
};
await new ExecuteInteractiveCommand(ScriptConsole.Default, logFactory).Execute(options);
return 0;
}
private async static Task<int> RunInteractiveWithSeed(string file, LogFactory logFactory, string[] arguments, string[] packageSources, AssemblyLoadContext assemblyLoadContext)
{
var options = new ExecuteInteractiveCommandOptions(new ScriptFile(file), arguments, packageSources)
{
AssemblyLoadContext = assemblyLoadContext
};
await new ExecuteInteractiveCommand(ScriptConsole.Default, logFactory).Execute(options);
return 0;
}
}
}
| |
namespace Orleans.CodeGenerator.Utilities
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans.Runtime;
using System.Globalization;
/// <summary>
/// The syntax factory extensions.
/// </summary>
internal static class SyntaxFactoryExtensions
{
/// <summary>
/// Returns <see cref="TypeSyntax"/> for the provided <paramref name="type"/>.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="includeNamespace">
/// A value indicating whether or not to include the namespace name.
/// </param>
/// <param name="includeGenericParameters">
/// Whether or not to include the names of generic parameters in the result.
/// </param>
/// <returns>
/// <see cref="TypeSyntax"/> for the provided <paramref name="type"/>.
/// </returns>
public static TypeSyntax GetTypeSyntax(
this Type type,
bool includeNamespace = true,
bool includeGenericParameters = true)
{
if (type == typeof(void))
{
return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword));
}
return
SyntaxFactory.ParseTypeName(
type.GetParseableName(
new TypeFormattingOptions(
includeNamespace: includeNamespace,
includeGenericParameters: includeGenericParameters)));
}
/// <summary>
/// Returns <see cref="NameSyntax"/> specified <paramref name="type"/>.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="includeNamespace">
/// A value indicating whether or not to include the namespace name.
/// </param>
/// <returns>
/// <see cref="NameSyntax"/> specified <paramref name="type"/>.
/// </returns>
public static NameSyntax GetNameSyntax(this Type type, bool includeNamespace = true)
{
return
SyntaxFactory.ParseName(
type.GetParseableName(new TypeFormattingOptions(includeNamespace: includeNamespace)));
}
/// <summary>
/// Returns <see cref="NameSyntax"/> specified <paramref name="method"/>.
/// </summary>
/// <param name="method">
/// The method.
/// </param>
/// <returns>
/// <see cref="NameSyntax"/> specified <paramref name="method"/>.
/// </returns>
public static SimpleNameSyntax GetNameSyntax(this MethodInfo method)
{
var plainName = method.GetUnadornedMethodName();
if (method.IsGenericMethod)
{
var args = method.GetGenericArguments().Select(arg => arg.GetTypeSyntax());
return plainName.ToGenericName().AddTypeArgumentListArguments(args.ToArray());
}
return plainName.ToIdentifierName();
}
/// <summary>
/// Returns <see cref="ParenthesizedExpressionSyntax"/> representing parenthesized binary expression of <paramref name="bindingFlags"/>.
/// </summary>
/// <param name="operationKind">
/// The kind of the binary expression.
/// </param>
/// <param name="bindingFlags">
/// The binding flags.
/// </param>
/// <returns>
/// <see cref="ParenthesizedExpressionSyntax"/> representing parenthesized binary expression of <paramref name="bindingFlags"/>.
/// </returns>
public static ParenthesizedExpressionSyntax GetBindingFlagsParenthesizedExpressionSyntax(SyntaxKind operationKind, params BindingFlags[] bindingFlags)
{
if (bindingFlags.Length < 2)
{
throw new ArgumentOutOfRangeException(
"bindingFlags",
string.Format("Can't create parenthesized binary expression with {0} arguments", bindingFlags.Length));
}
var flags = SyntaxFactory.IdentifierName("System").Member("Reflection").Member("BindingFlags");
var bindingFlagsBinaryExpression = SyntaxFactory.BinaryExpression(
operationKind,
flags.Member(bindingFlags[0].ToString()),
flags.Member(bindingFlags[1].ToString()));
for (var i = 2; i < bindingFlags.Length; i++)
{
bindingFlagsBinaryExpression = SyntaxFactory.BinaryExpression(
operationKind,
bindingFlagsBinaryExpression,
flags.Member(bindingFlags[i].ToString()));
}
return SyntaxFactory.ParenthesizedExpression(bindingFlagsBinaryExpression);
}
/// <summary>
/// Returns <see cref="ArrayCreationExpressionSyntax"/> representing the array creation form of <paramref name="arrayType"/>.
/// </summary>
/// <param name="separatedSyntaxList">
/// Args used in initialization.
/// </param>
/// <param name="arrayType">
/// The array type.
/// </param>
/// <returns>
/// <see cref="ArrayCreationExpressionSyntax"/> representing the array creation form of <paramref name="arrayType"/>.
/// </returns>
public static ArrayCreationExpressionSyntax GetArrayCreationWithInitializerSyntax(this SeparatedSyntaxList<ExpressionSyntax> separatedSyntaxList, TypeSyntax arrayType)
{
var arrayRankSizes =
new SeparatedSyntaxList<ExpressionSyntax>().Add(SyntaxFactory.OmittedArraySizeExpression(
SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken)));
var arrayRankSpecifier = SyntaxFactory.ArrayRankSpecifier(
SyntaxFactory.Token(SyntaxKind.OpenBracketToken),
arrayRankSizes,
SyntaxFactory.Token(SyntaxKind.CloseBracketToken));
var arrayRankSpecifierSyntaxList = new SyntaxList<ArrayRankSpecifierSyntax>().Add(arrayRankSpecifier);
var arrayCreationExpressionSyntax = SyntaxFactory.ArrayCreationExpression(
SyntaxFactory.Token(SyntaxKind.NewKeyword),
SyntaxFactory.ArrayType(arrayType, arrayRankSpecifierSyntaxList),
SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression,
SyntaxFactory.Token(SyntaxKind.OpenBraceToken),
separatedSyntaxList,
SyntaxFactory.Token(SyntaxKind.CloseBraceToken)));
return arrayCreationExpressionSyntax;
}
/// <summary>
/// Returns <see cref="ArrayTypeSyntax"/> representing the array form of <paramref name="type"/>.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="includeNamespace">
/// A value indicating whether or not to include the namespace name.
/// </param>
/// <returns>
/// <see cref="ArrayTypeSyntax"/> representing the array form of <paramref name="type"/>.
/// </returns>
public static ArrayTypeSyntax GetArrayTypeSyntax(this Type type, bool includeNamespace = true)
{
return
SyntaxFactory.ArrayType(
SyntaxFactory.ParseTypeName(
type.GetParseableName(new TypeFormattingOptions(includeNamespace: includeNamespace))))
.AddRankSpecifiers(
SyntaxFactory.ArrayRankSpecifier().AddSizes(SyntaxFactory.OmittedArraySizeExpression()));
}
/// <summary>
/// Returns the method declaration syntax for the provided method.
/// </summary>
/// <param name="method">
/// The method.
/// </param>
/// <returns>
/// The method declaration syntax for the provided method.
/// </returns>
public static MethodDeclarationSyntax GetDeclarationSyntax(this MethodInfo method)
{
var syntax =
SyntaxFactory.MethodDeclaration(method.ReturnType.GetTypeSyntax(), method.Name.ToIdentifier())
.WithParameterList(SyntaxFactory.ParameterList().AddParameters(method.GetParameterListSyntax()));
if (method.IsPublic)
{
syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
}
else if (method.IsPrivate)
{
syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.PrivateKeyword));
}
else if (method.IsFamily)
{
syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword));
}
return syntax;
}
/// <summary>
/// Returns the method declaration syntax for the provided constructor.
/// </summary>
/// <param name="constructor">
/// The constructor.
/// </param>
/// <param name="typeName">
/// The name of the type which the constructor will reside on.
/// </param>
/// <returns>
/// The method declaration syntax for the provided constructor.
/// </returns>
public static ConstructorDeclarationSyntax GetDeclarationSyntax(this ConstructorInfo constructor, string typeName)
{
var syntax =
SyntaxFactory.ConstructorDeclaration(typeName.ToIdentifier())
.WithParameterList(SyntaxFactory.ParameterList().AddParameters(constructor.GetParameterListSyntax()));
if (constructor.IsPublic)
{
syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
}
else if (constructor.IsPrivate)
{
syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.PrivateKeyword));
}
else if (constructor.IsFamily)
{
syntax = syntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword));
}
return syntax;
}
/// <summary>
/// Returns the name of the provided parameter.
/// If the parameter has no name (possible in F#),
/// it returns a name computed by suffixing "arg" with the parameter's index
/// </summary>
/// <param name="parameter"> The parameter. </param>
/// <param name="parameterIndex"> The parameter index in the list of parameters. </param>
/// <returns> The parameter name. </returns>
public static string GetOrCreateName(this ParameterInfo parameter, int parameterIndex)
{
var argName = parameter.Name;
if (String.IsNullOrWhiteSpace(argName))
{
argName = String.Format(CultureInfo.InvariantCulture, "arg{0:G}", parameterIndex);
}
return argName;
}
/// <summary>
/// Returns the parameter list syntax for the provided method.
/// </summary>
/// <param name="method">
/// The method.
/// </param>
/// <returns>
/// The parameter list syntax for the provided method.
/// </returns>
public static ParameterSyntax[] GetParameterListSyntax(this MethodInfo method)
{
return
method.GetParameters()
.Select(
(parameter, parameterIndex) =>
SyntaxFactory.Parameter(parameter.GetOrCreateName(parameterIndex).ToIdentifier())
.WithType(parameter.ParameterType.GetTypeSyntax()))
.ToArray();
}
/// <summary>
/// Returns the parameter list syntax for the provided constructor
/// </summary>
/// <param name="constructor">
/// The constructor.
/// </param>
/// <returns>
/// The parameter list syntax for the provided constructor.
/// </returns>
public static ParameterSyntax[] GetParameterListSyntax(this ConstructorInfo constructor)
{
return
constructor.GetParameters()
.Select(
parameter =>
SyntaxFactory.Parameter(parameter.Name.ToIdentifier())
.WithType(parameter.ParameterType.GetTypeSyntax()))
.ToArray();
}
/// <summary>
/// Returns type constraint syntax for the provided generic type argument.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <returns>
/// Type constraint syntax for the provided generic type argument.
/// </returns>
public static TypeParameterConstraintClauseSyntax[] GetTypeConstraintSyntax(this Type type)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsGenericTypeDefinition)
{
var constraints = new List<TypeParameterConstraintClauseSyntax>();
foreach (var genericParameter in typeInfo.GetGenericArguments())
{
var parameterConstraints = new List<TypeParameterConstraintSyntax>();
var attributes = genericParameter.GenericParameterAttributes;
// The "class" or "struct" constraints must come first.
if (attributes.HasFlag(GenericParameterAttributes.ReferenceTypeConstraint))
{
parameterConstraints.Add(SyntaxFactory.ClassOrStructConstraint(SyntaxKind.ClassConstraint));
}
else if (attributes.HasFlag(GenericParameterAttributes.NotNullableValueTypeConstraint))
{
parameterConstraints.Add(SyntaxFactory.ClassOrStructConstraint(SyntaxKind.StructConstraint));
}
// Follow with the base class or interface constraints.
foreach (var genericType in genericParameter.GetGenericParameterConstraints())
{
// If the "struct" constraint was specified, skip the corresponding "ValueType" constraint.
if (genericType == typeof(ValueType))
{
continue;
}
parameterConstraints.Add(SyntaxFactory.TypeConstraint(genericType.GetTypeSyntax()));
}
// The "new()" constraint must be the last constraint in the sequence.
if (attributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint)
&& !attributes.HasFlag(GenericParameterAttributes.NotNullableValueTypeConstraint))
{
parameterConstraints.Add(SyntaxFactory.ConstructorConstraint());
}
if (parameterConstraints.Count > 0)
{
constraints.Add(
SyntaxFactory.TypeParameterConstraintClause(genericParameter.Name)
.AddConstraints(parameterConstraints.ToArray()));
}
}
return constraints.ToArray();
}
return new TypeParameterConstraintClauseSyntax[0];
}
/// <summary>
/// Returns member access syntax.
/// </summary>
/// <param name="instance">
/// The instance.
/// </param>
/// <param name="member">
/// The member.
/// </param>
/// <returns>
/// The resulting <see cref="MemberAccessExpressionSyntax"/>.
/// </returns>
public static MemberAccessExpressionSyntax Member(this ExpressionSyntax instance, string member)
{
return instance.Member(member.ToIdentifierName());
}
/// <summary>
/// Returns qualified name syntax.
/// </summary>
/// <param name="instance">
/// The instance.
/// </param>
/// <param name="member">
/// The member.
/// </param>
/// <returns>
/// The resulting <see cref="MemberAccessExpressionSyntax"/>.
/// </returns>
public static QualifiedNameSyntax Qualify(this NameSyntax instance, string member)
{
return instance.Qualify(member.ToIdentifierName());
}
/// <summary>
/// Returns member access syntax.
/// </summary>
/// <param name="instance">
/// The instance.
/// </param>
/// <param name="member">
/// The member.
/// </param>
/// <param name="genericTypes">
/// The generic type parameters.
/// </param>
/// <returns>
/// The resulting <see cref="MemberAccessExpressionSyntax"/>.
/// </returns>
public static MemberAccessExpressionSyntax Member(
this ExpressionSyntax instance,
string member,
params Type[] genericTypes)
{
return
instance.Member(
member.ToGenericName()
.AddTypeArgumentListArguments(genericTypes.Select(_ => _.GetTypeSyntax()).ToArray()));
}
/// <summary>
/// Returns member access syntax.
/// </summary>
/// <typeparam name="TInstance">
/// The class type.
/// </typeparam>
/// <typeparam name="T">
/// The member return type.
/// </typeparam>
/// <param name="instance">
/// The instance.
/// </param>
/// <param name="member">
/// The member.
/// </param>
/// <param name="genericTypes">
/// The generic type parameters.
/// </param>
/// <returns>
/// The resulting <see cref="MemberAccessExpressionSyntax"/>.
/// </returns>
public static MemberAccessExpressionSyntax Member<TInstance, T>(
this ExpressionSyntax instance,
Expression<Func<TInstance, T>> member,
params Type[] genericTypes)
{
var methodCall = member.Body as MethodCallExpression;
if (methodCall != null)
{
if (genericTypes != null && genericTypes.Length > 0)
{
return instance.Member(methodCall.Method.Name, genericTypes);
}
return instance.Member(methodCall.Method.Name.ToIdentifierName());
}
var memberAccess = member.Body as MemberExpression;
if (memberAccess != null)
{
if (genericTypes != null && genericTypes.Length > 0)
{
return instance.Member(memberAccess.Member.Name, genericTypes);
}
return instance.Member(memberAccess.Member.Name.ToIdentifierName());
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns method invocation syntax.
/// </summary>
/// <typeparam name="T">
/// The method return type.
/// </typeparam>
/// <param name="expression">
/// The invocation expression.
/// </param>
/// <returns>
/// The resulting <see cref="InvocationExpressionSyntax"/>.
/// </returns>
public static InvocationExpressionSyntax Invoke<T>(this Expression<Func<T>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
var decl = methodCall.Method.DeclaringType;
return
SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
decl.GetNameSyntax(),
methodCall.Method.GetNameSyntax()));
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns method invocation syntax.
/// </summary>
/// <param name="expression">
/// The invocation expression.
/// </param>
/// <param name="instance">
/// The instance to invoke this method on, or <see langword="null"/> for static invocation.
/// </param>
/// <returns>
/// The resulting <see cref="InvocationExpressionSyntax"/>.
/// </returns>
public static InvocationExpressionSyntax Invoke(this Expression<Action> expression, ExpressionSyntax instance = null)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
if (instance == null && methodCall.Method.IsStatic)
{
instance = methodCall.Method.DeclaringType.GetNameSyntax();
}
return SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
instance,
methodCall.Method.Name.ToIdentifierName()));
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns method invocation syntax.
/// </summary>
/// <typeparam name="T">The argument type of <paramref name="expression"/>.</typeparam>
/// <param name="expression">
/// The invocation expression.
/// </param>
/// <param name="instance">
/// The instance to invoke this method on, or <see langword="null"/> for static invocation.
/// </param>
/// <returns>
/// The resulting <see cref="InvocationExpressionSyntax"/>.
/// </returns>
public static InvocationExpressionSyntax Invoke<T>(this Expression<Action<T>> expression, ExpressionSyntax instance = null)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
var decl = methodCall.Method.DeclaringType;
return SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
instance ?? decl.GetNameSyntax(),
methodCall.Method.Name.ToIdentifierName()));
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns member access syntax.
/// </summary>
/// <param name="instance">
/// The instance.
/// </param>
/// <param name="member">
/// The member.
/// </param>
/// <returns>
/// The resulting <see cref="MemberAccessExpressionSyntax"/>.
/// </returns>
public static MemberAccessExpressionSyntax Member(this ExpressionSyntax instance, IdentifierNameSyntax member)
{
return SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, instance, member);
}
/// <summary>
/// Returns member access syntax.
/// </summary>
/// <param name="instance">
/// The instance.
/// </param>
/// <param name="member">
/// The member.
/// </param>
/// <returns>
/// The resulting <see cref="MemberAccessExpressionSyntax"/>.
/// </returns>
public static MemberAccessExpressionSyntax Member(this ExpressionSyntax instance, GenericNameSyntax member)
{
return SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, instance, member);
}
/// <summary>
/// Returns member access syntax.
/// </summary>
/// <param name="instance">
/// The instance.
/// </param>
/// <param name="member">
/// The member.
/// </param>
/// <returns>
/// The resulting <see cref="MemberAccessExpressionSyntax"/>.
/// </returns>
public static QualifiedNameSyntax Qualify(this NameSyntax instance, IdentifierNameSyntax member)
{
return SyntaxFactory.QualifiedName(instance, member).WithDotToken(SyntaxFactory.Token(SyntaxKind.DotToken));
}
}
}
| |
// 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.Xml;
using System.IO;
using System.Collections;
using System.Diagnostics;
using System.Text;
using OLEDB.Test.ModuleCore;
namespace System.Xml.XmlDiff
{
public enum NodePosition
{
Before = 0,
After = 1,
Unknown = 2,
Same = 3
}
public enum XmlDiffNodeType
{
Element = 0,
Attribute = 1,
ER = 2,
Text = 3,
CData = 4,
Comment = 5,
PI = 6,
WS = 7,
Document = 8
}
internal class PositionInfo : IXmlLineInfo
{
public virtual bool HasLineInfo() { return false; }
public virtual int LineNumber { get { return 0; } }
public virtual int LinePosition { get { return 0; } }
public static PositionInfo GetPositionInfo(Object o)
{
IXmlLineInfo lineInfo = o as IXmlLineInfo;
if (lineInfo != null && lineInfo.HasLineInfo())
{
return new ReaderPositionInfo(lineInfo);
}
else
{
return new PositionInfo();
}
}
}
internal class ReaderPositionInfo : PositionInfo
{
private IXmlLineInfo _mlineInfo;
public ReaderPositionInfo(IXmlLineInfo lineInfo)
{
_mlineInfo = lineInfo;
}
public override bool HasLineInfo() { return true; }
public override int LineNumber { get { return _mlineInfo.LineNumber; } }
public override int LinePosition
{
get { return _mlineInfo.LinePosition; }
}
}
public class XmlDiffDocument : XmlDiffNode
{
private bool _bLoaded;
private bool _bIgnoreAttributeOrder;
private bool _bIgnoreChildOrder;
private bool _bIgnoreComments;
private bool _bIgnoreWhitespace;
private bool _bIgnoreDTD;
private bool _bIgnoreNS;
private bool _bIgnorePrefix;
private bool _bCDataAsText;
private bool _bNormalizeNewline;
public XmlNameTable nameTable;
public XmlDiffDocument()
: base()
{
_bLoaded = false;
_bIgnoreAttributeOrder = false;
_bIgnoreChildOrder = false;
_bIgnoreComments = false;
_bIgnoreWhitespace = false;
_bIgnoreDTD = false;
_bCDataAsText = false;
}
public XmlDiffOption Option
{
set
{
this.IgnoreAttributeOrder = (((int)value & (int)(XmlDiffOption.IgnoreAttributeOrder)) > 0);
this.IgnoreChildOrder = (((int)value & (int)(XmlDiffOption.IgnoreChildOrder)) > 0);
this.IgnoreComments = (((int)value & (int)(XmlDiffOption.IgnoreComments)) > 0);
this.IgnoreWhitespace = (((int)value & (int)(XmlDiffOption.IgnoreWhitespace)) > 0);
this.IgnoreDTD = (((int)value & (int)(XmlDiffOption.IgnoreDTD)) > 0);
this.IgnoreNS = (((int)value & (int)(XmlDiffOption.IgnoreNS)) > 0);
this.IgnorePrefix = (((int)value & (int)(XmlDiffOption.IgnorePrefix)) > 0);
this.CDataAsText = (((int)value & (int)(XmlDiffOption.CDataAsText)) > 0);
this.NormalizeNewline = (((int)value & (int)(XmlDiffOption.NormalizeNewline)) > 0);
}
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Document; } }
public bool IgnoreAttributeOrder
{
get { return this._bIgnoreAttributeOrder; }
set { this._bIgnoreAttributeOrder = value; }
}
public bool IgnoreChildOrder
{
get { return this._bIgnoreChildOrder; }
set { this._bIgnoreChildOrder = value; }
}
public bool IgnoreComments
{
get { return this._bIgnoreComments; }
set { this._bIgnoreComments = value; }
}
public bool IgnoreWhitespace
{
get { return this._bIgnoreWhitespace; }
set { this._bIgnoreWhitespace = value; }
}
public bool IgnoreDTD
{
get { return this._bIgnoreDTD; }
set { this._bIgnoreDTD = value; }
}
public bool IgnoreNS
{
get { return this._bIgnoreNS; }
set { this._bIgnoreNS = value; }
}
public bool IgnorePrefix
{
get { return this._bIgnorePrefix; }
set { this._bIgnorePrefix = value; }
}
public bool CDataAsText
{
get { return this._bCDataAsText; }
set { this._bCDataAsText = value; }
}
public bool NormalizeNewline
{
get { return this._bNormalizeNewline; }
set { this._bNormalizeNewline = value; }
}
//NodePosition.Before is returned if node2 should be before node1;
//NodePosition.After is returned if node2 should be after node1;
//In any case, NodePosition.Unknown should never be returned.
internal NodePosition ComparePosition(XmlDiffNode node1, XmlDiffNode node2)
{
int nt1 = (int)(node1.NodeType);
int nt2 = (int)(node2.NodeType);
if (nt2 > nt1)
return NodePosition.After;
if (nt2 < nt1)
return NodePosition.Before;
//now nt1 == nt2
if (nt1 == (int)XmlDiffNodeType.Element)
{
return CompareElements(node1 as XmlDiffElement, node2 as XmlDiffElement);
}
else if (nt1 == (int)XmlDiffNodeType.Attribute)
{
return CompareAttributes(node1 as XmlDiffAttribute, node2 as XmlDiffAttribute);
}
else if (nt1 == (int)XmlDiffNodeType.ER)
{
return CompareERs(node1 as XmlDiffEntityReference, node2 as XmlDiffEntityReference);
}
else if (nt1 == (int)XmlDiffNodeType.PI)
{
return ComparePIs(node1 as XmlDiffProcessingInstruction, node2 as XmlDiffProcessingInstruction);
}
else if (node1 is XmlDiffCharacterData)
{
return CompareTextLikeNodes(node1 as XmlDiffCharacterData, node2 as XmlDiffCharacterData);
}
else
{
//something really wrong here, what should we do???
Debug.Assert(false, "ComparePosition meets an indecision situation.");
return NodePosition.Unknown;
}
}
private NodePosition CompareElements(XmlDiffElement elem1, XmlDiffElement elem2)
{
Debug.Assert(elem1 != null);
Debug.Assert(elem2 != null);
int nCompare = 0;
if ((nCompare = CompareText(elem2.LocalName, elem1.LocalName)) == 0)
{
if (IgnoreNS || (nCompare = CompareText(elem2.NamespaceURI, elem1.NamespaceURI)) == 0)
{
if (IgnorePrefix || (nCompare = CompareText(elem2.Prefix, elem1.Prefix)) == 0)
{
if ((nCompare = CompareText(elem2.Value, elem1.Value)) == 0)
{
if ((nCompare = CompareAttributes(elem2, elem1)) == 0)
{
return NodePosition.After;
}
}
}
}
}
if (nCompare > 0)
//elem2 > elem1
return NodePosition.After;
else
//elem2 < elem1
return NodePosition.Before;
}
private int CompareAttributes(XmlDiffElement elem1, XmlDiffElement elem2)
{
int count1 = elem1.AttributeCount;
int count2 = elem2.AttributeCount;
if (count1 > count2)
return 1;
else if (count1 < count2)
return -1;
else
{
XmlDiffAttribute current1 = elem1.FirstAttribute;
XmlDiffAttribute current2 = elem2.FirstAttribute;
// NodePosition result = 0;
int nCompare = 0;
while (current1 != null && current2 != null && nCompare == 0)
{
if ((nCompare = CompareText(current2.LocalName, current1.LocalName)) == 0)
{
if (IgnoreNS || (nCompare = CompareText(current2.NamespaceURI, current1.NamespaceURI)) == 0)
{
if (IgnorePrefix || (nCompare = CompareText(current2.Prefix, current1.Prefix)) == 0)
{
if ((nCompare = CompareText(current2.Value, current1.Value)) == 0)
{
//do nothing!
}
}
}
}
current1 = (XmlDiffAttribute)current1._next;
current2 = (XmlDiffAttribute)current2._next;
}
if (nCompare > 0)
//elem1 > attr2
return 1;
else
//elem1 < elem2
return -1;
}
}
private NodePosition CompareAttributes(XmlDiffAttribute attr1, XmlDiffAttribute attr2)
{
Debug.Assert(attr1 != null);
Debug.Assert(attr2 != null);
int nCompare = 0;
if ((nCompare = CompareText(attr2.LocalName, attr1.LocalName)) == 0)
{
if (IgnoreNS || (nCompare = CompareText(attr2.NamespaceURI, attr1.NamespaceURI)) == 0)
{
if (IgnorePrefix || (nCompare = CompareText(attr2.Prefix, attr1.Prefix)) == 0)
{
if ((nCompare = CompareText(attr2.Value, attr1.Value)) == 0)
{
return NodePosition.After;
}
}
}
}
if (nCompare > 0)
//attr2 > attr1
return NodePosition.After;
else
//attr2 < attr1
return NodePosition.Before;
}
private NodePosition CompareERs(XmlDiffEntityReference er1, XmlDiffEntityReference er2)
{
Debug.Assert(er1 != null);
Debug.Assert(er2 != null);
int nCompare = CompareText(er2.Name, er1.Name);
if (nCompare >= 0)
return NodePosition.After;
else
return NodePosition.Before;
}
private NodePosition ComparePIs(XmlDiffProcessingInstruction pi1, XmlDiffProcessingInstruction pi2)
{
Debug.Assert(pi1 != null);
Debug.Assert(pi2 != null);
int nCompare = 0;
if ((nCompare = CompareText(pi2.Name, pi1.Name)) == 0)
{
if ((nCompare = CompareText(pi2.Value, pi1.Value)) == 0)
{
return NodePosition.After;
}
}
if (nCompare > 0)
//pi2 > pi1
return NodePosition.After;
else
//pi2 < pi1
return NodePosition.Before;
}
private NodePosition CompareTextLikeNodes(XmlDiffCharacterData t1, XmlDiffCharacterData t2)
{
Debug.Assert(t1 != null);
Debug.Assert(t2 != null);
int nCompare = CompareText(t2.Value, t1.Value);
if (nCompare >= 0)
return NodePosition.After;
else
return NodePosition.Before;
}
//returns 0 if the same string; 1 if s1 > s1 and -1 if s1 < s2
private int CompareText(string s1, string s2)
{
int len = s1.Length;
//len becomes the smaller of the two
if (len > s2.Length)
len = s2.Length;
int nInd = 0;
char c1 = (char)0x0;
char c2 = (char)0x0;
while (nInd < len)
{
c1 = s1[nInd];
c2 = s2[nInd];
if (c1 < c2)
return -1; //s1 < s2
else if (c1 > c2)
return 1; //s1 > s2
nInd++;
}
if (s2.Length > s1.Length)
return -1; //s1 < s2
else if (s2.Length < s1.Length)
return 1; //s1 > s2
else return 0;
}
public virtual void Load(XmlReader reader)
{
if (_bLoaded)
throw new InvalidOperationException("The document already contains data and should not be used again.");
if (reader.ReadState == ReadState.Initial)
{
if (!reader.Read())
return;
}
PositionInfo pInfo = PositionInfo.GetPositionInfo(reader);
ReadChildNodes(this, reader, pInfo);
this._bLoaded = true;
this.nameTable = reader.NameTable;
}
internal void ReadChildNodes(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
bool lookAhead = false;
do
{
lookAhead = false;
switch (reader.NodeType)
{
case XmlNodeType.Element:
LoadElement(parent, reader, pInfo);
break;
case XmlNodeType.Comment:
if (!IgnoreComments)
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.Comment);
break;
case XmlNodeType.ProcessingInstruction:
LoadPI(parent, reader, pInfo);
break;
case XmlNodeType.SignificantWhitespace:
if (reader.XmlSpace == XmlSpace.Preserve)
{
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.WS);
}
break;
case XmlNodeType.CDATA:
if (!CDataAsText)
{
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.CData);
}
else //merge with adjacent text/CDATA nodes
{
StringBuilder text = new StringBuilder();
text.Append(reader.Value);
while ((lookAhead = reader.Read()) && (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA))
{
text.Append(reader.Value);
}
LoadTextNode(parent, text.ToString(), pInfo, XmlDiffNodeType.Text);
}
break;
case XmlNodeType.Text:
if (!CDataAsText)
{
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.Text);
}
else //megre with adjacent text/CDATA nodes
{
StringBuilder text = new StringBuilder();
text.Append(reader.Value);
while ((lookAhead = reader.Read()) && (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA))
{
text.Append(reader.Value);
}
LoadTextNode(parent, text.ToString(), pInfo, XmlDiffNodeType.Text);
}
break;
case XmlNodeType.EntityReference:
LoadEntityReference(parent, reader, pInfo);
break;
case XmlNodeType.EndElement:
SetElementEndPosition(parent as XmlDiffElement, pInfo);
return;
case XmlNodeType.Attribute: //attribute at top level
string attrVal = reader.Name + "=\"" + reader.Value + "\"";
LoadTopLevelAttribute(parent, attrVal, pInfo, XmlDiffNodeType.Text);
break;
default:
break;
}
} while (lookAhead || reader.Read());
}
private void LoadElement(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
XmlDiffElement elem = null;
bool bEmptyElement = reader.IsEmptyElement;
if (bEmptyElement)
elem = new XmlDiffEmptyElement(reader.LocalName, reader.Prefix, reader.NamespaceURI);
else
elem = new XmlDiffElement(reader.LocalName, reader.Prefix, reader.NamespaceURI);
elem.LineNumber = pInfo.LineNumber;
elem.LinePosition = pInfo.LinePosition;
ReadAttributes(elem, reader, pInfo);
if (!bEmptyElement)
{
reader.Read(); //move to child
ReadChildNodes(elem, reader, pInfo);
}
InsertChild(parent, elem);
}
private void ReadAttributes(XmlDiffElement parent, XmlReader reader, PositionInfo pInfo)
{
if (reader.MoveToFirstAttribute())
{
XmlDiffAttribute attr = new XmlDiffAttribute(reader.LocalName, reader.Prefix, reader.NamespaceURI, reader.Value);
attr.LineNumber = pInfo.LineNumber;
attr.LinePosition = pInfo.LinePosition;
InsertAttribute(parent, attr);
while (reader.MoveToNextAttribute())
{
attr = new XmlDiffAttribute(reader.LocalName, reader.Prefix, reader.NamespaceURI, reader.Value);
attr.LineNumber = pInfo.LineNumber;
attr.LinePosition = pInfo.LinePosition;
InsertAttribute(parent, attr);
}
}
}
private void LoadTextNode(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo, XmlDiffNodeType nt)
{
XmlDiffCharacterData textNode = new XmlDiffCharacterData(reader.Value, nt, this.NormalizeNewline);
textNode.LineNumber = pInfo.LineNumber;
textNode.LinePosition = pInfo.LinePosition;
InsertChild(parent, textNode);
}
private void LoadTextNode(XmlDiffNode parent, string text, PositionInfo pInfo, XmlDiffNodeType nt)
{
XmlDiffCharacterData textNode = new XmlDiffCharacterData(text, nt, this.NormalizeNewline);
textNode.LineNumber = pInfo.LineNumber;
textNode.LinePosition = pInfo.LinePosition;
InsertChild(parent, textNode);
}
private void LoadTopLevelAttribute(XmlDiffNode parent, string text, PositionInfo pInfo, XmlDiffNodeType nt)
{
XmlDiffCharacterData textNode = new XmlDiffCharacterData(text, nt, this.NormalizeNewline);
textNode.LineNumber = pInfo.LineNumber;
textNode.LinePosition = pInfo.LinePosition;
InsertTopLevelAttributeAsText(parent, textNode);
}
private void LoadPI(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
XmlDiffProcessingInstruction pi = new XmlDiffProcessingInstruction(reader.Name, reader.Value);
pi.LineNumber = pInfo.LineNumber;
pi.LinePosition = pInfo.LinePosition;
InsertChild(parent, pi);
}
private void LoadEntityReference(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
XmlDiffEntityReference er = new XmlDiffEntityReference(reader.Name);
er.LineNumber = pInfo.LineNumber;
er.LinePosition = pInfo.LinePosition;
InsertChild(parent, er);
}
private void SetElementEndPosition(XmlDiffElement elem, PositionInfo pInfo)
{
Debug.Assert(elem != null);
elem.EndLineNumber = pInfo.LineNumber;
elem.EndLinePosition = pInfo.LinePosition;
}
private void InsertChild(XmlDiffNode parent, XmlDiffNode newChild)
{
if (IgnoreChildOrder)
{
XmlDiffNode child = parent.FirstChild;
XmlDiffNode prevChild = null;
while (child != null && (ComparePosition(child, newChild) == NodePosition.After))
{
prevChild = child;
child = child.NextSibling;
}
parent.InsertChildAfter(prevChild, newChild);
}
else
parent.InsertChildAfter(parent.LastChild, newChild);
}
private void InsertTopLevelAttributeAsText(XmlDiffNode parent, XmlDiffCharacterData newChild)
{
if (parent.LastChild != null && (parent.LastChild.NodeType == XmlDiffNodeType.Text || parent.LastChild.NodeType == XmlDiffNodeType.WS))
{
((XmlDiffCharacterData)parent.LastChild).Value = ((XmlDiffCharacterData)parent.LastChild).Value + " " + newChild.Value;
}
else
{
parent.InsertChildAfter(parent.LastChild, newChild);
}
}
private void InsertAttribute(XmlDiffElement parent, XmlDiffAttribute newAttr)
{
Debug.Assert(parent != null);
Debug.Assert(newAttr != null);
newAttr._parent = parent;
if (IgnoreAttributeOrder)
{
XmlDiffAttribute attr = parent.FirstAttribute;
XmlDiffAttribute prevAttr = null;
while (attr != null && (CompareAttributes(attr, newAttr) == NodePosition.After))
{
prevAttr = attr;
attr = (XmlDiffAttribute)(attr.NextSibling);
}
parent.InsertAttributeAfter(prevAttr, newAttr);
}
else
parent.InsertAttributeAfter(parent.LastAttribute, newAttr);
}
public override void WriteTo(XmlWriter w)
{
WriteContentTo(w);
}
public override void WriteContentTo(XmlWriter w)
{
XmlDiffNode child = FirstChild;
while (child != null)
{
child.WriteTo(w);
child = child.NextSibling;
}
}
public XmlDiffNavigator CreateNavigator()
{
return new XmlDiffNavigator(this);
}
public void SortChildren()
{
if (this.FirstChild != null)
{
XmlDiffNode _first = this.FirstChild;
XmlDiffNode _current = this.FirstChild;
XmlDiffNode _last = this.LastChild;
this._firstChild = null;
this._lastChild = null;
//set flag to ignore child order
bool temp = IgnoreChildOrder;
IgnoreChildOrder = true;
XmlDiffNode _next = null;
do
{
if (_current is XmlDiffElement)
_next = _current._next;
_current._next = null;
InsertChild(this, _current);
if (_current == _last)
break;
_current = _next;
}
while (true);
//restore flag for ignoring child order
IgnoreChildOrder = temp;
}
}
void SortChildren(XmlDiffElement elem)
{
if (elem.FirstChild != null)
{
XmlDiffNode _first = elem.FirstChild;
XmlDiffNode _current = elem.FirstChild;
XmlDiffNode _last = elem.LastChild;
elem._firstChild = null;
elem._lastChild = null;
//set flag to ignore child order
bool temp = IgnoreChildOrder;
IgnoreChildOrder = true;
XmlDiffNode _next = null;
do
{
if (_current is XmlDiffElement)
_next = _current._next;
_current._next = null;
InsertChild(elem, _current);
if (_current == _last)
break;
_current = _next;
}
while (true);
//restore flag for ignoring child order
IgnoreChildOrder = temp;
}
}
}
//navgator over the xmldiffdocument
public class XmlDiffNavigator
{
private XmlDiffDocument _document;
private XmlDiffNode _currentNode;
public XmlDiffNavigator(XmlDiffDocument doc)
{
_document = doc;
_currentNode = _document;
}
public XmlDiffNavigator Clone()
{
XmlDiffNavigator _clone = new XmlDiffNavigator(_document);
if (!_clone.MoveTo(this))
throw new Exception("Cannot clone");
return _clone;
}
public NodePosition ComparePosition(XmlDiffNavigator nav)
{
XmlDiffNode targetNode = ((XmlDiffNavigator)nav).CurrentNode;
if (!(nav is XmlDiffNavigator))
{
return NodePosition.Unknown;
}
if (targetNode == this.CurrentNode)
{
return NodePosition.Same;
}
else
{
if (this.CurrentNode.ParentNode == null) //this is root
{
return NodePosition.After;
}
else if (targetNode.ParentNode == null) //this is root
{
return NodePosition.Before;
}
else //look in the following nodes
{
if (targetNode.LineNumber != 0 && this.CurrentNode.LineNumber != 0)
{
if (targetNode.LineNumber > this.CurrentNode.LineNumber)
{
return NodePosition.Before;
}
else if (targetNode.LineNumber == this.CurrentNode.LineNumber && targetNode.LinePosition > this.CurrentNode.LinePosition)
{
return NodePosition.Before;
}
else
return NodePosition.After;
}
return NodePosition.Before;
}
}
}
public String GetAttribute(String localName, String namespaceURI)
{
if (_currentNode is XmlDiffElement)
{
return ((XmlDiffElement)_currentNode).GetAttributeValue(localName, namespaceURI);
}
return "";
}
public String GetNamespace(String name)
{
Debug.Assert(false, "GetNamespace is NYI");
return "";
}
public bool IsSamePosition(XmlDiffNavigator other)
{
if (other is XmlDiffNavigator)
{
if (_currentNode == ((XmlDiffNavigator)other).CurrentNode)
return true;
}
return false;
}
public bool MoveTo(XmlDiffNavigator other)
{
if (other is XmlDiffNavigator)
{
_currentNode = ((XmlDiffNavigator)other).CurrentNode;
return true;
}
return false;
}
public bool MoveToAttribute(String localName, String namespaceURI)
{
if (_currentNode is XmlDiffElement)
{
XmlDiffAttribute _attr = ((XmlDiffElement)_currentNode).GetAttribute(localName, namespaceURI);
if (_attr != null)
{
_currentNode = _attr;
return true;
}
}
return false;
}
public bool MoveToFirst()
{
if (!(_currentNode is XmlDiffAttribute))
{
if (_currentNode.ParentNode.FirstChild == _currentNode)
{
if (_currentNode.ParentNode.FirstChild._next != null)
{
_currentNode = _currentNode.ParentNode.FirstChild._next;
return true;
}
}
else
{
_currentNode = _currentNode.ParentNode.FirstChild;
return true;
}
}
return false;
}
public bool MoveToFirstAttribute()
{
if (_currentNode is XmlDiffElement)
{
if (((XmlDiffElement)_currentNode).FirstAttribute != null)
{
XmlDiffAttribute _attr = ((XmlDiffElement)_currentNode).FirstAttribute;
while (_attr != null && IsNamespaceNode(_attr))
{
_attr = (XmlDiffAttribute)_attr._next;
}
if (_attr != null)
{
_currentNode = _attr;
return true;
}
}
}
return false;
}
public bool MoveToFirstChild()
{
if ((_currentNode is XmlDiffDocument || _currentNode is XmlDiffElement) && _currentNode.FirstChild != null)
{
_currentNode = _currentNode.FirstChild;
return true;
}
return false;
}
public bool MoveToId(String id)
{
Debug.Assert(false, "MoveToId is NYI");
return false;
}
public bool MoveToNamespace(String name)
{
Debug.Assert(false, "MoveToNamespace is NYI");
return false;
}
public bool MoveToNext()
{
if (!(_currentNode is XmlDiffAttribute) && _currentNode._next != null)
{
_currentNode = _currentNode._next;
return true;
}
return false;
}
public bool MoveToNextAttribute()
{
if (_currentNode is XmlDiffAttribute)
{
XmlDiffAttribute _attr = (XmlDiffAttribute)_currentNode._next;
while (_attr != null && IsNamespaceNode(_attr))
{
_attr = (XmlDiffAttribute)_attr._next;
}
if (_attr != null)
{
_currentNode = _attr;
return true;
}
}
return false;
}
private bool IsNamespaceNode(XmlDiffAttribute attr)
{
return attr.LocalName.ToLower() == "xmlns" ||
attr.Prefix.ToLower() == "xmlns";
}
public bool MoveToParent()
{
if (!(_currentNode is XmlDiffDocument))
{
_currentNode = _currentNode.ParentNode;
return true;
}
return false;
}
public bool MoveToPrevious()
{
if (_currentNode != _currentNode.ParentNode.FirstChild)
{
XmlDiffNode _current = _currentNode.ParentNode.FirstChild;
XmlDiffNode _prev = _currentNode.ParentNode.FirstChild;
while (_current != _currentNode)
{
_prev = _current;
_current = _current._next;
}
_currentNode = _prev;
return true;
}
return false;
}
public void MoveToRoot()
{
_currentNode = _document;
}
public string LocalName
{
get
{
if (_currentNode.NodeType == XmlDiffNodeType.Element)
{
return ((XmlDiffElement)_currentNode).LocalName;
}
else if (_currentNode.NodeType == XmlDiffNodeType.Attribute)
{
return ((XmlDiffAttribute)_currentNode).LocalName;
}
else if (_currentNode.NodeType == XmlDiffNodeType.PI)
{
return ((XmlDiffProcessingInstruction)_currentNode).Name;
}
return "";
}
}
public string Name
{
get
{
if (_currentNode.NodeType == XmlDiffNodeType.Element)
{
return _document.nameTable.Get(((XmlDiffElement)_currentNode).Name);
}
else if (_currentNode.NodeType == XmlDiffNodeType.Attribute)
{
return ((XmlDiffAttribute)_currentNode).Name;
}
else if (_currentNode.NodeType == XmlDiffNodeType.PI)
{
return ((XmlDiffProcessingInstruction)_currentNode).Name;
}
return "";
}
}
public string NamespaceURI
{
get
{
if (_currentNode is XmlDiffElement)
{
return ((XmlDiffElement)_currentNode).NamespaceURI;
}
else if (_currentNode is XmlDiffAttribute)
{
return ((XmlDiffAttribute)_currentNode).NamespaceURI;
}
return "";
}
}
public string Value
{
get
{
if (_currentNode is XmlDiffAttribute)
{
return ((XmlDiffAttribute)_currentNode).Value;
}
else if (_currentNode is XmlDiffCharacterData)
{
return ((XmlDiffCharacterData)_currentNode).Value;
}
else if (_currentNode is XmlDiffElement)
{
return ((XmlDiffElement)_currentNode).Value;
}
return "";
}
}
public string Prefix
{
get
{
if (_currentNode is XmlDiffElement)
{
return ((XmlDiffElement)_currentNode).Prefix;
}
else if (_currentNode is XmlDiffAttribute)
{
return ((XmlDiffAttribute)_currentNode).Prefix;
}
return "";
}
}
public string BaseURI
{
get
{
Debug.Assert(false, "BaseURI is NYI");
return "";
}
}
public string XmlLang
{
get
{
Debug.Assert(false, "XmlLang not supported");
return "";
}
}
public bool HasAttributes
{
get
{
return (_currentNode is XmlDiffElement && ((XmlDiffElement)_currentNode).FirstAttribute != null) ? true : false;
}
}
public bool HasChildren
{
get
{
return _currentNode._next != null ? true : false;
}
}
public bool IsEmptyElement
{
get
{
return _currentNode is XmlDiffEmptyElement ? true : false;
}
}
public XmlNameTable NameTable
{
get
{
return _document.nameTable;
}
}
public XmlDiffNode CurrentNode
{
get
{
return _currentNode;
}
}
public bool IsOnRoot()
{
return _currentNode == null ? true : false;
}
}
public class PropertyCollection : MyDict<string, object> { }
public abstract class XmlDiffNode
{
internal XmlDiffNode _next;
internal XmlDiffNode _firstChild;
internal XmlDiffNode _lastChild;
internal XmlDiffNode _parent;
internal int _lineNumber, _linePosition;
internal bool _bIgnoreValue;
private PropertyCollection _extendedProperties;
public XmlDiffNode()
{
this._next = null;
this._firstChild = null;
this._lastChild = null;
this._parent = null;
_lineNumber = 0;
_linePosition = 0;
}
public XmlDiffNode FirstChild
{
get
{
return this._firstChild;
}
}
public XmlDiffNode LastChild
{
get
{
return this._lastChild;
}
}
public XmlDiffNode NextSibling
{
get
{
return this._next;
}
}
public XmlDiffNode ParentNode
{
get
{
return this._parent;
}
}
public virtual bool IgnoreValue
{
get
{
return _bIgnoreValue;
}
set
{
_bIgnoreValue = value;
XmlDiffNode current = this._firstChild;
while (current != null)
{
current.IgnoreValue = value;
current = current._next;
}
}
}
public abstract XmlDiffNodeType NodeType { get; }
public virtual string OuterXml
{
get
{
StringWriter sw = new StringWriter();
XmlWriterSettings xws = new XmlWriterSettings();
xws.ConformanceLevel = ConformanceLevel.Auto;
xws.CheckCharacters = false;
XmlWriter xw = XmlWriter.Create(sw, xws);
WriteTo(xw);
xw.Dispose();
return sw.ToString();
}
}
public virtual string InnerXml
{
get
{
StringWriter sw = new StringWriter();
XmlWriterSettings xws = new XmlWriterSettings();
xws.ConformanceLevel = ConformanceLevel.Auto;
xws.CheckCharacters = false;
XmlWriter xw = XmlWriter.Create(sw, xws);
WriteTo(xw);
xw.Dispose();
return sw.ToString();
}
}
public abstract void WriteTo(XmlWriter w);
public abstract void WriteContentTo(XmlWriter w);
public PropertyCollection ExtendedProperties
{
get
{
if (_extendedProperties == null)
_extendedProperties = new PropertyCollection();
return _extendedProperties;
}
}
public virtual void InsertChildAfter(XmlDiffNode child, XmlDiffNode newChild)
{
Debug.Assert(newChild != null);
newChild._parent = this;
if (child == null)
{
newChild._next = this._firstChild;
this._firstChild = newChild;
}
else
{
Debug.Assert(child._parent == this);
newChild._next = child._next;
child._next = newChild;
}
if (newChild._next == null)
this._lastChild = newChild;
}
public virtual void DeleteChild(XmlDiffNode child)
{
if (child == this.FirstChild)//delete head
{
_firstChild = this.FirstChild.NextSibling;
}
else
{
XmlDiffNode current = this.FirstChild;
XmlDiffNode previous = null;
while (current != child)
{
previous = current;
current = current.NextSibling;
}
Debug.Assert(current != null);
if (current == this.LastChild) //tail being deleted
{
this._lastChild = current.NextSibling;
}
previous._next = current.NextSibling;
}
}
public int LineNumber
{
get { return this._lineNumber; }
set { this._lineNumber = value; }
}
public int LinePosition
{
get { return this._linePosition; }
set { this._linePosition = value; }
}
}
public class XmlDiffElement : XmlDiffNode
{
private string _lName;
private string _prefix;
private string _ns;
private XmlDiffAttribute _firstAttribute;
private XmlDiffAttribute _lastAttribute;
private int _attrC;
private int _endLineNumber, _endLinePosition;
public XmlDiffElement(string localName, string prefix, string ns)
: base()
{
this._lName = localName;
this._prefix = prefix;
this._ns = ns;
this._firstAttribute = null;
this._lastAttribute = null;
this._attrC = -1;
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Element; } }
public string LocalName { get { return this._lName; } }
public string NamespaceURI { get { return this._ns; } }
public string Prefix { get { return this._prefix; } }
public string Name
{
get
{
if (this._prefix.Length > 0)
return Prefix + ":" + LocalName;
else
return LocalName;
}
}
public XmlDiffAttribute FirstAttribute
{
get
{
return this._firstAttribute;
}
}
public XmlDiffAttribute LastAttribute
{
get
{
return this._lastAttribute;
}
}
public string GetAttributeValue(string LocalName, string NamespaceUri)
{
if (_firstAttribute != null)
{
XmlDiffAttribute _current = _firstAttribute;
do
{
if (_current.LocalName == LocalName && _current.NamespaceURI == NamespaceURI)
{
return _current.Value;
}
_current = (XmlDiffAttribute)_current._next;
}
while (_current != _lastAttribute);
}
return "";
}
public XmlDiffAttribute GetAttribute(string LocalName, string NamespaceUri)
{
if (_firstAttribute != null)
{
XmlDiffAttribute _current = _firstAttribute;
do
{
if (_current.LocalName == LocalName && _current.NamespaceURI == NamespaceURI)
{
return _current;
}
_current = (XmlDiffAttribute)_current._next;
}
while (_current != _lastAttribute);
}
return null;
}
internal void InsertAttributeAfter(XmlDiffAttribute attr, XmlDiffAttribute newAttr)
{
Debug.Assert(newAttr != null);
newAttr._ownerElement = this;
if (attr == null)
{
newAttr._next = this._firstAttribute;
this._firstAttribute = newAttr;
}
else
{
Debug.Assert(attr._ownerElement == this);
newAttr._next = attr._next;
attr._next = newAttr;
}
if (newAttr._next == null)
this._lastAttribute = newAttr;
}
internal void DeleteAttribute(XmlDiffAttribute attr)
{
if (attr == this.FirstAttribute)//delete head
{
if (attr == this.LastAttribute) //tail being deleted
{
this._lastAttribute = (XmlDiffAttribute)attr.NextSibling;
}
_firstAttribute = (XmlDiffAttribute)this.FirstAttribute.NextSibling;
}
else
{
XmlDiffAttribute current = this.FirstAttribute;
XmlDiffAttribute previous = null;
while (current != attr)
{
previous = current;
current = (XmlDiffAttribute)current.NextSibling;
}
Debug.Assert(current != null);
if (current == this.LastAttribute) //tail being deleted
{
this._lastAttribute = (XmlDiffAttribute)current.NextSibling;
}
previous._next = current.NextSibling;
}
}
public int AttributeCount
{
get
{
if (this._attrC != -1)
return this._attrC;
XmlDiffAttribute attr = this._firstAttribute;
this._attrC = 0;
while (attr != null)
{
this._attrC++;
attr = (XmlDiffAttribute)attr.NextSibling;
}
return this._attrC;
}
}
public override bool IgnoreValue
{
set
{
base.IgnoreValue = value;
XmlDiffAttribute current = this._firstAttribute;
while (current != null)
{
current.IgnoreValue = value;
current = (XmlDiffAttribute)current._next;
}
}
}
public int EndLineNumber
{
get { return this._endLineNumber; }
set { this._endLineNumber = value; }
}
public int EndLinePosition
{
get { return this._endLinePosition; }
set { this._endLinePosition = value; }
}
public override void WriteTo(XmlWriter w)
{
w.WriteStartElement(Prefix, LocalName, NamespaceURI);
XmlDiffAttribute attr = this._firstAttribute;
while (attr != null)
{
attr.WriteTo(w);
attr = (XmlDiffAttribute)(attr.NextSibling);
}
WriteContentTo(w);
w.WriteFullEndElement();
}
public override void WriteContentTo(XmlWriter w)
{
XmlDiffNode child = FirstChild;
while (child != null)
{
child.WriteTo(w);
child = child.NextSibling;
}
}
public string Value
{
get
{
if (this.IgnoreValue)
{
return "";
}
if (_firstChild != null)
{
StringBuilder _bldr = new StringBuilder();
XmlDiffNode _current = _firstChild;
do
{
if (_current is XmlDiffCharacterData && _current.NodeType != XmlDiffNodeType.Comment && _current.NodeType != XmlDiffNodeType.PI)
{
_bldr.Append(((XmlDiffCharacterData)_current).Value);
}
else if (_current is XmlDiffElement)
{
_bldr.Append(((XmlDiffElement)_current).Value);
}
_current = _current._next;
}
while (_current != null);
return _bldr.ToString();
}
return "";
}
}
}
public class XmlDiffEmptyElement : XmlDiffElement
{
public XmlDiffEmptyElement(string localName, string prefix, string ns) : base(localName, prefix, ns) { }
}
public class XmlDiffAttribute : XmlDiffNode
{
internal XmlDiffElement _ownerElement;
private string _lName;
private string _prefix;
private string _ns;
private string _value;
public XmlDiffAttribute(string localName, string prefix, string ns, string value)
: base()
{
this._lName = localName;
this._prefix = prefix;
this._ns = ns;
this._value = value;
}
public string Value
{
get
{
if (this.IgnoreValue)
{
return "";
}
return this._value;
}
}
public string LocalName { get { return this._lName; } }
public string NamespaceURI { get { return this._ns; } }
public string Prefix { get { return this._prefix; } }
public string Name
{
get
{
if (this._prefix.Length > 0)
return this._prefix + ":" + this._lName;
else
return this._lName;
}
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Attribute; } }
public override void WriteTo(XmlWriter w)
{
w.WriteStartAttribute(Prefix, LocalName, NamespaceURI);
WriteContentTo(w);
w.WriteEndAttribute();
}
public override void WriteContentTo(XmlWriter w)
{
w.WriteString(Value);
}
}
public class XmlDiffEntityReference : XmlDiffNode
{
private string _name;
public XmlDiffEntityReference(string name)
: base()
{
this._name = name;
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.ER; } }
public string Name { get { return this._name; } }
public override void WriteTo(XmlWriter w)
{
w.WriteEntityRef(this._name);
}
public override void WriteContentTo(XmlWriter w)
{
XmlDiffNode child = this.FirstChild;
while (child != null)
{
child.WriteTo(w);
child = child.NextSibling;
}
}
}
public class XmlDiffCharacterData : XmlDiffNode
{
private string _value;
private XmlDiffNodeType _nodetype;
public XmlDiffCharacterData(string value, XmlDiffNodeType nt, bool NormalizeNewline)
: base()
{
this._value = value;
if (NormalizeNewline)
{
this._value = this._value.Replace("\n", "");
this._value = this._value.Replace("\r", "");
}
this._nodetype = nt;
}
public string Value
{
get
{
if (this.IgnoreValue)
{
return "";
}
return this._value;
}
set
{
_value = value;
}
}
public override XmlDiffNodeType NodeType { get { return _nodetype; } }
public override void WriteTo(XmlWriter w)
{
switch (this._nodetype)
{
case XmlDiffNodeType.Comment:
w.WriteComment(Value);
break;
case XmlDiffNodeType.CData:
w.WriteCData(Value);
break;
case XmlDiffNodeType.WS:
case XmlDiffNodeType.Text:
w.WriteString(Value);
break;
default:
Debug.Assert(false, "Wrong type for text-like node : " + this._nodetype.ToString());
break;
}
}
public override void WriteContentTo(XmlWriter w) { }
}
public class XmlDiffProcessingInstruction : XmlDiffCharacterData
{
private string _name;
public XmlDiffProcessingInstruction(string name, string value)
: base(value, XmlDiffNodeType.PI, false)
{
this._name = name;
}
public string Name { get { return this._name; } }
public override void WriteTo(XmlWriter w)
{
w.WriteProcessingInstruction(this._name, Value);
}
public override void WriteContentTo(XmlWriter w) { }
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace Medo.Security.Cryptography.PasswordSafe {
/// <summary>
/// Collection of header fields.
/// </summary>
[DebuggerDisplay("{Count} headers")]
public class HeaderCollection : IList<Header> {
/// <summary>
/// Create a new instance.
/// </summary>
internal HeaderCollection(Document owner, ICollection<Header> fields) {
foreach (var field in fields) {
if (field.Owner != null) { throw new ArgumentOutOfRangeException(nameof(fields), "Item cannot be in other collection."); }
}
Owner = owner;
BaseCollection.AddRange(fields);
foreach (var field in fields) {
field.Owner = this;
}
//ensure first field is always Version
if (!Contains(HeaderType.Version)) {
BaseCollection.Insert(0, new Header(HeaderType.Version, BitConverter.GetBytes(Header.DefaultVersion)));
} else {
var versionField = this[HeaderType.Version];
var versionIndex = IndexOf(versionField);
if (versionIndex > 0) {
BaseCollection.RemoveAt(versionIndex);
BaseCollection.Insert(0, versionField);
}
}
}
internal Document Owner { get; set; }
internal void MarkAsChanged() {
Owner.MarkAsChanged();
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private readonly List<Header> BaseCollection = new List<Header>();
#region ICollection
/// <summary>
/// Adds an item.
/// </summary>
/// <param name="item">Item.</param>
/// <exception cref="ArgumentNullException">Item cannot be null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Item cannot be in other collection.</exception>
/// <exception cref="NotSupportedException">Collection is read-only.</exception>
public void Add(Header item) {
if (item == null) { throw new ArgumentNullException(nameof(item), "Item cannot be null."); }
if (item.Owner != null) { throw new ArgumentOutOfRangeException(nameof(item), "Item cannot be in other collection."); }
if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); }
BaseCollection.Add(item);
item.Owner = this;
MarkAsChanged();
}
/// <summary>
/// Adds multiple items.
/// </summary>
/// <param name="items">Item.</param>
/// <exception cref="ArgumentNullException">Items cannot be null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Item cannot be in other collection.</exception>
/// <exception cref="NotSupportedException">Collection is read-only.</exception>
public void AddRange(IEnumerable<Header> items) {
if (items == null) { throw new ArgumentNullException(nameof(items), "Item cannot be null."); }
foreach (var item in items) {
if (item.Owner != null) { throw new ArgumentOutOfRangeException(nameof(items), "Item cannot be in other collection."); }
}
if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); }
BaseCollection.AddRange(items);
foreach (var item in items) {
item.Owner = this;
}
MarkAsChanged();
}
/// <summary>
/// Removes all items.
/// </summary>
/// <exception cref="NotSupportedException">Collection is read-only.</exception>
public void Clear() {
if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); }
for (var i = BaseCollection.Count - 1; i > 0; i--) { //remove all except first field (Version)
BaseCollection[i].Owner = null;
BaseCollection.RemoveAt(i);
}
MarkAsChanged();
}
/// <summary>
/// Determines whether the collection contains a specific item.
/// </summary>
/// <param name="item">The item to locate.</param>
public bool Contains(Header item) {
if (item == null) { return false; }
return BaseCollection.Contains(item);
}
/// <summary>
/// Copies the elements of the collection to an array, starting at a particular array index.
/// </summary>
/// <param name="array">The one-dimensional array that is the destination of the elements copied from collection.</param>
/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
public void CopyTo(Header[] array, int arrayIndex) {
BaseCollection.CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets the number of items contained in the collection.
/// </summary>
public int Count {
get { return BaseCollection.Count; }
}
/// <summary>
/// Searches for the specified item and returns the zero-based index of the first occurrence within the entire collection.
/// </summary>
/// <param name="item">The item to locate.</param>
public int IndexOf(Header item) {
return BaseCollection.IndexOf(item);
}
/// <summary>
/// Inserts an element into the collection at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which item should be inserted.</param>
/// <param name="item">The item to insert.</param>
/// <exception cref="ArgumentNullException">Item cannot be null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Index is less than 0. -or- Index is greater than collection count.</exception>
/// <exception cref="NotSupportedException">Collection is read-only.</exception>
public void Insert(int index, Header item) {
if (item == null) { throw new ArgumentNullException(nameof(item), "Item cannot be null."); }
if (item.Owner != null) { throw new ArgumentOutOfRangeException(nameof(item), "Item cannot be in other collection."); }
if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); }
if ((index == 0) && (item.HeaderType != HeaderType.Version)) { throw new ArgumentOutOfRangeException(nameof(index), "Version must be the first field."); }
BaseCollection.Insert(index, item);
item.Owner = this;
MarkAsChanged();
}
/// <summary>
/// Gets a value indicating whether the collection is read-only.
/// </summary>
public bool IsReadOnly {
get { return Owner.IsReadOnly; }
}
/// <summary>
/// Removes the item from the collection.
/// </summary>
/// <param name="item">The item to remove.</param>
/// <exception cref="ArgumentNullException">Item cannot be null.</exception>
/// <exception cref="NotSupportedException">Collection is read-only.</exception>
public bool Remove(Header item) {
if (item == null) { throw new ArgumentNullException(nameof(item), "Item cannot be null."); }
if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); }
if ((item.HeaderType == HeaderType.Version) && BaseCollection.IndexOf(item) == 0) { throw new ArgumentOutOfRangeException(nameof(item), "Cannot remove the first version field."); }
if (BaseCollection.Remove(item)) {
item.Owner = null;
MarkAsChanged();
return true;
} else {
return false;
}
}
/// <summary>
/// Removes the element at the specified index of the collection.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">Index is less than 0. -or- Index is equal to or greater than collection count.</exception>
/// <exception cref="NotSupportedException">Collection is read-only.</exception>
public void RemoveAt(int index) {
if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); }
if (index == 0) { throw new ArgumentOutOfRangeException(nameof(index), "Cannot remove the first version field."); }
var item = this[index];
BaseCollection.Remove(item);
item.Owner = null;
MarkAsChanged();
}
/// <summary>
/// Exposes the enumerator, which supports a simple iteration over a collection of a specified type.
/// </summary>
public IEnumerator<Header> GetEnumerator() {
var items = new List<Header>(BaseCollection); //to avoid exception if access/modification time has to be updated while in foreach
foreach (var item in items) {
yield return item;
}
}
/// <summary>
/// Exposes the enumerator, which supports a simple iteration over a non-generic collection.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <exception cref="ArgumentNullException">Value cannot be null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Index is less than 0. -or- Index is equal to or greater than collection count. -or- Duplicate name in collection.</exception>
/// <exception cref="NotSupportedException">Collection is read-only.</exception>
public Header this[int index] {
get { return BaseCollection[index]; }
set {
if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); }
if (value == null) { throw new ArgumentNullException(nameof(value), "Value cannot be null."); }
if (value.Owner != null) { throw new ArgumentOutOfRangeException(nameof(value), "Item cannot be in other collection."); }
if (Contains(value)) { throw new ArgumentOutOfRangeException(nameof(value), "Duplicate item in collection."); }
if ((index == 0) && (value.HeaderType != HeaderType.Version)) { throw new ArgumentOutOfRangeException(nameof(value), "Version must be the first field."); }
var item = BaseCollection[index];
item.Owner = null;
BaseCollection.RemoveAt(index);
BaseCollection.Insert(index, value);
value.Owner = this;
MarkAsChanged();
}
}
#endregion
#region ICollection extra
/// <summary>
/// Determines whether the collection contains a specific type.
/// If multiple elements exist with the same type, the first one is returned.
/// </summary>
/// <param name="type">The item type to locate.</param>
public bool Contains(HeaderType type) {
foreach (var item in BaseCollection) {
if (item.HeaderType == type) { return true; }
}
return false;
}
/// <summary>
/// Gets field based on a type.
/// If multiple elements exist with the same field type, the first one is returned.
/// If type does not exist, it is created.
///
/// If value is set to null, field is removed.
/// </summary>
/// <param name="type">Type.</param>
/// <exception cref="ArgumentOutOfRangeException">Only null value is supported.</exception>
/// <exception cref="NotSupportedException">Collection is read-only.</exception>
public Header this[HeaderType type] {
get {
foreach (var field in BaseCollection) {
if (field.HeaderType == type) {
return field;
}
}
if (IsReadOnly) { return new Header(type); } //return dummy header if collection is read-only
var newField = new Header(this, type); //create a new field if one cannot be found
int index;
for (index = 0; index < BaseCollection.Count; index++) {
if (BaseCollection[index].HeaderType > type) { break; }
}
BaseCollection.Insert(index, newField); //insert it in order (does not change order for existing ones)
return newField;
}
set {
if (IsReadOnly) { throw new NotSupportedException("Collection is read-only."); }
if (value != null) { throw new ArgumentOutOfRangeException(nameof(value), "Only null value is supported."); }
Header fieldToRemove = null;
foreach (var field in BaseCollection) {
if (field.HeaderType == type) {
fieldToRemove = field;
break;
}
}
if (fieldToRemove != null) {
Remove(fieldToRemove);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using ServiceStack.Common.Utils;
using ServiceStack.Redis;
using ServiceStack.Common.Extensions;
namespace RedisStackOverflow.ServiceInterface
{
public interface IRepository
{
User GetOrCreateUser(User user);
UserStat GetUserStats(long userId);
List<Question> GetAllQuestions();
List<QuestionResult> GetRecentQuestionResults(int skip, int take);
List<QuestionResult> GetQuestionsByUser(long userId);
List<QuestionResult> GetQuestionsTaggedWith(string tagName);
void StoreQuestion(Question question);
void StoreAnswer(Answer answer);
List<Answer> GetAnswersForQuestion(long questionId);
void VoteQuestionUp(long userId, long questionId);
void VoteQuestionDown(long userId, long questionId);
void VoteAnswerUp(long userId, long answerId);
void VoteAnswerDown(long userId, long answerId);
QuestionStat GetQuestionStats(long questionId);
QuestionResult GetQuestion(long questionId);
List<User> GetUsersByIds(IEnumerable<long> userIds);
SiteStats GetSiteStats();
void DeleteQuestion(long questionId);
void DeleteAnswer(long questionId, long answerId);
}
public class Repository : IRepository
{
//Definition of all the redis keys that are used for indexes
static class TagIndex
{
public static string Questions(string tag) { return "urn:tags>q:" + tag.ToLower(); }
public static string All { get { return "urn:tags"; } }
}
static class QuestionUserIndex
{
public static string UpVotes(long questionId) { return "urn:q>user+:" + questionId; }
public static string DownVotes(long questionId) { return "urn:q>user-:" + questionId; }
}
static class UserQuestionIndex
{
public static string Questions(long userId) { return "urn:user>q:" + userId; }
public static string UpVotes(long userId) { return "urn:user>q+:" + userId; }
public static string DownVotes(long userId) { return "urn:user>q-:" + userId; }
}
static class AnswerUserIndex
{
public static string UpVotes(long answerId) { return "urn:a>user+:" + answerId; }
public static string DownVotes(long answerId) { return "urn:a>user-:" + answerId; }
}
static class UserAnswerIndex
{
public static string Answers(long userId) { return "urn:user>a:" + userId; }
public static string UpVotes(long userId) { return "urn:user>a+:" + userId; }
public static string DownVotes(long userId) { return "urn:user>a-:" + userId; }
}
IRedisClientsManager RedisManager { get; set; }
public Repository(IRedisClientsManager redisManager)
{
RedisManager = redisManager;
}
public User GetOrCreateUser(User user)
{
if (user.DisplayName.IsNullOrEmpty())
throw new ArgumentNullException("DisplayName");
var userIdAliasKey = "id:User:DisplayName:" + user.DisplayName.ToLower();
using (var redis = RedisManager.GetClient())
{
//Get a typed version of redis client that works with <User>
var redisUsers = redis.As<User>();
//Find user by DisplayName if exists
var userKey = redis.GetValue(userIdAliasKey);
if (userKey != null)
return redisUsers.GetValue(userKey);
//Generate Id for New User
if (user.Id == default(long))
user.Id = redisUsers.GetNextSequence();
redisUsers.Store(user);
//Save reference to User key using the DisplayName alias
redis.SetEntry(userIdAliasKey, user.CreateUrn());
return redisUsers.GetById(user.Id);
}
}
public UserStat GetUserStats(long userId)
{
using (var redis = RedisManager.GetClient())
{
return new UserStat
{
UserId = userId,
QuestionsCount = redis.GetSetCount(UserQuestionIndex.Questions(userId)),
AnswersCount = redis.GetSetCount(UserAnswerIndex.Answers(userId)),
};
}
}
public List<Question> GetAllQuestions()
{
return RedisManager.ExecAs<Question>(redisQuestions => redisQuestions.GetAll()).ToList();
}
public List<QuestionResult> GetRecentQuestionResults(int skip, int take)
{
using (var redis = RedisManager.GetReadOnlyClient())
{
return ToQuestionResults(redis.As<Question>().GetLatestFromRecentsList(skip, take));
}
}
public List<QuestionResult> GetQuestionsByUser(long userId)
{
using (var redis = RedisManager.GetReadOnlyClient())
{
var questionIds = redis.GetAllItemsFromSet(UserQuestionIndex.Questions(userId));
var questions = redis.As<Question>().GetByIds(questionIds);
return ToQuestionResults(questions);
}
}
public List<QuestionResult> GetQuestionsTaggedWith(string tagName)
{
using (var redis = RedisManager.GetReadOnlyClient())
{
var questionIds = redis.GetAllItemsFromSet(TagIndex.Questions(tagName));
var questions = redis.As<Question>().GetByIds(questionIds);
return ToQuestionResults(questions);
}
}
private List<QuestionResult> ToQuestionResults(IEnumerable<Question> questions)
{
var uniqueUserIds = questions.ConvertAll(x => x.UserId).ToHashSet();
var usersMap = GetUsersByIds(uniqueUserIds).ToDictionary(x => x.Id);
var results = questions.ConvertAll(x => new QuestionResult { Question = x });
var resultsMap = results.ToDictionary(q => q.Question.Id);
results.ForEach(x => x.User = usersMap[x.Question.UserId]);
//Batch multiple operations in a single pipelined transaction (i.e. for a single network request/response)
RedisManager.ExecTrans(trans =>
{
foreach (var question in questions)
{
var q = question;
trans.QueueCommand(r => r.GetSetCount(QuestionUserIndex.UpVotes(q.Id)),
voteUpCount => resultsMap[q.Id].VotesUpCount = voteUpCount);
trans.QueueCommand(r => r.GetSetCount(QuestionUserIndex.DownVotes(q.Id)),
voteDownCount => resultsMap[q.Id].VotesDownCount = voteDownCount);
trans.QueueCommand(r => r.As<Question>().GetRelatedEntitiesCount<Answer>(q.Id),
answersCount => resultsMap[q.Id].AnswersCount = answersCount);
}
});
return results;
}
/// <summary>
/// Delete question by performing compensating actions to StoreQuestion() to keep the datastore in a consistent state
/// </summary>
/// <param name="questionId"></param>
public void DeleteQuestion(long questionId)
{
using (var redis = RedisManager.GetClient())
{
var redisQuestions = redis.As<Question>();
var question = redisQuestions.GetById(questionId);
if (question == null) return;
//decrement score in tags list
question.Tags.ForEach(tag => redis.IncrementItemInSortedSet(TagIndex.All, tag, -1));
//remove all related answers
redisQuestions.DeleteRelatedEntities<Answer>(questionId);
//remove this question from user index
redis.RemoveItemFromSet(UserQuestionIndex.Questions(question.UserId), questionId.ToString());
//remove tag => questions index for each tag
question.Tags.ForEach(tag => redis.RemoveItemFromSet(TagIndex.Questions(tag), questionId.ToString()));
redisQuestions.DeleteById(questionId);
}
}
public void StoreQuestion(Question question)
{
using (var redis = RedisManager.GetClient())
{
var redisQuestions = redis.As<Question>();
if (question.Tags == null) question.Tags = new List<string>();
if (question.Id == default(long))
{
question.Id = redisQuestions.GetNextSequence();
question.CreatedDate = DateTime.UtcNow;
//Increment the popularity for each new question tag
question.Tags.ForEach(tag => redis.IncrementItemInSortedSet(TagIndex.All, tag, 1));
}
redisQuestions.Store(question);
redisQuestions.AddToRecentsList(question);
redis.AddItemToSet(UserQuestionIndex.Questions(question.UserId), question.Id.ToString());
//Populate tag => questions index for each tag
question.Tags.ForEach(tag => redis.AddItemToSet(TagIndex.Questions(tag), question.Id.ToString()));
}
}
/// <summary>
/// Delete Answer by performing compensating actions to StoreAnswer() to keep the datastore in a consistent state
/// </summary>
/// <param name="questionId"></param>
/// <param name="answerId"></param>
public void DeleteAnswer(long questionId, long answerId)
{
using (var redis = RedisManager.GetClient())
{
var answer = redis.As<Question>().GetRelatedEntities<Answer>(questionId).FirstOrDefault(x => x.Id == answerId);
if (answer == null) return;
redis.As<Question>().DeleteRelatedEntity<Answer>(questionId, answerId);
//remove user => answer index
redis.RemoveItemFromSet(UserAnswerIndex.Answers(answer.UserId), answerId.ToString());
}
}
public void StoreAnswer(Answer answer)
{
using (var redis = RedisManager.GetClient())
{
if (answer.Id == default(long))
{
answer.Id = redis.As<Answer>().GetNextSequence();
answer.CreatedDate = DateTime.UtcNow;
}
//Store as a 'Related Answer' to the parent Question
redis.As<Question>().StoreRelatedEntities(answer.QuestionId, answer);
//Populate user => answer index
redis.AddItemToSet(UserAnswerIndex.Answers(answer.UserId), answer.Id.ToString());
}
}
public List<Answer> GetAnswersForQuestion(long questionId)
{
using (var redis = RedisManager.GetClient())
{
return redis.As<Question>().GetRelatedEntities<Answer>(questionId);
}
}
public void VoteQuestionUp(long userId, long questionId)
{
//Populate Question => User and User => Question set indexes in a single transaction
RedisManager.ExecTrans(trans =>
{
//Register upvote against question and remove any downvotes if any
trans.QueueCommand(redis => redis.AddItemToSet(QuestionUserIndex.UpVotes(questionId), userId.ToString()));
trans.QueueCommand(redis => redis.RemoveItemFromSet(QuestionUserIndex.DownVotes(questionId), userId.ToString()));
//Register upvote against user and remove any downvotes if any
trans.QueueCommand(redis => redis.AddItemToSet(UserQuestionIndex.UpVotes(userId), questionId.ToString()));
trans.QueueCommand(redis => redis.RemoveItemFromSet(UserQuestionIndex.DownVotes(userId), questionId.ToString()));
});
}
public void VoteQuestionDown(long userId, long questionId)
{
//Populate Question => User and User => Question set indexes in a single transaction
RedisManager.ExecTrans(trans =>
{
//Register downvote against question and remove any upvotes if any
trans.QueueCommand(redis => redis.AddItemToSet(QuestionUserIndex.DownVotes(questionId), userId.ToString()));
trans.QueueCommand(redis => redis.RemoveItemFromSet(QuestionUserIndex.UpVotes(questionId), userId.ToString()));
//Register downvote against user and remove any upvotes if any
trans.QueueCommand(redis => redis.AddItemToSet(UserQuestionIndex.DownVotes(userId), questionId.ToString()));
trans.QueueCommand(redis => redis.RemoveItemFromSet(UserQuestionIndex.UpVotes(userId), questionId.ToString()));
});
}
public void VoteAnswerUp(long userId, long answerId)
{
//Populate Question => User and User => Question set indexes in a single transaction
RedisManager.ExecTrans(trans =>
{
//Register upvote against answer and remove any downvotes if any
trans.QueueCommand(redis => redis.AddItemToSet(AnswerUserIndex.UpVotes(answerId), userId.ToString()));
trans.QueueCommand(redis => redis.RemoveItemFromSet(AnswerUserIndex.DownVotes(answerId), userId.ToString()));
//Register upvote against user and remove any downvotes if any
trans.QueueCommand(redis => redis.AddItemToSet(UserAnswerIndex.UpVotes(userId), answerId.ToString()));
trans.QueueCommand(redis => redis.RemoveItemFromSet(UserAnswerIndex.DownVotes(userId), answerId.ToString()));
});
}
public void VoteAnswerDown(long userId, long answerId)
{
//Populate Question => User and User => Question set indexes in a single transaction
RedisManager.ExecTrans(trans =>
{
//Register downvote against answer and remove any upvotes if any
trans.QueueCommand(redis => redis.AddItemToSet(AnswerUserIndex.DownVotes(answerId), userId.ToString()));
trans.QueueCommand(redis => redis.RemoveItemFromSet(AnswerUserIndex.UpVotes(answerId), userId.ToString()));
//Register downvote against user and remove any upvotes if any
trans.QueueCommand(redis => redis.AddItemToSet(UserAnswerIndex.DownVotes(userId), answerId.ToString()));
trans.QueueCommand(redis => redis.RemoveItemFromSet(UserAnswerIndex.UpVotes(userId), answerId.ToString()));
});
}
public QuestionResult GetQuestion(long questionId)
{
var question = RedisManager.ExecAs<Question>(redisQuestions => redisQuestions.GetById(questionId));
if (question == null) return null;
var result = ToQuestionResults(new[] { question })[0];
var answers = GetAnswersForQuestion(questionId);
var uniqueUserIds = answers.ConvertAll(x => x.UserId).ToHashSet();
var usersMap = GetUsersByIds(uniqueUserIds).ToDictionary(x => x.Id);
result.Answers = answers.ConvertAll(answer =>
new AnswerResult { Answer = answer, User = usersMap[answer.UserId] });
return result;
}
public List<User> GetUsersByIds(IEnumerable<long> userIds)
{
return RedisManager.ExecAs<User>(redisUsers => redisUsers.GetByIds(userIds)).ToList();
}
public QuestionStat GetQuestionStats(long questionId)
{
using (var redis = RedisManager.GetReadOnlyClient())
{
var result = new QuestionStat
{
VotesUpCount = redis.GetSetCount(QuestionUserIndex.UpVotes(questionId)),
VotesDownCount = redis.GetSetCount(QuestionUserIndex.DownVotes(questionId))
};
result.VotesTotal = result.VotesUpCount - result.VotesDownCount;
return result;
}
}
public List<Tag> GetTagsByPopularity(int skip, int take)
{
using (var redis = RedisManager.GetReadOnlyClient())
{
var tagEntries = redis.GetRangeWithScoresFromSortedSetDesc(TagIndex.All, skip, take);
var tags = tagEntries.ConvertAll(kvp => new Tag { Name = kvp.Key, Score = (int)kvp.Value });
return tags;
}
}
public SiteStats GetSiteStats()
{
using (var redis = RedisManager.GetClient())
{
return new SiteStats
{
QuestionsCount = redis.As<Question>().TypeIdsSet.Count,
AnswersCount = redis.As<Answer>().TypeIdsSet.Count,
TopTags = GetTagsByPopularity(0, 10)
};
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Universe.SqlTrace.LocalInstances
{
[Serializable]
public class LocalInstanceInfo
{
static readonly Version ZeroVersion = new Version(0,0,0,0);
[XmlArray("SqlServers"), XmlArrayItem("Instance")]
public List<SqlInstance> Instances = new List<SqlInstance>();
public void SortByVersionAscending()
{
Instances.Sort((x, y) => (x.Ver ?? ZeroVersion).CompareTo(y.Ver ?? ZeroVersion));
}
public void SortByVersionDescending()
{
SortByVersionAscending();
Instances.Reverse();
}
public void WriteToXml(TextWriter writer)
{
XmlTextWriter wr = new XmlTextWriter(writer);
wr.Formatting = Formatting.Indented;
XmlSerializer xs = new XmlSerializer(typeof(LocalInstanceInfo));
xs.Serialize(writer, this);
wr.Flush();
}
public override string ToString()
{
StringBuilder ret = new StringBuilder();
foreach (SqlInstance instance in Instances)
{
if (ret.Length > 0)
ret.Append("; ");
ret.Append(instance.IsDefault ? "(default)" : instance.Name);
if (instance.Ver != null)
ret.Append(" ").Append(instance.Ver);
ret.AppendFormat(" {{{0}}}", instance.ForecastLevelString);
ret.Append(" ").Append(instance.Status);
}
return ret.ToString();
}
[Serializable]
public class SqlInstance
{
[XmlAttribute]
public string Name { get; set; }
[XmlIgnore]
public Version Ver { get; set; }
[XmlIgnore]
public Version FileVer { get; set; }
[XmlAttribute("OK")]
public bool IsOK { get; set; }
[XmlAttribute("Edition")]
public SqlEdition Edition { get; set; }
[XmlAttribute("Description")]
public string Description { get; set; }
[XmlIgnore]
public ServiceControllerStatus Status { get; set; }
[XmlAttribute("Status")]
public string StatusString
{
get { return (int) Status == 0 ? "" : Status.ToString(); }
set { Status = string.IsNullOrEmpty(value) ? 0 : (ServiceControllerStatus)Enum.Parse(typeof(ServiceControllerStatus), value); }
}
[XmlAttribute("Version")]
public string VerAsString
{
get { return Ver == null ? null : Ver.ToString(); }
set { Ver = string.IsNullOrEmpty(value) ? null : new Version(value); }
}
[XmlAttribute("FileVersion")]
public string FileVerAsString
{
get { return FileVer == null ? null : FileVer.ToString(); }
set { FileVer = string.IsNullOrEmpty(value) ? null : new Version(value); }
}
public SqlInstance()
{
}
public SqlInstance(string name)
{
Name = name;
}
public bool IsDefault
{
get { return string.IsNullOrEmpty(Name); }
}
public string FullLocalName
{
get { return IsDefault ? "(local)" : ("(local)" + "\\" + Name); }
}
public string ServiceKey
{
get { return GetServiceKey(Name); }
}
[XmlAttribute("Level")]
public string Level { get; set; }
public VersionLevel ForecastLevel
{
get
{
Version ver = Ver ?? FileVer;
if (ver == null)
return VersionLevel.Unknown;
int mj = ver.Major, mn = ver.Minor, b = ver.Build;
if (mj == 8)
{
if (b < 194)
return VersionLevel.SQL2000 | VersionLevel.CTP;
else if (b < 384)
return VersionLevel.SQL2000 | VersionLevel.RTM;
else if (b < 532)
return VersionLevel.SQL2000 | VersionLevel.SP1;
else if (b < 760)
return VersionLevel.SQL2000 | VersionLevel.SP2;
else if (b < 2039)
return VersionLevel.SQL2000 | VersionLevel.SP3;
else
return VersionLevel.SQL2000 | VersionLevel.SP4;
}
else if (mj == 9)
{
if (b < 1399)
return VersionLevel.SQL2005 | VersionLevel.CTP;
else if (b < 2047)
return VersionLevel.SQL2005 | VersionLevel.RTM;
else if (b < 3042)
return VersionLevel.SQL2005 | VersionLevel.SP1;
else if (b < 4035)
return VersionLevel.SQL2005 | VersionLevel.SP2;
else if (b < 5000)
return VersionLevel.SQL2005 | VersionLevel.SP3;
else
return VersionLevel.SQL2005 | VersionLevel.SP4;
}
else if (mj == 10 && mn == 0)
{
if (b < 1600)
return VersionLevel.SQL2008 | VersionLevel.CTP;
if (b < 2531)
return VersionLevel.SQL2008 | VersionLevel.RTM;
if (b < 4000)
return VersionLevel.SQL2008 | VersionLevel.SP1;
if (b < 5500)
return VersionLevel.SQL2008 | VersionLevel.SP2;
else
return VersionLevel.SQL2008 | VersionLevel.SP3;
// SP3: 10.0.5500
}
else if (mj == 10 && (mn == 50 || mn == 51))
{
if (b < 1600)
return VersionLevel.SQL2008R2 | VersionLevel.CTP;
if (b < 2500)
return VersionLevel.SQL2008R2 | VersionLevel.RTM;
else
return VersionLevel.SQL2008R2 | VersionLevel.SP1;
}
else if (mj == 11)
{
// 2012: 11.0.2100.60
if (b < 2100)
return VersionLevel.SQL2012 | VersionLevel.CTP;
else
return VersionLevel.SQL2012 | VersionLevel.RTM;
}
else
return VersionLevel.Unknown;
}
}
public string ForecastLevelString
{
get
{
var fl = ForecastLevel;
var fields = typeof(VersionLevel).GetFields(BindingFlags.Static | BindingFlags.Public);
foreach (var fi in fields)
{
if (fl.Equals(fi.GetValue(null)))
{
var attrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
}
return fl.ToString();
}
}
}
public static string GetServiceKey(string instanceName)
{
return string.IsNullOrEmpty(instanceName) ? "MSSQLSERVER" : "MSSQL$" + instanceName;
}
}
[Flags]
public enum VersionLevel
{
Unknown = 0,
SQL2000 = 1,
SQL2005 = 2,
SQL2008 = 4,
SQL2008R2 = 8,
SQL2012 = 16,
CTP = 1024,
RTM = 1024 * 2,
SP1 = 1024 * 4,
SP2 = 1024 * 8,
SP3 = 1024 * 16,
SP4 = 1024 * 32,
// 2000
[Description("SQL Server 2000 CPT")]
SQL2000CTP = SQL2000 | CTP,
[Description("SQL Server 2000 RTM")]
SQL2000RTM = SQL2000 | RTM,
[Description("SQL Server 2000 SP1")]
SQL2000SP1 = SQL2000 | SP1,
[Description("SQL Server 2000 SP2")]
SQL2000SP2 = SQL2000 | SP2,
[Description("SQL Server 2000 SP3")]
SQL2000SP3 = SQL2000 | SP3,
[Description("SQL Server 2000 SP4")]
SQL2000SP4 = SQL2000 | SP4,
// 2005
[Description("SQL Server 2005 CTP")]
SQL2005CTP = SQL2005 | CTP,
[Description("SQL Server 2005 RTM")]
SQL2005RTM = SQL2005 | RTM,
[Description("SQL Server 2005 SP1")]
SQL2005SP1 = SQL2005 | SP1,
[Description("SQL Server 2005 SP2")]
SQL2005SP2 = SQL2005 | SP2,
[Description("SQL Server 2005 SP3")]
SQL2005SP3 = SQL2005 | SP3,
[Description("SQL Server 2005 SP4")]
SQL2005SP4 = SQL2005 | SP4,
// 2008
[Description("SQL Server 2008 CTP")]
SQL2008CTP = SQL2008 | CTP,
[Description("SQL Server 2008 RTM")]
SQL2008RTM = SQL2008 | RTM,
[Description("SQL Server 2008 SP1")]
SQL2008SP1 = SQL2008 | SP1,
[Description("SQL Server 2008 SP2")]
SQL2008SP2 = SQL2008 | SP2,
[Description("SQL Server 2008 SP3")]
SQL2008SP3 = SQL2008 | SP3,
// 2008 R2
[Description("SQL Server 2008 R2 CTP")]
SQL2008R2CTP = SQL2008R2 | CTP,
[Description("SQL Server 2008 R2 RTM")]
SQL2008R2RTM = SQL2008R2 | RTM,
[Description("SQL Server 2008 R2 SP1")]
SQL2008R2SP1 = SQL2008R2 | SP1,
// 2012
[Description("SQL Server 2012 CTP")]
SQL2012CTP = SQL2012 | CTP,
[Description("SQL Server 2012 RTM")]
SQL2012RTM = SQL2012 | RTM,
}
public enum SqlEdition
{
Unknown,
Express,
LeastStandard,
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.SqlClient;
using System.Linq;
using System.Reflection;
namespace Artisan.Orm
{
public static class MappingManager
{
private static readonly Dictionary<Type, Delegate> CreateObjectFuncDictionary = new Dictionary<Type, Delegate>();
private static readonly Dictionary<Type, Delegate> CreateObjectRowFuncDictionary = new Dictionary<Type, Delegate>();
private static readonly Dictionary<Type, Tuple<Func<DataTable>, Delegate>> CreateDataFuncsDictionary = new Dictionary<Type, Tuple<Func<DataTable>, Delegate>>();
private static readonly ConcurrentDictionary<string, Delegate> AutoCreateObjectFuncDictionary = new ConcurrentDictionary<string, Delegate>();
private static readonly ConcurrentDictionary<string, Tuple<Func<DataTable>, Delegate>> AutoCreateDataFuncsDictionary = new ConcurrentDictionary<string, Tuple<Func<DataTable>, Delegate>>();
private static readonly ConcurrentDictionary<string, SqlParameter[]> SqlParametersDictionary = new ConcurrentDictionary<string, SqlParameter[]>();
static MappingManager()
{
foreach (var type in GetTypesWithMapperForAttribute())
{
var attributes = type.GetCustomAttributes(typeof(MapperForAttribute), true);
if (attributes.Length == 0) continue;
foreach (var attribute in attributes.Cast<MapperForAttribute>())
{
var methodInfo = type.GetMethod("CreateObject", new Type[] { typeof(SqlDataReader) });
if (methodInfo == null)
{
if (attribute.RequiredMethods.Intersect(new []{RequiredMethod.All, RequiredMethod.AllMain, RequiredMethod.BothForObject, RequiredMethod.CreateObject}).Any())
throw new NullReferenceException($"Mapper {type.Name} does not contain required method CreateObject");
}
else
{
var funcType = typeof(Func<,>).MakeGenericType(typeof(SqlDataReader), attribute.MapperForType);
var del = Delegate.CreateDelegate(funcType, methodInfo);
CreateObjectFuncDictionary.Add(attribute.MapperForType, del);
}
methodInfo = type.GetMethod("CreateObjectRow", new Type[] { typeof(SqlDataReader) });
if (methodInfo == null)
{
if (attribute.RequiredMethods.Intersect(new []{RequiredMethod.All, RequiredMethod.BothForObject, RequiredMethod.CreateObjectRow}).Any())
throw new NullReferenceException($"Mapper {type.Name} does not contain required method CreateObjectRow");
}
else
{
var funcType = typeof(Func<,>).MakeGenericType(typeof(SqlDataReader), typeof(ObjectRow));
var createObjectRowDelegate = Delegate.CreateDelegate(funcType, methodInfo);
CreateObjectRowFuncDictionary.Add(attribute.MapperForType, createObjectRowDelegate);
}
Func<DataTable> createDataTableFunc = null;
methodInfo = type.GetMethod("CreateDataTable");
if (methodInfo == null)
{
if (attribute.RequiredMethods.Intersect(new []{RequiredMethod.All, RequiredMethod.BothForDataTable }).Any())
throw new NullReferenceException($"Mapper {type.Name} does not contain required method CreateDataTable");
}
else
{
createDataTableFunc = (Func<DataTable>)Delegate.CreateDelegate(typeof(Func<DataTable>), methodInfo);
}
Delegate createDataRowDelegate = null;
methodInfo = type.GetMethod("CreateDataRow", new Type[] { attribute.MapperForType });
if (methodInfo == null) {
if (attribute.RequiredMethods.Intersect(new []{RequiredMethod.All, RequiredMethod.BothForDataTable }).Any())
throw new NullReferenceException($"Mapper {type.Name} does not contain required method CreateDataRow");
}
else {
var funcType = typeof(Func<,>).MakeGenericType(attribute.MapperForType, typeof(object[]));
createDataRowDelegate = Delegate.CreateDelegate(funcType, methodInfo);
}
CreateDataFuncsDictionary.Add(attribute.MapperForType, Tuple.Create(createDataTableFunc, createDataRowDelegate));
}
}
}
public static Func<SqlDataReader, T> GetCreateObjectFunc<T>()
{
Delegate del;
if (CreateObjectFuncDictionary.TryGetValue(typeof(T), out del))
return (Func<SqlDataReader, T>)del;
throw new NullReferenceException($"CreateObject Func not found. Check if MapperFor {typeof(T).FullName} exists and CreateObject exist.");
}
public static Func<SqlDataReader, ObjectRow> GetCreateObjectRowFunc<T>()
{
Delegate del;
if (CreateObjectRowFuncDictionary.TryGetValue(typeof(T), out del))
return (Func<SqlDataReader, ObjectRow>)del;
throw new NullReferenceException($"CreateRow Func not found. Check if MapperFor {typeof(T).FullName} and CreateRow exist.");
}
public static Func<DataTable> GetCreateDataTableFunc<T>()
{
Tuple<Func<DataTable>, Delegate> tuple;
return CreateDataFuncsDictionary.TryGetValue(typeof(T), out tuple) ? tuple.Item1 : null;
}
public static Func<T, object[]> GetCreateDataRowFunc<T>()
{
Tuple<Func<DataTable>, Delegate> tuple;
if (CreateDataFuncsDictionary.TryGetValue(typeof(T), out tuple))
return (Func<T, object[]>)tuple.Item2;
return null;
}
public static bool GetCreateDataFuncs<T>(out Func<DataTable> createDataTableFunc, out Func<T, object[]> createDataRowFunc)
{
Tuple<Func<DataTable>, Delegate> tuple;
if (CreateDataFuncsDictionary.TryGetValue(typeof(T), out tuple))
{
createDataTableFunc = tuple.Item1;
createDataRowFunc = (Func<T, object[]>)tuple.Item2;
return true;
}
createDataTableFunc = null;
createDataRowFunc = null;
return false;
}
public static bool GetCreateDataFuncs(Type type, out Func<DataTable> createDataTableFunc, out Delegate createDataRowFunc)
{
Tuple<Func<DataTable>, Delegate> funcs;
if (CreateDataFuncsDictionary.TryGetValue(type, out funcs))
{
createDataTableFunc = funcs.Item1;
createDataRowFunc = funcs.Item2;
return true;
}
createDataTableFunc = null;
createDataRowFunc = null;
return false;
}
public static bool AddAutoCreateObjectFunc<T>(string key, Func<SqlDataReader, T> autoCreateObjectFunc)
{
return AutoCreateObjectFuncDictionary.TryAdd(key, autoCreateObjectFunc);
}
public static Func<SqlDataReader, T> GetAutoCreateObjectFunc<T>(string key)
{
Delegate del;
if (AutoCreateObjectFuncDictionary.TryGetValue(key, out del)) {
return (Func<SqlDataReader, T>)del;
}
return null;
}
public static bool AddAutoCreateDataFuncs<T>(string key, Func<DataTable> createDataTableFunc, Func<T, object[]> createDataRowFunc)
{
var funcs = new Tuple<Func<DataTable>, Delegate>(createDataTableFunc, createDataRowFunc);
return AutoCreateDataFuncsDictionary.TryAdd(key, funcs);
}
public static bool GetAutoCreateDataFuncs<T>(string key, out Func<DataTable> createDataTableFunc, out Func<T, object[]> createDataRowFunc)
{
Tuple<Func<DataTable>, Delegate> funcs;
if (AutoCreateDataFuncsDictionary.TryGetValue(key, out funcs))
{
createDataTableFunc = funcs.Item1;
createDataRowFunc = (Func<T, object[]>)funcs.Item2;
return true;
}
createDataTableFunc = null;
createDataRowFunc = null;
return false;
}
private static IEnumerable<Type> GetTypesWithMapperForAttribute()
{
foreach (Assembly assembly in GetCurrentAndDependentAssemblies())
{
foreach (Type type in assembly.GetTypes().Where(type => type.GetCustomAttributes(typeof(MapperForAttribute), true).Length > 0))
{
yield return type;
}
}
}
public static bool AddSqlParameters(string key, SqlParameter[] sqlParameters)
{
return SqlParametersDictionary.TryAdd(key, sqlParameters);
}
public static SqlParameter[] GetSqlParameters(string key)
{
return SqlParametersDictionary.TryGetValue(key, out var collection) ? collection : null;
}
#region [ Get Dependent Assemblies ]
private static IEnumerable<Assembly> GetCurrentAndDependentAssemblies()
{
var currentAssembly = typeof(MappingManager).Assembly;
return AppDomain.CurrentDomain.GetAssemblies()
// http://stackoverflow.com/a/8850495/623190
.Where(a => GetNamesOfAssembliesReferencedBy(a).Contains(currentAssembly.FullName))
.Concat(new[] { currentAssembly })
// https://www.codeproject.com/Articles/1155836/Artisan-Orm-or-How-To-Reinvent-the-Wheel?msg=5419092#xx5419092xx
.GroupBy(a => a.FullName)
.Select(x => x.First());
}
public static IEnumerable<string> GetNamesOfAssembliesReferencedBy(Assembly assembly)
{
return assembly.GetReferencedAssemblies()
.Select(assemblyName => assemblyName.FullName);
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// AssociativeAggregationOperator.cs
//
// <OWNER>[....]</OWNER>
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Threading;
#if SILVERLIGHT
using System.Core; // for System.Core.SR
#endif
namespace System.Linq.Parallel
{
/// <summary>
/// The aggregation operator is a little unique, in that the enumerators it returns
/// yield intermediate results instead of the final results. That's because there is
/// one last Aggregate operation that must occur in order to perform the final reduction
/// over the intermediate streams. In other words, the intermediate enumerators produced
/// by this operator are never seen by other query operators or consumers directly.
///
/// An aggregation performs parallel prefixing internally. Given a binary operator O,
/// it will generate intermediate results by folding O across partitions; then it
/// performs a final reduction by folding O accross the intermediate results. The
/// analysis engine knows about associativity and commutativity, and will ensure the
/// style of partitioning inserted into the tree is compatable with the operator.
///
/// For instance, say O is + (meaning it is AC), our input is {1,2,...,8}, and we
/// use 4 partitions to calculate the aggregation. Sequentially this would look
/// like this O(O(O(1,2),...),8), in other words ((1+2)+...)+8. The parallel prefix
/// of this (w/ 4 partitions) instead calculates the intermediate aggregations, i.e.:
/// t1 = O(1,2), t2 = O(3,4), ... t4 = O(7,8), aka t1 = 1+2, t2 = 3+4, t4 = 7+8.
/// The final step is to aggregate O over these intermediaries, i.e.
/// O(O(O(t1,t2),t3),t4), or ((t1+t2)+t3)+t4. This generalizes to any binary operator.
///
/// Beause some aggregations use a different input, intermediate, and output types,
/// we support an even more generalized aggregation type. In this model, we have
/// three operators, an intermediate (used for the incremental aggregations), a
/// final (used for the final summary of intermediate results), and a result selector
/// (used to perform whatever transformation is needed on the final summary).
/// </summary>
/// <typeparam name="TInput"></typeparam>
/// <typeparam name="TIntermediate"></typeparam>
/// <typeparam name="TOutput"></typeparam>
internal sealed class AssociativeAggregationOperator<TInput, TIntermediate, TOutput> : UnaryQueryOperator<TInput, TIntermediate>
{
private readonly TIntermediate m_seed; // A seed used during aggregation.
private readonly bool m_seedIsSpecified; // Whether a seed was specified. If not, the first element will be used.
private readonly bool m_throwIfEmpty; // Whether to throw an exception if the data source is empty.
// An intermediate reduction function.
private Func<TIntermediate, TInput, TIntermediate> m_intermediateReduce;
// A final reduction function.
private Func<TIntermediate, TIntermediate, TIntermediate> m_finalReduce;
// The result selector function.
private Func<TIntermediate, TOutput> m_resultSelector;
// A function that constructs seed instances
private Func<TIntermediate> m_seedFactory;
//---------------------------------------------------------------------------------------
// Constructs a new instance of an associative operator.
//
// Assumptions:
// This operator must be associative.
//
internal AssociativeAggregationOperator(IEnumerable<TInput> child, TIntermediate seed, Func<TIntermediate> seedFactory, bool seedIsSpecified,
Func<TIntermediate, TInput, TIntermediate> intermediateReduce,
Func<TIntermediate, TIntermediate, TIntermediate> finalReduce,
Func<TIntermediate, TOutput> resultSelector, bool throwIfEmpty, QueryAggregationOptions options)
:base(child)
{
Contract.Assert(child != null, "child data source cannot be null");
Contract.Assert(intermediateReduce != null, "need an intermediate reduce function");
Contract.Assert(finalReduce != null, "need a final reduce function");
Contract.Assert(resultSelector != null, "need a result selector function");
Contract.Assert(Enum.IsDefined(typeof(QueryAggregationOptions), options), "enum out of valid range");
Contract.Assert((options & QueryAggregationOptions.Associative) == QueryAggregationOptions.Associative, "expected an associative operator");
Contract.Assert(typeof(TIntermediate) == typeof(TInput) || seedIsSpecified, "seed must be specified if TIntermediate differs from TInput");
m_seed = seed;
m_seedFactory = seedFactory;
m_seedIsSpecified = seedIsSpecified;
m_intermediateReduce = intermediateReduce;
m_finalReduce = finalReduce;
m_resultSelector = resultSelector;
m_throwIfEmpty = throwIfEmpty;
}
//---------------------------------------------------------------------------------------
// Executes the entire query tree, and aggregates the intermediate results into the
// final result based on the binary operators and final reduction.
//
// Return Value:
// The single result of aggregation.
//
internal TOutput Aggregate()
{
Contract.Assert(m_finalReduce != null);
Contract.Assert(m_resultSelector != null);
TIntermediate accumulator = default(TIntermediate);
bool hadElements = false;
// Because the final reduction is typically much cheaper than the intermediate
// reductions over the individual partitions, and because each parallel partition
// will do a lot of work to produce a single output element, we prefer to turn off
// pipelining, and process the final reductions serially.
using (IEnumerator<TIntermediate> enumerator = GetEnumerator(ParallelMergeOptions.FullyBuffered, true))
{
// We just reduce the elements in each output partition. If the operation is associative,
// this will yield the correct answer. If not, we should never be calling this routine.
while (enumerator.MoveNext())
{
if (hadElements)
{
// Accumulate results by passing the current accumulation and current element to
// the reduction operation.
try
{
accumulator = m_finalReduce(accumulator, enumerator.Current);
}
catch (ThreadAbortException)
{
// Do not wrap ThreadAbortExceptions
throw;
}
catch (Exception ex)
{
// We need to wrap all exceptions into an aggregate.
throw new AggregateException(ex);
}
}
else
{
// This is the first element. Just set the accumulator to the first element.
accumulator = enumerator.Current;
hadElements = true;
}
}
// If there were no elements, we must throw an exception.
if (!hadElements)
{
if (m_throwIfEmpty)
{
throw new InvalidOperationException(SR.GetString(SR.NoElements));
}
else
{
accumulator = m_seedFactory == null ? m_seed : m_seedFactory();
}
}
}
// Finally, run the selection routine to yield the final element.
try
{
return m_resultSelector(accumulator);
}
catch (ThreadAbortException)
{
// Do not wrap ThreadAbortExceptions
throw;
}
catch (Exception ex)
{
// We need to wrap all exceptions into an aggregate.
throw new AggregateException(ex);
}
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<TIntermediate> Open(QuerySettings settings, bool preferStriping)
{
// We just open the child operator.
QueryResults<TInput> childQueryResults = Child.Open(settings, preferStriping);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TInput, TKey> inputStream, IPartitionedStreamRecipient<TIntermediate> recipient,
bool preferStriping, QuerySettings settings)
{
int partitionCount = inputStream.PartitionCount;
PartitionedStream<TIntermediate, int> outputStream = new PartitionedStream<TIntermediate, int>(
partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Correct);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new AssociativeAggregationOperatorEnumerator<TKey>(inputStream[i], this, i, settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TIntermediate> AsSequentialQuery(CancellationToken token)
{
Contract.Assert(false, "This method should never be called. Associative aggregation can always be parallelized.");
throw new NotSupportedException();
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
//---------------------------------------------------------------------------------------
// This enumerator type encapsulates the intermediary aggregation over the underlying
// (possibly partitioned) data source.
//
private class AssociativeAggregationOperatorEnumerator<TKey> : QueryOperatorEnumerator<TIntermediate, int>
{
private readonly QueryOperatorEnumerator<TInput, TKey> m_source; // The source data.
private readonly AssociativeAggregationOperator<TInput, TIntermediate, TOutput> m_reduceOperator; // The operator.
private readonly int m_partitionIndex; // The index of this partition.
private readonly CancellationToken m_cancellationToken;
private bool m_accumulated; // Whether we've accumulated already. (false-sharing risk, but only written once)
//---------------------------------------------------------------------------------------
// Instantiates a new aggregation operator.
//
internal AssociativeAggregationOperatorEnumerator(QueryOperatorEnumerator<TInput, TKey> source,
AssociativeAggregationOperator<TInput, TIntermediate, TOutput> reduceOperator, int partitionIndex,
CancellationToken cancellationToken)
{
Contract.Assert(source != null);
Contract.Assert(reduceOperator != null);
m_source = source;
m_reduceOperator = reduceOperator;
m_partitionIndex = partitionIndex;
m_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// This API, upon the first time calling it, walks the entire source query tree. It begins
// with an accumulator value set to the aggregation operator's seed, and always passes
// the accumulator along with the current element from the data source to the binary
// intermediary aggregation operator. The return value is kept in the accumulator. At
// the end, we will have our intermediate result, ready for final aggregation.
//
internal override bool MoveNext(ref TIntermediate currentElement, ref int currentKey)
{
Contract.Assert(m_reduceOperator != null);
Contract.Assert(m_reduceOperator.m_intermediateReduce != null, "expected a compiled operator");
// Only produce a single element. Return false if MoveNext() was already called before.
if (m_accumulated)
{
return false;
}
m_accumulated = true;
bool hadNext = false;
TIntermediate accumulator = default(TIntermediate);
// Initialize the accumulator.
if (m_reduceOperator.m_seedIsSpecified)
{
// If the seed is specified, initialize accumulator to the seed value.
accumulator = m_reduceOperator.m_seedFactory == null
? m_reduceOperator.m_seed
: m_reduceOperator.m_seedFactory();
}
else
{
// If the seed is not specified, then we take the first element as the seed.
// Seed may be unspecified only if TInput is the same as TIntermediate.
Contract.Assert(typeof(TInput) == typeof(TIntermediate));
TInput acc = default(TInput);
TKey accKeyUnused = default(TKey);
if (!m_source.MoveNext(ref acc, ref accKeyUnused)) return false;
hadNext = true;
accumulator = (TIntermediate)((object)acc);
}
// Scan through the source and accumulate the result.
TInput input = default(TInput);
TKey keyUnused = default(TKey);
int i = 0;
while (m_source.MoveNext(ref input, ref keyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(m_cancellationToken);
hadNext = true;
accumulator = m_reduceOperator.m_intermediateReduce(accumulator, input);
}
if (hadNext)
{
currentElement = accumulator;
currentKey = m_partitionIndex; // A reduction's "index" is just its partition number.
return true;
}
return false;
}
protected override void Dispose(bool disposing)
{
Contract.Assert(m_source != null);
m_source.Dispose();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using UnityEngine;
namespace Captury
{
//=================================
// define captury class structures
//=================================
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CapturyJoint
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]
public byte[] name;
public int parent;
public float ox, oy, oz;
public float rx, ry, rz;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CapturyActor
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] name;
public int id;
public int numJoints;
public IntPtr joints;
public int numBlobs;
public IntPtr blobs;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CapturyPose
{
public int actor;
public long timestamp;
public int numValues;
public IntPtr values;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CapturyARTag
{
public int id;
public float ox, oy, oz; // position
public float rx, ry, rz; // rotation
}
[StructLayout(LayoutKind.Sequential)]
public struct CapturyImage
{
public int width;
public int height;
public int camera;
public ulong timestamp;
public IntPtr data;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CapturyTransform
{
public float rx; // rotation euler angles
public float ry;
public float rz;
public float tx; // translation
public float ty;
public float tz;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CapturyCamera
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] name;
public int id;
public float positionX;
public float positionY;
public float positionZ;
public float orientationX;
public float orientationY;
public float orientationZ;
public float sensorWidth; // in mm
public float sensorHeight; // in mm
public float focalLength; // in mm
public float lensCenterX; // in mm
public float lensCenterY; // in mm
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] distortionModel;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)]
public float distortion;
// the following can be computed from the above values and are provided for convenience only
// the matrices are stored column wise:
// 0 3 6 9
// 1 4 7 10
// 2 5 8 11
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
float extrinsic;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]
float intrinsic;
};
//==========================================
// internal structures that are more easy to use
//==========================================
[Serializable]
public class CapturySkeletonJoint
{
public string name;
public int parent;
public Vector3 offset;
public Vector3 orientation;
public Transform transform;
}
[Serializable]
public class CapturySkeleton
{
public string name;
public int id;
public int playerID = -1;
public CapturySkeletonJoint[] joints;
public IntPtr rawData = IntPtr.Zero;
public IntPtr retargetTarget = IntPtr.Zero;
private GameObject reference;
public bool upToDate = true;
public GameObject mesh // reference to game object that is animated
{
get { return reference; }
set
{
upToDate = false;
reference = value;
if (reference == null)
{
foreach (CapturySkeletonJoint j in joints)
j.transform = null;
return;
}
foreach (CapturySkeletonJoint j in joints)
{
// check if the joint name matches a reference transform and assign it
ArrayList children = reference.transform.GetAllChildren();
foreach (Transform tra in children)
{
if (tra.name.EndsWith(j.name))
{
j.transform = tra;
continue;
}
}
}
}
}
}
[Serializable]
public class CapturyMarkerTransform
{
public Quaternion rotation;
public Vector3 translation;
public UInt64 timestamp;
public float bestAccuracy;
public bool consumed;
}
[Serializable]
public class ARTag
{
public int id;
public Vector3 translation;
public Quaternion rotation;
}
//====================
// the network plugin
//====================
[RequireComponent(typeof(CapturyOriginManager))]
public class CapturyNetworkPlugin : MonoBehaviour
{
//=============================================
// import the functions from RemoteCaptury dll
//=============================================
[DllImport("RemoteCaptury")]
private static extern int Captury_connect(string ip, ushort port);
[DllImport("RemoteCaptury")]
private static extern int Captury_disconnect();
[DllImport("RemoteCaptury")]
private static extern int Captury_getActors(out IntPtr actorData);
[DllImport("RemoteCaptury")]
private static extern int Captury_startStreaming(int what);
[DllImport("RemoteCaptury")]
private static extern int Captury_stopStreaming();
[DllImport("RemoteCaptury")]
private static extern IntPtr Captury_getCurrentPose(IntPtr actor);
[DllImport("RemoteCaptury")]
private static extern void Captury_freePose(IntPtr pose);
[DllImport("RemoteCaptury")]
private static extern void Captury_requestTexture(IntPtr actor);
[DllImport("RemoteCaptury")]
private static extern IntPtr Captury_getTexture(IntPtr actor);
[DllImport("RemoteCaptury")]
private static extern void Captury_freeImage(IntPtr image);
[DllImport("RemoteCaptury")]
private static extern int Captury_setRotationConstraint(int actorId, int jointIndex, IntPtr rotation, UInt64 timestamp, float weight);
[DllImport("RemoteCaptury")]
private static extern UInt64 Captury_getMarkerTransform(IntPtr actor, int jointIndex, IntPtr transform);
[DllImport("RemoteCaptury")]
private static extern UInt64 Captury_synchronizeTime();
[DllImport("RemoteCaptury")]
private static extern UInt64 Captury_getTime();
[DllImport("RemoteCaptury")]
private static extern Int64 Captury_getTimeOffset();
[DllImport("RemoteCaptury")]
private static extern IntPtr Captury_getLastErrorMessage();
[DllImport("RemoteCaptury")]
private static extern void Captury_freeErrorMessage(IntPtr msg);
[DllImport("RemoteCaptury")]
private static extern int Captury_getCameras(out IntPtr cameras);
[DllImport("RemoteCaptury")]
private static extern IntPtr Captury_getCurrentARTags();
[DllImport("RemoteCaptury")]
private static extern void Captury_freeARTags(IntPtr arTags);
[DllImport("Retargetery")]
private static extern IntPtr liveRetarget(IntPtr src, IntPtr tgt, IntPtr input);
// Events
public delegate void SkeletonDelegate(CapturySkeleton skeleton);
public event SkeletonDelegate SkeletonFound;
public event SkeletonDelegate SkeletonLost;
public delegate void CamerasChangedDelegate(Vector3[] positions, Quaternion[] rotations);
public event CamerasChangedDelegate CamerasChanged;
public delegate void ARTagsDetectedDelegate(ARTag[] artags);
public event ARTagsDetectedDelegate ARTagsDetected;
public Vector3[] cameraPositions;
public Quaternion[] cameraOrientations;
public ARTag[] arTags = new ARTag[0];
/// <summary>
/// Reference to <see cref="capturyOriginManager"/> which handles the origin of the coordinate system
/// </summary>
private CapturyOriginManager capturyOriginManager;
/// <summary>
/// Reference to the current <see cref="CapturyOrigin"/> in the scene which defines the origin of the coordinate system of all avatars
/// </summary>
private CapturyOrigin capturyOrigin;
private static readonly string headJointName = "Head";
public static string HeadJointName
{
get
{
return headJointName;
}
}
// threading data for communication with server
private Thread communicationThread;
private Mutex communicationMutex = new Mutex();
private bool communicationFinished = false;
// internal variables
private bool isConnected = false;
private bool isSetup = false;
// skeleton data from Captury
private Dictionary<int, IntPtr> actorPointers = new Dictionary<int, IntPtr>();
private Dictionary<int, int> actorFound = new Dictionary<int, int>();
private Dictionary<int, CapturySkeleton> skeletons = new Dictionary<int, CapturySkeleton>();
//private Dictionary<int, CapturyMarkerTransform> headTransforms = new Dictionary<int, CapturyMarkerTransform>();
private Dictionary<string, int> jointsWithConstraints = new Dictionary<string, int>();
/// <summary>
/// Captury Live settings
/// </summary>
private CapturyConfig config;
void Awake()
{
// load config
config = CapturyConfigManager.Config;
// register to CapturyOrigin change event
capturyOriginManager = GetComponent<CapturyOriginManager>();
capturyOriginManager.CapturyOriginChanged += OnCapturyOriginChanged;
}
//=============================
// this is run once at startup
//=============================
void Start()
{
// start the connection thread
communicationThread = new Thread(lookForActors);
communicationThread.Start();
}
//==========================
// this is run once at exit
//==========================
void OnDisable()
{
communicationFinished = true;
communicationThread.Join();
}
//============================
// this is run once per frame
//============================
void Update()
{
// only perform if we are actually connected
if (!isConnected)
return;
// make sure we lock access before doing anything
// Debug.Log ("Starting pose update...");
communicationMutex.WaitOne();
// set origin offset based on CapturyOrigin, if existent. Otherwise keep world origin (0,0,0)
Vector3 offsetToOrigin = Vector3.zero;
if (capturyOrigin != null)
{
offsetToOrigin = capturyOrigin.OffsetToWorldOrigin;
}
// fetch current pose for all skeletons
foreach (KeyValuePair<int, CapturySkeleton> kvp in skeletons)
{
// get the actor id
int actorID = kvp.Key;
// check if the actor is mapped to something, if not, ignore
if (skeletons[actorID].mesh == null)
continue;
// get pointer to pose
IntPtr poseData = Captury_getCurrentPose(actorPointers[actorID]);
// check if we actually got data, if not, continue
if (poseData == IntPtr.Zero)
{
// something went wrong, get error message
IntPtr msg = Captury_getLastErrorMessage();
string errmsg = Marshal.PtrToStringAnsi(msg);
Debug.Log("Stream error: " + errmsg);
Captury_freeErrorMessage(msg);
}
else
{
//Debug.Log("received pose for " + actorID);
// convert the pose
CapturyPose pose;
if (skeletons[actorID].retargetTarget != IntPtr.Zero)
{
CapturyPose posex = (CapturyPose)Marshal.PtrToStructure(poseData, typeof(CapturyPose));
float[] valuex = new float[posex.numValues * 6];
Marshal.Copy(posex.values, valuex, 0, posex.numValues * 6);
Debug.Log("pose = " + String.Join(", ", new List<float>(valuex).ConvertAll(i => i.ToString()).ToArray()));
if (!skeletons[actorID].upToDate)
{
CapturyActor actor = (CapturyActor)Marshal.PtrToStructure(skeletons[actorID].retargetTarget, typeof(CapturyActor));
CapturySkeleton skel = skeletons[actorID];
IntPtr rawData = skel.rawData;
ConvertActor(actor, skeletons[actorID].retargetTarget, ref skel);
skel.rawData = rawData;
skeletons[actorID] = skel;
skeletons[actorID].mesh = skeletons[actorID].mesh;
skeletons[actorID].upToDate = true;
}
IntPtr retargetedPose = liveRetarget(skeletons[actorID].rawData, skeletons[actorID].retargetTarget, poseData);
pose = (CapturyPose)Marshal.PtrToStructure(retargetedPose, typeof(CapturyPose));
} else
pose = (CapturyPose)Marshal.PtrToStructure(poseData, typeof(CapturyPose));
// copy the data into a float array
float[] values = new float[pose.numValues * 6];
Marshal.Copy(pose.values, values, 0, pose.numValues * 6);
Debug.Log("retargeted = " + String.Join(", ", new List<float>(values).ConvertAll(i => i.ToString()).ToArray()));
// now loop over all joints
Vector3 pos = new Vector3();
Vector3 rot = new Vector3();
for (int jointID = 0; jointID < skeletons[actorID].joints.Length; jointID++)
{
// ignore any joints that do not map to a transform
if (skeletons[actorID].joints[jointID].transform == null)
continue;
// set offset and rotation
int baseIndex = jointID * 6;
pos.Set(values[baseIndex + 0], values[baseIndex + 1], values[baseIndex + 2]);
rot.Set(values[baseIndex + 3], values[baseIndex + 4], values[baseIndex + 5]);
skeletons[actorID].joints[jointID].transform.position = ConvertPosition(pos) + offsetToOrigin;
skeletons[actorID].joints[jointID].transform.rotation = ConvertRotation(rot);
}
// finally, free the pose data again, as we are finished
Captury_freePose(poseData);
}
}
// get artags
IntPtr arTagData = Captury_getCurrentARTags();
// check if we actually got data, if not, continue
if (arTagData == IntPtr.Zero)
{
// something went wrong, get error message
//IntPtr msg = Captury_getLastErrorMessage();
//string errmsg = Marshal.PtrToStringAnsi(msg);
//Captury_freeErrorMessage(msg);
}
else
{
IntPtr at = arTagData;
int num;
for (num = 0; num < 100; ++num)
{
CapturyARTag arTag = (CapturyARTag)Marshal.PtrToStructure(at, typeof(CapturyARTag));
if (arTag.id == -1)
break;
Array.Resize(ref arTags, num + 1);
arTags[num] = new ARTag();
arTags[num].id = arTag.id;
arTags[num].translation = ConvertPosition(new Vector3(arTag.ox, arTag.oy, arTag.oz)) + offsetToOrigin;
arTags[num].rotation = ConvertRotation(new Vector3(arTag.rx, arTag.ry, arTag.rz)) * Quaternion.Euler(0, 180, 0) * Quaternion.Euler(-90, 0, 0);
at = new IntPtr(at.ToInt64() + Marshal.SizeOf(typeof(CapturyARTag)));
}
if (num != 0 && ARTagsDetected != null)
ARTagsDetected(arTags);
else
Array.Resize(ref arTags, 0);
Captury_freeARTags(arTagData);
}
communicationMutex.ReleaseMutex();
}
//================================================
// This function continously looks for new actors
// It runs in a separate thread
//================================================
void lookForActors()
{
while (!communicationFinished)
{
// wait for actorCheckTimeout ms before continuing
// Debug.Log ("Going to sleep...");
Thread.Sleep(config.actorCheckTimeout);
// Debug.Log ("Waking up...");
// now look for new data
// try to connect to captury live
if (!isSetup)
{
if (Captury_connect(config.host, config.port) == 1 && Captury_synchronizeTime() != 0)
{
isSetup = true;
Debug.Log("Successfully opened port to Captury Live");
Debug.Log("The time difference is " + Captury_getTimeOffset());
}
else
Debug.Log(String.Format("Unable to connect to Captury Live at {0}:{1} ", config.host, config.port));
IntPtr cameraData = IntPtr.Zero;
int numCameras = Captury_getCameras(out cameraData);
if (numCameras > 0 && cameraData != IntPtr.Zero)
{
cameraPositions = new Vector3[numCameras];
cameraOrientations = new Quaternion[numCameras];
int szStruct = Marshal.SizeOf(typeof(CapturyCamera)) + 192; // this offset is here to take care of implicit padding
for (uint i = 0; i < numCameras; i++)
{
CapturyCamera camera = new CapturyCamera();
camera = (CapturyCamera)Marshal.PtrToStructure(new IntPtr(cameraData.ToInt64() + (szStruct * i)), typeof(CapturyCamera));
// Debug.Log("camera " + camera.id.ToString("x") + " (" + camera.positionX + ", " + camera.positionY + "," + camera.positionZ + ") (" +
// camera.orientationX + ", " + camera.orientationY + "," + camera.orientationZ + ") ss: (" + camera.sensorWidth + ", " + camera.sensorHeight + ") fl:" +
// camera.focalLength + " lc: (" + camera.lensCenterX + ", " + camera.lensCenterY + ") ");
cameraPositions[i] = ConvertPosition(new Vector3(camera.positionX, camera.positionY, camera.positionZ));
cameraOrientations[i] = ConvertRotation(new Vector3(camera.orientationX, camera.orientationY, camera.orientationZ));
}
// Fire cameras changed event
if (CamerasChanged != null)
{
CamerasChanged(cameraPositions, cameraOrientations);
}
}
}
if (isSetup)
{
// grab actors
IntPtr actorData = IntPtr.Zero;
int numActors = Captury_getActors(out actorData);
if (numActors > 0 && actorData != IntPtr.Zero)
{
Debug.Log(String.Format("Received {0} actors", numActors));
// create actor struct
int szStruct = Marshal.SizeOf(typeof(CapturyActor))+4; // implicit padding
for (uint i = 0; i < numActors; i++)
{
// get an actor
CapturyActor actor = new CapturyActor();
actor = (CapturyActor)Marshal.PtrToStructure(new IntPtr(actorData.ToInt64() + (szStruct * i)), typeof(CapturyActor));
// check if we already have it in our dictionary
if (skeletons.ContainsKey(actor.id)) // access to actors does not need to be locked here because the other thread is read-only
{
communicationMutex.ReleaseMutex();
actorFound[actor.id] = 5;
continue;
}
Debug.Log("Found new actor " + actor.id);
// no? we need to convert it
IntPtr actorPointer = new IntPtr(actorData.ToInt64() + (szStruct * i));
CapturySkeleton skeleton = new CapturySkeleton();
ConvertActor(actor, actorData, ref skeleton);
if (SkeletonFound != null)
{
SkeletonFound(skeleton);
}
// and add it to the list of actors we are processing, making sure this is secured by the mutex
communicationMutex.WaitOne();
actorPointers.Add(actor.id, actorPointer);
skeletons.Add(actor.id, skeleton);
actorFound.Add(actor.id, 5);
communicationMutex.ReleaseMutex();
}
}
if (!isConnected)
{
if (Captury_startStreaming(config.streamARTags ? 5 : 1) == 1)
{
Debug.Log("Successfully started streaming data");
isConnected = true;
}
else
Debug.LogWarning("failed to start streaming");
}
// reduce the actor countdown by one for each actor
int[] keys = new int[actorFound.Keys.Count];
actorFound.Keys.CopyTo(keys, 0);
foreach (int key in keys)
actorFound[key]--;
}
// remove all actors that were not found in the past few actor checks
// Debug.Log ("Updating actor structure");
communicationMutex.WaitOne();
List<int> unusedKeys = new List<int>();
foreach (KeyValuePair<int, int> kvp in actorFound)
{
if (kvp.Value <= 0)
{
if (SkeletonLost != null)
{
Debug.Log("lost skeleton. telling all my friends.");
SkeletonLost(skeletons[kvp.Key]);
}
// remove actor
actorPointers.Remove(kvp.Key);
skeletons.Remove(kvp.Key);
unusedKeys.Add(kvp.Key);
}
}
communicationMutex.ReleaseMutex();
// Debug.Log ("Updating actor structure done");
// clear out actorfound structure
foreach (int key in unusedKeys)
actorFound.Remove(key);
// look for current transformation of bones with markers - the head
/* foreach (KeyValuePair<int, IntPtr> kvp in actorPointers)
{
int id = kvp.Key;
// find the index of the head joint
int headJointIndex = -1;
for (int i = 0; i < skeletons[id].joints.Length; ++i)
{
if (skeletons[id].joints[i].name.EndsWith(headJointName))
{
headJointIndex = i;
break;
}
}
if (headJointIndex == -1)
{
Debug.Log("no head joint for skeleton " + id);
continue;
}
// get the transform and store it in headTransforms
IntPtr trafo = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CapturyTransform)));
UInt64 timestamp = Captury_getMarkerTransform(kvp.Value, headJointIndex, trafo);
// is there a constraint for this joint that is not older than 500ms?
if (timestamp != 0)
{
CapturyTransform t = (CapturyTransform)Marshal.PtrToStructure(trafo, typeof(CapturyTransform));
communicationMutex.WaitOne();
if (headTransforms.ContainsKey(id))
{
// this is a new transform. the other thread should have a look at it.
if (headTransforms[id].timestamp < timestamp)
headTransforms[id].consumed = false;
}
else
{
headTransforms[id] = new CapturyMarkerTransform();
headTransforms[id].bestAccuracy = 0.95f;
// if the new transform is actually already old mark it as old directly
if (timestamp > Captury_getTime() - 500000)
headTransforms[id].consumed = false;
else
headTransforms[id].consumed = true;
}
headTransforms[id].rotation = ConvertRotation(new Vector3(t.rx * 180 / (float)Math.PI, t.ry * 180 / (float)Math.PI, t.rz * 180 / (float)Math.PI));
headTransforms[id].translation = ConvertPosition(new Vector3(t.tx, t.ty, t.tz));
headTransforms[id].timestamp = timestamp;
communicationMutex.ReleaseMutex();
// Debug.Log(string.Format("transform for actor.joint {0}.{1} is good, really t {2}, delta now {3}", id, headJointIndex, timestamp, Captury_getTime() - timestamp));
}
else
{
communicationMutex.WaitOne();
headTransforms.Remove(id);
communicationMutex.ReleaseMutex();
}
Marshal.FreeHGlobal(trafo);
}*/
}
Debug.Log("Disconnecting");
// make sure we disconnect
Captury_disconnect();
isSetup = false;
isConnected = false;
}
public void setRotationConstraint(int id, string jointName, Transform t)
{
if (skeletons.ContainsKey(id) == false)
{
Debug.Log("Cannot set rotation for " + jointName + ": no skeleton with id " + id);
return;
}
else
{
//Debug.Log("Set " + jointName + "-rotation to " + t);
}
communicationMutex.WaitOne();
CapturySkeleton skel = skeletons[id];
communicationMutex.ReleaseMutex();
int index;
if (jointsWithConstraints.ContainsKey(jointName))
{
index = jointsWithConstraints[jointName];
}
else
{
index = 0;
foreach (CapturySkeletonJoint j in skel.joints)
{
if (j.name == jointName)
{
break;
}
++index;
}
if (index == skel.joints.Length)
{
//Debug.Log("Cannot set constraint for joint " + jointName + ": no such joint");
return;
}
}
// CapturySkeletonJoint jnt = skel.joints[index];
Vector3 euler = ConvertToEulerAngles(ConvertRotationToLive(t.rotation));
IntPtr rotation = Marshal.AllocHGlobal(12);
Marshal.StructureToPtr(euler, rotation, false);
Captury_setRotationConstraint(id, index, rotation, Captury_getTime(), 1.0f);
Marshal.FreeHGlobal(rotation);
}
/// <summary>
/// Called when <see cref="CapturyOrigin"/> changes and sets it as local variable.
/// </summary>
/// <param name="newCapturyOrigin"></param>
public void OnCapturyOriginChanged(CapturyOrigin capturyOrigin)
{
this.capturyOrigin = capturyOrigin;
}
//===============================================
// helper function to map an actor to a skeleton
//===============================================
public void ConvertActor(CapturyActor actor, IntPtr actorData, ref CapturySkeleton skel)
{
if (skel == null)
{
Debug.Log("Null skeleton reference");
return;
}
// copy data over
skel.name = System.Text.Encoding.UTF8.GetString(actor.name);
skel.id = actor.id;
skel.rawData = actorData;
// create joints
int szStruct = Marshal.SizeOf(typeof(CapturyJoint));
skel.joints = new CapturySkeletonJoint[actor.numJoints];
for (uint i = 0; i < actor.numJoints; i++)
{
// marshall the joints into a new joint struct
CapturyJoint joint = new CapturyJoint();
joint = (CapturyJoint)Marshal.PtrToStructure(new IntPtr(actor.joints.ToInt64() + (szStruct * i)), typeof(CapturyJoint));
skel.joints[i] = new CapturySkeletonJoint();
skel.joints[i].name = System.Text.Encoding.ASCII.GetString(joint.name);
int jpos = skel.joints[i].name.IndexOf("\0");
skel.joints[i].name = skel.joints[i].name.Substring(0, jpos);
skel.joints[i].offset.Set(joint.ox, joint.oy, joint.oz);
skel.joints[i].orientation.Set(joint.rx, joint.ry, joint.rz);
skel.joints[i].parent = joint.parent;
//Debug.Log ("Got joint " + skel.joints[i].name + " at " + joint.ox + joint.oy + joint.oz);
}
}
//========================================================================================================
// Helper function to convert a position from a right-handed to left-handed coordinate system (both Y-up)
//========================================================================================================
public Vector3 ConvertPosition(Vector3 position)
{
position.x *= -config.scaleFactor;
position.y *= config.scaleFactor;
position.z *= config.scaleFactor;
return position;
}
//========================================================================================================
// Helper function to convert a position from a left-handed to right-handed coordinate system (both Y-up)
//========================================================================================================
public Vector3 ConvertPositionToLive(Vector3 position)
{
position.x /= -config.scaleFactor;
position.y /= config.scaleFactor;
position.z /= config.scaleFactor;
return position;
}
//===========================================================================================================================
// Helper function to convert a rotation from a right-handed Captury Live to left-handed Unity coordinate system (both Y-up)
//===========================================================================================================================
private Quaternion ConvertRotation(Vector3 rotation)
{
Quaternion qx = Quaternion.AngleAxis(rotation.x, Vector3.right);
Quaternion qy = Quaternion.AngleAxis(rotation.y, Vector3.down);
Quaternion qz = Quaternion.AngleAxis(rotation.z, Vector3.back);
Quaternion qq = qz * qy * qx;
return qq;
}
//===========================================================================================================
// Helper function to convert a rotation from Unity back to Captury Live (left-handed to right-handed, Y-up)
//===========================================================================================================
public Quaternion ConvertRotationToLive(Quaternion rotation)
{
Vector3 angles = rotation.eulerAngles;
Quaternion qx = Quaternion.AngleAxis(angles.x, Vector3.right);
Quaternion qy = Quaternion.AngleAxis(angles.y, Vector3.down);
Quaternion qz = Quaternion.AngleAxis(angles.z, Vector3.back);
Quaternion qq = qz * qy * qx;
return qq;
}
//=============================================================================
// Helper function to convert a rotation to the Euler angles Captury Live uses
//=============================================================================
public Vector3 ConvertToEulerAngles(Quaternion quat)
{
const float RAD2DEGf = 0.0174532925199432958f;
Vector3 euler = new Vector3();
float sqw = quat.w * quat.w;
float sqx = quat.x * quat.x;
float sqy = quat.y * quat.y;
float sqz = quat.z * quat.z;
float tmp1 = quat.x * quat.y;
float tmp2 = quat.z * quat.w;
euler[1] = (float)-Math.Asin(2.0 * (tmp1 - tmp2));
float C = (float)Math.Cos(euler[1]);
if (Math.Abs(C) > 0.005)
{
euler[2] = (float)Math.Atan2(2.0f * (tmp1 + tmp2) / C, (sqx - sqy - sqz + sqw) / C) * RAD2DEGf;
euler[0] = (float)Math.Atan2(2.0f * (tmp1 + tmp2) / C, (-sqx - sqy + sqz + sqw) / C) * RAD2DEGf;
}
else
{
euler[2] = 0;
if ((tmp1 - tmp2) < 0)
euler[0] = (float)Math.Atan2(0.0f, (-sqx + sqy - sqz + sqw) * 0.5f + (tmp1 + tmp2)) * RAD2DEGf;
else
euler[0] = (float)Math.Atan2(2 * (tmp1 - tmp2), (-sqx + sqy - sqz + sqw) * 0.5f - (tmp1 + tmp2)) * RAD2DEGf;
}
euler[1] *= RAD2DEGf;
return euler;
}
}
//==========================================================================
// Helper extension function to get all children from a specified transform
//==========================================================================
public static class TransformExtension
{
public static ArrayList GetAllChildren(this Transform transform)
{
ArrayList children = new ArrayList();
foreach (Transform child in transform)
{
children.Add(child);
children.AddRange(GetAllChildren(child));
}
return children;
}
}
}
| |
/*
* DateTimeFormatInfo.cs - Implementation of the
* "System.Globalization.DateTimeFormatInfo" class.
*
* Copyright (C) 2001 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Globalization
{
using System;
public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider
{
// Internal state.
private static DateTimeFormatInfo invariantInfo;
private bool readOnly;
private String amDesignator;
private String pmDesignator;
private String[] abbreviatedDayNames;
private String[] dayNames;
private String[] abbreviatedMonthNames;
private String[] monthNames;
private String[] eraNames;
private String[] abbrevEraNames;
private String dateSeparator;
private String timeSeparator;
private String fullDateTimePattern;
private String longDatePattern;
private String longTimePattern;
private String monthDayPattern;
private String shortDatePattern;
private String shortTimePattern;
private String yearMonthPattern;
private Calendar calendar;
#if !ECMA_COMPAT
private CalendarWeekRule calendarWeekRule;
private DayOfWeek firstDayOfWeek;
#endif // !ECMA_COMPAT
private String[] dateTimePatterns;
// Invariant abbreviated day names.
private static readonly String[] invAbbrevDayNames =
{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
// Invariant day names.
private static readonly String[] invDayNames =
{"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
// Invariant abbreviated month names.
private static readonly String[] invAbbrevMonthNames =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ""};
// Invariant month names.
private static readonly String[] invMonthNames =
{"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December", ""};
// Invariant era names.
private static readonly String[] invEraNames = {"A.D."};
private static readonly String[] invAbbrevEraNames = {"AD"};
// Invariant date time pattern list. Each string begins
// with a format character followed by a colon.
private static readonly String[] invDateTimePatterns =
{"d:MM/dd/yyyy",
"D:dddd, dd MMMM yyyy",
"f:dddd, dd MMMM yyyy HH:mm",
"f:dddd, dd MMMM yyyy hh:mm tt",
"f:dddd, dd MMMM yyyy H:mm",
"f:dddd, dd MMMM yyyy h:mm tt",
"F:dddd, dd MMMM yyyy HH:mm:ss",
"g:MM/dd/yyyy HH:mm",
"g:MM/dd/yyyy hh:mm tt",
"g:MM/dd/yyyy H:mm",
"g:MM/dd/yyyy h:mm tt",
"G:MM/dd/yyyy HH:mm:ss",
"m:MMMM dd",
"M:MMMM dd",
"r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"s:yyyy'-'MM'-'dd'T'HH':'mm':'ss",
"t:HH:mm",
"t:hh:mm tt",
"t:H:mm",
"t:h:mm tt",
"T:HH:mm:ss",
"u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
"U:dddd, dd MMMM yyyy HH:mm:ss",
"y:yyyy MMMM",
"Y:yyyy MMMM"};
// Constructor.
public DateTimeFormatInfo()
{
readOnly = false;
amDesignator = "AM";
pmDesignator = "PM";
abbreviatedDayNames = invAbbrevDayNames;
dayNames = invDayNames;
abbreviatedMonthNames = invAbbrevMonthNames;
monthNames = invMonthNames;
eraNames = invEraNames;
abbrevEraNames = invAbbrevEraNames;
dateSeparator = "/";
timeSeparator = ":";
fullDateTimePattern = "dddd, dd MMMM yyyy HH:mm:ss";
longDatePattern = "dddd, dd MMMM yyyy";
longTimePattern = "HH:mm:ss";
monthDayPattern = "MMMM dd";
shortDatePattern = "MM/dd/yyyy";
shortTimePattern = "HH:mm";
yearMonthPattern = "yyyy MMMM";
calendar = new GregorianCalendar();
dateTimePatterns = invDateTimePatterns;
#if !ECMA_COMPAT
calendarWeekRule = CalendarWeekRule.FirstDay;
firstDayOfWeek = DayOfWeek.Sunday;
#endif // !ECMA_COMPAT
}
// Get the invariant date time format information.
public static DateTimeFormatInfo InvariantInfo
{
get
{
lock(typeof(DateTimeFormatInfo))
{
if(invariantInfo == null)
{
invariantInfo = new DateTimeFormatInfo();
invariantInfo.readOnly = true;
}
return invariantInfo;
}
}
}
// Get the date time format information for the current thread's culture.
public static DateTimeFormatInfo CurrentInfo
{
get
{
return CultureInfo.CurrentCulture.DateTimeFormat;
}
}
// Implement the ICloneable interface.
public Object Clone()
{
#if !ECMA_COMPAT
DateTimeFormatInfo dateTimeFormat = (DateTimeFormatInfo)MemberwiseClone();
dateTimeFormat.readOnly = false;
return dateTimeFormat;
#else
return MemberwiseClone();
#endif
}
// Get the abbreviated name for a month.
public String GetAbbreviatedMonthName(int month)
{
if(month >= 1 && month <= 13)
{
return abbreviatedMonthNames[month - 1];
}
else
{
throw new ArgumentOutOfRangeException
("month", _("ArgRange_Month"));
}
}
// Search for an era name within an array.
private static int SearchForEra(String[] names, String name)
{
int posn;
if(names == null)
{
return -1;
}
for(posn = 0; posn < names.Length; ++posn)
{
if(String.Compare(names[posn], name, true) == 0)
{
return posn + 1;
}
}
return -1;
}
// Get a value that represents an era name.
public int GetEra(String eraName)
{
int era;
if(eraName == null)
{
throw new ArgumentNullException("eraName");
}
era = SearchForEra(eraNames, eraName);
if(era == -1)
{
era = SearchForEra(abbrevEraNames, eraName);
}
if(era == -1)
{
era = SearchForEra(invEraNames, eraName);
}
if(era == -1)
{
era = SearchForEra(invAbbrevEraNames, eraName);
}
return era;
}
// Get the name of a particular era.
public String GetEraName(int era)
{
if(era == System.Globalization.Calendar.CurrentEra)
{
era = Calendar.GetEra(DateTime.Now);
}
if(era >= 1 && era <= eraNames.Length)
{
return eraNames[era - 1];
}
else
{
throw new ArgumentOutOfRangeException
("era", _("Arg_InvalidEra"));
}
}
// Implement the IFormatProvider interface.
public Object GetFormat(Type formatType)
{
if(formatType == typeof(DateTimeFormatInfo))
{
return this;
}
else
{
return CurrentInfo;
}
}
// Get the date time format information associated with "provider".
#if ECMA_COMPAT
internal
#else
public
#endif
static DateTimeFormatInfo GetInstance(IFormatProvider provider)
{
if(provider != null)
{
Object obj = provider.GetFormat(typeof(DateTimeFormatInfo));
if(obj != null)
{
return (DateTimeFormatInfo)obj;
}
}
return CurrentInfo;
}
// Get the full name of a specific month.
public String GetMonthName(int month)
{
if(month >= 1 && month <= 13)
{
return monthNames[month - 1];
}
else
{
throw new ArgumentOutOfRangeException
("month", _("ArgRange_Month"));
}
}
// Create a read-only copy of a DateTimeFormatInfo object.
public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi)
{
if(dtfi == null)
{
throw new ArgumentNullException("dtfi");
}
else if(dtfi.IsReadOnly)
{
return dtfi;
}
else
{
DateTimeFormatInfo newDtfi;
newDtfi = (DateTimeFormatInfo)(dtfi.Clone());
newDtfi.readOnly = true;
return newDtfi;
}
}
// Get the abbreviated name of a week day.
public String GetAbbreviatedDayName(DayOfWeek dayOfWeek)
{
if(dayOfWeek >= DayOfWeek.Sunday &&
dayOfWeek <= DayOfWeek.Saturday)
{
return abbreviatedDayNames[(int)dayOfWeek];
}
else
{
throw new ArgumentOutOfRangeException
("dayOfWeek", _("Arg_DayOfWeek"));
}
}
// Get the full name of a week day.
public String GetDayName(DayOfWeek dayOfWeek)
{
if(dayOfWeek >= DayOfWeek.Sunday &&
dayOfWeek <= DayOfWeek.Saturday)
{
return dayNames[(int)dayOfWeek];
}
else
{
throw new ArgumentOutOfRangeException
("dayOfWeek", _("Arg_DayOfWeek"));
}
}
#if !ECMA_COMPAT
// Get the abbreviated name of an era.
public String GetAbbreviatedEraName(int era)
{
if(abbrevEraNames == null)
{
// Use the full name if there are no abbreviated names.
return GetEraName(era);
}
if(era == System.Globalization.Calendar.CurrentEra)
{
era = Calendar.GetEra(DateTime.Now);
}
if(era >= 1 && era <= abbrevEraNames.Length)
{
return abbrevEraNames[era - 1];
}
else
{
throw new ArgumentOutOfRangeException
("era", _("Arg_InvalidEra"));
}
}
#endif // !ECMA_COMPAT
// Get all date time patterns.
public String[] GetAllDateTimePatterns()
{
String[] patterns = new String [dateTimePatterns.Length];
int posn;
for(posn = 0; posn < dateTimePatterns.Length; ++posn)
{
patterns[posn] = dateTimePatterns[posn].Substring(2);
}
return patterns;
}
public String[] GetAllDateTimePatterns(char format)
{
String[] patterns;
int posn, len;
len = 0;
for(posn = 0; posn < dateTimePatterns.Length; ++posn)
{
if(dateTimePatterns[posn][0] == format)
{
++len;
}
}
if(len == 0)
{
throw new ArgumentException(_("Arg_DateTimeFormatChar"));
}
patterns = new String [len];
len = 0;
for(posn = 0; posn < dateTimePatterns.Length; ++posn)
{
if(dateTimePatterns[posn][0] == format)
{
patterns[len++] = dateTimePatterns[posn].Substring(2);
}
}
return patterns;
}
// Properties.
public String AMDesignator
{
get
{
return amDesignator;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
amDesignator = value;
}
}
public String PMDesignator
{
get
{
return pmDesignator;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
pmDesignator = value;
}
}
public String[] AbbreviatedDayNames
{
get
{
return abbreviatedDayNames;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
else if(value.Length != 7)
{
throw new ArgumentException(_("Arg_Array7Elems"));
}
CheckForNulls(value);
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
abbreviatedDayNames = value;
}
}
public String[] DayNames
{
get
{
return dayNames;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
else if(value.Length != 7)
{
throw new ArgumentException(_("Arg_Array7Elems"));
}
CheckForNulls(value);
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
dayNames = value;
}
}
public String[] AbbreviatedMonthNames
{
get
{
return abbreviatedMonthNames;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
else if(value.Length != 13)
{
throw new ArgumentException(_("Arg_Array13Elems"));
}
CheckForNulls(value);
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
abbreviatedMonthNames = value;
}
}
public String[] MonthNames
{
get
{
return monthNames;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
else if(value.Length != 13)
{
throw new ArgumentException(_("Arg_Array13Elems"));
}
CheckForNulls(value);
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
monthNames = value;
}
}
public String DateSeparator
{
get
{
return dateSeparator;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
dateSeparator = value;
}
}
public String TimeSeparator
{
get
{
return timeSeparator;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
timeSeparator = value;
}
}
public bool IsReadOnly
{
get
{
return readOnly;
}
}
public String FullDateTimePattern
{
get
{
return fullDateTimePattern;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
fullDateTimePattern = value;
}
}
public String LongDatePattern
{
get
{
return longDatePattern;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
longDatePattern = value;
}
}
public String LongTimePattern
{
get
{
return longTimePattern;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
longTimePattern = value;
}
}
public String MonthDayPattern
{
get
{
return monthDayPattern;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
monthDayPattern = value;
}
}
public String ShortDatePattern
{
get
{
return shortDatePattern;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
shortDatePattern = value;
}
}
public String ShortTimePattern
{
get
{
return shortTimePattern;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
shortTimePattern = value;
}
}
public String YearMonthPattern
{
get
{
return yearMonthPattern;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
yearMonthPattern = value;
}
}
// Get or set the calendar in use by this date/time formatting object.
#if ECMA_COMPAT
internal
#else
public
#endif
Calendar Calendar
{
get
{
return calendar;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
// Validate the calendar against the current thread.
if(value is GregorianCalendar)
{
// We can always use the Gregorian calendar.
calendar = value;
return;
}
Calendar temp = CultureInfo.CurrentCulture.Calendar;
if(temp != null &&
temp.GetType().IsAssignableFrom(value.GetType()))
{
calendar = value;
return;
}
Calendar[] opt =
CultureInfo.CurrentCulture.OptionalCalendars;
if(opt != null)
{
int posn;
for(posn = 0; posn < opt.Length; ++posn)
{
temp = opt[posn];
if(temp != null &&
temp.GetType().IsAssignableFrom(value.GetType()))
{
calendar = value;
return;
}
}
}
// The calendar is invalid for the current culture.
throw new ArgumentException(_("Arg_InvalidCalendar"));
}
}
#if !ECMA_COMPAT
// Non-ECMA properties.
public CalendarWeekRule CalendarWeekRule
{
get
{
return calendarWeekRule;
}
set
{
if(value != CalendarWeekRule.FirstDay &&
value != CalendarWeekRule.FirstFullWeek &&
value != CalendarWeekRule.FirstFourDayWeek)
{
throw new ArgumentOutOfRangeException
(_("Arg_CalendarWeekRule"));
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
calendarWeekRule = value;
}
}
public DayOfWeek FirstDayOfWeek
{
get
{
return firstDayOfWeek;
}
set
{
if(value < DayOfWeek.Sunday || value > DayOfWeek.Saturday)
{
throw new ArgumentOutOfRangeException
(_("Arg_DayOfWeek"));
}
if(readOnly)
{
throw new InvalidOperationException
(_("Invalid_ReadOnly"));
}
firstDayOfWeek = value;
}
}
public String RFC1123Pattern
{
get
{
return "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
}
}
public String SortableDateTimePattern
{
get
{
return "yyyy'-'MM'-'dd'T'HH':'mm':'ss";
}
}
public String UniversalSortableDateTimePattern
{
get
{
return "yyyy'-'MM'-'dd HH':'mm':'ss'Z'";
}
}
#endif // !ECMA_COMPAT
// Check for null strings in an array.
private static void CheckForNulls(String[] value)
{
int index;
for(index = 0; index < value.Length; ++index)
{
if(value[index] == null)
{
throw new ArgumentNullException
("value[" + index.ToString() + "]");
}
}
}
// Set the era name lists - this should not be used by applications.
// It exists to support I18N plugins, which have no other way to
// set this information through the published API's.
public void I18NSetEraNames(String[] names, String[] abbrevNames)
{
if(names == null)
{
throw new ArgumentNullException("names");
}
CheckForNulls(names);
if(abbrevNames != null)
{
CheckForNulls(abbrevNames);
}
eraNames = names;
abbrevEraNames = abbrevNames;
}
// Set the date/time pattern list - this should not be used by
// applications. It exists to support I18N plugins.
public void I18NSetDateTimePatterns(String[] patterns)
{
if(patterns == null)
{
throw new ArgumentNullException("patterns");
}
CheckForNulls(patterns);
dateTimePatterns = patterns;
}
}; // class DateTimeFormatInfo
}; // namespace System.Globalization
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xml;
using Microsoft.Xml.Schema;
using Microsoft.Xml.XPath;
using System.Globalization;
using System.Security;
// using System.Security.Policy;
// using System.Security.Permissions;
using System.Reflection;
using System.Runtime.Versioning;
namespace Microsoft.Xml
{
using System;
internal sealed class DocumentSchemaValidator : IXmlNamespaceResolver
{
private XmlSchemaValidator _validator;
private XmlSchemaSet _schemas;
private XmlNamespaceManager _nsManager;
private XmlNameTable _nameTable;
//Attributes
private ArrayList _defaultAttributes;
private XmlValueGetter _nodeValueGetter;
private XmlSchemaInfo _attributeSchemaInfo;
//Element PSVI
private XmlSchemaInfo _schemaInfo;
//Event Handler
private ValidationEventHandler _eventHandler;
private ValidationEventHandler _internalEventHandler;
//Store nodes
private XmlNode _startNode;
private XmlNode _currentNode;
private XmlDocument _document;
//List of nodes for partial validation tree walk
private XmlNode[] _nodeSequenceToValidate;
private bool _isPartialTreeValid;
private bool _psviAugmentation;
private bool _isValid;
//To avoid SchemaNames creation
private string _nsXmlNs;
private string _nsXsi;
private string _xsiType;
private string _xsiNil;
public DocumentSchemaValidator(XmlDocument ownerDocument, XmlSchemaSet schemas, ValidationEventHandler eventHandler)
{
_schemas = schemas;
_eventHandler = eventHandler;
_document = ownerDocument;
_internalEventHandler = new ValidationEventHandler(InternalValidationCallBack);
_nameTable = _document.NameTable;
_nsManager = new XmlNamespaceManager(_nameTable);
Debug.Assert(schemas != null && schemas.Count > 0);
_nodeValueGetter = new XmlValueGetter(GetNodeValue);
_psviAugmentation = true;
//Add common strings to be compared to NameTable
_nsXmlNs = _nameTable.Add(XmlReservedNs.NsXmlNs);
_nsXsi = _nameTable.Add(XmlReservedNs.NsXsi);
_xsiType = _nameTable.Add("type");
_xsiNil = _nameTable.Add("nil");
}
public bool PsviAugmentation
{
get { return _psviAugmentation; }
set { _psviAugmentation = value; }
}
public bool Validate(XmlNode nodeToValidate)
{
XmlSchemaObject partialValidationType = null;
XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.AllowXmlAttributes;
Debug.Assert(nodeToValidate.SchemaInfo != null);
_startNode = nodeToValidate;
switch (nodeToValidate.NodeType)
{
case XmlNodeType.Document:
validationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints;
break;
case XmlNodeType.DocumentFragment:
break;
case XmlNodeType.Element: //Validate children of this element
IXmlSchemaInfo schemaInfo = nodeToValidate.SchemaInfo;
XmlSchemaElement schemaElement = schemaInfo.SchemaElement;
if (schemaElement != null)
{
if (!schemaElement.RefName.IsEmpty)
{ //If it is element ref,
partialValidationType = _schemas.GlobalElements[schemaElement.QualifiedName]; //Get Global element with correct Nillable, Default etc
}
else
{ //local element
partialValidationType = schemaElement;
}
//Verify that if there was xsi:type, the schemaElement returned has the correct type set
Debug.Assert(schemaElement.ElementSchemaType == schemaInfo.SchemaType);
}
else
{ //Can be an element that matched xs:any and had xsi:type
partialValidationType = schemaInfo.SchemaType;
if (partialValidationType == null)
{ //Validated against xs:any with pc= lax or skip or undeclared / not validated element
if (nodeToValidate.ParentNode.NodeType == XmlNodeType.Document)
{
//If this is the documentElement and it has not been validated at all
nodeToValidate = nodeToValidate.ParentNode;
}
else
{
partialValidationType = FindSchemaInfo(nodeToValidate as XmlElement);
if (partialValidationType == null)
{
throw new XmlSchemaValidationException(ResXml.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate);
}
}
}
}
break;
case XmlNodeType.Attribute:
if (nodeToValidate.XPNodeType == XPathNodeType.Namespace) goto default;
partialValidationType = nodeToValidate.SchemaInfo.SchemaAttribute;
if (partialValidationType == null)
{ //Validated against xs:anyAttribute with pc = lax or skip / undeclared attribute
partialValidationType = FindSchemaInfo(nodeToValidate as XmlAttribute);
if (partialValidationType == null)
{
throw new XmlSchemaValidationException(ResXml.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate);
}
}
break;
default:
throw new InvalidOperationException(string.Format(ResXml.XmlDocument_ValidateInvalidNodeType, null));
}
_isValid = true;
CreateValidator(partialValidationType, validationFlags);
if (_psviAugmentation)
{
if (_schemaInfo == null)
{ //Might have created it during FindSchemaInfo
_schemaInfo = new XmlSchemaInfo();
}
_attributeSchemaInfo = new XmlSchemaInfo();
}
ValidateNode(nodeToValidate);
_validator.EndValidation();
return _isValid;
}
public IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
IDictionary<string, string> dictionary = _nsManager.GetNamespacesInScope(scope);
if (scope != XmlNamespaceScope.Local)
{
XmlNode node = _startNode;
while (node != null)
{
switch (node.NodeType)
{
case XmlNodeType.Element:
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
for (int i = 0; i < attrs.Count; i++)
{
XmlAttribute attr = attrs[i];
if (Ref.Equal(attr.NamespaceURI, _document.strReservedXmlns))
{
if (attr.Prefix.Length == 0)
{
// xmlns='' declaration
if (!dictionary.ContainsKey(string.Empty))
{
dictionary.Add(string.Empty, attr.Value);
}
}
else
{
// xmlns:prefix='' declaration
if (!dictionary.ContainsKey(attr.LocalName))
{
dictionary.Add(attr.LocalName, attr.Value);
}
}
}
}
}
node = node.ParentNode;
break;
case XmlNodeType.Attribute:
node = ((XmlAttribute)node).OwnerElement;
break;
default:
node = node.ParentNode;
break;
}
}
}
return dictionary;
}
public string LookupNamespace(string prefix)
{
string namespaceName = _nsManager.LookupNamespace(prefix);
if (namespaceName == null)
{
namespaceName = _startNode.GetNamespaceOfPrefixStrict(prefix);
}
return namespaceName;
}
public string LookupPrefix(string namespaceName)
{
string prefix = _nsManager.LookupPrefix(namespaceName);
if (prefix == null)
{
prefix = _startNode.GetPrefixOfNamespaceStrict(namespaceName);
}
return prefix;
}
private IXmlNamespaceResolver NamespaceResolver
{
get
{
if ((object)_startNode == (object)_document)
{
return _nsManager;
}
return this;
}
}
private void CreateValidator(XmlSchemaObject partialValidationType, XmlSchemaValidationFlags validationFlags)
{
_validator = new XmlSchemaValidator(_nameTable, _schemas, NamespaceResolver, validationFlags);
_validator.SourceUri = XmlConvert.ToUri(_document.BaseURI);
_validator.XmlResolver = null;
_validator.ValidationEventHandler += _internalEventHandler;
_validator.ValidationEventSender = this;
if (partialValidationType != null)
{
_validator.Initialize(partialValidationType);
}
else
{
_validator.Initialize();
}
}
private void ValidateNode(XmlNode node)
{
_currentNode = node;
switch (_currentNode.NodeType)
{
case XmlNodeType.Document:
XmlElement docElem = ((XmlDocument)node).DocumentElement;
if (docElem == null)
{
throw new InvalidOperationException(string.Format(ResXml.Xml_InvalidXmlDocument, string.Format(ResXml.Xdom_NoRootEle)));
}
ValidateNode(docElem);
break;
case XmlNodeType.DocumentFragment:
case XmlNodeType.EntityReference:
for (XmlNode child = node.FirstChild; child != null; child = child.NextSibling)
{
ValidateNode(child);
}
break;
case XmlNodeType.Element:
ValidateElement();
break;
case XmlNodeType.Attribute: //Top-level attribute
XmlAttribute attr = _currentNode as XmlAttribute;
_validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, _nodeValueGetter, _attributeSchemaInfo);
if (_psviAugmentation)
{
attr.XmlName = _document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, _attributeSchemaInfo);
}
break;
case XmlNodeType.Text:
_validator.ValidateText(_nodeValueGetter);
break;
case XmlNodeType.CDATA:
_validator.ValidateText(_nodeValueGetter);
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_validator.ValidateWhitespace(_nodeValueGetter);
break;
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
break;
default:
throw new InvalidOperationException(string.Format(ResXml.Xml_UnexpectedNodeType, new string[] { _currentNode.NodeType.ToString() }));
}
}
// SxS: This function calls ValidateElement on XmlSchemaValidator which is annotated with ResourceExposure attribute.
// Since the resource names passed to ValidateElement method are null and the function does not expose any resources
// it is fine to disable the SxS warning.
private void ValidateElement()
{
_nsManager.PushScope();
XmlElement elementNode = _currentNode as XmlElement;
Debug.Assert(elementNode != null);
XmlAttributeCollection attributes = elementNode.Attributes;
XmlAttribute attr = null;
//Find Xsi attributes that need to be processed before validating the element
string xsiNil = null;
string xsiType = null;
for (int i = 0; i < attributes.Count; i++)
{
attr = attributes[i];
string objectNs = attr.NamespaceURI;
string objectName = attr.LocalName;
Debug.Assert(_nameTable.Get(attr.NamespaceURI) != null);
Debug.Assert(_nameTable.Get(attr.LocalName) != null);
if (Ref.Equal(objectNs, _nsXsi))
{
if (Ref.Equal(objectName, _xsiType))
{
xsiType = attr.Value;
}
else if (Ref.Equal(objectName, _xsiNil))
{
xsiNil = attr.Value;
}
}
else if (Ref.Equal(objectNs, _nsXmlNs))
{
_nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value);
}
}
_validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, _schemaInfo, xsiType, xsiNil, null, null);
ValidateAttributes(elementNode);
_validator.ValidateEndOfAttributes(_schemaInfo);
//If element has children, drill down
for (XmlNode child = elementNode.FirstChild; child != null; child = child.NextSibling)
{
ValidateNode(child);
}
//Validate end of element
_currentNode = elementNode; //Reset current Node for validation call back
_validator.ValidateEndElement(_schemaInfo);
//Get XmlName, as memberType / validity might be set now
if (_psviAugmentation)
{
elementNode.XmlName = _document.AddXmlName(elementNode.Prefix, elementNode.LocalName, elementNode.NamespaceURI, _schemaInfo);
if (_schemaInfo.IsDefault)
{ //the element has a default value
XmlText textNode = _document.CreateTextNode(_schemaInfo.SchemaElement.ElementDecl.DefaultValueRaw);
elementNode.AppendChild(textNode);
}
}
_nsManager.PopScope(); //Pop current namespace scope
}
private void ValidateAttributes(XmlElement elementNode)
{
XmlAttributeCollection attributes = elementNode.Attributes;
XmlAttribute attr = null;
for (int i = 0; i < attributes.Count; i++)
{
attr = attributes[i];
_currentNode = attr; //For nodeValueGetter to pick up the right attribute value
if (Ref.Equal(attr.NamespaceURI, _nsXmlNs))
{ //Do not validate namespace decls
continue;
}
_validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, _nodeValueGetter, _attributeSchemaInfo);
if (_psviAugmentation)
{
attr.XmlName = _document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, _attributeSchemaInfo);
}
}
if (_psviAugmentation)
{
//Add default attributes to the attributes collection
if (_defaultAttributes == null)
{
_defaultAttributes = new ArrayList();
}
else
{
_defaultAttributes.Clear();
}
_validator.GetUnspecifiedDefaultAttributes(_defaultAttributes);
XmlSchemaAttribute schemaAttribute = null;
XmlQualifiedName attrQName;
attr = null;
for (int i = 0; i < _defaultAttributes.Count; i++)
{
schemaAttribute = _defaultAttributes[i] as XmlSchemaAttribute;
attrQName = schemaAttribute.QualifiedName;
Debug.Assert(schemaAttribute != null);
attr = _document.CreateDefaultAttribute(GetDefaultPrefix(attrQName.Namespace), attrQName.Name, attrQName.Namespace);
SetDefaultAttributeSchemaInfo(schemaAttribute);
attr.XmlName = _document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, _attributeSchemaInfo);
attr.AppendChild(_document.CreateTextNode(schemaAttribute.AttDef.DefaultValueRaw));
attributes.Append(attr);
XmlUnspecifiedAttribute defAttr = attr as XmlUnspecifiedAttribute;
if (defAttr != null)
{
defAttr.SetSpecified(false);
}
}
}
}
private void SetDefaultAttributeSchemaInfo(XmlSchemaAttribute schemaAttribute)
{
Debug.Assert(_attributeSchemaInfo != null);
_attributeSchemaInfo.Clear();
_attributeSchemaInfo.IsDefault = true;
_attributeSchemaInfo.IsNil = false;
_attributeSchemaInfo.SchemaType = schemaAttribute.AttributeSchemaType;
_attributeSchemaInfo.SchemaAttribute = schemaAttribute;
//Get memberType for default attribute
SchemaAttDef attributeDef = schemaAttribute.AttDef;
if (attributeDef.Datatype.Variety == XmlSchemaDatatypeVariety.Union)
{
XsdSimpleValue simpleValue = attributeDef.DefaultValueTyped as XsdSimpleValue;
Debug.Assert(simpleValue != null);
_attributeSchemaInfo.MemberType = simpleValue.XmlType;
}
_attributeSchemaInfo.Validity = XmlSchemaValidity.Valid;
}
private string GetDefaultPrefix(string attributeNS)
{
IDictionary<string, string> namespaceDecls = NamespaceResolver.GetNamespacesInScope(XmlNamespaceScope.All);
string defaultPrefix = null;
string defaultNS;
attributeNS = _nameTable.Add(attributeNS); //atomize ns
foreach (KeyValuePair<string, string> pair in namespaceDecls)
{
defaultNS = _nameTable.Add(pair.Value);
if (object.ReferenceEquals(defaultNS, attributeNS))
{
defaultPrefix = pair.Key;
if (defaultPrefix.Length != 0)
{ //Locate first non-empty prefix
return defaultPrefix;
}
}
}
return defaultPrefix;
}
private object GetNodeValue()
{
return _currentNode.Value;
}
//Code for finding type during partial validation
private XmlSchemaObject FindSchemaInfo(XmlElement elementToValidate)
{
_isPartialTreeValid = true;
Debug.Assert(elementToValidate.ParentNode.NodeType != XmlNodeType.Document); //Handle if it is the documentElement seperately
//Create nodelist to navigate down again
XmlNode currentNode = elementToValidate;
IXmlSchemaInfo parentSchemaInfo = null;
int nodeIndex = 0;
//Check common case of parent node first
XmlNode parentNode = currentNode.ParentNode;
do
{
parentSchemaInfo = parentNode.SchemaInfo;
if (parentSchemaInfo.SchemaElement != null || parentSchemaInfo.SchemaType != null)
{
break; //Found ancestor with schemaInfo
}
CheckNodeSequenceCapacity(nodeIndex);
_nodeSequenceToValidate[nodeIndex++] = parentNode;
parentNode = parentNode.ParentNode;
} while (parentNode != null);
if (parentNode == null)
{ //Did not find any type info all the way to the root, currentNode is Document || DocumentFragment
nodeIndex = nodeIndex - 1; //Subtract the one for document and set the node to null
_nodeSequenceToValidate[nodeIndex] = null;
return GetTypeFromAncestors(elementToValidate, null, nodeIndex);
}
else
{
//Start validating down from the parent or ancestor that has schema info and shallow validate all previous siblings
//to correctly ascertain particle for current node
CheckNodeSequenceCapacity(nodeIndex);
_nodeSequenceToValidate[nodeIndex++] = parentNode;
XmlSchemaObject ancestorSchemaObject = parentSchemaInfo.SchemaElement;
if (ancestorSchemaObject == null)
{
ancestorSchemaObject = parentSchemaInfo.SchemaType;
}
return GetTypeFromAncestors(elementToValidate, ancestorSchemaObject, nodeIndex);
}
}
/*private XmlSchemaElement GetTypeFromParent(XmlElement elementToValidate, XmlSchemaComplexType parentSchemaType) {
XmlQualifiedName elementName = new XmlQualifiedName(elementToValidate.LocalName, elementToValidate.NamespaceURI);
XmlSchemaElement elem = parentSchemaType.LocalElements[elementName] as XmlSchemaElement;
if (elem == null) { //Element not found as direct child of the content model. It might be invalid at this position or it might be a substitution member
SchemaInfo compiledSchemaInfo = schemas.CompiledInfo;
XmlSchemaElement memberElem = compiledSchemaInfo.GetElement(elementName);
if (memberElem != null) {
}
}
}*/
private void CheckNodeSequenceCapacity(int currentIndex)
{
if (_nodeSequenceToValidate == null)
{ //Normally users would call Validate one level down, this allows for 4
_nodeSequenceToValidate = new XmlNode[4];
}
else if (currentIndex >= _nodeSequenceToValidate.Length - 1)
{ //reached capacity of array, Need to increase capacity to twice the initial
XmlNode[] newNodeSequence = new XmlNode[_nodeSequenceToValidate.Length * 2];
Array.Copy(_nodeSequenceToValidate, 0, newNodeSequence, 0, _nodeSequenceToValidate.Length);
_nodeSequenceToValidate = newNodeSequence;
}
}
private XmlSchemaAttribute FindSchemaInfo(XmlAttribute attributeToValidate)
{
XmlElement parentElement = attributeToValidate.OwnerElement;
XmlSchemaObject schemaObject = FindSchemaInfo(parentElement);
XmlSchemaComplexType elementSchemaType = GetComplexType(schemaObject);
if (elementSchemaType == null)
{
return null;
}
XmlQualifiedName attName = new XmlQualifiedName(attributeToValidate.LocalName, attributeToValidate.NamespaceURI);
XmlSchemaAttribute schemaAttribute = elementSchemaType.AttributeUses[attName] as XmlSchemaAttribute;
if (schemaAttribute == null)
{
XmlSchemaAnyAttribute anyAttribute = elementSchemaType.AttributeWildcard;
if (anyAttribute != null)
{
if (anyAttribute.NamespaceList.Allows(attName))
{ //Match wildcard against global attribute
schemaAttribute = _schemas.GlobalAttributes[attName] as XmlSchemaAttribute;
}
}
}
return schemaAttribute;
}
private XmlSchemaObject GetTypeFromAncestors(XmlElement elementToValidate, XmlSchemaObject ancestorType, int ancestorsCount)
{
//schemaInfo is currentNode's schemaInfo
_validator = CreateTypeFinderValidator(ancestorType);
_schemaInfo = new XmlSchemaInfo();
//start at the ancestor to start validating
int startIndex = ancestorsCount - 1;
bool ancestorHasWildCard = AncestorTypeHasWildcard(ancestorType);
for (int i = startIndex; i >= 0; i--)
{
XmlNode node = _nodeSequenceToValidate[i];
XmlElement currentElement = node as XmlElement;
ValidateSingleElement(currentElement, false, _schemaInfo);
if (!ancestorHasWildCard)
{ //store type if ancestor does not have wildcard in its content model
currentElement.XmlName = _document.AddXmlName(currentElement.Prefix, currentElement.LocalName, currentElement.NamespaceURI, _schemaInfo);
//update wildcard flag
ancestorHasWildCard = AncestorTypeHasWildcard(_schemaInfo.SchemaElement);
}
_validator.ValidateEndOfAttributes(null);
if (i > 0)
{
ValidateChildrenTillNextAncestor(node, _nodeSequenceToValidate[i - 1]);
}
else
{ //i == 0
ValidateChildrenTillNextAncestor(node, elementToValidate);
}
}
Debug.Assert(_nodeSequenceToValidate[0] == elementToValidate.ParentNode);
//validate element whose type is needed,
ValidateSingleElement(elementToValidate, false, _schemaInfo);
XmlSchemaObject schemaInfoFound = null;
if (_schemaInfo.SchemaElement != null)
{
schemaInfoFound = _schemaInfo.SchemaElement;
}
else
{
schemaInfoFound = _schemaInfo.SchemaType;
}
if (schemaInfoFound == null)
{ //Detect if the node was validated lax or skip
if (_validator.CurrentProcessContents == XmlSchemaContentProcessing.Skip)
{
if (_isPartialTreeValid)
{ //Then node assessed as skip; if there was error we turn processContents to skip as well. But this is not the same as validating as skip.
return XmlSchemaComplexType.AnyTypeSkip;
}
}
else if (_validator.CurrentProcessContents == XmlSchemaContentProcessing.Lax)
{
return XmlSchemaComplexType.AnyType;
}
}
return schemaInfoFound;
}
private bool AncestorTypeHasWildcard(XmlSchemaObject ancestorType)
{
XmlSchemaComplexType ancestorSchemaType = GetComplexType(ancestorType);
if (ancestorType != null)
{
return ancestorSchemaType.HasWildCard;
}
return false;
}
private XmlSchemaComplexType GetComplexType(XmlSchemaObject schemaObject)
{
if (schemaObject == null)
{
return null;
}
XmlSchemaElement schemaElement = schemaObject as XmlSchemaElement;
XmlSchemaComplexType complexType = null;
if (schemaElement != null)
{
complexType = schemaElement.ElementSchemaType as XmlSchemaComplexType;
}
else
{
complexType = schemaObject as XmlSchemaComplexType;
}
return complexType;
}
// SxS: This function calls ValidateElement on XmlSchemaValidator which is annotated with ResourceExposure attribute.
// Since the resource names passed to ValidateElement method are null and the function does not expose any resources
// it is fine to supress the warning.
private void ValidateSingleElement(XmlElement elementNode, bool skipToEnd, XmlSchemaInfo newSchemaInfo)
{
_nsManager.PushScope();
Debug.Assert(elementNode != null);
XmlAttributeCollection attributes = elementNode.Attributes;
XmlAttribute attr = null;
//Find Xsi attributes that need to be processed before validating the element
string xsiNil = null;
string xsiType = null;
for (int i = 0; i < attributes.Count; i++)
{
attr = attributes[i];
string objectNs = attr.NamespaceURI;
string objectName = attr.LocalName;
Debug.Assert(_nameTable.Get(attr.NamespaceURI) != null);
Debug.Assert(_nameTable.Get(attr.LocalName) != null);
if (Ref.Equal(objectNs, _nsXsi))
{
if (Ref.Equal(objectName, _xsiType))
{
xsiType = attr.Value;
}
else if (Ref.Equal(objectName, _xsiNil))
{
xsiNil = attr.Value;
}
}
else if (Ref.Equal(objectNs, _nsXmlNs))
{
_nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value);
}
}
_validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, newSchemaInfo, xsiType, xsiNil, null, null);
//Validate end of element
if (skipToEnd)
{
_validator.ValidateEndOfAttributes(newSchemaInfo);
_validator.SkipToEndElement(newSchemaInfo);
_nsManager.PopScope(); //Pop current namespace scope
}
}
private void ValidateChildrenTillNextAncestor(XmlNode parentNode, XmlNode childToStopAt)
{
XmlNode child;
for (child = parentNode.FirstChild; child != null; child = child.NextSibling)
{
if (child == childToStopAt)
{
break;
}
switch (child.NodeType)
{
case XmlNodeType.EntityReference:
ValidateChildrenTillNextAncestor(child, childToStopAt);
break;
case XmlNodeType.Element: //Flat validation, do not drill down into children
ValidateSingleElement(child as XmlElement, true, null);
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
_validator.ValidateText(child.Value);
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_validator.ValidateWhitespace(child.Value);
break;
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
break;
default:
throw new InvalidOperationException(string.Format(ResXml.Xml_UnexpectedNodeType, new string[] { _currentNode.NodeType.ToString() }));
}
}
Debug.Assert(child == childToStopAt);
}
private XmlSchemaValidator CreateTypeFinderValidator(XmlSchemaObject partialValidationType)
{
XmlSchemaValidator findTypeValidator = new XmlSchemaValidator(_document.NameTable, _document.Schemas, _nsManager, XmlSchemaValidationFlags.None);
findTypeValidator.ValidationEventHandler += new ValidationEventHandler(TypeFinderCallBack);
if (partialValidationType != null)
{
findTypeValidator.Initialize(partialValidationType);
}
else
{ //If we walked up to the root and no schemaInfo was there, start validating from root
findTypeValidator.Initialize();
}
return findTypeValidator;
}
private void TypeFinderCallBack(object sender, ValidationEventArgs arg)
{
if (arg.Severity == XmlSeverityType.Error)
{
_isPartialTreeValid = false;
}
}
private void InternalValidationCallBack(object sender, ValidationEventArgs arg)
{
if (arg.Severity == XmlSeverityType.Error)
{
_isValid = false;
}
XmlSchemaValidationException ex = arg.Exception as XmlSchemaValidationException;
Debug.Assert(ex != null);
ex.SetSourceObject(_currentNode);
if (_eventHandler != null)
{ //Invoke user's event handler
_eventHandler(sender, arg);
}
else if (arg.Severity == XmlSeverityType.Error)
{
throw ex;
}
}
}
}
| |
using System;
using Rothko.Interfaces.Commands;
using Rothko.Commands;
using NUnit.Framework;
using Rothko.Model;
using Rothko.Enumerators;
namespace Rothko.Tests.Commands
{
[TestFixture]
public class SelectCommandTests
{
Map _Map;
Unit _Unit1;
Unit _Unit2;
Unit _DeadUnit;
Unit _CarrierUnit;
Structure _Structure1;
Structure _Structure2;
SelectCommand _Command;
[SetUp]
public void SetUp()
{
_Map = new Map();
_Unit1 = new Unit() { ID = 1, X = 1, Y = 1, HealthPoints = 10 };
_Unit2 = new Unit() { ID = 2, X = 2, Y = 3, HealthPoints = 10, MovePoints = 10 };
_DeadUnit = new Unit() { ID = 3, X = 2, Y = 3, HealthPoints = 0 };
_CarrierUnit = new Unit() { ID = 4, X = 2, Y = 3, HealthPoints = 10 };
_Structure1 = new Structure() { ID = 1, X = 1, Y = 1 };
_Structure2 = new Structure() { ID = 2, X = 2, Y = 3 };
_Command = new SelectCommand(_Map, 2, 3);
}
[Test]
public void SelectCommandShouldSelectUnitInCoordinatesWhenUnitIsPresent()
{
_Map.Units.Add (_Unit1);
_Map.Units.Add (_Unit2);
Assert.AreEqual(null, _Map.IDUnit_Selected);
Assert.AreEqual(null, _Map.SelectedUnit);
_Command.Execute();
Assert.AreEqual(_Unit2.ID, _Map.IDUnit_Selected);
Assert.AreNotEqual(null, _Map.SelectedUnit);
Assert.AreEqual(_Unit2.ID, _Map.SelectedUnit.ID);
}
[Test]
public void SelectCommandShouldSetGameStateToUnitDecidingPathIfSelectingUnitWhichHasntMovedYet()
{
_Map.Units.Add (_Unit2);
_Command.Execute();
Assert.AreEqual(GameState.UnitDecidingPath, _Map.GameState);
}
[Test]
public void SelectCommandShouldSetGameStateToUnitSelectIfSelectingUnitCannotMoveAnymore()
{
_Unit2.MovePoints = 0;
_Map.Units.Add (_Unit2);
_Command.Execute();
Assert.AreEqual(GameState.UnitSelected, _Map.GameState);
}
[Test]
public void SelectCommandShouldDoNothingIfNoUnitIsPresent()
{
_Command.Execute();
Assert.AreEqual(null, _Map.IDUnit_Selected);
}
[Test]
public void SelectCommandShouldDoNothingIfUnitIsInactive()
{
_Map.Units.Add (_DeadUnit);
_Command.Execute();
Assert.AreEqual(null, _Map.IDUnit_Selected);
}
[Test]
public void SelectCommandShouldSelectCarrierUnitIfThereAreMoreThanOneUnitsInLocation()
{
_Unit2.IDUnitCarrier = _CarrierUnit.ID;
_Map.Units.Add (_Unit2);
_Map.Units.Add (_CarrierUnit);
_Command.Execute();
Assert.AreEqual(_CarrierUnit.ID, _Map.IDUnit_Selected);
_Map.Units.Clear();
_Map.Units.Add (_CarrierUnit);
_Map.Units.Add (_Unit2);
_Command.Execute();
Assert.AreEqual(_CarrierUnit.ID, _Map.IDUnit_Selected);
}
[Test]
public void SelectCommandShouldSelectStructureIfThereIsNoUnitInLocation()
{
_Map.Structures.Add (_Structure1);
_Map.Structures.Add (_Structure2);
_Command.Execute();
Assert.AreEqual(_Structure2.ID, _Map.IDStructure_Selected);
Assert.AreEqual(_Structure2, _Map.SelectedStructure);
}
[Test]
public void SelectCommandShouldSetGameStateToStructureSelectedIfSelectingStructure()
{
_Map.Structures.Add (_Structure2);
_Command.Execute();
Assert.AreEqual(GameState.StructureSelected, _Map.GameState);
}
[Test]
public void SelectCommandShouldSelectUnitIfThereIsBothUnitAndStructureInSameLocation()
{
_Map.Units.Add (_Unit1);
_Map.Units.Add (_Unit2);
_Map.Structures.Add (_Structure1);
_Map.Structures.Add (_Structure2);
_Command.Execute();
Assert.AreEqual(_Unit2.ID, _Map.IDUnit_Selected);
Assert.AreEqual(_Unit2, _Map.SelectedUnit);
Assert.AreEqual(null, _Map.IDStructure_Selected);
Assert.AreEqual(null, _Map.SelectedStructure);
}
[Test]
public void SelectCommandShouldUnSelectUnitIfWeAreNowSelectingStructure()
{
_Map.Units.Add (_Unit1);
_Map.Units.Add (_Unit2);
_Map.Structures.Add (_Structure1);
_Map.Structures.Add (_Structure2);
_Command.Execute();
Assert.AreEqual(_Unit2.ID, _Map.IDUnit_Selected);
Assert.AreEqual(_Unit2, _Map.SelectedUnit);
_Unit2.X = 99;
_Command.Execute();
Assert.AreEqual(null, _Map.IDUnit_Selected);
Assert.AreEqual(null, _Map.SelectedUnit);
Assert.AreEqual(_Structure2.ID, _Map.IDStructure_Selected);
Assert.AreEqual(_Structure2, _Map.SelectedStructure);
}
[Test]
public void SelectCommandShouldUnSelectStructureIfWeAreNowSelectingUnit()
{
_Unit2.X = 99;
_Map.Units.Add (_Unit1);
_Map.Units.Add (_Unit2);
_Map.Structures.Add (_Structure1);
_Map.Structures.Add (_Structure2);
_Command.Execute();
Assert.AreEqual(_Structure2.ID, _Map.IDStructure_Selected);
Assert.AreEqual(_Structure2, _Map.SelectedStructure);
_Unit2.X = 2;
_Structure2.X = 99;
_Command.Execute();
Assert.AreEqual(_Unit2.ID, _Map.IDUnit_Selected);
Assert.AreEqual(_Unit2, _Map.SelectedUnit);
Assert.AreEqual(null, _Map.IDStructure_Selected);
Assert.AreEqual(null, _Map.SelectedStructure);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Reflection.Internal;
namespace System.Reflection.Metadata.Ecma335
{
internal struct StringStreamReader
{
private static string[] virtualValues;
internal readonly MemoryBlock Block;
internal StringStreamReader(MemoryBlock block, MetadataKind metadataKind)
{
if (virtualValues == null && metadataKind != MetadataKind.Ecma335)
{
// Note:
// Virtual values shall not contain surrogates, otherwise StartsWith might be inconsistent
// when comparing to a text that ends with a high surrogate.
var values = new string[(int)StringHandle.VirtualIndex.Count];
values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime] = "System.Runtime.WindowsRuntime";
values[(int)StringHandle.VirtualIndex.System_Runtime] = "System.Runtime";
values[(int)StringHandle.VirtualIndex.System_ObjectModel] = "System.ObjectModel";
values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml] = "System.Runtime.WindowsRuntime.UI.Xaml";
values[(int)StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime] = "System.Runtime.InteropServices.WindowsRuntime";
values[(int)StringHandle.VirtualIndex.System_Numerics_Vectors] = "System.Numerics.Vectors";
values[(int)StringHandle.VirtualIndex.Dispose] = "Dispose";
values[(int)StringHandle.VirtualIndex.AttributeTargets] = "AttributeTargets";
values[(int)StringHandle.VirtualIndex.AttributeUsageAttribute] = "AttributeUsageAttribute";
values[(int)StringHandle.VirtualIndex.Color] = "Color";
values[(int)StringHandle.VirtualIndex.CornerRadius] = "CornerRadius";
values[(int)StringHandle.VirtualIndex.DateTimeOffset] = "DateTimeOffset";
values[(int)StringHandle.VirtualIndex.Duration] = "Duration";
values[(int)StringHandle.VirtualIndex.DurationType] = "DurationType";
values[(int)StringHandle.VirtualIndex.EventHandler1] = "EventHandler`1";
values[(int)StringHandle.VirtualIndex.EventRegistrationToken] = "EventRegistrationToken";
values[(int)StringHandle.VirtualIndex.Exception] = "Exception";
values[(int)StringHandle.VirtualIndex.GeneratorPosition] = "GeneratorPosition";
values[(int)StringHandle.VirtualIndex.GridLength] = "GridLength";
values[(int)StringHandle.VirtualIndex.GridUnitType] = "GridUnitType";
values[(int)StringHandle.VirtualIndex.ICommand] = "ICommand";
values[(int)StringHandle.VirtualIndex.IDictionary2] = "IDictionary`2";
values[(int)StringHandle.VirtualIndex.IDisposable] = "IDisposable";
values[(int)StringHandle.VirtualIndex.IEnumerable] = "IEnumerable";
values[(int)StringHandle.VirtualIndex.IEnumerable1] = "IEnumerable`1";
values[(int)StringHandle.VirtualIndex.IList] = "IList";
values[(int)StringHandle.VirtualIndex.IList1] = "IList`1";
values[(int)StringHandle.VirtualIndex.INotifyCollectionChanged] = "INotifyCollectionChanged";
values[(int)StringHandle.VirtualIndex.INotifyPropertyChanged] = "INotifyPropertyChanged";
values[(int)StringHandle.VirtualIndex.IReadOnlyDictionary2] = "IReadOnlyDictionary`2";
values[(int)StringHandle.VirtualIndex.IReadOnlyList1] = "IReadOnlyList`1";
values[(int)StringHandle.VirtualIndex.KeyTime] = "KeyTime";
values[(int)StringHandle.VirtualIndex.KeyValuePair2] = "KeyValuePair`2";
values[(int)StringHandle.VirtualIndex.Matrix] = "Matrix";
values[(int)StringHandle.VirtualIndex.Matrix3D] = "Matrix3D";
values[(int)StringHandle.VirtualIndex.Matrix3x2] = "Matrix3x2";
values[(int)StringHandle.VirtualIndex.Matrix4x4] = "Matrix4x4";
values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedAction] = "NotifyCollectionChangedAction";
values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs] = "NotifyCollectionChangedEventArgs";
values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler] = "NotifyCollectionChangedEventHandler";
values[(int)StringHandle.VirtualIndex.Nullable1] = "Nullable`1";
values[(int)StringHandle.VirtualIndex.Plane] = "Plane";
values[(int)StringHandle.VirtualIndex.Point] = "Point";
values[(int)StringHandle.VirtualIndex.PropertyChangedEventArgs] = "PropertyChangedEventArgs";
values[(int)StringHandle.VirtualIndex.PropertyChangedEventHandler] = "PropertyChangedEventHandler";
values[(int)StringHandle.VirtualIndex.Quaternion] = "Quaternion";
values[(int)StringHandle.VirtualIndex.Rect] = "Rect";
values[(int)StringHandle.VirtualIndex.RepeatBehavior] = "RepeatBehavior";
values[(int)StringHandle.VirtualIndex.RepeatBehaviorType] = "RepeatBehaviorType";
values[(int)StringHandle.VirtualIndex.Size] = "Size";
values[(int)StringHandle.VirtualIndex.System] = "System";
values[(int)StringHandle.VirtualIndex.System_Collections] = "System.Collections";
values[(int)StringHandle.VirtualIndex.System_Collections_Generic] = "System.Collections.Generic";
values[(int)StringHandle.VirtualIndex.System_Collections_Specialized] = "System.Collections.Specialized";
values[(int)StringHandle.VirtualIndex.System_ComponentModel] = "System.ComponentModel";
values[(int)StringHandle.VirtualIndex.System_Numerics] = "System.Numerics";
values[(int)StringHandle.VirtualIndex.System_Windows_Input] = "System.Windows.Input";
values[(int)StringHandle.VirtualIndex.Thickness] = "Thickness";
values[(int)StringHandle.VirtualIndex.TimeSpan] = "TimeSpan";
values[(int)StringHandle.VirtualIndex.Type] = "Type";
values[(int)StringHandle.VirtualIndex.Uri] = "Uri";
values[(int)StringHandle.VirtualIndex.Vector2] = "Vector2";
values[(int)StringHandle.VirtualIndex.Vector3] = "Vector3";
values[(int)StringHandle.VirtualIndex.Vector4] = "Vector4";
values[(int)StringHandle.VirtualIndex.Windows_Foundation] = "Windows.Foundation";
values[(int)StringHandle.VirtualIndex.Windows_UI] = "Windows.UI";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml] = "Windows.UI.Xaml";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives] = "Windows.UI.Xaml.Controls.Primitives";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media] = "Windows.UI.Xaml.Media";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation] = "Windows.UI.Xaml.Media.Animation";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D] = "Windows.UI.Xaml.Media.Media3D";
virtualValues = values;
AssertFilled();
}
this.Block = TrimEnd(block);
}
[Conditional("DEBUG")]
private static void AssertFilled()
{
for (int i = 0; i < virtualValues.Length; i++)
{
Debug.Assert(virtualValues[i] != null, "Missing virtual value for StringHandle.VirtualIndex." + (StringHandle.VirtualIndex)i);
}
}
// Trims the alignment padding of the heap.
// See StgStringPool::InitOnMem in ndp\clr\src\Utilcode\StgPool.cpp.
// This is especially important for EnC.
private static MemoryBlock TrimEnd(MemoryBlock block)
{
if (block.Length == 0)
{
return block;
}
int i = block.Length - 1;
while (i >= 0 && block.PeekByte(i) == 0)
{
i--;
}
// this shouldn't happen in valid metadata:
if (i == block.Length - 1)
{
return block;
}
// +1 for terminating \0
return block.GetMemoryBlockAt(0, i + 2);
}
internal string GetVirtualValue(StringHandle.VirtualIndex index)
{
return virtualValues[(int)index];
}
internal string GetString(StringHandle handle, MetadataStringDecoder utf8Decoder)
{
int index = handle.Index;
byte[] prefix;
if (handle.IsVirtual)
{
switch (handle.StringKind)
{
case StringKind.Plain:
return virtualValues[index];
case StringKind.WinRTPrefixed:
prefix = MetadataReader.WinRTPrefix;
break;
default:
Debug.Assert(false, "We should not get here");
return null;
}
}
else
{
prefix = null;
}
int bytesRead;
char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0';
return this.Block.PeekUtf8NullTerminated(index, prefix, utf8Decoder, out bytesRead, otherTerminator);
}
internal StringHandle GetNextHandle(StringHandle handle)
{
if (handle.IsVirtual)
{
return default(StringHandle);
}
int terminator = this.Block.IndexOf(0, handle.Index);
if (terminator == -1 || terminator == Block.Length - 1)
{
return default(StringHandle);
}
return StringHandle.FromIndex((uint)(terminator + 1));
}
internal bool Equals(StringHandle handle, string value, MetadataStringDecoder utf8Decoder)
{
Debug.Assert(value != null);
if (handle.IsVirtual)
{
// TODO:This can allocate unnecessarily for <WinRT> prefixed handles.
return GetString(handle, utf8Decoder) == value;
}
if (handle.IsNil)
{
return value.Length == 0;
}
// TODO: MetadataStringComparer needs to use the user-supplied encoding.
// Need to pass the decoder down and use in Utf8NullTerminatedEquals.
char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0';
return this.Block.Utf8NullTerminatedEquals(handle.Index, value, otherTerminator);
}
internal bool StartsWith(StringHandle handle, string value, MetadataStringDecoder utf8Decoder)
{
Debug.Assert(value != null);
if (handle.IsVirtual)
{
// TODO:This can allocate unnecessarily for <WinRT> prefixed handles.
return GetString(handle, utf8Decoder).StartsWith(value, StringComparison.Ordinal);
}
if (handle.IsNil)
{
return value.Length == 0;
}
// TODO: MetadataStringComparer needs to use the user-supplied encoding.
// Need to pass the decoder down and use in Utf8NullTerminatedEquals.
char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0';
return this.Block.Utf8NullTerminatedStartsWith(handle.Index, value, otherTerminator);
}
/// <summary>
/// Returns true if the given raw (non-virtual) handle represents the same string as given ASCII string.
/// </summary>
internal bool EqualsRaw(StringHandle rawHandle, string asciiString)
{
Debug.Assert(!rawHandle.IsVirtual);
Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported");
return this.Block.CompareUtf8NullTerminatedStringWithAsciiString(rawHandle.Index, asciiString) == 0;
}
/// <summary>
/// Returns the heap index of the given ASCII character or -1 if not found prior null terminator or end of heap.
/// </summary>
internal int IndexOfRaw(int startIndex, char asciiChar)
{
Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f);
return this.Block.Utf8NullTerminatedOffsetOfAsciiChar(startIndex, asciiChar);
}
/// <summary>
/// Returns true if the given raw (non-virtual) handle represents a string that starts with given ASCII prefix.
/// </summary>
internal bool StartsWithRaw(StringHandle rawHandle, string asciiPrefix)
{
Debug.Assert(!rawHandle.IsVirtual);
Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported");
return this.Block.Utf8NullTermintatedStringStartsWithAsciiPrefix(rawHandle.Index, asciiPrefix);
}
/// <summary>
/// Equivalent to Array.BinarySearch, searches for given raw (non-virtual) handle in given array of ASCII strings.
/// </summary>
internal int BinarySearchRaw(string[] asciiKeys, StringHandle rawHandle)
{
Debug.Assert(!rawHandle.IsVirtual);
Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported");
return this.Block.BinarySearch(asciiKeys, rawHandle.Index);
}
}
internal unsafe struct BlobStreamReader
{
private struct VirtualHeapBlob
{
public readonly GCHandle Pinned;
public readonly byte[] Array;
public VirtualHeapBlob(byte[] array)
{
Pinned = GCHandle.Alloc(array, GCHandleType.Pinned);
Array = array;
}
}
// Container for virtual heap blobs that unpins handles on finalization.
// This is not handled via dispose because the only resource is managed memory.
private sealed class VirtualHeapBlobTable
{
public readonly Dictionary<BlobHandle, VirtualHeapBlob> Table;
public VirtualHeapBlobTable()
{
Table = new Dictionary<BlobHandle, VirtualHeapBlob>();
}
~VirtualHeapBlobTable()
{
if (Table != null)
{
foreach (var blob in Table.Values)
{
blob.Pinned.Free();
}
}
}
}
// Since the number of virtual blobs we need is small (the number of attribute classes in .winmd files)
// we can create a pinned handle for each of them.
// If we needed many more blobs we could create and pin a single byte[] and allocate blobs there.
private VirtualHeapBlobTable lazyVirtualHeapBlobs;
private static byte[][] virtualHeapBlobs;
internal readonly MemoryBlock Block;
internal BlobStreamReader(MemoryBlock block, MetadataKind metadataKind)
{
this.lazyVirtualHeapBlobs = null;
this.Block = block;
if (virtualHeapBlobs == null && metadataKind != MetadataKind.Ecma335)
{
var blobs = new byte[(int)BlobHandle.VirtualIndex.Count][];
blobs[(int)BlobHandle.VirtualIndex.ContractPublicKeyToken] = new byte[]
{
0xB0, 0x3F, 0x5F, 0x7F, 0x11, 0xD5, 0x0A, 0x3A
};
blobs[(int)BlobHandle.VirtualIndex.ContractPublicKey] = new byte[]
{
0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00,
0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00,
0x07, 0xD1, 0xFA, 0x57, 0xC4, 0xAE, 0xD9, 0xF0, 0xA3, 0x2E, 0x84, 0xAA, 0x0F, 0xAE, 0xFD, 0x0D,
0xE9, 0xE8, 0xFD, 0x6A, 0xEC, 0x8F, 0x87, 0xFB, 0x03, 0x76, 0x6C, 0x83, 0x4C, 0x99, 0x92, 0x1E,
0xB2, 0x3B, 0xE7, 0x9A, 0xD9, 0xD5, 0xDC, 0xC1, 0xDD, 0x9A, 0xD2, 0x36, 0x13, 0x21, 0x02, 0x90,
0x0B, 0x72, 0x3C, 0xF9, 0x80, 0x95, 0x7F, 0xC4, 0xE1, 0x77, 0x10, 0x8F, 0xC6, 0x07, 0x77, 0x4F,
0x29, 0xE8, 0x32, 0x0E, 0x92, 0xEA, 0x05, 0xEC, 0xE4, 0xE8, 0x21, 0xC0, 0xA5, 0xEF, 0xE8, 0xF1,
0x64, 0x5C, 0x4C, 0x0C, 0x93, 0xC1, 0xAB, 0x99, 0x28, 0x5D, 0x62, 0x2C, 0xAA, 0x65, 0x2C, 0x1D,
0xFA, 0xD6, 0x3D, 0x74, 0x5D, 0x6F, 0x2D, 0xE5, 0xF1, 0x7E, 0x5E, 0xAF, 0x0F, 0xC4, 0x96, 0x3D,
0x26, 0x1C, 0x8A, 0x12, 0x43, 0x65, 0x18, 0x20, 0x6D, 0xC0, 0x93, 0x34, 0x4D, 0x5A, 0xD2, 0x93
};
blobs[(int)BlobHandle.VirtualIndex.AttributeUsage_AllowSingle] = new byte[]
{
// preable:
0x01, 0x00,
// target (template parameter):
0x00, 0x00, 0x00, 0x00,
// named arg count:
0x01, 0x00,
// SERIALIZATION_TYPE_PROPERTY
0x54,
// ELEMENT_TYPE_BOOLEAN
0x02,
// "AllowMultiple".Length
0x0D,
// "AllowMultiple"
0x41, 0x6C, 0x6C, 0x6F, 0x77, 0x4D, 0x75, 0x6C, 0x74, 0x69, 0x70, 0x6C, 0x65,
// false
0x00
};
blobs[(int)BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple] = new byte[]
{
// preable:
0x01, 0x00,
// target (template parameter):
0x00, 0x00, 0x00, 0x00,
// named arg count:
0x01, 0x00,
// SERIALIZATION_TYPE_PROPERTY
0x54,
// ELEMENT_TYPE_BOOLEAN
0x02,
// "AllowMultiple".Length
0x0D,
// "AllowMultiple"
0x41, 0x6C, 0x6C, 0x6F, 0x77, 0x4D, 0x75, 0x6C, 0x74, 0x69, 0x70, 0x6C, 0x65,
// true
0x01
};
virtualHeapBlobs = blobs;
}
}
internal byte[] GetBytes(BlobHandle handle)
{
if (handle.IsVirtual)
{
// consider: if we returned an ImmutableArray we wouldn't need to copy
return GetVirtualBlobArray(handle, unique: true);
}
int offset = handle.Index;
int bytesRead;
int numberOfBytes = this.Block.PeekCompressedInteger(offset, out bytesRead);
if (numberOfBytes == BlobReader.InvalidCompressedInteger)
{
return EmptyArray<byte>.Instance;
}
return this.Block.PeekBytes(offset + bytesRead, numberOfBytes);
}
internal BlobReader GetBlobReader(BlobHandle handle)
{
if (handle.IsVirtual)
{
if (lazyVirtualHeapBlobs == null)
{
Interlocked.CompareExchange(ref lazyVirtualHeapBlobs, new VirtualHeapBlobTable(), null);
}
int index = (int)handle.GetVirtualIndex();
int length = virtualHeapBlobs[index].Length;
VirtualHeapBlob virtualBlob;
lock (lazyVirtualHeapBlobs)
{
if (!lazyVirtualHeapBlobs.Table.TryGetValue(handle, out virtualBlob))
{
virtualBlob = new VirtualHeapBlob(GetVirtualBlobArray(handle, unique: false));
lazyVirtualHeapBlobs.Table.Add(handle, virtualBlob);
}
}
return new BlobReader(new MemoryBlock((byte*)virtualBlob.Pinned.AddrOfPinnedObject(), length));
}
int offset, size;
Block.PeekHeapValueOffsetAndSize(handle.Index, out offset, out size);
return new BlobReader(this.Block.GetMemoryBlockAt(offset, size));
}
internal BlobHandle GetNextHandle(BlobHandle handle)
{
if (handle.IsVirtual)
{
return default(BlobHandle);
}
int offset, size;
if (!Block.PeekHeapValueOffsetAndSize(handle.Index, out offset, out size))
{
return default(BlobHandle);
}
int nextIndex = offset + size;
if (nextIndex >= Block.Length)
{
return default(BlobHandle);
}
return BlobHandle.FromIndex((uint)nextIndex);
}
internal byte[] GetVirtualBlobArray(BlobHandle handle, bool unique)
{
BlobHandle.VirtualIndex index = handle.GetVirtualIndex();
byte[] result = virtualHeapBlobs[(int)index];
switch (index)
{
case BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple:
case BlobHandle.VirtualIndex.AttributeUsage_AllowSingle:
result = (byte[])result.Clone();
handle.SubstituteTemplateParameters(result);
break;
default:
if (unique)
{
result = (byte[])result.Clone();
}
break;
}
return result;
}
}
internal struct GuidStreamReader
{
internal readonly MemoryBlock Block;
internal const int GuidSize = 16;
public GuidStreamReader(MemoryBlock block)
{
this.Block = block;
}
internal Guid GetGuid(GuidHandle handle)
{
if (handle.IsNil)
{
return default(Guid);
}
// Metadata Spec: The Guid heap is an array of GUIDs, each 16 bytes wide.
// Its first element is numbered 1, its second 2, and so on.
return this.Block.PeekGuid((handle.Index - 1) * GuidSize);
}
}
internal struct UserStringStreamReader
{
internal readonly MemoryBlock Block;
public UserStringStreamReader(MemoryBlock block)
{
this.Block = block;
}
internal string GetString(UserStringHandle handle)
{
int offset, size;
if (!Block.PeekHeapValueOffsetAndSize(handle.Index, out offset, out size))
{
return string.Empty;
}
// Spec: Furthermore, there is an additional terminal byte (so all byte counts are odd, not even).
// The size in the blob header is the length of the string in bytes + 1.
return this.Block.PeekUtf16(offset, size & ~1);
}
internal UserStringHandle GetNextHandle(UserStringHandle handle)
{
int offset, size;
if (!Block.PeekHeapValueOffsetAndSize(handle.Index, out offset, out size))
{
return default(UserStringHandle);
}
int nextIndex = offset + size;
if (nextIndex >= Block.Length)
{
return default(UserStringHandle);
}
return UserStringHandle.FromIndex((uint)nextIndex);
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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 DiscUtils.Streams;
namespace DiscUtils.Udf
{
internal static class UdfUtilities
{
private static readonly ushort[] CrcTable =
{
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
};
public static ushort ComputeCrc(byte[] buffer, int offset, int length)
{
ushort result = 0;
for (int i = 0; i < length; ++i)
{
result = (ushort)(CrcTable[(result >> 8 ^ buffer[offset + i]) & 0xFF] ^ (result << 8));
}
return result;
}
public static DateTime ParseTimestamp(byte[] buffer, int offset)
{
bool allZero = true;
for (int i = 0; i < 12; ++i)
{
if (buffer[i] != 0)
{
allZero = false;
break;
}
}
if (allZero)
{
return DateTime.MinValue;
}
ushort typeAndZone = EndianUtilities.ToUInt16LittleEndian(buffer, offset);
int type = (typeAndZone >> 12) & 0x0F;
int minutesWest = typeAndZone & 0xFFF;
if ((minutesWest & 0x800) != 0)
{
minutesWest = (-1 & ~0xFFF) | minutesWest;
}
int year = ForceRange(1, 9999, EndianUtilities.ToInt16LittleEndian(buffer, offset + 2));
int month = ForceRange(1, 12, buffer[offset + 4]);
int day = ForceRange(1, 31, buffer[offset + 5]);
int hour = ForceRange(0, 23, buffer[offset + 6]);
int min = ForceRange(0, 59, buffer[offset + 7]);
int sec = ForceRange(0, 59, buffer[offset + 8]);
int csec = ForceRange(0, 99, buffer[offset + 9]);
int hmsec = ForceRange(0, 99, buffer[offset + 10]);
int msec = ForceRange(0, 99, buffer[offset + 11]);
try
{
DateTime baseTime = new DateTime(year, month, day, hour, min, sec, 10 * csec + hmsec / 10,
DateTimeKind.Utc);
return baseTime - TimeSpan.FromMinutes(minutesWest);
}
catch (ArgumentOutOfRangeException)
{
return DateTime.MinValue;
}
}
public static string ReadDString(byte[] buffer, int offset, int count)
{
int byteLen = buffer[offset + count - 1];
return ReadDCharacters(buffer, offset, byteLen);
}
public static string ReadDCharacters(byte[] buffer, int offset, int count)
{
if (count == 0)
{
return string.Empty;
}
byte alg = buffer[offset];
if (alg != 8 && alg != 16)
{
throw new InvalidDataException("Corrupt compressed unicode string");
}
StringBuilder result = new StringBuilder(count);
int pos = 1;
while (pos < count)
{
char ch = '\0';
if (alg == 16)
{
ch = (char)(buffer[offset + pos] << 8);
pos++;
}
if (pos < count)
{
ch |= (char)buffer[offset + pos];
pos++;
}
result.Append(ch);
}
return result.ToString();
}
public static byte[] ReadExtent(UdfContext context, LongAllocationDescriptor extent)
{
LogicalPartition partition = context.LogicalPartitions[extent.ExtentLocation.Partition];
long pos = extent.ExtentLocation.LogicalBlock * partition.LogicalBlockSize;
return StreamUtilities.ReadExact(partition.Content, pos, (int)extent.ExtentLength);
}
private static short ForceRange(short min, short max, short val)
{
if (val < min)
{
return min;
}
if (val > max)
{
return max;
}
return val;
}
private static byte ForceRange(byte min, byte max, byte val)
{
if (val < min)
{
return min;
}
if (val > max)
{
return max;
}
return val;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
namespace System.Collections.Specialized.Tests
{
public class ResetTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
StringCollection sc;
StringEnumerator en;
string curr; // Enumerator.Current value
bool res; // boolean result of MoveNext()
// simple string values
string[] values =
{
"a",
"aa",
"",
" ",
"text",
" spaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// [] StringEnumerator.Reset()
//-----------------------------------------------------------------
sc = new StringCollection();
//
// [] on Empty Collection
//
//
// no exception
//
en = sc.GetEnumerator();
en.Reset();
//
// Attempt to get Current should result in exception
//
Assert.Throws<InvalidOperationException>(() => { curr = en.Current; });
//
// [] Add item to collection and Reset()
//
int cnt = sc.Count;
sc.Add(values[0]);
if (sc.Count != 1)
{
Assert.False(true, string.Format("Error, failed to add item"));
}
Assert.Throws<InvalidOperationException>(() => { en.Reset(); });
//
// [] on Filled collection
//
sc.AddRange(values);
en = sc.GetEnumerator();
//
// Reset() should not result in any exceptions
//
en.Reset();
en.Reset();
//
// [] Move to 0th item and Reset()
//
if (!en.MoveNext())
{
Assert.False(true, string.Format("Error, MoveNext() returned false"));
}
curr = en.Current;
if (String.Compare(curr, values[0]) != 0)
{
Assert.False(true, string.Format("Error, Current returned wrong value"));
}
// Reset() and repeat two checks
en.Reset();
if (!en.MoveNext())
{
Assert.False(true, string.Format("Error, MoveNext() returned false"));
}
if (String.Compare(en.Current, curr) != 0)
{
Assert.False(true, string.Format("Error, Current returned wrong value"));
}
//
// [] Move to Count/2 item and Reset()
//
int ind = sc.Count / 2;
en.Reset();
for (int i = 0; i < ind + 1; i++)
{
res = en.MoveNext();
if (!res)
{
Assert.False(true, string.Format("Error, MoveNext returned false", i));
}
curr = en.Current;
if (String.Compare(curr, sc[i]) != 0)
{
Assert.False(true, string.Format("Error, Current returned \"{1}\" instead of \"{2}\"", i, curr, sc[i]));
}
// while we didn't MoveNext, Current should return the same value
string curr1 = en.Current;
if (String.Compare(curr, curr1) != 0)
{
Assert.False(true, string.Format("Error, second call of Current returned different result", i));
}
}
// Reset() and check 0th item
en.Reset();
if (!en.MoveNext())
{
Assert.False(true, string.Format("Error, MoveNext() returned false"));
}
if (String.Compare(en.Current, sc[0]) != 0)
{
Assert.False(true, string.Format("Error, Current returned wrong value"));
}
//
// [] Move to the last item and Reset()
//
ind = sc.Count;
en.Reset();
for (int i = 0; i < ind; i++)
{
res = en.MoveNext();
if (!res)
{
Assert.False(true, string.Format("Error, MoveNext returned false", i));
}
curr = en.Current;
if (String.Compare(curr, sc[i]) != 0)
{
Assert.False(true, string.Format("Error, Current returned \"{1}\" instead of \"{2}\"", i, curr, sc[i]));
}
// while we didn't MoveNext, Current should return the same value
string curr1 = en.Current;
if (String.Compare(curr, curr1) != 0)
{
Assert.False(true, string.Format("Error, second call of Current returned different result", i));
}
}
// Reset() and check 0th item
en.Reset();
if (!en.MoveNext())
{
Assert.False(true, string.Format("Error, MoveNext() returned false"));
}
if (String.Compare(en.Current, sc[0]) != 0)
{
Assert.False(true, string.Format("Error, Current returned wrong value"));
}
//
// [] Move beyond the last item and Reset()
//
en.Reset();
for (int i = 0; i < ind; i++)
{
res = en.MoveNext();
}
// next MoveNext should bring us outside of the collection
//
res = en.MoveNext();
res = en.MoveNext();
if (res)
{
Assert.False(true, string.Format("Error, MoveNext returned true"));
}
// Reset() and check 0th item
en.Reset();
if (!en.MoveNext())
{
Assert.False(true, string.Format("Error, MoveNext() returned false"));
}
if (String.Compare(en.Current, sc[0]) != 0)
{
Assert.False(true, string.Format("Error, Current returned wrong value"));
}
//
// Attempt to get Current should result in exception
//
en.Reset();
Assert.Throws<InvalidOperationException>(() => { curr = en.Current; });
//
// [] Modify collection when enumerating
//
if (sc.Count < 1)
sc.AddRange(values);
//
// modify the collection and call Reset() before first MoveNext()
//
en = sc.GetEnumerator();
sc.RemoveAt(0);
Assert.Throws<InvalidOperationException>(() => { en.Reset(); });
//
// Enumerate to the middle item of the collection, modify the collection,
// and call Reset()
//
// create valid enumerator
//
en = sc.GetEnumerator();
for (int i = 0; i < sc.Count / 2; i++)
{
res = en.MoveNext();
}
curr = en.Current;
sc.RemoveAt(0);
// will return previous current
if (String.Compare(curr, en.Current) != 0)
{
Assert.False(true, string.Format("Error, current returned {0} instead of {1}", en.Current, curr));
}
// exception expected
Assert.Throws<InvalidOperationException>(() => { en.Reset(); });
//
// Enumerate to the last item of the collection, modify the collection,
// and call Reset()
//
// create valid enumerator
//
en = sc.GetEnumerator();
for (int i = 0; i < sc.Count; i++)
{
res = en.MoveNext();
}
sc.RemoveAt(0);
// exception expected
Assert.Throws<InvalidOperationException>(() => { en.Reset(); });
//
// [] Modify collection after enumerating beyond the end
//
if (sc.Count < 1)
sc.AddRange(values);
en = sc.GetEnumerator();
for (int i = 0; i < sc.Count; i++)
{
res = en.MoveNext();
}
res = en.MoveNext(); // should be beyond the end
if (res)
{
Assert.False(true, string.Format("Error, MoveNext returned true after moving beyond the end"));
}
cnt = sc.Count;
sc.RemoveAt(0);
if (sc.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, didn't remove 0-item"));
}
// exception expected
Assert.Throws<InvalidOperationException>(() => { en.Reset(); });
}
}
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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 C5;
using NUnit.Framework;
namespace C5UnitTests.heaps
{
using CollectionOfInt = IntervalHeap<int>;
[TestFixture]
public class GenericTesters
{
[Test]
public void TestEvents()
{
Func<CollectionOfInt> factory = delegate() { return new CollectionOfInt(TenEqualityComparer.Default); };
new C5UnitTests.Templates.Events.PriorityQueueTester<CollectionOfInt>().Test(factory);
}
[Test]
public void Extensible()
{
C5UnitTests.Templates.Extensible.Clone.Tester<CollectionOfInt>();
C5UnitTests.Templates.Extensible.Serialization.Tester<CollectionOfInt>();
}
}
[TestFixture]
public class Events
{
IPriorityQueue<int> queue;
ArrayList<KeyValuePair<Acts, int>> events;
[SetUp]
public void Init()
{
queue = new IntervalHeap<int>();
events = new ArrayList<KeyValuePair<Acts, int>>();
}
[TearDown]
public void Dispose() { queue = null; events = null; }
[Test]
public void Listenable()
{
Assert.AreEqual(EventTypeEnum.Basic, queue.ListenableEvents);
}
enum Acts
{
Add, Remove, Changed
}
[Test]
public void Direct()
{
CollectionChangedHandler<int> cch;
ItemsAddedHandler<int> iah;
ItemsRemovedHandler<int> irh;
Assert.AreEqual(EventTypeEnum.None, queue.ActiveEvents);
queue.CollectionChanged += (cch = new CollectionChangedHandler<int>(queue_CollectionChanged));
Assert.AreEqual(EventTypeEnum.Changed, queue.ActiveEvents);
queue.ItemsAdded += (iah = new ItemsAddedHandler<int>(queue_ItemAdded));
Assert.AreEqual(EventTypeEnum.Changed | EventTypeEnum.Added, queue.ActiveEvents);
queue.ItemsRemoved += (irh = new ItemsRemovedHandler<int>(queue_ItemRemoved));
Assert.AreEqual(EventTypeEnum.Changed | EventTypeEnum.Added | EventTypeEnum.Removed, queue.ActiveEvents);
queue.Add(34);
queue.Add(56);
queue.AddAll(new int[] { });
queue.Add(34);
queue.Add(12);
queue.DeleteMax();
queue.DeleteMin();
queue.AddAll(new int[] { 4, 5, 6, 2 });
Assert.AreEqual(17, events.Count);
int[] vals = { 34, 0, 56, 0, 34, 0, 12, 0, 56, 0, 12, 0, 4, 5, 6, 2, 0 };
Acts[] acts = { Acts.Add, Acts.Changed, Acts.Add, Acts.Changed, Acts.Add, Acts.Changed, Acts.Add, Acts.Changed,
Acts.Remove, Acts.Changed, Acts.Remove, Acts.Changed, Acts.Add, Acts.Add, Acts.Add, Acts.Add, Acts.Changed };
for (int i = 0; i < vals.Length; i++)
{
//Console.WriteLine("{0}", events[cell]);
Assert.AreEqual(acts[i], events[i].Key, "Action " + i);
Assert.AreEqual(vals[i], events[i].Value, "Value " + i);
}
queue.CollectionChanged -= cch;
Assert.AreEqual(EventTypeEnum.Added | EventTypeEnum.Removed, queue.ActiveEvents);
queue.ItemsAdded -= iah;
Assert.AreEqual(EventTypeEnum.Removed, queue.ActiveEvents);
queue.ItemsRemoved -= irh;
Assert.AreEqual(EventTypeEnum.None, queue.ActiveEvents);
}
[Test]
public void Guarded()
{
ICollectionValue<int> guarded = new GuardedCollectionValue<int>(queue);
guarded.CollectionChanged += new CollectionChangedHandler<int>(queue_CollectionChanged);
guarded.ItemsAdded += new ItemsAddedHandler<int>(queue_ItemAdded);
guarded.ItemsRemoved += new ItemsRemovedHandler<int>(queue_ItemRemoved);
queue.Add(34);
queue.Add(56);
queue.Add(34);
queue.Add(12);
queue.DeleteMax();
queue.DeleteMin();
queue.AddAll(new int[] { 4, 5, 6, 2 });
Assert.AreEqual(17, events.Count);
int[] vals = { 34, 0, 56, 0, 34, 0, 12, 0, 56, 0, 12, 0, 4, 5, 6, 2, 0 };
Acts[] acts = { Acts.Add, Acts.Changed, Acts.Add, Acts.Changed, Acts.Add, Acts.Changed, Acts.Add, Acts.Changed,
Acts.Remove, Acts.Changed, Acts.Remove, Acts.Changed, Acts.Add, Acts.Add, Acts.Add, Acts.Add, Acts.Changed };
for (int i = 0; i < vals.Length; i++)
{
//Console.WriteLine("{0}", events[cell]);
Assert.AreEqual(vals[i], events[i].Value);
Assert.AreEqual(acts[i], events[i].Key);
}
}
void queue_CollectionChanged(object sender)
{
events.Add(new KeyValuePair<Acts, int>(Acts.Changed, 0));
}
void queue_ItemAdded(object sender, ItemCountEventArgs<int> e)
{
events.Add(new KeyValuePair<Acts, int>(Acts.Add, e.Item));
}
void queue_ItemRemoved(object sender, ItemCountEventArgs<int> e)
{
events.Add(new KeyValuePair<Acts, int>(Acts.Remove, e.Item));
}
}
[TestFixture]
public class Formatting
{
IntervalHeap<int> coll;
IFormatProvider rad16;
[SetUp]
public void Init() { coll = new IntervalHeap<int>(); rad16 = new RadixFormatProvider(16); }
[TearDown]
public void Dispose() { coll = null; rad16 = null; }
[Test]
public void Format()
{
Assert.AreEqual("{ }", coll.ToString());
coll.AddAll(new int[] { -4, 28, 129, 65530 });
Assert.AreEqual("{ -4, 65530, 28, 129 }", coll.ToString());
Assert.AreEqual("{ -4, FFFA, 1C, 81 }", coll.ToString(null, rad16));
Assert.AreEqual("{ -4, 65530, ... }", coll.ToString("L14", null));
Assert.AreEqual("{ -4, FFFA, ... }", coll.ToString("L14", rad16));
}
}
[TestFixture]
public class IntervalHeapTests
{
IPriorityQueue<int> queue;
[SetUp]
public void Init() { queue = new IntervalHeap<int>(); }
[TearDown]
public void Dispose() { queue = null; }
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void NullEqualityComparerinConstructor1()
{
new IntervalHeap<int>(null);
}
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void NullEqualityComparerinConstructor2()
{
new IntervalHeap<int>(5, null);
}
[Test]
public void Handles()
{
IPriorityQueueHandle<int>[] handles = new IPriorityQueueHandle<int>[10];
queue.Add(ref handles[0], 7);
Assert.IsTrue(queue.Check());
queue.Add(ref handles[1], 72);
Assert.IsTrue(queue.Check());
queue.Add(ref handles[2], 27);
Assert.IsTrue(queue.Check());
queue.Add(ref handles[3], 17);
Assert.IsTrue(queue.Check());
queue.Add(ref handles[4], 70);
Assert.IsTrue(queue.Check());
queue.Add(ref handles[5], 1);
Assert.IsTrue(queue.Check());
queue.Add(ref handles[6], 2);
Assert.IsTrue(queue.Check());
queue.Add(ref handles[7], 7);
Assert.IsTrue(queue.Check());
queue.Add(ref handles[8], 8);
Assert.IsTrue(queue.Check());
queue.Add(ref handles[9], 9);
Assert.IsTrue(queue.Check());
queue.Delete(handles[2]);
Assert.IsTrue(queue.Check());
queue.Delete(handles[0]);
Assert.IsTrue(queue.Check());
queue.Delete(handles[8]);
Assert.IsTrue(queue.Check());
queue.Delete(handles[4]);
Assert.IsTrue(queue.Check());
queue.Delete(handles[6]);
Assert.IsTrue(queue.Check());
Assert.AreEqual(5, queue.Count);
}
[Test]
public void Replace()
{
IPriorityQueueHandle<int> handle = null;
queue.Add(6);
queue.Add(10);
queue.Add(ref handle, 7);
queue.Add(21);
Assert.AreEqual(7, queue.Replace(handle, 12));
Assert.AreEqual(21, queue.FindMax());
Assert.AreEqual(12, queue.Replace(handle, 34));
Assert.AreEqual(34, queue.FindMax());
Assert.IsTrue(queue.Check());
//replace max
Assert.AreEqual(34, queue.Replace(handle, 60));
Assert.AreEqual(60, queue.FindMax());
Assert.AreEqual(60, queue.Replace(handle, queue[handle] + 80));
Assert.AreEqual(140, queue.FindMax());
Assert.IsTrue(queue.Check());
}
[Test]
public void Replace2()
{
IPriorityQueueHandle<int> handle = null;
queue.Add(6);
queue.Add(10);
queue.Add(ref handle, 7);
//Replace last item in queue with something large
Assert.AreEqual(7, queue.Replace(handle, 12));
Assert.IsTrue(queue.Check());
}
/// <summary>
/// bug20070504.txt by Viet Yen Nguyen
/// </summary>
[Test]
public void Replace3()
{
IPriorityQueueHandle<int> handle = null;
queue.Add(ref handle, 10);
Assert.AreEqual(10, queue.Replace(handle, 12));
Assert.IsTrue(queue.Check());
}
/// <summary>
/// bug20080222.txt by Thomas Dufour
/// </summary>
[Test]
public void Replace4a()
{
IPriorityQueueHandle<int> handle1 = null;
queue.Add(ref handle1, 4);
Assert.AreEqual(4, queue.FindMin());
queue.Add(3);
Assert.AreEqual(3, queue.FindMin());
Assert.AreEqual(4, queue.Replace(handle1, 2));
Assert.AreEqual(2, queue.FindMin());
}
[Test]
public void Replace4b()
{
IPriorityQueueHandle<int> handle1 = null;
queue.Add(ref handle1, 2);
Assert.AreEqual(2, queue.FindMax());
queue.Add(3);
Assert.AreEqual(3, queue.FindMax());
Assert.AreEqual(2, queue.Replace(handle1, 4));
Assert.AreEqual(4, queue.FindMax());
}
[Test]
public void Replace5a()
{
for (int size = 0; size < 130; size++)
{
IPriorityQueue<double> q = new IntervalHeap<double>();
IPriorityQueueHandle<double> handle1 = null;
q.Add(ref handle1, 3.0);
Assert.AreEqual(3.0, q.FindMin());
for (int i = 1; i < size; i++)
q.Add(i + 3.0);
Assert.AreEqual(3.0, q.FindMin());
for (int min = 2; min >= -10; min--)
{
Assert.AreEqual(min + 1.0, q.Replace(handle1, min));
Assert.AreEqual(min, q.FindMin());
}
Assert.AreEqual(-10.0, q.DeleteMin());
for (int i = 1; i < size; i++)
Assert.AreEqual(i + 3.0, q.DeleteMin());
Assert.IsTrue(q.IsEmpty);
}
}
[Test]
public void Replace5b()
{
for (int size = 0; size < 130; size++)
{
IPriorityQueue<double> q = new IntervalHeap<double>();
IPriorityQueueHandle<double> handle1 = null;
q.Add(ref handle1, -3.0);
Assert.AreEqual(-3.0, q.FindMax());
for (int i = 1; i < size; i++)
q.Add(-i - 3.0);
Assert.AreEqual(-3.0, q.FindMax());
for (int max = -2; max <= 10; max++)
{
Assert.AreEqual(max - 1.0, q.Replace(handle1, max));
Assert.AreEqual(max, q.FindMax());
}
Assert.AreEqual(10.0, q.DeleteMax());
for (int i = 1; i < size; i++)
Assert.AreEqual(-i - 3.0, q.DeleteMax());
Assert.IsTrue(q.IsEmpty);
}
}
[Test]
public void Delete1a()
{
IPriorityQueueHandle<int> handle1 = null;
queue.Add(ref handle1, 4);
Assert.AreEqual(4, queue.FindMin());
queue.Add(3);
Assert.AreEqual(3, queue.FindMin());
queue.Add(2);
Assert.AreEqual(4, queue.Delete(handle1));
Assert.AreEqual(2, queue.FindMin());
Assert.AreEqual(3, queue.FindMax());
}
[Test]
public void Delete1b()
{
IPriorityQueueHandle<int> handle1 = null;
queue.Add(ref handle1, 2);
Assert.AreEqual(2, queue.FindMax());
queue.Add(3);
Assert.AreEqual(3, queue.FindMax());
queue.Add(4);
Assert.AreEqual(2, queue.Delete(handle1));
Assert.AreEqual(3, queue.FindMin());
Assert.AreEqual(4, queue.FindMax());
}
[Test]
public void ReuseHandle()
{
IPriorityQueueHandle<int> handle = null;
queue.Add(ref handle, 7);
queue.Delete(handle);
queue.Add(ref handle, 8);
}
[Test]
[ExpectedException(typeof(InvalidPriorityQueueHandleException))]
public void ErrorAddValidHandle()
{
IPriorityQueueHandle<int> handle = null;
queue.Add(ref handle, 7);
queue.Add(ref handle, 8);
}
[Test]
[ExpectedException(typeof(InvalidPriorityQueueHandleException))]
public void ErrorDeleteInvalidHandle()
{
IPriorityQueueHandle<int> handle = null;
queue.Add(ref handle, 7);
queue.Delete(handle);
queue.Delete(handle);
}
[Test]
[ExpectedException(typeof(InvalidPriorityQueueHandleException))]
public void ErrorReplaceInvalidHandle()
{
IPriorityQueueHandle<int> handle = null;
queue.Add(ref handle, 7);
queue.Delete(handle);
queue.Replace(handle, 13);
}
[Test]
public void Simple()
{
Assert.IsTrue(queue.AllowsDuplicates);
Assert.AreEqual(0, queue.Count);
queue.Add(8); queue.Add(18); queue.Add(8); queue.Add(3);
Assert.AreEqual(4, queue.Count);
Assert.AreEqual(18, queue.DeleteMax());
Assert.AreEqual(3, queue.Count);
Assert.AreEqual(3, queue.DeleteMin());
Assert.AreEqual(2, queue.Count);
Assert.AreEqual(8, queue.FindMax());
Assert.AreEqual(8, queue.DeleteMax());
Assert.AreEqual(8, queue.FindMax());
queue.Add(15);
Assert.AreEqual(15, queue.FindMax());
Assert.AreEqual(8, queue.FindMin());
Assert.IsTrue(queue.Comparer.Compare(2, 3) < 0);
Assert.IsTrue(queue.Comparer.Compare(4, 3) > 0);
Assert.IsTrue(queue.Comparer.Compare(3, 3) == 0);
}
[Test]
public void Enumerate()
{
int[] a = new int[4];
int siz = 0;
foreach (int i in queue)
siz++;
Assert.AreEqual(0, siz);
queue.Add(8); queue.Add(18); queue.Add(8); queue.Add(3);
foreach (int i in queue)
a[siz++] = i;
Assert.AreEqual(4, siz);
Array.Sort(a, 0, siz);
Assert.AreEqual(3, a[0]);
Assert.AreEqual(8, a[1]);
Assert.AreEqual(8, a[2]);
Assert.AreEqual(18, a[3]);
siz = 0;
Assert.AreEqual(18, queue.DeleteMax());
foreach (int i in queue)
a[siz++] = i;
Assert.AreEqual(3, siz);
Array.Sort(a, 0, siz);
Assert.AreEqual(3, a[0]);
Assert.AreEqual(8, a[1]);
Assert.AreEqual(8, a[2]);
siz = 0;
Assert.AreEqual(8, queue.DeleteMax());
foreach (int i in queue)
a[siz++] = i;
Assert.AreEqual(2, siz);
Array.Sort(a, 0, siz);
Assert.AreEqual(3, a[0]);
Assert.AreEqual(8, a[1]);
siz = 0;
Assert.AreEqual(8, queue.DeleteMax());
foreach (int i in queue)
a[siz++] = i;
Assert.AreEqual(1, siz);
Assert.AreEqual(3, a[0]);
}
[Test]
public void Random()
{
int length = 1000;
int[] a = new int[length];
Random ran = new Random(6754);
for (int i = 0; i < length; i++)
queue.Add(a[i] = ran.Next());
Assert.IsTrue(queue.Check());
Array.Sort(a);
for (int i = 0; i < length / 2; i++)
{
Assert.AreEqual(a[length - i - 1], queue.DeleteMax());
Assert.IsTrue(queue.Check());
Assert.AreEqual(a[i], queue.DeleteMin());
Assert.IsTrue(queue.Check());
}
Assert.IsTrue(queue.IsEmpty);
}
[Test]
public void RandomWithHandles()
{
int length = 1000;
int[] a = new int[length];
Random ran = new Random(6754);
for (int i = 0; i < length; i++)
{
IPriorityQueueHandle<int> h = null;
queue.Add(ref h, a[i] = ran.Next());
Assert.IsTrue(queue.Check());
}
Assert.IsTrue(queue.Check());
Array.Sort(a);
for (int i = 0; i < length / 2; i++)
{
Assert.AreEqual(a[length - i - 1], queue.DeleteMax());
Assert.IsTrue(queue.Check());
Assert.AreEqual(a[i], queue.DeleteMin());
Assert.IsTrue(queue.Check());
}
Assert.IsTrue(queue.IsEmpty);
}
[Test]
public void RandomWithDeleteHandles()
{
Random ran = new Random(6754);
int length = 1000;
int[] a = new int[length];
ArrayList<int> shuffle = new ArrayList<int>(length);
IPriorityQueueHandle<int>[] h = new IPriorityQueueHandle<int>[length];
for (int i = 0; i < length; i++)
{
shuffle.Add(i);
queue.Add(ref h[i], a[i] = ran.Next());
Assert.IsTrue(queue.Check());
}
Assert.IsTrue(queue.Check());
shuffle.Shuffle(ran);
for (int i = 0; i < length; i++)
{
int j = shuffle[i];
Assert.AreEqual(a[j], queue.Delete(h[j]));
Assert.IsTrue(queue.Check());
}
Assert.IsTrue(queue.IsEmpty);
}
[Test]
public void RandomIndexing()
{
Random ran = new Random(6754);
int length = 1000;
int[] a = new int[length];
int[] b = new int[length];
ArrayList<int> shuffle = new ArrayList<int>(length);
IPriorityQueueHandle<int>[] h = new IPriorityQueueHandle<int>[length];
for (int i = 0; i < length; i++)
{
shuffle.Add(i);
queue.Add(ref h[i], a[i] = ran.Next());
b[i] = ran.Next();
Assert.IsTrue(queue.Check());
}
Assert.IsTrue(queue.Check());
shuffle.Shuffle(ran);
for (int i = 0; i < length; i++)
{
int j = shuffle[i];
Assert.AreEqual(a[j], queue[h[j]]);
queue[h[j]] = b[j];
Assert.AreEqual(b[j], queue[h[j]]);
Assert.IsTrue(queue.Check());
}
}
[Test]
public void RandomDuplicates()
{
int length = 1000;
int s;
int[] a = new int[length];
Random ran = new Random(6754);
for (int i = 0; i < length; i++)
queue.Add(a[i] = ran.Next(3, 13));
Assert.IsTrue(queue.Check());
Array.Sort(a);
for (int i = 0; i < length / 2; i++)
{
Assert.AreEqual(a[i], queue.DeleteMin());
Assert.IsTrue(queue.Check());
Assert.AreEqual(a[length - i - 1], s = queue.DeleteMax());
Assert.IsTrue(queue.Check());
}
Assert.IsTrue(queue.IsEmpty);
}
[Test]
public void AddAll()
{
int length = 1000;
int[] a = new int[length];
Random ran = new Random(6754);
LinkedList<int> lst = new LinkedList<int>();
for (int i = 0; i < length; i++)
lst.Add(a[i] = ran.Next());
queue.AddAll(lst);
Assert.IsTrue(queue.Check());
Array.Sort(a);
for (int i = 0; i < length / 2; i++)
{
Assert.AreEqual(a[length - i - 1], queue.DeleteMax());
Assert.IsTrue(queue.Check());
Assert.AreEqual(a[i], queue.DeleteMin());
Assert.IsTrue(queue.Check());
}
Assert.IsTrue(queue.IsEmpty);
}
}
}
| |
// 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 OrSByte()
{
var test = new SimpleBinaryOpTest__OrSByte();
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 SimpleBinaryOpTest__OrSByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = 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.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.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<SByte> _fld1;
public Vector128<SByte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__OrSByte testClass)
{
var result = Sse2.Or(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__OrSByte testClass)
{
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = Sse2.Or(
Sse2.LoadVector128((SByte*)(pFld1)),
Sse2.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector128<SByte> _clsVar1;
private static Vector128<SByte> _clsVar2;
private Vector128<SByte> _fld1;
private Vector128<SByte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__OrSByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
}
public SimpleBinaryOpTest__OrSByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Or(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Or(
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.Or(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<SByte>* pClsVar1 = &_clsVar1)
fixed (Vector128<SByte>* pClsVar2 = &_clsVar2)
{
var result = Sse2.Or(
Sse2.LoadVector128((SByte*)(pClsVar1)),
Sse2.LoadVector128((SByte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = Sse2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__OrSByte();
var result = Sse2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__OrSByte();
fixed (Vector128<SByte>* pFld1 = &test._fld1)
fixed (Vector128<SByte>* pFld2 = &test._fld2)
{
var result = Sse2.Or(
Sse2.LoadVector128((SByte*)(pFld1)),
Sse2.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = Sse2.Or(
Sse2.LoadVector128((SByte*)(pFld1)),
Sse2.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.Or(
Sse2.LoadVector128((SByte*)(&test._fld1)),
Sse2.LoadVector128((SByte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _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<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((sbyte)(left[0] | right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((sbyte)(left[i] | right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Or)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
// Federico Di Gregorio <fog@initd.org>
//
// Copyright (C) 2008 Novell (http://www.novell.com)
// Copyright (C) 2009 Federico Di Gregorio.
//
// 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.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
#if LINQ
using System.Linq;
#endif
#if TEST
using NDesk.Options;
#endif
#if NDESK_OPTIONS
namespace NDesk.Options
#else
namespace Mono.Options
#endif
{
static class StringCoda {
public static IEnumerable<string> WrappedLines (string self, params int[] widths)
{
IEnumerable<int> w = widths;
return WrappedLines (self, w);
}
public static IEnumerable<string> WrappedLines (string self, IEnumerable<int> widths)
{
if (widths == null)
throw new ArgumentNullException ("widths");
return CreateWrappedLinesIterator (self, widths);
}
private static IEnumerable<string> CreateWrappedLinesIterator (string self, IEnumerable<int> widths)
{
if (string.IsNullOrEmpty (self)) {
yield return string.Empty;
yield break;
}
using (IEnumerator<int> ewidths = widths.GetEnumerator ()) {
bool? hw = null;
int width = GetNextWidth (ewidths, int.MaxValue, ref hw);
int start = 0, end;
do {
end = GetLineEnd (start, width, self);
char c = self [end-1];
if (char.IsWhiteSpace (c))
--end;
bool needContinuation = end != self.Length && !IsEolChar (c);
string continuation = "";
if (needContinuation) {
--end;
continuation = "-";
}
string line = self.Substring (start, end - start) + continuation;
yield return line;
start = end;
if (char.IsWhiteSpace (c))
++start;
width = GetNextWidth (ewidths, width, ref hw);
} while (start < self.Length);
}
}
private static int GetNextWidth (IEnumerator<int> ewidths, int curWidth, ref bool? eValid)
{
if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) {
curWidth = (eValid = ewidths.MoveNext ()).Value ? ewidths.Current : curWidth;
// '.' is any character, - is for a continuation
const string minWidth = ".-";
if (curWidth < minWidth.Length)
throw new ArgumentOutOfRangeException ("widths",
string.Format ("Element must be >= {0}, was {1}.", minWidth.Length, curWidth));
return curWidth;
}
// no more elements, use the last element.
return curWidth;
}
private static bool IsEolChar (char c)
{
return !char.IsLetterOrDigit (c);
}
private static int GetLineEnd (int start, int length, string description)
{
int end = System.Math.Min (start + length, description.Length);
int sep = -1;
for (int i = start; i < end; ++i) {
if (description [i] == '\n')
return i+1;
if (IsEolChar (description [i]))
sep = i+1;
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
public class OptionValueCollection : IList, IList<string> {
List<string> values = new List<string> ();
OptionContext c;
internal OptionValueCollection (OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
#endregion
#region ICollection<T>
public void Add (string item) {values.Add (item);}
public void Clear () {values.Clear ();}
public bool Contains (string item) {return values.Contains (item);}
public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
public bool Remove (string item) {return values.Remove (item);}
public int Count {get {return values.Count;}}
public bool IsReadOnly {get {return false;}}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IList
int IList.Add (object value) {return (values as IList).Add (value);}
bool IList.Contains (object value) {return (values as IList).Contains (value);}
int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
void IList.Remove (object value) {(values as IList).Remove (value);}
void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
bool IList.IsFixedSize {get {return false;}}
object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
#endregion
#region IList<T>
public int IndexOf (string item) {return values.IndexOf (item);}
public void Insert (int index, string item) {values.Insert (index, item);}
public void RemoveAt (int index) {values.RemoveAt (index);}
private void AssertValid (int index)
{
if (c.Option == null)
throw new InvalidOperationException ("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException ("index");
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException (string.Format (
c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this [int index] {
get {
AssertValid (index);
return index >= values.Count ? null : values [index];
}
set {
values [index] = value;
}
}
#endregion
public List<string> ToList ()
{
return new List<string> (values);
}
public string[] ToArray ()
{
return values.ToArray ();
}
public override string ToString ()
{
return string.Join (", ", values.ToArray ());
}
}
public class OptionContext {
private Option option;
private string name;
private int index;
private OptionSet set;
private OptionValueCollection c;
public OptionContext (OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection (this);
}
public Option Option {
get {return option;}
set {option = value;}
}
public string OptionName {
get {return name;}
set {name = value;}
}
public int OptionIndex {
get {return index;}
set {index = value;}
}
public OptionSet OptionSet {
get {return set;}
}
public OptionValueCollection OptionValues {
get {return c;}
}
}
public enum OptionValueType {
None,
Optional,
Required,
}
public abstract class Option {
string prototype, description;
string[] names;
OptionValueType type;
int count;
string[] separators;
protected Option (string prototype, string description)
: this (prototype, description, 1)
{
}
protected Option (string prototype, string description, int maxValueCount)
{
if (prototype == null)
throw new ArgumentNullException ("prototype");
if (prototype.Length == 0)
throw new ArgumentException ("Cannot be the empty string.", "prototype");
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException ("maxValueCount");
this.prototype = prototype;
this.description = description;
this.count = maxValueCount;
this.names = (this is OptionSet.Category)
// append GetHashCode() so that "duplicate" categories have distinct
// names, e.g. adding multiple "" categories should be valid.
? new[]{prototype + this.GetHashCode ()}
: prototype.Split ('|');
if (this is OptionSet.Category)
return;
this.type = ParsePrototype ();
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException (
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException (
string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
if (Array.IndexOf (names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException (
"The default option handler '<>' cannot require values.",
"prototype");
}
public string Prototype {get {return prototype;}}
public string Description {get {return description;}}
public OptionValueType OptionValueType {get {return type;}}
public int MaxValueCount {get {return count;}}
public string[] GetNames ()
{
return (string[]) names.Clone ();
}
public string[] GetValueSeparators ()
{
if (separators == null)
return new string [0];
return (string[]) separators.Clone ();
}
protected static T Parse<T> (string value, OptionContext c)
{
Type tt = typeof (T);
bool nullable = tt.IsValueType && tt.IsGenericType &&
!tt.IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition () == typeof (Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
TypeConverter conv = TypeDescriptor.GetConverter (targetType);
T t = default (T);
try {
if (value != null)
t = (T) conv.ConvertFromString (value);
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names {get {return names;}}
internal string[] ValueSeparators {get {return separators;}}
static readonly char[] NameTerminator = new char[]{'=', ':'};
private OptionValueType ParsePrototype ()
{
char type = '\0';
List<string> seps = new List<string> ();
for (int i = 0; i < names.Length; ++i) {
string name = names [i];
if (name.Length == 0)
throw new ArgumentException ("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny (NameTerminator);
if (end == -1)
continue;
names [i] = name.Substring (0, end);
if (type == '\0' || type == name [end])
type = name [end];
else
throw new ArgumentException (
string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
"prototype");
AddSeparators (name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException (
string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1) {
if (seps.Count == 0)
this.separators = new string[]{":", "="};
else if (seps.Count == 1 && seps [0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray ();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators (string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end+1; i < name.Length; ++i) {
switch (name [i]) {
case '{':
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i+1;
break;
case '}':
if (start == -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add (name.Substring (start, i-start));
start = -1;
break;
default:
if (start == -1)
seps.Add (name [i].ToString ());
break;
}
}
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke (OptionContext c)
{
OnParseComplete (c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear ();
}
protected abstract void OnParseComplete (OptionContext c);
public override string ToString ()
{
return Prototype;
}
}
public abstract class ArgumentSource {
protected ArgumentSource ()
{
}
public abstract string[] GetNames ();
public abstract string Description { get; }
public abstract bool GetArguments (string value, out IEnumerable<string> replacement);
public static IEnumerable<string> GetArgumentsFromFile (string file)
{
return GetArguments (File.OpenText (file), true);
}
public static IEnumerable<string> GetArguments (TextReader reader)
{
return GetArguments (reader, false);
}
// Cribbed from mcs/driver.cs:LoadArgs(string)
static IEnumerable<string> GetArguments (TextReader reader, bool close)
{
try {
StringBuilder arg = new StringBuilder ();
string line;
while ((line = reader.ReadLine ()) != null) {
int t = line.Length;
for (int i = 0; i < t; i++) {
char c = line [i];
if (c == '"' || c == '\'') {
char end = c;
for (i++; i < t; i++){
c = line [i];
if (c == end)
break;
arg.Append (c);
}
} else if (c == ' ') {
if (arg.Length > 0) {
yield return arg.ToString ();
arg.Length = 0;
}
} else if (c == '#') {
break;
} else
arg.Append (c);
}
if (arg.Length > 0) {
yield return arg.ToString ();
arg.Length = 0;
}
}
}
finally {
if (close)
reader.Close ();
}
}
}
public class ResponseFileSource : ArgumentSource {
public override string[] GetNames ()
{
return new string[]{"@file"};
}
public override string Description {
get {return "Read response file for more options.";}
}
public override bool GetArguments (string value, out IEnumerable<string> replacement)
{
if (string.IsNullOrEmpty (value) || !value.StartsWith ("@")) {
replacement = null;
return false;
}
replacement = ArgumentSource.GetArgumentsFromFile (value.Substring (1));
return true;
}
}
[Serializable]
public class OptionException : Exception {
private string option;
public OptionException ()
{
}
public OptionException (string message, string optionName)
: base (message)
{
this.option = optionName;
}
public OptionException (string message, string optionName, Exception innerException)
: base (message, innerException)
{
this.option = optionName;
}
protected OptionException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
this.option = info.GetString ("OptionName");
}
public string OptionName {
get {return this.option;}
}
[SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
base.GetObjectData (info, context);
info.AddValue ("OptionName", option);
}
}
public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option>
{
public OptionSet ()
: this (delegate (string f) {return f;})
{
}
public OptionSet (Converter<string, string> localizer)
{
this.localizer = localizer;
this.roSources = new ReadOnlyCollection<ArgumentSource>(sources);
}
Converter<string, string> localizer;
public Converter<string, string> MessageLocalizer {
get {return localizer;}
}
List<ArgumentSource> sources = new List<ArgumentSource> ();
ReadOnlyCollection<ArgumentSource> roSources;
public ReadOnlyCollection<ArgumentSource> ArgumentSources {
get {return roSources;}
}
protected override string GetKeyForItem (Option item)
{
if (item == null)
throw new ArgumentNullException ("option");
if (item.Names != null && item.Names.Length > 0)
return item.Names [0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException ("Option has no names!");
}
[Obsolete ("Use KeyedCollection.this[string]")]
protected Option GetOptionForName (string option)
{
if (option == null)
throw new ArgumentNullException ("option");
try {
return base [option];
}
catch (KeyNotFoundException) {
return null;
}
}
protected override void InsertItem (int index, Option item)
{
base.InsertItem (index, item);
AddImpl (item);
}
protected override void RemoveItem (int index)
{
Option p = Items [index];
base.RemoveItem (index);
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i) {
Dictionary.Remove (p.Names [i]);
}
}
protected override void SetItem (int index, Option item)
{
base.SetItem (index, item);
AddImpl (item);
}
private void AddImpl (Option option)
{
if (option == null)
throw new ArgumentNullException ("option");
List<string> added = new List<string> (option.Names.Length);
try {
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i) {
Dictionary.Add (option.Names [i], option);
added.Add (option.Names [i]);
}
}
catch (Exception) {
foreach (string name in added)
Dictionary.Remove (name);
throw;
}
}
public OptionSet Add (string header)
{
if (header == null)
throw new ArgumentNullException ("header");
Add (new Category (header));
return this;
}
internal sealed class Category : Option {
// Prototype starts with '=' because this is an invalid prototype
// (see Option.ParsePrototype(), and thus it'll prevent Category
// instances from being accidentally used as normal options.
public Category (string description)
: base ("=:Category:= " + description, description)
{
}
protected override void OnParseComplete (OptionContext c)
{
throw new NotSupportedException ("Category.OnParseComplete should not be invoked.");
}
}
public new OptionSet Add (Option option)
{
base.Add (option);
return this;
}
sealed class ActionOption : Option {
Action<OptionValueCollection> action;
public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
: base (prototype, description, count)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (c.OptionValues);
}
}
public OptionSet Add (string prototype, Action<string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 1,
delegate (OptionValueCollection v) { action (v [0]); });
base.Add (p);
return this;
}
public OptionSet Add (string prototype, OptionAction<string, string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 2,
delegate (OptionValueCollection v) {action (v [0], v [1]);});
base.Add (p);
return this;
}
sealed class ActionOption<T> : Option {
Action<T> action;
public ActionOption (string prototype, string description, Action<T> action)
: base (prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (Parse<T> (c.OptionValues [0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option {
OptionAction<TKey, TValue> action;
public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
: base (prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (
Parse<TKey> (c.OptionValues [0], c),
Parse<TValue> (c.OptionValues [1], c));
}
}
public OptionSet Add<T> (string prototype, Action<T> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<T> (string prototype, string description, Action<T> action)
{
return Add (new ActionOption<T> (prototype, description, action));
}
public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add (new ActionOption<TKey, TValue> (prototype, description, action));
}
public OptionSet Add (ArgumentSource source)
{
if (source == null)
throw new ArgumentNullException ("source");
sources.Add (source);
return this;
}
protected virtual OptionContext CreateOptionContext ()
{
return new OptionContext (this);
}
public List<string> Parse (IEnumerable<string> arguments)
{
if (arguments == null)
throw new ArgumentNullException ("arguments");
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string> ();
Option def = Contains ("<>") ? this ["<>"] : null;
ArgumentEnumerator ae = new ArgumentEnumerator (arguments);
foreach (string argument in ae) {
++c.OptionIndex;
if (argument == "--") {
process = false;
continue;
}
if (!process) {
Unprocessed (unprocessed, def, c, argument);
continue;
}
if (AddSource (ae, argument))
continue;
if (!Parse (argument, c))
Unprocessed (unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke (c);
return unprocessed;
}
class ArgumentEnumerator : IEnumerable<string> {
List<IEnumerator<string>> sources = new List<IEnumerator<string>> ();
public ArgumentEnumerator (IEnumerable<string> arguments)
{
sources.Add (arguments.GetEnumerator ());
}
public void Add (IEnumerable<string> arguments)
{
sources.Add (arguments.GetEnumerator ());
}
public IEnumerator<string> GetEnumerator ()
{
do {
IEnumerator<string> c = sources [sources.Count-1];
if (c.MoveNext ())
yield return c.Current;
else {
c.Dispose ();
sources.RemoveAt (sources.Count-1);
}
} while (sources.Count > 0);
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
}
bool AddSource (ArgumentEnumerator ae, string argument)
{
foreach (ArgumentSource source in sources) {
IEnumerable<string> replacement;
if (!source.GetArguments (argument, out replacement))
continue;
ae.Add (replacement);
return true;
}
return false;
}
private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null) {
extra.Add (argument);
return false;
}
c.OptionValues.Add (argument);
c.Option = def;
c.Option.Invoke (c);
return false;
}
private readonly Regex ValueOption = new Regex (
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException ("argument");
flag = name = sep = value = null;
Match m = ValueOption.Match (argument);
if (!m.Success) {
return false;
}
flag = m.Groups ["flag"].Value;
name = m.Groups ["name"].Value;
if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
sep = m.Groups ["sep"].Value;
value = m.Groups ["value"].Value;
}
return true;
}
protected virtual bool Parse (string argument, OptionContext c)
{
if (c.Option != null) {
ParseValue (argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts (argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains (n)) {
p = this [n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType) {
case OptionValueType.None:
c.OptionValues.Add (n);
c.Option.Invoke (c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue (v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool (argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue (f, string.Concat (n + s + v), c))
return true;
return false;
}
private void ParseValue (string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split (c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None)
: new string[]{option}) {
c.OptionValues.Add (o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke (c);
else if (c.OptionValues.Count > c.Option.MaxValueCount) {
throw new OptionException (localizer (string.Format (
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool (string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
Contains ((rn = n.Substring (0, n.Length-1)))) {
p = this [rn];
string v = n [n.Length-1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add (v);
p.Invoke (c);
return true;
}
return false;
}
private bool ParseBundledValue (string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i) {
Option p;
string opt = f + n [i].ToString ();
string rn = n [i].ToString ();
if (!Contains (rn)) {
if (i == 0)
return false;
throw new OptionException (string.Format (localizer (
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this [rn];
switch (p.OptionValueType) {
case OptionValueType.None:
Invoke (c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required: {
string v = n.Substring (i+1);
c.Option = p;
c.OptionName = opt;
ParseValue (v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke (OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add (value);
option.Invoke (c);
}
private const int OptionWidth = 29;
private const int Description_FirstWidth = 80 - OptionWidth;
private const int Description_RemWidth = 80 - OptionWidth - 2;
public void WriteOptionDescriptions (TextWriter o)
{
foreach (Option p in this) {
int written = 0;
Category c = p as Category;
if (c != null) {
WriteDescription (o, p.Description, "", 80, 80);
continue;
}
if (!WriteOptionPrototype (o, p, ref written))
continue;
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
WriteDescription (o, p.Description, new string (' ', OptionWidth+2),
Description_FirstWidth, Description_RemWidth);
}
foreach (ArgumentSource s in sources) {
string[] names = s.GetNames ();
if (names == null || names.Length == 0)
continue;
int written = 0;
Write (o, ref written, " ");
Write (o, ref written, names [0]);
for (int i = 1; i < names.Length; ++i) {
Write (o, ref written, ", ");
Write (o, ref written, names [i]);
}
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
WriteDescription (o, s.Description, new string (' ', OptionWidth+2),
Description_FirstWidth, Description_RemWidth);
}
}
void WriteDescription (TextWriter o, string value, string prefix, int firstWidth, int remWidth)
{
bool indent = false;
foreach (string line in GetLines (localizer (GetDescription (value)), firstWidth, remWidth)) {
if (indent)
o.Write (prefix);
o.WriteLine (line);
indent = true;
}
}
bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex (names, 0);
if (i == names.Length)
return false;
if (names [i].Length == 1) {
Write (o, ref written, " -");
Write (o, ref written, names [0]);
}
else {
Write (o, ref written, " --");
Write (o, ref written, names [0]);
}
for ( i = GetNextOptionIndex (names, i+1);
i < names.Length; i = GetNextOptionIndex (names, i+1)) {
Write (o, ref written, ", ");
Write (o, ref written, names [i].Length == 1 ? "-" : "--");
Write (o, ref written, names [i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required) {
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("["));
}
Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators [0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c) {
Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("]"));
}
}
return true;
}
static int GetNextOptionIndex (string[] names, int i)
{
while (i < names.Length && names [i] == "<>") {
++i;
}
return i;
}
static void Write (TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write (s);
}
private static string GetArgumentName (int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[]{"{0:", "{"};
else
nameStart = new string[]{"{" + index + ":"};
for (int i = 0; i < nameStart.Length; ++i) {
int start, j = 0;
do {
start = description.IndexOf (nameStart [i], j);
} while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf ("}", start);
if (end == -1)
continue;
return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription (string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder (description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i) {
switch (description [i]) {
case '{':
if (i == start) {
sb.Append ('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0) {
if ((i+1) == description.Length || description [i+1] != '}')
throw new InvalidOperationException ("Invalid option description: " + description);
++i;
sb.Append ("}");
}
else {
sb.Append (description.Substring (start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append (description [i]);
break;
}
}
return sb.ToString ();
}
private static IEnumerable<string> GetLines (string description, int firstWidth, int remWidth)
{
return StringCoda.WrappedLines (description, firstWidth, remWidth);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
namespace MaterialDesignThemes.Wpf
{
public class SnackbarMessageQueue : ISnackbarMessageQueue, IDisposable
{
private readonly Dispatcher _dispatcher;
private readonly TimeSpan _messageDuration;
private readonly HashSet<Snackbar> _pairedSnackbars = new();
private readonly LinkedList<SnackbarMessageQueueItem> _snackbarMessages = new();
private readonly object _snackbarMessagesLock = new();
private readonly ManualResetEvent _disposedEvent = new(false);
private readonly ManualResetEvent _pausedEvent = new(false);
private readonly SemaphoreSlim _showMessageSemaphore = new(1, 1);
private int _pauseCounter;
private bool _isDisposed;
public IReadOnlyList<SnackbarMessageQueueItem> QueuedMessages
{
get
{
lock (_snackbarMessagesLock)
{
return _snackbarMessages.ToList();
}
}
}
/// <summary>
/// If set, the active snackbar will be closed.
/// </summary>
/// <remarks>
/// Available only while the snackbar is displayed.
/// Should be locked by <see cref="_snackbarMessagesLock"/>.
/// </remarks>
private ManualResetEvent? _closeSnackbarEvent;
/// <summary>
/// Gets the <see cref="System.Windows.Threading.Dispatcher"/> this <see cref="SnackbarMessageQueue"/> is associated with.
/// </summary>
internal Dispatcher Dispatcher => _dispatcher;
#region MouseNotOverManagedWaitHandle
private class MouseNotOverManagedWaitHandle : IDisposable
{
private readonly UIElement _uiElement;
private readonly ManualResetEvent _waitHandle;
private readonly ManualResetEvent _disposedWaitHandle = new ManualResetEvent(false);
private bool _isDisposed;
private readonly object _waitHandleGate = new object();
public MouseNotOverManagedWaitHandle(UIElement uiElement)
{
_uiElement = uiElement ?? throw new ArgumentNullException(nameof(uiElement));
_waitHandle = new ManualResetEvent(!uiElement.IsMouseOver);
uiElement.MouseEnter += UiElementOnMouseEnter;
uiElement.MouseLeave += UiElementOnMouseLeave;
}
public EventWaitHandle WaitHandle => _waitHandle;
private void UiElementOnMouseEnter(object sender, MouseEventArgs mouseEventArgs) => _waitHandle.Reset();
private async void UiElementOnMouseLeave(object sender, MouseEventArgs mouseEventArgs)
{
await Task.Run(() =>
{
try
{
_disposedWaitHandle.WaitOne(TimeSpan.FromSeconds(2));
}
catch (ObjectDisposedException)
{
/* we are we suppressing this?
* as we have switched out wait onto another thread, so we don't block the UI thread, the
* _cleanUp/Dispose() action might also happen, and the _disposedWaitHandle might get disposed
* just before we WaitOne. We won't add a lock in the _cleanUp because it might block for 2 seconds.
* We could use a Monitor.TryEnter in _cleanUp and run clean up after but oh my gosh it's just getting
* too complicated for this use case, so for the rare times this happens, we can swallow safely
*/
}
});
if (((UIElement)sender).IsMouseOver) return;
lock (_waitHandleGate)
{
if (!_isDisposed)
_waitHandle.Set();
}
}
public void Dispose()
{
if (_isDisposed)
return;
_uiElement.MouseEnter -= UiElementOnMouseEnter;
_uiElement.MouseLeave -= UiElementOnMouseLeave;
lock (_waitHandleGate)
{
_waitHandle.Dispose();
_isDisposed = true;
}
_disposedWaitHandle.Set();
_disposedWaitHandle.Dispose();
}
}
#endregion
public SnackbarMessageQueue()
: this(TimeSpan.FromSeconds(3))
{
}
public SnackbarMessageQueue(TimeSpan messageDuration)
: this(messageDuration, Dispatcher.FromThread(Thread.CurrentThread)
?? throw new InvalidOperationException("SnackbarMessageQueue must be created in a dispatcher thread"))
{ }
public SnackbarMessageQueue(TimeSpan messageDuration, Dispatcher dispatcher)
{
_messageDuration = messageDuration;
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
}
//oh if only I had Disposable.Create in this lib :) tempted to copy it in like dragablz,
//but this is an internal method so no one will know my dirty Action disposer...
internal Action Pair(Snackbar snackbar)
{
if (snackbar is null) throw new ArgumentNullException(nameof(snackbar));
_pairedSnackbars.Add(snackbar);
return () => _pairedSnackbars.Remove(snackbar);
}
internal Action Pause()
{
if (_isDisposed) return () => { };
if (Interlocked.Increment(ref _pauseCounter) == 1)
_pausedEvent.Set();
return () =>
{
if (Interlocked.Decrement(ref _pauseCounter) == 0)
_pausedEvent.Reset();
};
}
/// <summary>
/// Gets or sets a value that indicates whether this message queue displays messages without discarding duplicates.
/// False to show every message even if there are duplicates.
/// </summary>
public bool DiscardDuplicates { get; set; }
public void Enqueue(object content) => Enqueue(content, false);
public void Enqueue(object content, bool neverConsiderToBeDuplicate)
=> Enqueue(content, null, null, null, false, neverConsiderToBeDuplicate);
public void Enqueue(object content, object? actionContent, Action? actionHandler)
=> Enqueue(content, actionContent, actionHandler, false);
public void Enqueue(object content, object? actionContent, Action? actionHandler, bool promote)
=> Enqueue(content, actionContent, _ => actionHandler?.Invoke(), false, promote, false);
public void Enqueue<TArgument>(object content, object? actionContent, Action<TArgument?>? actionHandler,
TArgument? actionArgument)
=> Enqueue(content, actionContent, actionHandler, actionArgument, false, false);
public void Enqueue<TArgument>(object content, object? actionContent, Action<TArgument?>? actionHandler,
TArgument? actionArgument, bool promote) =>
Enqueue(content, actionContent, actionHandler, actionArgument, promote, false);
public void Enqueue<TArgument>(object content, object? actionContent, Action<TArgument?>? actionHandler,
TArgument? actionArgument, bool promote, bool neverConsiderToBeDuplicate, TimeSpan? durationOverride = null)
{
if (content is null) throw new ArgumentNullException(nameof(content));
if (actionContent is null ^ actionHandler is null)
{
throw new ArgumentNullException(actionContent != null ? nameof(actionContent) : nameof(actionHandler),
"All action arguments must be provided if any are provided.");
}
Action<object?>? handler = actionHandler != null
? new Action<object?>(argument => actionHandler((TArgument?)argument))
: null;
Enqueue(content, actionContent, handler, actionArgument, promote, neverConsiderToBeDuplicate, durationOverride);
}
public void Enqueue(object content, object? actionContent, Action<object?>? actionHandler,
object? actionArgument, bool promote, bool neverConsiderToBeDuplicate, TimeSpan? durationOverride = null)
{
if (content is null) throw new ArgumentNullException(nameof(content));
if (actionContent is null ^ actionHandler is null)
{
throw new ArgumentNullException(actionContent != null ? nameof(actionContent) : nameof(actionHandler),
"All action arguments must be provided if any are provided.");
}
var snackbarMessageQueueItem = new SnackbarMessageQueueItem(content, durationOverride ?? _messageDuration,
actionContent, actionHandler, actionArgument, promote, neverConsiderToBeDuplicate);
InsertItem(snackbarMessageQueueItem);
}
private void InsertItem(SnackbarMessageQueueItem item)
{
lock (_snackbarMessagesLock)
{
var added = false;
var node = _snackbarMessages.First;
while (node != null)
{
if (DiscardDuplicates && item.IsDuplicate(node.Value)) return;
if (item.IsPromoted && !node.Value.IsPromoted)
{
_snackbarMessages.AddBefore(node, item);
added = true;
break;
}
node = node.Next;
}
if (!added)
{
_snackbarMessages.AddLast(item);
}
}
_dispatcher.InvokeAsync(ShowNextAsync);
}
/// <summary>
/// Clear the message queue and close the active snackbar.
/// This method can be called from any thread.
/// </summary>
public void Clear()
{
lock (_snackbarMessagesLock)
{
_snackbarMessages.Clear();
_closeSnackbarEvent?.Set();
}
}
private void StartDuration(TimeSpan minimumDuration, EventWaitHandle durationPassedWaitHandle)
{
if (durationPassedWaitHandle is null) throw new ArgumentNullException(nameof(durationPassedWaitHandle));
var completionTime = DateTime.Now.Add(minimumDuration);
//this keeps the event waiting simpler, rather that actually watching play -> pause -> play -> pause etc
var granularity = TimeSpan.FromMilliseconds(200);
Task.Run(() =>
{
while (true)
{
if (DateTime.Now >= completionTime) // time is over
{
durationPassedWaitHandle.Set();
break;
}
if (_disposedEvent.WaitOne(granularity)) // queue is disposed
break;
if (durationPassedWaitHandle.WaitOne(TimeSpan.Zero)) // manual exit (like message action click)
break;
if (_pausedEvent.WaitOne(TimeSpan.Zero)) // on pause completion time is extended
completionTime = completionTime.Add(granularity);
}
});
}
private async Task ShowNextAsync()
{
await _showMessageSemaphore.WaitAsync()
.ConfigureAwait(true);
try
{
Snackbar snackbar;
while (true)
{
if (_isDisposed || _dispatcher.HasShutdownStarted)
return;
snackbar = FindSnackbar();
if (snackbar != null)
break;
Trace.TraceWarning("A snackbar message is waiting, but no snackbar instances are assigned to the message queue.");
await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(true);
}
LinkedListNode<SnackbarMessageQueueItem>? messageNode;
lock (_snackbarMessagesLock)
{
messageNode = _snackbarMessages.First;
if (messageNode is null)
return;
_closeSnackbarEvent = new ManualResetEvent(false);
}
await ShowAsync(snackbar, messageNode.Value, _closeSnackbarEvent)
.ConfigureAwait(false);
lock (_snackbarMessagesLock)
{
if (messageNode.List == _snackbarMessages) // Check if it has not been cleared.
_snackbarMessages.Remove(messageNode);
_closeSnackbarEvent.Dispose();
_closeSnackbarEvent = null;
}
}
finally
{
_showMessageSemaphore.Release();
}
Snackbar FindSnackbar() => _pairedSnackbars.FirstOrDefault(sb =>
{
if (!sb.IsLoaded || sb.Visibility != Visibility.Visible) return false;
var window = Window.GetWindow(sb);
return window?.WindowState != WindowState.Minimized;
});
}
private async Task ShowAsync(Snackbar snackbar, SnackbarMessageQueueItem messageQueueItem, ManualResetEvent actionClickWaitHandle)
{
//create and show the message, setting up all the handles we need to wait on
var tuple = CreateAndShowMessage(snackbar, messageQueueItem, actionClickWaitHandle);
var snackbarMessage = tuple.Item1;
var mouseNotOverManagedWaitHandle = tuple.Item2;
var durationPassedWaitHandle = new ManualResetEvent(false);
StartDuration(messageQueueItem.Duration.Add(snackbar.ActivateStoryboardDuration), durationPassedWaitHandle);
//wait until time span completed (including pauses and mouse overs), or the action is clicked
await WaitForCompletionAsync(mouseNotOverManagedWaitHandle, durationPassedWaitHandle, actionClickWaitHandle);
//close message on snackbar
snackbar.SetCurrentValue(Snackbar.IsActiveProperty, false);
//we could wait for the animation event, but just doing
//this for now...at least it is prevent extra call back hell
await Task.Delay(snackbar.DeactivateStoryboardDuration);
//this prevents missing resource warnings after the message is removed from the Snackbar
//see https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit/issues/2040
snackbarMessage.Resources = SnackbarMessage.defaultResources;
//remove message on snackbar
snackbar.SetCurrentValue(Snackbar.MessageProperty, null);
mouseNotOverManagedWaitHandle.Dispose();
durationPassedWaitHandle.Dispose();
}
private static Tuple<SnackbarMessage, MouseNotOverManagedWaitHandle> CreateAndShowMessage(UIElement snackbar,
SnackbarMessageQueueItem messageQueueItem, EventWaitHandle actionClickWaitHandle)
{
var clickCount = 0;
var snackbarMessage = new SnackbarMessage
{
Content = messageQueueItem.Content,
ActionContent = messageQueueItem.ActionContent
};
snackbarMessage.ActionClick += (sender, args) =>
{
if (++clickCount == 1)
DoActionCallback(messageQueueItem);
actionClickWaitHandle.Set();
};
snackbar.SetCurrentValue(Snackbar.MessageProperty, snackbarMessage);
snackbar.SetCurrentValue(Snackbar.IsActiveProperty, true);
return Tuple.Create(snackbarMessage, new MouseNotOverManagedWaitHandle(snackbar));
}
private static async Task WaitForCompletionAsync(
MouseNotOverManagedWaitHandle mouseNotOverManagedWaitHandle,
EventWaitHandle durationPassedWaitHandle,
EventWaitHandle actionClickWaitHandle)
{
var durationTask = Task.Run(() =>
{
WaitHandle.WaitAll(new WaitHandle[]
{
mouseNotOverManagedWaitHandle.WaitHandle,
durationPassedWaitHandle
});
});
var actionClickTask = Task.Run(actionClickWaitHandle.WaitOne);
await Task.WhenAny(durationTask, actionClickTask);
mouseNotOverManagedWaitHandle.WaitHandle.Set();
durationPassedWaitHandle.Set();
actionClickWaitHandle.Set();
await Task.WhenAll(durationTask, actionClickTask);
}
private static void DoActionCallback(SnackbarMessageQueueItem messageQueueItem)
{
try
{
messageQueueItem.ActionHandler?.Invoke(messageQueueItem.ActionArgument);
}
catch (Exception exc)
{
Trace.WriteLine("Error during SnackbarMessageQueue message action callback, exception will be rethrown.");
Trace.WriteLine($"{exc.Message} ({exc.GetType().FullName})");
Trace.WriteLine(exc.StackTrace);
throw;
}
}
public void Dispose()
{
_isDisposed = true;
_disposedEvent.Set();
_disposedEvent.Dispose();
_pausedEvent.Dispose();
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using log4net;
using MindTouch.Tasking;
using MindTouch.Web;
using MindTouch.Xml;
using NUnit.Framework;
namespace MindTouch.Dream.Test {
using Yield = IEnumerator<IYield>;
[TestFixture]
public class ServiceTests {
private DreamHostInfo _hostInfo;
[SetUp]
public void Init() {
_hostInfo = DreamTestHelper.CreateRandomPortHost();
_hostInfo.Host.Self.At("load").With("name", "test.mindtouch.dream").Post(DreamMessage.Ok());
}
[Test]
public void Public_features_are_accessible_without_access_cookie() {
var service = _hostInfo.CreateService(typeof(AccessTestService), "access");
service.WithoutKeys().AtLocalHost.At("public").Get(new Result<DreamMessage>()).Wait()
.AssertSuccess("access without keys failed");
service.WithInternalKey().AtLocalHost.At("public").Get(new Result<DreamMessage>()).Wait()
.AssertSuccess("access with internal key failed");
service.WithPrivateKey().AtLocalHost.At("public").Get(new Result<DreamMessage>()).Wait()
.AssertSuccess("access with private key failed");
}
[Test]
public void Internal_features_require_internal_or_private_key() {
var service = _hostInfo.CreateService(typeof(AccessTestService), "access");
service.WithoutKeys().AtLocalHost.At("internal").Get(new Result<DreamMessage>()).Wait()
.AssertStatus(DreamStatus.Forbidden, "access without succeeded unexpectedly");
service.WithInternalKey().AtLocalHost.At("internal").Get(new Result<DreamMessage>()).Wait()
.AssertSuccess("access with internal key failed");
service.WithPrivateKey().AtLocalHost.At("internal").Get(new Result<DreamMessage>()).Wait()
.AssertSuccess("access with private key failed");
}
[Test]
public void Protected_features_require_private_key() {
var service = _hostInfo.CreateService(typeof(AccessTestService), "access");
service.WithoutKeys().AtLocalHost.At("protected").Get(new Result<DreamMessage>()).Wait()
.AssertStatus(DreamStatus.Forbidden, "access without succeeded unexpectedly");
service.WithInternalKey().AtLocalHost.At("protected").Get(new Result<DreamMessage>()).Wait()
.AssertStatus(DreamStatus.Forbidden, "access with internal key succeeded unexpectedly");
service.WithPrivateKey().AtLocalHost.At("protected").Get(new Result<DreamMessage>()).Wait()
.AssertSuccess("access with private key failed");
}
[Test]
public void Private_features_require_private_key() {
var service = _hostInfo.CreateService(typeof(AccessTestService), "access");
service.WithoutKeys().AtLocalHost.At("private").Get(new Result<DreamMessage>()).Wait()
.AssertStatus(DreamStatus.Forbidden, "access without succeeded unexpectedly");
service.WithInternalKey().AtLocalHost.At("private").Get(new Result<DreamMessage>()).Wait()
.AssertStatus(DreamStatus.Forbidden, "access with internal key succeeded unexpectedly");
service.WithPrivateKey().AtLocalHost.At("private").Get(new Result<DreamMessage>()).Wait()
.AssertSuccess("access with private key failed");
}
[Test]
public void Can_specify_internal_key_for_service() {
var key = StringUtil.CreateAlphaNumericKey(4);
var service = _hostInfo.CreateService(typeof(AccessTestService), "customkeys", new XDoc("config").Elem("internal-service-key", key));
var keys = service.AtLocalHost.At("keys").Get().ToDocument();
Assert.AreEqual(key, keys["internal-service-key"].AsText, "internal service key was wrong");
Assert.AreNotEqual(key, keys["private-service-key"].AsText, "private service key should not be the same as internal key");
var cookiejar = new DreamCookieJar();
cookiejar.Update(DreamCookie.NewSetCookie("service-key", key, service.AtLocalHost.Uri), service.AtLocalHost.Uri);
service.WithoutKeys().AtLocalHost
.WithCookieJar(cookiejar)
.At("internal")
.Get(new Result<DreamMessage>())
.Wait()
.AssertSuccess("access with internal key failed");
}
[Test]
public void Can_specify_private_key_for_service() {
var key = StringUtil.CreateAlphaNumericKey(4);
var service = _hostInfo.CreateService(typeof(AccessTestService), "customkeys", new XDoc("config").Elem("private-service-key", key));
var keys = service.AtLocalHost.At("keys").Get().ToDocument();
Assert.AreEqual(key, keys["private-service-key"].AsText, "private service key was wrong");
Assert.AreNotEqual(key, keys["internal-service-key"].AsText, "internal service key should not be the same as private key");
var cookiejar = new DreamCookieJar();
cookiejar.Update(DreamCookie.NewSetCookie("service-key", key, service.AtLocalHost.Uri), service.AtLocalHost.Uri);
service.WithoutKeys().AtLocalHost
.WithCookieJar(cookiejar)
.At("private")
.Get(new Result<DreamMessage>())
.Wait()
.AssertSuccess("access with private key failed");
}
[Test]
public void Service_can_create_child_service() {
XDoc config = new XDoc("config")
.Elem("path", "parent")
.Elem("sid", "sid://mindtouch.com/TestParentService");
DreamMessage result = _hostInfo.LocalHost.At("host", "services").With("apikey", _hostInfo.ApiKey).PostAsync(config).Wait();
Assert.IsTrue(result.IsSuccessful, result.ToText());
Plug localhost = Plug.New(_hostInfo.LocalHost.Uri.WithoutQuery());
result = localhost.At("parent", "child", "test").GetAsync().Wait();
Assert.AreEqual(DreamStatus.NotFound, result.Status, result.ToText());
result = localhost.At("parent", "createchild").GetAsync().Wait();
Assert.IsTrue(result.IsSuccessful, result.ToText());
result = localhost.At("parent", "child", "test").GetAsync().Wait();
Assert.IsTrue(result.IsSuccessful, result.ToText());
}
[Test]
public void Can_provide_list_of_args_as_repeated_params_to_feature() {
MockServiceInfo mock = MockService.CreateMockService(_hostInfo);
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response2) {
XDoc msg = new XDoc("ids");
foreach(KeyValuePair<string, string> kv in context.GetParams()) {
if(kv.Key == "id") {
msg.Elem("id", kv.Value);
}
}
response2.Return(DreamMessage.Ok(msg));
};
Plug p = mock.AtLocalHost;
int n = 100;
List<string> ids = new List<string>();
for(int i = 0; i < n; i++) {
p = p.With("id", i);
ids.Add(i.ToString());
}
DreamMessage result = p.GetAsync().Wait();
Assert.IsTrue(result.IsSuccessful);
List<string> seen = new List<string>();
foreach(XDoc id in result.ToDocument()["id"]) {
string v = id.AsText;
Assert.Contains(v, ids);
Assert.IsFalse(seen.Contains(v));
seen.Add(v);
}
Assert.AreEqual(ids.Count, seen.Count);
}
[Test]
public void Service_throwing_on_start_does_not_grab_the_uri() {
XDoc config = new XDoc("config")
.Elem("path", "bad")
.Elem("throw", "true")
.Elem("sid", "sid://mindtouch.com/TestBadStartService");
try {
DreamTestHelper.CreateService(_hostInfo, config);
Assert.Fail("service creation should have failed");
} catch { }
var response = _hostInfo.LocalHost.At("host", "services").With("apikey", _hostInfo.ApiKey).Get();
Assert.AreEqual(0, response.ToDocument()[string.Format("service[sid='sid://mindtouch.com/TestBadStartService']")].ListLength);
config = new XDoc("config")
.Elem("path", "bad")
.Elem("throw", "false")
.Elem("sid", "sid://mindtouch.com/TestBadStartService");
DreamTestHelper.CreateService(_hostInfo, config);
response = _hostInfo.LocalHost.At("host", "services").With("apikey", _hostInfo.ApiKey).Get();
Assert.AreEqual(1, response.ToDocument()[string.Format("service[sid='sid://mindtouch.com/TestBadStartService']")].ListLength);
}
[Test]
public void Child_service_throwing_on_start_does_not_grab_the_uri() {
XDoc config = new XDoc("config")
.Elem("path", "empty")
.Elem("sid", "sid://mindtouch.com/TestParentService");
var serviceInfo = DreamTestHelper.CreateService(_hostInfo, config);
Plug parent = serviceInfo.WithPrivateKey().AtLocalHost;
var response = parent.At("createbadstartchild").With("throw", "true").GetAsync().Wait();
Assert.IsFalse(response.IsSuccessful, response.ToText());
response = _hostInfo.LocalHost.At("host", "services").With("apikey", _hostInfo.ApiKey).Get();
Assert.AreEqual(0, response.ToDocument()[string.Format("service[sid='sid://mindtouch.com/TestBadStartService']")].ListLength);
response = parent.At("createbadstartchild").With("throw", "false").GetAsync().Wait();
Assert.IsTrue(response.IsSuccessful, response.ToText());
response = _hostInfo.LocalHost.At("host", "services").With("apikey", _hostInfo.ApiKey).Get();
Assert.AreEqual(1, response.ToDocument()[string.Format("service[sid='sid://mindtouch.com/TestBadStartService']")].ListLength);
}
[Test]
public void Service_throwing_on_delete_does_not_prevent_cleanup_and_restart() {
XDoc config = new XDoc("config")
.Elem("path", "bad")
.Elem("sid", "sid://mindtouch.com/TestBadStopService");
var serviceInfo = DreamTestHelper.CreateService(_hostInfo, config);
var response = _hostInfo.LocalHost.At("host", "services").With("apikey", _hostInfo.ApiKey).Get();
Assert.AreEqual("/bad", response.ToDocument()[string.Format("service[sid='sid://mindtouch.com/TestBadStopService']/path")].Contents);
response = serviceInfo.WithPrivateKey().AtLocalHost.DeleteAsync().Wait();
Assert.IsTrue(response.IsSuccessful, response.ToText());
response = _hostInfo.LocalHost.At("host", "services").With("apikey", _hostInfo.ApiKey).Get();
Assert.AreEqual(0, response.ToDocument()[string.Format("service[sid='sid://mindtouch.com/TestBadStopService']")].ListLength);
DreamTestHelper.CreateService(_hostInfo, config);
response = _hostInfo.LocalHost.At("host", "services").With("apikey", _hostInfo.ApiKey).Get();
Assert.AreEqual("/bad", response.ToDocument()[string.Format("service[sid='sid://mindtouch.com/TestBadStopService']/path")].Contents);
}
[Test]
public void Child_service_throwing_on_delete_does_not_prevent_cleanup_and_restart_of_child() {
XDoc config = new XDoc("config")
.Elem("path", "empty")
.Elem("sid", "sid://mindtouch.com/TestParentService");
var serviceInfo = DreamTestHelper.CreateService(_hostInfo, config);
Plug parent = serviceInfo.WithPrivateKey().AtLocalHost;
var response = parent.At("createbadchild").GetAsync().Wait();
Assert.IsTrue(response.IsSuccessful, response.ToText());
response = _hostInfo.LocalHost.At("host", "services").With("apikey", _hostInfo.ApiKey).Get();
Assert.AreEqual(1, response.ToDocument()[string.Format("service[sid='sid://mindtouch.com/TestBadStopService']")].ListLength);
response = parent.At("destroybadchild").GetAsync().Wait();
Assert.IsTrue(response.IsSuccessful, response.ToText());
response = _hostInfo.LocalHost.At("host", "services").With("apikey", _hostInfo.ApiKey).Get();
Assert.AreEqual(0, response.ToDocument()[string.Format("service[sid='sid://mindtouch.com/TestBadStopService']")].ListLength);
}
[Test]
public void Creating_two_services_at_same_uri_fails() {
XDoc config = new XDoc("config")
.Elem("path", "empty")
.Elem("sid", "sid://mindtouch.com/TestEmptyService");
var serviceInfo = DreamTestHelper.CreateService(_hostInfo, config);
var response = _hostInfo.LocalHost.At("host", "services").With("apikey", _hostInfo.ApiKey).Get();
Assert.AreEqual("/empty", response.ToDocument()[string.Format("service[sid='sid://mindtouch.com/TestEmptyService']/path")].Contents);
try {
serviceInfo = DreamTestHelper.CreateService(_hostInfo, config);
Assert.Fail();
} catch { }
}
[Test]
public void Creating_two_child_services_at_same_uri_fails() {
XDoc config = new XDoc("config")
.Elem("path", "empty")
.Elem("sid", "sid://mindtouch.com/TestParentService");
var serviceInfo = DreamTestHelper.CreateService(_hostInfo, config);
Plug parent = serviceInfo.WithPrivateKey().AtLocalHost;
var response = parent.At("createchild").GetAsync().Wait();
Assert.IsTrue(response.IsSuccessful, response.ToText());
response = _hostInfo.LocalHost.At("host", "services").With("apikey", _hostInfo.ApiKey).Get();
Assert.AreEqual(1, response.ToDocument()[string.Format("service[sid='sid://mindtouch.com/TestChildService']")].ListLength);
response = parent.At("createchild").GetAsync().Wait();
Assert.IsFalse(response.IsSuccessful, response.ToText());
}
[Test]
public void Child_that_fails_first_time_around_can_still_be_created() {
XDoc config = new XDoc("config")
.Elem("path", "empty")
.Elem("sid", "sid://mindtouch.com/TestParentService");
var serviceInfo = DreamTestHelper.CreateService(_hostInfo, config);
Plug parent = serviceInfo.WithPrivateKey().AtLocalHost;
var response = parent.At("createandretychild").GetAsync().Wait();
Assert.IsTrue(response.IsSuccessful, response.ToText());
}
}
[DreamService("TestService", "Copyright (c) 2011 MindTouch, Inc.",
Info = "",
SID = new[] { "sid://mindtouch.com/AccessTestService" }
)]
public class AccessTestService : DreamService {
[DreamFeature("GET:keys", "")]
public XDoc GetKeys() {
return new XDoc("keys")
.Elem("private-service-key", PrivateAccessKey)
.Elem("internal-service-key", InternalAccessKey);
}
[DreamFeature("GET:public", "")]
public DreamMessage GetPublic() {
return DreamMessage.Ok();
}
[DreamFeature("GET:internal", "")]
internal DreamMessage GetInternal() {
return DreamMessage.Ok();
}
[DreamFeature("GET:protected", "")]
protected DreamMessage GetProtected() {
return DreamMessage.Ok();
}
[DreamFeature("GET:private", "")]
private DreamMessage GetPrivate() {
return DreamMessage.Ok();
}
}
[DreamService("TestParentService", "Copyright (c) 2011 MindTouch, Inc.",
Info = "",
SID = new[] { "sid://mindtouch.com/TestParentService" }
)]
public class TestParentService : DreamService {
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
private Plug _badChild;
[DreamFeature("*:createchild", "test")]
public Yield CreateChildService(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
yield return CreateService("child", "sid://mindtouch.com/TestChildService", null, new Result<Plug>());
response.Return(DreamMessage.Ok());
yield break;
}
[DreamFeature("*:createbadstartchild", "test")]
public Yield CreateBadStartChild(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
yield return CreateService(
"badchild",
"sid://mindtouch.com/TestBadStartService",
new XDoc("config").Elem("throw", context.GetParam("throw", "false")),
new Result<Plug>()).Set(v => _badChild = v);
response.Return(DreamMessage.Ok());
yield break;
}
[DreamFeature("*:createandretychild", "test")]
public Yield CreateStartChildWithRetry(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
Result<Plug> r;
_log.Debug("first create attempt");
yield return r = CreateService(
"retrychild",
"sid://mindtouch.com/TestBadStartService",
new XDoc("config").Elem("throw", true),
new Result<Plug>()).Catch();
_log.DebugFormat("first attempt result: {0}", r.Exception.Message);
_log.Debug("second create attempt");
yield return CreateService(
"retrychild",
"sid://mindtouch.com/TestBadStartService",
new XDoc("config").Elem("throw", context.GetParam("throw", "false")),
new Result<Plug>());
response.Return(DreamMessage.Ok());
yield break;
}
[DreamFeature("*:createbadchild", "test")]
public Yield CreateBadChild(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
yield return CreateService("badchild", "sid://mindtouch.com/TestBadStopService", null, new Result<Plug>()).Set(v => _badChild = v);
response.Return(DreamMessage.Ok());
yield break;
}
[DreamFeature("*:destroybadchild", "test")]
public Yield DestroyBadChild(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
if(_badChild != null) {
yield return _badChild.DeleteAsync().CatchAndLog(_log);
}
response.Return(DreamMessage.Ok());
yield break;
}
protected override Yield Start(XDoc config, Result result) {
yield return Coroutine.Invoke(base.Start, config, new Result());
result.Return();
}
}
[DreamService("TestChildService", "Copyright (c) 2011 MindTouch, Inc.",
Info = "",
SID = new[] { "sid://mindtouch.com/TestChildService" }
)]
public class TestChildService : DreamService {
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
[DreamFeature("*:test", "test")]
public Yield Test(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
response.Return(DreamMessage.Ok());
yield break;
}
}
[DreamService("TestBadStartService", "Copyright (c) 2011 MindTouch, Inc.",
Info = "",
SID = new[] { "sid://mindtouch.com/TestBadStartService" }
)]
public class TestBadStartService : DreamService {
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
protected override Yield Start(XDoc config, Result result) {
yield return Coroutine.Invoke(base.Start, config, new Result());
if(config["throw"].AsBool ?? false) {
_log.DebugFormat("start about to throw");
throw new Exception("don't get me started");
}
_log.DebugFormat("start not throwing");
result.Return();
}
}
[DreamService("TestBadStopService", "Copyright (c) 2011 MindTouch, Inc.",
Info = "",
SID = new[] { "sid://mindtouch.com/TestBadStopService" }
)]
public class TestBadStopService : DreamService {
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
protected override Yield Start(XDoc config, Result result) {
yield return Coroutine.Invoke(base.Start, config, new Result());
result.Return();
}
protected override Yield Stop(Result result) {
yield return Coroutine.Invoke(base.Stop, new Result());
_log.DebugFormat("stop about to throw");
throw new Exception("You can't stop me!");
}
}
[DreamService("TestEmptyService", "Copyright (c) 2011 MindTouch, Inc.",
Info = "",
SID = new[] { "sid://mindtouch.com/TestEmptyService" }
)]
public class TestEmptyService : DreamService { }
}
| |
// 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.Diagnostics;
namespace ILCompiler.DependencyAnalysis.X64
{
public struct X64Emitter
{
public X64Emitter(NodeFactory factory, bool relocsOnly)
{
Builder = new ObjectDataBuilder(factory, relocsOnly);
TargetRegister = new TargetRegisterMap(factory.Target.OperatingSystem);
}
public ObjectDataBuilder Builder;
public TargetRegisterMap TargetRegister;
// Assembly stub creation api. TBD, actually make this general purpose
public void EmitMOV(Register regDst, ref AddrMode memory)
{
EmitIndirInstructionSize(0x8a, regDst, ref memory);
}
public void EmitMOV(Register regDst, Register regSrc)
{
AddrMode rexAddrMode = new AddrMode(regSrc, null, 0, 0, AddrModeSize.Int64);
EmitRexPrefix(regDst, ref rexAddrMode);
Builder.EmitByte(0x8B);
Builder.EmitByte((byte)(0xC0 | (((int)regDst & 0x07) << 3) | (((int)regSrc & 0x07))));
}
public void EmitMOV(Register regDst, int imm32)
{
AddrMode rexAddrMode = new AddrMode(regDst, null, 0, 0, AddrModeSize.Int32);
EmitRexPrefix(regDst, ref rexAddrMode);
Builder.EmitByte((byte)(0xB8 | ((int)regDst & 0x07)));
Builder.EmitInt(imm32);
}
public void EmitMOV(Register regDst, ISymbolNode node)
{
if (node.RepresentsIndirectionCell)
{
Builder.EmitByte(0x67);
Builder.EmitByte(0x48);
Builder.EmitByte(0x8B);
Builder.EmitByte((byte)(0x00 | ((byte)regDst << 3) | 0x05));
Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_REL32);
}
else
{
EmitLEAQ(regDst, node, delta: 0);
}
}
public void EmitLEAQ(Register reg, ISymbolNode symbol, int delta = 0)
{
AddrMode rexAddrMode = new AddrMode(Register.RAX, null, 0, 0, AddrModeSize.Int64);
EmitRexPrefix(reg, ref rexAddrMode);
Builder.EmitByte(0x8D);
Builder.EmitByte((byte)(0x05 | (((int)reg) & 0x07) << 3));
Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32, delta);
}
public void EmitLEA(Register reg, ref AddrMode addrMode)
{
Debug.Assert(addrMode.Size != AddrModeSize.Int8 &&
addrMode.Size != AddrModeSize.Int16);
EmitIndirInstruction(0x8D, reg, ref addrMode);
}
public void EmitCMP(ref AddrMode addrMode, sbyte immediate)
{
if (addrMode.Size == AddrModeSize.Int16)
Builder.EmitByte(0x66);
EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), 0x7, ref addrMode);
Builder.EmitByte((byte)immediate);
}
public void EmitADD(ref AddrMode addrMode, sbyte immediate)
{
if (addrMode.Size == AddrModeSize.Int16)
Builder.EmitByte(0x66);
EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), (byte)0, ref addrMode);
Builder.EmitByte((byte)immediate);
}
public void EmitJMP(ISymbolNode symbol)
{
if (symbol.RepresentsIndirectionCell)
{
Builder.EmitByte(0xff);
Builder.EmitByte(0x25);
Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32);
}
else
{
Builder.EmitByte(0xE9);
Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32);
}
}
public void EmitJE(ISymbolNode symbol)
{
if (symbol.RepresentsIndirectionCell)
{
throw new NotImplementedException();
}
else
{
Builder.EmitByte(0x0f);
Builder.EmitByte(0x84);
Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32);
}
}
public void EmitINT3()
{
Builder.EmitByte(0xCC);
}
public void EmitJmpToAddrMode(ref AddrMode addrMode)
{
EmitIndirInstruction(0xFF, 0x4, ref addrMode);
}
public void EmitPUSH(sbyte imm8)
{
Builder.EmitByte(0x6A);
Builder.EmitByte(unchecked((byte)imm8));
}
public void EmitPUSH(ISymbolNode node)
{
if (node.RepresentsIndirectionCell)
{
// push [rip + relative node offset]
Builder.EmitByte(0xFF);
Builder.EmitByte(0x35);
Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_REL32);
}
else
{
// push rax (arbitrary value)
Builder.EmitByte(0x50);
// lea rax, [rip + relative node offset]
Builder.EmitByte(0x48);
Builder.EmitByte(0x8D);
Builder.EmitByte(0x05);
Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_REL32);
// xchg [rsp], rax; this also restores the previous value of rax
Builder.EmitByte(0x48);
Builder.EmitByte(0x87);
Builder.EmitByte(0x04);
Builder.EmitByte(0x24);
}
}
public void EmitRET()
{
Builder.EmitByte(0xC3);
}
public void EmitRETIfEqual()
{
// jne @+1
Builder.EmitByte(0x75);
Builder.EmitByte(0x01);
// ret
Builder.EmitByte(0xC3);
}
private bool InSignedByteRange(int i)
{
return i == (int)(sbyte)i;
}
private void EmitImmediate(int immediate, int size)
{
switch (size)
{
case 0:
break;
case 1:
Builder.EmitByte((byte)immediate);
break;
case 2:
Builder.EmitShort((short)immediate);
break;
case 4:
Builder.EmitInt(immediate);
break;
default:
throw new NotImplementedException();
}
}
private void EmitModRM(byte subOpcode, ref AddrMode addrMode)
{
byte modRM = (byte)((subOpcode & 0x07) << 3);
if (addrMode.BaseReg > Register.None)
{
Debug.Assert(addrMode.BaseReg >= Register.RegDirect);
Register reg = (Register)(addrMode.BaseReg - Register.RegDirect);
Builder.EmitByte((byte)(0xC0 | modRM | ((int)reg & 0x07)));
}
else
{
byte lowOrderBitsOfBaseReg = (byte)((int)addrMode.BaseReg & 0x07);
modRM |= lowOrderBitsOfBaseReg;
int offsetSize = 0;
if (addrMode.Offset == 0 && (lowOrderBitsOfBaseReg != (byte)Register.RBP))
{
offsetSize = 0;
}
else if (InSignedByteRange(addrMode.Offset))
{
offsetSize = 1;
modRM |= 0x40;
}
else
{
offsetSize = 4;
modRM |= 0x80;
}
bool emitSibByte = false;
Register sibByteBaseRegister = addrMode.BaseReg;
if (addrMode.BaseReg == Register.None)
{
//# ifdef _TARGET_AMD64_
// x64 requires SIB to avoid RIP relative address
emitSibByte = true;
//#else
// emitSibByte = (addrMode.m_indexReg != MDIL_REG_NO_INDEX);
//#endif
modRM &= 0x38; // set Mod bits to 00 and clear out base reg
offsetSize = 4; // this forces 32-bit displacement
if (emitSibByte)
{
// EBP in SIB byte means no base
// ModRM base register forced to ESP in SIB code below
sibByteBaseRegister = Register.RBP;
}
else
{
// EBP in ModRM means no base
modRM |= (byte)(Register.RBP);
}
}
else if (lowOrderBitsOfBaseReg == (byte)Register.RSP || addrMode.IndexReg.HasValue)
{
emitSibByte = true;
}
if (!emitSibByte)
{
Builder.EmitByte(modRM);
}
else
{
// MDIL_REG_ESP as the base is the marker that there is a SIB byte
modRM = (byte)((modRM & 0xF8) | (int)Register.RSP);
Builder.EmitByte(modRM);
int indexRegAsInt = (int)(addrMode.IndexReg.HasValue ? addrMode.IndexReg.Value : Register.RSP);
Builder.EmitByte((byte)((addrMode.Scale << 6) + ((indexRegAsInt & 0x07) << 3) + ((int)sibByteBaseRegister & 0x07)));
}
EmitImmediate(addrMode.Offset, offsetSize);
}
}
private void EmitExtendedOpcode(int opcode)
{
if ((opcode >> 16) != 0)
{
if ((opcode >> 24) != 0)
{
Builder.EmitByte((byte)(opcode >> 24));
}
Builder.EmitByte((byte)(opcode >> 16));
}
Builder.EmitByte((byte)(opcode >> 8));
}
private void EmitRexPrefix(Register reg, ref AddrMode addrMode)
{
byte rexPrefix = 0;
// Check the situations where a REX prefix is needed
// Are we accessing a byte register that wasn't byte accessible in x86?
if (addrMode.Size == AddrModeSize.Int8 && reg >= Register.RSP)
{
rexPrefix |= 0x40; // REX - access to new 8-bit registers
}
// Is this a 64 bit instruction?
if (addrMode.Size == AddrModeSize.Int64)
{
rexPrefix |= 0x48; // REX.W - 64-bit data operand
}
// Is the destination register one of the new ones?
if (reg >= Register.R8)
{
rexPrefix |= 0x44; // REX.R - extension of the register field
}
// Is the index register one of the new ones?
if (addrMode.IndexReg.HasValue && addrMode.IndexReg.Value >= Register.R8 && addrMode.IndexReg.Value <= Register.R15)
{
rexPrefix |= 0x42; // REX.X - extension of the SIB index field
}
// Is the base register one of the new ones?
if (addrMode.BaseReg >= Register.R8 && addrMode.BaseReg <= Register.R15
|| addrMode.BaseReg >= (int)Register.R8 + Register.RegDirect && addrMode.BaseReg <= (int)Register.R15 + Register.RegDirect)
{
rexPrefix |= 0x41; // REX.WB (Wide, extended Base)
}
// If we have anything so far, emit it.
if (rexPrefix != 0)
{
Builder.EmitByte(rexPrefix);
}
}
private void EmitIndirInstruction(int opcode, byte subOpcode, ref AddrMode addrMode)
{
EmitRexPrefix(Register.RAX, ref addrMode);
if ((opcode >> 8) != 0)
{
EmitExtendedOpcode(opcode);
}
Builder.EmitByte((byte)opcode);
EmitModRM(subOpcode, ref addrMode);
}
private void EmitIndirInstruction(int opcode, Register dstReg, ref AddrMode addrMode)
{
EmitRexPrefix(dstReg, ref addrMode);
if ((opcode >> 8) != 0)
{
EmitExtendedOpcode(opcode);
}
Builder.EmitByte((byte)opcode);
EmitModRM((byte)((int)dstReg & 0x07), ref addrMode);
}
private void EmitIndirInstructionSize(int opcode, Register dstReg, ref AddrMode addrMode)
{
//# ifndef _TARGET_AMD64_
// assert that ESP, EBP, ESI, EDI are not accessed as bytes in 32-bit mode
// Debug.Assert(!(addrMode.Size == AddrModeSize.Int8 && dstReg > Register.RBX));
//#endif
Debug.Assert(addrMode.Size != 0);
if (addrMode.Size == AddrModeSize.Int16)
Builder.EmitByte(0x66);
EmitIndirInstruction(opcode + ((addrMode.Size != AddrModeSize.Int8) ? 1 : 0), dstReg, ref addrMode);
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using OpenMetaverse;
using Aurora.Framework;
using OpenSim.Region.Framework.Scenes;
namespace Aurora.Modules.Terrain.PaintBrushes
{
/// <summary>
/// Thermal Weathering Paint Brush
/// </summary>
public class WeatherSphere : ITerrainPaintableEffect
{
private const float talus = 0.2f;
private const NeighbourSystem type = NeighbourSystem.Moore;
#region Supporting Functions
private static int[] Neighbours(NeighbourSystem neighbourType, int index)
{
int[] coord = new int[2];
index++;
switch (neighbourType)
{
case NeighbourSystem.Moore:
switch (index)
{
case 1:
coord[0] = -1;
coord[1] = -1;
break;
case 2:
coord[0] = -0;
coord[1] = -1;
break;
case 3:
coord[0] = +1;
coord[1] = -1;
break;
case 4:
coord[0] = -1;
coord[1] = -0;
break;
case 5:
coord[0] = -0;
coord[1] = -0;
break;
case 6:
coord[0] = +1;
coord[1] = -0;
break;
case 7:
coord[0] = -1;
coord[1] = +1;
break;
case 8:
coord[0] = -0;
coord[1] = +1;
break;
case 9:
coord[0] = +1;
coord[1] = +1;
break;
default:
break;
}
break;
case NeighbourSystem.VonNeumann:
switch (index)
{
case 1:
coord[0] = 0;
coord[1] = -1;
break;
case 2:
coord[0] = -1;
coord[1] = 0;
break;
case 3:
coord[0] = +1;
coord[1] = 0;
break;
case 4:
coord[0] = 0;
coord[1] = +1;
break;
case 5:
coord[0] = -0;
coord[1] = -0;
break;
default:
break;
}
break;
}
return coord;
}
private enum NeighbourSystem
{
Moore,
VonNeumann
};
#endregion
#region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, UUID userID, float rx, float ry, float rz, float strength,
float duration, float BrushSize, List<IScene> scene)
{
strength = TerrainUtil.MetersToSphericalStrength(strength);
int x;
for (x = 0; x < map.Width; x++)
{
int y;
for (y = 0; y < map.Height; y++)
{
if (!map.Scene.Permissions.CanTerraformLand(userID, new Vector3(x, y, 0)))
continue;
float z = TerrainUtil.SphericalFactor(x, y, rx, ry, strength);
if (z > 0) // add in non-zero amount
{
const int NEIGHBOUR_ME = 4;
const int NEIGHBOUR_MAX = 9;
for (int j = 0; j < NEIGHBOUR_MAX; j++)
{
if (j != NEIGHBOUR_ME)
{
int[] coords = Neighbours(type, j);
coords[0] += x;
coords[1] += y;
if (coords[0] > map.Width - 1)
continue;
if (coords[1] > map.Height - 1)
continue;
if (coords[0] < 0)
continue;
if (coords[1] < 0)
continue;
float heightF = map[x, y];
float target = map[coords[0], coords[1]];
if (target > heightF + talus)
{
float calc = duration*((target - heightF) - talus)*z;
heightF += calc;
target -= calc;
}
map[x, y] = heightF;
map[coords[0], coords[1]] = target;
}
}
}
}
}
}
#endregion
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Methods for manipulating (sorting) collections.
/// Sort methods work directly on the supplied lists and don't copy to/from arrays
/// before/after. For medium size collections as used in the Lucene indexer that is
/// much more efficient.
///
/// @lucene.internal
/// </summary>
public sealed class CollectionUtil
{
private CollectionUtil() // no instance
{
}
private sealed class ListIntroSorter<T> : IntroSorter
{
internal T pivot;
internal IList<T> list;
internal readonly IComparer<T> Comp;
internal ListIntroSorter(IList<T> list, IComparer<T> comp)
: base()
{
/* LUCENE TO-DO I believe all ILists are RA
if (!(list is RandomAccess))
{
throw new System.ArgumentException("CollectionUtil can only sort random access lists in-place.");
}*/
this.list = list;
this.Comp = comp;
}
protected internal override int Pivot
{
set
{
pivot = list[value];
}
}
protected override void Swap(int i, int j)
{
list = list.Swap(i, j);
}
protected override int Compare(int i, int j)
{
return Comp.Compare(list[i], list[j]);
}
protected internal override int ComparePivot(int j)
{
return Comp.Compare(pivot, list[j]);
}
}
private sealed class ListTimSorter<T> : TimSorter
{
internal IList<T> List;
internal readonly IComparer<T> Comp;
internal readonly T[] Tmp;
internal ListTimSorter(IList<T> list, IComparer<T> comp, int maxTempSlots)
: base(maxTempSlots)
{
/* LUCENE TO-DO I believe all ILists are RA
if (!(list is RandomAccess))
{
throw new System.ArgumentException("CollectionUtil can only sort random access lists in-place.");
}*/
this.List = list;
this.Comp = comp;
if (maxTempSlots > 0)
{
this.Tmp = new T[maxTempSlots];
}
else
{
this.Tmp = null;
}
}
protected override void Swap(int i, int j)
{
List = List.Swap(i, j);
}
protected internal override void Copy(int src, int dest)
{
List[dest] = List[src];
}
protected internal override void Save(int i, int len)
{
for (int j = 0; j < len; ++j)
{
Tmp[j] = List[i + j];
}
}
protected internal override void Restore(int i, int j)
{
List[j] = Tmp[i];
}
protected override int Compare(int i, int j)
{
return Comp.Compare(List[i], List[j]);
}
protected internal override int CompareSaved(int i, int j)
{
return Comp.Compare(Tmp[i], List[j]);
}
}
/// <summary>
/// Sorts the given random access <seealso cref="List"/> using the <seealso cref="Comparator"/>.
/// The list must implement <seealso cref="RandomAccess"/>. this method uses the intro sort
/// algorithm, but falls back to insertion sort for small lists. </summary>
/// <exception cref="IllegalArgumentException"> if list is e.g. a linked list without random access. </exception>
public static void IntroSort<T>(IList<T> list, IComparer<T> comp)
{
int size = list.Count;
if (size <= 1)
{
return;
}
(new ListIntroSorter<T>(list, comp)).Sort(0, size);
}
/// <summary>
/// Sorts the given random access <seealso cref="List"/> in natural order.
/// The list must implement <seealso cref="RandomAccess"/>. this method uses the intro sort
/// algorithm, but falls back to insertion sort for small lists. </summary>
/// <exception cref="IllegalArgumentException"> if list is e.g. a linked list without random access. </exception>
public static void IntroSort<T>(IList<T> list)
where T : IComparable<T>
{
int size = list.Count;
if (size <= 1)
{
return;
}
IntroSort(list, ArrayUtil.naturalComparator<T>());
}
// Tim sorts:
/// <summary>
/// Sorts the given random access <seealso cref="List"/> using the <seealso cref="Comparator"/>.
/// The list must implement <seealso cref="RandomAccess"/>. this method uses the Tim sort
/// algorithm, but falls back to binary sort for small lists. </summary>
/// <exception cref="IllegalArgumentException"> if list is e.g. a linked list without random access. </exception>
public static void TimSort<T>(IList<T> list, IComparer<T> comp)
{
int size = list.Count;
if (size <= 1)
{
return;
}
(new ListTimSorter<T>(list, comp, list.Count / 64)).Sort(0, size);
}
/// <summary>
/// Sorts the given random access <seealso cref="List"/> in natural order.
/// The list must implement <seealso cref="RandomAccess"/>. this method uses the Tim sort
/// algorithm, but falls back to binary sort for small lists. </summary>
/// <exception cref="IllegalArgumentException"> if list is e.g. a linked list without random access. </exception>
public static void TimSort<T>(IList<T> list)
where T : IComparable<T>
{
int size = list.Count;
if (size <= 1)
{
return;
}
TimSort(list, ArrayUtil.naturalComparator<T>());
}
}
}
| |
using System;
using System.Collections;
using Fonet.Layout;
using Fonet.Pdf;
using Fonet.Pdf.Gdi;
namespace Fonet.Render.Pdf.Fonts {
/// <summary>
/// A Type 2 CIDFont is a font whose glyph descriptions are based on the
/// TrueType font format.
/// </summary>
/// <remarks>
/// TODO: Support font subsetting
/// </remarks>
internal class Type2CIDFont : CIDFont, IFontDescriptor {
public const string IdentityHEncoding = "Identity-H";
/// <summary>
/// Wrapper around a Win32 HDC.
/// </summary>
protected GdiDeviceContent dc;
/// <summary>
/// Provides font metrics using the Win32 Api.
/// </summary>
protected GdiFontMetrics metrics;
/// <summary>
/// List of kerning pairs.
/// </summary>
protected GdiKerningPairs kerning;
/// <summary>
/// Maps a glyph index to a PDF width
/// </summary>
protected int[] widths;
/// <summary>
/// Windows font name, e.g. 'Arial Bold'
/// </summary>
protected string baseFontName;
/// <summary>
///
/// </summary>
protected FontProperties properties;
/// <summary>
/// Maps a glyph index to a character code.
/// </summary>
protected SortedList usedGlyphs;
/// <summary>
/// Maps character code to glyph index. The array is based on the
/// value of <see cref="FirstChar"/>.
/// </summary>
protected GdiUnicodeRanges unicodeRanges;
/// <summary>
/// Class constructor.
/// </summary>
/// <param name="properties"></param>
public Type2CIDFont(FontProperties properties) {
this.properties = properties;
this.baseFontName = properties.FaceName.Replace(" ", "-");
this.usedGlyphs = new SortedList();
ObtainFontMetrics();
}
/// <summary>
/// Creates a <see cref="GdiFontMetrics"/> object from <b>baseFontName</b>
/// </summary>
private void ObtainFontMetrics() {
dc = new GdiDeviceContent();
GdiFont font = GdiFont.CreateDesignFont(
properties.FaceName, properties.IsBold, properties.IsItalic, dc);
unicodeRanges = new GdiUnicodeRanges(dc);
metrics = font.GetMetrics(dc);
}
/// <summary>
/// Class destructor.
/// </summary>
~Type2CIDFont() {
dc.Dispose();
}
#region Implementation of CIDFont members
public override string CidBaseFont {
get { return baseFontName; }
}
public override PdfWArray WArray {
get {
// The widths array for a font using the Unicode encoding is enormous.
// Instead of encoding the entire widths array, we generated a subset
// based on the used glyphs only.
IList indicies = usedGlyphs.GetKeyList();
int[] subsetWidths = GetSubsetWidthsArray(indicies);
PdfWArray widthsArray = new PdfWArray((int) indicies[0]);
widthsArray.AddEntry(subsetWidths);
return widthsArray;
}
}
public override IDictionary CMapEntries {
get {
// The usedGlyphs sorted list maps glyph indices to unicode values
return (IDictionary) usedGlyphs.Clone();
}
}
private int[] GetSubsetWidthsArray(IList indicies) {
int firstIndex = (int) indicies[0];
int lastIndex = (int) indicies[indicies.Count - 1];
// Allocate space for glyph subset
int[] subsetWidths = new int[lastIndex - firstIndex + 1];
Array.Clear(subsetWidths, 0, subsetWidths.Length);
char firstChar = (char) metrics.FirstChar;
foreach (DictionaryEntry entry in usedGlyphs) {
char c = (char) entry.Value;
int glyphIndex = (int) entry.Key;
subsetWidths[glyphIndex - firstIndex] = widths[glyphIndex];
}
return subsetWidths;
}
#endregion
#region Implementation of Font members
/// <summary>
/// Returns <see cref="PdfFontSubTypeEnum.CIDFontType2"/>.
/// </summary>
public override PdfFontSubTypeEnum SubType {
get { return PdfFontSubTypeEnum.CIDFontType2; }
}
public override string FontName {
get { return baseFontName; }
}
public override string Encoding {
get { return IdentityHEncoding; }
}
public override IFontDescriptor Descriptor {
get { return this; }
}
public override bool MultiByteFont {
get { return true; }
}
public override ushort MapCharacter(char c) {
// Obtain glyph index from Unicode character
ushort glyphIndex = unicodeRanges.MapCharacter(c);
AddGlyphToCharMapping(glyphIndex, c);
return glyphIndex;
}
protected virtual void AddGlyphToCharMapping(ushort glyphIndex, char c) {
// The usedGlyphs dictionary permits a reverse lookup (glyph index to char)
if (!usedGlyphs.ContainsKey((int) glyphIndex)) {
usedGlyphs.Add((int) glyphIndex, c);
}
}
public override int Ascender {
get { return metrics.Ascent; }
}
public override int Descender {
get { return metrics.Descent; }
}
public override int CapHeight {
get { return metrics.CapHeight; }
}
public override int FirstChar {
get { return metrics.FirstChar; }
}
public override int LastChar {
get { return metrics.LastChar; }
}
public override int GetWidth(ushort charIndex) {
EnsureWidthsArray();
// The widths array is keyed on character code, not glyph index
return widths[charIndex];
}
public override int[] Widths {
get {
EnsureWidthsArray();
return widths;
}
}
protected void EnsureWidthsArray() {
if (widths == null) {
widths = metrics.GetWidths();
}
}
#endregion
#region Implementation of IFontDescriptior interface
public int Flags {
get { return metrics.Flags; }
}
public int[] FontBBox {
get { return metrics.BoundingBox; }
}
public int ItalicAngle {
get { return metrics.ItalicAngle; }
}
public int StemV {
get { return metrics.StemV; }
}
public bool HasKerningInfo {
get {
if (kerning == null) {
kerning = metrics.KerningPairs;
}
return (kerning.Count != 0);
}
}
public bool IsEmbeddable {
get { return metrics.IsEmbeddable; }
}
public bool IsSubsettable {
get { return metrics.IsSubsettable; }
}
public virtual byte[] FontData {
get { return metrics.GetFontData(); }
}
public GdiKerningPairs KerningInfo {
get {
if (kerning == null) {
kerning = metrics.KerningPairs;
}
return kerning;
}
}
#endregion
}
}
| |
#if NET461
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace RimDev.Stuntman.Core
{
public static class IAppBuilderExtensions
{
/// <summary>
/// Enable Stuntman on this application.
/// </summary>
public static void UseStuntman(this IAppBuilder app, StuntmanOptions options)
{
if (options.AllowBearerTokenAuthentication)
{
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
AuthenticationType = Constants.StuntmanAuthenticationType,
Provider = new StuntmanOAuthBearerProvider(options),
AccessTokenFormat = new StuntmanOAuthAccessTokenFormat()
});
}
if (options.AllowCookieAuthentication)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = Constants.StuntmanAuthenticationType,
LoginPath = new PathString(options.SignInUri),
LogoutPath = new PathString(options.SignOutUri),
ReturnUrlParameter = Constants.StuntmanOptions.ReturnUrlQueryStringKey,
});
app.Map(options.SignInUri, signin =>
{
signin.Use(async (context, next) =>
{
var claims = new List<Claim>();
var overrideUserId = context.Request.Query[Constants.StuntmanOptions.OverrideQueryStringKey];
if (string.IsNullOrWhiteSpace(overrideUserId))
{
await next.Invoke();
IAppBuilderShared.ShowLoginUI(context, options);
}
else
{
var user = options.Users
.Where(x => x.Id == overrideUserId)
.FirstOrDefault();
if (user == null)
{
context.Response.StatusCode = 404;
await context.Response.WriteAsync(
$"options provided does not include the requested '{overrideUserId}' user.");
return;
}
claims.Add(new Claim(ClaimTypes.Name, user.Name));
claims.AddRange(user.Claims);
var identity = new ClaimsIdentity(claims, Constants.StuntmanAuthenticationType);
var authManager = context.Authentication;
authManager.SignIn(identity);
await next.Invoke();
}
});
IAppBuilderShared.RedirectToReturnUrl(signin);
});
app.Map(options.SignOutUri, signout =>
{
signout.Use((context, next) =>
{
var authManager = context.Authentication;
authManager.SignOut(Constants.StuntmanAuthenticationType);
return next.Invoke();
});
IAppBuilderShared.RedirectToReturnUrl(signout);
});
}
if (options.ServerEnabled)
{
app.Map(options.ServerUri, server =>
{
server.Use(async (context, next) =>
{
var response = new StuntmanServerResponse { Users = options.Users };
var json = JsonConvert.SerializeObject(response);
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(json);
});
});
}
}
private class StuntmanOAuthBearerProvider : OAuthBearerAuthenticationProvider
{
public StuntmanOAuthBearerProvider(StuntmanOptions options)
{
this.options = options;
}
private readonly StuntmanOptions options;
public override Task ValidateIdentity(OAuthValidateIdentityContext context)
{
var authorizationBearerToken = context.Request.Headers["Authorization"];
if (string.IsNullOrWhiteSpace(authorizationBearerToken))
{
context.Rejected();
return Task.FromResult(false);
}
else
{
var authorizationBearerTokenParts = authorizationBearerToken
.Split(' ');
var accessToken = authorizationBearerTokenParts
.LastOrDefault();
var claims = new List<Claim>();
StuntmanUser user = null;
if (authorizationBearerTokenParts.Count() != 2 ||
string.IsNullOrWhiteSpace(accessToken))
{
context.Response.StatusCode = 400;
context.Response.ReasonPhrase = "Authorization header is not in correct format.";
context.Rejected();
return Task.FromResult(false);
}
else
{
user = options.Users
.Where(x => x.AccessToken == accessToken)
.FirstOrDefault();
if (user == null)
{
if (!options.AllowBearerTokenPassthrough)
{
context.Response.StatusCode = 403;
context.Response.ReasonPhrase =
$"options provided does not include the requested '{accessToken}' user.";
context.Rejected();
}
return Task.FromResult(false);
}
else
{
claims.Add(new Claim("access_token", accessToken));
}
}
claims.Add(new Claim(ClaimTypes.Name, user.Name));
claims.AddRange(user.Claims);
var identity = new ClaimsIdentity(claims, Constants.StuntmanAuthenticationType);
context.Validated(identity);
var authManager = context.OwinContext.Authentication;
authManager.SignIn(identity);
if (options.AfterBearerValidateIdentity != null)
{
options.AfterBearerValidateIdentity(context);
}
return Task.FromResult(true);
}
}
}
private class StuntmanOAuthAccessTokenFormat : ISecureDataFormat<AuthenticationTicket>
{
public string Protect(AuthenticationTicket data)
{
throw new NotSupportedException(
"Stuntman does not protect data.");
}
public AuthenticationTicket Unprotect(string protectedText)
{
return new AuthenticationTicket(
identity: new ClaimsIdentity(),
properties: new AuthenticationProperties());
}
}
}
}
#endif
| |
// (c) Copyright Esri, 2010 - 2013
// This source is subject to the Apache 2.0 License.
// Please see http://www.apache.org/licenses/LICENSE-2.0.html for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using System.Resources;
using System.Security;
using ESRI.ArcGIS.Geoprocessing;
namespace ESRI.ArcGIS.OSM.GeoProcessing
{
[Guid("AD6C56FB-5130-458E-B9AA-30631BF19472")]
[ComVisible(true)]
public interface IHttpBasicGPValue
{
string UserName { set; get; }
string PassWord { set; }
string EncodedUserNamePassWord { get; set; }
}
[Guid("fab65ce5-775b-47b2-bc0b-87d93d3ebe94")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("OSMEditor.HttpBasicGPValue")]
public class HttpBasicGPValue : IHttpBasicGPValue, IGPValue, IClone, IPersistVariant, IXMLSerialize, IGPDescribe
{
#region IGPValue Members
ResourceManager resourceManager = null;
string httpBasicGPPValueDisplayName = "Username/Password using Http Basic Encoding";
IGPDataTypeFactory authenticationGPDataTypeFactory = null;
// the first release of the tools (initial release ArcGIS 10) is 1 // 06/10/2010, ESRI Prototype Lab
const int m_httpBasicGPValueVersion = 1;
const string m_xmlElementName = "EncodedAuthentication";
string m_username = null;
string m_password = null;
string m_encodedUserAuthentication = null;
public HttpBasicGPValue()
{
resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);
httpBasicGPPValueDisplayName = resourceManager.GetString("GPTools_Authentication_GPValue_displayname");
if (authenticationGPDataTypeFactory == null)
{
authenticationGPDataTypeFactory = new AuthenticationDataTypeFactory();
}
m_password = String.Empty;
m_username = String.Empty;
m_encodedUserAuthentication = String.Empty;
}
public IGPDataType DataType
{
get
{
return authenticationGPDataTypeFactory.GetDataType("HttpBasicAuthenticationDataType");
}
}
public void Empty()
{
m_username = String.Empty;
m_password = String.Empty;
}
public string GetAsText()
{
return "";
}
public bool IsEmpty()
{
if (String.IsNullOrEmpty(m_username) || String.IsNullOrEmpty(m_password))
{
return true;
}
else
{
return false;
}
}
public IGPMessage SetAsText(string text)
{
IGPMessage valueSetMessage = new GPMessageClass();
try
{
DecodeUserNamePassword(text);
}
catch (ArgumentNullException ex)
{
// pass
}
catch
{
valueSetMessage.Type = esriGPMessageType.esriGPMessageTypeError;
valueSetMessage.Description = resourceManager.GetString("GPTools_Authentication_GPValue_UnableParseAuthentication");
valueSetMessage.ErrorCode = 500;
}
return valueSetMessage;
}
#endregion
#region IClone Members
public void Assign(IClone src)
{
IHttpBasicGPValue httpBasicGPValue = src as IHttpBasicGPValue;
if (httpBasicGPValue == null)
return;
DecodeUserNamePassword(httpBasicGPValue.EncodedUserNamePassWord);
}
public IClone Clone()
{
IClone clone = new HttpBasicGPValue();
clone.Assign((IClone)this);
return clone;
}
public bool IsEqual(IClone other)
{
bool equalResult = false;
IHttpBasicGPValue httpBasicGPValue = other as IHttpBasicGPValue;
if (httpBasicGPValue == null)
return equalResult;
if (httpBasicGPValue.EncodedUserNamePassWord.Equals(EncodeUserAuthentication(m_username, m_password)))
{
equalResult = true;
}
return equalResult;
}
public bool IsIdentical(IClone other)
{
if (this.Equals(other))
{
return true;
}
else
{
return false;
}
}
#endregion
#region IPersistVariant Members
public UID ID
{
get
{
UID httpBasicGPValueUID = new UIDClass();
httpBasicGPValueUID.Value = "{fab65ce5-775b-47b2-bc0b-87d93d3ebe94}";
return httpBasicGPValueUID;
}
}
public void Load(IVariantStream Stream)
{
int version = (int)Stream.Read();
if (version > m_httpBasicGPValueVersion)
return;
m_username = Stream.Read() as string;
m_password = Stream.Read() as string;
}
public void Save(IVariantStream Stream)
{
Stream.Write(m_httpBasicGPValueVersion);
Stream.Write(m_username);
Stream.Write(m_password);
}
#endregion
#region IXMLSerialize Members
public void Deserialize(IXMLSerializeData data)
{
int elementIndex = -1;
elementIndex = data.Find(m_xmlElementName);
if (elementIndex > -1)
{
DecodeUserNamePassword(data.GetString(elementIndex));
}
}
public void Serialize(IXMLSerializeData data)
{
data.TypeName = "HttpBasicAuthenticationGPValue";
data.TypeNamespaceURI = "http://www.esri.com/schemas/ArcGIS/10.0";
data.AddString(m_xmlElementName, EncodeUserAuthentication(m_username, m_password));
}
#endregion
#region IGPDescribe Members
public object Describe(string Name)
{
string describeReturn = String.Empty;
if (Name.Equals(m_xmlElementName))
{
describeReturn = "OpenStreetMap Authentication";
}
if (Name.Equals("DataType"))
{
IGPDataType currentDataType = this.DataType;
describeReturn = currentDataType.Name;
}
return describeReturn;
}
#endregion
#region IHttpBasicGPValue Members
public string UserName
{
set
{
m_username = value;
}
get
{
return m_username;
}
}
public string PassWord
{
set
{
m_password = value;
}
}
public string EncodedUserNamePassWord
{
get
{
return EncodeUserAuthentication(m_username, m_password);
}
set
{
DecodeUserNamePassword(value);
}
}
#endregion
private void DecodeUserNamePassword(string value)
{
if (String.IsNullOrEmpty(value))
return;
string authInfo = Encoding.Default.GetString(Convert.FromBase64String(value));
string[] splitAuthInfo = authInfo.Split(":".ToCharArray());
m_username = splitAuthInfo[0];
m_password = splitAuthInfo[1];
splitAuthInfo = null;
authInfo = null;
}
private string EncodeUserAuthentication(string m_username, string m_password)
{
string encodedAuthenticationString = String.Empty;
try
{
string authInfo = m_username + ":" + m_password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
encodedAuthenticationString = authInfo;
}
catch { }
return encodedAuthenticationString;
}
}
}
| |
/*
* 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>
/// The metrics associated with a VM
/// First published in XenServer 4.0.
/// </summary>
public partial class VM_metrics : XenObject<VM_metrics>
{
public VM_metrics()
{
}
public VM_metrics(string uuid,
long memory_actual,
long VCPUs_number,
Dictionary<long, double> VCPUs_utilisation,
Dictionary<long, long> VCPUs_CPU,
Dictionary<string, string> VCPUs_params,
Dictionary<long, string[]> VCPUs_flags,
string[] state,
DateTime start_time,
DateTime install_time,
DateTime last_updated,
Dictionary<string, string> other_config,
bool hvm,
bool nested_virt,
bool nomigrate)
{
this.uuid = uuid;
this.memory_actual = memory_actual;
this.VCPUs_number = VCPUs_number;
this.VCPUs_utilisation = VCPUs_utilisation;
this.VCPUs_CPU = VCPUs_CPU;
this.VCPUs_params = VCPUs_params;
this.VCPUs_flags = VCPUs_flags;
this.state = state;
this.start_time = start_time;
this.install_time = install_time;
this.last_updated = last_updated;
this.other_config = other_config;
this.hvm = hvm;
this.nested_virt = nested_virt;
this.nomigrate = nomigrate;
}
/// <summary>
/// Creates a new VM_metrics from a Proxy_VM_metrics.
/// </summary>
/// <param name="proxy"></param>
public VM_metrics(Proxy_VM_metrics proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(VM_metrics update)
{
uuid = update.uuid;
memory_actual = update.memory_actual;
VCPUs_number = update.VCPUs_number;
VCPUs_utilisation = update.VCPUs_utilisation;
VCPUs_CPU = update.VCPUs_CPU;
VCPUs_params = update.VCPUs_params;
VCPUs_flags = update.VCPUs_flags;
state = update.state;
start_time = update.start_time;
install_time = update.install_time;
last_updated = update.last_updated;
other_config = update.other_config;
hvm = update.hvm;
nested_virt = update.nested_virt;
nomigrate = update.nomigrate;
}
internal void UpdateFromProxy(Proxy_VM_metrics proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
memory_actual = proxy.memory_actual == null ? 0 : long.Parse((string)proxy.memory_actual);
VCPUs_number = proxy.VCPUs_number == null ? 0 : long.Parse((string)proxy.VCPUs_number);
VCPUs_utilisation = proxy.VCPUs_utilisation == null ? null : Maps.convert_from_proxy_long_double(proxy.VCPUs_utilisation);
VCPUs_CPU = proxy.VCPUs_CPU == null ? null : Maps.convert_from_proxy_long_long(proxy.VCPUs_CPU);
VCPUs_params = proxy.VCPUs_params == null ? null : Maps.convert_from_proxy_string_string(proxy.VCPUs_params);
VCPUs_flags = proxy.VCPUs_flags == null ? null : Maps.convert_from_proxy_long_string_array(proxy.VCPUs_flags);
state = proxy.state == null ? new string[] {} : (string [])proxy.state;
start_time = proxy.start_time;
install_time = proxy.install_time;
last_updated = proxy.last_updated;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
hvm = (bool)proxy.hvm;
nested_virt = (bool)proxy.nested_virt;
nomigrate = (bool)proxy.nomigrate;
}
public Proxy_VM_metrics ToProxy()
{
Proxy_VM_metrics result_ = new Proxy_VM_metrics();
result_.uuid = uuid ?? "";
result_.memory_actual = memory_actual.ToString();
result_.VCPUs_number = VCPUs_number.ToString();
result_.VCPUs_utilisation = Maps.convert_to_proxy_long_double(VCPUs_utilisation);
result_.VCPUs_CPU = Maps.convert_to_proxy_long_long(VCPUs_CPU);
result_.VCPUs_params = Maps.convert_to_proxy_string_string(VCPUs_params);
result_.VCPUs_flags = Maps.convert_to_proxy_long_string_array(VCPUs_flags);
result_.state = state;
result_.start_time = start_time;
result_.install_time = install_time;
result_.last_updated = last_updated;
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.hvm = hvm;
result_.nested_virt = nested_virt;
result_.nomigrate = nomigrate;
return result_;
}
/// <summary>
/// Creates a new VM_metrics from a Hashtable.
/// </summary>
/// <param name="table"></param>
public VM_metrics(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
memory_actual = Marshalling.ParseLong(table, "memory_actual");
VCPUs_number = Marshalling.ParseLong(table, "VCPUs_number");
VCPUs_utilisation = Maps.convert_from_proxy_long_double(Marshalling.ParseHashTable(table, "VCPUs_utilisation"));
VCPUs_CPU = Maps.convert_from_proxy_long_long(Marshalling.ParseHashTable(table, "VCPUs_CPU"));
VCPUs_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "VCPUs_params"));
VCPUs_flags = Maps.convert_from_proxy_long_string_array(Marshalling.ParseHashTable(table, "VCPUs_flags"));
state = Marshalling.ParseStringArray(table, "state");
start_time = Marshalling.ParseDateTime(table, "start_time");
install_time = Marshalling.ParseDateTime(table, "install_time");
last_updated = Marshalling.ParseDateTime(table, "last_updated");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
hvm = Marshalling.ParseBool(table, "hvm");
nested_virt = Marshalling.ParseBool(table, "nested_virt");
nomigrate = Marshalling.ParseBool(table, "nomigrate");
}
public bool DeepEquals(VM_metrics other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._memory_actual, other._memory_actual) &&
Helper.AreEqual2(this._VCPUs_number, other._VCPUs_number) &&
Helper.AreEqual2(this._VCPUs_utilisation, other._VCPUs_utilisation) &&
Helper.AreEqual2(this._VCPUs_CPU, other._VCPUs_CPU) &&
Helper.AreEqual2(this._VCPUs_params, other._VCPUs_params) &&
Helper.AreEqual2(this._VCPUs_flags, other._VCPUs_flags) &&
Helper.AreEqual2(this._state, other._state) &&
Helper.AreEqual2(this._start_time, other._start_time) &&
Helper.AreEqual2(this._install_time, other._install_time) &&
Helper.AreEqual2(this._last_updated, other._last_updated) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._hvm, other._hvm) &&
Helper.AreEqual2(this._nested_virt, other._nested_virt) &&
Helper.AreEqual2(this._nomigrate, other._nomigrate);
}
public override string SaveChanges(Session session, string opaqueRef, VM_metrics server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
VM_metrics.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static VM_metrics get_record(Session session, string _vm_metrics)
{
return new VM_metrics((Proxy_VM_metrics)session.proxy.vm_metrics_get_record(session.uuid, _vm_metrics ?? "").parse());
}
/// <summary>
/// Get a reference to the VM_metrics instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VM_metrics> get_by_uuid(Session session, string _uuid)
{
return XenRef<VM_metrics>.Create(session.proxy.vm_metrics_get_by_uuid(session.uuid, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static string get_uuid(Session session, string _vm_metrics)
{
return (string)session.proxy.vm_metrics_get_uuid(session.uuid, _vm_metrics ?? "").parse();
}
/// <summary>
/// Get the memory/actual field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static long get_memory_actual(Session session, string _vm_metrics)
{
return long.Parse((string)session.proxy.vm_metrics_get_memory_actual(session.uuid, _vm_metrics ?? "").parse());
}
/// <summary>
/// Get the VCPUs/number field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static long get_VCPUs_number(Session session, string _vm_metrics)
{
return long.Parse((string)session.proxy.vm_metrics_get_vcpus_number(session.uuid, _vm_metrics ?? "").parse());
}
/// <summary>
/// Get the VCPUs/utilisation field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static Dictionary<long, double> get_VCPUs_utilisation(Session session, string _vm_metrics)
{
return Maps.convert_from_proxy_long_double(session.proxy.vm_metrics_get_vcpus_utilisation(session.uuid, _vm_metrics ?? "").parse());
}
/// <summary>
/// Get the VCPUs/CPU field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static Dictionary<long, long> get_VCPUs_CPU(Session session, string _vm_metrics)
{
return Maps.convert_from_proxy_long_long(session.proxy.vm_metrics_get_vcpus_cpu(session.uuid, _vm_metrics ?? "").parse());
}
/// <summary>
/// Get the VCPUs/params field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static Dictionary<string, string> get_VCPUs_params(Session session, string _vm_metrics)
{
return Maps.convert_from_proxy_string_string(session.proxy.vm_metrics_get_vcpus_params(session.uuid, _vm_metrics ?? "").parse());
}
/// <summary>
/// Get the VCPUs/flags field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static Dictionary<long, string[]> get_VCPUs_flags(Session session, string _vm_metrics)
{
return Maps.convert_from_proxy_long_string_array(session.proxy.vm_metrics_get_vcpus_flags(session.uuid, _vm_metrics ?? "").parse());
}
/// <summary>
/// Get the state field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static string[] get_state(Session session, string _vm_metrics)
{
return (string [])session.proxy.vm_metrics_get_state(session.uuid, _vm_metrics ?? "").parse();
}
/// <summary>
/// Get the start_time field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static DateTime get_start_time(Session session, string _vm_metrics)
{
return session.proxy.vm_metrics_get_start_time(session.uuid, _vm_metrics ?? "").parse();
}
/// <summary>
/// Get the install_time field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static DateTime get_install_time(Session session, string _vm_metrics)
{
return session.proxy.vm_metrics_get_install_time(session.uuid, _vm_metrics ?? "").parse();
}
/// <summary>
/// Get the last_updated field of the given VM_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static DateTime get_last_updated(Session session, string _vm_metrics)
{
return session.proxy.vm_metrics_get_last_updated(session.uuid, _vm_metrics ?? "").parse();
}
/// <summary>
/// Get the other_config field of the given VM_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static Dictionary<string, string> get_other_config(Session session, string _vm_metrics)
{
return Maps.convert_from_proxy_string_string(session.proxy.vm_metrics_get_other_config(session.uuid, _vm_metrics ?? "").parse());
}
/// <summary>
/// Get the hvm field of the given VM_metrics.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static bool get_hvm(Session session, string _vm_metrics)
{
return (bool)session.proxy.vm_metrics_get_hvm(session.uuid, _vm_metrics ?? "").parse();
}
/// <summary>
/// Get the nested_virt field of the given VM_metrics.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static bool get_nested_virt(Session session, string _vm_metrics)
{
return (bool)session.proxy.vm_metrics_get_nested_virt(session.uuid, _vm_metrics ?? "").parse();
}
/// <summary>
/// Get the nomigrate field of the given VM_metrics.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
public static bool get_nomigrate(Session session, string _vm_metrics)
{
return (bool)session.proxy.vm_metrics_get_nomigrate(session.uuid, _vm_metrics ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given VM_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _vm_metrics, Dictionary<string, string> _other_config)
{
session.proxy.vm_metrics_set_other_config(session.uuid, _vm_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given VM_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _vm_metrics, string _key, string _value)
{
session.proxy.vm_metrics_add_to_other_config(session.uuid, _vm_metrics ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given VM_metrics. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _vm_metrics, string _key)
{
session.proxy.vm_metrics_remove_from_other_config(session.uuid, _vm_metrics ?? "", _key ?? "").parse();
}
/// <summary>
/// Return a list of all the VM_metrics instances known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VM_metrics>> get_all(Session session)
{
return XenRef<VM_metrics>.Create(session.proxy.vm_metrics_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the VM_metrics Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VM_metrics>, VM_metrics> get_all_records(Session session)
{
return XenRef<VM_metrics>.Create<Proxy_VM_metrics>(session.proxy.vm_metrics_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>
/// Guest's actual memory (bytes)
/// </summary>
public virtual long memory_actual
{
get { return _memory_actual; }
set
{
if (!Helper.AreEqual(value, _memory_actual))
{
_memory_actual = value;
Changed = true;
NotifyPropertyChanged("memory_actual");
}
}
}
private long _memory_actual;
/// <summary>
/// Current number of VCPUs
/// </summary>
public virtual long VCPUs_number
{
get { return _VCPUs_number; }
set
{
if (!Helper.AreEqual(value, _VCPUs_number))
{
_VCPUs_number = value;
Changed = true;
NotifyPropertyChanged("VCPUs_number");
}
}
}
private long _VCPUs_number;
/// <summary>
/// Utilisation for all of guest's current VCPUs
/// </summary>
public virtual Dictionary<long, double> VCPUs_utilisation
{
get { return _VCPUs_utilisation; }
set
{
if (!Helper.AreEqual(value, _VCPUs_utilisation))
{
_VCPUs_utilisation = value;
Changed = true;
NotifyPropertyChanged("VCPUs_utilisation");
}
}
}
private Dictionary<long, double> _VCPUs_utilisation;
/// <summary>
/// VCPU to PCPU map
/// </summary>
public virtual Dictionary<long, long> VCPUs_CPU
{
get { return _VCPUs_CPU; }
set
{
if (!Helper.AreEqual(value, _VCPUs_CPU))
{
_VCPUs_CPU = value;
Changed = true;
NotifyPropertyChanged("VCPUs_CPU");
}
}
}
private Dictionary<long, long> _VCPUs_CPU;
/// <summary>
/// The live equivalent to VM.VCPUs_params
/// </summary>
public virtual Dictionary<string, string> VCPUs_params
{
get { return _VCPUs_params; }
set
{
if (!Helper.AreEqual(value, _VCPUs_params))
{
_VCPUs_params = value;
Changed = true;
NotifyPropertyChanged("VCPUs_params");
}
}
}
private Dictionary<string, string> _VCPUs_params;
/// <summary>
/// CPU flags (blocked,online,running)
/// </summary>
public virtual Dictionary<long, string[]> VCPUs_flags
{
get { return _VCPUs_flags; }
set
{
if (!Helper.AreEqual(value, _VCPUs_flags))
{
_VCPUs_flags = value;
Changed = true;
NotifyPropertyChanged("VCPUs_flags");
}
}
}
private Dictionary<long, string[]> _VCPUs_flags;
/// <summary>
/// The state of the guest, eg blocked, dying etc
/// </summary>
public virtual string[] state
{
get { return _state; }
set
{
if (!Helper.AreEqual(value, _state))
{
_state = value;
Changed = true;
NotifyPropertyChanged("state");
}
}
}
private string[] _state;
/// <summary>
/// Time at which this VM was last booted
/// </summary>
public virtual DateTime start_time
{
get { return _start_time; }
set
{
if (!Helper.AreEqual(value, _start_time))
{
_start_time = value;
Changed = true;
NotifyPropertyChanged("start_time");
}
}
}
private DateTime _start_time;
/// <summary>
/// Time at which the VM was installed
/// </summary>
public virtual DateTime install_time
{
get { return _install_time; }
set
{
if (!Helper.AreEqual(value, _install_time))
{
_install_time = value;
Changed = true;
NotifyPropertyChanged("install_time");
}
}
}
private DateTime _install_time;
/// <summary>
/// Time at which this information was last updated
/// </summary>
public virtual DateTime last_updated
{
get { return _last_updated; }
set
{
if (!Helper.AreEqual(value, _last_updated))
{
_last_updated = value;
Changed = true;
NotifyPropertyChanged("last_updated");
}
}
}
private DateTime _last_updated;
/// <summary>
/// additional configuration
/// First published in XenServer 5.0.
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
/// <summary>
/// hardware virtual machine
/// First published in XenServer 7.1.
/// </summary>
public virtual bool hvm
{
get { return _hvm; }
set
{
if (!Helper.AreEqual(value, _hvm))
{
_hvm = value;
Changed = true;
NotifyPropertyChanged("hvm");
}
}
}
private bool _hvm;
/// <summary>
/// VM supports nested virtualisation
/// First published in XenServer 7.1.
/// </summary>
public virtual bool nested_virt
{
get { return _nested_virt; }
set
{
if (!Helper.AreEqual(value, _nested_virt))
{
_nested_virt = value;
Changed = true;
NotifyPropertyChanged("nested_virt");
}
}
}
private bool _nested_virt;
/// <summary>
/// VM is immobile and can't migrate between hosts
/// First published in XenServer 7.1.
/// </summary>
public virtual bool nomigrate
{
get { return _nomigrate; }
set
{
if (!Helper.AreEqual(value, _nomigrate))
{
_nomigrate = value;
Changed = true;
NotifyPropertyChanged("nomigrate");
}
}
}
private bool _nomigrate;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class VolatileKeywordRecommenderTests : KeywordRecommenderTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AtRoot_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClass_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"class C { }
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalStatement_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalVariableDeclaration_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInEmptyStatement()
{
VerifyAbsence(AddInsideMethod(
@"$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInCompilationUnit()
{
VerifyAbsence(SourceCodeKind.Regular, @"$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterExtern()
{
VerifyAbsence(SourceCodeKind.Regular, @"extern alias Foo;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterExtern_Interactive()
{
VerifyKeyword(SourceCodeKind.Script, @"extern alias Foo;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterUsing()
{
VerifyAbsence(SourceCodeKind.Regular, @"using Foo;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterUsing_Interactive()
{
VerifyKeyword(SourceCodeKind.Script, @"using Foo;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNamespace()
{
VerifyAbsence(SourceCodeKind.Regular, @"namespace N {}
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterTypeDeclaration()
{
VerifyAbsence(SourceCodeKind.Regular, @"class C {}
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterDelegateDeclaration()
{
VerifyAbsence(SourceCodeKind.Regular, @"delegate void Foo();
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethod()
{
VerifyKeyword(
@"class C {
void Foo() {}
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterField()
{
VerifyKeyword(
@"class C {
int i;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterProperty()
{
VerifyKeyword(
@"class C {
int i { get; }
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBeforeUsing()
{
VerifyAbsence(SourceCodeKind.Regular,
@"$$
using Foo;");
}
[WpfFact(Skip = "528041"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBeforeUsing_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"$$
using Foo;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterAssemblyAttribute()
{
VerifyAbsence(SourceCodeKind.Regular, @"[assembly: foo]
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAssemblyAttribute_Interactive()
{
VerifyKeyword(SourceCodeKind.Script, @"[assembly: foo]
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterRootAttribute()
{
VerifyAbsence(@"[foo]
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAttribute()
{
VerifyKeyword(
@"class C {
[foo]
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideStruct()
{
VerifyKeyword(
@"struct S {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInsideInterface()
{
VerifyAbsence(@"interface I {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInsideEnum()
{
VerifyAbsence(@"enum E {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideClass()
{
VerifyKeyword(
@"class C {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPartial()
{
VerifyAbsence(@"partial $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterAbstract()
{
VerifyAbsence(@"abstract $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterInternal()
{
VerifyAbsence(SourceCodeKind.Regular, @"internal $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterInternal_Interactive()
{
VerifyKeyword(SourceCodeKind.Script, @"internal $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedInternal()
{
VerifyKeyword(
@"class C {
internal $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPublic()
{
VerifyAbsence(SourceCodeKind.Regular, @"public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPublic_Interactive()
{
VerifyKeyword(SourceCodeKind.Script, @"public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPublic()
{
VerifyKeyword(
@"class C {
public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPrivate()
{
VerifyAbsence(SourceCodeKind.Regular,
@"private $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPrivate_Script()
{
VerifyKeyword(SourceCodeKind.Script,
@"private $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPrivate()
{
VerifyKeyword(
@"class C {
private $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterProtected()
{
VerifyAbsence(
@"protected $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedProtected()
{
VerifyKeyword(
@"class C {
protected $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterSealed()
{
VerifyAbsence(@"sealed $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedSealed()
{
VerifyAbsence(
@"class C {
sealed $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterStatic()
{
VerifyAbsence(SourceCodeKind.Regular, @"static $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStatic_Interactive()
{
VerifyKeyword(SourceCodeKind.Script, @"static $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedStatic()
{
VerifyKeyword(
@"class C {
static $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterStaticPublic()
{
VerifyAbsence(SourceCodeKind.Regular, @"static public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStaticPublic_Interactive()
{
VerifyKeyword(SourceCodeKind.Script, @"static public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedStaticPublic()
{
VerifyKeyword(
@"class C {
static public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterDelegate()
{
VerifyAbsence(@"delegate $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterEvent()
{
VerifyAbsence(
@"class C {
event $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterConst()
{
VerifyAbsence(
@"class C {
const $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterVolatile()
{
VerifyAbsence(
@"class C {
volatile $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNew()
{
VerifyAbsence(
@"new $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedNew()
{
VerifyKeyword(
@"class C {
new $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInMethod()
{
VerifyAbsence(
@"class C {
void Foo() {
$$");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall;
using FlatRedBall.Input;
using FlatRedBall.Instructions;
using FlatRedBall.ManagedSpriteGroups;
using FlatRedBall.Math;
using FlatRedBall.Math.Geometry;
using EditorObjects;
using EditorObjects.Undo;
using FlatRedBall.Graphics;
using FlatRedBall.Graphics.Model;
using FlatRedBall.Gui;
#if FRB_XNA
using Microsoft.Xna.Framework.Input;
using EditorObjects.Undo.PropertyComparers;
#elif FRB_MDX
using Keys = Microsoft.DirectX.DirectInput.Key;
using EditorObjects.Undo.PropertyComparers;
#endif
namespace EditorObjects
{
public static class UndoManager
{
#region Fields
static List<InstructionList> mInstructions = new List<InstructionList>();
static InstructionList mUndosAddedThisFrame = new InstructionList();
static Dictionary<Type, PropertyComparer>
mPropertyComparers = new Dictionary<Type, PropertyComparer>();
static ListDisplayWindow mInstructionListDisplayWindow;
#endregion
#region Properties
public static List<InstructionList> Instructions
{
get { return mInstructions; }
}
#endregion
#region Methods
#region Constructor
static UndoManager()
{
// These should be moved into their own constructors that the user can call depending on what undos they need
#region Set the members to watch for Sprites
PropertyComparer<Sprite> spritePropertyComparer =
new PropertyComparer<Sprite>();
mPropertyComparers.Add(typeof(Sprite), spritePropertyComparer);
spritePropertyComparer.AddMemberWatching<float>("X");
spritePropertyComparer.AddMemberWatching<float>("Y");
spritePropertyComparer.AddMemberWatching<float>("Z");
spritePropertyComparer.AddMemberWatching<float>("ScaleX");
spritePropertyComparer.AddMemberWatching<float>("ScaleY");
spritePropertyComparer.AddMemberWatching<float>("RotationX");
spritePropertyComparer.AddMemberWatching<float>("RotationY");
spritePropertyComparer.AddMemberWatching<float>("RotationZ");
spritePropertyComparer.AddMemberWatching<float>("RelativeX");
spritePropertyComparer.AddMemberWatching<float>("RelativeY");
spritePropertyComparer.AddMemberWatching<float>("RelativeZ");
spritePropertyComparer.AddMemberWatching<float>("RelativeRotationX");
spritePropertyComparer.AddMemberWatching<float>("RelativeRotationY");
spritePropertyComparer.AddMemberWatching<float>("RelativeRotationZ");
#endregion
#region Set the members to watch for SpriteFrames
PropertyComparer<SpriteFrame> spriteFramePropertyComparer =
new PropertyComparer<SpriteFrame>();
mPropertyComparers.Add(typeof(SpriteFrame), spriteFramePropertyComparer);
spriteFramePropertyComparer.AddMemberWatching<float>("X");
spriteFramePropertyComparer.AddMemberWatching<float>("Y");
spriteFramePropertyComparer.AddMemberWatching<float>("Z");
spriteFramePropertyComparer.AddMemberWatching<float>("ScaleX");
spriteFramePropertyComparer.AddMemberWatching<float>("ScaleY");
spriteFramePropertyComparer.AddMemberWatching<float>("RotationX");
spriteFramePropertyComparer.AddMemberWatching<float>("RotationY");
spriteFramePropertyComparer.AddMemberWatching<float>("RotationZ");
spriteFramePropertyComparer.AddMemberWatching<float>("RelativeX");
spriteFramePropertyComparer.AddMemberWatching<float>("RelativeY");
spriteFramePropertyComparer.AddMemberWatching<float>("RelativeZ");
spriteFramePropertyComparer.AddMemberWatching<float>("RelativeRotationX");
spriteFramePropertyComparer.AddMemberWatching<float>("RelativeRotationY");
spriteFramePropertyComparer.AddMemberWatching<float>("RelativeRotationZ");
#endregion
#region Set the members to watch for Polygons
PolygonPropertyComparer polygonPropertyComparer = new PolygonPropertyComparer();
mPropertyComparers.Add(typeof(Polygon), polygonPropertyComparer);
polygonPropertyComparer.AddMemberWatching<float>("X");
polygonPropertyComparer.AddMemberWatching<float>("Y");
polygonPropertyComparer.AddMemberWatching<float>("Z");
polygonPropertyComparer.AddMemberWatching<float>("RotationZ");
#endregion
#region Set the members to watch for AxisAlignedRectangles
PropertyComparer<AxisAlignedRectangle> axisAlignedRectanglePropertyComparer =
new PropertyComparer<AxisAlignedRectangle>();
mPropertyComparers.Add(typeof(AxisAlignedRectangle), axisAlignedRectanglePropertyComparer);
axisAlignedRectanglePropertyComparer.AddMemberWatching<float>("X");
axisAlignedRectanglePropertyComparer.AddMemberWatching<float>("Y");
axisAlignedRectanglePropertyComparer.AddMemberWatching<float>("Z");
axisAlignedRectanglePropertyComparer.AddMemberWatching<float>("ScaleX");
axisAlignedRectanglePropertyComparer.AddMemberWatching<float>("ScaleY");
#endregion
#region Set the members to watch for Circles
PropertyComparer<Circle> circlePropertyComparer = new PropertyComparer<Circle>();
mPropertyComparers.Add(typeof(Circle), circlePropertyComparer);
circlePropertyComparer.AddMemberWatching<float>("X");
circlePropertyComparer.AddMemberWatching<float>("Y");
circlePropertyComparer.AddMemberWatching<float>("Z");
circlePropertyComparer.AddMemberWatching<float>("Radius");
#endregion
#region Set the members to watch for Spheres
PropertyComparer<Sphere> spherePropertyComparer =
new PropertyComparer<Sphere>();
mPropertyComparers.Add(typeof(Sphere), spherePropertyComparer);
spherePropertyComparer.AddMemberWatching<float>("X");
spherePropertyComparer.AddMemberWatching<float>("Y");
spherePropertyComparer.AddMemberWatching<float>("Z");
spherePropertyComparer.AddMemberWatching<float>("Radius");
#endregion
#region Set the members to watch for Texts
PropertyComparer<Text> textPropertyComparer =
new PropertyComparer<Text>();
mPropertyComparers.Add(typeof(Text), textPropertyComparer);
textPropertyComparer.AddMemberWatching<float>("X");
textPropertyComparer.AddMemberWatching<float>("Y");
textPropertyComparer.AddMemberWatching<float>("Z");
textPropertyComparer.AddMemberWatching<float>("RotationZ");
#endregion
#region Set the members to watch for PositionedModels
PropertyComparer<PositionedModel> positionedModelPropertyComparer =
new PropertyComparer<PositionedModel>();
mPropertyComparers.Add(typeof(PositionedModel), positionedModelPropertyComparer);
positionedModelPropertyComparer.AddMemberWatching<float>("X");
positionedModelPropertyComparer.AddMemberWatching<float>("Y");
positionedModelPropertyComparer.AddMemberWatching<float>("Z");
positionedModelPropertyComparer.AddMemberWatching<float>("RotationZ");
#endregion
#region Set the members to watch for SpriteGrids
mPropertyComparers.Add(typeof(SpriteGrid),
new SpriteGridPropertyComparer());
#endregion
}
#endregion
#region Public Methods
public static void AddToThisFramesUndo(Instruction instructionToAdd)
{
mUndosAddedThisFrame.Add(instructionToAdd);
}
public static void AddToWatch<T>(T objectToWatch) where T : new()
{
PropertyComparer<T> propertyComparer =
mPropertyComparers[typeof(T)] as PropertyComparer<T>;
if (objectToWatch == null)
{
throw new NullReferenceException("Can't add a null object to the UndoManager's watch");
}
if (propertyComparer.Contains(objectToWatch) == false)
{
propertyComparer.AddObject(objectToWatch, new T());
}
}
public static void AddAxisAlignedCubePropertyComparer()
{
PropertyComparer<AxisAlignedCube> axisAlignedCubePropertyComparer =
new PropertyComparer<AxisAlignedCube>();
mPropertyComparers.Add(typeof(AxisAlignedCube), axisAlignedCubePropertyComparer);
axisAlignedCubePropertyComparer.AddMemberWatching<float>("X");
axisAlignedCubePropertyComparer.AddMemberWatching<float>("Y");
axisAlignedCubePropertyComparer.AddMemberWatching<float>("Z");
axisAlignedCubePropertyComparer.AddMemberWatching<float>("ScaleX");
axisAlignedCubePropertyComparer.AddMemberWatching<float>("ScaleY");
axisAlignedCubePropertyComparer.AddMemberWatching<float>("ScaleZ");
}
public static void ClearObjectsWatching<T>() where T : new()
{
PropertyComparer<T> propertyComparer =
mPropertyComparers[typeof(T)] as PropertyComparer<T>;
propertyComparer.ClearObjects();
}
public static void EndOfFrameActivity()
{
UpdateListDisplayWindow();
#region Perform Undos if pushed Control+Z
if (InputManager.Keyboard.ControlZPushed() &&
mInstructions.Count != 0)
{
InstructionList instructionList = mInstructions[mInstructions.Count - 1];
for (int i = 0; i < instructionList.Count; i++)
{
Instruction instruction = instructionList[i];
// See if the instruction is one that has an associated delegate
if (instruction is GenericInstruction)
{
GenericInstruction asGenericInstruction = instruction as GenericInstruction;
Type targetType = asGenericInstruction.Target.GetType();
PropertyComparer propertyComparerForType = null;
if(mPropertyComparers.ContainsKey(targetType))
{
// There is a PropertyComparer for this exact type
propertyComparerForType = mPropertyComparers[targetType];
}
else
{
// There isn't a PropertyComparer for this exact type, so climb up the inheritance tree
foreach (PropertyComparer pc in mPropertyComparers.Values)
{
if (pc.GenericType.IsAssignableFrom(targetType))
{
propertyComparerForType = pc;
break;
}
}
}
// If there's no PropertyComparer, then the app might be a UI-only app. If that's
// the case, we don't want to run afterUpdateDelegates
if (propertyComparerForType != null)
{
AfterUpdateDelegate afterUpdateDelegate =
propertyComparerForType.GetAfterUpdateDelegateForMember(asGenericInstruction.Member);
if (afterUpdateDelegate != null)
{
afterUpdateDelegate(asGenericInstruction.Target);
}
}
}
instruction.Execute();
}
mInstructions.RemoveAt(mInstructions.Count - 1);
}
#endregion
// Vic says that this will break if undos are added through this and through
// the property comparers in the same frame.
if (mUndosAddedThisFrame.Count != 0)
{
mInstructions.Add(mUndosAddedThisFrame);
mUndosAddedThisFrame = new InstructionList();
}
}
public static bool HasPropertyComparerForType(Type type)
{
return mPropertyComparers.ContainsKey(type);
}
public static void RecordUndos<T>() where T : new()
{
RecordUndos<T>(true);
}
public static void RecordUndos<T>(bool createNewList) where T : new()
{
PropertyComparer<T> propertyComparer =
mPropertyComparers[typeof(T)] as PropertyComparer<T>;
propertyComparer.GetAllChangedMemberInstructions(mInstructions, createNewList);
}
public static void SetAfterUpdateDelegate(Type type, string member, AfterUpdateDelegate afterUpdateDelegate)
{
PropertyComparer propertyComparer =
mPropertyComparers[type];
propertyComparer.SetAfterUpdateDelegateForMember(member, afterUpdateDelegate);
}
public static void SetPropertyComparer(Type type, PropertyComparer propertyComparer)
{
if (mPropertyComparers.ContainsKey(type))
{
mPropertyComparers.Remove(type);
}
mPropertyComparers.Add(type, propertyComparer);
}
public static void ShowListDisplayWindow()
{
ShowListDisplayWindow(null);
}
/// <summary>
/// Shows a ListDisplayWindow with the undos in the UndoManager. This is provided as a convenience function so it
/// can be used in MenuStrips.
/// </summary>
/// <param name="callingWindow">This property will not be used - it's here to match the GuiMessage delegate.</param>
public static void ShowListDisplayWindow(Window callingWindow)
{
#region If the ListDisplayWindow hasn't been created yet, create it
if (mInstructionListDisplayWindow == null)
{
mInstructionListDisplayWindow = new ListDisplayWindow(GuiManager.Cursor);
mInstructionListDisplayWindow.ListShowing = mInstructions;
mInstructionListDisplayWindow.HasMoveBar = true;
mInstructionListDisplayWindow.HasCloseButton = true;
mInstructionListDisplayWindow.Resizable = true;
mInstructionListDisplayWindow.ScaleX = 9;
mInstructionListDisplayWindow.X = SpriteManager.Camera.XEdge * 2 - mInstructionListDisplayWindow.ScaleX;
mInstructionListDisplayWindow.Name = "Undos";
GuiManager.AddWindow(mInstructionListDisplayWindow);
}
#endregion
#region Show and bring the ListDisplayWindow to the top
mInstructionListDisplayWindow.Visible = true;
GuiManager.BringToFront(mInstructionListDisplayWindow);
#endregion
}
public static new string ToString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Undos: ").Append(mInstructions.Count.ToString());
return stringBuilder.ToString();
}
#endregion
#region Private Methods
private static void UpdateListDisplayWindow()
{
if (mInstructionListDisplayWindow != null)
{
mInstructionListDisplayWindow.UpdateToList();
}
}
#endregion
#endregion
}
}
| |
// DeflaterEngine.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// 2010-08-13 Sky Sanders - Modified for Silverlight 3/4 and Windows Phone 7
using System;
using ICSharpCode.SharpZipLib.Checksums;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// Strategies for deflater
/// </summary>
internal enum DeflateStrategy
{
/// <summary>
/// The default strategy
/// </summary>
Default = 0,
/// <summary>
/// This strategy will only allow longer string repetitions. It is
/// useful for random data with a small character set.
/// </summary>
Filtered = 1,
/// <summary>
/// This strategy will not look for string repetitions at all. It
/// only encodes with Huffman trees (which means, that more common
/// characters get a smaller encoding.
/// </summary>
HuffmanOnly = 2
}
// DEFLATE ALGORITHM:
//
// The uncompressed stream is inserted into the window array. When
// the window array is full the first half is thrown away and the
// second half is copied to the beginning.
//
// The head array is a hash table. Three characters build a hash value
// and they the value points to the corresponding index in window of
// the last string with this hash. The prev array implements a
// linked list of matches with the same hash: prev[index & WMASK] points
// to the previous index with the same hash.
//
/// <summary>
/// Low level compression engine for deflate algorithm which uses a 32K sliding window
/// with secondary compression from Huffman/Shannon-Fano codes.
/// </summary>
internal class DeflaterEngine : DeflaterConstants
{
#region Constants
const int TooFar = 4096;
#endregion
#region Constructors
/// <summary>
/// Construct instance with pending buffer
/// </summary>
/// <param name="pending">
/// Pending buffer to use
/// </param>>
public DeflaterEngine(DeflaterPending pending)
{
this.pending = pending;
huffman = new DeflaterHuffman(pending);
adler = new Adler32();
window = new byte[2 * WSIZE];
head = new short[HASH_SIZE];
prev = new short[WSIZE];
// We start at index 1, to avoid an implementation deficiency, that
// we cannot build a repeat pattern at index 0.
blockStart = strstart = 1;
}
#endregion
/// <summary>
/// Deflate drives actual compression of data
/// </summary>
/// <param name="flush">True to flush input buffers</param>
/// <param name="finish">Finish deflation with the current input.</param>
/// <returns>Returns true if progress has been made.</returns>
public bool Deflate(bool flush, bool finish)
{
bool progress;
do
{
FillWindow();
bool canFlush = flush && (inputOff == inputEnd);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.WriteLine("window: [" + blockStart + "," + strstart + ","
+ lookahead + "], " + compressionFunction + "," + canFlush);
}
#endif
switch (compressionFunction)
{
case DEFLATE_STORED:
progress = DeflateStored(canFlush, finish);
break;
case DEFLATE_FAST:
progress = DeflateFast(canFlush, finish);
break;
case DEFLATE_SLOW:
progress = DeflateSlow(canFlush, finish);
break;
default:
throw new InvalidOperationException("unknown compressionFunction");
}
} while (pending.IsFlushed && progress); // repeat while we have no pending output and progress was made
return progress;
}
/// <summary>
/// Sets input data to be deflated. Should only be called when <code>NeedsInput()</code>
/// returns true
/// </summary>
/// <param name="buffer">The buffer containing input data.</param>
/// <param name="offset">The offset of the first byte of data.</param>
/// <param name="count">The number of bytes of data to use as input.</param>
public void SetInput(byte[] buffer, int offset, int count)
{
if ( buffer == null )
{
throw new ArgumentNullException("buffer");
}
if ( offset < 0 )
{
throw new ArgumentOutOfRangeException("offset");
}
if ( count < 0 )
{
throw new ArgumentOutOfRangeException("count");
}
if (inputOff < inputEnd)
{
throw new InvalidOperationException("Old input was not completely processed");
}
int end = offset + count;
/* We want to throw an ArrayIndexOutOfBoundsException early. The
* check is very tricky: it also handles integer wrap around.
*/
if ((offset > end) || (end > buffer.Length) )
{
throw new ArgumentOutOfRangeException("count");
}
inputBuf = buffer;
inputOff = offset;
inputEnd = end;
}
/// <summary>
/// Determines if more <see cref="SetInput">input</see> is needed.
/// </summary>
/// <returns>Return true if input is needed via <see cref="SetInput">SetInput</see></returns>
public bool NeedsInput()
{
return (inputEnd == inputOff);
}
/// <summary>
/// Set compression dictionary
/// </summary>
/// <param name="buffer">The buffer containing the dictionary data</param>
/// <param name="offset">The offset in the buffer for the first byte of data</param>
/// <param name="length">The length of the dictionary data.</param>
public void SetDictionary(byte[] buffer, int offset, int length)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (strstart != 1) )
{
throw new InvalidOperationException("strstart not 1");
}
#endif
adler.Update(buffer, offset, length);
if (length < MIN_MATCH)
{
return;
}
if (length > MAX_DIST)
{
offset += length - MAX_DIST;
length = MAX_DIST;
}
System.Array.Copy(buffer, offset, window, strstart, length);
UpdateHash();
--length;
while (--length > 0)
{
InsertString();
strstart++;
}
strstart += 2;
blockStart = strstart;
}
/// <summary>
/// Reset internal state
/// </summary>
public void Reset()
{
huffman.Reset();
adler.Reset();
blockStart = strstart = 1;
lookahead = 0;
totalIn = 0;
prevAvailable = false;
matchLen = MIN_MATCH - 1;
for (int i = 0; i < HASH_SIZE; i++) {
head[i] = 0;
}
for (int i = 0; i < WSIZE; i++) {
prev[i] = 0;
}
}
/// <summary>
/// Reset Adler checksum
/// </summary>
public void ResetAdler()
{
adler.Reset();
}
/// <summary>
/// Get current value of Adler checksum
/// </summary>
public int Adler {
get {
return unchecked((int)adler.Value);
}
}
/// <summary>
/// Total data processed
/// </summary>
public long TotalIn {
get {
return totalIn;
}
}
/// <summary>
/// Get/set the <see cref="DeflateStrategy">deflate strategy</see>
/// </summary>
public DeflateStrategy Strategy {
get {
return strategy;
}
set {
strategy = value;
}
}
/// <summary>
/// Set the deflate level (0-9)
/// </summary>
/// <param name="level">The value to set the level to.</param>
public void SetLevel(int level)
{
if ( (level < 0) || (level > 9) )
{
throw new ArgumentOutOfRangeException("level");
}
goodLength = DeflaterConstants.GOOD_LENGTH[level];
max_lazy = DeflaterConstants.MAX_LAZY[level];
niceLength = DeflaterConstants.NICE_LENGTH[level];
max_chain = DeflaterConstants.MAX_CHAIN[level];
if (DeflaterConstants.COMPR_FUNC[level] != compressionFunction) {
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.WriteLine("Change from " + compressionFunction + " to "
+ DeflaterConstants.COMPR_FUNC[level]);
}
#endif
switch (compressionFunction) {
case DEFLATE_STORED:
if (strstart > blockStart) {
huffman.FlushStoredBlock(window, blockStart,
strstart - blockStart, false);
blockStart = strstart;
}
UpdateHash();
break;
case DEFLATE_FAST:
if (strstart > blockStart) {
huffman.FlushBlock(window, blockStart, strstart - blockStart,
false);
blockStart = strstart;
}
break;
case DEFLATE_SLOW:
if (prevAvailable) {
huffman.TallyLit(window[strstart-1] & 0xff);
}
if (strstart > blockStart) {
huffman.FlushBlock(window, blockStart, strstart - blockStart, false);
blockStart = strstart;
}
prevAvailable = false;
matchLen = MIN_MATCH - 1;
break;
}
compressionFunction = COMPR_FUNC[level];
}
}
/// <summary>
/// Fill the window
/// </summary>
public void FillWindow()
{
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (strstart >= WSIZE + MAX_DIST)
{
SlideWindow();
}
/* If there is not enough lookahead, but still some input left,
* read in the input
*/
while (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd)
{
int more = 2 * WSIZE - lookahead - strstart;
if (more > inputEnd - inputOff)
{
more = inputEnd - inputOff;
}
System.Array.Copy(inputBuf, inputOff, window, strstart + lookahead, more);
adler.Update(inputBuf, inputOff, more);
inputOff += more;
totalIn += more;
lookahead += more;
}
if (lookahead >= MIN_MATCH)
{
UpdateHash();
}
}
void UpdateHash()
{
/*
if (DEBUGGING) {
Console.WriteLine("updateHash: "+strstart);
}
*/
ins_h = (window[strstart] << HASH_SHIFT) ^ window[strstart + 1];
}
/// <summary>
/// Inserts the current string in the head hash and returns the previous
/// value for this hash.
/// </summary>
/// <returns>The previous hash value</returns>
int InsertString()
{
short match;
int hash = ((ins_h << HASH_SHIFT) ^ window[strstart + (MIN_MATCH -1)]) & HASH_MASK;
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
if (hash != (((window[strstart] << (2*HASH_SHIFT)) ^
(window[strstart + 1] << HASH_SHIFT) ^
(window[strstart + 2])) & HASH_MASK)) {
throw new SharpZipBaseException("hash inconsistent: " + hash + "/"
+window[strstart] + ","
+window[strstart + 1] + ","
+window[strstart + 2] + "," + HASH_SHIFT);
}
}
#endif
prev[strstart & WMASK] = match = head[hash];
head[hash] = unchecked((short)strstart);
ins_h = hash;
return match & 0xffff;
}
void SlideWindow()
{
Array.Copy(window, WSIZE, window, 0, WSIZE);
matchStart -= WSIZE;
strstart -= WSIZE;
blockStart -= WSIZE;
// Slide the hash table (could be avoided with 32 bit values
// at the expense of memory usage).
for (int i = 0; i < HASH_SIZE; ++i) {
int m = head[i] & 0xffff;
head[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0);
}
// Slide the prev table.
for (int i = 0; i < WSIZE; i++) {
int m = prev[i] & 0xffff;
prev[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0);
}
}
/// <summary>
/// Find the best (longest) string in the window matching the
/// string starting at strstart.
///
/// Preconditions:
/// <code>
/// strstart + MAX_MATCH <= window.length.</code>
/// </summary>
/// <param name="curMatch"></param>
/// <returns>True if a match greater than the minimum length is found</returns>
bool FindLongestMatch(int curMatch)
{
int chainLength = this.max_chain;
int niceLength = this.niceLength;
short[] prev = this.prev;
int scan = this.strstart;
int match;
int best_end = this.strstart + matchLen;
int best_len = Math.Max(matchLen, MIN_MATCH - 1);
int limit = Math.Max(strstart - MAX_DIST, 0);
int strend = strstart + MAX_MATCH - 1;
byte scan_end1 = window[best_end - 1];
byte scan_end = window[best_end];
// Do not waste too much time if we already have a good match:
if (best_len >= this.goodLength) {
chainLength >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (niceLength > lookahead) {
niceLength = lookahead;
}
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (strstart > 2 * WSIZE - MIN_LOOKAHEAD))
{
throw new InvalidOperationException("need lookahead");
}
#endif
do {
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (curMatch >= strstart) )
{
throw new InvalidOperationException("no future");
}
#endif
if (window[curMatch + best_len] != scan_end ||
window[curMatch + best_len - 1] != scan_end1 ||
window[curMatch] != window[scan] ||
window[curMatch + 1] != window[scan + 1]) {
continue;
}
match = curMatch + 2;
scan += 2;
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart + 258.
*/
while (
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
(scan < strend))
{
// Do nothing
}
if (scan > best_end) {
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (ins_h == 0) )
Console.Error.WriteLine("Found match: " + curMatch + "-" + (scan - strstart));
#endif
matchStart = curMatch;
best_end = scan;
best_len = scan - strstart;
if (best_len >= niceLength) {
break;
}
scan_end1 = window[best_end - 1];
scan_end = window[best_end];
}
scan = strstart;
} while ((curMatch = (prev[curMatch & WMASK] & 0xffff)) > limit && --chainLength != 0);
matchLen = Math.Min(best_len, lookahead);
return matchLen >= MIN_MATCH;
}
bool DeflateStored(bool flush, bool finish)
{
if (!flush && (lookahead == 0)) {
return false;
}
strstart += lookahead;
lookahead = 0;
int storedLength = strstart - blockStart;
if ((storedLength >= DeflaterConstants.MAX_BLOCK_SIZE) || // Block is full
(blockStart < WSIZE && storedLength >= MAX_DIST) || // Block may move out of window
flush) {
bool lastBlock = finish;
if (storedLength > DeflaterConstants.MAX_BLOCK_SIZE) {
storedLength = DeflaterConstants.MAX_BLOCK_SIZE;
lastBlock = false;
}
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
Console.WriteLine("storedBlock[" + storedLength + "," + lastBlock + "]");
}
#endif
huffman.FlushStoredBlock(window, blockStart, storedLength, lastBlock);
blockStart += storedLength;
return !lastBlock;
}
return true;
}
bool DeflateFast(bool flush, bool finish)
{
if (lookahead < MIN_LOOKAHEAD && !flush) {
return false;
}
while (lookahead >= MIN_LOOKAHEAD || flush) {
if (lookahead == 0) {
// We are flushing everything
huffman.FlushBlock(window, blockStart, strstart - blockStart, finish);
blockStart = strstart;
return false;
}
if (strstart > 2 * WSIZE - MIN_LOOKAHEAD) {
/* slide window, as FindLongestMatch needs this.
* This should only happen when flushing and the window
* is almost full.
*/
SlideWindow();
}
int hashHead;
if (lookahead >= MIN_MATCH &&
(hashHead = InsertString()) != 0 &&
strategy != DeflateStrategy.HuffmanOnly &&
strstart - hashHead <= MAX_DIST &&
FindLongestMatch(hashHead)) {
// longestMatch sets matchStart and matchLen
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
for (int i = 0 ; i < matchLen; i++) {
if (window[strstart + i] != window[matchStart + i]) {
throw new SharpZipBaseException("Match failure");
}
}
}
#endif
bool full = huffman.TallyDist(strstart - matchStart, matchLen);
lookahead -= matchLen;
if (matchLen <= max_lazy && lookahead >= MIN_MATCH) {
while (--matchLen > 0) {
++strstart;
InsertString();
}
++strstart;
} else {
strstart += matchLen;
if (lookahead >= MIN_MATCH - 1) {
UpdateHash();
}
}
matchLen = MIN_MATCH - 1;
if (!full) {
continue;
}
} else {
// No match found
huffman.TallyLit(window[strstart] & 0xff);
++strstart;
--lookahead;
}
if (huffman.IsFull()) {
bool lastBlock = finish && (lookahead == 0);
huffman.FlushBlock(window, blockStart, strstart - blockStart, lastBlock);
blockStart = strstart;
return !lastBlock;
}
}
return true;
}
bool DeflateSlow(bool flush, bool finish)
{
if (lookahead < MIN_LOOKAHEAD && !flush) {
return false;
}
while (lookahead >= MIN_LOOKAHEAD || flush) {
if (lookahead == 0) {
if (prevAvailable) {
huffman.TallyLit(window[strstart-1] & 0xff);
}
prevAvailable = false;
// We are flushing everything
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && !flush)
{
throw new SharpZipBaseException("Not flushing, but no lookahead");
}
#endif
huffman.FlushBlock(window, blockStart, strstart - blockStart,
finish);
blockStart = strstart;
return false;
}
if (strstart >= 2 * WSIZE - MIN_LOOKAHEAD) {
/* slide window, as FindLongestMatch needs this.
* This should only happen when flushing and the window
* is almost full.
*/
SlideWindow();
}
int prevMatch = matchStart;
int prevLen = matchLen;
if (lookahead >= MIN_MATCH) {
int hashHead = InsertString();
if (strategy != DeflateStrategy.HuffmanOnly &&
hashHead != 0 &&
strstart - hashHead <= MAX_DIST &&
FindLongestMatch(hashHead)) {
// longestMatch sets matchStart and matchLen
// Discard match if too small and too far away
if (matchLen <= 5 && (strategy == DeflateStrategy.Filtered || (matchLen == MIN_MATCH && strstart - matchStart > TooFar))) {
matchLen = MIN_MATCH - 1;
}
}
}
// previous match was better
if ((prevLen >= MIN_MATCH) && (matchLen <= prevLen) ) {
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
for (int i = 0 ; i < matchLen; i++) {
if (window[strstart-1+i] != window[prevMatch + i])
throw new SharpZipBaseException();
}
}
#endif
huffman.TallyDist(strstart - 1 - prevMatch, prevLen);
prevLen -= 2;
do {
strstart++;
lookahead--;
if (lookahead >= MIN_MATCH) {
InsertString();
}
} while (--prevLen > 0);
strstart ++;
lookahead--;
prevAvailable = false;
matchLen = MIN_MATCH - 1;
} else {
if (prevAvailable) {
huffman.TallyLit(window[strstart-1] & 0xff);
}
prevAvailable = true;
strstart++;
lookahead--;
}
if (huffman.IsFull()) {
int len = strstart - blockStart;
if (prevAvailable) {
len--;
}
bool lastBlock = (finish && (lookahead == 0) && !prevAvailable);
huffman.FlushBlock(window, blockStart, len, lastBlock);
blockStart += len;
return !lastBlock;
}
}
return true;
}
#region Instance Fields
// Hash index of string to be inserted
int ins_h;
/// <summary>
/// Hashtable, hashing three characters to an index for window, so
/// that window[index]..window[index+2] have this hash code.
/// Note that the array should really be unsigned short, so you need
/// to and the values with 0xffff.
/// </summary>
short[] head;
/// <summary>
/// <code>prev[index & WMASK]</code> points to the previous index that has the
/// same hash code as the string starting at index. This way
/// entries with the same hash code are in a linked list.
/// Note that the array should really be unsigned short, so you need
/// to and the values with 0xffff.
/// </summary>
short[] prev;
int matchStart;
// Length of best match
int matchLen;
// Set if previous match exists
bool prevAvailable;
int blockStart;
/// <summary>
/// Points to the current character in the window.
/// </summary>
int strstart;
/// <summary>
/// lookahead is the number of characters starting at strstart in
/// window that are valid.
/// So window[strstart] until window[strstart+lookahead-1] are valid
/// characters.
/// </summary>
int lookahead;
/// <summary>
/// This array contains the part of the uncompressed stream that
/// is of relevance. The current character is indexed by strstart.
/// </summary>
byte[] window;
DeflateStrategy strategy;
int max_chain, max_lazy, niceLength, goodLength;
/// <summary>
/// The current compression function.
/// </summary>
int compressionFunction;
/// <summary>
/// The input data for compression.
/// </summary>
byte[] inputBuf;
/// <summary>
/// The total bytes of input read.
/// </summary>
long totalIn;
/// <summary>
/// The offset into inputBuf, where input data starts.
/// </summary>
int inputOff;
/// <summary>
/// The end offset of the input data.
/// </summary>
int inputEnd;
DeflaterPending pending;
DeflaterHuffman huffman;
/// <summary>
/// The adler checksum
/// </summary>
Adler32 adler;
#endregion
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: SortedDictionary.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Dot42.Collections;
using Java.Util;
namespace System.Collections.Generic
{
public class SortedDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
internal readonly TreeMap<TKey, TValue> map;
/// <summary>
/// Default ctor
/// </summary>
public SortedDictionary()
{
map = new TreeMap<TKey, TValue>();
}
/// <summary>
/// Gets the number of elements
/// </summary>
public int Count { get { return map.Size(); } }
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public TValue this[TKey key]
{
get
{
if (map.ContainsKey(key))
return map.Get(key);
throw new KeyNotFoundException();
}
set { map.Put(key, value); }
}
/// <summary>
/// Add the given key and value to the dictionary.
/// </summary>
public void Add(TKey key, TValue value)
{
map.Put(key, value);
}
/// <summary>
/// Removes the given key from the dictionary.
/// </summary>
public void Remove(TKey key)
{
map.Remove(key);
}
/// <summary>
/// Remove all entries
/// </summary>
public void Clear()
{
map.Clear();
}
/// <summary>
/// Does this dictionary contain an element with given key?
/// </summary>
public bool ContainsKey(TKey key)
{
return map.ContainsKey(key);
}
/// <summary>
/// Does this dictionary contain an element with given key?
/// </summary>
public bool ContainsValue(TValue value)
{
return map.ContainsValue(value);
}
/// <summary>
/// Try to get a value from this dictionary.
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
if (map.ContainsKey(key))
{
value = map.Get(key);
return true;
}
value = default(TValue);
return false;
}
/// <summary>
/// Copies the elements of the SortedDictionary to the specified array
/// of KeyValuePair structures, starting at the specified index.
/// </summary>
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
foreach (var keyValue in this)
{
array[index++] = keyValue;
}
}
/// <summary>
/// Gets the comparer used to compare keys.
/// </summary>
public IEqualityComparer<TKey> Comparer
{
get { throw new NotImplementedException("System.Collections.Generic.SortedDictionary<,>.Comparer"); }
}
/// <summary>
/// Gets an enummerator to enumerate over all elements in this sequence.
/// </summary>
/// <returns></returns>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
foreach (var entry in new IterableWrapper<IMap_IEntry<TKey, TValue>>(map.EntrySet()))
{
yield return new KeyValuePair<TKey, TValue>(entry.GetKey(), entry.GetValue());
}
}
/// <summary>
/// Gets an enummerator to enumerate over all elements in this sequence.
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Gets the keys of the collection.
/// </summary>
public KeyCollection Keys
{
get { return new KeyCollection(this); }
}
/// <summary>
/// Gets the values of the collection.
/// </summary>
public ValueCollection Values
{
get { return new ValueCollection(this); }
}
public sealed class KeyCollection : ICollection<TKey>
{
private readonly Java.Util.ICollection<TKey> keys;
/// <summary>
/// Default ctor
/// </summary>
public KeyCollection(SortedDictionary<TKey, TValue> dictionary)
{
keys = dictionary.map.KeySet();
}
/// <summary>
/// Gets an enummerator to enumerate over all elements in this sequence.
/// </summary>
/// <returns></returns>
public IEnumerator<TKey> GetEnumerator()
{
return new IteratorWrapper<TKey>(keys);
}
/// <summary>
/// Gets an enummerator to enumerate over all elements in this sequence.
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public int Count
{
get { return keys.Size(); }
}
public bool IsReadOnly
{
get { return true; }
}
public void Add(TKey item)
{
keys.Add(item);
}
public void Clear()
{
keys.Clear();
}
public bool Contains(TKey item)
{
return keys.Contains(item);
}
public bool Remove(TKey item)
{
return keys.Remove(item);
}
public void CopyTo(TKey[] array, int index)
{
throw new NotImplementedException("System.Collections.Generic.SortedDictionary<,>.KeyCollection.CopyTo");
}
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get { throw new NotImplementedException("System.Collections.Generic.SortedDictionary<,>.KeyCollection.SyncRoot"); }
}
public void CopyTo(Array array, int index)
{
throw new NotImplementedException("System.Collections.Generic.SortedDictionary<,>.KeyCollection.CopyTo");
}
}
public sealed class ValueCollection : ICollection<TValue>
{
private readonly Java.Util.ICollection<TValue> values;
/// <summary>
/// Default ctor
/// </summary>
public ValueCollection(SortedDictionary<TKey, TValue> dictionary)
{
values = dictionary.map.Values();
}
/// <summary>
/// Gets an enummerator to enumerate over all elements in this sequence.
/// </summary>
/// <returns></returns>
public IEnumerator<TValue> GetEnumerator()
{
return new IteratorWrapper<TValue>(values);
}
/// <summary>
/// Gets an enummerator to enumerate over all elements in this sequence.
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public int Count
{
get { return values.Size(); }
}
public bool IsReadOnly
{
get { return true; }
}
public void Add(TValue item)
{
values.Add(item);
}
public void Clear()
{
values.Clear();
}
public bool Contains(TValue item)
{
return values.Contains(item);
}
public bool Remove(TValue item)
{
return values.Remove(item);
}
public void CopyTo(TValue[] array, int index)
{
throw new NotImplementedException("System.Collections.Generic.SortedDictionary<,>.ValueCollection.CopyTo");
}
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get { throw new NotImplementedException("System.Collections.Generic.SortedDictionary<,>.ValueCollection.SyncRoot"); }
}
public void CopyTo(Array array, int index)
{
throw new NotImplementedException("System.Collections.Generic.SortedDictionary<,>.ValueCollection.CopyTo");
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace WebApiQuickstart.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace System.Net
{
internal class Logging
{
private static volatile bool s_LoggingEnabled = true;
private static volatile bool s_LoggingInitialized;
private const int DefaultMaxDumpSize = 1024;
private const bool DefaultUseProtocolTextOnly = false;
private const string AttributeNameMaxSize = "maxdatasize";
private const string AttributeNameTraceMode = "tracemode";
private static readonly string[] s_supportedAttributes = new string[] { AttributeNameMaxSize, AttributeNameTraceMode };
private const string AttributeValueProtocolOnly = "protocolonly";
private const string TraceSourceWebName = "System.Net";
private const string TraceSourceHttpListenerName = "System.Net.HttpListener";
private const string TraceSourceSocketsName = "System.Net.Sockets";
private const string TraceSourceWebSocketsName = "System.Net.WebSockets";
private const string TraceSourceCacheName = "System.Net.Cache";
private const string TraceSourceHttpName = "System.Net.Http";
private static TraceSource s_WebTraceSource;
private static TraceSource s_HttpListenerTraceSource;
private static TraceSource s_SocketsTraceSource;
private static TraceSource s_WebSocketsTraceSource;
private static TraceSource s_CacheTraceSource;
private static TraceSource s_TraceSourceHttpName;
private Logging()
{
}
private static object s_InternalSyncObject;
private static object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
object o = new Object();
Interlocked.CompareExchange(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
internal static bool On
{
get
{
if (!s_LoggingInitialized)
{
InitializeLogging();
}
return s_LoggingEnabled;
}
}
internal static bool IsVerbose(TraceSource traceSource)
{
return ValidateSettings(traceSource, TraceEventType.Verbose);
}
internal static TraceSource Web
{
get
{
if (!s_LoggingInitialized)
{
InitializeLogging();
}
if (!s_LoggingEnabled)
{
return null;
}
return s_WebTraceSource;
}
}
internal static TraceSource Http
{
get
{
if (!s_LoggingInitialized)
{
InitializeLogging();
}
if (!s_LoggingEnabled)
{
return null;
}
return s_TraceSourceHttpName;
}
}
internal static TraceSource HttpListener
{
get
{
if (!s_LoggingInitialized)
{
InitializeLogging();
}
if (!s_LoggingEnabled)
{
return null;
}
return s_HttpListenerTraceSource;
}
}
internal static TraceSource Sockets
{
get
{
if (!s_LoggingInitialized)
{
InitializeLogging();
}
if (!s_LoggingEnabled)
{
return null;
}
return s_SocketsTraceSource;
}
}
internal static TraceSource RequestCache
{
get
{
if (!s_LoggingInitialized)
{
InitializeLogging();
}
if (!s_LoggingEnabled)
{
return null;
}
return s_CacheTraceSource;
}
}
internal static TraceSource WebSockets
{
get
{
if (!s_LoggingInitialized)
{
InitializeLogging();
}
if (!s_LoggingEnabled)
{
return null;
}
return s_WebSocketsTraceSource;
}
}
private static bool GetUseProtocolTextSetting(TraceSource traceSource)
{
return DefaultUseProtocolTextOnly;
}
private static int GetMaxDumpSizeSetting(TraceSource traceSource)
{
return DefaultMaxDumpSize;
}
// Sets up internal config settings for logging.
private static void InitializeLogging()
{
lock (InternalSyncObject)
{
if (!s_LoggingInitialized)
{
bool loggingEnabled = false;
s_WebTraceSource = new NclTraceSource(TraceSourceWebName);
s_HttpListenerTraceSource = new NclTraceSource(TraceSourceHttpListenerName);
s_SocketsTraceSource = new NclTraceSource(TraceSourceSocketsName);
s_WebSocketsTraceSource = new NclTraceSource(TraceSourceWebSocketsName);
s_CacheTraceSource = new NclTraceSource(TraceSourceCacheName);
s_TraceSourceHttpName = new NclTraceSource(TraceSourceHttpName);
GlobalLog.Print("Initalizating tracing");
try
{
loggingEnabled = (s_WebTraceSource.Switch.ShouldTrace(TraceEventType.Critical) ||
s_HttpListenerTraceSource.Switch.ShouldTrace(TraceEventType.Critical) ||
s_SocketsTraceSource.Switch.ShouldTrace(TraceEventType.Critical) ||
s_WebSocketsTraceSource.Switch.ShouldTrace(TraceEventType.Critical) ||
s_CacheTraceSource.Switch.ShouldTrace(TraceEventType.Critical) ||
s_TraceSourceHttpName.Switch.ShouldTrace(TraceEventType.Critical));
}
catch (SecurityException)
{
// These may throw if the caller does not have permission to hook up trace listeners.
// We treat this case as though logging were disabled.
Close();
loggingEnabled = false;
}
s_LoggingEnabled = loggingEnabled;
s_LoggingInitialized = true;
}
}
}
private static void Close()
{
if (s_WebTraceSource != null)
{
s_WebTraceSource.Close();
}
if (s_HttpListenerTraceSource != null)
{
s_HttpListenerTraceSource.Close();
}
if (s_SocketsTraceSource != null)
{
s_SocketsTraceSource.Close();
}
if (s_WebSocketsTraceSource != null)
{
s_WebSocketsTraceSource.Close();
}
if (s_CacheTraceSource != null)
{
s_CacheTraceSource.Close();
}
if (s_TraceSourceHttpName != null)
{
s_TraceSourceHttpName.Close();
}
}
// Confirms logging is enabled, given current logging settings
private static bool ValidateSettings(TraceSource traceSource, TraceEventType traceLevel)
{
if (!s_LoggingEnabled)
{
return false;
}
if (!s_LoggingInitialized)
{
InitializeLogging();
}
if (traceSource == null || !traceSource.Switch.ShouldTrace(traceLevel))
{
return false;
}
return true;
}
// Converts an object to a normalized string that can be printed
// takes System.Net.ObjectNamedFoo and coverts to ObjectNamedFoo,
// except IPAddress, IPEndPoint, and Uri, which return ToString().
private static string GetObjectName(object obj)
{
if (obj is Uri || obj is System.Net.IPAddress || obj is System.Net.IPEndPoint)
{
return obj.ToString();
}
else
{
return obj.GetType().Name;
}
}
internal static void PrintLine(TraceSource traceSource, TraceEventType eventType, int id, string msg)
{
string logHeader = "[" + Environment.CurrentManagedThreadId.ToString("d4", CultureInfo.InvariantCulture) + "] ";
traceSource.TraceEvent(eventType, id, logHeader + msg);
}
internal static void Associate(TraceSource traceSource, object objA, object objB)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
string lineA = GetObjectName(objA) + "#" + Logging.HashString(objA);
string lineB = GetObjectName(objB) + "#" + Logging.HashString(objB);
PrintLine(traceSource, TraceEventType.Information, 0, "Associating " + lineA + " with " + lineB);
}
internal static void Enter(TraceSource traceSource, object obj, string method, string param)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
Enter(traceSource, GetObjectName(obj) + "#" + Logging.HashString(obj), method, param);
}
internal static void Enter(TraceSource traceSource, object obj, string method, object paramObject)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
Enter(traceSource, GetObjectName(obj) + "#" + Logging.HashString(obj), method, paramObject);
}
internal static void Enter(TraceSource traceSource, string obj, string method, string param)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
Enter(traceSource, obj + "::" + method + "(" + param + ")");
}
internal static void Enter(TraceSource traceSource, string obj, string method, object paramObject)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
string paramObjectValue = "";
if (paramObject != null)
{
paramObjectValue = GetObjectName(paramObject) + "#" + Logging.HashString(paramObject);
}
Enter(traceSource, obj + "::" + method + "(" + paramObjectValue + ")");
}
internal static void Enter(TraceSource traceSource, string method, string parameters)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
Enter(traceSource, method + "(" + parameters + ")");
}
internal static void Enter(TraceSource traceSource, string msg)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
// Trace.CorrelationManager.StartLogicalOperation();
PrintLine(traceSource, TraceEventType.Verbose, 0, msg);
}
internal static void Exit(TraceSource traceSource, object obj, string method, object retObject)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
string retValue = "";
if (retObject != null)
{
retValue = GetObjectName(retObject) + "#" + Logging.HashString(retObject);
}
Exit(traceSource, obj, method, retValue);
}
internal static void Exit(TraceSource traceSource, string obj, string method, object retObject)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
string retValue = "";
if (retObject != null)
{
retValue = GetObjectName(retObject) + "#" + Logging.HashString(retObject);
}
Exit(traceSource, obj, method, retValue);
}
internal static void Exit(TraceSource traceSource, object obj, string method, string retValue)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
Exit(traceSource, GetObjectName(obj) + "#" + Logging.HashString(obj), method, retValue);
}
internal static void Exit(TraceSource traceSource, string obj, string method, string retValue)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
if (!string.IsNullOrEmpty(retValue))
{
retValue = "\t-> " + retValue;
}
Exit(traceSource, obj + "::" + method + "() " + retValue);
}
internal static void Exit(TraceSource traceSource, string method, string parameters)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
Exit(traceSource, method + "() " + parameters);
}
internal static void Exit(TraceSource traceSource, string msg)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
PrintLine(traceSource, TraceEventType.Verbose, 0, "Exiting " + msg);
// Trace.CorrelationManager.StopLogicalOperation();
}
internal static void Exception(TraceSource traceSource, object obj, string method, Exception e)
{
if (!ValidateSettings(traceSource, TraceEventType.Error))
{
return;
}
string infoLine = SR.Format(SR.net_log_exception, GetObjectLogHash(obj), method, e.Message);
if (!string.IsNullOrEmpty(e.StackTrace))
{
infoLine += Environment.NewLine + e.StackTrace;
}
PrintLine(traceSource, TraceEventType.Error, 0, infoLine);
}
internal static void PrintInfo(TraceSource traceSource, string msg)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
PrintLine(traceSource, TraceEventType.Information, 0, msg);
}
internal static void PrintInfo(TraceSource traceSource, object obj, string msg)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
PrintLine(traceSource, TraceEventType.Information, 0,
GetObjectName(obj) + "#" + Logging.HashString(obj)
+ " - " + msg);
}
internal static void PrintInfo(TraceSource traceSource, object obj, string method, string param)
{
if (!ValidateSettings(traceSource, TraceEventType.Information))
{
return;
}
PrintLine(traceSource, TraceEventType.Information, 0,
GetObjectName(obj) + "#" + Logging.HashString(obj)
+ "::" + method + "(" + param + ")");
}
internal static void PrintWarning(TraceSource traceSource, string msg)
{
if (!ValidateSettings(traceSource, TraceEventType.Warning))
{
return;
}
PrintLine(traceSource, TraceEventType.Warning, 0, msg);
}
internal static void PrintWarning(TraceSource traceSource, object obj, string method, string msg)
{
if (!ValidateSettings(traceSource, TraceEventType.Warning))
{
return;
}
PrintLine(traceSource, TraceEventType.Warning, 0,
GetObjectName(obj) + "#" + Logging.HashString(obj)
+ "::" + method + "() - " + msg);
}
internal static void PrintError(TraceSource traceSource, string msg)
{
if (!ValidateSettings(traceSource, TraceEventType.Error))
{
return;
}
PrintLine(traceSource, TraceEventType.Error, 0, msg);
}
internal static void PrintError(TraceSource traceSource, object obj, string method, string msg)
{
if (!ValidateSettings(traceSource, TraceEventType.Error))
{
return;
}
PrintLine(traceSource, TraceEventType.Error, 0,
GetObjectName(obj) + "#" + Logging.HashString(obj)
+ "::" + method + "() - " + msg);
}
internal static string GetObjectLogHash(object obj)
{
return GetObjectName(obj) + "#" + Logging.HashString(obj);
}
internal static void Dump(TraceSource traceSource, object obj, string method, IntPtr bufferPtr, int length)
{
if (!ValidateSettings(traceSource, TraceEventType.Verbose) || bufferPtr == IntPtr.Zero || length < 0)
{
return;
}
byte[] buffer = new byte[length];
Marshal.Copy(bufferPtr, buffer, 0, length);
Dump(traceSource, obj, method, buffer, 0, length);
}
internal static void Dump(TraceSource traceSource, object obj, string method, byte[] buffer, int offset, int length)
{
if (!ValidateSettings(traceSource, TraceEventType.Verbose))
{
return;
}
if (buffer == null)
{
PrintLine(traceSource, TraceEventType.Verbose, 0, "(null)");
return;
}
if (offset > buffer.Length)
{
PrintLine(traceSource, TraceEventType.Verbose, 0, "(offset out of range)");
return;
}
PrintLine(traceSource, TraceEventType.Verbose, 0, "Data from " + GetObjectName(obj) + "#" + Logging.HashString(obj) + "::" + method);
int maxDumpSize = GetMaxDumpSizeSetting(traceSource);
if (length > maxDumpSize)
{
PrintLine(traceSource, TraceEventType.Verbose, 0, "(printing " + maxDumpSize.ToString(NumberFormatInfo.InvariantInfo) + " out of " + length.ToString(NumberFormatInfo.InvariantInfo) + ")");
length = maxDumpSize;
}
if ((length < 0) || (length > buffer.Length - offset))
{
length = buffer.Length - offset;
}
do
{
int n = Math.Min(length, 16);
string disp = string.Format(CultureInfo.CurrentCulture, "{0:X8} : ", offset);
for (int i = 0; i < n; ++i)
{
disp += string.Format(CultureInfo.CurrentCulture, "{0:X2}", buffer[offset + i]) + ((i == 7) ? '-' : ' ');
}
for (int i = n; i < 16; ++i)
{
disp += " ";
}
disp += ": ";
for (int i = 0; i < n; ++i)
{
disp += ((buffer[offset + i] < 0x20) || (buffer[offset + i] > 0x7e))
? '.'
: (char)(buffer[offset + i]);
}
PrintLine(traceSource, TraceEventType.Verbose, 0, disp);
offset += n;
length -= n;
} while (length > 0);
}
internal static string ObjectToString(object objectValue)
{
if (objectValue == null)
{
return "(null)";
}
else if (objectValue is string && ((string)objectValue).Length == 0)
{
return "(string.empty)";
}
else if (objectValue is Exception)
{
return ExceptionMessage(objectValue as Exception);
}
else if (objectValue is IntPtr)
{
return "0x" + ((IntPtr)objectValue).ToString("x");
}
else
{
return objectValue.ToString();
}
}
internal static string HashString(object objectValue)
{
if (objectValue == null)
{
return "(null)";
}
else if (objectValue is string && ((string)objectValue).Length == 0)
{
return "(string.empty)";
}
else
{
return objectValue.GetHashCode().ToString(NumberFormatInfo.InvariantInfo);
}
}
private static string ExceptionMessage(Exception exception)
{
if (exception == null)
{
return string.Empty;
}
if (exception.InnerException == null)
{
return exception.Message;
}
return exception.Message + " (" + ExceptionMessage(exception.InnerException) + ")";
}
private class NclTraceSource : TraceSource
{
internal NclTraceSource(string name) : base(name) { }
protected internal string[] GetSupportedAttributes()
{
return Logging.s_supportedAttributes;
}
}
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software; you can redistribute it and/or modify
* it under the terms of The MIT License (MIT).
*
* You should have received a copy of the MIT License
* along with SharpNEAT; if not, see https://opensource.org/licenses/MIT.
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using SharpNeat.Core;
namespace SharpNeat.DistanceMetrics
{
/// <summary>
/// Manhattan distance metric.
///
/// The Manhattan distance is simply the sum total of all of the distances in each dimension.
/// Also known as the taxicab distance, rectilinear distance, L1 distance or L1 norm.
///
/// Use the default constructor for classical Manhattan Distance.
/// Optionally the constructor can be provided with a two coefficients and a constant that can be used to modify/distort
/// distance measures. These are:
///
/// matchDistanceCoeff - When comparing two positions in the same dimension the distance between those two position is
/// multiplied by this coefficient.
///
/// mismatchDistanceCoeff, mismatchDistanceConstant - When comparing two coordinates where one describes a position in a given
/// dimension and the other does not then the second coordinate is assumed to be at position zero in that dimension. However,
/// the resulting distance is multiplied by this coefficient and mismatchDistanceConstant is added, therefore allowing matches and
/// mismatches to be weighted differently, e.g. more emphasis can be placed on mismatches (and therefore network topology).
/// If mismatchDistanceCoeff is zero and mismatchDistanceConstant is non-zero then the distance of mismatches is a fixed value.
///
/// The two coefficients and constant allow the following schemes:
///
/// 1) Classical Manhattan distance.
/// 2) Topology only distance metric (ignore connections weights).
/// 3) Equivalent of genome distance in Original NEAT (O-NEAT). This is actually a mix of (1) and (2).
/// </summary>
public class ManhattanDistanceMetric : IDistanceMetric
{
/// <summary>A coefficient to applied to the distance obtained from two coordinates that both
/// describe a position in a given dimension.</summary>
readonly double _matchDistanceCoeff;
/// <summary>A coefficient applied to the distance obtained from two coordinates where only one of the coordinates describes
/// a position in a given dimension. The other point is taken to be at position zero in that dimension.</summary>
readonly double _mismatchDistanceCoeff;
/// <summary>A constant that is added to the distance where only one of the coordinates describes a position in a given dimension.
/// This adds extra emphasis to distance when comparing coordinates that exist in different dimensions.</summary>
readonly double _mismatchDistanceConstant;
#region Constructors
/// <summary>
/// Constructs using default weightings for comparisons on matching and mismatching dimensions.
/// Classical Manhattan Distance.
/// </summary>
public ManhattanDistanceMetric() : this(1.0, 1.0, 0.0)
{
}
/// <summary>
/// Constructs using the provided weightings for comparisons on matching and mismatching dimensions.
/// </summary>
/// <param name="matchDistanceCoeff">A coefficient to applied to the distance obtained from two coordinates that both
/// describe a position in a given dimension.</param>
/// <param name="mismatchDistanceCoeff">A coefficient applied to the distance obtained from two coordinates where only one of the coordinates describes
/// a position in a given dimension. The other point is taken to be at position zero in that dimension.</param>
/// <param name="mismatchDistanceConstant">A constant that is added to the distance where only one of the coordinates describes a position in a given dimension.
/// This adds extra emphasis to distance when comparing coordinates that exist in different dimensions.</param>
public ManhattanDistanceMetric(double matchDistanceCoeff, double mismatchDistanceCoeff, double mismatchDistanceConstant)
{
_matchDistanceCoeff = matchDistanceCoeff;
_mismatchDistanceCoeff = mismatchDistanceCoeff;
_mismatchDistanceConstant = mismatchDistanceConstant;
}
#endregion
#region IDistanceMetric Members
/// <summary>
/// Tests if the distance between two positions is less than some threshold.
///
/// A simple way of implementing this method would be to calculate the distance between the
/// two coordinates and test if it is less than the threshold. However, that approach requires that all of the
/// elements in both CoordinateVectors be fully compared. We can improve performance in the general case
/// by testing if the threshold has been passed after each vector element comparison thus allowing an early exit
/// from the method for many calls. Further to this, we can begin comparing from the ends of the vectors where
/// differences are most likely to occur.
/// </summary>
public bool TestDistance(CoordinateVector p1, CoordinateVector p2, double threshold)
{
KeyValuePair<ulong,double>[] arr1 = p1.CoordArray;
KeyValuePair<ulong,double>[] arr2 = p2.CoordArray;
// Store these heavily used values locally.
int arr1Length = arr1.Length;
int arr2Length = arr2.Length;
//--- Test for special cases.
if(0 == arr1Length && 0 == arr2Length)
{ // Both arrays are empty. No disparities, therefore the distance is zero.
return 0.0 < threshold;
}
double distance = 0.0;
if(0 == arr1Length)
{ // All arr2 elements are mismatches.
// p1 doesn't specify a value in these dimensions therefore we take its position to be 0 in all of them.
for(int i=0; i<arr2Length; i++) {
distance += Math.Abs(arr2[i].Value);
}
distance = (_mismatchDistanceConstant * arr2Length) + (distance * _mismatchDistanceCoeff);
return distance < threshold;
}
if(0 == arr2Length)
{ // All arr1 elements are mismatches.
// p2 doesn't specify a value in these dimensions therefore we take it's position to be 0 in all of them.
for(int i=0; i<arr1Length; i++) {
distance += Math.Abs(arr1[i].Value);
}
distance = (_mismatchDistanceConstant * arr1Length) + (distance * _mismatchDistanceCoeff);
return distance < threshold;
}
//----- Both arrays contain elements. Compare the contents starting from the ends where the greatest discrepancies
// between coordinates are expected to occur. In the general case this should result in less element comparisons
// before the threshold is passed and we exit the method.
int arr1Idx = arr1Length - 1;
int arr2Idx = arr2Length - 1;
KeyValuePair<ulong,double> elem1 = arr1[arr1Idx];
KeyValuePair<ulong,double> elem2 = arr2[arr2Idx];
for(;;)
{
if(elem2.Key > elem1.Key)
{
// p1 doesn't specify a value in this dimension therefore we take it's position to be 0.
distance += _mismatchDistanceConstant + (Math.Abs(elem2.Value) * _mismatchDistanceCoeff);
// Move to the next element in arr2.
arr2Idx--;
}
else if(elem1.Key == elem2.Key)
{
// Matching elements.
distance += Math.Abs(elem1.Value - elem2.Value) * _matchDistanceCoeff;
// Move to the next element in both arrays.
arr1Idx--;
arr2Idx--;
}
else // elem1.Key > elem2.Key
{
// p2 doesn't specify a value in this dimension therefore we take it's position to be 0.
distance += _mismatchDistanceConstant + (Math.Abs(elem1.Value) * _mismatchDistanceCoeff);
// Move to the next element in arr1.
arr1Idx--;
}
// Test the threshold.
if(distance >= threshold) {
return false;
}
// Check if we have exhausted one or both of the arrays.
if(arr1Idx < 0)
{ // Any remaining arr2 elements are mismatches.
for(int i=arr2Idx; i >- 1; i--) {
distance += _mismatchDistanceConstant + (Math.Abs(arr2[i].Value) * _mismatchDistanceCoeff);
}
return distance < threshold;
}
if(arr2Idx < 0)
{ // All remaining arr1 elements are mismatches.
for(int i=arr1Idx; i > -1; i--) {
distance += _mismatchDistanceConstant + (Math.Abs(arr1[i].Value) * _mismatchDistanceCoeff);
}
return distance < threshold;
}
elem1 = arr1[arr1Idx];
elem2 = arr2[arr2Idx];
}
}
/// <summary>
/// Gets the distance between two positions.
/// </summary>
public double GetDistance(CoordinateVector p1, CoordinateVector p2)
{
KeyValuePair<ulong,double>[] arr1 = p1.CoordArray;
KeyValuePair<ulong,double>[] arr2 = p2.CoordArray;
// Store these heavily used values locally.
int arr1Length = arr1.Length;
int arr2Length = arr2.Length;
//--- Test for special cases.
if(0 == arr1Length && 0 == arr2Length)
{ // Both arrays are empty. No disparities, therefore the distance is zero.
return 0.0;
}
double distance = 0;
if(0 == arr1Length)
{ // All arr2 genes are mismatches.
for(int i=0; i<arr2Length; i++) {
distance += Math.Abs(arr2[i].Value);
}
return (_mismatchDistanceConstant * arr2Length) + (distance * _mismatchDistanceCoeff);
}
if(0 == arr2Length)
{ // All arr1 elements are mismatches.
for(int i=0; i<arr1Length; i++) {
distance += Math.Abs(arr1[i].Value);
}
return (_mismatchDistanceConstant * arr1Length) + (distance * _mismatchDistanceCoeff);
}
//----- Both arrays contain elements.
int arr1Idx = 0;
int arr2Idx = 0;
KeyValuePair<ulong,double> elem1 = arr1[arr1Idx];
KeyValuePair<ulong,double> elem2 = arr2[arr2Idx];
for(;;)
{
if(elem1.Key < elem2.Key)
{
// p2 doesn't specify a value in this dimension therefore we take it's position to be 0.
distance += _mismatchDistanceConstant + (Math.Abs(elem1.Value) * _mismatchDistanceCoeff);
// Move to the next element in arr1.
arr1Idx++;
}
else if(elem1.Key == elem2.Key)
{
// Matching elements.
distance += Math.Abs(elem1.Value - elem2.Value) * _matchDistanceCoeff;
// Move to the next element in both arrays.
arr1Idx++;
arr2Idx++;
}
else // elem2.Key < elem1.Key
{
// p1 doesn't specify a value in this dimension therefore we take it's position to be 0.
distance += _mismatchDistanceConstant + (Math.Abs(elem2.Value) * _mismatchDistanceCoeff);
// Move to the next element in arr2.
arr2Idx++;
}
// Check if we have exhausted one or both of the arrays.
if(arr1Idx == arr1Length)
{ // All remaining arr2 elements are mismatches.
for(int i=arr2Idx; i<arr2Length; i++) {
distance += _mismatchDistanceConstant + (Math.Abs(arr2[i].Value) * _mismatchDistanceCoeff);
}
return distance;
}
if(arr2Idx == arr2Length)
{ // All remaining arr1 elements are mismatches.
for(int i=arr1Idx; i<arr1.Length; i++) {
distance += _mismatchDistanceConstant + (Math.Abs(arr1[i].Value) * _mismatchDistanceCoeff);
}
return distance;
}
elem1 = arr1[arr1Idx];
elem2 = arr2[arr2Idx];
}
}
// TODO: Determine mathematically correct centroid. This method calculates the Euclidean distance centroid and
// is an approximation of the true centroid in L1 space (Manhattan distance).
// Note. In practice this is possibly a near optimal centroid for all but small clusters.
/// <summary>
/// Calculates the centroid for the given set of points.
/// The centroid is a central position within a set of points that minimizes the sum of the squared distance
/// between each of those points and the centroid. As such it can also be thought of as being an exemplar
/// for a set of points.
///
/// The centroid calculation is dependent on the distance metric, hence this method is defined on IDistanceMetric.
/// For some distance metrics the centroid may not be a unique point, in those cases one of the possible centroids
/// is returned.
///
/// A centroid is used in k-means clustering to define the center of a cluster.
/// </summary>
public CoordinateVector CalculateCentroid(IList<CoordinateVector> coordList)
{
// Special case - one item in list, it *is* the centroid.
if(1 == coordList.Count) {
return coordList[0];
}
// Each coordinate element has an ID. Here we calculate the total for each ID across all CoordinateVectors,
// then divide the totals by the number of CoordinateVectors to get the average for each ID. That is, we
// calculate the component-wise mean.
//
// Coord elements within a CoordinateVector must be sorted by ID, therefore we use a SortedDictionary here
// when building the centroid coordinate to eliminate the need to sort elements later.
//
// We use SortedDictionary and not SortedList for performance. SortedList is fastest for insertion
// only if the inserts are in order (sorted). However, this is generally not the case here because although
// coordinate IDs are sorted within the source CoordinateVectors, not all IDs exist within all CoordinateVectors
// therefore a low ID may be presented to coordElemTotals after a higher ID.
SortedDictionary<ulong, double[]> coordElemTotals = new SortedDictionary<ulong,double[]>();
// Loop over coords.
foreach(CoordinateVector coord in coordList)
{
// Loop over each element within the current coord.
foreach(KeyValuePair<ulong,double> coordElem in coord.CoordArray)
{
// If the ID has previously been encountered then add the current element value to it, otherwise
// add a new double[1] to hold the value.
// Note that we wrap the double value in an object so that we do not have to re-insert values
// to increment them. In tests this approach was about 40% faster (including GC overhead).
double[] doubleWrapper;
if(coordElemTotals.TryGetValue(coordElem.Key, out doubleWrapper)) {
doubleWrapper[0] += coordElem.Value;
}
else {
coordElemTotals.Add(coordElem.Key, new double[]{coordElem.Value});
}
}
}
// Put the unique coord elems from coordElemTotals into a list, dividing each element's value
// by the total number of coords as we go.
double coordCountReciprocol = 1.0 / (double)coordList.Count;
KeyValuePair<ulong,double>[] centroidElemArr = new KeyValuePair<ulong,double>[coordElemTotals.Count];
int i=0;
foreach(KeyValuePair<ulong,double[]> coordElem in coordElemTotals)
{ // For speed we multiply by reciprocal instead of dividing by coordCount.
centroidElemArr[i++] = new KeyValuePair<ulong,double>(coordElem.Key, coordElem.Value[0] * coordCountReciprocol);
}
// Use the new list of elements to construct a centroid CoordinateVector.
return new CoordinateVector(centroidElemArr);
}
/// <summary>
/// Parallelized version of CalculateCentroid().
/// </summary>
public CoordinateVector CalculateCentroidParallel(IList<CoordinateVector> coordList)
{
// Special case - one item in list, it *is* the centroid.
if (1 == coordList.Count)
{
return coordList[0];
}
// Each coordinate element has an ID. Here we calculate the total for each ID across all CoordinateVectors,
// then divide the totals by the number of CoordinateVectors to get the average for each ID. That is, we
// calculate the component-wise mean.
// ConcurrentDictionary provides a low-locking strategy that greatly improves performance here
// compared to using mutual exclusion locks or even ReadWriterLock(s).
ConcurrentDictionary<ulong,double[]> coordElemTotals = new ConcurrentDictionary<ulong, double[]>();
// Loop over coords.
Parallel.ForEach(coordList, delegate(CoordinateVector coord)
{
// Loop over each element within the current coord.
foreach (KeyValuePair<ulong, double> coordElem in coord.CoordArray)
{
// If the ID has previously been encountered then add the current element value to it, otherwise
// add a new double[1] to hold the value.
// Note that we wrap the double value in an object so that we do not have to re-insert values
// to increment them. In tests this approach was about 40% faster (including GC overhead).
// If position is zero then (A) skip doing any work, and (B) zero will break the following logic.
if (coordElem.Value == 0.0) {
continue;
}
double[] doubleWrapper;
if (coordElemTotals.TryGetValue(coordElem.Key, out doubleWrapper))
{ // By locking just the specific object that holds the value we are incrementing
// we greatly reduce the amount of lock contention.
lock(doubleWrapper)
{
doubleWrapper[0] += coordElem.Value;
}
}
else
{
doubleWrapper = new double[] { coordElem.Value };
if (!coordElemTotals.TryAdd(coordElem.Key, doubleWrapper))
{
if(coordElemTotals.TryGetValue(coordElem.Key, out doubleWrapper))
{
lock (doubleWrapper)
{
doubleWrapper[0] += coordElem.Value;
}
}
}
}
}
});
// Put the unique coord elems from coordElemTotals into a list, dividing each element's value
// by the total number of coords as we go.
double coordCountReciprocol = 1.0 / (double)coordList.Count;
KeyValuePair<ulong, double>[] centroidElemArr = new KeyValuePair<ulong, double>[coordElemTotals.Count];
int i = 0;
foreach (KeyValuePair<ulong, double[]> coordElem in coordElemTotals)
{ // For speed we multiply by reciprocal instead of dividing by coordCount.
centroidElemArr[i++] = new KeyValuePair<ulong, double>(coordElem.Key, coordElem.Value[0] * coordCountReciprocol);
}
// Coord elements within a CoordinateVector must be sorted by ID.
Array.Sort(centroidElemArr, delegate(KeyValuePair<ulong, double> x, KeyValuePair<ulong, double> y)
{
if (x.Key < y.Key) {
return -1;
}
if (x.Key > y.Key) {
return 1;
}
return 0;
});
// Use the new list of elements to construct a centroid CoordinateVector.
return new CoordinateVector(centroidElemArr);
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Dialogflow.V2
{
/// <summary>Settings for <see cref="SessionsClient"/> instances.</summary>
public sealed partial class SessionsSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="SessionsSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="SessionsSettings"/>.</returns>
public static SessionsSettings GetDefault() => new SessionsSettings();
/// <summary>Constructs a new <see cref="SessionsSettings"/> object with default settings.</summary>
public SessionsSettings()
{
}
private SessionsSettings(SessionsSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
DetectIntentSettings = existing.DetectIntentSettings;
StreamingDetectIntentSettings = existing.StreamingDetectIntentSettings;
StreamingDetectIntentStreamingSettings = existing.StreamingDetectIntentStreamingSettings;
OnCopy(existing);
}
partial void OnCopy(SessionsSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>SessionsClient.DetectIntent</c>
/// and <c>SessionsClient.DetectIntentAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>.</description>
/// </item>
/// <item><description>Timeout: 220 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DetectIntentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(220000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SessionsClient.StreamingDetectIntent</c> and <c>SessionsClient.StreamingDetectIntentAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 220 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings StreamingDetectIntentSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(220000)));
/// <summary>
/// <see cref="gaxgrpc::BidirectionalStreamingSettings"/> for calls to <c>SessionsClient.StreamingDetectIntent</c>
/// and <c>SessionsClient.StreamingDetectIntentAsync</c>.
/// </summary>
/// <remarks>The default local send queue size is 100.</remarks>
public gaxgrpc::BidirectionalStreamingSettings StreamingDetectIntentStreamingSettings { get; set; } = new gaxgrpc::BidirectionalStreamingSettings(100);
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="SessionsSettings"/> object.</returns>
public SessionsSettings Clone() => new SessionsSettings(this);
}
/// <summary>
/// Builder class for <see cref="SessionsClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class SessionsClientBuilder : gaxgrpc::ClientBuilderBase<SessionsClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public SessionsSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public SessionsClientBuilder()
{
UseJwtAccessWithScopes = SessionsClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref SessionsClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<SessionsClient> task);
/// <summary>Builds the resulting client.</summary>
public override SessionsClient Build()
{
SessionsClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<SessionsClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<SessionsClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private SessionsClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return SessionsClient.Create(callInvoker, Settings);
}
private async stt::Task<SessionsClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return SessionsClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => SessionsClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => SessionsClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => SessionsClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>Sessions client wrapper, for convenient use.</summary>
/// <remarks>
/// A service used for session interactions.
///
/// For more information, see the [API interactions
/// guide](https://cloud.google.com/dialogflow/docs/api-overview).
/// </remarks>
public abstract partial class SessionsClient
{
/// <summary>
/// The default endpoint for the Sessions service, which is a host of "dialogflow.googleapis.com" and a port of
/// 443.
/// </summary>
public static string DefaultEndpoint { get; } = "dialogflow.googleapis.com:443";
/// <summary>The default Sessions scopes.</summary>
/// <remarks>
/// The default Sessions scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/dialogflow</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/dialogflow",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="SessionsClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="SessionsClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="SessionsClient"/>.</returns>
public static stt::Task<SessionsClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new SessionsClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="SessionsClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="SessionsClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="SessionsClient"/>.</returns>
public static SessionsClient Create() => new SessionsClientBuilder().Build();
/// <summary>
/// Creates a <see cref="SessionsClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="SessionsSettings"/>.</param>
/// <returns>The created <see cref="SessionsClient"/>.</returns>
internal static SessionsClient Create(grpccore::CallInvoker callInvoker, SessionsSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
Sessions.SessionsClient grpcClient = new Sessions.SessionsClient(callInvoker);
return new SessionsClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC Sessions client</summary>
public virtual Sessions.SessionsClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Processes a natural language query and returns structured, actionable data
/// as a result. This method is not idempotent, because it may cause contexts
/// and session entity types to be updated, which in turn might affect
/// results of future queries.
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]
/// instead of `DetectIntent`. `AnalyzeContent` has additional
/// functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual DetectIntentResponse DetectIntent(DetectIntentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Processes a natural language query and returns structured, actionable data
/// as a result. This method is not idempotent, because it may cause contexts
/// and session entity types to be updated, which in turn might affect
/// results of future queries.
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]
/// instead of `DetectIntent`. `AnalyzeContent` has additional
/// functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DetectIntentResponse> DetectIntentAsync(DetectIntentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Processes a natural language query and returns structured, actionable data
/// as a result. This method is not idempotent, because it may cause contexts
/// and session entity types to be updated, which in turn might affect
/// results of future queries.
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]
/// instead of `DetectIntent`. `AnalyzeContent` has additional
/// functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DetectIntentResponse> DetectIntentAsync(DetectIntentRequest request, st::CancellationToken cancellationToken) =>
DetectIntentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Processes a natural language query and returns structured, actionable data
/// as a result. This method is not idempotent, because it may cause contexts
/// and session entity types to be updated, which in turn might affect
/// results of future queries.
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]
/// instead of `DetectIntent`. `AnalyzeContent` has additional
/// functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="session">
/// Required. The name of the session this query is sent to. Format:
/// `projects/{Project ID}/agent/sessions/{Session ID}`, or
/// `projects/{Project ID}/agent/environments/{Environment ID}/users/{User
/// ID&gt;/sessions/&lt;Session ID&gt;`. If `Environment ID` is not specified, we assume
/// default 'draft' environment (`Environment ID` might be referred to as
/// environment name at some places). If `User ID` is not specified, we are
/// using "-". It's up to the API caller to choose an appropriate `Session ID`
/// and `User Id`. They can be a random number or some type of user and session
/// identifiers (preferably hashed). The length of the `Session ID` and
/// `User ID` must not exceed 36 characters.
///
/// For more information, see the [API interactions
/// guide](https://cloud.google.com/dialogflow/docs/api-overview).
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </param>
/// <param name="queryInput">
/// Required. The input specification. It can be set to:
///
/// 1. an audio config
/// which instructs the speech recognizer how to process the speech audio,
///
/// 2. a conversational query in the form of text, or
///
/// 3. an event that specifies which intent to trigger.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual DetectIntentResponse DetectIntent(string session, QueryInput queryInput, gaxgrpc::CallSettings callSettings = null) =>
DetectIntent(new DetectIntentRequest
{
Session = gax::GaxPreconditions.CheckNotNullOrEmpty(session, nameof(session)),
QueryInput = gax::GaxPreconditions.CheckNotNull(queryInput, nameof(queryInput)),
}, callSettings);
/// <summary>
/// Processes a natural language query and returns structured, actionable data
/// as a result. This method is not idempotent, because it may cause contexts
/// and session entity types to be updated, which in turn might affect
/// results of future queries.
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]
/// instead of `DetectIntent`. `AnalyzeContent` has additional
/// functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="session">
/// Required. The name of the session this query is sent to. Format:
/// `projects/{Project ID}/agent/sessions/{Session ID}`, or
/// `projects/{Project ID}/agent/environments/{Environment ID}/users/{User
/// ID&gt;/sessions/&lt;Session ID&gt;`. If `Environment ID` is not specified, we assume
/// default 'draft' environment (`Environment ID` might be referred to as
/// environment name at some places). If `User ID` is not specified, we are
/// using "-". It's up to the API caller to choose an appropriate `Session ID`
/// and `User Id`. They can be a random number or some type of user and session
/// identifiers (preferably hashed). The length of the `Session ID` and
/// `User ID` must not exceed 36 characters.
///
/// For more information, see the [API interactions
/// guide](https://cloud.google.com/dialogflow/docs/api-overview).
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </param>
/// <param name="queryInput">
/// Required. The input specification. It can be set to:
///
/// 1. an audio config
/// which instructs the speech recognizer how to process the speech audio,
///
/// 2. a conversational query in the form of text, or
///
/// 3. an event that specifies which intent to trigger.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DetectIntentResponse> DetectIntentAsync(string session, QueryInput queryInput, gaxgrpc::CallSettings callSettings = null) =>
DetectIntentAsync(new DetectIntentRequest
{
Session = gax::GaxPreconditions.CheckNotNullOrEmpty(session, nameof(session)),
QueryInput = gax::GaxPreconditions.CheckNotNull(queryInput, nameof(queryInput)),
}, callSettings);
/// <summary>
/// Processes a natural language query and returns structured, actionable data
/// as a result. This method is not idempotent, because it may cause contexts
/// and session entity types to be updated, which in turn might affect
/// results of future queries.
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]
/// instead of `DetectIntent`. `AnalyzeContent` has additional
/// functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="session">
/// Required. The name of the session this query is sent to. Format:
/// `projects/{Project ID}/agent/sessions/{Session ID}`, or
/// `projects/{Project ID}/agent/environments/{Environment ID}/users/{User
/// ID&gt;/sessions/&lt;Session ID&gt;`. If `Environment ID` is not specified, we assume
/// default 'draft' environment (`Environment ID` might be referred to as
/// environment name at some places). If `User ID` is not specified, we are
/// using "-". It's up to the API caller to choose an appropriate `Session ID`
/// and `User Id`. They can be a random number or some type of user and session
/// identifiers (preferably hashed). The length of the `Session ID` and
/// `User ID` must not exceed 36 characters.
///
/// For more information, see the [API interactions
/// guide](https://cloud.google.com/dialogflow/docs/api-overview).
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </param>
/// <param name="queryInput">
/// Required. The input specification. It can be set to:
///
/// 1. an audio config
/// which instructs the speech recognizer how to process the speech audio,
///
/// 2. a conversational query in the form of text, or
///
/// 3. an event that specifies which intent to trigger.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DetectIntentResponse> DetectIntentAsync(string session, QueryInput queryInput, st::CancellationToken cancellationToken) =>
DetectIntentAsync(session, queryInput, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Processes a natural language query and returns structured, actionable data
/// as a result. This method is not idempotent, because it may cause contexts
/// and session entity types to be updated, which in turn might affect
/// results of future queries.
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]
/// instead of `DetectIntent`. `AnalyzeContent` has additional
/// functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="session">
/// Required. The name of the session this query is sent to. Format:
/// `projects/{Project ID}/agent/sessions/{Session ID}`, or
/// `projects/{Project ID}/agent/environments/{Environment ID}/users/{User
/// ID&gt;/sessions/&lt;Session ID&gt;`. If `Environment ID` is not specified, we assume
/// default 'draft' environment (`Environment ID` might be referred to as
/// environment name at some places). If `User ID` is not specified, we are
/// using "-". It's up to the API caller to choose an appropriate `Session ID`
/// and `User Id`. They can be a random number or some type of user and session
/// identifiers (preferably hashed). The length of the `Session ID` and
/// `User ID` must not exceed 36 characters.
///
/// For more information, see the [API interactions
/// guide](https://cloud.google.com/dialogflow/docs/api-overview).
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </param>
/// <param name="queryInput">
/// Required. The input specification. It can be set to:
///
/// 1. an audio config
/// which instructs the speech recognizer how to process the speech audio,
///
/// 2. a conversational query in the form of text, or
///
/// 3. an event that specifies which intent to trigger.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual DetectIntentResponse DetectIntent(SessionName session, QueryInput queryInput, gaxgrpc::CallSettings callSettings = null) =>
DetectIntent(new DetectIntentRequest
{
SessionAsSessionName = gax::GaxPreconditions.CheckNotNull(session, nameof(session)),
QueryInput = gax::GaxPreconditions.CheckNotNull(queryInput, nameof(queryInput)),
}, callSettings);
/// <summary>
/// Processes a natural language query and returns structured, actionable data
/// as a result. This method is not idempotent, because it may cause contexts
/// and session entity types to be updated, which in turn might affect
/// results of future queries.
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]
/// instead of `DetectIntent`. `AnalyzeContent` has additional
/// functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="session">
/// Required. The name of the session this query is sent to. Format:
/// `projects/{Project ID}/agent/sessions/{Session ID}`, or
/// `projects/{Project ID}/agent/environments/{Environment ID}/users/{User
/// ID&gt;/sessions/&lt;Session ID&gt;`. If `Environment ID` is not specified, we assume
/// default 'draft' environment (`Environment ID` might be referred to as
/// environment name at some places). If `User ID` is not specified, we are
/// using "-". It's up to the API caller to choose an appropriate `Session ID`
/// and `User Id`. They can be a random number or some type of user and session
/// identifiers (preferably hashed). The length of the `Session ID` and
/// `User ID` must not exceed 36 characters.
///
/// For more information, see the [API interactions
/// guide](https://cloud.google.com/dialogflow/docs/api-overview).
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </param>
/// <param name="queryInput">
/// Required. The input specification. It can be set to:
///
/// 1. an audio config
/// which instructs the speech recognizer how to process the speech audio,
///
/// 2. a conversational query in the form of text, or
///
/// 3. an event that specifies which intent to trigger.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DetectIntentResponse> DetectIntentAsync(SessionName session, QueryInput queryInput, gaxgrpc::CallSettings callSettings = null) =>
DetectIntentAsync(new DetectIntentRequest
{
SessionAsSessionName = gax::GaxPreconditions.CheckNotNull(session, nameof(session)),
QueryInput = gax::GaxPreconditions.CheckNotNull(queryInput, nameof(queryInput)),
}, callSettings);
/// <summary>
/// Processes a natural language query and returns structured, actionable data
/// as a result. This method is not idempotent, because it may cause contexts
/// and session entity types to be updated, which in turn might affect
/// results of future queries.
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]
/// instead of `DetectIntent`. `AnalyzeContent` has additional
/// functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="session">
/// Required. The name of the session this query is sent to. Format:
/// `projects/{Project ID}/agent/sessions/{Session ID}`, or
/// `projects/{Project ID}/agent/environments/{Environment ID}/users/{User
/// ID&gt;/sessions/&lt;Session ID&gt;`. If `Environment ID` is not specified, we assume
/// default 'draft' environment (`Environment ID` might be referred to as
/// environment name at some places). If `User ID` is not specified, we are
/// using "-". It's up to the API caller to choose an appropriate `Session ID`
/// and `User Id`. They can be a random number or some type of user and session
/// identifiers (preferably hashed). The length of the `Session ID` and
/// `User ID` must not exceed 36 characters.
///
/// For more information, see the [API interactions
/// guide](https://cloud.google.com/dialogflow/docs/api-overview).
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </param>
/// <param name="queryInput">
/// Required. The input specification. It can be set to:
///
/// 1. an audio config
/// which instructs the speech recognizer how to process the speech audio,
///
/// 2. a conversational query in the form of text, or
///
/// 3. an event that specifies which intent to trigger.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DetectIntentResponse> DetectIntentAsync(SessionName session, QueryInput queryInput, st::CancellationToken cancellationToken) =>
DetectIntentAsync(session, queryInput, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Bidirectional streaming methods for
/// <see cref="StreamingDetectIntent(gaxgrpc::CallSettings,gaxgrpc::BidirectionalStreamingSettings)"/>.
/// </summary>
public abstract partial class StreamingDetectIntentStream : gaxgrpc::BidirectionalStreamingBase<StreamingDetectIntentRequest, StreamingDetectIntentResponse>
{
}
/// <summary>
/// Processes a natural language query in audio format in a streaming fashion
/// and returns structured, actionable data as a result. This method is only
/// available via the gRPC API (not REST).
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent]
/// instead of `StreamingDetectIntent`. `StreamingAnalyzeContent` has
/// additional functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <param name="streamingSettings">If not null, applies streaming overrides to this RPC call.</param>
/// <returns>The client-server stream.</returns>
public virtual StreamingDetectIntentStream StreamingDetectIntent(gaxgrpc::CallSettings callSettings = null, gaxgrpc::BidirectionalStreamingSettings streamingSettings = null) =>
throw new sys::NotImplementedException();
}
/// <summary>Sessions client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// A service used for session interactions.
///
/// For more information, see the [API interactions
/// guide](https://cloud.google.com/dialogflow/docs/api-overview).
/// </remarks>
public sealed partial class SessionsClientImpl : SessionsClient
{
private readonly gaxgrpc::ApiCall<DetectIntentRequest, DetectIntentResponse> _callDetectIntent;
private readonly gaxgrpc::ApiBidirectionalStreamingCall<StreamingDetectIntentRequest, StreamingDetectIntentResponse> _callStreamingDetectIntent;
/// <summary>
/// Constructs a client wrapper for the Sessions service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="SessionsSettings"/> used within this client.</param>
public SessionsClientImpl(Sessions.SessionsClient grpcClient, SessionsSettings settings)
{
GrpcClient = grpcClient;
SessionsSettings effectiveSettings = settings ?? SessionsSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callDetectIntent = clientHelper.BuildApiCall<DetectIntentRequest, DetectIntentResponse>(grpcClient.DetectIntentAsync, grpcClient.DetectIntent, effectiveSettings.DetectIntentSettings).WithGoogleRequestParam("session", request => request.Session);
Modify_ApiCall(ref _callDetectIntent);
Modify_DetectIntentApiCall(ref _callDetectIntent);
_callStreamingDetectIntent = clientHelper.BuildApiCall<StreamingDetectIntentRequest, StreamingDetectIntentResponse>(grpcClient.StreamingDetectIntent, effectiveSettings.StreamingDetectIntentSettings, effectiveSettings.StreamingDetectIntentStreamingSettings);
Modify_ApiCall(ref _callStreamingDetectIntent);
Modify_StreamingDetectIntentApiCall(ref _callStreamingDetectIntent);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiBidirectionalStreamingCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_DetectIntentApiCall(ref gaxgrpc::ApiCall<DetectIntentRequest, DetectIntentResponse> call);
partial void Modify_StreamingDetectIntentApiCall(ref gaxgrpc::ApiBidirectionalStreamingCall<StreamingDetectIntentRequest, StreamingDetectIntentResponse> call);
partial void OnConstruction(Sessions.SessionsClient grpcClient, SessionsSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC Sessions client</summary>
public override Sessions.SessionsClient GrpcClient { get; }
partial void Modify_DetectIntentRequest(ref DetectIntentRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_StreamingDetectIntentRequestCallSettings(ref gaxgrpc::CallSettings settings);
partial void Modify_StreamingDetectIntentRequestRequest(ref StreamingDetectIntentRequest request);
/// <summary>
/// Processes a natural language query and returns structured, actionable data
/// as a result. This method is not idempotent, because it may cause contexts
/// and session entity types to be updated, which in turn might affect
/// results of future queries.
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]
/// instead of `DetectIntent`. `AnalyzeContent` has additional
/// functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override DetectIntentResponse DetectIntent(DetectIntentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DetectIntentRequest(ref request, ref callSettings);
return _callDetectIntent.Sync(request, callSettings);
}
/// <summary>
/// Processes a natural language query and returns structured, actionable data
/// as a result. This method is not idempotent, because it may cause contexts
/// and session entity types to be updated, which in turn might affect
/// results of future queries.
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]
/// instead of `DetectIntent`. `AnalyzeContent` has additional
/// functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<DetectIntentResponse> DetectIntentAsync(DetectIntentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DetectIntentRequest(ref request, ref callSettings);
return _callDetectIntent.Async(request, callSettings);
}
internal sealed partial class StreamingDetectIntentStreamImpl : StreamingDetectIntentStream
{
/// <summary>Construct the bidirectional streaming method for <c>StreamingDetectIntent</c>.</summary>
/// <param name="service">The service containing this streaming method.</param>
/// <param name="call">The underlying gRPC duplex streaming call.</param>
/// <param name="writeBuffer">
/// The <see cref="gaxgrpc::BufferedClientStreamWriter{StreamingDetectIntentRequest}"/> instance associated
/// with this streaming call.
/// </param>
public StreamingDetectIntentStreamImpl(SessionsClientImpl service, grpccore::AsyncDuplexStreamingCall<StreamingDetectIntentRequest, StreamingDetectIntentResponse> call, gaxgrpc::BufferedClientStreamWriter<StreamingDetectIntentRequest> writeBuffer)
{
_service = service;
GrpcCall = call;
_writeBuffer = writeBuffer;
}
private SessionsClientImpl _service;
private gaxgrpc::BufferedClientStreamWriter<StreamingDetectIntentRequest> _writeBuffer;
public override grpccore::AsyncDuplexStreamingCall<StreamingDetectIntentRequest, StreamingDetectIntentResponse> GrpcCall { get; }
private StreamingDetectIntentRequest ModifyRequest(StreamingDetectIntentRequest request)
{
_service.Modify_StreamingDetectIntentRequestRequest(ref request);
return request;
}
public override stt::Task TryWriteAsync(StreamingDetectIntentRequest message) =>
_writeBuffer.TryWriteAsync(ModifyRequest(message));
public override stt::Task WriteAsync(StreamingDetectIntentRequest message) =>
_writeBuffer.WriteAsync(ModifyRequest(message));
public override stt::Task TryWriteAsync(StreamingDetectIntentRequest message, grpccore::WriteOptions options) =>
_writeBuffer.TryWriteAsync(ModifyRequest(message), options);
public override stt::Task WriteAsync(StreamingDetectIntentRequest message, grpccore::WriteOptions options) =>
_writeBuffer.WriteAsync(ModifyRequest(message), options);
public override stt::Task TryWriteCompleteAsync() => _writeBuffer.TryWriteCompleteAsync();
public override stt::Task WriteCompleteAsync() => _writeBuffer.WriteCompleteAsync();
}
/// <summary>
/// Processes a natural language query in audio format in a streaming fashion
/// and returns structured, actionable data as a result. This method is only
/// available via the gRPC API (not REST).
///
/// If you might use
/// [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa)
/// or other CCAI products now or in the future, consider using
/// [StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent]
/// instead of `StreamingDetectIntent`. `StreamingAnalyzeContent` has
/// additional functionality for Agent Assist and other CCAI products.
///
/// Note: Always use agent versions for production traffic.
/// See [Versions and
/// environments](https://cloud.google.com/dialogflow/es/docs/agents-versions).
/// </summary>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <param name="streamingSettings">If not null, applies streaming overrides to this RPC call.</param>
/// <returns>The client-server stream.</returns>
public override SessionsClient.StreamingDetectIntentStream StreamingDetectIntent(gaxgrpc::CallSettings callSettings = null, gaxgrpc::BidirectionalStreamingSettings streamingSettings = null)
{
Modify_StreamingDetectIntentRequestCallSettings(ref callSettings);
gaxgrpc::BidirectionalStreamingSettings effectiveStreamingSettings = streamingSettings ?? _callStreamingDetectIntent.StreamingSettings;
grpccore::AsyncDuplexStreamingCall<StreamingDetectIntentRequest, StreamingDetectIntentResponse> call = _callStreamingDetectIntent.Call(callSettings);
gaxgrpc::BufferedClientStreamWriter<StreamingDetectIntentRequest> writeBuffer = new gaxgrpc::BufferedClientStreamWriter<StreamingDetectIntentRequest>(call.RequestStream, effectiveStreamingSettings.BufferedClientWriterCapacity);
return new StreamingDetectIntentStreamImpl(this, call, writeBuffer);
}
}
}
| |
// 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.
//*************************************************************************************************************
// For each dynamic assembly there will be two AssemblyBuilder objects: the "internal"
// AssemblyBuilder object and the "external" AssemblyBuilder object.
// 1. The "internal" object is the real assembly object that the VM creates and knows about. However,
// you can perform RefEmit operations on it only if you have its granted permission. From the AppDomain
// and other "internal" objects like the "internal" ModuleBuilders and runtime types, you can only
// get the "internal" objects. This is to prevent low-trust code from getting a hold of the dynamic
// AssemblyBuilder/ModuleBuilder/TypeBuilder/MethodBuilder/etc other people have created by simply
// enumerating the AppDomain and inject code in it.
// 2. The "external" object is merely an wrapper of the "internal" object and all operations on it
// are directed to the internal object. This is the one you get by calling DefineDynamicAssembly
// on AppDomain and the one you can always perform RefEmit operations on. You can get other "external"
// objects from the "external" AssemblyBuilder, ModuleBuilder, TypeBuilder, MethodBuilder, etc. Note
// that VM doesn't know about this object. So every time we call into the VM we need to pass in the
// "internal" object.
//
// "internal" and "external" ModuleBuilders are similar
//*************************************************************************************************************
namespace System.Reflection.Emit
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.SymbolStore;
using CultureInfo = System.Globalization.CultureInfo;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Threading;
// When the user calls AppDomain.DefineDynamicAssembly the loader creates a new InternalAssemblyBuilder.
// This InternalAssemblyBuilder can be retrieved via a call to Assembly.GetAssemblies() by untrusted code.
// In the past, when InternalAssemblyBuilder was AssemblyBuilder, the untrusted user could down cast the
// Assembly to an AssemblyBuilder and emit code with the elevated permissions of the trusted code which
// origionally created the AssemblyBuilder via DefineDynamicAssembly. Today, this can no longer happen
// because the Assembly returned via AssemblyGetAssemblies() will be an InternalAssemblyBuilder.
// Only the caller of DefineDynamicAssembly will get an AssemblyBuilder.
// There is a 1-1 relationship between InternalAssemblyBuilder and AssemblyBuilder.
// AssemblyBuilder is composed of its InternalAssemblyBuilder.
// The AssemblyBuilder data members (e.g. m_foo) were changed to properties which then delegate
// the access to the composed InternalAssemblyBuilder. This way, AssemblyBuilder simply wraps
// InternalAssemblyBuilder and still operates on InternalAssemblyBuilder members.
// This also makes the change transparent to the loader. This is good because most of the complexity
// of Assembly building is in the loader code so not touching that code reduces the chance of
// introducing new bugs.
internal sealed class InternalAssemblyBuilder : RuntimeAssembly
{
private InternalAssemblyBuilder() { }
#region object overrides
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj is InternalAssemblyBuilder)
return ((object)this == obj);
return obj.Equals(this);
}
// Need a dummy GetHashCode to pair with Equals
public override int GetHashCode() { return base.GetHashCode(); }
#endregion
// Assembly methods that are overridden by AssemblyBuilder should be overridden by InternalAssemblyBuilder too
#region Methods inherited from Assembly
public override String[] GetManifestResourceNames()
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override FileStream GetFile(String name)
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override FileStream[] GetFiles(bool getResourceModules)
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override Stream GetManifestResourceStream(Type type, String name)
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override Stream GetManifestResourceStream(String name)
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override ManifestResourceInfo GetManifestResourceInfo(String resourceName)
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override String Location
{
get
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
}
public override String CodeBase
{
get
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
}
public override Type[] GetExportedTypes()
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override String ImageRuntimeVersion
{
get
{
return RuntimeEnvironment.GetSystemVersion();
}
}
#endregion
}
// AssemblyBuilder class.
// deliberately not [serializable]
public sealed class AssemblyBuilder : Assembly
{
#region FCALL
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern RuntimeModule GetInMemoryAssemblyModule(RuntimeAssembly assembly);
private Module nGetInMemoryAssemblyModule()
{
return AssemblyBuilder.GetInMemoryAssemblyModule(GetNativeHandle());
}
#endregion
#region Internal Data Members
// This is only valid in the "external" AssemblyBuilder
internal AssemblyBuilderData m_assemblyData;
private InternalAssemblyBuilder m_internalAssemblyBuilder;
private ModuleBuilder m_manifestModuleBuilder;
// Set to true if the manifest module was returned by code:DefineDynamicModule to the user
private bool m_fManifestModuleUsedAsDefinedModule;
internal const string MANIFEST_MODULE_NAME = "RefEmit_InMemoryManifestModule";
internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module)
{
Contract.Requires(module != null);
Debug.Assert(this.InternalAssembly == module.Assembly);
lock (SyncRoot)
{
// in CoreCLR there is only one module in each dynamic assembly, the manifest module
if (m_manifestModuleBuilder.InternalModule == module)
return m_manifestModuleBuilder;
throw new ArgumentException(null, nameof(module));
}
}
internal object SyncRoot
{
get
{
return InternalAssembly.SyncRoot;
}
}
internal InternalAssemblyBuilder InternalAssembly
{
get
{
return m_internalAssemblyBuilder;
}
}
internal RuntimeAssembly GetNativeHandle()
{
return InternalAssembly.GetNativeHandle();
}
#endregion
#region Constructor
internal AssemblyBuilder(AppDomain domain,
AssemblyName name,
AssemblyBuilderAccess access,
ref StackCrawlMark stackMark,
IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (access != AssemblyBuilderAccess.Run
&& access != AssemblyBuilderAccess.RunAndCollect
)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)access), nameof(access));
}
// Clone the name in case the caller modifies it underneath us.
name = (AssemblyName)name.Clone();
// Scan the assembly level attributes for any attributes which modify how we create the
// assembly. Currently, we look for any attribute which modifies the security transparency
// of the assembly.
List<CustomAttributeBuilder> assemblyAttributes = null;
if (unsafeAssemblyAttributes != null)
{
// Create a copy to ensure that it cannot be modified from another thread
// as it is used further below.
assemblyAttributes = new List<CustomAttributeBuilder>(unsafeAssemblyAttributes);
}
m_internalAssemblyBuilder = (InternalAssemblyBuilder)nCreateDynamicAssembly(domain,
name,
ref stackMark,
access);
m_assemblyData = new AssemblyBuilderData(m_internalAssemblyBuilder,
name.Name,
access);
// Make sure that ManifestModule is properly initialized
// We need to do this before setting any CustomAttribute
InitManifestModule();
if (assemblyAttributes != null)
{
foreach (CustomAttributeBuilder assemblyAttribute in assemblyAttributes)
SetCustomAttribute(assemblyAttribute);
}
}
private void InitManifestModule()
{
InternalModuleBuilder modBuilder = (InternalModuleBuilder)nGetInMemoryAssemblyModule();
// Note that this ModuleBuilder cannot be used for RefEmit yet
// because it hasn't been initialized.
// However, it can be used to set the custom attribute on the Assembly
m_manifestModuleBuilder = new ModuleBuilder(this, modBuilder);
// We are only setting the name in the managed ModuleBuilderData here.
// The name in the underlying metadata will be set when the
// manifest module is created during nCreateDynamicAssembly.
// This name needs to stay in sync with that used in
// Assembly::Init to call ReflectionModule::Create (in VM)
m_manifestModuleBuilder.Init(AssemblyBuilder.MANIFEST_MODULE_NAME, null, 0);
m_fManifestModuleUsedAsDefinedModule = false;
}
#endregion
#region DefineDynamicAssembly
/**********************************************
* If an AssemblyName has a public key specified, the assembly is assumed
* to have a strong name and a hash will be computed when the assembly
* is saved.
**********************************************/
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static AssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
AssemblyBuilderAccess access)
{
Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalDefineDynamicAssembly(name, access,
ref stackMark, null);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static AssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
AssemblyBuilderAccess access,
IEnumerable<CustomAttributeBuilder> assemblyAttributes)
{
Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalDefineDynamicAssembly(name,
access,
ref stackMark,
assemblyAttributes);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Assembly nCreateDynamicAssembly(AppDomain domain,
AssemblyName name,
ref StackCrawlMark stackMark,
AssemblyBuilderAccess access);
private class AssemblyBuilderLock { }
internal static AssemblyBuilder InternalDefineDynamicAssembly(
AssemblyName name,
AssemblyBuilderAccess access,
ref StackCrawlMark stackMark,
IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes)
{
lock (typeof(AssemblyBuilderLock))
{
// we can only create dynamic assemblies in the current domain
return new AssemblyBuilder(AppDomain.CurrentDomain,
name,
access,
ref stackMark,
unsafeAssemblyAttributes);
} //lock(typeof(AssemblyBuilderLock))
}
#endregion
#region DefineDynamicModule
/**********************************************
*
* Defines a named dynamic module. It is an error to define multiple
* modules within an Assembly with the same name. This dynamic module is
* a transient module.
*
**********************************************/
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public ModuleBuilder DefineDynamicModule(
String name)
{
Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return DefineDynamicModuleInternal(name, false, ref stackMark);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public ModuleBuilder DefineDynamicModule(
String name,
bool emitSymbolInfo) // specify if emit symbol info or not
{
Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return DefineDynamicModuleInternal(name, emitSymbolInfo, ref stackMark);
}
private ModuleBuilder DefineDynamicModuleInternal(
String name,
bool emitSymbolInfo, // specify if emit symbol info or not
ref StackCrawlMark stackMark)
{
lock (SyncRoot)
{
return DefineDynamicModuleInternalNoLock(name, emitSymbolInfo, ref stackMark);
}
}
private ModuleBuilder DefineDynamicModuleInternalNoLock(
String name,
bool emitSymbolInfo, // specify if emit symbol info or not
ref StackCrawlMark stackMark)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
if (name[0] == '\0')
throw new ArgumentException(SR.Argument_InvalidName, nameof(name));
Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
Contract.EndContractBlock();
BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + " )");
Debug.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal");
ModuleBuilder dynModule;
ISymbolWriter writer = null;
IntPtr pInternalSymWriter = new IntPtr();
// create the dynamic module- only one ModuleBuilder per AssemblyBuilder can be created
if (m_fManifestModuleUsedAsDefinedModule == true)
throw new InvalidOperationException(SR.InvalidOperation_NoMultiModuleAssembly);
// Init(...) has already been called on m_manifestModuleBuilder in InitManifestModule()
dynModule = m_manifestModuleBuilder;
// Create the symbol writer
if (emitSymbolInfo)
{
writer = SymWrapperCore.SymWriter.CreateSymWriter();
String fileName = "Unused"; // this symfile is never written to disk so filename does not matter.
// Pass the "real" module to the VM
pInternalSymWriter = ModuleBuilder.nCreateISymWriterForDynamicModule(dynModule.InternalModule, fileName);
// In Telesto, we took the SetUnderlyingWriter method private as it's a very rickety method.
// This might someday be a good move for the desktop CLR too.
((SymWrapperCore.SymWriter)writer).InternalSetUnderlyingWriter(pInternalSymWriter);
} // Creating the symbol writer
dynModule.SetSymWriter(writer);
m_assemblyData.AddModule(dynModule);
if (dynModule == m_manifestModuleBuilder)
{ // We are reusing manifest module as user-defined dynamic module
m_fManifestModuleUsedAsDefinedModule = true;
}
return dynModule;
} // DefineDynamicModuleInternalNoLock
#endregion
internal void CheckContext(params Type[][] typess)
{
if (typess == null)
return;
foreach (Type[] types in typess)
if (types != null)
CheckContext(types);
}
internal void CheckContext(params Type[] types)
{
if (types == null)
return;
foreach (Type type in types)
{
if (type == null)
continue;
if (type.Module == null || type.Module.Assembly == null)
throw new ArgumentException(SR.Argument_TypeNotValid);
if (type.Module.Assembly == typeof(object).Module.Assembly)
continue;
if (type.Module.Assembly.ReflectionOnly && !ReflectionOnly)
throw new InvalidOperationException(SR.Format(SR.Arugment_EmitMixedContext1, type.AssemblyQualifiedName));
if (!type.Module.Assembly.ReflectionOnly && ReflectionOnly)
throw new InvalidOperationException(SR.Format(SR.Arugment_EmitMixedContext2, type.AssemblyQualifiedName));
}
}
#region object overrides
public override bool Equals(object obj)
{
return InternalAssembly.Equals(obj);
}
// Need a dummy GetHashCode to pair with Equals
public override int GetHashCode() { return InternalAssembly.GetHashCode(); }
#endregion
#region ICustomAttributeProvider Members
public override Object[] GetCustomAttributes(bool inherit)
{
return InternalAssembly.GetCustomAttributes(inherit);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return InternalAssembly.GetCustomAttributes(attributeType, inherit);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return InternalAssembly.IsDefined(attributeType, inherit);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return InternalAssembly.GetCustomAttributesData();
}
#endregion
#region Assembly overrides
// Returns the names of all the resources
public override String[] GetManifestResourceNames()
{
return InternalAssembly.GetManifestResourceNames();
}
public override FileStream GetFile(String name)
{
return InternalAssembly.GetFile(name);
}
public override FileStream[] GetFiles(bool getResourceModules)
{
return InternalAssembly.GetFiles(getResourceModules);
}
public override Stream GetManifestResourceStream(Type type, String name)
{
return InternalAssembly.GetManifestResourceStream(type, name);
}
public override Stream GetManifestResourceStream(String name)
{
return InternalAssembly.GetManifestResourceStream(name);
}
public override ManifestResourceInfo GetManifestResourceInfo(String resourceName)
{
return InternalAssembly.GetManifestResourceInfo(resourceName);
}
public override String Location
{
get
{
return InternalAssembly.Location;
}
}
public override String ImageRuntimeVersion
{
get
{
return InternalAssembly.ImageRuntimeVersion;
}
}
public override String CodeBase
{
get
{
return InternalAssembly.CodeBase;
}
}
// Override the EntryPoint method on Assembly.
// This doesn't need to be synchronized because it is simple enough
public override MethodInfo EntryPoint
{
get
{
return m_assemblyData.m_entryPointMethod;
}
}
// Get an array of all the public types defined in this assembly
public override Type[] GetExportedTypes()
{
return InternalAssembly.GetExportedTypes();
}
public override AssemblyName GetName(bool copiedName)
{
return InternalAssembly.GetName(copiedName);
}
public override String FullName
{
get
{
return InternalAssembly.FullName;
}
}
public override Type GetType(String name, bool throwOnError, bool ignoreCase)
{
return InternalAssembly.GetType(name, throwOnError, ignoreCase);
}
public override Module ManifestModule
{
get
{
return m_manifestModuleBuilder.InternalModule;
}
}
public override bool ReflectionOnly
{
get
{
return InternalAssembly.ReflectionOnly;
}
}
public override Module GetModule(String name)
{
return InternalAssembly.GetModule(name);
}
public override AssemblyName[] GetReferencedAssemblies()
{
return InternalAssembly.GetReferencedAssemblies();
}
public override bool GlobalAssemblyCache
{
get
{
return InternalAssembly.GlobalAssemblyCache;
}
}
public override Int64 HostContext
{
get
{
return InternalAssembly.HostContext;
}
}
public override Module[] GetModules(bool getResourceModules)
{
return InternalAssembly.GetModules(getResourceModules);
}
public override Module[] GetLoadedModules(bool getResourceModules)
{
return InternalAssembly.GetLoadedModules(getResourceModules);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Assembly GetSatelliteAssembly(CultureInfo culture)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalAssembly.InternalGetSatelliteAssembly(culture, null, ref stackMark);
}
// Useful for binding to a very specific version of a satellite assembly
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalAssembly.InternalGetSatelliteAssembly(culture, version, ref stackMark);
}
public override bool IsDynamic
{
get
{
return true;
}
}
#endregion
/**********************************************
*
* return a dynamic module with the specified name.
*
**********************************************/
public ModuleBuilder GetDynamicModule(
String name) // the name of module for the look up
{
lock (SyncRoot)
{
return GetDynamicModuleNoLock(name);
}
}
private ModuleBuilder GetDynamicModuleNoLock(
String name) // the name of module for the look up
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
Contract.EndContractBlock();
BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.GetDynamicModule( " + name + " )");
int size = m_assemblyData.m_moduleBuilderList.Count;
for (int i = 0; i < size; i++)
{
ModuleBuilder moduleBuilder = (ModuleBuilder)m_assemblyData.m_moduleBuilderList[i];
if (moduleBuilder.m_moduleData.m_strModuleName.Equals(name))
{
return moduleBuilder;
}
}
return null;
}
/**********************************************
* Use this function if client decides to form the custom attribute blob themselves
**********************************************/
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
Contract.EndContractBlock();
lock (SyncRoot)
{
SetCustomAttributeNoLock(con, binaryAttribute);
}
}
private void SetCustomAttributeNoLock(ConstructorInfo con, byte[] binaryAttribute)
{
TypeBuilder.DefineCustomAttribute(
m_manifestModuleBuilder, // pass in the in-memory assembly module
AssemblyBuilderData.m_tkAssembly, // This is the AssemblyDef token
m_manifestModuleBuilder.GetConstructorToken(con).Token,
binaryAttribute,
false,
typeof(System.Diagnostics.DebuggableAttribute) == con.DeclaringType);
// Track the CA for persistence
if (m_assemblyData.m_access != AssemblyBuilderAccess.Run)
{
// tracking the CAs for persistence
m_assemblyData.AddCustomAttribute(con, binaryAttribute);
}
}
/**********************************************
* Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
**********************************************/
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
{
throw new ArgumentNullException(nameof(customBuilder));
}
Contract.EndContractBlock();
lock (SyncRoot)
{
SetCustomAttributeNoLock(customBuilder);
}
}
private void SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder)
{
customBuilder.CreateCustomAttribute(
m_manifestModuleBuilder,
AssemblyBuilderData.m_tkAssembly); // This is the AssemblyDef token
// Track the CA for persistence
if (m_assemblyData.m_access != AssemblyBuilderAccess.Run)
{
m_assemblyData.AddCustomAttribute(customBuilder);
}
}
/**********************************************
*
* Private methods
*
**********************************************/
/**********************************************
* Make a private constructor so these cannot be constructed externally.
* @internonly
**********************************************/
private AssemblyBuilder() { }
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net;
using System.Security.Authentication;
using RedditSharp.Things;
using System.Threading.Tasks;
using DefaultWebAgent = RedditSharp.WebAgent;
namespace RedditSharp
{
/// <summary>
/// Class to communicate with Reddit.com
/// </summary>
public class Reddit
{
#region Constant Urls
private const string SslLoginUrl = "https://ssl.reddit.com/api/login";
private const string LoginUrl = "/api/login/username";
private const string UserInfoUrl = "/user/{0}/about.json";
private const string MeUrl = "/api/me.json";
private const string OAuthMeUrl = "/api/v1/me.json";
private const string SubredditAboutUrl = "/r/{0}/about.json";
private const string ComposeMessageUrl = "/api/compose";
private const string RegisterAccountUrl = "/api/register";
private const string GetThingUrl = "/api/info.json?id={0}";
private const string GetCommentUrl = "/r/{0}/comments/{1}/foo/{2}";
private const string GetPostUrl = "{0}.json";
private const string DomainUrl = "www.reddit.com";
private const string OAuthDomainUrl = "oauth.reddit.com";
private const string SearchUrl = "/search.json?q={0}&restrict_sr=off&sort={1}&t={2}";
private const string UrlSearchPattern = "url:'{0}'";
private const string NewSubredditsUrl = "/subreddits/new.json";
private const string PopularSubredditsUrl = "/subreddits/popular.json";
private const string GoldSubredditsUrl = "/subreddits/gold.json";
private const string DefaultSubredditsUrl = "/subreddits/default.json";
private const string SearchSubredditsUrl = "/subreddits/search.json?q={0}";
#endregion
#region Static Variables
static Reddit()
{
DefaultWebAgent.UserAgent = "";
DefaultWebAgent.RateLimit = DefaultWebAgent.RateLimitMode.Pace;
DefaultWebAgent.Protocol = "https";
DefaultWebAgent.RootDomain = "www.reddit.com";
}
#endregion
internal IWebAgent WebAgent { get; set; }
/// <summary>
/// Captcha solver instance to use when solving captchas.
/// </summary>
public ICaptchaSolver CaptchaSolver;
/// <summary>
/// The authenticated user for this instance.
/// </summary>
public AuthenticatedUser User { get; set; }
/// <summary>
/// Sets the Rate Limiting Mode of the underlying WebAgent
/// </summary>
public DefaultWebAgent.RateLimitMode RateLimit
{
get { return DefaultWebAgent.RateLimit; }
set { DefaultWebAgent.RateLimit = value; }
}
internal JsonSerializerSettings JsonSerializerSettings { get; set; }
/// <summary>
/// Gets the FrontPage using the current Reddit instance.
/// </summary>
public Subreddit FrontPage
{
get { return Subreddit.GetFrontPage(this); }
}
/// <summary>
/// Gets /r/All using the current Reddit instance.
/// </summary>
public Subreddit RSlashAll
{
get { return Subreddit.GetRSlashAll(this); }
}
public Reddit()
: this(true) { }
public Reddit(bool useSsl)
{
DefaultWebAgent defaultAgent = new DefaultWebAgent();
JsonSerializerSettings = new JsonSerializerSettings
{
CheckAdditionalContent = false,
DefaultValueHandling = DefaultValueHandling.Ignore
};
DefaultWebAgent.Protocol = useSsl ? "https" : "http";
WebAgent = defaultAgent;
CaptchaSolver = new ConsoleCaptchaSolver();
}
public Reddit(DefaultWebAgent.RateLimitMode limitMode, bool useSsl = true)
: this(useSsl)
{
DefaultWebAgent.UserAgent = "";
DefaultWebAgent.RateLimit = limitMode;
DefaultWebAgent.RootDomain = "www.reddit.com";
}
public Reddit(string username, string password, bool useSsl = true)
: this(useSsl)
{
LogIn(username, password, useSsl);
}
public Reddit(string accessToken)
: this(true)
{
DefaultWebAgent.RootDomain = OAuthDomainUrl;
WebAgent.AccessToken = accessToken;
InitOrUpdateUser();
}
/// <summary>
/// Creates a Reddit instance with the given WebAgent implementation
/// </summary>
/// <param name="agent">Implementation of IWebAgent interface. Used to generate requests.</param>
public Reddit(IWebAgent agent)
{
WebAgent = agent;
JsonSerializerSettings = new JsonSerializerSettings
{
CheckAdditionalContent = false,
DefaultValueHandling = DefaultValueHandling.Ignore
};
CaptchaSolver = new ConsoleCaptchaSolver();
}
/// <summary>
/// Creates a Reddit instance with the given WebAgent implementation
/// </summary>
/// <param name="agent">Implementation of IWebAgent interface. Used to generate requests.</param>
/// <param name="initUser">Whether to run InitOrUpdateUser, requires <paramref name="agent"/> to have credentials first.</param>
public Reddit(IWebAgent agent, bool initUser)
{
WebAgent = agent;
JsonSerializerSettings = new JsonSerializerSettings
{
CheckAdditionalContent = false,
DefaultValueHandling = DefaultValueHandling.Ignore
};
CaptchaSolver = new ConsoleCaptchaSolver();
if(initUser) InitOrUpdateUser();
}
/// <summary>
/// Logs in the current Reddit instance.
/// </summary>
/// <param name="username">The username of the user to log on to.</param>
/// <param name="password">The password of the user to log on to.</param>
/// <param name="useSsl">Whether to use SSL or not. (default: true)</param>
/// <returns></returns>
public AuthenticatedUser LogIn(string username, string password, bool useSsl = true)
{
if (Type.GetType("Mono.Runtime") != null)
ServicePointManager.ServerCertificateValidationCallback = (s, c, ch, ssl) => true;
WebAgent.Cookies = new CookieContainer();
HttpWebRequest request;
if (useSsl)
request = WebAgent.CreatePost(SslLoginUrl);
else
request = WebAgent.CreatePost(LoginUrl);
var stream = request.GetRequestStream();
if (useSsl)
{
WebAgent.WritePostBody(stream, new
{
user = username,
passwd = password,
api_type = "json"
});
}
else
{
WebAgent.WritePostBody(stream, new
{
user = username,
passwd = password,
api_type = "json",
op = "login"
});
}
stream.Close();
var response = (HttpWebResponse)request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result)["json"];
if (json["errors"].Count() != 0)
throw new AuthenticationException("Incorrect login.");
InitOrUpdateUser();
return User;
}
public RedditUser GetUser(string name)
{
var request = WebAgent.CreateGet(string.Format(UserInfoUrl, name));
var response = request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
return new RedditUser().Init(this, json, WebAgent);
}
/// <summary>
/// Initializes the User property if it's null,
/// otherwise replaces the existing user object
/// with a new one fetched from reddit servers.
/// </summary>
public void InitOrUpdateUser()
{
var request = WebAgent.CreateGet(string.IsNullOrEmpty(WebAgent.AccessToken) ? MeUrl : OAuthMeUrl);
var response = (HttpWebResponse)request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
User = new AuthenticatedUser().Init(this, json, WebAgent);
}
#region Obsolete Getter Methods
[Obsolete("Use User property instead")]
public AuthenticatedUser GetMe()
{
return User;
}
#endregion Obsolete Getter Methods
public Subreddit GetSubreddit(string name)
{
if (name.StartsWith("r/"))
name = name.Substring(2);
if (name.StartsWith("/r/"))
name = name.Substring(3);
name = name.TrimEnd('/');
return GetThing<Subreddit>(string.Format(SubredditAboutUrl, name));
}
/// <summary>
/// Returns the subreddit.
/// </summary>
/// <param name="name">The name of the subreddit</param>
/// <returns>The Subreddit by given name</returns>
public async Task<Subreddit> GetSubredditAsync(string name)
{
if (name.StartsWith("r/"))
name = name.Substring(2);
if (name.StartsWith("/r/"))
name = name.Substring(3);
name = name.TrimEnd('/');
return await GetThingAsync<Subreddit>(string.Format(SubredditAboutUrl, name));
}
public Domain GetDomain(string domain)
{
if (!domain.StartsWith("http://") && !domain.StartsWith("https://"))
domain = "http://" + domain;
var uri = new Uri(domain);
return new Domain(this, uri, WebAgent);
}
public JToken GetToken(Uri uri)
{
var url = uri.AbsoluteUri;
if (url.EndsWith("/"))
url = url.Remove(url.Length - 1);
var request = WebAgent.CreateGet(string.Format(GetPostUrl, url));
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return json[0]["data"]["children"].First;
}
public Post GetPost(Uri uri)
{
return new Post().Init(this, GetToken(uri), WebAgent);
}
public void ComposePrivateMessage(string subject, string body, string to, string captchaId = "", string captchaAnswer = "")
{
if (User == null)
throw new Exception("User can not be null.");
var request = WebAgent.CreatePost(ComposeMessageUrl);
WebAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
subject,
text = body,
to,
uh = User.Modhash,
iden = captchaId,
captcha = captchaAnswer
});
var response = request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
ICaptchaSolver solver = CaptchaSolver; // Prevent race condition
if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "BAD_CAPTCHA" && solver != null)
{
captchaId = json["json"]["captcha"].ToString();
CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(captchaId));
if (!captchaResponse.Cancel) // Keep trying until we are told to cancel
ComposePrivateMessage(subject, body, to, captchaId, captchaResponse.Answer);
}
}
/// <summary>
/// Registers a new Reddit user
/// </summary>
/// <param name="userName">The username for the new account.</param>
/// <param name="passwd">The password for the new account.</param>
/// <param name="email">The optional recovery email for the new account.</param>
/// <returns>The newly created user account</returns>
public AuthenticatedUser RegisterAccount(string userName, string passwd, string email = "")
{
var request = WebAgent.CreatePost(RegisterAccountUrl);
WebAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
email = email,
passwd = passwd,
passwd2 = passwd,
user = userName
});
var response = request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
return new AuthenticatedUser().Init(this, json, WebAgent);
// TODO: Error
}
public Thing GetThingByFullname(string fullname)
{
var request = WebAgent.CreateGet(string.Format(GetThingUrl, fullname));
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return Thing.Parse(this, json["data"]["children"][0], WebAgent);
}
public Comment GetComment(string subreddit, string name, string linkName)
{
try
{
if (linkName.StartsWith("t3_"))
linkName = linkName.Substring(3);
if (name.StartsWith("t1_"))
name = name.Substring(3);
var url = string.Format(GetCommentUrl, subreddit, linkName, name);
return GetComment(new Uri(url));
}
catch (WebException)
{
return null;
}
}
public Comment GetComment(Uri uri)
{
var url = string.Format(GetPostUrl, uri.AbsoluteUri);
var request = WebAgent.CreateGet(url);
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
var sender = new Post().Init(this, json[0]["data"]["children"][0], WebAgent);
return new Comment().Init(this, json[1]["data"]["children"][0], WebAgent, sender);
}
public Listing<T> SearchByUrl<T>(string url) where T : Thing
{
var urlSearchQuery = string.Format(UrlSearchPattern, url);
return Search<T>(urlSearchQuery);
}
public Listing<T> Search<T>(string query, Sorting sortE = Sorting.Relevance, TimeSorting timeE = TimeSorting.All) where T : Thing
{
string sort = sortE.ToString().ToLower();
string time = timeE.ToString().ToLower();
return new Listing<T>(this, string.Format(SearchUrl, query, sort, time), WebAgent);
}
#region SubredditSearching
/// <summary>
/// Returns a Listing of newly created subreddits.
/// </summary>
/// <returns></returns>
public Listing<Subreddit> GetNewSubreddits()
{
return new Listing<Subreddit>(this, NewSubredditsUrl, WebAgent);
}
/// <summary>
/// Returns a Listing of the most popular subreddits.
/// </summary>
/// <returns></returns>
public Listing<Subreddit> GetPopularSubreddits()
{
return new Listing<Subreddit>(this, PopularSubredditsUrl, WebAgent);
}
/// <summary>
/// Returns a Listing of Gold-only subreddits. This endpoint will not return anything if the authenticated Reddit account does not currently have gold.
/// </summary>
/// <returns></returns>
public Listing<Subreddit> GetGoldSubreddits()
{
return new Listing<Subreddit>(this, GoldSubredditsUrl, WebAgent);
}
/// <summary>
/// Returns the Listing of default subreddits.
/// </summary>
/// <returns></returns>
public Listing<Subreddit> GetDefaultSubreddits()
{
return new Listing<Subreddit>(this, DefaultSubredditsUrl, WebAgent);
}
/// <summary>
/// Returns the Listing of subreddits related to a query.
/// </summary>
/// <returns></returns>
public Listing<Subreddit> SearchSubreddits(string query)
{
return new Listing<Subreddit>(this, string.Format(SearchSubredditsUrl, query), WebAgent);
}
#endregion SubredditSearching
#region Helpers
protected async internal Task<T> GetThingAsync<T>(string url) where T : Thing
{
var request = WebAgent.CreateGet(url);
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
var ret = await Thing.ParseAsync(this, json, WebAgent);
return (T)ret;
}
protected internal T GetThing<T>(string url) where T : Thing
{
var request = WebAgent.CreateGet(url);
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return (T)Thing.Parse(this, json, WebAgent);
}
#endregion
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\EnvironmentQuery\Generators\EnvQueryGenerator_CurrentLocation.h:13
namespace UnrealEngine
{
[ManageType("ManageEnvQueryGenerator_CurrentLocation")]
public partial class ManageEnvQueryGenerator_CurrentLocation : UEnvQueryGenerator_CurrentLocation, IManageWrapper
{
public ManageEnvQueryGenerator_CurrentLocation(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_UpdateNodeVersion(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_CurrentLocation_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
public override void UpdateNodeVersion()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_UpdateNodeVersion(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__UEnvQueryGenerator_CurrentLocation_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__UEnvQueryGenerator_CurrentLocation_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageEnvQueryGenerator_CurrentLocation self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageEnvQueryGenerator_CurrentLocation(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageEnvQueryGenerator_CurrentLocation>(PtrDesc);
}
}
}
| |
using System;
using ChainUtils.BouncyCastle.Crypto.Paddings;
using ChainUtils.BouncyCastle.Crypto.Parameters;
namespace ChainUtils.BouncyCastle.Crypto.Macs
{
/**
* implements a Cipher-FeedBack (CFB) mode on top of a simple cipher.
*/
class MacCFBBlockCipher
: IBlockCipher
{
private byte[] IV;
private byte[] cfbV;
private byte[] cfbOutV;
private readonly int blockSize;
private readonly IBlockCipher cipher;
/**
* Basic constructor.
*
* @param cipher the block cipher to be used as the basis of the
* feedback mode.
* @param blockSize the block size in bits (note: a multiple of 8)
*/
public MacCFBBlockCipher(
IBlockCipher cipher,
int bitBlockSize)
{
this.cipher = cipher;
blockSize = bitBlockSize / 8;
IV = new byte[cipher.GetBlockSize()];
cfbV = new byte[cipher.GetBlockSize()];
cfbOutV = new byte[cipher.GetBlockSize()];
}
/**
* Initialise the cipher and, possibly, the initialisation vector (IV).
* If an IV isn't passed as part of the parameter, the IV will be all zeros.
* An IV which is too short is handled in FIPS compliant fashion.
*
* @param param the key and other data required by the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (parameters is ParametersWithIV)
{
var ivParam = (ParametersWithIV)parameters;
var iv = ivParam.GetIV();
if (iv.Length < IV.Length)
{
Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length);
}
else
{
Array.Copy(iv, 0, IV, 0, IV.Length);
}
parameters = ivParam.Parameters;
}
Reset();
cipher.Init(true, parameters);
}
/**
* return the algorithm name and mode.
*
* @return the name of the underlying algorithm followed by "/CFB"
* and the block size in bits.
*/
public string AlgorithmName
{
get { return cipher.AlgorithmName + "/CFB" + (blockSize * 8); }
}
public bool IsPartialBlockOkay
{
get { return true; }
}
/**
* return the block size we are operating at.
*
* @return the block size we are operating at (in bytes).
*/
public int GetBlockSize()
{
return blockSize;
}
/**
* Process one block of input from the array in and write it to
* the out array.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public int ProcessBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
if ((inOff + blockSize) > input.Length)
throw new DataLengthException("input buffer too short");
if ((outOff + blockSize) > outBytes.Length)
throw new DataLengthException("output buffer too short");
cipher.ProcessBlock(cfbV, 0, cfbOutV, 0);
//
// XOR the cfbV with the plaintext producing the cipher text
//
for (var i = 0; i < blockSize; i++)
{
outBytes[outOff + i] = (byte)(cfbOutV[i] ^ input[inOff + i]);
}
//
// change over the input block.
//
Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize);
Array.Copy(outBytes, outOff, cfbV, cfbV.Length - blockSize, blockSize);
return blockSize;
}
/**
* reset the chaining vector back to the IV and reset the underlying
* cipher.
*/
public void Reset()
{
IV.CopyTo(cfbV, 0);
cipher.Reset();
}
public void GetMacBlock(
byte[] mac)
{
cipher.ProcessBlock(cfbV, 0, mac, 0);
}
}
public class CfbBlockCipherMac
: IMac
{
private byte[] mac;
private byte[] Buffer;
private int bufOff;
private MacCFBBlockCipher cipher;
private IBlockCipherPadding padding;
private int macSize;
/**
* create a standard MAC based on a CFB block cipher. This will produce an
* authentication code half the length of the block size of the cipher, with
* the CFB mode set to 8 bits.
*
* @param cipher the cipher to be used as the basis of the MAC generation.
*/
public CfbBlockCipherMac(
IBlockCipher cipher)
: this(cipher, 8, (cipher.GetBlockSize() * 8) / 2, null)
{
}
/**
* create a standard MAC based on a CFB block cipher. This will produce an
* authentication code half the length of the block size of the cipher, with
* the CFB mode set to 8 bits.
*
* @param cipher the cipher to be used as the basis of the MAC generation.
* @param padding the padding to be used.
*/
public CfbBlockCipherMac(
IBlockCipher cipher,
IBlockCipherPadding padding)
: this(cipher, 8, (cipher.GetBlockSize() * 8) / 2, padding)
{
}
/**
* create a standard MAC based on a block cipher with the size of the
* MAC been given in bits. This class uses CFB mode as the basis for the
* MAC generation.
* <p>
* Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
* or 16 bits if being used as a data authenticator (FIPS Publication 113),
* and in general should be less than the size of the block cipher as it reduces
* the chance of an exhaustive attack (see Handbook of Applied Cryptography).
* </p>
* @param cipher the cipher to be used as the basis of the MAC generation.
* @param cfbBitSize the size of an output block produced by the CFB mode.
* @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
*/
public CfbBlockCipherMac(
IBlockCipher cipher,
int cfbBitSize,
int macSizeInBits)
: this(cipher, cfbBitSize, macSizeInBits, null)
{
}
/**
* create a standard MAC based on a block cipher with the size of the
* MAC been given in bits. This class uses CFB mode as the basis for the
* MAC generation.
* <p>
* Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
* or 16 bits if being used as a data authenticator (FIPS Publication 113),
* and in general should be less than the size of the block cipher as it reduces
* the chance of an exhaustive attack (see Handbook of Applied Cryptography).
* </p>
* @param cipher the cipher to be used as the basis of the MAC generation.
* @param cfbBitSize the size of an output block produced by the CFB mode.
* @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
* @param padding a padding to be used.
*/
public CfbBlockCipherMac(
IBlockCipher cipher,
int cfbBitSize,
int macSizeInBits,
IBlockCipherPadding padding)
{
if ((macSizeInBits % 8) != 0)
throw new ArgumentException("MAC size must be multiple of 8");
mac = new byte[cipher.GetBlockSize()];
this.cipher = new MacCFBBlockCipher(cipher, cfbBitSize);
this.padding = padding;
macSize = macSizeInBits / 8;
Buffer = new byte[this.cipher.GetBlockSize()];
bufOff = 0;
}
public string AlgorithmName
{
get { return cipher.AlgorithmName; }
}
public void Init(
ICipherParameters parameters)
{
Reset();
cipher.Init(true, parameters);
}
public int GetMacSize()
{
return macSize;
}
public void Update(
byte input)
{
if (bufOff == Buffer.Length)
{
cipher.ProcessBlock(Buffer, 0, mac, 0);
bufOff = 0;
}
Buffer[bufOff++] = input;
}
public void BlockUpdate(
byte[] input,
int inOff,
int len)
{
if (len < 0)
throw new ArgumentException("Can't have a negative input length!");
var blockSize = cipher.GetBlockSize();
var resultLen = 0;
var gapLen = blockSize - bufOff;
if (len > gapLen)
{
Array.Copy(input, inOff, Buffer, bufOff, gapLen);
resultLen += cipher.ProcessBlock(Buffer, 0, mac, 0);
bufOff = 0;
len -= gapLen;
inOff += gapLen;
while (len > blockSize)
{
resultLen += cipher.ProcessBlock(input, inOff, mac, 0);
len -= blockSize;
inOff += blockSize;
}
}
Array.Copy(input, inOff, Buffer, bufOff, len);
bufOff += len;
}
public int DoFinal(
byte[] output,
int outOff)
{
var blockSize = cipher.GetBlockSize();
// pad with zeroes
if (padding == null)
{
while (bufOff < blockSize)
{
Buffer[bufOff++] = 0;
}
}
else
{
padding.AddPadding(Buffer, bufOff);
}
cipher.ProcessBlock(Buffer, 0, mac, 0);
cipher.GetMacBlock(mac);
Array.Copy(mac, 0, output, outOff, macSize);
Reset();
return macSize;
}
/**
* Reset the mac generator.
*/
public void Reset()
{
// Clear the buffer.
Array.Clear(Buffer, 0, Buffer.Length);
bufOff = 0;
// Reset the underlying cipher.
cipher.Reset();
}
}
}
| |
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Amazon Software License (the "License").
// You may not use this file except in compliance with the
// License. A copy of the License is located at
//
// http://aws.amazon.com/asl/
//
// or in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, express or implied. See the License
// for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Amazon.DynamoDBv2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
namespace Amazon.DynamoDBv2.DocumentModel
{
/// <summary>
/// A collection of attribute key-value pairs that defines
/// an item in DynamoDB.
/// </summary>
public class Document : DynamoDBEntry, IDictionary<string, DynamoDBEntry>
{
#region Private/internal members
private Dictionary<string, DynamoDBEntry> originalValues;
private Dictionary<string, DynamoDBEntry> currentValues;
#endregion
#region Constructors
/// <summary>
/// Constructs an empty Document.
/// </summary>
public Document()
{
originalValues = new Dictionary<string, DynamoDBEntry>();
currentValues = new Dictionary<string, DynamoDBEntry>();
}
/// <summary>
/// Constructs a Document with the passed-in values as its attribute values.
/// </summary>
/// <param name="values"></param>
public Document(Dictionary<string, DynamoDBEntry> values)
{
originalValues = new Dictionary<string, DynamoDBEntry>();
currentValues = new Dictionary<string, DynamoDBEntry>(values);
}
internal Document(Document source)
{
originalValues = new Dictionary<string, DynamoDBEntry>(source.originalValues);
currentValues = new Dictionary<string, DynamoDBEntry>(source.currentValues);
}
#endregion
#region Properties/accessors
/// <summary>
/// Attribute accessor, allows getting or setting of an individual attribute.
/// </summary>
/// <param name="key">Name of the attribute.</param>
/// <returns>Current value of the attribute.</returns>
public DynamoDBEntry this[string key]
{
get
{
return currentValues[key];
}
set
{
if (value == null)
{
currentValues[key] = new Primitive();
}
else
{
currentValues[key] = value;
}
}
}
/// <summary>
/// Returns true if the attribute has been changed.
/// </summary>
/// <param name="attributeName">Name of the attribute.</param>
/// <returns>True if the attribute has been changed.</returns>
public bool IsAttributeChanged(string attributeName)
{
DynamoDBEntry original;
this.originalValues.TryGetValue(attributeName, out original);
DynamoDBEntry current;
this.currentValues.TryGetValue(attributeName, out current);
if ((original != null && current == null) || (original == null && current != null))
return true;
if (original == null && current == null)
return false;
return !original.Equals(current);
}
/// <summary>
/// Returns true if the document contains attributes that have not been saved.
/// </summary>
/// <returns>True if the document contains attributes that have not been saved.</returns>
public bool IsDirty()
{
Dictionary<string, string> keys = new Dictionary<string, string>();
foreach (string key in currentValues.Keys)
{
keys.Add(key, key);
}
foreach (string key in originalValues.Keys)
{
if (!keys.ContainsKey(key))
{
keys.Add(key, key);
}
}
foreach (string key in keys.Keys)
{
if (this.IsAttributeChanged(key))
{
return true;
}
}
return false;
}
internal void CommitChanges()
{
this.originalValues.Clear();
foreach (var kvp in currentValues)
{
this.originalValues[kvp.Key] = kvp.Value.Clone() as DynamoDBEntry;
}
}
/// <summary>
/// Gets the value associated with the specified attribute value.
/// </summary>
/// <param name="attributeName">Attribute name</param>
/// <param name="entry">
/// If the specified attribute value is found, returns the value associated with the
/// attribute; otherwise, null.
/// </param>
/// <returns>True if attribute is found; false otherwise</returns>
public bool TryGetValue(string attributeName, out DynamoDBEntry entry)
{
return this.currentValues.TryGetValue(attributeName, out entry);
}
/// <summary>
/// Determines if a specific attribute is set on the Document.
/// </summary>
/// <param name="attributeName">Attribute name</param>
/// <returns>Returns true if the specified attribute is found; false otherwise.</returns>
public bool Contains(string attributeName)
{
return this.currentValues.ContainsKey(attributeName);
}
/// <summary>
/// Returns a new instance of Document where all unconverted .NET types
/// are converted to DynamoDBEntry types using a specific conversion.
/// </summary>
/// <param name="conversion"></param>
/// <returns></returns>
public Document ForceConversion(DynamoDBEntryConversion conversion)
{
Document newDocument = new Document();
foreach(var kvp in this)
{
string name = kvp.Key;
DynamoDBEntry entry = kvp.Value;
var unconvertedEntry = entry as UnconvertedDynamoDBEntry;
if (unconvertedEntry != null)
entry = unconvertedEntry.Convert(conversion);
var doc = entry as Document;
if (doc != null)
entry = doc.ForceConversion(conversion);
var list = entry as DynamoDBList;
if (list != null)
entry = list.ForceConversion(conversion);
newDocument[name] = entry;
}
return newDocument;
}
#endregion
#region DynamoDB conversion
/// <summary>
/// <para>
/// Converts the current Document into a matching JSON string.
/// </para>
/// <para>
/// DynamoDB types are a superset of JSON types, thus the following DynamoDB cannot
/// be properly represented as JSON data:
/// PrimitiveList (SS, NS, BS types) - these sets will be converted to JSON arrays
/// Binary Primitive (B type) - binary data will be converted to Base64 strings
/// </para>
/// <para>
/// If the resultant JSON is passed to Document.FromJson, the binary values will be
/// treated as Base64 strings. Invoke Document.DecodeBase64Attributes to decode these
/// strings into binary data.
/// </para>
/// </summary>
/// <returns>JSON string corresponding to the current Document.</returns>
public string ToJson()
{
return JsonUtils.ToJson(this, prettyPrint: false);
}
/// <summary>
/// <para>
/// Converts the current Document into a matching pretty JSON string.
/// </para>
/// <para>
/// DynamoDB types are a superset of JSON types, thus the following DynamoDB cannot
/// be properly represented as JSON data:
/// PrimitiveList (SS, NS, BS types) - these sets will be converted to JSON arrays
/// Binary Primitive (B type) - binary data will be converted to Base64 strings
/// </para>
/// <para>
/// If the resultant JSON is passed to Document.FromJson, the binary values will be
/// treated as Base64 strings. Invoke Document.DecodeBase64Attributes to decode these
/// strings into binary data.
/// </para>
/// </summary>
/// <returns>JSON string corresponding to the current Document.</returns>
public string ToJsonPretty()
{
return JsonUtils.ToJson(this, prettyPrint: true);
}
/// <summary>
/// Creates a map of attribute names mapped to AttributeValue objects.
/// Converts .NET types using the conversion specified by AWSConfigs.DynamoDBConfig.ConversionSchema
/// </summary>
/// <returns></returns>
public Dictionary<string, AttributeValue> ToAttributeMap()
{
return ToAttributeMap(DynamoDBEntryConversion.CurrentConversion);
}
/// <summary>
/// Creates a map of attribute names mapped to AttributeValue objects.
/// </summary>
/// <param name="conversion">Conversion to use for converting .NET values to DynamoDB values.</param>
/// <returns></returns>
public Dictionary<string, AttributeValue> ToAttributeMap(DynamoDBEntryConversion conversion)
{
if (conversion == null) throw new ArgumentNullException("conversion");
Dictionary<string, AttributeValue> ret = new Dictionary<string, AttributeValue>();
foreach (var attribute in currentValues)
{
AttributeValue value = attribute.Value.ConvertToAttributeValue(new AttributeConversionConfig(conversion));
if (value != null)
{
ret.Add(attribute.Key, value);
}
}
return ret;
}
/// <summary>
/// Creates a map of attribute names mapped to ExpectedAttributeValue objects.
/// </summary>
/// <returns></returns>
public Dictionary<string, ExpectedAttributeValue> ToExpectedAttributeMap()
{
return ToExpectedAttributeMap(DynamoDBEntryConversion.CurrentConversion);
}
/// <summary>
/// Creates a map of attribute names mapped to ExpectedAttributeValue objects.
/// </summary>
/// <param name="conversion">Conversion to use for converting .NET values to DynamoDB values.</param>
/// <returns></returns>
public Dictionary<string, ExpectedAttributeValue> ToExpectedAttributeMap(DynamoDBEntryConversion conversion)
{
if (conversion == null) throw new ArgumentNullException("conversion");
Dictionary<string, ExpectedAttributeValue> ret = new Dictionary<string, ExpectedAttributeValue>();
foreach (var attribute in currentValues)
{
ret.Add(attribute.Key, attribute.Value.ConvertToExpectedAttributeValue(new AttributeConversionConfig(conversion)));
}
return ret;
}
/// <summary>
/// Creates a map of attribute names mapped to AttributeValueUpdate objects.
/// </summary>
/// <param name="changedAttributesOnly">If true, only attributes that have been changed will be in the map.</param>
/// <returns></returns>
public Dictionary<string, AttributeValueUpdate> ToAttributeUpdateMap(bool changedAttributesOnly)
{
return ToAttributeUpdateMap(DynamoDBEntryConversion.CurrentConversion, changedAttributesOnly);
}
/// <summary>
/// Creates a map of attribute names mapped to AttributeValueUpdate objects.
/// </summary>
/// <param name="changedAttributesOnly">If true, only attributes that have been changed will be in the map.</param>
/// <param name="conversion">Conversion to use for converting .NET values to DynamoDB values.</param>
/// <returns></returns>
public Dictionary<string, AttributeValueUpdate> ToAttributeUpdateMap(DynamoDBEntryConversion conversion, bool changedAttributesOnly)
{
if (conversion == null) throw new ArgumentNullException("conversion");
Dictionary<string, AttributeValueUpdate> ret = new Dictionary<string, AttributeValueUpdate>();
foreach (var attribute in currentValues)
{
string name = attribute.Key;
DynamoDBEntry value = attribute.Value;
if (!changedAttributesOnly || this.IsAttributeChanged(name))
{
ret.Add(name, value.ConvertToAttributeUpdateValue(new AttributeConversionConfig(conversion)));
}
}
return ret;
}
/// <summary>
/// Returns the names of all the attributes.
/// </summary>
/// <returns>List of attribute names.</returns>
public List<String> GetAttributeNames()
{
return new List<string>(this.currentValues.Keys);
}
/// <summary>
/// <para>
/// Decodes root-level Base64-encoded strings to their binary representations.
/// Use this method if the Document was constructed from JSON that contains
/// base64-encoded binary values, which result from calling ToJson on a Document
/// with binary data.
/// </para>
/// <para>
/// Individual strings become binary data.
/// List and sets of Base64-encoded strings become lists and sets of binary data.
/// </para>
/// </summary>
/// <param name="attributeNames">Names of root-level attributes to decode.</param>
public void DecodeBase64Attributes(params string[] attributeNames)
{
JsonUtils.DecodeBase64Attributes(this, attributeNames);
}
#endregion
#region Attribute to DynamoDBEntry conversion
internal static DynamoDBEntry AttributeValueToDynamoDBEntry(AttributeValue attributeValue)
{
Primitive primitive;
if (TryToPrimitive(attributeValue, out primitive))
return primitive;
PrimitiveList primitiveList;
if (TryToPrimitiveList(attributeValue, out primitiveList))
return primitiveList;
DynamoDBBool ddbBool;
if (TryToDynamoDBBool(attributeValue, out ddbBool))
return ddbBool;
DynamoDBNull ddbNull;
if (TryToDynamoDBNull(attributeValue, out ddbNull))
return ddbNull;
DynamoDBList ddbList;
if (TryToDynamoDBList(attributeValue, out ddbList))
return ddbList;
Document document;
if (TryToDocument(attributeValue, out document))
return document;
return null;
}
private static bool TryToPrimitiveList(AttributeValue attributeValue, out PrimitiveList primitiveList)
{
primitiveList = null;
Primitive primitive;
if (attributeValue.IsSetSS())
{
primitiveList = new PrimitiveList(DynamoDBEntryType.String);
foreach (string item in attributeValue.SS)
{
primitive = new Primitive(item);
primitiveList.Add(primitive);
}
}
else if (attributeValue.IsSetNS())
{
primitiveList = new PrimitiveList(DynamoDBEntryType.Numeric);
foreach (string item in attributeValue.NS)
{
primitive = new Primitive(item, true);
primitiveList.Add(primitive);
}
}
else if (attributeValue.IsSetBS())
{
primitiveList = new PrimitiveList(DynamoDBEntryType.Binary);
foreach (MemoryStream item in attributeValue.BS)
{
primitive = new Primitive(item);
primitiveList.Add(primitive);
}
}
return (primitiveList != null);
}
private static bool TryToPrimitive(AttributeValue attributeValue, out Primitive primitive)
{
primitive = null;
if (attributeValue.IsSetS())
{
primitive = new Primitive(attributeValue.S);
}
else if (attributeValue.IsSetN())
{
primitive = new Primitive(attributeValue.N, true);
}
else if (attributeValue.IsSetB())
{
primitive = new Primitive(attributeValue.B);
}
return (primitive != null);
}
private static bool TryToDynamoDBBool(AttributeValue attributeValue, out DynamoDBBool ddbBool)
{
ddbBool = null;
if (attributeValue.IsSetBOOL())
{
ddbBool = new DynamoDBBool(attributeValue.BOOL);
}
return (ddbBool != null);
}
private static bool TryToDynamoDBNull(AttributeValue attributeValue, out DynamoDBNull ddbNull)
{
ddbNull = null;
if (attributeValue.IsSetNULL())
{
ddbNull = new DynamoDBNull();
}
return (ddbNull != null);
}
private static bool TryToDynamoDBList(AttributeValue attributeValue, out DynamoDBList list)
{
list = null;
if (attributeValue.IsSetL())
{
var items = attributeValue.L;
var entries = items.Select<AttributeValue,DynamoDBEntry>(AttributeValueToDynamoDBEntry);
list = new DynamoDBList(entries);
}
return (list != null);
}
private static bool TryToDocument(AttributeValue attributeValue, out Document document)
{
document = null;
if (attributeValue.IsSetM())
{
document = new Document();
var items = attributeValue.M;
foreach(var kvp in items)
{
var name = kvp.Key;
var value = kvp.Value;
var entry = AttributeValueToDynamoDBEntry(value);
document[name] = entry;
}
}
return (document != null);
}
#endregion
#region Static methods
/// <summary>
/// Creates a Document from an attribute map.
/// </summary>
/// <param name="data">Map of attribute names to attribute values.</param>
/// <returns>Document representing the data.</returns>
public static Document FromAttributeMap(Dictionary<string, AttributeValue> data)
{
Document doc = new Document();
if (data != null)
{
// Add Primitives and PrimitiveLists
foreach (var attribute in data)
{
string wholeKey = attribute.Key;
AttributeValue value = attribute.Value;
DynamoDBEntry convertedValue = AttributeValueToDynamoDBEntry(value);
if (convertedValue != null)
doc.currentValues[wholeKey] = convertedValue;
}
}
doc.CommitChanges();
return doc;
}
/// <summary>
/// Creates a document from a JSON string.
/// The conversion is as follows:
/// Objects are converted to DynamoDB M types.
/// Arrays are converted to DynamoDB L types.
/// Boolean types are converted to DynamoDB BOOL types.
/// Null values are converted to DynamoDB NULL types.
/// Numerics are converted to DynamoDB N types.
/// Strings are converted to DynamoDB S types.
/// </summary>
/// <param name="json">JSON string.</param>
/// <returns>Document representing the JSON data.</returns>
public static Document FromJson(string json)
{
return JsonUtils.FromJson(json);
}
#endregion
#region IDictionary<string,DynamoDBEntry> Members
public void Add(string key, DynamoDBEntry value)
{
currentValues.Add(key, value);
}
public bool ContainsKey(string key)
{
return currentValues.ContainsKey(key);
}
public ICollection<string> Keys
{
get { return currentValues.Keys; }
}
public bool Remove(string key)
{
return currentValues.Remove(key);
}
public ICollection<DynamoDBEntry> Values
{
get { return currentValues.Values; }
}
#endregion
#region ICollection<KeyValuePair<string,DynamoDBEntry>> Members
public void Add(KeyValuePair<string, DynamoDBEntry> item)
{
currentValues.Add(item.Key, item.Value);
}
public void Clear()
{
currentValues.Clear();
}
public bool Contains(KeyValuePair<string, DynamoDBEntry> item)
{
//DynamoDBEntry value;
//if (!this.TryGetValue(item.Key, out value))
// return false;
//return value.Equals(item.Value);
var icollection = (ICollection<KeyValuePair<string, DynamoDBEntry>>)currentValues;
return icollection.Contains(item);
}
public void CopyTo(KeyValuePair<string, DynamoDBEntry>[] array, int arrayIndex)
{
var icollection = (ICollection<KeyValuePair<string, DynamoDBEntry>>)currentValues;
icollection.CopyTo(array, arrayIndex);
}
public int Count
{
get { return currentValues.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(KeyValuePair<string, DynamoDBEntry> item)
{
var icollection = (ICollection<KeyValuePair<string, DynamoDBEntry>>)currentValues;
return icollection.Remove(item);
}
#endregion
#region IEnumerable<KeyValuePair<string,DynamoDBEntry>> Members
public IEnumerator<KeyValuePair<string, DynamoDBEntry>> GetEnumerator()
{
return currentValues.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return currentValues.GetEnumerator();
}
#endregion
#region DynamoDBEntry overrides
internal override AttributeValue ConvertToAttributeValue(AttributeConversionConfig conversionConfig)
{
var map = new Dictionary<string, AttributeValue>(StringComparer.Ordinal);
foreach(var item in currentValues)
{
var key = item.Key;
var entry = item.Value;
AttributeValue entryAttributeValue;
using (conversionConfig.CRT.Track(entry))
{
entryAttributeValue = entry.ConvertToAttributeValue(conversionConfig);
}
if (entryAttributeValue != null)
{
map[key] = entryAttributeValue;
}
}
var attributeValue = new AttributeValue();
attributeValue.M = map;
attributeValue.IsMSet = true;
return attributeValue;
}
public override object Clone()
{
var doc = new Document(this);
return doc;
}
#endregion
#region Overrides
public override bool Equals(object obj)
{
var otherDocument = obj as Document;
if (otherDocument == null)
return false;
if (Keys.Count != otherDocument.Keys.Count)
return false;
foreach(var key in Keys)
{
if (!otherDocument.ContainsKey(key))
return false;
var a = this[key];
var b = otherDocument[key];
if (!a.Equals(b))
return false;
}
return true;
}
public override int GetHashCode()
{
var hashCode = 0;
foreach(var kvp in this)
{
string key = kvp.Key;
DynamoDBEntry entry = kvp.Value;
hashCode = Hashing.CombineHashes(hashCode, key.GetHashCode(), entry.GetHashCode());
}
return hashCode;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Data.Common;
using System.Diagnostics;
namespace System.Data.SqlClient
{
public sealed class SqlTransaction : DbTransaction
{
internal readonly IsolationLevel _isolationLevel = IsolationLevel.ReadCommitted;
private SqlInternalTransaction _internalTransaction;
private SqlConnection _connection;
private bool _isFromAPI;
internal SqlTransaction(SqlInternalConnection internalConnection, SqlConnection con,
IsolationLevel iso, SqlInternalTransaction internalTransaction)
{
_isolationLevel = iso;
_connection = con;
if (internalTransaction == null)
{
_internalTransaction = new SqlInternalTransaction(internalConnection, TransactionType.LocalFromAPI, this);
}
else
{
Debug.Assert(internalConnection.CurrentTransaction == internalTransaction, "Unexpected Parser.CurrentTransaction state!");
_internalTransaction = internalTransaction;
_internalTransaction.InitParent(this);
}
}
////////////////////////////////////////////////////////////////////////////////////////
// PROPERTIES
////////////////////////////////////////////////////////////////////////////////////////
new public SqlConnection Connection
{
get
{
if (IsZombied)
{
return null;
}
else
{
return _connection;
}
}
}
override protected DbConnection DbConnection
{
get
{
return Connection;
}
}
internal SqlInternalTransaction InternalTransaction
{
get
{
return _internalTransaction;
}
}
override public IsolationLevel IsolationLevel
{
get
{
ZombieCheck();
return _isolationLevel;
}
}
private bool IsYukonPartialZombie
{
get
{
return (null != _internalTransaction && _internalTransaction.IsCompleted);
}
}
internal bool IsZombied
{
get
{
return (null == _internalTransaction || _internalTransaction.IsCompleted);
}
}
internal SqlStatistics Statistics
{
get
{
if (null != _connection)
{
if (_connection.StatisticsEnabled)
{
return _connection.Statistics;
}
}
return null;
}
}
////////////////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS
////////////////////////////////////////////////////////////////////////////////////////
override public void Commit()
{
ZombieCheck();
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
_isFromAPI = true;
_internalTransaction.Commit();
}
finally
{
_isFromAPI = false;
SqlStatistics.StopTimer(statistics);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (!IsZombied && !IsYukonPartialZombie)
{
_internalTransaction.Dispose();
}
}
base.Dispose(disposing);
}
override public void Rollback()
{
if (IsYukonPartialZombie)
{
// Put something in the trace in case a customer has an issue
_internalTransaction = null; // yukon zombification
}
else
{
ZombieCheck();
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
_isFromAPI = true;
_internalTransaction.Rollback();
}
finally
{
_isFromAPI = false;
SqlStatistics.StopTimer(statistics);
}
}
}
public void Rollback(string transactionName)
{
ZombieCheck();
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
_isFromAPI = true;
_internalTransaction.Rollback(transactionName);
}
finally
{
_isFromAPI = false;
SqlStatistics.StopTimer(statistics);
}
}
public void Save(string savePointName)
{
ZombieCheck();
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
_internalTransaction.Save(savePointName);
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
////////////////////////////////////////////////////////////////////////////////////////
// INTERNAL METHODS
////////////////////////////////////////////////////////////////////////////////////////
internal void Zombie()
{
// For Yukon, we have to defer "zombification" until
// we get past the users' next rollback, else we'll
// throw an exception there that is a breaking change.
// Of course, if the connection is aready closed,
// then we're free to zombify...
SqlInternalConnection internalConnection = (_connection.InnerConnection as SqlInternalConnection);
if (internalConnection == null || _isFromAPI)
{
_internalTransaction = null; // pre-yukon zombification
}
}
////////////////////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
////////////////////////////////////////////////////////////////////////////////////////
private void ZombieCheck()
{
// If this transaction has been completed, throw exception since it is unusable.
if (IsZombied)
{
if (IsYukonPartialZombie)
{
_internalTransaction = null; // yukon zombification
}
throw ADP.TransactionZombied(this);
}
}
}
}
| |
/**
* 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.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace Flood.Serialization
{
public class CompactSerializer : Serializer
{
private static DataObject ANONYMOUS_STRUCT = new DataObject("");
private static Field TSTOP = new Field("", DataType.Stop, (short)0);
private static byte[] ttypeToCompactType = new byte[16];
/**
* All of the on-wire type codes.
*/
private static class Types
{
public const byte STOP = 0x00;
public const byte BOOLEAN_TRUE = 0x01;
public const byte BOOLEAN_FALSE = 0x02;
public const byte BYTE = 0x03;
public const byte I16 = 0x04;
public const byte I32 = 0x05;
public const byte I64 = 0x06;
public const byte DOUBLE = 0x07;
public const byte BINARY = 0x08;
public const byte LIST = 0x09;
public const byte SET = 0x0A;
public const byte MAP = 0x0B;
public const byte DATA_OBJECT = 0x0C;
}
/**
* Used to keep track of the last field for the current and previous structs,
* so we can do the delta stuff.
*/
private Stack<short> lastField_ = new Stack<short>(15);
private short lastFieldId_ = 0;
/**
* If we encounter a boolean field begin, save the TField here so it can
* have the value incorporated.
*/
private Nullable<Field> booleanField_;
/**
* If we Read a field header, and it's a boolean field, save the boolean
* value here so that ReadBool can use it.
*/
private Nullable<Boolean> boolValue_;
public CompactSerializer(System.IO.Stream stream)
:base(stream)
{
ttypeToCompactType[(int)DataType.Stop] = Types.STOP;
ttypeToCompactType[(int)DataType.Bool] = Types.BOOLEAN_TRUE;
ttypeToCompactType[(int)DataType.Byte] = Types.BYTE;
ttypeToCompactType[(int)DataType.I16] = Types.I16;
ttypeToCompactType[(int)DataType.I32] = Types.I32;
ttypeToCompactType[(int)DataType.I64] = Types.I64;
ttypeToCompactType[(int)DataType.Double] = Types.DOUBLE;
ttypeToCompactType[(int)DataType.String] = Types.BINARY;
ttypeToCompactType[(int)DataType.List] = Types.LIST;
ttypeToCompactType[(int)DataType.Map] = Types.MAP;
}
public void reset()
{
lastField_.Clear();
lastFieldId_ = 0;
}
#region Write Methods
/**
* Writes a byte without any possibility of all that field header nonsense.
* Used internally by other writing methods that know they need to Write a byte.
*/
private byte[] byteDirectBuffer = new byte[1];
private void WriteByteDirect(byte b)
{
byteDirectBuffer[0] = b;
Buffer.Write(byteDirectBuffer, 0, byteDirectBuffer.Length);
}
/**
* Writes a byte without any possibility of all that field header nonsense.
*/
private void WriteByteDirect(int n)
{
WriteByteDirect((byte)n);
}
/**
* Write an i32 as a varint. Results in 1-5 bytes on the wire.
* TODO: make a permanent buffer like WriteVarint64?
*/
byte[] i32buf = new byte[5];
private void WriteVarint32(uint n)
{
int idx = 0;
while (true)
{
if ((n & ~0x7F) == 0)
{
i32buf[idx++] = (byte)n;
// WriteByteDirect((byte)n);
break;
// return;
}
else
{
i32buf[idx++] = (byte)((n & 0x7F) | 0x80);
// WriteByteDirect((byte)((n & 0x7F) | 0x80));
n >>= 7;
}
}
Buffer.Write(i32buf, 0, idx);
}
/**
* Write a struct begin. This doesn't actually put anything on the wire. We
* use it as an opportunity to put special placeholder markers on the field
* stack so we can get the field id deltas correct.
*/
public override void WriteDataObjectBegin(DataObject strct)
{
lastField_.Push(lastFieldId_);
lastFieldId_ = 0;
}
/**
* Write a struct end. This doesn't actually put anything on the wire. We use
* this as an opportunity to pop the last field from the current struct off
* of the field stack.
*/
public override void WriteDataObjectEnd()
{
lastFieldId_ = lastField_.Pop();
}
/**
* Write a field header containing the field id and field type. If the
* difference between the current field id and the last one is small (< 15),
* then the field id will be encoded in the 4 MSB as a delta. Otherwise, the
* field id will follow the type header as a zigzag varint.
*/
public override void WriteFieldBegin(Field field)
{
if (field.Type == DataType.Bool)
{
// we want to possibly include the value, so we'll wait.
booleanField_ = field;
}
else
{
WriteFieldBeginInternal(field, 0xFF);
}
}
/**
* The workhorse of WriteFieldBegin. It has the option of doing a
* 'type override' of the type header. This is used specifically in the
* boolean field case.
*/
private void WriteFieldBeginInternal(Field field, byte typeOverride)
{
// short lastField = lastField_.Pop();
// if there's a type override, use that.
byte typeToWrite = typeOverride == 0xFF ? getCompactType(field.Type) : typeOverride;
// check if we can use delta encoding for the field id
if (field.ID > lastFieldId_ && field.ID - lastFieldId_ <= 15)
{
// Write them together
WriteByteDirect((field.ID - lastFieldId_) << 4 | typeToWrite);
}
else
{
// Write them separate
WriteByteDirect(typeToWrite);
WriteI16(field.ID);
}
lastFieldId_ = field.ID;
// lastField_.push(field.id);
}
/**
* Write the STOP symbol so we know there are no more fields in this struct.
*/
public override void WriteFieldStop()
{
WriteByteDirect(Types.STOP);
}
/**
* Write a map header. If the map is empty, omit the key and value type
* headers, as we don't need any additional information to skip it.
*/
public override void WriteMapBegin(TMap map)
{
if (map.Count == 0)
{
WriteByteDirect(0);
}
else
{
WriteVarint32((uint)map.Count);
WriteByteDirect(getCompactType(map.KeyType) << 4 | getCompactType(map.ValueType));
}
}
/**
* Write a array header.
*/
public override void WriteListBegin(TList list)
{
WriteCollectionBegin(list.ElementType, list.Count);
}
/**
* Write a boolean value. Potentially, this could be a boolean field, in
* which case the field header info isn't written yet. If so, decide what the
* right type header is for the value and then Write the field header.
* Otherwise, Write a single byte.
*/
public override void WriteBool(Boolean b)
{
if (booleanField_ != null)
{
// we haven't written the field header yet
WriteFieldBeginInternal(booleanField_.Value, b ? Types.BOOLEAN_TRUE : Types.BOOLEAN_FALSE);
booleanField_ = null;
}
else
{
// we're not part of a field, so just Write the value.
WriteByteDirect(b ? Types.BOOLEAN_TRUE : Types.BOOLEAN_FALSE);
}
}
/**
* Write a byte. Nothing to see here!
*/
public override void WriteByte(byte b)
{
WriteByteDirect(b);
}
/**
* Write an I16 as a zigzag varint.
*/
public override void WriteI16(short i16)
{
WriteVarint32(intToZigZag(i16));
}
/**
* Write an i32 as a zigzag varint.
*/
public override void WriteI32(int i32)
{
WriteVarint32(intToZigZag(i32));
}
/**
* Write an i64 as a zigzag varint.
*/
public override void WriteI64(long i64)
{
WriteVarint64(longToZigzag(i64));
}
/**
* Write a double to the wire as 8 bytes.
*/
public override void WriteDouble(double dub)
{
byte[] data = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
fixedLongToBytes(BitConverter.DoubleToInt64Bits(dub), data, 0);
Buffer.Write(data, 0, data.Length);
}
/**
* Write a string to the wire with a varint size preceding.
*/
public override void WriteString(String str)
{
byte[] bytes = UTF8Encoding.UTF8.GetBytes(str);
WriteBinary(bytes, 0, bytes.Length);
}
/**
* Write a byte array, using a varint for the size.
*/
public override void WriteBinary(byte[] bin)
{
WriteBinary(bin, 0, bin.Length);
}
private void WriteBinary(byte[] buf, int offset, int length)
{
WriteVarint32((uint)length);
Buffer.Write(buf, offset, length);
}
//
// These methods are called by structs, but don't actually have any wire
// output or purpose.
//
public override void WriteMapEnd() { }
public override void WriteListEnd() { }
public override void WriteFieldEnd() { }
//
// Internal writing methods
//
/**
* Abstract method for writing the start of lists and sets. List and sets on
* the wire differ only by the type indicator.
*/
protected void WriteCollectionBegin(DataType elemType, int size)
{
if (size <= 14)
{
WriteByteDirect(size << 4 | getCompactType(elemType));
}
else
{
WriteByteDirect(0xf0 | getCompactType(elemType));
WriteVarint32((uint)size);
}
}
/**
* Write an i64 as a varint. Results in 1-10 bytes on the wire.
*/
byte[] varint64out = new byte[10];
private void WriteVarint64(ulong n)
{
int idx = 0;
while (true)
{
if ((n & ~(ulong)0x7FL) == 0)
{
varint64out[idx++] = (byte)n;
break;
}
else
{
varint64out[idx++] = ((byte)((n & 0x7F) | 0x80));
n >>= 7;
}
}
Buffer.Write(varint64out, 0, idx);
}
/**
* Convert l into a zigzag long. This allows negative numbers to be
* represented compactly as a varint.
*/
private ulong longToZigzag(long n)
{
return (ulong)(((ulong)n << 1) ^ ((ulong)n >> 63));
}
/**
* Convert n into a zigzag int. This allows negative numbers to be
* represented compactly as a varint.
*/
private uint intToZigZag(int n)
{
return (uint)(((uint)n << 1) ^ ((uint)n >> 31));
}
/**
* Convert a long into little-endian bytes in buf starting at off and going
* until off+7.
*/
private void fixedLongToBytes(long n, byte[] buf, int off)
{
buf[off + 0] = (byte)(n & 0xff);
buf[off + 1] = (byte)((n >> 8) & 0xff);
buf[off + 2] = (byte)((n >> 16) & 0xff);
buf[off + 3] = (byte)((n >> 24) & 0xff);
buf[off + 4] = (byte)((n >> 32) & 0xff);
buf[off + 5] = (byte)((n >> 40) & 0xff);
buf[off + 6] = (byte)((n >> 48) & 0xff);
buf[off + 7] = (byte)((n >> 56) & 0xff);
}
#endregion
#region ReadMethods
/**
* Read a struct begin. There's nothing on the wire for this, but it is our
* opportunity to push a new struct begin marker onto the field stack.
*/
public override DataObject ReadDataObjectBegin()
{
lastField_.Push(lastFieldId_);
lastFieldId_ = 0;
return ANONYMOUS_STRUCT;
}
/**
* Doesn't actually consume any wire data, just removes the last field for
* this struct from the field stack.
*/
public override void ReadDataObjectEnd()
{
// consume the last field we Read off the wire.
lastFieldId_ = lastField_.Pop();
}
/**
* Read a field header off the wire.
*/
public override Field ReadFieldBegin()
{
byte type = ReadByte();
// if it's a stop, then we can return immediately, as the struct is over.
if (type == Types.STOP)
{
return TSTOP;
}
short fieldId;
// mask off the 4 MSB of the type header. it could contain a field id delta.
short modifier = (short)((type & 0xf0) >> 4);
if (modifier == 0)
{
// not a delta. look ahead for the zigzag varint field id.
fieldId = ReadI16();
}
else
{
// has a delta. add the delta to the last Read field id.
fieldId = (short)(lastFieldId_ + modifier);
}
Field field = new Field("", getTType((byte)(type & 0x0f)), fieldId);
// if this happens to be a boolean field, the value is encoded in the type
if (isBoolType(type))
{
// save the boolean value in a special instance variable.
boolValue_ = (byte)(type & 0x0f) == Types.BOOLEAN_TRUE ? true : false;
}
// push the new field onto the field stack so we can keep the deltas going.
lastFieldId_ = field.ID;
return field;
}
/**
* Read a map header off the wire. If the size is zero, skip Reading the key
* and value type. This means that 0-length maps will yield TMaps without the
* "correct" types.
*/
public override TMap ReadMapBegin()
{
int size = (int)ReadVarint32();
byte keyAndValueType = size == 0 ? (byte)0 : ReadByte();
return new TMap(getTType((byte)(keyAndValueType >> 4)), getTType((byte)(keyAndValueType & 0xf)), size);
}
/**
* Read a array header off the wire. If the array size is 0-14, the size will
* be packed into the element type header. If it's a longer array, the 4 MSB
* of the element type header will be 0xF, and a varint will follow with the
* true size.
*/
public override TList ReadListBegin()
{
byte size_and_type = ReadByte();
int size = (size_and_type >> 4) & 0x0f;
if (size == 15)
{
size = (int)ReadVarint32();
}
DataType type = getTType(size_and_type);
return new TList(type, size);
}
/**
* Read a boolean off the wire. If this is a boolean field, the value should
* already have been Read during ReadFieldBegin, so we'll just consume the
* pre-stored value. Otherwise, Read a byte.
*/
public override Boolean ReadBool()
{
if (boolValue_ != null)
{
bool result = boolValue_.Value;
boolValue_ = null;
return result;
}
return ReadByte() == Types.BOOLEAN_TRUE;
}
byte[] byteRawBuf = new byte[1];
/**
* Read a single byte off the wire. Nothing interesting here.
*/
public override byte ReadByte()
{
Buffer.Read(byteRawBuf, 0, 1);
return byteRawBuf[0];
}
/**
* Read an i16 from the wire as a zigzag varint.
*/
public override short ReadI16()
{
return (short)zigzagToInt(ReadVarint32());
}
/**
* Read an i32 from the wire as a zigzag varint.
*/
public override int ReadI32()
{
return zigzagToInt(ReadVarint32());
}
/**
* Read an i64 from the wire as a zigzag varint.
*/
public override long ReadI64()
{
return zigzagToLong(ReadVarint64());
}
/**
* No magic here - just Read a double off the wire.
*/
public override double ReadDouble()
{
byte[] longBits = new byte[8];
Buffer.Read(longBits, 0, 8);
return BitConverter.Int64BitsToDouble(bytesToLong(longBits));
}
/**
* Reads a byte[] (via ReadBinary), and then UTF-8 decodes it.
*/
public override String ReadString()
{
int length = (int)ReadVarint32();
if (length == 0)
{
return "";
}
return Encoding.UTF8.GetString(ReadBinary(length));
}
/**
* Read a byte[] from the wire.
*/
public override byte[] ReadBinary()
{
int length = (int)ReadVarint32();
if (length == 0) return new byte[0];
byte[] buf = new byte[length];
Buffer.Read(buf, 0, length);
return buf;
}
/**
* Read a byte[] of a known length from the wire.
*/
private byte[] ReadBinary(int length)
{
if (length == 0) return new byte[0];
byte[] buf = new byte[length];
Buffer.Read(buf, 0, length);
return buf;
}
//
// These methods are here for the struct to call, but don't have any wire
// encoding.
//
public override void ReadFieldEnd() { }
public override void ReadMapEnd() { }
public override void ReadListEnd() { }
//
// Internal Reading methods
//
/**
* Read an i32 from the wire as a varint. The MSB of each byte is collection
* if there is another byte to follow. This can Read up to 5 bytes.
*/
private uint ReadVarint32()
{
uint result = 0;
int shift = 0;
while (true)
{
byte b = ReadByte();
result |= (uint)(b & 0x7f) << shift;
if ((b & 0x80) != 0x80) break;
shift += 7;
}
return result;
}
/**
* Read an i64 from the wire as a proper varint. The MSB of each byte is collection
* if there is another byte to follow. This can Read up to 10 bytes.
*/
private ulong ReadVarint64()
{
int shift = 0;
ulong result = 0;
while (true)
{
byte b = ReadByte();
result |= (ulong)(b & 0x7f) << shift;
if ((b & 0x80) != 0x80) break;
shift += 7;
}
return result;
}
#endregion
//
// encoding helpers
//
/**
* Convert from zigzag int to int.
*/
private int zigzagToInt(uint n)
{
return (int)(n >> 1) ^ (-(int)(n & 1));
}
/**
* Convert from zigzag long to long.
*/
private long zigzagToLong(ulong n)
{
return (long)(n >> 1) ^ (-(long)(n & 1));
}
/**
* Note that it's important that the mask bytes are long literals,
* otherwise they'll default to ints, and when you shift an int left 56 bits,
* you just get a messed up int.
*/
private long bytesToLong(byte[] bytes)
{
return
((bytes[7] & 0xffL) << 56) |
((bytes[6] & 0xffL) << 48) |
((bytes[5] & 0xffL) << 40) |
((bytes[4] & 0xffL) << 32) |
((bytes[3] & 0xffL) << 24) |
((bytes[2] & 0xffL) << 16) |
((bytes[1] & 0xffL) << 8) |
((bytes[0] & 0xffL));
}
//
// type testing and converting
//
private Boolean isBoolType(byte b)
{
int lowerNibble = b & 0x0f;
return lowerNibble == Types.BOOLEAN_TRUE || lowerNibble == Types.BOOLEAN_FALSE;
}
/**
* Given a TCompactProtocol.Types constant, convert it to its corresponding
* DataType value.
*/
private DataType getTType(byte type)
{
switch ((byte)(type & 0x0f))
{
case Types.STOP:
return DataType.Stop;
case Types.BOOLEAN_FALSE:
case Types.BOOLEAN_TRUE:
return DataType.Bool;
case Types.BYTE:
return DataType.Byte;
case Types.I16:
return DataType.I16;
case Types.I32:
return DataType.I32;
case Types.I64:
return DataType.I64;
case Types.DOUBLE:
return DataType.Double;
case Types.BINARY:
return DataType.String;
case Types.LIST:
return DataType.List;
case Types.MAP:
return DataType.Map;
default:
throw new SerializerException("don't know what type: " + (byte)(type & 0x0f));
}
}
/**
* Given a DataType value, find the appropriate TCompactProtocol.Types constant.
*/
private byte getCompactType(DataType ttype)
{
return ttypeToCompactType[(int)ttype];
}
}
}
| |
/*
Copyright 2008 The 'A Concurrent Hashtable' development team
(http://www.codeplex.com/CH/People/ProjectPeople.aspx)
This library is licensed under the GNU Library General Public License (LGPL). You should
have received a copy of the license along with the source code. If not, an online copy
of the license can be found at http://www.codeplex.com/CH/license.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace Orvid.Concurrent.Collections
{
/// <summary>
/// Base class for concurrent hashtable implementations
/// </summary>
/// <typeparam name="TStored">Type of the items stored in the hashtable.</typeparam>
/// <typeparam name="TSearch">Type of the key to search with.</typeparam>
public abstract class ConcurrentHashtable<TStored, TSearch>
{
/// <summary>
/// Constructor (protected)
/// </summary>
/// <remarks>Use Initialize method after construction.</remarks>
protected ConcurrentHashtable()
{}
/// <summary>
/// Initialize the newly created ConcurrentHashtable. Invoke in final (sealed) constructor
/// or Create method.
/// </summary>
protected virtual void Initialize()
{
var minSegments = MinSegments;
var segmentAllocatedSpace = MinSegmentAllocatedSpace;
_CurrentRange = CreateSegmentRange(minSegments, segmentAllocatedSpace);
_NewRange = _CurrentRange;
_SwitchPoint = 0;
_AllocatedSpace = minSegments * segmentAllocatedSpace;
}
/// <summary>
/// Create a segment range
/// </summary>
/// <param name="segmentCount">Number of segments in range.</param>
/// <param name="initialSegmentSize">Number of slots allocated initialy in each segment.</param>
/// <returns>The created <see cref="Segmentrange{TStored,TSearch}"/> instance.</returns>
internal virtual Segmentrange<TStored, TSearch> CreateSegmentRange(int segmentCount, int initialSegmentSize)
{ return Segmentrange<TStored, TSearch>.Create(segmentCount, initialSegmentSize); }
/// <summary>
/// While adjusting the segmentation, _NewRange will hold a reference to the new range of segments.
/// when the adjustment is complete this reference will be copied to _CurrentRange.
/// </summary>
internal Segmentrange<TStored, TSearch> _NewRange;
/// <summary>
/// Will hold the most current reange of segments. When busy adjusting the segmentation, this
/// field will hold a reference to the old range.
/// </summary>
internal Segmentrange<TStored, TSearch> _CurrentRange;
/// <summary>
/// While adjusting the segmentation this field will hold a boundary.
/// Clients accessing items with a key hash value below this boundary (unsigned compared)
/// will access _NewRange. The others will access _CurrentRange
/// </summary>
Int32 _SwitchPoint;
#region Traits
//Methods used by Segment objects that tell them how to treat stored items and search keys.
/// <summary>
/// Get a hashcode for given storeable item.
/// </summary>
/// <param name="item">Reference to the item to get a hash value for.</param>
/// <returns>The hash value as an <see cref="UInt32"/>.</returns>
/// <remarks>
/// The hash returned should be properly randomized hash. The standard GetItemHashCode methods are usually not good enough.
/// A storeable item and a matching search key should return the same hash code.
/// So the statement <code>ItemEqualsItem(storeableItem, searchKey) ? GetItemHashCode(storeableItem) == GetItemHashCode(searchKey) : true </code> should always be true;
/// </remarks>
internal protected abstract UInt32 GetItemHashCode(ref TStored item);
/// <summary>
/// Get a hashcode for given search key.
/// </summary>
/// <param name="key">Reference to the key to get a hash value for.</param>
/// <returns>The hash value as an <see cref="UInt32"/>.</returns>
/// <remarks>
/// The hash returned should be properly randomized hash. The standard GetItemHashCode methods are usually not good enough.
/// A storeable item and a matching search key should return the same hash code.
/// So the statement <code>ItemEqualsItem(storeableItem, searchKey) ? GetItemHashCode(storeableItem) == GetItemHashCode(searchKey) : true </code> should always be true;
/// </remarks>
internal protected abstract UInt32 GetKeyHashCode(ref TSearch key);
/// <summary>
/// Compares a storeable item to a search key. Should return true if they match.
/// </summary>
/// <param name="item">Reference to the storeable item to compare.</param>
/// <param name="key">Reference to the search key to compare.</param>
/// <returns>True if the storeable item and search key match; false otherwise.</returns>
internal protected abstract bool ItemEqualsKey(ref TStored item, ref TSearch key);
/// <summary>
/// Compares two storeable items for equality.
/// </summary>
/// <param name="item1">Reference to the first storeable item to compare.</param>
/// <param name="item2">Reference to the second storeable item to compare.</param>
/// <returns>True if the two soreable items should be regarded as equal.</returns>
internal protected abstract bool ItemEqualsItem(ref TStored item1, ref TStored item2);
/// <summary>
/// Indicates if a specific item reference contains a valid item.
/// </summary>
/// <param name="item">The storeable item reference to check.</param>
/// <returns>True if the reference doesn't refer to a valid item; false otherwise.</returns>
/// <remarks>The statement <code>IsEmpty(default(TStoredI))</code> should always be true.</remarks>
internal protected abstract bool IsEmpty(ref TStored item);
/// <summary>
/// Returns the type of the key value or object.
/// </summary>
/// <param name="item">The stored item to get the type of the key for.</param>
/// <returns>The actual type of the key or null if it can not be determined.</returns>
/// <remarks>
/// Used for diagnostics purposes.
/// </remarks>
internal protected virtual Type GetKeyType(ref TStored item)
{ return item == null ? null : item.GetType(); }
#endregion
#region SyncRoot
readonly object _SyncRoot = new object();
/// <summary>
/// Returns an object that serves as a lock for range operations
/// </summary>
/// <remarks>
/// Clients use this primarily for enumerating over the Tables contents.
/// Locking doesn't guarantee that the contents don't change, but prevents operations that would
/// disrupt the enumeration process.
/// Operations that use this lock:
/// Count, Clear, DisposeGarbage and AssessSegmentation.
/// Keeping this lock will prevent the table from re-segmenting.
/// </remarks>
protected object SyncRoot { get { return _SyncRoot; } }
#endregion
#region Per segment accessors
/// <summary>
/// Gets a segment out of either _NewRange or _CurrentRange based on the hash value.
/// </summary>
/// <param name="hash"></param>
/// <returns></returns>
internal Segment<TStored, TSearch> GetSegment(UInt32 hash)
{ return ((UInt32)hash < (UInt32)_SwitchPoint ? _NewRange : _CurrentRange).GetSegment(hash); }
/// <summary>
/// Gets a LOCKED segment out of either _NewRange or _CurrentRange based on the hash value.
/// Unlock needs to be called on this segment before it can be used by other clients.
/// </summary>
/// <param name="hash"></param>
/// <returns></returns>
internal Segment<TStored, TSearch> GetSegmentLockedForWriting(UInt32 hash)
{
while (true)
{
var segment = GetSegment(hash);
segment.LockForWriting();
if (segment.IsAlive)
return segment;
segment.ReleaseForWriting();
}
}
/// <summary>
/// Gets a LOCKED segment out of either _NewRange or _CurrentRange based on the hash value.
/// Unlock needs to be called on this segment before it can be used by other clients.
/// </summary>
/// <param name="hash"></param>
/// <returns></returns>
internal Segment<TStored, TSearch> GetSegmentLockedForReading(UInt32 hash)
{
while (true)
{
var segment = GetSegment(hash);
segment.LockForReading();
if (segment.IsAlive)
return segment;
segment.ReleaseForReading();
}
}
/// <summary>
/// Finds an item in the table collection that maches the given searchKey
/// </summary>
/// <param name="searchKey">The key to the item.</param>
/// <param name="item">Out reference to a field that will receive the found item.</param>
/// <returns>A boolean that will be true if an item has been found and false otherwise.</returns>
protected bool FindItem(ref TSearch searchKey, out TStored item)
{
var segment = GetSegmentLockedForReading(this.GetKeyHashCode(ref searchKey));
try
{
return segment.FindItem(ref searchKey, out item, this);
}
finally
{ segment.ReleaseForReading(); }
}
/// <summary>
/// Looks for an existing item in the table contents using an alternative copy. If it can be found it will be returned.
/// If not then the alternative copy will be added to the table contents and the alternative copy will be returned.
/// </summary>
/// <param name="searchKey">A copy to search an already existing instance with</param>
/// <param name="item">Out reference to receive the found item or the alternative copy</param>
/// <returns>A boolean that will be true if an existing copy was found and false otherwise.</returns>
protected virtual bool GetOldestItem(ref TStored searchKey, out TStored item)
{
var segment = GetSegmentLockedForWriting(this.GetItemHashCode(ref searchKey));
try
{
return segment.GetOldestItem(ref searchKey, out item, this);
}
finally
{ segment.ReleaseForWriting(); }
}
/// <summary>
/// Replaces and existing item
/// </summary>
/// <param name="newItem"></param>
/// <param name="oldItem"></param>
/// <param name="sanction"></param>
/// <returns>true is the existing item was successfully replaced.</returns>
protected bool ReplaceItem(ref TSearch searchKey, ref TStored newItem, out TStored oldItem, Func<TStored,bool> sanction)
{
var segment = GetSegmentLockedForWriting(this.GetItemHashCode(ref newItem));
try
{
TStored dummy;
if (!segment.InsertItem(ref newItem, out oldItem, this))
{
segment.RemoveItem(ref searchKey, out dummy, this);
return false;
}
if (sanction(oldItem))
return true;
segment.InsertItem(ref oldItem, out dummy, this);
return false;
}
finally
{ segment.ReleaseForWriting(); }
}
/// <summary>
/// Inserts an item in the table contents possibly replacing an existing item.
/// </summary>
/// <param name="searchKey">The item to insert in the table</param>
/// <param name="replacedItem">Out reference to a field that will receive any possibly replaced item.</param>
/// <returns>A boolean that will be true if an existing copy was found and replaced and false otherwise.</returns>
protected bool InsertItem(ref TStored searchKey, out TStored replacedItem)
{
var segment = GetSegmentLockedForWriting(this.GetItemHashCode(ref searchKey));
try
{
return segment.InsertItem(ref searchKey, out replacedItem, this);
}
finally
{ segment.ReleaseForWriting(); }
}
/// <summary>
/// Removes an item from the table contents.
/// </summary>
/// <param name="searchKey">The key to find the item with.</param>
/// <param name="removedItem">Out reference to a field that will receive the found and removed item.</param>
/// <returns>A boolean that will be rue if an item was found and removed and false otherwise.</returns>
protected bool RemoveItem(ref TSearch searchKey, out TStored removedItem)
{
var segment = GetSegmentLockedForWriting(this.GetKeyHashCode(ref searchKey));
try
{
return segment.RemoveItem(ref searchKey, out removedItem, this);
}
finally
{ segment.ReleaseForWriting(); }
}
#endregion
#region Collection wide accessors
//These methods require a lock on SyncRoot. They will not block regular per segment accessors (for long)
/// <summary>
/// Enumerates all segments in _CurrentRange and locking them before yielding them and resleasing the lock afterwards
/// The order in which the segments are returned is undefined.
/// Lock SyncRoot before using this enumerable.
/// </summary>
/// <returns></returns>
internal IEnumerable<Segment<TStored, TSearch>> EnumerateAmorphLockedSegments(bool forReading)
{
//if segments are locked a queue will be created to try them later
//this is so that we can continue with other not locked segments.
Queue<Segment<TStored, TSearch>> lockedSegmentIxs = null;
for (int i = 0, end = _CurrentRange.Count; i != end; ++i)
{
var segment = _CurrentRange.GetSegmentByIndex(i);
if (segment.Lock(forReading))
{
try { yield return segment; }
finally { segment.Release(forReading); }
}
else
{
if (lockedSegmentIxs == null)
lockedSegmentIxs = new Queue<Segment<TStored, TSearch>>();
lockedSegmentIxs.Enqueue(segment);
}
}
if (lockedSegmentIxs != null)
{
var ctr = lockedSegmentIxs.Count;
while (lockedSegmentIxs.Count != 0)
{
//once we retried them all and we are still not done.. wait a bit.
if (ctr-- == 0)
{
Thread.Sleep(0);
ctr = lockedSegmentIxs.Count;
}
var segment = lockedSegmentIxs.Dequeue();
if (segment.Lock(forReading))
{
try { yield return segment; }
finally { segment.Release(forReading); }
}
else
lockedSegmentIxs.Enqueue(segment);
}
}
}
/// <summary>
/// Gets an IEnumerable to iterate over all items in all segments.
/// </summary>
/// <returns></returns>
/// <remarks>
/// A lock should be aquired and held on SyncRoot while this IEnumerable is being used.
/// The order in which the items are returned is undetermined.
/// </remarks>
protected IEnumerable<TStored> Items
{
get
{
foreach (var segment in EnumerateAmorphLockedSegments(true))
{
int j = -1;
TStored foundItem;
while ((j = segment.GetNextItem(j, out foundItem, this)) >= 0)
yield return foundItem;
}
}
}
/// <summary>
/// Removes all items from the collection.
/// Aquires a lock on SyncRoot before it does it's thing.
/// When this method returns and multiple threads have access to this table it
/// is not guaranteed that the table is actually empty.
/// </summary>
protected void Clear()
{
lock(SyncRoot)
foreach(var segment in EnumerateAmorphLockedSegments(false))
segment.Clear(this);
}
/// <summary>
/// Returns a count of all items in teh collection. This may not be
/// aqurate when multiple threads are accessing this table.
/// Aquires a lock on SyncRoot before it does it's thing.
/// </summary>
protected int Count
{
get
{
lock (SyncRoot)
{
Int32 count = 0;
//Don't need to lock a segment to get the count.
for (int i = 0, end = _CurrentRange.Count; i != end; ++i)
count += _CurrentRange.GetSegmentByIndex(i)._Count;
return count;
}
}
}
#endregion
#region Table Maintenance methods
/// <summary>
/// Gives the minimum number of segments a hashtable can contain. This should be 1 or more and always a power of 2.
/// </summary>
protected virtual Int32 MinSegments { get { return 4; } }
/// <summary>
/// Gives the minimum number of allocated item slots per segment. This should be 1 or more, always a power of 2
/// and less than 1/2 of MeanSegmentAllocatedSpace.
/// </summary>
protected virtual Int32 MinSegmentAllocatedSpace { get { return 4; } }
/// <summary>
/// Gives the prefered number of allocated item slots per segment. This should be 4 or more and always a power of 2.
/// </summary>
protected virtual Int32 MeanSegmentAllocatedSpace { get { return 16; } }
/// <summary>
/// Determines if a segmentation adjustment is needed.
/// </summary>
/// <returns>True</returns>
bool SegmentationAdjustmentNeeded()
{
var minSegments = MinSegments;
var meanSegmentAllocatedSpace = MeanSegmentAllocatedSpace;
var newSpace = Math.Max(_AllocatedSpace, minSegments * meanSegmentAllocatedSpace);
var meanSpace = _CurrentRange.Count * meanSegmentAllocatedSpace;
return newSpace > (meanSpace << 1) || newSpace <= (meanSpace >> 1);
}
/// <summary>
/// Bool as int (for interlocked functions) that is true if a Segmentation assesment is pending.
/// </summary>
Int32 _AssessSegmentationPending;
/// <summary>
/// The total allocated number of item slots. Filled with nonempty items or not.
/// </summary>
Int32 _AllocatedSpace;
/// <summary>
/// When a segment resizes it uses this method to inform the hashtable of the change in allocated space.
/// </summary>
/// <param name="effect"></param>
internal void EffectTotalAllocatedSpace(Int32 effect)
{
//this might be a point of contention. But resizing of segments should happen (far) less often
//than inserts and removals and therefore this should not pose a problem.
Interlocked.Add(ref _AllocatedSpace, effect);
if ( SegmentationAdjustmentNeeded() && Interlocked.Exchange(ref _AssessSegmentationPending, 1) == 0 )
ThreadPool.QueueUserWorkItem(AssessSegmentation);
}
/// <summary>
/// Schedule a call to the AssessSegmentation() method.
/// </summary>
protected void ScheduleMaintenance()
{
if (Interlocked.Exchange(ref _AssessSegmentationPending, 1) == 0)
ThreadPool.QueueUserWorkItem(AssessSegmentation);
}
/// <summary>
/// Checks if segmentation needs to be adjusted and if so performs the adjustment.
/// </summary>
/// <param name="dummy"></param>
void AssessSegmentation(object dummy)
{
try
{
AssessSegmentation();
}
finally
{
Interlocked.Exchange(ref _AssessSegmentationPending, 0);
EffectTotalAllocatedSpace(0);
}
}
/// <summary>
/// This method is called when a re-segmentation is expected to be needed. It checks if it actually is needed and, if so, performs the re-segementation.
/// </summary>
protected virtual void AssessSegmentation()
{
//in case of a sudden loss of almost all content we
//may need to do this multiple times.
while (SegmentationAdjustmentNeeded())
{
var meanSegmentAllocatedSpace = MeanSegmentAllocatedSpace;
int allocatedSpace = _AllocatedSpace;
int atleastSegments = allocatedSpace / meanSegmentAllocatedSpace;
Int32 segments = MinSegments;
while (atleastSegments > segments)
segments <<= 1;
SetSegmentation(segments, meanSegmentAllocatedSpace);
}
}
/// <summary>
/// Adjusts the segmentation to the new segment count
/// </summary>
/// <param name="newSegmentCount">The new number of segments to use. This must be a power of 2.</param>
/// <param name="segmentSize">The number of item slots to reserve in each segment.</param>
void SetSegmentation(Int32 newSegmentCount, Int32 segmentSize)
{
//Variables to detect a bad hash.
var totalNewSegmentSize = 0;
var largestSegmentSize = 0;
Segment<TStored,TSearch> largestSegment = null;
lock (SyncRoot)
{
#if DEBUG
//<<<<<<<<<<<<<<<<<<<< debug <<<<<<<<<<<<<<<<<<<<<<<<
//{
// int minSize = _CurrentRange.GetSegmentByIndex(0)._List.Length;
// int maxSize = minSize;
// for (int i = 1, end = _CurrentRange.Count; i < end; ++i)
// {
// int currentSize = _CurrentRange.GetSegmentByIndex(i)._List.Length;
// if (currentSize < minSize)
// minSize = currentSize;
// if (currentSize > maxSize)
// maxSize = currentSize;
// }
// System.Diagnostics.Debug.Assert(maxSize <= 8 * minSize, "Probably a bad hash");
//}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#endif
unchecked
{
//create the new range
Segmentrange<TStored, TSearch> newRange = CreateSegmentRange(newSegmentCount, segmentSize);
//increase total allocated space now. We can do this safely
//because at this point _AssessSegmentationPending flag will be true,
//preventing an immediate reassesment.
Interlocked.Add(ref _AllocatedSpace, newSegmentCount * segmentSize);
//lock all new segments
//we are going to release these locks while we migrate the items from the
//old (current) range to the new range.
for (int i = 0, end = newRange.Count; i != end; ++i)
newRange.GetSegmentByIndex(i).LockForWriting();
//set new (completely locked) range
Interlocked.Exchange(ref _NewRange, newRange);
//calculate the step sizes for our switch points
var currentSwitchPointStep = (UInt32)(1 << _CurrentRange.Shift);
var newSwitchPointStep = (UInt32)(1 << newRange.Shift);
//position in new range up from where the new segments are locked
var newLockedPoint = (UInt32)0;
//At this moment _SwitchPoint should be 0
var switchPoint = (UInt32)_SwitchPoint;
do
{
Segment<TStored, TSearch> currentSegment;
do
{
//aquire segment to migrate
currentSegment = _CurrentRange.GetSegment(switchPoint);
//lock segment
currentSegment.LockForWriting();
if (currentSegment.IsAlive)
break;
currentSegment.ReleaseForWriting();
}
while (true);
//migrate all items in the segment to the new range
TStored currentKey;
int it = -1;
while ((it = currentSegment.GetNextItem(it, out currentKey, this)) >= 0)
{
var currentKeyHash = this.GetItemHashCode(ref currentKey);
//get the new segment. this is already locked.
var newSegment = _NewRange.GetSegment(currentKeyHash);
TStored dummyKey;
newSegment.InsertItem(ref currentKey, out dummyKey, this);
}
//substract allocated space from allocated space count and trash segment.
currentSegment.Bye(this);
currentSegment.ReleaseForWriting();
if (switchPoint == 0 - currentSwitchPointStep)
{
//we are about to wrap _SwitchPoint arround.
//We have migrated all items from the entire table to the
//new range.
//replace current with new before advancing, otherwise
//we would create a completely blocked table.
Interlocked.Exchange(ref _CurrentRange, newRange);
}
//advance _SwitchPoint
switchPoint = (UInt32)Interlocked.Add(ref _SwitchPoint, (Int32)currentSwitchPointStep);
//release lock of new segments upto the point where we can still add new items
//during this migration.
while (true)
{
var nextNewLockedPoint = newLockedPoint + newSwitchPointStep;
if (nextNewLockedPoint > switchPoint || nextNewLockedPoint == 0)
break;
var newSegment = newRange.GetSegment(newLockedPoint);
newSegment.Trim(this);
var newSegmentSize = newSegment._Count;
totalNewSegmentSize += newSegmentSize;
if( newSegmentSize > largestSegmentSize )
{
largestSegmentSize = newSegmentSize;
largestSegment = newSegment;
}
newSegment.ReleaseForWriting();
newLockedPoint = nextNewLockedPoint;
}
}
while (switchPoint != 0);
//unlock any remaining new segments
while (newLockedPoint != 0)
{
var newSegment = newRange.GetSegment(newLockedPoint);
newSegment.Trim(this);
var newSegmentSize = newSegment._Count;
totalNewSegmentSize += newSegmentSize;
if( newSegmentSize > largestSegmentSize )
{
largestSegmentSize = newSegmentSize;
largestSegment = newSegment;
}
newSegment.ReleaseForWriting();
newLockedPoint += newSwitchPointStep;
}
}
}
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2021 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.
//
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Collections.Generic;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class RetryingTargetWrapperTests : NLogTestBase
{
[Fact]
public void RetryingTargetWrapperTest1()
{
var target = new MyTarget();
var wrapper = new RetryingTargetWrapper()
{
WrappedTarget = target,
RetryCount = 10,
RetryDelayMilliseconds = 1,
};
wrapper.Initialize(null);
target.Initialize(null);
var exceptions = new List<Exception>();
var events = new []
{
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
};
wrapper.WriteAsyncLogEvents(events);
// make sure all events went through
Assert.Equal(3, target.Events.Count);
Assert.Same(events[0].LogEvent, target.Events[0]);
Assert.Same(events[1].LogEvent, target.Events[1]);
Assert.Same(events[2].LogEvent, target.Events[2]);
Assert.Equal(events.Length, exceptions.Count);
// make sure there were no exception
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
}
[Fact]
public void RetryingTargetWrapperTest2()
{
var target = new MyTarget()
{
ThrowExceptions = 6,
};
var wrapper = new RetryingTargetWrapper()
{
WrappedTarget = target,
RetryCount = 4,
RetryDelayMilliseconds = 1,
};
wrapper.Initialize(null);
target.Initialize(null);
var exceptions = new List<Exception>();
var events = new []
{
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
};
var result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace);
Assert.True(result.IndexOf("Error while writing to 'MyTarget'. Try 1/4") != -1);
Assert.True(result.IndexOf("Error while writing to 'MyTarget'. Try 2/4") != -1);
Assert.True(result.IndexOf("Error while writing to 'MyTarget'. Try 3/4") != -1);
Assert.True(result.IndexOf("Error while writing to 'MyTarget'. Try 4/4") != -1);
Assert.True(result.IndexOf("Warn Too many retries. Aborting.") != -1);
Assert.True(result.IndexOf("Error while writing to 'MyTarget'. Try 1/4") != -1);
Assert.True(result.IndexOf("Error while writing to 'MyTarget'. Try 2/4") != -1);
// first event does not get to wrapped target because of too many attempts.
// second event gets there in 3rd retry
// and third event gets there immediately
Assert.Equal(2, target.Events.Count);
Assert.Same(events[1].LogEvent, target.Events[0]);
Assert.Same(events[2].LogEvent, target.Events[1]);
Assert.Equal(events.Length, exceptions.Count);
Assert.NotNull(exceptions[0]);
Assert.Equal("Some exception has occurred.", exceptions[0].Message);
Assert.Null(exceptions[1]);
Assert.Null(exceptions[2]);
}
#if MONO
[Fact(Skip="Not working under MONO - Premature abort seems to fail, and instead it just waits until finished")]
#else
[Fact]
#endif
public void RetryingTargetWrapperBlockingCloseTest()
{
RetryingIntegrationTest(3, () =>
{
var target = new MyTarget()
{
ThrowExceptions = 5,
};
var wrapper = new RetryingTargetWrapper()
{
WrappedTarget = target,
RetryCount = 10,
RetryDelayMilliseconds = 5000,
};
var asyncWrapper = new AsyncTargetWrapper(wrapper) {TimeToSleepBetweenBatches = 1};
asyncWrapper.Initialize(null);
wrapper.Initialize(null);
target.Initialize(null);
var exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
};
// Attempt to write LogEvents that will take forever to retry
asyncWrapper.WriteAsyncLogEvents(events);
// Wait a little for the AsyncWrapper to start writing
System.Threading.Thread.Sleep(50);
// Close down the AsyncWrapper while busy writing
asyncWrapper.Close();
// Close down the RetryingWrapper while busy retrying
wrapper.Close();
// Close down the actual target while busy writing
target.Close();
// Wait a little for the RetryingWrapper to detect that it has been closed down
System.Threading.Thread.Sleep(200);
// The premature abort, causes the exception to be logged
Assert.NotNull(exceptions[0]);
});
}
public class MyTarget : Target
{
public MyTarget()
{
Events = new List<LogEventInfo>();
}
public MyTarget(string name) : this()
{
Name = name;
}
public List<LogEventInfo> Events { get; set; }
public int ThrowExceptions { get; set; }
protected override void Write(AsyncLogEventInfo logEvent)
{
if (ThrowExceptions-- > 0)
{
logEvent.Continuation(new ApplicationException("Some exception has occurred."));
return;
}
Events.Add(logEvent.LogEvent);
logEvent.Continuation(null);
}
protected override void Write(LogEventInfo logEvent)
{
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// (C) Franklin Wise
// (C) 2003 Martin Willemoes Hansen
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using Xunit;
namespace System.Data.Tests
{
public class ForeignKeyConstraintTest
{
private DataSet _ds;
//NOTE: fk constraints only work when the table is part of a DataSet
public ForeignKeyConstraintTest()
{
_ds = new DataSet();
//Setup DataTable
DataTable table;
table = new DataTable("TestTable");
table.Columns.Add("Col1", typeof(int));
table.Columns.Add("Col2", typeof(int));
table.Columns.Add("Col3", typeof(int));
_ds.Tables.Add(table);
table = new DataTable("TestTable2");
table.Columns.Add("Col1", typeof(int));
table.Columns.Add("Col2", typeof(int));
table.Columns.Add("Col3", typeof(int));
_ds.Tables.Add(table);
}
// Tests ctor (string, DataColumn, DataColumn)
[Fact]
public void Ctor1()
{
DataTable Table = _ds.Tables[0];
Assert.Equal(0, Table.Constraints.Count);
Table = _ds.Tables[1];
Assert.Equal(0, Table.Constraints.Count);
// ctor (string, DataColumn, DataColumn
ForeignKeyConstraint Constraint = new ForeignKeyConstraint("test", _ds.Tables[0].Columns[2], _ds.Tables[1].Columns[0]);
Table = _ds.Tables[1];
Table.Constraints.Add(Constraint);
Assert.Equal(1, Table.Constraints.Count);
Assert.Equal("test", Table.Constraints[0].ConstraintName);
Assert.Equal(typeof(ForeignKeyConstraint), Table.Constraints[0].GetType());
Table = _ds.Tables[0];
Assert.Equal(1, Table.Constraints.Count);
Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName);
Assert.Equal(typeof(UniqueConstraint), Table.Constraints[0].GetType());
}
// Tests ctor (DataColumn, DataColumn)
[Fact]
public void Ctor2()
{
DataTable Table = _ds.Tables[0];
Assert.Equal(0, Table.Constraints.Count);
Table = _ds.Tables[1];
Assert.Equal(0, Table.Constraints.Count);
// ctor (string, DataColumn, DataColumn
ForeignKeyConstraint Constraint = new ForeignKeyConstraint(_ds.Tables[0].Columns[2], _ds.Tables[1].Columns[0]);
Table = _ds.Tables[1];
Table.Constraints.Add(Constraint);
Assert.Equal(1, Table.Constraints.Count);
Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName);
Assert.Equal(typeof(ForeignKeyConstraint), Table.Constraints[0].GetType());
Table = _ds.Tables[0];
Assert.Equal(1, Table.Constraints.Count);
Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName);
Assert.Equal(typeof(UniqueConstraint), Table.Constraints[0].GetType());
}
// Test ctor (DataColumn [], DataColumn [])
[Fact]
public void Ctor3()
{
DataTable Table = _ds.Tables[0];
Assert.Equal(0, Table.Constraints.Count);
Table = _ds.Tables[1];
Assert.Equal(0, Table.Constraints.Count);
DataColumn[] Cols1 = new DataColumn[2];
Cols1[0] = _ds.Tables[0].Columns[1];
Cols1[1] = _ds.Tables[0].Columns[2];
DataColumn[] Cols2 = new DataColumn[2];
Cols2[0] = _ds.Tables[1].Columns[0];
Cols2[1] = _ds.Tables[1].Columns[1];
ForeignKeyConstraint Constraint = new ForeignKeyConstraint(Cols1, Cols2);
Table = _ds.Tables[1];
Table.Constraints.Add(Constraint);
Assert.Equal(1, Table.Constraints.Count);
Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName);
Assert.Equal(typeof(ForeignKeyConstraint), Table.Constraints[0].GetType());
Table = _ds.Tables[0];
Assert.Equal(1, Table.Constraints.Count);
Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName);
Assert.Equal(typeof(UniqueConstraint), Table.Constraints[0].GetType());
}
// Tests ctor (string, DataColumn [], DataColumn [])
[Fact]
public void Ctor4()
{
DataTable Table = _ds.Tables[0];
Assert.Equal(0, Table.Constraints.Count);
Table = _ds.Tables[1];
Assert.Equal(0, Table.Constraints.Count);
DataColumn[] Cols1 = new DataColumn[2];
Cols1[0] = _ds.Tables[0].Columns[1];
Cols1[1] = _ds.Tables[0].Columns[2];
DataColumn[] Cols2 = new DataColumn[2];
Cols2[0] = _ds.Tables[1].Columns[0];
Cols2[1] = _ds.Tables[1].Columns[1];
ForeignKeyConstraint Constraint = new ForeignKeyConstraint("Test", Cols1, Cols2);
Table = _ds.Tables[1];
Table.Constraints.Add(Constraint);
Assert.Equal(1, Table.Constraints.Count);
Assert.Equal("Test", Table.Constraints[0].ConstraintName);
Assert.Equal(typeof(ForeignKeyConstraint), Table.Constraints[0].GetType());
Table = _ds.Tables[0];
Assert.Equal(1, Table.Constraints.Count);
Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName);
Assert.Equal(typeof(UniqueConstraint), Table.Constraints[0].GetType());
}
[Fact]
public void TestCtor5()
{
DataTable table1 = new DataTable("Table1");
DataTable table2 = new DataTable("Table2");
DataSet dataSet = new DataSet();
dataSet.Tables.Add(table1);
dataSet.Tables.Add(table2);
DataColumn column1 = new DataColumn("col1");
DataColumn column2 = new DataColumn("col2");
DataColumn column3 = new DataColumn("col3");
table1.Columns.Add(column1);
table1.Columns.Add(column2);
table1.Columns.Add(column3);
DataColumn column4 = new DataColumn("col4");
DataColumn column5 = new DataColumn("col5");
DataColumn column6 = new DataColumn("col6");
table2.Columns.Add(column4);
table2.Columns.Add(column5);
table2.Columns.Add(column6);
string[] parentColumnNames = { "col1", "col2", "col3" };
string[] childColumnNames = { "col4", "col5", "col6" };
string parentTableName = "table1";
// Create a ForeingKeyConstraint Object using the constructor
// ForeignKeyConstraint (string, string, string[], string[], AcceptRejectRule, Rule, Rule);
ForeignKeyConstraint fkc = new ForeignKeyConstraint("hello world", parentTableName, parentColumnNames, childColumnNames, AcceptRejectRule.Cascade, Rule.Cascade, Rule.Cascade); // Assert that the Constraint object does not belong to any table yet
try
{
DataTable tmp = fkc.Table;
Assert.False(true);
}
catch (NullReferenceException)
{ // actually .NET throws this (bug)
}
catch (InvalidOperationException)
{
}
Constraint[] constraints = new Constraint[3];
constraints[0] = new UniqueConstraint(column1);
constraints[1] = new UniqueConstraint(column2);
constraints[2] = fkc;
// Try to add the constraint to ConstraintCollection of the DataTable through Add()
try
{
table2.Constraints.Add(fkc);
throw new ApplicationException("An Exception was expected");
}
// LAMESPEC : spec says InvalidConstraintException but throws this
catch (NullReferenceException)
{
}
#if false // FIXME: Here this test crashes under MS.NET.
// OK - So AddRange() is the only way!
table2.Constraints.AddRange (constraints);
// After AddRange(), Check the properties of ForeignKeyConstraint object
Assert.True(fkc.RelatedColumns [0].ColumnName.Equals ("col1"));
Assert.True(fkc.RelatedColumns [1].ColumnName.Equals ("col2"));
Assert.True(fkc.RelatedColumns [2].ColumnName.Equals ("col3"));
Assert.True(fkc.Columns [0].ColumnName.Equals ("col4"));
Assert.True(fkc.Columns [1].ColumnName.Equals ("col5"));
Assert.True(fkc.Columns [2].ColumnName.Equals ("col6"));
#endif
// Try to add columns with names which do not exist in the table
parentColumnNames[2] = "noColumn";
ForeignKeyConstraint foreignKeyConstraint = new ForeignKeyConstraint("hello world", parentTableName, parentColumnNames, childColumnNames, AcceptRejectRule.Cascade, Rule.Cascade, Rule.Cascade);
constraints[0] = new UniqueConstraint(column1);
constraints[1] = new UniqueConstraint(column2);
constraints[2] = foreignKeyConstraint;
try
{
table2.Constraints.AddRange(constraints);
throw new ApplicationException("An Exception was expected");
}
catch (ArgumentException e)
{
}
catch (InvalidConstraintException e)
{ // Could not test on ms.net, as ms.net does not reach here so far.
}
#if false // FIXME: Here this test crashes under MS.NET.
// Check whether the child table really contains the foreign key constraint named "hello world"
Assert.True(table2.Constraints.Contains ("hello world"));
#endif
}
// If Childs and parents are in same table
[Fact]
public void KeyBetweenColumns()
{
DataTable Table = _ds.Tables[0];
Assert.Equal(0, Table.Constraints.Count);
Table = _ds.Tables[1];
Assert.Equal(0, Table.Constraints.Count);
ForeignKeyConstraint Constraint = new ForeignKeyConstraint("Test", _ds.Tables[0].Columns[0], _ds.Tables[0].Columns[2]);
Table = _ds.Tables[0];
Table.Constraints.Add(Constraint);
Assert.Equal(2, Table.Constraints.Count);
Assert.Equal("Constraint1", Table.Constraints[0].ConstraintName);
Assert.Equal(typeof(UniqueConstraint), Table.Constraints[0].GetType());
Assert.Equal("Test", Table.Constraints[1].ConstraintName);
Assert.Equal(typeof(ForeignKeyConstraint), Table.Constraints[1].GetType());
}
[Fact]
public void CtorExceptions()
{
ForeignKeyConstraint fkc;
DataTable localTable = new DataTable();
localTable.Columns.Add("Col1", typeof(int));
localTable.Columns.Add("Col2", typeof(bool));
//Null
Assert.Throws<NullReferenceException>(() =>
{
fkc = new ForeignKeyConstraint(null, (DataColumn)null);
});
//zero length collection
Assert.Throws<ArgumentException>(() =>
{
fkc = new ForeignKeyConstraint(new DataColumn[] { }, new DataColumn[] { });
});
//different datasets
Assert.Throws<InvalidOperationException>(() =>
{
fkc = new ForeignKeyConstraint(_ds.Tables[0].Columns[0], localTable.Columns[0]);
});
Assert.Throws<InvalidOperationException>(() =>
{
fkc = new ForeignKeyConstraint(_ds.Tables[0].Columns[0], localTable.Columns[1]);
});
// Cannot create a Key from Columns that belong to
// different tables.
Assert.Throws<InvalidConstraintException>(() =>
{
fkc = new ForeignKeyConstraint(new DataColumn[] { _ds.Tables[0].Columns[0], _ds.Tables[0].Columns[1] }, new DataColumn[] { localTable.Columns[1], _ds.Tables[1].Columns[0] });
});
}
[Fact]
public void CtorExceptions2()
{
DataColumn col = new DataColumn("MyCol1", typeof(int));
ForeignKeyConstraint fkc;
//Columns must belong to a Table
Assert.Throws<ArgumentException>(() =>
{
fkc = new ForeignKeyConstraint(col, _ds.Tables[0].Columns[0]);
});
//Columns must belong to the same table
//InvalidConstraintException
DataColumn[] difTable = new DataColumn[] {_ds.Tables[0].Columns[2],
_ds.Tables[1].Columns[0]};
Assert.Throws<InvalidConstraintException>(() =>
{
fkc = new ForeignKeyConstraint(difTable, new DataColumn[] {
_ds.Tables[0].Columns[1],
_ds.Tables[0].Columns[0]});
});
//parent columns and child columns should be the same length
//ArgumentException
DataColumn[] twoCol =
new DataColumn[] { _ds.Tables[0].Columns[0], _ds.Tables[0].Columns[1] };
Assert.Throws<ArgumentException>(() =>
{
fkc = new ForeignKeyConstraint(twoCol,
new DataColumn[] { _ds.Tables[0].Columns[0] });
});
//InvalidOperation: Parent and child are the same column.
Assert.Throws<InvalidOperationException>(() =>
{
fkc = new ForeignKeyConstraint(_ds.Tables[0].Columns[0],
_ds.Tables[0].Columns[0]);
});
}
[Fact]
public void EqualsAndHashCode()
{
DataTable tbl = _ds.Tables[0];
DataTable tbl2 = _ds.Tables[1];
ForeignKeyConstraint fkc = new ForeignKeyConstraint(
new DataColumn[] { tbl.Columns[0], tbl.Columns[1] },
new DataColumn[] { tbl2.Columns[0], tbl2.Columns[1] });
ForeignKeyConstraint fkc2 = new ForeignKeyConstraint(
new DataColumn[] { tbl.Columns[0], tbl.Columns[1] },
new DataColumn[] { tbl2.Columns[0], tbl2.Columns[1] });
ForeignKeyConstraint fkcDiff =
new ForeignKeyConstraint(tbl.Columns[1], tbl.Columns[2]);
Assert.True(fkc.Equals(fkc2));
Assert.True(fkc2.Equals(fkc));
Assert.True(fkc.Equals(fkc));
Assert.True(fkc.Equals(fkcDiff) == false);
//Assert.True( "Hash Code Assert.True.Failed. 1");
Assert.True(fkc.GetHashCode() != fkcDiff.GetHashCode());
}
[Fact]
public void ViolationTest()
{
Assert.Throws<ArgumentException>(() =>
{
DataTable parent = _ds.Tables[0];
DataTable child = _ds.Tables[1];
parent.Rows.Add(new object[] { 1, 1, 1 });
child.Rows.Add(new object[] { 2, 2, 2 });
try
{
child.Constraints.Add(new ForeignKeyConstraint(parent.Columns[0],
child.Columns[0])
);
}
finally
{
// clear the rows for further testing
_ds.Clear();
}
});
}
[Fact]
public void NoViolationTest()
{
DataTable parent = _ds.Tables[0];
DataTable child = _ds.Tables[1];
parent.Rows.Add(new object[] { 1, 1, 1 });
child.Rows.Add(new object[] { 2, 2, 2 });
try
{
_ds.EnforceConstraints = false;
child.Constraints.Add(new ForeignKeyConstraint(parent.Columns[0],
child.Columns[0])
);
}
finally
{
// clear the rows for further testing
_ds.Clear();
_ds.EnforceConstraints = true;
}
}
[Fact]
public void ModifyParentKeyBeforeAcceptChanges()
{
DataSet ds1 = new DataSet();
DataTable t1 = ds1.Tables.Add("t1");
DataTable t2 = ds1.Tables.Add("t2");
t1.Columns.Add("col1", typeof(int));
t2.Columns.Add("col2", typeof(int));
ds1.Relations.Add("fk", t1.Columns[0], t2.Columns[0]);
t1.Rows.Add(new object[] { 10 });
t2.Rows.Add(new object[] { 10 });
t1.Rows[0][0] = 20;
Assert.True((int)t2.Rows[0][0] == 20);
}
[Fact]
// https://bugzilla.novell.com/show_bug.cgi?id=650402
public void ForeignKey_650402()
{
DataSet data = new DataSet();
DataTable parent = new DataTable("parent");
DataColumn pk = parent.Columns.Add("PK");
DataTable child = new DataTable("child");
DataColumn fk = child.Columns.Add("FK");
data.Tables.Add(parent);
data.Tables.Add(child);
data.Relations.Add(pk, fk);
parent.Rows.Add("value");
child.Rows.Add("value");
data.AcceptChanges();
child.Rows[0].Delete();
parent.Rows[0][0] = "value2";
data.EnforceConstraints = false;
data.EnforceConstraints = true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Features;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Mail;
using Umbraco.Cms.Core.Media;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Trees;
using Umbraco.Cms.Core.WebAssets;
using Umbraco.Cms.Web.BackOffice.HealthChecks;
using Umbraco.Cms.Web.BackOffice.Profiling;
using Umbraco.Cms.Web.BackOffice.PropertyEditors;
using Umbraco.Cms.Web.BackOffice.Routing;
using Umbraco.Cms.Web.BackOffice.Security;
using Umbraco.Cms.Web.BackOffice.Trees;
using Umbraco.Cms.Web.Common.Attributes;
using Umbraco.Extensions;
using Constants = Umbraco.Cms.Core.Constants;
namespace Umbraco.Cms.Web.BackOffice.Controllers
{
/// <summary>
/// Used to collect the server variables for use in the back office angular app
/// </summary>
public class BackOfficeServerVariables
{
private readonly LinkGenerator _linkGenerator;
private readonly IRuntimeState _runtimeState;
private readonly UmbracoFeatures _features;
private readonly GlobalSettings _globalSettings;
private readonly IUmbracoVersion _umbracoVersion;
private readonly ContentSettings _contentSettings;
private readonly TreeCollection _treeCollection;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly RuntimeSettings _runtimeSettings;
private readonly SecuritySettings _securitySettings;
private readonly IRuntimeMinifier _runtimeMinifier;
private readonly IBackOfficeExternalLoginProviders _externalLogins;
private readonly IImageUrlGenerator _imageUrlGenerator;
private readonly PreviewRoutes _previewRoutes;
private readonly IEmailSender _emailSender;
private readonly MemberPasswordConfigurationSettings _memberPasswordConfigurationSettings;
public BackOfficeServerVariables(
LinkGenerator linkGenerator,
IRuntimeState runtimeState,
UmbracoFeatures features,
IOptions<GlobalSettings> globalSettings,
IUmbracoVersion umbracoVersion,
IOptions<ContentSettings> contentSettings,
IHttpContextAccessor httpContextAccessor,
TreeCollection treeCollection,
IHostingEnvironment hostingEnvironment,
IOptions<RuntimeSettings> runtimeSettings,
IOptions<SecuritySettings> securitySettings,
IRuntimeMinifier runtimeMinifier,
IBackOfficeExternalLoginProviders externalLogins,
IImageUrlGenerator imageUrlGenerator,
PreviewRoutes previewRoutes,
IEmailSender emailSender,
IOptions<MemberPasswordConfigurationSettings> memberPasswordConfigurationSettings)
{
_linkGenerator = linkGenerator;
_runtimeState = runtimeState;
_features = features;
_globalSettings = globalSettings.Value;
_umbracoVersion = umbracoVersion;
_contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings));
_httpContextAccessor = httpContextAccessor;
_treeCollection = treeCollection ?? throw new ArgumentNullException(nameof(treeCollection));
_hostingEnvironment = hostingEnvironment;
_runtimeSettings = runtimeSettings.Value;
_securitySettings = securitySettings.Value;
_runtimeMinifier = runtimeMinifier;
_externalLogins = externalLogins;
_imageUrlGenerator = imageUrlGenerator;
_previewRoutes = previewRoutes;
_emailSender = emailSender;
_memberPasswordConfigurationSettings = memberPasswordConfigurationSettings.Value;
}
/// <summary>
/// Returns the server variables for non-authenticated users
/// </summary>
/// <returns></returns>
internal async Task<Dictionary<string, object>> BareMinimumServerVariablesAsync()
{
//this is the filter for the keys that we'll keep based on the full version of the server vars
var keepOnlyKeys = new Dictionary<string, string[]>
{
{"umbracoUrls", new[] {"authenticationApiBaseUrl", "serverVarsJs", "externalLoginsUrl", "currentUserApiBaseUrl", "previewHubUrl", "iconApiBaseUrl"}},
{"umbracoSettings", new[] {"allowPasswordReset", "imageFileTypes", "maxFileSize", "loginBackgroundImage", "loginLogoImage", "canSendRequiredEmail", "usernameIsEmail", "minimumPasswordLength", "minimumPasswordNonAlphaNum"}},
{"application", new[] {"applicationPath", "cacheBuster"}},
{"isDebuggingEnabled", new string[] { }},
{"features", new [] {"disabledFeatures"}}
};
//now do the filtering...
var defaults = await GetServerVariablesAsync();
foreach (var key in defaults.Keys.ToArray())
{
if (keepOnlyKeys.ContainsKey(key) == false)
{
defaults.Remove(key);
}
else
{
if (defaults[key] is System.Collections.IDictionary asDictionary)
{
var toKeep = keepOnlyKeys[key];
foreach (var k in asDictionary.Keys.Cast<string>().ToArray())
{
if (toKeep.Contains(k) == false)
{
asDictionary.Remove(k);
}
}
}
}
}
// TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
// so based on compat and how things are currently working we need to replace the serverVarsJs one
((Dictionary<string, object>)defaults["umbracoUrls"])["serverVarsJs"]
= _linkGenerator.GetPathByAction(
nameof(BackOfficeController.ServerVariables),
ControllerExtensions.GetControllerName<BackOfficeController>(),
new { area = Constants.Web.Mvc.BackOfficeArea });
return defaults;
}
/// <summary>
/// Returns the server variables for authenticated users
/// </summary>
/// <returns></returns>
internal async Task<Dictionary<string, object>> GetServerVariablesAsync()
{
var globalSettings = _globalSettings;
var backOfficeControllerName = ControllerExtensions.GetControllerName<BackOfficeController>();
var defaultVals = new Dictionary<string, object>
{
{
"umbracoUrls", new Dictionary<string, object>
{
// TODO: Add 'umbracoApiControllerBaseUrl' which people can use in JS
// to prepend their URL. We could then also use this in our own resources instead of
// having each URL defined here explicitly - we can do that in v8! for now
// for umbraco services we'll stick to explicitly defining the endpoints.
{"externalLoginsUrl", _linkGenerator.GetPathByAction(nameof(BackOfficeController.ExternalLogin), backOfficeControllerName, new { area = Constants.Web.Mvc.BackOfficeArea })},
{"externalLinkLoginsUrl", _linkGenerator.GetPathByAction(nameof(BackOfficeController.LinkLogin), backOfficeControllerName, new { area = Constants.Web.Mvc.BackOfficeArea })},
{"gridConfig", _linkGenerator.GetPathByAction(nameof(BackOfficeController.GetGridConfig), backOfficeControllerName, new { area = Constants.Web.Mvc.BackOfficeArea })},
// TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
{"serverVarsJs", _linkGenerator.GetPathByAction(nameof(BackOfficeController.Application), backOfficeControllerName, new { area = Constants.Web.Mvc.BackOfficeArea })},
//API URLs
{
"packagesRestApiBaseUrl", Constants.PackageRepository.RestApiBaseUrl
},
{
"redirectUrlManagementApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<RedirectUrlManagementController>(
controller => controller.GetEnableState())
},
{
"tourApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<TourController>(
controller => controller.GetTours())
},
{
"embedApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<RteEmbedController>(
controller => controller.GetEmbed("", 0, 0))
},
{
"userApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<UsersController>(
controller => controller.PostSaveUser(null))
},
{
"userGroupsApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<UserGroupsController>(
controller => controller.PostSaveUserGroup(null))
},
{
"contentApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<ContentController>(
controller => controller.PostSave(null))
},
{
"publicAccessApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<PublicAccessController>(
controller => controller.GetPublicAccess(0))
},
{
"mediaApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<MediaController>(
controller => controller.GetRootMedia())
},
{
"iconApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<IconController>(
controller => controller.GetIcon(""))
},
{
"imagesApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<ImagesController>(
controller => controller.GetBigThumbnail(""))
},
{
"sectionApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<SectionController>(
controller => controller.GetSections())
},
{
"treeApplicationApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<ApplicationTreeController>(
controller => controller.GetApplicationTrees(null, null, null, TreeUse.None))
},
{
"contentTypeApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<ContentTypeController>(
controller => controller.GetAllowedChildren(0))
},
{
"mediaTypeApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<MediaTypeController>(
controller => controller.GetAllowedChildren(0))
},
{
"macroRenderingApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<MacroRenderingController>(
controller => controller.GetMacroParameters(0))
},
{
"macroApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<MacrosController>(
controller => controller.Create(null))
},
{
"authenticationApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<AuthenticationController>(
controller => controller.PostLogin(null))
},
{
"currentUserApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<CurrentUserController>(
controller => controller.PostChangePassword(null))
},
{
"entityApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<EntityController>(
controller => controller.GetById(0, UmbracoEntityTypes.Media))
},
{
"dataTypeApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<DataTypeController>(
controller => controller.GetById(0))
},
{
"dashboardApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<DashboardController>(
controller => controller.GetDashboard(null))
},
{
"logApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<LogController>(
controller => controller.GetPagedEntityLog(0, 0, 0, Direction.Ascending, null))
},
{
"memberApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<MemberController>(
controller => controller.GetByKey(Guid.Empty))
},
{
"packageApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<PackageController>(
controller => controller.GetCreatedPackages())
},
{
"relationApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<RelationController>(
controller => controller.GetById(0))
},
{
"rteApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<RichTextPreValueController>(
controller => controller.GetConfiguration())
},
{
"stylesheetApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<StylesheetController>(
controller => controller.GetAll())
},
{
"memberTypeApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<MemberTypeController>(
controller => controller.GetAllTypes())
},
{
"memberTypeQueryApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<MemberTypeQueryController>(
controller => controller.GetAllTypes())
},
{
"memberGroupApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<MemberGroupController>(
controller => controller.GetAllGroups())
},
{
"updateCheckApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<UpdateCheckController>(
controller => controller.GetCheck())
},
{
"templateApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<TemplateController>(
controller => controller.GetById(0))
},
{
"memberTreeBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<MemberTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"mediaTreeBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<MediaTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"contentTreeBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<ContentTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"tagsDataBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<TagsDataController>(
controller => controller.GetTags("", "", null))
},
{
"examineMgmtBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<ExamineManagementController>(
controller => controller.GetIndexerDetails())
},
{
"healthCheckBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<HealthCheckController>(
controller => controller.GetAllHealthChecks())
},
{
"templateQueryApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<TemplateQueryController>(
controller => controller.PostTemplateQuery(null))
},
{
"codeFileApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<CodeFileController>(
controller => controller.GetByPath("", ""))
},
{
"publishedStatusBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<PublishedStatusController>(
controller => controller.GetPublishedStatusUrl())
},
{
"dictionaryApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<DictionaryController>(
controller => controller.DeleteById(int.MaxValue))
},
{
"publishedSnapshotCacheStatusBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<PublishedSnapshotCacheStatusController>(
controller => controller.GetStatus())
},
{
"helpApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<HelpController>(
controller => controller.GetContextHelpForPage("","",""))
},
{
"backOfficeAssetsApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<BackOfficeAssetsController>(
controller => controller.GetSupportedLocales())
},
{
"languageApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<LanguageController>(
controller => controller.GetAllLanguages())
},
{
"relationTypeApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<RelationTypeController>(
controller => controller.GetById(1))
},
{
"logViewerApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<LogViewerController>(
controller => controller.GetNumberOfErrors(null, null))
},
{
"webProfilingBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<WebProfilingController>(
controller => controller.GetStatus())
},
{
"tinyMceApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<TinyMceController>(
controller => controller.UploadImage(null))
},
{
"imageUrlGeneratorApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<ImageUrlGeneratorController>(
controller => controller.GetCropUrl(null, null, null, null))
},
{
"elementTypeApiBaseUrl", _linkGenerator.GetUmbracoApiServiceBaseUrl<ElementTypeController>(
controller => controller.GetAll())
},
{
"previewHubUrl", _previewRoutes.GetPreviewHubRoute()
},
}
},
{
"umbracoSettings", new Dictionary<string, object>
{
{"umbracoPath", _globalSettings.GetBackOfficePath(_hostingEnvironment)},
{"mediaPath", _hostingEnvironment.ToAbsolute(globalSettings.UmbracoMediaPath).TrimEnd(Constants.CharArrays.ForwardSlash)},
{"appPluginsPath", _hostingEnvironment.ToAbsolute(Constants.SystemDirectories.AppPlugins).TrimEnd(Constants.CharArrays.ForwardSlash)},
{
"imageFileTypes",
string.Join(",", _imageUrlGenerator.SupportedImageFileTypes)
},
{
"disallowedUploadFiles",
string.Join(",", _contentSettings.DisallowedUploadFiles)
},
{
"allowedUploadFiles",
string.Join(",", _contentSettings.AllowedUploadFiles)
},
{
"maxFileSize",
GetMaxRequestLength()
},
{"keepUserLoggedIn", _securitySettings.KeepUserLoggedIn},
{"usernameIsEmail", _securitySettings.UsernameIsEmail},
{"cssPath", _hostingEnvironment.ToAbsolute(globalSettings.UmbracoCssPath).TrimEnd(Constants.CharArrays.ForwardSlash)},
{"allowPasswordReset", _securitySettings.AllowPasswordReset},
{"loginBackgroundImage", _contentSettings.LoginBackgroundImage},
{"loginLogoImage", _contentSettings.LoginLogoImage },
{"showUserInvite", _emailSender.CanSendRequiredEmail()},
{"canSendRequiredEmail", _emailSender.CanSendRequiredEmail()},
{"showAllowSegmentationForDocumentTypes", false},
{"minimumPasswordLength", _memberPasswordConfigurationSettings.RequiredLength},
{"minimumPasswordNonAlphaNum", _memberPasswordConfigurationSettings.GetMinNonAlphaNumericChars()},
{"sanitizeTinyMce", _globalSettings.SanitizeTinyMce}
}
},
{
"umbracoPlugins", new Dictionary<string, object>
{
// for each tree that is [PluginController], get
// alias -> areaName
// so that routing (route.js) can look for views
{ "trees", GetPluginTrees().ToArray() }
}
},
{
"isDebuggingEnabled", _hostingEnvironment.IsDebugMode
},
{
"application", GetApplicationState()
},
{
"externalLogins", new Dictionary<string, object>
{
{
// TODO: It would be nicer to not have to manually translate these properties
// but then needs to be changed in quite a few places in angular
"providers", (await _externalLogins.GetBackOfficeProvidersAsync())
.Select(p => new
{
authType = p.ExternalLoginProvider.AuthenticationType,
caption = p.AuthenticationScheme.DisplayName,
properties = p.ExternalLoginProvider.Options
})
.ToArray()
}
}
},
{
"features", new Dictionary<string,object>
{
{
"disabledFeatures", new Dictionary<string,object>
{
{ "disableTemplates", _features.Disabled.DisableTemplates}
}
}
}
}
};
return defaultVals;
}
[DataContract]
private class PluginTree
{
[DataMember(Name = "alias")]
public string Alias { get; set; }
[DataMember(Name = "packageFolder")]
public string PackageFolder { get; set; }
}
private IEnumerable<PluginTree> GetPluginTrees()
{
// used to be (cached)
//var treeTypes = Current.TypeLoader.GetAttributedTreeControllers();
//
// ie inheriting from TreeController and marked with TreeAttribute
//
// do this instead
// inheriting from TreeControllerBase and marked with TreeAttribute
foreach (var tree in _treeCollection)
{
var treeType = tree.TreeControllerType;
// exclude anything marked with CoreTreeAttribute
var coreTree = treeType.GetCustomAttribute<CoreTreeAttribute>(false);
if (coreTree != null) continue;
// exclude anything not marked with PluginControllerAttribute
var pluginController = treeType.GetCustomAttribute<PluginControllerAttribute>(false);
if (pluginController == null) continue;
yield return new PluginTree { Alias = tree.TreeAlias, PackageFolder = pluginController.AreaName };
}
}
/// <summary>
/// Returns the server variables regarding the application state
/// </summary>
/// <returns></returns>
private Dictionary<string, object> GetApplicationState()
{
var version = _runtimeState.SemanticVersion.ToSemanticStringWithoutBuild();
var app = new Dictionary<string, object>
{
// add versions - see UmbracoVersion for details & differences
// the complete application version (eg "8.1.2-alpha.25")
{ "version", version },
// the assembly version (eg "8.0.0")
{ "assemblyVersion", _umbracoVersion.AssemblyVersion.ToString() }
};
//the value is the hash of the version, cdf version and the configured state
app.Add("cacheBuster", $"{version}.{_runtimeState.Level}.{_runtimeMinifier.CacheBuster}".GenerateHash());
//useful for dealing with virtual paths on the client side when hosted in virtual directories especially
app.Add("applicationPath", _httpContextAccessor.GetRequiredHttpContext().Request.PathBase.ToString().EnsureEndsWith('/'));
//add the server's GMT time offset in minutes
app.Add("serverTimeOffset", Convert.ToInt32(DateTimeOffset.Now.Offset.TotalMinutes));
return app;
}
private string GetMaxRequestLength()
{
return _runtimeSettings.MaxRequestLength.HasValue ? _runtimeSettings.MaxRequestLength.Value.ToString() : string.Empty;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnPermisosActuale class.
/// </summary>
[Serializable]
public partial class PnPermisosActualeCollection : ActiveList<PnPermisosActuale, PnPermisosActualeCollection>
{
public PnPermisosActualeCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnPermisosActualeCollection</returns>
public PnPermisosActualeCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnPermisosActuale o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_permisos_actuales table.
/// </summary>
[Serializable]
public partial class PnPermisosActuale : ActiveRecord<PnPermisosActuale>, IActiveRecord
{
#region .ctors and Default Settings
public PnPermisosActuale()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnPermisosActuale(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnPermisosActuale(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnPermisosActuale(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_permisos_actuales", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdPermisosActuales = new TableSchema.TableColumn(schema);
colvarIdPermisosActuales.ColumnName = "id_permisos_actuales";
colvarIdPermisosActuales.DataType = DbType.Int32;
colvarIdPermisosActuales.MaxLength = 0;
colvarIdPermisosActuales.AutoIncrement = true;
colvarIdPermisosActuales.IsNullable = false;
colvarIdPermisosActuales.IsPrimaryKey = true;
colvarIdPermisosActuales.IsForeignKey = false;
colvarIdPermisosActuales.IsReadOnly = false;
colvarIdPermisosActuales.DefaultSetting = @"";
colvarIdPermisosActuales.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPermisosActuales);
TableSchema.TableColumn colvarIdUsuario = new TableSchema.TableColumn(schema);
colvarIdUsuario.ColumnName = "id_usuario";
colvarIdUsuario.DataType = DbType.Int32;
colvarIdUsuario.MaxLength = 0;
colvarIdUsuario.AutoIncrement = false;
colvarIdUsuario.IsNullable = false;
colvarIdUsuario.IsPrimaryKey = false;
colvarIdUsuario.IsForeignKey = true;
colvarIdUsuario.IsReadOnly = false;
colvarIdUsuario.DefaultSetting = @"";
colvarIdUsuario.ForeignKeyTableName = "PN_usuarios";
schema.Columns.Add(colvarIdUsuario);
TableSchema.TableColumn colvarData = new TableSchema.TableColumn(schema);
colvarData.ColumnName = "data";
colvarData.DataType = DbType.AnsiString;
colvarData.MaxLength = -1;
colvarData.AutoIncrement = false;
colvarData.IsNullable = true;
colvarData.IsPrimaryKey = false;
colvarData.IsForeignKey = false;
colvarData.IsReadOnly = false;
colvarData.DefaultSetting = @"";
colvarData.ForeignKeyTableName = "";
schema.Columns.Add(colvarData);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_permisos_actuales",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdPermisosActuales")]
[Bindable(true)]
public int IdPermisosActuales
{
get { return GetColumnValue<int>(Columns.IdPermisosActuales); }
set { SetColumnValue(Columns.IdPermisosActuales, value); }
}
[XmlAttribute("IdUsuario")]
[Bindable(true)]
public int IdUsuario
{
get { return GetColumnValue<int>(Columns.IdUsuario); }
set { SetColumnValue(Columns.IdUsuario, value); }
}
[XmlAttribute("Data")]
[Bindable(true)]
public string Data
{
get { return GetColumnValue<string>(Columns.Data); }
set { SetColumnValue(Columns.Data, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a PnUsuario ActiveRecord object related to this PnPermisosActuale
///
/// </summary>
public DalSic.PnUsuario PnUsuario
{
get { return DalSic.PnUsuario.FetchByID(this.IdUsuario); }
set { SetColumnValue("id_usuario", value.IdUsuario); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdUsuario,string varData)
{
PnPermisosActuale item = new PnPermisosActuale();
item.IdUsuario = varIdUsuario;
item.Data = varData;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdPermisosActuales,int varIdUsuario,string varData)
{
PnPermisosActuale item = new PnPermisosActuale();
item.IdPermisosActuales = varIdPermisosActuales;
item.IdUsuario = varIdUsuario;
item.Data = varData;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdPermisosActualesColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdUsuarioColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn DataColumn
{
get { return Schema.Columns[2]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdPermisosActuales = @"id_permisos_actuales";
public static string IdUsuario = @"id_usuario";
public static string Data = @"data";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal delegate BoundStatement GenerateMethodBody(EEMethodSymbol method, DiagnosticBag diagnostics);
/// <summary>
/// Synthesized expression evaluation method.
/// </summary>
internal sealed class EEMethodSymbol : MethodSymbol
{
// We only create a single EE method (per EE type) that represents an arbitrary expression,
// whose lowering may produce synthesized members (lambdas, dynamic sites, etc).
// We may thus assume that the method ordinal is always 0.
//
// Consider making the implementation more flexible in order to avoid this assumption.
// In future we might need to compile multiple expression and then we'll need to assign
// a unique method ordinal to each of them to avoid duplicate synthesized member names.
private const int _methodOrdinal = 0;
internal readonly TypeMap TypeMap;
internal readonly MethodSymbol SubstitutedSourceMethod;
internal readonly ImmutableArray<LocalSymbol> Locals;
internal readonly ImmutableArray<LocalSymbol> LocalsForBinding;
private readonly EENamedTypeSymbol _container;
private readonly string _name;
private readonly ImmutableArray<Location> _locations;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly ImmutableArray<ParameterSymbol> _parameters;
private readonly ParameterSymbol _thisParameter;
private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables;
/// <summary>
/// Invoked at most once to generate the method body.
/// (If the compilation has no errors, it will be invoked
/// exactly once, otherwise it may be skipped.)
/// </summary>
private readonly GenerateMethodBody _generateMethodBody;
private TypeSymbol _lazyReturnType;
// NOTE: This is only used for asserts, so it could be conditional on DEBUG.
private readonly ImmutableArray<TypeParameterSymbol> _allTypeParameters;
internal EEMethodSymbol(
EENamedTypeSymbol container,
string name,
Location location,
MethodSymbol sourceMethod,
ImmutableArray<LocalSymbol> sourceLocals,
ImmutableArray<LocalSymbol> sourceLocalsForBinding,
ImmutableDictionary<string, DisplayClassVariable> sourceDisplayClassVariables,
GenerateMethodBody generateMethodBody)
{
Debug.Assert(sourceMethod.IsDefinition);
Debug.Assert(sourceMethod.ContainingSymbol == container.SubstitutedSourceType.OriginalDefinition);
Debug.Assert(sourceLocals.All(l => l.ContainingSymbol == sourceMethod));
_container = container;
_name = name;
_locations = ImmutableArray.Create(location);
// What we want is to map all original type parameters to the corresponding new type parameters
// (since the old ones have the wrong owners). Unfortunately, we have a circular dependency:
// 1) Each new type parameter requires the entire map in order to be able to construct its constraint list.
// 2) The map cannot be constructed until all new type parameters exist.
// Our solution is to pass each new type parameter a lazy reference to the type map. We then
// initialize the map as soon as the new type parameters are available - and before they are
// handed out - so that there is never a period where they can require the type map and find
// it uninitialized.
var sourceMethodTypeParameters = sourceMethod.TypeParameters;
var allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters);
var getTypeMap = new Func<TypeMap>(() => this.TypeMap);
_typeParameters = sourceMethodTypeParameters.SelectAsArray(
(tp, i, arg) => (TypeParameterSymbol)new EETypeParameterSymbol(this, tp, i, getTypeMap),
(object)null);
_allTypeParameters = container.TypeParameters.Concat(_typeParameters);
this.TypeMap = new TypeMap(allSourceTypeParameters, _allTypeParameters);
EENamedTypeSymbol.VerifyTypeParameters(this, _typeParameters);
var substitutedSourceType = container.SubstitutedSourceType;
this.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType);
if (sourceMethod.Arity > 0)
{
this.SubstitutedSourceMethod = this.SubstitutedSourceMethod.Construct(_typeParameters.As<TypeSymbol>());
}
TypeParameterChecker.Check(this.SubstitutedSourceMethod, _allTypeParameters);
// Create a map from original parameter to target parameter.
var parameterBuilder = ArrayBuilder<ParameterSymbol>.GetInstance();
var substitutedSourceThisParameter = this.SubstitutedSourceMethod.ThisParameter;
var substitutedSourceHasThisParameter = (object)substitutedSourceThisParameter != null;
if (substitutedSourceHasThisParameter)
{
_thisParameter = MakeParameterSymbol(0, GeneratedNames.ThisProxyFieldName(), substitutedSourceThisParameter);
Debug.Assert(_thisParameter.Type == this.SubstitutedSourceMethod.ContainingType);
parameterBuilder.Add(_thisParameter);
}
var ordinalOffset = (substitutedSourceHasThisParameter ? 1 : 0);
foreach (var substitutedSourceParameter in this.SubstitutedSourceMethod.Parameters)
{
var ordinal = substitutedSourceParameter.Ordinal + ordinalOffset;
Debug.Assert(ordinal == parameterBuilder.Count);
var parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter);
parameterBuilder.Add(parameter);
}
_parameters = parameterBuilder.ToImmutableAndFree();
var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
var localsMap = PooledDictionary<LocalSymbol, LocalSymbol>.GetInstance();
foreach (var sourceLocal in sourceLocals)
{
var local = sourceLocal.ToOtherMethod(this, this.TypeMap);
localsMap.Add(sourceLocal, local);
localsBuilder.Add(local);
}
this.Locals = localsBuilder.ToImmutableAndFree();
localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var sourceLocal in sourceLocalsForBinding)
{
LocalSymbol local;
if (!localsMap.TryGetValue(sourceLocal, out local))
{
local = sourceLocal.ToOtherMethod(this, this.TypeMap);
localsMap.Add(sourceLocal, local);
}
localsBuilder.Add(local);
}
this.LocalsForBinding = localsBuilder.ToImmutableAndFree();
// Create a map from variable name to display class field.
var displayClassVariables = PooledDictionary<string, DisplayClassVariable>.GetInstance();
foreach (var pair in sourceDisplayClassVariables)
{
var variable = pair.Value;
var oldDisplayClassInstance = variable.DisplayClassInstance;
// Note: we don't call ToOtherMethod in the local case because doing so would produce
// a new LocalSymbol that would not be ReferenceEquals to the one in this.LocalsForBinding.
var oldDisplayClassInstanceFromLocal = oldDisplayClassInstance as DisplayClassInstanceFromLocal;
var newDisplayClassInstance = (oldDisplayClassInstanceFromLocal == null) ?
oldDisplayClassInstance.ToOtherMethod(this, this.TypeMap) :
new DisplayClassInstanceFromLocal((EELocalSymbol)localsMap[oldDisplayClassInstanceFromLocal.Local]);
variable = variable.SubstituteFields(newDisplayClassInstance, this.TypeMap);
displayClassVariables.Add(pair.Key, variable);
}
_displayClassVariables = displayClassVariables.ToImmutableDictionary();
displayClassVariables.Free();
localsMap.Free();
_generateMethodBody = generateMethodBody;
}
private ParameterSymbol MakeParameterSymbol(int ordinal, string name, ParameterSymbol sourceParameter)
{
return new SynthesizedParameterSymbol(this, sourceParameter.Type, ordinal, sourceParameter.RefKind, name, sourceParameter.CustomModifiers, sourceParameter.CountOfCustomModifiersPrecedingByRef);
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataFinal
{
get { return false; }
}
public override MethodKind MethodKind
{
get { return MethodKind.Ordinary; }
}
public override string Name
{
get { return _name; }
}
public override int Arity
{
get { return _typeParameters.Length; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
internal override bool HasSpecialName
{
get { return true; }
}
internal override System.Reflection.MethodImplAttributes ImplementationAttributes
{
get { return default(System.Reflection.MethodImplAttributes); }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
public override DllImportData GetDllImportData()
{
return null;
}
internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { return null; }
}
internal override bool RequiresSecurityObject
{
get { return false; }
}
internal override bool TryGetThisParameter(out ParameterSymbol thisParameter)
{
thisParameter = null;
return true;
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override bool IsVararg
{
get { return this.SubstitutedSourceMethod.IsVararg; }
}
internal override RefKind RefKind
{
get { return this.SubstitutedSourceMethod.RefKind; }
}
public override bool ReturnsVoid
{
get { return this.ReturnType.SpecialType == SpecialType.System_Void; }
}
public override bool IsAsync
{
get { return false; }
}
public override TypeSymbol ReturnType
{
get
{
if (_lazyReturnType == null)
{
throw new InvalidOperationException();
}
return _lazyReturnType;
}
}
public override ImmutableArray<TypeSymbol> TypeArguments
{
get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return _parameters; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<MethodSymbol>.Empty; }
}
public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
public override Symbol AssociatedSymbol
{
get { return null; }
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override Cci.CallingConvention CallingConvention
{
get
{
Debug.Assert(this.IsStatic);
var cc = Cci.CallingConvention.Default;
if (this.IsVararg)
{
cc |= Cci.CallingConvention.ExtraArguments;
}
if (this.IsGenericMethod)
{
cc |= Cci.CallingConvention.Generic;
}
return cc;
}
}
internal override bool GenerateDebugInfo
{
get { return false; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override ImmutableArray<Location> Locations
{
get { return _locations; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { throw ExceptionUtilities.Unreachable; }
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Internal; }
}
public override bool IsStatic
{
get { return true; }
}
public override bool IsVirtual
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override void GenerateMethodBody(TypeCompilationState compilationState, DiagnosticBag diagnostics)
{
var body = _generateMethodBody(this, diagnostics);
var compilation = compilationState.Compilation;
_lazyReturnType = CalculateReturnType(compilation, body);
// Can't do this until the return type has been computed.
TypeParameterChecker.Check(this, _allTypeParameters);
if (diagnostics.HasAnyErrors())
{
return;
}
DiagnosticsPass.IssueDiagnostics(compilation, body, diagnostics, this);
if (diagnostics.HasAnyErrors())
{
return;
}
// Check for use-site diagnostics (e.g. missing types in the signature).
DiagnosticInfo useSiteDiagnosticInfo = null;
this.CalculateUseSiteDiagnostic(ref useSiteDiagnosticInfo);
if (useSiteDiagnosticInfo != null && useSiteDiagnosticInfo.Severity == DiagnosticSeverity.Error)
{
diagnostics.Add(useSiteDiagnosticInfo, this.Locations[0]);
return;
}
try
{
var declaredLocals = PooledHashSet<LocalSymbol>.GetInstance();
try
{
// Rewrite local declaration statement.
body = (BoundStatement)LocalDeclarationRewriter.Rewrite(compilation, _container, declaredLocals, body);
// Verify local declaration names.
foreach (var local in declaredLocals)
{
Debug.Assert(local.Locations.Length > 0);
var name = local.Name;
if (name.StartsWith("$", StringComparison.Ordinal))
{
diagnostics.Add(ErrorCode.ERR_UnexpectedCharacter, local.Locations[0], name[0]);
return;
}
}
// Rewrite references to placeholder "locals".
body = (BoundStatement)PlaceholderLocalRewriter.Rewrite(compilation, _container, declaredLocals, body, diagnostics);
if (diagnostics.HasAnyErrors())
{
return;
}
}
finally
{
declaredLocals.Free();
}
var syntax = body.Syntax;
var statementsBuilder = ArrayBuilder<BoundStatement>.GetInstance();
statementsBuilder.Add(body);
// Insert an implicit return statement if necessary.
if (body.Kind != BoundKind.ReturnStatement)
{
statementsBuilder.Add(new BoundReturnStatement(syntax, RefKind.None, expressionOpt: null));
}
var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
var localsSet = PooledHashSet<LocalSymbol>.GetInstance();
foreach (var local in this.LocalsForBinding)
{
Debug.Assert(!localsSet.Contains(local));
localsBuilder.Add(local);
localsSet.Add(local);
}
foreach (var local in this.Locals)
{
if (!localsSet.Contains(local))
{
Debug.Assert(!localsSet.Contains(local));
localsBuilder.Add(local);
localsSet.Add(local);
}
}
localsSet.Free();
body = new BoundBlock(syntax, localsBuilder.ToImmutableAndFree(), ImmutableArray<LocalFunctionSymbol>.Empty, statementsBuilder.ToImmutableAndFree()) { WasCompilerGenerated = true };
Debug.Assert(!diagnostics.HasAnyErrors());
Debug.Assert(!body.HasErrors);
bool sawLambdas;
bool sawLocalFunctions;
bool sawAwaitInExceptionHandler;
ImmutableArray<SourceSpan> dynamicAnalysisSpans = ImmutableArray<SourceSpan>.Empty;
body = LocalRewriter.Rewrite(
compilation: this.DeclaringCompilation,
method: this,
methodOrdinal: _methodOrdinal,
containingType: _container,
statement: body,
compilationState: compilationState,
previousSubmissionFields: null,
allowOmissionOfConditionalCalls: false,
instrumentForDynamicAnalysis: false,
debugDocumentProvider: null,
dynamicAnalysisSpans: ref dynamicAnalysisSpans,
diagnostics: diagnostics,
sawLambdas: out sawLambdas,
sawLocalFunctions: out sawLocalFunctions,
sawAwaitInExceptionHandler: out sawAwaitInExceptionHandler);
Debug.Assert(!sawAwaitInExceptionHandler);
Debug.Assert(dynamicAnalysisSpans.Length == 0);
if (body.HasErrors)
{
return;
}
// Variables may have been captured by lambdas in the original method
// or in the expression, and we need to preserve the existing values of
// those variables in the expression. This requires rewriting the variables
// in the expression based on the closure classes from both the original
// method and the expression, and generating a preamble that copies
// values into the expression closure classes.
//
// Consider the original method:
// static void M()
// {
// int x, y, z;
// ...
// F(() => x + y);
// }
// and the expression in the EE: "F(() => x + z)".
//
// The expression is first rewritten using the closure class and local <1>
// from the original method: F(() => <1>.x + z)
// Then lambda rewriting introduces a new closure class that includes
// the locals <1> and z, and a corresponding local <2>: F(() => <2>.<1>.x + <2>.z)
// And a preamble is added to initialize the fields of <2>:
// <2> = new <>c__DisplayClass0();
// <2>.<1> = <1>;
// <2>.z = z;
// Rewrite "this" and "base" references to parameter in this method.
// Rewrite variables within body to reference existing display classes.
body = (BoundStatement)CapturedVariableRewriter.Rewrite(
this.SubstitutedSourceMethod.IsStatic ? null : _parameters[0],
compilation.Conversions,
_displayClassVariables,
body,
diagnostics);
if (body.HasErrors)
{
Debug.Assert(false, "Please add a test case capturing whatever caused this assert.");
return;
}
if (diagnostics.HasAnyErrors())
{
return;
}
if (sawLambdas || sawLocalFunctions)
{
var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance();
var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance();
body = LambdaRewriter.Rewrite(
loweredBody: body,
thisType: this.SubstitutedSourceMethod.ContainingType,
thisParameter: _thisParameter,
method: this,
methodOrdinal: _methodOrdinal,
substitutedSourceMethod: this.SubstitutedSourceMethod.OriginalDefinition,
closureDebugInfoBuilder: closureDebugInfoBuilder,
lambdaDebugInfoBuilder: lambdaDebugInfoBuilder,
slotAllocatorOpt: null,
compilationState: compilationState,
diagnostics: diagnostics,
assignLocals: true);
// we don't need this information:
closureDebugInfoBuilder.Free();
lambdaDebugInfoBuilder.Free();
}
// Insert locals from the original method,
// followed by any new locals.
var block = (BoundBlock)body;
var localBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var local in this.Locals)
{
Debug.Assert(!(local is EELocalSymbol) || (((EELocalSymbol)local).Ordinal == localBuilder.Count));
localBuilder.Add(local);
}
foreach (var local in block.Locals)
{
var oldLocal = local as EELocalSymbol;
if (oldLocal != null)
{
Debug.Assert(localBuilder[oldLocal.Ordinal] == oldLocal);
continue;
}
localBuilder.Add(local);
}
body = block.Update(localBuilder.ToImmutableAndFree(), block.LocalFunctions, block.Statements);
TypeParameterChecker.Check(body, _allTypeParameters);
compilationState.AddSynthesizedMethod(this, body);
}
catch (BoundTreeVisitor.CancelledByStackGuardException ex)
{
ex.AddAnError(diagnostics);
}
}
private static TypeSymbol CalculateReturnType(CSharpCompilation compilation, BoundStatement bodyOpt)
{
if (bodyOpt == null)
{
// If the method doesn't do anything, then it doesn't return anything.
return compilation.GetSpecialType(SpecialType.System_Void);
}
switch (bodyOpt.Kind)
{
case BoundKind.ReturnStatement:
return ((BoundReturnStatement)bodyOpt).ExpressionOpt.Type;
case BoundKind.ExpressionStatement:
case BoundKind.LocalDeclaration:
case BoundKind.MultipleLocalDeclarations:
return compilation.GetSpecialType(SpecialType.System_Void);
default:
throw ExceptionUtilities.UnexpectedValue(bodyOpt.Kind);
}
}
internal override void AddSynthesizedReturnTypeAttributes(ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedReturnTypeAttributes(ref attributes);
if (this.ReturnType.ContainsDynamic())
{
var compilation = this.DeclaringCompilation;
if ((object)compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctor) != null)
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(this.ReturnType, this.ReturnTypeCustomModifiers.Length));
}
}
}
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree)
{
return localPosition;
}
}
}
| |
using System;
using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
/// <summary>
/// Provides helper overloads to a <see cref="Configuration"/>.
/// </summary>
public static class ConfigurationExtensions
{
/// <summary>
/// Get a configuration value for the given key parts.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>(new []{ "core", "bare" }).Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="keyParts">The key parts</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public static ConfigurationEntry<T> Get<T>(this Configuration config, string[] keyParts)
{
Ensure.ArgumentNotNull(keyParts, "keyParts");
return config.Get<T>(string.Join(".", keyParts));
}
/// <summary>
/// Get a configuration value for the given key parts.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [difftool "kdiff3"]
/// path = c:/Program Files/KDiff3/kdiff3.exe
/// </code>
///
/// You would call:
///
/// <code>
/// string where = repo.Config.Get<string>("difftool", "kdiff3", "path").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="firstKeyPart">The first key part</param>
/// <param name="secondKeyPart">The second key part</param>
/// <param name="thirdKeyPart">The third key part</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public static ConfigurationEntry<T> Get<T>(this Configuration config, string firstKeyPart, string secondKeyPart, string thirdKeyPart)
{
Ensure.ArgumentNotNullOrEmptyString(firstKeyPart, "firstKeyPart");
Ensure.ArgumentNotNullOrEmptyString(secondKeyPart, "secondKeyPart");
Ensure.ArgumentNotNullOrEmptyString(thirdKeyPart, "thirdKeyPart");
return config.Get<T>(new[] { firstKeyPart, secondKeyPart, thirdKeyPart });
}
/// <summary>
/// Get a configuration value for the given key.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="key">The key</param>
/// <returns>The configuration value, or the default value for the selected <see typeparamref="T"/>if not found</returns>
public static T GetValueOrDefault<T>(this Configuration config, string key)
{
return ValueOrDefault(config.Get<T>(key), default(T));
}
/// <summary>
/// Get a configuration value for the given key,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="key">The key</param>
/// <param name="defaultValue">The default value if the key is not set.</param>
/// <returns>The configuration value, or the default value</returns>
public static T GetValueOrDefault<T>(this Configuration config, string key, T defaultValue)
{
return ValueOrDefault(config.Get<T>(key), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="key">The key.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <returns>The configuration value, or the default value for <see typeparamref="T"/> if not found</returns>
public static T GetValueOrDefault<T>(this Configuration config, string key, ConfigurationLevel level)
{
return ValueOrDefault(config.Get<T>(key, level), default(T));
}
/// <summary>
/// Get a configuration value for the given key,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="key">The key.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <param name="defaultValue">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or the default value.</returns>
public static T GetValueOrDefault<T>(this Configuration config, string key, ConfigurationLevel level, T defaultValue)
{
return ValueOrDefault(config.Get<T>(key, level), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key parts
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="keyParts">The key parts.</param>
/// <returns>The configuration value, or the default value for<see typeparamref="T"/> if not found</returns>
public static T GetValueOrDefault<T>(this Configuration config, string[] keyParts)
{
return ValueOrDefault(config.Get<T>(keyParts), default(T));
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="keyParts">The key parts.</param>
/// <param name="defaultValue">The default value if the key is not set.</param>
/// <returns>The configuration value, or the default value.</returns>
public static T GetValueOrDefault<T>(this Configuration config, string[] keyParts, T defaultValue)
{
return ValueOrDefault(config.Get<T>(keyParts), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key parts.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="firstKeyPart">The first key part.</param>
/// <param name="secondKeyPart">The second key part.</param>
/// <param name="thirdKeyPart">The third key part.</param>
/// <returns>The configuration value, or the default value for the selected <see typeparamref="T"/> if not found</returns>
public static T GetValueOrDefault<T>(this Configuration config, string firstKeyPart, string secondKeyPart, string thirdKeyPart)
{
return ValueOrDefault(config.Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), default(T));
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="firstKeyPart">The first key part.</param>
/// <param name="secondKeyPart">The second key part.</param>
/// <param name="thirdKeyPart">The third key part.</param>
/// <param name="defaultValue">The default value if the key is not set.</param>
/// <returns>The configuration value, or the default.</returns>
public static T GetValueOrDefault<T>(this Configuration config, string firstKeyPart, string secondKeyPart, string thirdKeyPart, T defaultValue)
{
return ValueOrDefault(config.Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="key">The key</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public static T GetValueOrDefault<T>(this Configuration config, string key, Func<T> defaultValueSelector)
{
return ValueOrDefault(config.Get<T>(key), defaultValueSelector);
}
/// <summary>
/// Get a configuration value for the given key,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="key">The key.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public static T GetValueOrDefault<T>(this Configuration config, string key, ConfigurationLevel level, Func<T> defaultValueSelector)
{
return ValueOrDefault(config.Get<T>(key, level), defaultValueSelector);
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="keyParts">The key parts.</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public static T GetValueOrDefault<T>(this Configuration config, string[] keyParts, Func<T> defaultValueSelector)
{
return ValueOrDefault(config.Get<T>(keyParts), defaultValueSelector);
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="config">The configuration being worked with.</param>
/// <param name="firstKeyPart">The first key part.</param>
/// <param name="secondKeyPart">The second key part.</param>
/// <param name="thirdKeyPart">The third key part.</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public static T GetValueOrDefault<T>(this Configuration config, string firstKeyPart, string secondKeyPart, string thirdKeyPart, Func<T> defaultValueSelector)
{
return ValueOrDefault(config.Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), defaultValueSelector);
}
private static T ValueOrDefault<T>(ConfigurationEntry<T> value, T defaultValue)
{
return value == null ? defaultValue : value.Value;
}
private static T ValueOrDefault<T>(ConfigurationEntry<T> value, Func<T> defaultValueSelector)
{
Ensure.ArgumentNotNull(defaultValueSelector, "defaultValueSelector");
return value == null
? defaultValueSelector()
: value.Value;
}
}
}
| |
/*
* REST API Documentation for Schoolbus
*
* API Sample
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SchoolBusAPI.Models;
using Microsoft.EntityFrameworkCore;
using SchoolBusAPI.Mappings;
using SchoolBusAPI.ViewModels;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
using System.Net.Http;
using System.Text;
using Microsoft.AspNetCore.WebUtilities;
namespace SchoolBusAPI.Services.Impl
{
/// <summary>
///
/// </summary>
public class SchoolBusService : ServiceBase, ISchoolBusService
{
private readonly DbAppContext _context;
private readonly IConfiguration Configuration;
/// <summary>
/// Create a service and set the database context
/// </summary>
public SchoolBusService(IHttpContextAccessor httpContextAccessor, IConfiguration configuration, DbAppContext context) : base(httpContextAccessor, context)
{
_context = context;
Configuration = configuration;
}
/// <summary>
/// Adjust a SchoolBus item to ensure child object data is in place correctly
/// </summary>
/// <param name="item"></param>
private void AdjustSchoolBus(SchoolBus item)
{
if (item != null)
{
if (item.SchoolBusOwner != null)
{
int school_bus_owner_id = item.SchoolBusOwner.Id;
bool school_bus_owner_exists = _context.SchoolBusOwners.Any(a => a.Id == school_bus_owner_id);
if (school_bus_owner_exists)
{
SchoolBusOwner school_bus_owner = _context.SchoolBusOwners.First(a => a.Id == school_bus_owner_id);
item.SchoolBusOwner = school_bus_owner;
}
else // invalid data
{
item.SchoolBusOwner = null;
}
}
// adjust District.
if (item.District != null)
{
int district_id = item.District.Id;
var district_exists = _context.Districts.Any(a => a.Id == district_id);
if (district_exists)
{
District district = _context.Districts.First(a => a.Id == district_id);
item.District = district;
}
else
{
item.District = null;
}
} // adjust school district
if (item.SchoolDistrict != null)
{
int schoolDistrict_id = item.SchoolDistrict.Id;
bool schoolDistrict_exists = _context.SchoolDistricts.Any(a => a.Id == schoolDistrict_id);
if (schoolDistrict_exists)
{
SchoolDistrict school_district = _context.SchoolDistricts.First(a => a.Id == schoolDistrict_id);
item.SchoolDistrict = school_district;
}
else
// invalid data
{
item.SchoolDistrict = null;
}
}
// adjust home city
if (item.HomeTerminalCity != null)
{
int city_id = item.HomeTerminalCity.Id;
bool city_exists = _context.Cities.Any(a => a.Id == city_id);
if (city_exists)
{
City city = _context.Cities.First(a => a.Id == city_id);
item.HomeTerminalCity = city;
}
else
// invalid data
{
item.HomeTerminalCity = null;
}
}
// adjust inspector
if (item.Inspector != null)
{
int inspector_id = item.Inspector.Id;
bool inspector_exists = _context.Users.Any(a => a.Id == inspector_id);
if (inspector_exists)
{
User inspector = _context.Users.First(a => a.Id == inspector_id);
item.Inspector = inspector;
}
else
// invalid data
{
item.Inspector = null;
}
}
// adjust CCWData
if (item.CCWData != null)
{
int ccwdata_id = item.CCWData.Id;
bool ccwdata_exists = _context.CCWDatas.Any(a => a.Id == ccwdata_id);
if (ccwdata_exists)
{
CCWData ccwdata = _context.CCWDatas.First(a => a.Id == ccwdata_id);
item.CCWData = ccwdata;
}
else
// invalid data
{
item.CCWData = null;
}
}
}
}
/// <summary>
/// Creates several school buses
/// </summary>
/// <remarks>Used for bulk creation of schoolbus records.</remarks>
/// <param name="body"></param>
/// <response code="201">SchoolBus items created</response>
public virtual IActionResult SchoolbusesBulkPostAsync (SchoolBus[] items)
{
if (items == null)
{
return new BadRequestResult();
}
foreach (SchoolBus item in items)
{
// adjust school bus owner
AdjustSchoolBus(item);
var exists = _context.SchoolBuss.Any(a => a.Id == item.Id);
if (exists)
{
_context.SchoolBuss.Update(item);
}
else
{
_context.SchoolBuss.Add(item);
}
}
// Save the changes
_context.SaveChanges();
return new NoContentResult();
}
/// <summary>
/// Returns a single school bus object
/// </summary>
/// <remarks></remarks>
/// <param name="id">Id of SchoolBus to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">Not Found</response>
public virtual IActionResult SchoolbusesIdGetAsync (int id)
{
bool exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
var result = _context.SchoolBuss
.Include(x => x.HomeTerminalCity)
.Include(x => x.SchoolDistrict)
.Include(x => x.SchoolBusOwner.PrimaryContact)
.Include(x => x.District.Region)
.Include(x => x.Inspector)
.Include(x => x.CCWData)
.First(a => a.Id == id);
return new ObjectResult(result);
}
else
{
return new StatusCodeResult(404);
}
}
/// <summary>
/// Returns a collection of school buses
/// </summary>
/// <remarks></remarks>
/// <response code="200">OK</response>
public virtual IActionResult SchoolbusesGetAsync ()
{
var result = _context.SchoolBuss
.Include(x => x.HomeTerminalCity)
.Include(x => x.SchoolDistrict)
.Include(x => x.SchoolBusOwner.PrimaryContact)
.Include(x => x.District.Region)
.Include(x => x.Inspector)
.Include(x => x.CCWData)
.ToList();
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns attachments for a particular SchoolBus</remarks>
/// <param name="id">id of SchoolBus to fetch attachments for</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
public virtual IActionResult SchoolbusesIdAttachmentsGetAsync (int id)
{
bool exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
SchoolBus schoolBus = _context.SchoolBuss
.Include(x => x.Attachments)
.First(a => a.Id == id);
var result = MappingExtensions.GetAttachmentListAsViewModel(schoolBus.Attachments);
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Returns CCWData for a particular Schoolbus</remarks>
/// <param name="id">id of SchoolBus to fetch CCWData for</param>
/// <response code="200">OK</response>
public virtual IActionResult SchoolbusesIdCcwdataGetAsync (int id)
{
// validate the bus id
bool exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
SchoolBus schoolbus = _context.SchoolBuss.Where(a => a.Id == id).First();
string regi = schoolbus.ICBCRegistrationNumber;
// get CCW data for this bus.
// could be none.
// validate the bus id
bool ccw_exists = _context.CCWDatas.Any(a => a.ICBCRegistrationNumber == regi);
if (ccw_exists)
{
var result = _context.CCWDatas.Where(a => a.ICBCRegistrationNumber == regi).First();
return new ObjectResult(result);
}
else
{
// record not found
CCWData[] nodata = new CCWData[0];
return new ObjectResult (nodata);
}
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SchoolBus to delete</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
public virtual IActionResult SchoolbusesIdDeletePostAsync (int id)
{
bool exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
var item = _context.SchoolBuss.First(a => a.Id == id);
if (item != null)
{
_context.SchoolBuss.Remove(item);
// Save the changes
_context.SaveChanges();
}
return new ObjectResult(item);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Returns History for a particular SchoolBus</remarks>
/// <param name="id">id of SchoolBus to fetch SchoolBusHistory for</param>
/// <response code="200">OK</response>
public virtual IActionResult SchoolbusesIdHistoryGetAsync (int id, int? offset, int? limit)
{
bool exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
SchoolBus schoolBus = _context.SchoolBuss
.Include(x => x.History)
.First(a => a.Id == id);
List<History> data = schoolBus.History.OrderByDescending(y => y.LastUpdateTimestamp).ToList();
if (offset == null)
{
offset = 0;
}
if (limit == null)
{
limit = data.Count() - offset;
}
List<HistoryViewModel> result = new List<HistoryViewModel>();
for (int i = (int)offset; i < data.Count() && i < offset + limit; i++)
{
result.Add(data[i].ToViewModel(id));
}
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Add a History record to the SchoolBus</remarks>
/// <param name="id">id of SchoolBus to fetch History for</param>
/// <param name="item"></param>
/// <response code="201">History created</response>
public virtual IActionResult SchoolbusesIdHistoryPostAsync(int id, History item)
{
HistoryViewModel result = new HistoryViewModel();
bool exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
SchoolBus schoolBus = _context.SchoolBuss
.Include(x => x.History)
.First(a => a.Id == id);
if (schoolBus.History == null)
{
schoolBus.History = new List<History>();
}
// force add
item.Id = 0;
schoolBus.History.Add(item);
_context.SchoolBuss.Update(schoolBus);
_context.SaveChanges();
}
result.HistoryText = item.HistoryText;
result.Id = item.Id;
result.LastUpdateTimestamp = item.LastUpdateTimestamp;
result.LastUpdateUserid = item.LastUpdateUserid;
result.AffectedEntityId = id;
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns notes for a particular SchoolBus.</remarks>
/// <param name="id">id of SchoolBus to fetch notes for</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
public virtual IActionResult SchoolbusesIdNotesGetAsync (int id)
{
bool exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
SchoolBus schoolBus = _context.SchoolBuss
.Include(x => x.Notes)
.First(a => a.Id == id);
var result = schoolBus.Notes;
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
/// Returns a PDF Permit
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public virtual IActionResult SchoolbusesIdPdfpermitGetAsync (int id)
{
FileContentResult result = null;
bool exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
SchoolBus schoolBus = _context.SchoolBuss
.Include(x => x.CCWData)
.Include(x => x.SchoolBusOwner.PrimaryContact)
.Include(x => x.SchoolDistrict)
.First(a => a.Id == id);
// construct the view model.
PermitViewModel permitViewModel = new PermitViewModel();
// only do the ICBC fields if the CCW data is available.
if (schoolBus.CCWData != null)
{
permitViewModel.IcbcMake = schoolBus.CCWData.ICBCMake;
permitViewModel.IcbcModelYear = schoolBus.CCWData.ICBCModelYear;
permitViewModel.IcbcRegistrationNumber = schoolBus.CCWData.ICBCRegistrationNumber;
permitViewModel.VehicleIdentificationNumber = schoolBus.CCWData.ICBCVehicleIdentificationNumber;
permitViewModel.SchoolBusOwnerAddressLine1 = schoolBus.CCWData.ICBCRegOwnerAddr1;
// line 2 is a combination of the various fields that may contain data.
List<string> strings = new List<string>();
if (! string.IsNullOrWhiteSpace (schoolBus.CCWData.ICBCRegOwnerAddr2))
{
strings.Add(schoolBus.CCWData.ICBCRegOwnerAddr2);
}
if (!string.IsNullOrWhiteSpace(schoolBus.CCWData.ICBCRegOwnerCity))
{
strings.Add(schoolBus.CCWData.ICBCRegOwnerCity);
}
if (!string.IsNullOrWhiteSpace(schoolBus.CCWData.ICBCRegOwnerProv))
{
strings.Add(schoolBus.CCWData.ICBCRegOwnerProv);
}
if (!string.IsNullOrWhiteSpace(schoolBus.CCWData.ICBCRegOwnerPostalCode))
{
strings.Add(schoolBus.CCWData.ICBCRegOwnerPostalCode);
}
if (strings.Count > 0)
{
permitViewModel.SchoolBusOwnerAddressLine2 = String.Join(", ", strings);
}
permitViewModel.SchoolBusOwnerPostalCode = schoolBus.CCWData.ICBCRegOwnerPostalCode;
permitViewModel.SchoolBusOwnerProvince = schoolBus.CCWData.ICBCRegOwnerProv;
permitViewModel.SchoolBusOwnerCity = schoolBus.CCWData.ICBCRegOwnerCity;
permitViewModel.SchoolBusOwnerName = schoolBus.CCWData.ICBCRegOwnerName;
}
permitViewModel.PermitIssueDate = null;
if (schoolBus.PermitIssueDate != null)
{
// Since the PDF template is raw HTML and won't convert a date object, we must adjust the time zone here.
TimeZoneInfo tzi = null;
try
{
// try the IANA timzeone first.
tzi = TimeZoneInfo.FindSystemTimeZoneById("America / Vancouver");
}
catch (Exception e)
{
tzi = null;
}
if (tzi == null)
{
try
{
tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
}
catch (Exception e)
{
tzi = null;
}
}
DateTime dto = DateTime.UtcNow;
if (tzi != null)
{
dto = TimeZoneInfo.ConvertTime((DateTime)schoolBus.PermitIssueDate, tzi);
}
else
{
dto = (DateTime) schoolBus.PermitIssueDate;
}
permitViewModel.PermitIssueDate = dto.ToString("yyyy-MM-dd");
}
permitViewModel.PermitNumber = schoolBus.PermitNumber;
permitViewModel.RestrictionsText = schoolBus.RestrictionsText;
permitViewModel.SchoolBusMobilityAidCapacity = schoolBus.MobilityAidCapacity.ToString();
permitViewModel.UnitNumber = schoolBus.UnitNumber;
permitViewModel.PermitClassCode = schoolBus.PermitClassCode;
permitViewModel.BodyTypeCode = schoolBus.BodyTypeCode;
permitViewModel.SchoolBusSeatingCapacity = schoolBus.SchoolBusSeatingCapacity;
if (schoolBus.SchoolDistrict != null)
{
permitViewModel.SchoolDistrictshortName = schoolBus.SchoolDistrict.ShortName;
}
string payload = JsonConvert.SerializeObject(permitViewModel);
// pass the request on to the PDF Micro Service
string pdfHost = Configuration["PDF_SERVICE_NAME"];
string targetUrl = pdfHost + "/api/PDF/GetPDF";
// call the microservice
try
{
HttpClient client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, targetUrl);
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
request.Headers.Clear();
// transfer over the request headers.
foreach (var item in Request.Headers)
{
string key = item.Key;
string value = item.Value;
request.Headers.Add(key, value);
}
Task<HttpResponseMessage> responseTask = client.SendAsync(request);
responseTask.Wait();
HttpResponseMessage response = responseTask.Result;
if (response.StatusCode == HttpStatusCode.OK) // success
{
var bytetask = response.Content.ReadAsByteArrayAsync();
bytetask.Wait();
result = new FileContentResult(bytetask.Result, "application/pdf");
result.FileDownloadName = "Permit-" + schoolBus.PermitNumber + ".pdf";
}
}
catch (Exception e)
{
result = null;
}
// check that the result has a value
if (result != null)
{
return result;
}
else
{
return new StatusCodeResult(400); // problem occured
}
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
/// Updates a single school bus object
/// </summary>
/// <remarks></remarks>
/// <param name="id">Id of SchoolBus to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">Not Found</response>
public virtual IActionResult SchoolbusesIdPutAsync (int id, SchoolBus item)
{
// adjust school bus owner
AdjustSchoolBus(item);
bool exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists && id == item.Id)
{
_context.SchoolBuss.Update(item);
// Save the changes
_context.SaveChanges();
return new ObjectResult(item);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <response code="201">SchoolBus created</response>
public virtual IActionResult SchoolbusesPostAsync(SchoolBus item)
{
// adjust school bus owner
AdjustSchoolBus(item);
bool exists = _context.SchoolBuss.Any(a => a.Id == item.Id);
if (exists)
{
_context.SchoolBuss.Update(item);
// Save the changes
}
else
{
// record not found
_context.SchoolBuss.Add(item);
}
_context.SaveChanges();
return new ObjectResult(item);
}
/// <param name="id">id of SchoolBus to fetch Inspections for</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
public virtual IActionResult SchoolbusesIdInspectionsGetAsync(int id)
{
bool exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
var items = _context.Inspections
.Include(x => x.Inspector)
.Include(x => x.SchoolBus)
.Where(a => a.SchoolBus.Id == id);
return new ObjectResult(items);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Obtains a new permit number for the indicated Schoolbus. Returns the updated SchoolBus record.</remarks>
/// <param name="id">id of SchoolBus to obtain a new permit number for</param>
/// <response code="200">OK</response>
public virtual IActionResult SchoolbusesIdNewpermitPutAsync(int id)
{
bool exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
// get the current max permit number.
int permit = 36000;
var maxPermitRecord = _context.SchoolBuss
.OrderByDescending(x => x.PermitNumber)
.FirstOrDefault(x => x.PermitNumber != null);
if (maxPermitRecord != null)
{
permit = (int)maxPermitRecord.PermitNumber + 1;
}
var item = _context.SchoolBuss
.Include(x => x.HomeTerminalCity)
.Include(x => x.SchoolDistrict)
.Include(x => x.SchoolBusOwner.PrimaryContact)
.Include(x => x.District.Region)
.Include(x => x.Inspector)
.Include(x => x.CCWData)
.First(a => a.Id == id);
item.PermitNumber = permit;
item.PermitIssueDate = DateTime.UtcNow;
_context.SchoolBuss.Update(item);
_context.SaveChanges();
return new ObjectResult(item);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
/// Searches school buses
/// </summary>
/// <remarks>Used for the search schoolbus page.</remarks>
/// <param name="districts">Districts (array of id numbers)</param>
/// <param name="inspectors">Assigned School Bus Inspectors (array of id numbers)</param>
/// <param name="cities">Cities (array of id numbers)</param>
/// <param name="schooldistricts">School Districts (array of id numbers)</param>
/// <param name="owner"></param>
/// <param name="regi">e Regi Number</param>
/// <param name="vin">VIN</param>
/// <param name="plate">License Plate String</param>
/// <param name="includeInactive">True if Inactive schoolbuses will be returned</param>
/// <param name="onlyReInspections">If true, only buses that need a re-inspection will be returned</param>
/// <param name="startDate">Inspection start date</param>
/// <param name="endDate">Inspection end date</param>
/// <response code="200">OK</response>
public IActionResult SchoolbusesSearchGetAsync(int?[] districts, int?[] inspectors, int?[] cities, int?[] schooldistricts, int? owner, string regi, string vin, string plate, bool? includeInactive, bool? onlyReInspections, DateTime? startDate, DateTime? endDate)
{
// Eager loading of related data
var data = _context.SchoolBuss
.Include(x => x.HomeTerminalCity)
.Include(x => x.SchoolBusOwner)
.Include(x => x.District)
.Include(x => x.Inspector)
.Select(x => x);
bool keySearch = false;
// do key search fields first.
if (regi != null)
{
// first convert the regi to a number.
int tempRegi;
bool parsed = int.TryParse(regi, out tempRegi);
if (parsed)
{
regi = tempRegi.ToString();
}
data = data.Where(x => x.ICBCRegistrationNumber.Contains(regi));
keySearch = true;
}
if (vin != null)
{
data = data.Where(x => x.VehicleIdentificationNumber == vin);
keySearch = true;
}
if (plate != null)
{
data = data.Where(x => x.LicencePlateNumber == plate);
keySearch = true;
}
// only search other fields if a key search was not done.
if (!keySearch)
{
if (districts != null)
{
foreach (int? district in districts)
{
if (district != null)
{
data = data.Where(x => x.District.Id == district);
}
}
}
if (inspectors != null)
{
foreach (int? inspector in inspectors)
{
if (inspector != null)
{
data = data.Where(x => x.Inspector.Id == inspector);
}
}
}
if (cities != null)
{
foreach (int? city in cities)
{
if (city != null)
{
data = data.Where(x => x.HomeTerminalCity.Id == city);
}
}
}
if (schooldistricts != null)
{
foreach (int? schooldistrict in schooldistricts)
{
if (schooldistrict != null)
{
data = data.Where(x => x.SchoolDistrict.Id == schooldistrict);
}
}
}
if (owner != null)
{
data = data.Where(x => x.SchoolBusOwner.Id == owner);
}
if (includeInactive == null || (includeInactive != null && includeInactive == false))
{
data = data.Where(x => x.Status.ToLower() == "active");
}
if (onlyReInspections != null && onlyReInspections == true)
{
data = data.Where(x => x.NextInspectionTypeCode.ToLower() == "re-inspection");
}
if (startDate != null)
{
data = data.Where(x => x.NextInspectionDate >= startDate);
}
if (endDate != null)
{
data = data.Where(x => x.NextInspectionDate <= endDate);
}
}
var result = data.ToList();
return new ObjectResult(result);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace Epi.Windows.Enter.Controls
{
/// <summary>
/// Represents a Windows date time picker control. It enhances the .NET standard <b>DateTimePicker</b>
/// control with the possibility to show empty values (null values).
/// </summary>
[ComVisible(false)]
public class DateTimePicker : System.Windows.Forms.DateTimePicker
{
#region Member variables
// true, when no date shall be displayed (empty DateTimePicker)
private bool mIsNull;
//private bool mIsTextMode = true;
// If misNull = true, this value is shown in the DTP
private string mNullValue;
//private System.Windows.Forms.TextBox mTextBox = new TextBox();
// The format of the DateTimePicker control
private DateTimePickerFormat mFormat = DateTimePickerFormat.Long;
// The custom format of the DateTimePicker control
private string mCustomFormat;
// The format of the DateTimePicker control as string
private string mFormatAsString;
#endregion
#region Constructor
/// <summary>
/// Default Constructor
/// </summary>
public DateTimePicker() : base()
{
base.Format = DateTimePickerFormat.Custom;
mNullValue = " ";
Format = DateTimePickerFormat.Long;
}
#endregion
#region Public properties
/// <summary>
/// Gets or sets the date/time value assigned to the control.
/// </summary>
/// <value>The DateTime value assigned to the control
/// </value>
/// <remarks>
/// <p>If the <b>Value</b> property has not been changed in code or by the user, it is set
/// to the current date and time (<see cref="DateTime.Now"/>).</p>
/// <p>If <b>Value</b> is <b>null</b>, the DateTimePicker shows
/// <see cref="NullValue"/>.</p>
/// </remarks>
[Bindable(true)]
[Browsable(false)]
public new Object Value
{
get
{
if (mIsNull)
{
return null;
}
else
{
return base.Value;
}
}
set
{
if (value == null || value == DBNull.Value)
{
SetToNullValue();
}
else
{
SetToDateTimeValue();
base.Value = (DateTime)value;
}
}
}
/// <summary>
/// Gets or sets the format of the date and time displayed in the control.
/// </summary>
/// <value>One of the <see cref="DateTimePickerFormat"/> values. The default is
/// <see cref="DateTimePickerFormat.Long"/>.</value>
[Browsable(true)]
[DefaultValue(DateTimePickerFormat.Long), TypeConverter(typeof(Enum))]
public new DateTimePickerFormat Format
{
get { return mFormat; }
set
{
mFormat = value;
if (!mIsNull)
{
SetFormat();
}
OnFormatChanged(EventArgs.Empty);
}
}
/// <summary>
/// Gets or sets the custom date/time format string.
/// <value>A string that represents the custom date/time format. The default is a null
/// reference (<b>Nothing</b> in Visual Basic).</value>
/// </summary>
public new String CustomFormat
{
get { return mCustomFormat; }
set { mCustomFormat = value; }
}
/// <summary>
/// Gets or sets the string value that is assigned to the control as null value.
/// </summary>
/// <value>The string value assigned to the control as null value.</value>
/// <remarks>
/// If the <see cref="Value"/> is <b>null</b>, <b>NullValue</b> is
/// shown in the <b>DateTimePicker</b> control.
/// </remarks>
[Browsable(true)]
[Category("Behavior")]
[Description("The string used to display null values in the control")]
[DefaultValue(" ")]
public String NullValue
{
get { return mNullValue; }
set { mNullValue = value; }
}
#endregion
#region Private methods/properties
/// <summary>
/// Stores the current format of the DateTimePicker as string.
/// </summary>
private string FormatAsString
{
get { return mFormatAsString; }
set
{
mFormatAsString = value;
base.CustomFormat = value; }
}
/// <summary>
/// Sets the format according to the current DateTimePickerFormat.
/// </summary>
private void SetFormat()
{
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
DateTimeFormatInfo dtf = ci.DateTimeFormat;
switch (mFormat)
{
case DateTimePickerFormat.Long:
FormatAsString = dtf.LongDatePattern;
break;
case DateTimePickerFormat.Short:
FormatAsString = dtf.ShortDatePattern;
break;
case DateTimePickerFormat.Time:
FormatAsString = dtf.ShortTimePattern;
break;
case DateTimePickerFormat.Custom:
FormatAsString = this.CustomFormat;
break;
}
}
/// <summary>
/// Sets the <b>DateTimePicker</b> to the value of the <see cref="NullValue"/> property.
/// </summary>
private void SetToNullValue()
{
mIsNull = true;
base.CustomFormat = (mNullValue == null || mNullValue == String.Empty) ? " " : "'" + mNullValue + "'";
}
/// <summary>
/// Sets the <b>DateTimePicker</b> back to a non null value.
/// </summary>
private void SetToDateTimeValue()
{
if (mIsNull)
{
SetFormat();
mIsNull = false;
base.OnValueChanged(new EventArgs());
}
}
#endregion
#region Events
/// <summary>
/// This member overrides <see cref="Control.WndProc"/>.
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref Message m)
{
if (mIsNull)
{
if (m.Msg == 0x4e) // WMmNOTIFY
{
NMHDR nm = (NMHDR)m.GetLParam(typeof(NMHDR));
if (nm.Code == -746 || nm.Code == -722) // DTNmCLOSEUP || DTNm?
SetToDateTimeValue();
}
}
base.WndProc(ref m);
}
[StructLayout(LayoutKind.Sequential)]
private struct NMHDR
{
public IntPtr HwndFrom;
public int IdFrom;
public int Code;
}
/// <summary>
/// This member overrides <see cref="Control.OnKeyDown"/>.
/// </summary>
/// <param name="e"></param>
protected override void OnKeyUp(KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
this.Value = null;
OnValueChanged(EventArgs.Empty);
}
base.OnKeyUp(e);
}
protected override void OnValueChanged(EventArgs eventargs)
{
base.OnValueChanged(eventargs);
}
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
base.Focus();
if (this.Value == null)
{
SendKeys.SendWait("%{DOWN}");
}
}
protected override void OnLeave(EventArgs e)
{
SendKeys.Send("{ESC}");
base.OnLeave(e);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar.Equals('\r') || e.KeyChar.Equals('\t'))
{
e.Handled = true;
}
base.OnKeyPress(e);
}
#endregion
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using ASC.Data.Backup.Tasks.Data;
using ASC.Data.Backup.Utils;
namespace ASC.Data.Backup.Tasks.Modules
{
internal class CommunityModuleSpecifics : ModuleSpecificsBase
{
private readonly TableInfo[] _tables = new[]
{
new TableInfo("bookmarking_bookmark", "Tenant", "ID")
{
UserIDColumns = new[] {"UserCreatorID"},
DateColumns = new Dictionary<string, bool> {{"Date", false}}
},
new TableInfo("bookmarking_bookmarktag", "tenant"),
new TableInfo("bookmarking_comment", "tenant", "ID", IdType.Guid)
{
UserIDColumns = new[] {"UserID"},
DateColumns = new Dictionary<string, bool> {{"Datetime", false}}
},
new TableInfo("bookmarking_tag", "tenant", "TagID"),
new TableInfo("bookmarking_userbookmark", "tenant", "UserBookmarkID")
{
UserIDColumns = new[] {"UserID"},
DateColumns = new Dictionary<string, bool> {{"DateAdded", false}, {"LastModified", false}}
},
new TableInfo("bookmarking_userbookmarktag", "tenant"),
new TableInfo("blogs_comments", "Tenant", "id", IdType.Guid)
{
UserIDColumns = new[] {"created_by"},
DateColumns = new Dictionary<string, bool> {{"created_when", false}}
},
new TableInfo("blogs_posts", "Tenant", "post_id", IdType.Autoincrement)
{
UserIDColumns = new[] {"created_by"},
DateColumns = new Dictionary<string, bool> {{"created_when", false}, {"LastModified", false}}
},
new TableInfo("blogs_reviewposts", "Tenant")
{
UserIDColumns = new[] {"reviewed_by"},
DateColumns = new Dictionary<string, bool> {{"timestamp", false}}
},
new TableInfo("blogs_tags", "Tenant"),
new TableInfo("events_comment", "Tenant", "id")
{
UserIDColumns = new[] {"Creator"},
DateColumns = new Dictionary<string, bool> {{"Date", false}}
},
new TableInfo("events_feed", "Tenant", "id")
{
UserIDColumns = new[] {"Creator"},
DateColumns = new Dictionary<string, bool> {{"Date", false}, {"LastModified", false}}
},
new TableInfo("events_poll", "Tenant")
{
DateColumns = new Dictionary<string, bool> {{"StartDate", true}, {"EndDate", true}}
},
new TableInfo("events_pollanswer", "Tenant") {UserIDColumns = new[] {"User"}}, //todo: check //varchar(64)?
new TableInfo("events_pollvariant", "Tenant", "Id"),
new TableInfo("events_reader", "Tenant") {UserIDColumns = new[] {"Reader"}}, //todo: check
new TableInfo("forum_answer", "TenantID", "id")
{
UserIDColumns = new[] {"user_id"},
DateColumns = new Dictionary<string, bool> {{"create_date", false}}
},
new TableInfo("forum_answer_variant"),
new TableInfo("forum_attachment", "TenantID", "id")
{
DateColumns = new Dictionary<string, bool> {{"create_date", false}}
},
new TableInfo("forum_category", "TenantID", "id")
{
UserIDColumns = new[] {"poster_id"},
DateColumns = new Dictionary<string, bool> {{"create_date", false}}
},
new TableInfo("forum_lastvisit", "tenantid")
{
UserIDColumns = new[] {"user_id"},
DateColumns = new Dictionary<string, bool> {{"last_visit", false}}
},
new TableInfo("forum_post", "TenantID", "id")
{
UserIDColumns = new[] {"poster_id", "editor_id"},
DateColumns = new Dictionary<string, bool> {{"create_date", false}, {"edit_date", false}, {"LastModified", false}}
},
new TableInfo("forum_question", "TenantID", "id") {DateColumns = new Dictionary<string, bool> {{"create_date", false}}},
new TableInfo("forum_tag", "TenantID", "id"),
new TableInfo("forum_thread", "TenantID", "id")
{
UserIDColumns = new[] {"recent_poster_id"},
DateColumns = new Dictionary<string, bool> {{"recent_post_date", false}}
},
new TableInfo("forum_topic", "TenantID", "id")
{
UserIDColumns = new[] {"poster_id"},
DateColumns = new Dictionary<string, bool> {{"create_date", false}, {"LastModified", false}}
},
new TableInfo("forum_topicwatch", "TenantID") {UserIDColumns = new[] {"UserID"}},
new TableInfo("forum_topic_tag"),
new TableInfo("forum_variant", idColumn: "id"),
new TableInfo("wiki_categories", "Tenant"),
new TableInfo("wiki_comments", "Tenant", "Id", IdType.Guid)
{
UserIDColumns = new[] {"UserId"},
DateColumns = new Dictionary<string, bool> {{"Date", false}}
},
new TableInfo("wiki_files", "Tenant")
{
UserIDColumns = new[] {"UserID"},
DateColumns = new Dictionary<string, bool> {{"Date", false}}
},
new TableInfo("wiki_pages", "tenant", "id", IdType.Autoincrement)
{
UserIDColumns = new[] {"modified_by"},
DateColumns = new Dictionary<string, bool> {{"modified_on", false}}
},
new TableInfo("wiki_pages_history", "Tenant")
{
UserIDColumns = new[] {"create_by"},
DateColumns = new Dictionary<string, bool> {{"create_on", false}}
},
};
private readonly RelationInfo[] _tableRelations = new[]
{
new RelationInfo("bookmarking_bookmark", "ID", "bookmarking_bookmarktag", "BookmarkID"),
new RelationInfo("bookmarking_tag", "TagID", "bookmarking_bookmarktag", "TagID"),
new RelationInfo("bookmarking_bookmark", "ID", "bookmarking_comment", "BookmarkID"),
new RelationInfo("bookmarking_comment", "ID", "bookmarking_comment", "Parent"),
new RelationInfo("bookmarking_bookmark", "ID", "bookmarking_userbookmark", "BookmarkID"),
new RelationInfo("bookmarking_tag", "TagID", "bookmarking_userbookmarktag", "TagID"),
new RelationInfo("bookmarking_userbookmark", "UserBookmarkID", "bookmarking_userbookmarktag", "UserBookmarkID"),
new RelationInfo("blogs_comments", "id", "blogs_comments", "parent_id"),
new RelationInfo("blogs_posts", "id", "blogs_comments", "post_id"),
new RelationInfo("blogs_comments", "id", "blogs_posts", "LastCommentId", null, null, RelationImportance.Low),
new RelationInfo("blogs_posts", "id", "blogs_reviewposts", "post_id"),
new RelationInfo("blogs_posts", "id", "blogs_tags", "post_id"),
new RelationInfo("events_feed", "Id", "events_comment", "Feed"),
new RelationInfo("events_comment", "Id", "events_comment", "Parent"),
new RelationInfo("events_feed", "Id", "events_poll", "Id"),
new RelationInfo("events_pollvariant", "Id", "events_pollanswer", "Variant"),
new RelationInfo("events_feed", "Id", "events_pollvariant", "Poll"),
new RelationInfo("events_feed", "Id", "events_reader", "Feed"),
new RelationInfo("forum_question", "id", "forum_answer", "question_id"),
new RelationInfo("forum_answer", "id", "forum_answer_variant", "answer_id"),
new RelationInfo("forum_variant", "id", "forum_answer_variant", "variant_id"),
new RelationInfo("forum_post", "id", "forum_attachment", "post_id"),
new RelationInfo("forum_category", "id", "forum_attachment", "path"),
new RelationInfo("forum_thread", "id", "forum_attachment", "path"),
new RelationInfo("forum_thread", "id", "forum_lastvisit", "thread_id"),
new RelationInfo("forum_topic", "id", "forum_post", "topic_id"),
new RelationInfo("forum_post", "id", "forum_post", "parent_post_id"),
new RelationInfo("forum_topic", "id", "forum_question", "topic_id"),
new RelationInfo("forum_category", "id", "forum_thread", "category_id"),
new RelationInfo("forum_post", "id", "forum_thread", "recent_post_id", null, null, RelationImportance.Low),
new RelationInfo("forum_topic", "id", "forum_thread", "recent_topic_id", null, null, RelationImportance.Low),
new RelationInfo("forum_thread", "id", "forum_topic", "thread_id"),
new RelationInfo("forum_question", "id", "forum_topic", "question_id", null, null, RelationImportance.Low),
new RelationInfo("forum_post", "id", "forum_topic", "recent_post_id", null, null, RelationImportance.Low),
new RelationInfo("forum_topic", "id", "forum_topicwatch", "TopicID"),
new RelationInfo("forum_topic", "id", "forum_topic_tag", "topic_id"),
new RelationInfo("forum_tag", "id", "forum_topic_tag", "tag_id"),
new RelationInfo("forum_question", "id", "forum_variant", "question_id"),
new RelationInfo("wiki_comments", "Id", "wiki_comments", "ParentId")
};
public override ModuleName ModuleName
{
get { return ModuleName.Community; }
}
public override IEnumerable<TableInfo> Tables
{
get { return _tables; }
}
public override IEnumerable<RelationInfo> TableRelations
{
get { return _tableRelations; }
}
public override bool TryAdjustFilePath(bool dump, ColumnMapper columnMapper, ref string filePath)
{
filePath = PreparePath(dump, columnMapper, "/", filePath);
return filePath != null;
}
protected override bool TryPrepareValue(bool dump, DbConnection connection, ColumnMapper columnMapper, TableInfo table, string columnName, IEnumerable<RelationInfo> relations, ref object value)
{
relations = relations.ToList();
if (relations.All(x => x.ChildTable == "forum_attachment" && x.ChildColumn == "path"))
{
value = PreparePath(dump, columnMapper, "\\", Convert.ToString(value));
return value != null;
}
return base.TryPrepareValue(dump, connection, columnMapper, table, columnName, relations, ref value);
}
protected override bool TryPrepareValue(DbConnection connection, ColumnMapper columnMapper, TableInfo table, string columnName, ref object value)
{
var column = columnName.ToLowerInvariant();
if (table.Name == "forum_post" && column == "text" ||
table.Name == "events_feed" && column == "text" ||
table.Name == "events_comment" && column == "comment" ||
table.Name == "blogs_posts" && column == "content" ||
table.Name == "blogs_comments" && column == "content" ||
table.Name == "bookmarking_comment" && column == "content" ||
table.Name == "wiki_comments" && column == "body")
{
value = FCKEditorPathUtility.CorrectStoragePath(value as string, columnMapper.GetTenantMapping());
return true;
}
return base.TryPrepareValue(connection, columnMapper, table, columnName, ref value);
}
protected override string GetSelectCommandConditionText(int tenantId, TableInfo table)
{
if (table.Name == "forum_answer_variant")
return "inner join forum_answer as t1 on t1.id = t.answer_id where t1.TenantID = " + tenantId;
if (table.Name == "forum_variant")
return "inner join forum_question as t1 on t1.id = t.question_id where t1.TenantID = " + tenantId;
if (table.Name == "forum_topic_tag")
return "inner join forum_topic as t1 on t1.id = t.topic_id where t1.TenantID = " + tenantId;
return base.GetSelectCommandConditionText(tenantId, table);
}
private static string PreparePath(bool dump, ColumnMapper columnMapper, string partsSeparator, string path)
{
string[] parts = path.Split(new[] { partsSeparator }, StringSplitOptions.None);
if (parts.Length != 4)
return null;
var categoryId = columnMapper.GetMapping("forum_category", "id", parts[0]);
if (categoryId == null)
{
if (!dump) return null;
categoryId = parts[0];
}
var threadId = columnMapper.GetMapping("forum_thread", "id", parts[1]);
if (threadId == null)
{
if (!dump) return null;
threadId = parts[1];
}
parts[0] = categoryId.ToString();
parts[1] = threadId.ToString();
return string.Join(partsSeparator, parts);
}
}
}
| |
using System;
using OrchardCore.ContentManagement.Records;
using OrchardCore.Data.Migration;
namespace OrchardCore.ContentFields.Indexing.SQL
{
public class Migrations : DataMigration
{
public int Create()
{
// NOTE: The Text Length has been decreased from 4000 characters to 768.
// For existing SQL databases update the TextFieldIndex tables Text column length manually.
SchemaBuilder.CreateMapIndexTable(nameof(TextFieldIndex), table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("Text", column => column.Nullable().WithLength(TextFieldIndex.MaxTextSize))
.Column<string>("BigText", column => column.Nullable().Unlimited())
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(TextFieldIndex), table => table
.CreateIndex("IDX_TextFieldIndex_Text", "Text")
);
SchemaBuilder.CreateMapIndexTable(nameof(BooleanFieldIndex), table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<bool>("Boolean", column => column.Nullable())
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(BooleanFieldIndex), table => table
.CreateIndex("IDX_BooleanFieldIndex_Boolean", "Boolean")
);
SchemaBuilder.CreateMapIndexTable(nameof(NumericFieldIndex), table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<decimal>("Numeric", column => column.Nullable())
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(NumericFieldIndex), table => table
.CreateIndex("IDX_NumericFieldIndex_Numeric", "Numeric")
);
SchemaBuilder.CreateMapIndexTable(nameof(DateTimeFieldIndex), table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<DateTime>("DateTime", column => column.Nullable())
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(DateTimeFieldIndex), table => table
.CreateIndex("IDX_DateTimeFieldIndex_DateTime", "DateTime")
);
SchemaBuilder.CreateMapIndexTable(nameof(DateFieldIndex), table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<DateTime>("Date", column => column.Nullable())
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(DateFieldIndex), table => table
.CreateIndex("IDX_DateFieldIndex_Date", "Date")
);
SchemaBuilder.CreateMapIndexTable(nameof(ContentPickerFieldIndex), table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("SelectedContentItemId", column => column.WithLength(26))
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(ContentPickerFieldIndex), table => table
.CreateIndex("IDX_ContentPickerFieldIndex_SelectedContentItemId", "SelectedContentItemId")
);
SchemaBuilder.CreateMapIndexTable(nameof(TimeFieldIndex), table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<DateTime>("Time", column => column.Nullable())
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(TimeFieldIndex), table => table
.CreateIndex("IDX_TimeFieldIndex_Time", "Time")
);
// NOTE: The Url and Text Length has been decreased from 4000 characters to 768.
// For existing SQL databases update the LinkFieldIndex tables Url and Text column length manually.
// The BigText and BigUrl columns are new additions so will not be populated until the content item is republished.
SchemaBuilder.CreateMapIndexTable(nameof(LinkFieldIndex), table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("Url", column => column.Nullable().WithLength(LinkFieldIndex.MaxUrlSize))
.Column<string>("BigUrl", column => column.Nullable().Unlimited())
.Column<string>("Text", column => column.Nullable().WithLength(LinkFieldIndex.MaxTextSize))
.Column<string>("BigText", column => column.Nullable().Unlimited())
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_Latest", "Latest")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_Url", "Url")
);
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.CreateIndex("IDX_LinkFieldIndex_Text", "Text")
);
SchemaBuilder.CreateMapIndexTable(nameof(HtmlFieldIndex), table => table
.Column<string>("ContentItemId", column => column.WithLength(26))
.Column<string>("ContentItemVersionId", column => column.WithLength(26))
.Column<string>("ContentType", column => column.WithLength(ContentItemIndex.MaxContentTypeSize))
.Column<string>("ContentPart", column => column.WithLength(ContentItemIndex.MaxContentPartSize))
.Column<string>("ContentField", column => column.WithLength(ContentItemIndex.MaxContentFieldSize))
.Column<bool>("Published", column => column.Nullable())
.Column<bool>("Latest", column => column.Nullable())
.Column<string>("Html", column => column.Nullable().Unlimited())
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_ContentItemId", "ContentItemId")
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_ContentItemVersionId", "ContentItemVersionId")
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_ContentType", "ContentType")
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_ContentPart", "ContentPart")
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_ContentField", "ContentField")
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_Published", "Published")
);
SchemaBuilder.AlterTable(nameof(HtmlFieldIndex), table => table
.CreateIndex("IDX_HtmlFieldIndex_Latest", "Latest")
);
// Return 2 to shorcut migrations on new installations.
return 2;
}
public int UpdateFrom1()
{
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.AddColumn<string>("BigUrl", column => column.Nullable().Unlimited()));
SchemaBuilder.AlterTable(nameof(LinkFieldIndex), table => table
.AddColumn<string>("BigText", column => column.Nullable().Unlimited()));
return 2;
}
}
}
| |
/*
* Copyright 2011 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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using CoinSharp.IO;
using CoinSharp.TransactionScript;
namespace CoinSharp
{
/// <summary>
/// A transfer of coins from one address to another creates a transaction in which the outputs
/// can be claimed by the recipient in the input of another transaction. You can imagine a
/// transaction as being a module which is wired up to others, the inputs of one have to be wired
/// to the outputs of another. The exceptions are coinbase transactions, which create new coins.
/// </summary>
[Serializable]
public class TransactionInput : Message
{
public static readonly byte[] EmptyArray = new byte[0];
// Allows for altering transactions after they were broadcast. Tx replacement is currently disabled in the C++
// client so this is always the UINT_MAX.
// TODO: Document this in more detail and build features that use it.
private uint _sequence;
// Data needed to connect to the output of the transaction we're gathering coins from.
internal TransactionOutPoint Outpoint { get; private set; }
// The "script bytes" might not actually be a script. In coinbase transactions where new coins are minted there
// is no input transaction, so instead the scriptBytes contains some extra stuff (like a rollover nonce) that we
// don't care about much. The bytes are turned into a Script object (cached below) on demand via a getter.
internal byte[] ScriptBytes { get; set; }
// The Script object obtained from parsing scriptBytes. Only filled in on demand and if the transaction is not
// coinbase.
[NonSerialized] private Script _scriptSig;
// A pointer to the transaction that owns this input.
internal Transaction ParentTransaction { get; private set; }
/// <summary>
/// Used only in creation of the genesis block.
/// </summary>
internal TransactionInput(NetworkParameters networkParams, Transaction parentTransaction, byte[] scriptBytes)
: base(networkParams)
{
ScriptBytes = scriptBytes;
Outpoint = new TransactionOutPoint(networkParams, -1, null);
_sequence = uint.MaxValue;
ParentTransaction = parentTransaction;
}
/// <summary>
/// Creates an UNSIGNED input that links to the given output
/// </summary>
internal TransactionInput(NetworkParameters networkParams, Transaction parentTransaction, TransactionOutput output)
: base(networkParams)
{
var outputIndex = output.Index;
Outpoint = new TransactionOutPoint(networkParams, outputIndex, output.ParentTransaction);
ScriptBytes = EmptyArray;
_sequence = uint.MaxValue;
ParentTransaction = parentTransaction;
}
/// <summary>
/// Deserializes an input message. This is usually part of a transaction message.
/// </summary>
/// <exception cref="ProtocolException"/>
public TransactionInput(NetworkParameters networkParams, Transaction parentTransaction, byte[] payload, int offset)
: base(networkParams, payload, offset)
{
ParentTransaction = parentTransaction;
}
/// <exception cref="ProtocolException"/>
protected override void Parse()
{
Outpoint = new TransactionOutPoint(Params, Bytes, Cursor);
Cursor += Outpoint.MessageSize;
var scriptLen = (int) ReadVarInt();
ScriptBytes = ReadBytes(scriptLen);
_sequence = ReadUint32();
}
/// <exception cref="IOException"/>
public override void BitcoinSerializeToStream(Stream stream)
{
Outpoint.BitcoinSerializeToStream(stream);
stream.Write(new VarInt((ulong) ScriptBytes.Length).Encode());
stream.Write(ScriptBytes);
stream.WriteLittleEndian(_sequence);
}
/// <summary>
/// Coinbase transactions have special inputs with hashes of zero. If this is such an input, returns true.
/// </summary>
public bool IsCoinBase
{
get { return Outpoint.Hash.Equals(Sha256Hash.ZeroHash); }
}
/// <summary>
/// Returns the input script.
/// </summary>
/// <exception cref="ScriptException"/>
public Script ScriptSig
{
get
{
// Transactions that generate new coins don't actually have a script. Instead this
// parameter is overloaded to be something totally different.
if (_scriptSig == null)
{
Debug.Assert(ScriptBytes != null);
_scriptSig = new Script(Params, ScriptBytes, 0, ScriptBytes.Length);
}
return _scriptSig;
}
}
/// <summary>
/// Convenience method that returns the from address of this input by parsing the scriptSig.
/// </summary>
/// <exception cref="ScriptException">If the scriptSig could not be understood (eg, if this is a coinbase transaction).</exception>
public Address FromAddress
{
get
{
Debug.Assert(!IsCoinBase);
return ScriptSig.FromAddress;
}
}
/// <summary>
/// Returns a human readable debug string.
/// </summary>
public override string ToString()
{
if (IsCoinBase)
{
return "TxIn: COINBASE";
}
return "TxIn from tx " + Outpoint + " (pubkey: " + Utils.BytesToHexString(ScriptSig.PubKey) + ") script:" + ScriptSig;
}
internal enum ConnectionResult
{
NoSuchTx,
AlreadySpent,
Success
}
// TODO: Clean all this up once TransactionOutPoint disappears.
/// <summary>
/// Locates the referenced output from the given pool of transactions.
/// </summary>
/// <returns>The TransactionOutput or null if the transactions map doesn't contain the referenced tx.</returns>
internal TransactionOutput GetConnectedOutput(IDictionary<Sha256Hash, Transaction> transactions)
{
Transaction tx;
if (!transactions.TryGetValue(Outpoint.Hash, out tx))
return null;
var @out = tx.Outputs[Outpoint.Index];
return @out;
}
/// <summary>
/// Connects this input to the relevant output of the referenced transaction if it's in the given map.
/// Connecting means updating the internal pointers and spent flags.
/// </summary>
/// <param name="transactions">Map of txhash->transaction.</param>
/// <param name="disconnect">Whether to abort if there's a pre-existing connection or not.</param>
/// <returns>True if connection took place, false if the referenced transaction was not in the list.</returns>
internal ConnectionResult Connect(IDictionary<Sha256Hash, Transaction> transactions, bool disconnect)
{
Transaction tx;
if (!transactions.TryGetValue(Outpoint.Hash, out tx))
return ConnectionResult.NoSuchTx;
var @out = tx.Outputs[Outpoint.Index];
if (!@out.IsAvailableForSpending)
{
if (disconnect)
@out.MarkAsUnspent();
else
return ConnectionResult.AlreadySpent;
}
Outpoint.FromTx = tx;
@out.MarkAsSpent(this);
return ConnectionResult.Success;
}
/// <summary>
/// Release the connected output, making it spendable once again.
/// </summary>
/// <returns>True if the disconnection took place, false if it was not connected.</returns>
internal bool Disconnect()
{
if (Outpoint.FromTx == null) return false;
Outpoint.FromTx.Outputs[Outpoint.Index].MarkAsUnspent();
Outpoint.FromTx = null;
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
using System.Runtime.Versioning;
namespace System.Collections.Generic
{
#region ArraySortHelper for single arrays
internal static class IntrospectiveSortUtilities
{
// This is the threshold where Introspective sort switches to Insertion sort.
// Imperically, 16 seems to speed up most cases without slowing down others, at least for integers.
// Large value types may benefit from a smaller number.
internal const int IntrosortSizeThreshold = 16;
internal static int FloorLog2(int n)
{
int result = 0;
while (n >= 1)
{
result++;
n = n / 2;
}
return result;
}
internal static void ThrowOrIgnoreBadComparer(Object comparer)
{
// This is hit when an invarant of QuickSort is violated due to a bad IComparer implementation (for
// example, imagine an IComparer that returns 0 when items are equal but -1 all other times).
throw new ArgumentException(SR.Format(SR.Arg_BogusIComparer, comparer));
}
}
internal class ArraySortHelper<T>
{
#region ArraySortHelper<T> public Members
public static void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
Contract.Assert(keys != null, "Check the arguments in the caller!");
Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
try
{
if (comparer == null)
{
comparer = LowLevelComparer<T>.Default;
}
IntrospectiveSort(keys, index, length, comparer);
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
public static int BinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
try
{
if (comparer == null)
{
comparer = LowLevelComparer<T>.Default;
}
return InternalBinarySearch(array, index, length, value, comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
#endregion
internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
Contract.Requires(array != null, "Check the arguments in the caller!");
Contract.Requires(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
int lo = index;
int hi = index + length - 1;
while (lo <= hi)
{
int i = lo + ((hi - lo) >> 1);
int order = comparer.Compare(array[i], value);
if (order == 0) return i;
if (order < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
private static void SwapIfGreater(T[] keys, IComparer<T> comparer, int a, int b)
{
if (a != b)
{
if (comparer.Compare(keys[a], keys[b]) > 0)
{
T key = keys[a];
keys[a] = keys[b];
keys[b] = key;
}
}
}
private static void Swap(T[] a, int i, int j)
{
if (i != j)
{
T t = a[i];
a[i] = a[j];
a[j] = t;
}
}
internal static void IntrospectiveSort(T[] keys, int left, int length, IComparer<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
Contract.Requires(left >= 0);
Contract.Requires(length >= 0);
Contract.Requires(length <= keys.Length);
Contract.Requires(length + left <= keys.Length);
if (length < 2)
return;
IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2(keys.Length), comparer);
}
private static void IntroSort(T[] keys, int lo, int hi, int depthLimit, IComparer<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreater(keys, comparer, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreater(keys, comparer, lo, hi - 1);
SwapIfGreater(keys, comparer, lo, hi);
SwapIfGreater(keys, comparer, hi - 1, hi);
return;
}
InsertionSort(keys, lo, hi, comparer);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, lo, hi, comparer);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, lo, hi, comparer);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, p + 1, hi, depthLimit, comparer);
hi = p - 1;
}
}
private static int PickPivotAndPartition(T[] keys, int lo, int hi, IComparer<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi > lo);
Contract.Requires(hi < keys.Length);
Contract.Ensures(Contract.Result<int>() >= lo && Contract.Result<int>() <= hi);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreater(keys, comparer, lo, middle); // swap the low with the mid point
SwapIfGreater(keys, comparer, lo, hi); // swap the low with the high
SwapIfGreater(keys, comparer, middle, hi); // swap the middle with the high
T pivot = keys[middle];
Swap(keys, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
while (comparer.Compare(keys[++left], pivot) < 0) ;
while (comparer.Compare(pivot, keys[--right]) < 0) ;
if (left >= right)
break;
Swap(keys, left, right);
}
// Put pivot in the right location.
Swap(keys, left, (hi - 1));
return left;
}
private static void Heapsort(T[] keys, int lo, int hi, IComparer<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi > lo);
Contract.Requires(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, i, n, lo, comparer);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, lo, lo + i - 1);
DownHeap(keys, 1, i - 1, lo, comparer);
}
}
private static void DownHeap(T[] keys, int i, int n, int lo, IComparer<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(lo < keys.Length);
T d = keys[lo + i - 1];
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && comparer.Compare(keys[lo + child - 1], keys[lo + child]) < 0)
{
child++;
}
if (!(comparer.Compare(d, keys[lo + child - 1]) < 0))
break;
keys[lo + i - 1] = keys[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
}
private static void InsertionSort(T[] keys, int lo, int hi, IComparer<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi >= lo);
Contract.Requires(hi <= keys.Length);
int i, j;
T t;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
while (j >= lo && comparer.Compare(t, keys[j]) < 0)
{
keys[j + 1] = keys[j];
j--;
}
keys[j + 1] = t;
}
}
}
#endregion
#region ArraySortHelper for paired key and value arrays
internal class ArraySortHelper<TKey, TValue>
{
// WARNING: We allow diagnostic tools to directly inspect this member (s_defaultArraySortHelper).
// See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
// Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
// Get in touch with the diagnostics team if you have questions.
private static volatile ArraySortHelper<TKey, TValue> s_defaultArraySortHelper;
public static ArraySortHelper<TKey, TValue> Default
{
get
{
ArraySortHelper<TKey, TValue> sorter = s_defaultArraySortHelper;
if (sorter == null)
sorter = CreateArraySortHelper();
return sorter;
}
}
private static ArraySortHelper<TKey, TValue> CreateArraySortHelper()
{
s_defaultArraySortHelper = new ArraySortHelper<TKey, TValue>();
return s_defaultArraySortHelper;
}
public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
{
Contract.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method
Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
try
{
if (comparer == null || comparer == LowLevelComparer<TKey>.Default)
{
comparer = LowLevelComparer<TKey>.Default;
}
IntrospectiveSort(keys, values, index, length, comparer);
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, IComparer<TKey> comparer, int a, int b)
{
Contract.Requires(keys != null);
Contract.Requires(values == null || values.Length >= keys.Length);
Contract.Requires(comparer != null);
Contract.Requires(0 <= a && a < keys.Length);
Contract.Requires(0 <= b && b < keys.Length);
if (a != b)
{
if (comparer.Compare(keys[a], keys[b]) > 0)
{
TKey key = keys[a];
keys[a] = keys[b];
keys[b] = key;
if (values != null)
{
TValue value = values[a];
values[a] = values[b];
values[b] = value;
}
}
}
}
private static void Swap(TKey[] keys, TValue[] values, int i, int j)
{
if (i != j)
{
TKey k = keys[i];
keys[i] = keys[j];
keys[j] = k;
if (values != null)
{
TValue v = values[i];
values[i] = values[j];
values[j] = v;
}
}
}
internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(comparer != null);
Contract.Requires(left >= 0);
Contract.Requires(length >= 0);
Contract.Requires(length <= keys.Length);
Contract.Requires(length + left <= keys.Length);
Contract.Requires(length + left <= values.Length);
if (length < 2)
return;
IntroSort(keys, values, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2(keys.Length), comparer);
}
private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreaterWithItems(keys, values, comparer, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreaterWithItems(keys, values, comparer, lo, hi - 1);
SwapIfGreaterWithItems(keys, values, comparer, lo, hi);
SwapIfGreaterWithItems(keys, values, comparer, hi - 1, hi);
return;
}
InsertionSort(keys, values, lo, hi, comparer);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, values, lo, hi, comparer);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, values, lo, hi, comparer);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, values, p + 1, hi, depthLimit, comparer);
hi = p - 1;
}
}
private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi > lo);
Contract.Requires(hi < keys.Length);
Contract.Ensures(Contract.Result<int>() >= lo && Contract.Result<int>() <= hi);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreaterWithItems(keys, values, comparer, lo, middle); // swap the low with the mid point
SwapIfGreaterWithItems(keys, values, comparer, lo, hi); // swap the low with the high
SwapIfGreaterWithItems(keys, values, comparer, middle, hi); // swap the middle with the high
TKey pivot = keys[middle];
Swap(keys, values, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
while (comparer.Compare(keys[++left], pivot) < 0) ;
while (comparer.Compare(pivot, keys[--right]) < 0) ;
if (left >= right)
break;
Swap(keys, values, left, right);
}
// Put pivot in the right location.
Swap(keys, values, left, (hi - 1));
return left;
}
private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi > lo);
Contract.Requires(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, values, i, n, lo, comparer);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, values, lo, lo + i - 1);
DownHeap(keys, values, 1, i - 1, lo, comparer);
}
}
private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(lo < keys.Length);
TKey d = keys[lo + i - 1];
TValue dValue = (values != null) ? values[lo + i - 1] : default(TValue);
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && comparer.Compare(keys[lo + child - 1], keys[lo + child]) < 0)
{
child++;
}
if (!(comparer.Compare(d, keys[lo + child - 1]) < 0))
break;
keys[lo + i - 1] = keys[lo + child - 1];
if (values != null)
values[lo + i - 1] = values[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
if (values != null)
values[lo + i - 1] = dValue;
}
private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi >= lo);
Contract.Requires(hi <= keys.Length);
int i, j;
TKey t;
TValue tValue;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
tValue = (values != null) ? values[i + 1] : default(TValue);
while (j >= lo && comparer.Compare(t, keys[j]) < 0)
{
keys[j + 1] = keys[j];
if (values != null)
values[j + 1] = values[j];
j--;
}
keys[j + 1] = t;
if (values != null)
values[j + 1] = tValue;
}
}
}
#endregion
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="" file="UpdateTableBuilder.cs">
//
// </copyright>
// <summary>
// The BuildUpdateTable interface.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#region using directives
using System;
using System.Linq.Expressions;
using RabbitDB.Contracts.SqlDialect;
using RabbitDB.Mapping;
using RabbitDB.SqlBuilder;
#endregion
namespace RabbitDB.Expressions
{
/// <summary>
/// The BuildUpdateTable interface.
/// </summary>
/// <typeparam name="T">
/// </typeparam>
internal interface IBuildUpdateTable<T>
{
#region Public Methods
/// <summary>
/// The set.
/// </summary>
/// <param name="column">
/// The column.
/// </param>
/// <param name="statement">
/// The statement.
/// </param>
/// <returns>
/// The
/// <see>
/// <cref>IBuildUpdateTable</cref>
/// </see>
/// .
/// </returns>
IBuildUpdateTable<T> Set(Expression<Func<T, object>> column, Expression<Func<T, object>> statement);
/// <summary>
/// The set.
/// </summary>
/// <param name="column">
/// The column.
/// </param>
/// <param name="value">
/// The value.
/// </param>
/// <returns>
/// The
/// <see>
/// <cref>IBuildUpdateTable</cref>
/// </see>
/// .
/// </returns>
IBuildUpdateTable<T> Set(Expression<Func<T, object>> column, object value);
/// <summary>
/// The set.
/// </summary>
/// <param name="column">
/// The column.
/// </param>
/// <param name="value">
/// The value.
/// </param>
void Set(string column, object value);
/// <summary>
/// The where.
/// </summary>
/// <param name="criteria">
/// The criteria.
/// </param>
void Where(Expression<Func<T, bool>> criteria);
#endregion
}
/// <summary>
/// The update table builder.
/// </summary>
/// <typeparam name="T">
/// </typeparam>
internal class UpdateTableBuilder<T> : IBuildUpdateTable<T>
{
#region Fields
/// <summary>
/// The _builder.
/// </summary>
private readonly SqlExpressionBuilder<T> _builder;
/// <summary>
/// The _sql dialect.
/// </summary>
private readonly ISqlDialect _sqlDialect;
/// <summary>
/// The _table info.
/// </summary>
private readonly TableInfo _tableInfo;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <see cref="UpdateTableBuilder{T}" /> class.
/// </summary>
/// <param name="sqlDialect">
/// The sql dialect.
/// </param>
/// <param name="updateSqlBuilder">
/// The update sql builder.
/// </param>
public UpdateTableBuilder(ISqlDialect sqlDialect, UpdateSqlBuilder updateSqlBuilder)
{
_builder = new SqlExpressionBuilder<T>(sqlDialect);
_sqlDialect = sqlDialect;
_tableInfo = TableInfo<T>.GetTableInfo;
_builder.Append(updateSqlBuilder.GetBaseUpdate());
}
#endregion
#region Public Methods
/// <summary>
/// The get parameters.
/// </summary>
/// <returns>
/// The <see cref="object[]" />.
/// </returns>
public object[] GetParameters()
{
return _builder.Parameters.ToArray();
}
/// <summary>
/// The get sql.
/// </summary>
/// <returns>
/// The <see cref="string" />.
/// </returns>
public string GetSql()
{
return _builder.ToString();
}
/// <summary>
/// The set.
/// </summary>
/// <param name="column">
/// The column.
/// </param>
/// <param name="statement">
/// The statement.
/// </param>
/// <returns>
/// The
/// <see>
/// <cref>IBuildUpdateTable</cref>
/// </see>
/// .
/// </returns>
public IBuildUpdateTable<T> Set(Expression<Func<T, object>> column, Expression<Func<T, object>> statement)
{
_builder.Append($" {_sqlDialect.SqlCharacters.EscapeName(_tableInfo.ResolveColumnName(column.Body.GetPropertyName()))}=");
_builder.Write(statement);
_builder.Append(",");
return this;
}
/// <summary>
/// The set.
/// </summary>
/// <param name="column">
/// The column.
/// </param>
/// <param name="value">
/// The value.
/// </param>
/// <returns>
/// The
/// <see>
/// <cref>IBuildUpdateTable</cref>
/// </see>
/// .
/// </returns>
public IBuildUpdateTable<T> Set(Expression<Func<T, object>> column, object value)
{
Set(column.Body.GetPropertyName(), value);
return this;
}
/// <summary>
/// The set.
/// </summary>
/// <param name="column">
/// The column.
/// </param>
/// <param name="value">
/// The value.
/// </param>
public void Set(string column, object value)
{
_builder.Append($" {_sqlDialect.SqlCharacters.EscapeName(_tableInfo.ResolveColumnName(column))}=@{_builder.Parameters.NextIndex},");
_builder.Parameters.Add(value);
}
/// <summary>
/// The where.
/// </summary>
/// <param name="criteria">
/// The criteria.
/// </param>
public void Where(Expression<Func<T, bool>> criteria)
{
_builder.EndEnumeration();
_builder.Where(criteria);
}
#endregion
}
}
| |
// Copyright 2007-2018 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.Transports.InMemory
{
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Builders;
using Configuration;
using Context;
using Fabric;
using GreenPipes;
using GreenPipes.Agents;
using GreenPipes.Caching;
using Logging;
using MassTransit.Topology;
using Pipeline;
using Topology.Builders;
/// <summary>
/// Caches InMemory transport instances so that they are only created and used once
/// </summary>
public class InMemoryHost :
Supervisor,
IInMemoryHostControl,
ISendTransportProvider
{
static readonly ILog _log = Logger.Get<InMemoryHost>();
readonly Uri _baseUri;
readonly IIndex<string, InMemorySendTransport> _index;
readonly IMessageFabric _messageFabric;
readonly IReceiveEndpointCollection _receiveEndpoints;
readonly IInMemoryReceiveEndpointFactory _receiveEndpointFactory;
public InMemoryHost(IInMemoryBusConfiguration busConfiguration, int concurrencyLimit, IHostTopology topology, Uri baseAddress = null)
{
Topology = topology;
_baseUri = baseAddress ?? new Uri("loopback://localhost/");
_messageFabric = new MessageFabric(concurrencyLimit);
_receiveEndpoints = new ReceiveEndpointCollection();
var cacheSettings = new CacheSettings(10000, TimeSpan.FromMinutes(1), TimeSpan.FromHours(24));
var cache = new GreenCache<InMemorySendTransport>(cacheSettings);
_index = cache.AddIndex("exchangeName", x => x.ExchangeName);
_receiveEndpointFactory = new InMemoryReceiveEndpointFactory(busConfiguration);
}
public IReceiveEndpointCollection ReceiveEndpoints => _receiveEndpoints;
public void AddReceiveEndpoint(string endpointName, IReceiveEndpointControl receiveEndpoint)
{
ReceiveEndpoints.Add(endpointName, receiveEndpoint);
}
public async Task<HostHandle> Start()
{
HostReceiveEndpointHandle[] handles = ReceiveEndpoints.StartEndpoints();
return new Handle(this, handles);
}
public bool Matches(Uri address)
{
return address.ToString().StartsWith(_baseUri.ToString(), StringComparison.OrdinalIgnoreCase);
}
void IProbeSite.Probe(ProbeContext context)
{
var scope = context.CreateScope("host");
scope.Set(new
{
Type = "InMemory"
});
_messageFabric.Probe(scope);
_receiveEndpoints.Probe(scope);
}
public IReceiveTransport GetReceiveTransport(string queueName, IReceivePipe receivePipe, ReceiveEndpointContext topology)
{
if (_log.IsDebugEnabled)
_log.DebugFormat("Creating receive transport for queue: {0}", queueName);
var queue = _messageFabric.GetQueue(queueName);
var skippedExchange = _messageFabric.GetExchange($"{queueName}_skipped");
var errorExchange = _messageFabric.GetExchange($"{queueName}_error");
var transport = new InMemoryReceiveTransport(new Uri(_baseUri, queueName), queue, receivePipe, errorExchange, skippedExchange, topology);
Add(transport);
return transport;
}
public HostReceiveEndpointHandle ConnectReceiveEndpoint(string queueName, Action<IInMemoryReceiveEndpointConfigurator> configure = null)
{
_receiveEndpointFactory.CreateReceiveEndpoint(queueName, configure);
return _receiveEndpoints.Start(queueName);
}
public Uri Address => _baseUri;
public IHostTopology Topology { get; }
ConnectHandle IConsumeMessageObserverConnector.ConnectConsumeMessageObserver<T>(IConsumeMessageObserver<T> observer)
{
return _receiveEndpoints.ConnectConsumeMessageObserver(observer);
}
ConnectHandle IConsumeObserverConnector.ConnectConsumeObserver(IConsumeObserver observer)
{
return _receiveEndpoints.ConnectConsumeObserver(observer);
}
ConnectHandle IReceiveObserverConnector.ConnectReceiveObserver(IReceiveObserver observer)
{
return _receiveEndpoints.ConnectReceiveObserver(observer);
}
ConnectHandle IReceiveEndpointObserverConnector.ConnectReceiveEndpointObserver(IReceiveEndpointObserver observer)
{
return _receiveEndpoints.ConnectReceiveEndpointObserver(observer);
}
ConnectHandle IPublishObserverConnector.ConnectPublishObserver(IPublishObserver observer)
{
return _receiveEndpoints.ConnectPublishObserver(observer);
}
ConnectHandle ISendObserverConnector.ConnectSendObserver(ISendObserver observer)
{
return _receiveEndpoints.ConnectSendObserver(observer);
}
public async Task<ISendTransport> GetSendTransport(Uri address)
{
var queueName = address.AbsolutePath.Split('/').Last();
return await _index.Get(queueName, async key =>
{
if (_log.IsDebugEnabled)
_log.DebugFormat("Creating send transport for exchange: {0}", queueName);
var exchange = _messageFabric.GetExchange(queueName);
var transport = new InMemorySendTransport(exchange);
return transport;
});
}
public IInMemoryExchange GetExchange(Uri address)
{
var queueName = address.AbsolutePath.Split('/').Last();
var exchange = _messageFabric.GetExchange(queueName);
return exchange;
}
public IInMemoryPublishTopologyBuilder CreatePublishTopologyBuilder(
PublishEndpointTopologyBuilder.Options options = PublishEndpointTopologyBuilder.Options.MaintainHierarchy)
{
return new PublishEndpointTopologyBuilder(_messageFabric, options);
}
public IInMemoryConsumeTopologyBuilder CreateConsumeTopologyBuilder()
{
return new InMemoryConsumeTopologyBuilder(_messageFabric);
}
class Handle :
BaseHostHandle
{
readonly InMemoryHost _host;
public Handle(InMemoryHost host, HostReceiveEndpointHandle[] handles)
: base(host, handles)
{
_host = host;
}
public override async Task Stop(CancellationToken cancellationToken)
{
await base.Stop(cancellationToken).ConfigureAwait(false);
}
}
}
}
| |
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 WebDemo.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;
}
}
}
| |
#region Using directives
using SimpleFramework.Xml.Core;
using SimpleFramework.Xml;
using System;
#endregion
namespace SimpleFramework.Xml.Core {
public class MethodTest : ValidationTestCase {
private const String SOURCE_EXPLICIT =
"<?xml version=\"1.0\"?>\n"+
"<test>\n"+
" <bool>true</bool>\r\n"+
" <byte>16</byte> \n\r"+
" <short>120</short> \n\r"+
" <int>1234</int>\n"+
" <float>1234.56</float> \n\r"+
" <long>1234567</long>\n"+
" <double>1234567.89</double> \n\r"+
"</test>";
private const String SOURCE_IMPLICIT =
"<?xml version=\"1.0\"?>\n"+
"<implicitMethodNameExample>\n"+
" <boolValue>true</boolValue>\r\n"+
" <byteValue>16</byteValue> \n\r"+
" <shortValue>120</shortValue> \n\r"+
" <intValue>1234</intValue>\n"+
" <floatValue>1234.56</floatValue> \n\r"+
" <longValue>1234567</longValue>\n"+
" <doubleValue>1234567.89</doubleValue> \n\r"+
"</implicitMethodNameExample>";
[Root(Name="test")]
private static class ExplicitMethodNameExample {
protected bool boolValue;
protected byte byteValue;
protected short shortValue;
protected int intValue;
protected float floatValue;
protected long longValue;
protected double doubleValue;
public ExplicitMethodNameExample() {
super();
}
[Element(Name="bool")]
public bool BooleanValue {
get {
return boolValue;
}
set {
this.boolValue = value;
}
}
//public bool GetBooleanValue() {
// return boolValue;
//}
//public void SetBooleanValue(bool boolValue) {
// this.boolValue = boolValue;
//}
public byte ByteValue {
get {
return byteValue;
}
set {
this.byteValue = value;
}
}
//public byte GetByteValue() {
// return byteValue;
//}
//public void SetByteValue(byte byteValue) {
// this.byteValue = byteValue;
//}
public double DoubleValue {
get {
return doubleValue;
}
set {
this.doubleValue = value;
}
}
//public double GetDoubleValue() {
// return doubleValue;
//}
//public void SetDoubleValue(double doubleValue) {
// this.doubleValue = doubleValue;
//}
public float FloatValue {
get {
return floatValue;
}
set {
this.floatValue = value;
}
}
//public float GetFloatValue() {
// return floatValue;
//}
//public void SetFloatValue(float floatValue) {
// this.floatValue = floatValue;
//}
public int IntValue {
get {
return intValue;
}
set {
this.intValue = value;
}
}
//public int GetIntValue() {
// return intValue;
//}
//public void SetIntValue(int intValue) {
// this.intValue = intValue;
//}
public long LongValue {
get {
return longValue;
}
set {
this.longValue = value;
}
}
//public long GetLongValue() {
// return longValue;
//}
//public void SetLongValue(long longValue) {
// this.longValue = longValue;
//}
public short ShortValue {
get {
return shortValue;
}
set {
this.shortValue = value;
}
}
//public short GetShortValue() {
// return shortValue;
//}
//public void SetShortValue(short shortValue) {
// this.shortValue = shortValue;
//}
[Root]
private static class ImplicitMethodNameExample : ExplicitMethodNameExample {
[Element]
public bool BooleanValue {
get {
return boolValue;
}
set {
this.boolValue = value;
}
}
//public bool GetBooleanValue() {
// return boolValue;
//}
//public void SetBooleanValue(bool boolValue) {
// this.boolValue = boolValue;
//}
public byte ByteValue {
get {
return byteValue;
}
set {
this.byteValue = value;
}
}
//public byte GetByteValue() {
// return byteValue;
//}
//public void SetByteValue(byte byteValue) {
// this.byteValue = byteValue;
//}
public double DoubleValue {
get {
return doubleValue;
}
set {
this.doubleValue = value;
}
}
//public double GetDoubleValue() {
// return doubleValue;
//}
//public void SetDoubleValue(double doubleValue) {
// this.doubleValue = doubleValue;
//}
public float FloatValue {
get {
return floatValue;
}
set {
this.floatValue = value;
}
}
//public float GetFloatValue() {
// return floatValue;
//}
//public void SetFloatValue(float floatValue) {
// this.floatValue = floatValue;
//}
public int IntValue {
get {
return intValue;
}
set {
this.intValue = value;
}
}
//public int GetIntValue() {
// return intValue;
//}
//public void SetIntValue(int intValue) {
// this.intValue = intValue;
//}
public long LongValue {
get {
return longValue;
}
set {
this.longValue = value;
}
}
//public long GetLongValue() {
// return longValue;
//}
//public void SetLongValue(long longValue) {
// this.longValue = longValue;
//}
public short ShortValue {
get {
return shortValue;
}
set {
this.shortValue = value;
}
}
//public short GetShortValue() {
// return shortValue;
//}
//public void SetShortValue(short shortValue) {
// this.shortValue = shortValue;
//}
private Persister persister;
public void SetUp() {
persister = new Persister();
}
public void TestExplicitMethodNameExample() {
ExplicitMethodNameExample entry = persister.Read(ExplicitMethodNameExample.class, SOURCE_EXPLICIT);
AssertEquals(entry.boolValue, true);
AssertEquals(entry.byteValue, 16);
AssertEquals(entry.shortValue, 120);
AssertEquals(entry.intValue, 1234);
AssertEquals(entry.floatValue, 1234.56f);
AssertEquals(entry.longValue, 1234567l);
AssertEquals(entry.doubleValue, 1234567.89d);
StringWriter buffer = new StringWriter();
persister.Write(entry, buffer);
Validate(entry, persister);
entry = persister.Read(ExplicitMethodNameExample.class, buffer.toString());
AssertEquals(entry.boolValue, true);
AssertEquals(entry.byteValue, 16);
AssertEquals(entry.shortValue, 120);
AssertEquals(entry.intValue, 1234);
AssertEquals(entry.floatValue, 1234.56f);
AssertEquals(entry.longValue, 1234567l);
AssertEquals(entry.doubleValue, 1234567.89d);
Validate(entry, persister);
}
public void TestImplicitMethodNameExample() {
ImplicitMethodNameExample entry = persister.Read(ImplicitMethodNameExample.class, SOURCE_IMPLICIT);
AssertEquals(entry.boolValue, true);
AssertEquals(entry.byteValue, 16);
AssertEquals(entry.shortValue, 120);
AssertEquals(entry.intValue, 1234);
AssertEquals(entry.floatValue, 1234.56f);
AssertEquals(entry.longValue, 1234567l);
AssertEquals(entry.doubleValue, 1234567.89d);
StringWriter buffer = new StringWriter();
persister.Write(entry, buffer);
Validate(entry, persister);
entry = persister.Read(ImplicitMethodNameExample.class, buffer.toString());
AssertEquals(entry.boolValue, true);
AssertEquals(entry.byteValue, 16);
AssertEquals(entry.shortValue, 120);
AssertEquals(entry.intValue, 1234);
AssertEquals(entry.floatValue, 1234.56f);
AssertEquals(entry.longValue, 1234567l);
AssertEquals(entry.doubleValue, 1234567.89d);
Validate(entry, persister);
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: $
* $Date: $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2005 - Gilles Bayon
*
*
* 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
#region Using
using System.Data;
using System.Collections;
using System.Text;
using IBatisNet.Common.Logging;
using IBatisNet.Common;
using IBatisNet.Common.Utilities.Objects;
using IBatisNet.DataMapper.Configuration.Statements;
using IBatisNet.DataMapper.Configuration.ParameterMapping;
using IBatisNet.DataMapper.Exceptions;
using IBatisNet.DataMapper.Scope;
#endregion
namespace IBatisNet.DataMapper.Commands
{
/// <summary>
/// Summary description for DefaultPreparedCommand.
/// </summary>
internal class DefaultPreparedCommand : IPreparedCommand
{
#region Fields
private static readonly ILog _logger = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType );
#endregion
#region IPreparedCommand Members
/// <summary>
/// Create an IDbCommand for the IDalSession and the current SQL Statement
/// and fill IDbCommand IDataParameter's with the parameterObject.
/// </summary>
/// <param name="request"></param>
/// <param name="session">The IDalSession</param>
/// <param name="statement">The IStatement</param>
/// <param name="parameterObject">
/// The parameter object that will fill the sql parameter
/// </param>
/// <returns>An IDbCommand with all the IDataParameter filled.</returns>
public IDbCommand Create(RequestScope request, IDalSession session, IStatement statement, object parameterObject )
{
// the IDbConnection & the IDbTransaction are assign in the CreateCommand
IDbCommand command = session.CreateCommand(statement.CommandType);
command.CommandText = request.PreparedStatement.PreparedSql;
if (_logger.IsDebugEnabled)
{
_logger.Debug("Statement Id: [" + statement.Id + "] PreparedStatement : [" + command.CommandText + "]");
}
ApplyParameterMap( session, command, request, statement, parameterObject );
return command;
}
/// <summary>
///
/// </summary>
/// <param name="session"></param>
/// <param name="command"></param>
/// <param name="request"></param>
/// <param name="statement"></param>
/// <param name="parameterObject"></param>
protected virtual void ApplyParameterMap
( IDalSession session, IDbCommand command,
RequestScope request, IStatement statement, object parameterObject )
{
ArrayList properties = request.PreparedStatement.DbParametersName;
ArrayList parameters = request.PreparedStatement.DbParameters;
StringBuilder paramLogList = new StringBuilder(); // Log info
StringBuilder typeLogList = new StringBuilder(); // Log info
for ( int i = 0; i < properties.Count; ++i )
{
IDataParameter sqlParameter = (IDataParameter)parameters[i];
IDataParameter parameterCopy = command.CreateParameter();
ParameterProperty property = request.ParameterMap.GetProperty(i);
#region Logging
if (_logger.IsDebugEnabled)
{
paramLogList.Append(sqlParameter.ParameterName);
paramLogList.Append("=[");
typeLogList.Append(sqlParameter.ParameterName);
typeLogList.Append("=[");
}
#endregion
if (command.CommandType == CommandType.StoredProcedure)
{
#region store procedure command
// A store procedure must always use a ParameterMap
// to indicate the mapping order of the properties to the columns
if (request.ParameterMap == null) // Inline Parameters
{
throw new DataMapperException("A procedure statement tag must alway have a parameterMap attribute, which is not the case for the procedure '"+statement.Id+"'.");
}
else // Parameters via ParameterMap
{
if (property.DirectionAttribute.Length == 0)
{
property.Direction = sqlParameter.Direction;
}
// DbDataParameter dataParameter = (IDbDataParameter)parameters[i];
// property.Precision = dataParameter.Precision;
// property.Scale = dataParameter.Scale;
// property.Size = dataParameter.Size;
sqlParameter.Direction = property.Direction;
}
#endregion
}
#region Logging
if (_logger.IsDebugEnabled)
{
paramLogList.Append( property.PropertyName );
paramLogList.Append( "," );
}
#endregion
request.ParameterMap.SetParameter(property, parameterCopy, parameterObject );
parameterCopy.Direction = sqlParameter.Direction;
// With a ParameterMap, we could specify the ParameterDbTypeProperty
if (request.ParameterMap != null)
{
if (request.ParameterMap.GetProperty(i).DbType != null &&
request.ParameterMap.GetProperty(i).DbType.Length >0)
{
string dbTypePropertyName = session.DataSource.Provider.ParameterDbTypeProperty;
ObjectProbe.SetPropertyValue(parameterCopy, dbTypePropertyName, ObjectProbe.GetPropertyValue(sqlParameter, dbTypePropertyName));
}
else
{
//parameterCopy.DbType = sqlParameter.DbType;
}
}
else
{
//parameterCopy.DbType = sqlParameter.DbType;
}
#region Logging
if (_logger.IsDebugEnabled)
{
if (parameterCopy.Value == System.DBNull.Value)
{
paramLogList.Append("null");
paramLogList.Append( "], " );
typeLogList.Append("System.DBNull, null");
typeLogList.Append( "], " );
}
else
{
paramLogList.Append( parameterCopy.Value.ToString() );
paramLogList.Append( "], " );
// sqlParameter.DbType could be null (as with Npgsql)
// if PreparedStatementFactory did not find a dbType for the parameter in:
// line 225: "if (property.DbType.Length >0)"
// Use parameterCopy.DbType
//typeLogList.Append( sqlParameter.DbType.ToString() );
typeLogList.Append( parameterCopy.DbType.ToString() );
typeLogList.Append( ", " );
typeLogList.Append( parameterCopy.Value.GetType().ToString() );
typeLogList.Append( "], " );
}
}
#endregion
// JIRA-49 Fixes (size, precision, and scale)
if (session.DataSource.Provider.SetDbParameterSize)
{
if (((IDbDataParameter)sqlParameter).Size > 0)
{
((IDbDataParameter)parameterCopy).Size = ((IDbDataParameter)sqlParameter).Size;
}
}
if (session.DataSource.Provider.SetDbParameterPrecision)
{
((IDbDataParameter)parameterCopy).Precision = ((IDbDataParameter)sqlParameter).Precision;
}
if (session.DataSource.Provider.SetDbParameterScale)
{
((IDbDataParameter)parameterCopy).Scale = ((IDbDataParameter)sqlParameter).Scale;
}
parameterCopy.ParameterName = sqlParameter.ParameterName;
command.Parameters.Add( parameterCopy );
}
#region Logging
if (_logger.IsDebugEnabled && properties.Count>0)
{
_logger.Debug("Statement Id: [" + statement.Id + "] Parameters: [" + paramLogList.ToString(0, paramLogList.Length - 2) + "]");
_logger.Debug("Statement Id: [" + statement.Id + "] Types: [" + typeLogList.ToString(0, typeLogList.Length - 2) + "]");
}
#endregion
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="MainForm.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TQVaultAE.GUI
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Windows.Forms;
using Tooltip;
using TQVaultAE.GUI.Components;
using TQVaultAE.GUI.Models;
using TQVaultAE.Data;
using TQVaultAE.Logs;
using TQVaultAE.Entities;
using TQVaultAE.Presentation;
using TQVaultAE.Config;
using TQVaultAE.Services;
/// <summary>
/// Main Dialog class
/// </summary>
internal partial class MainForm : VaultForm
{
private readonly log4net.ILog Log = null;
#region Fields
/// <summary>
/// Indicates whether the database resources have completed loading.
/// </summary>
private bool resourcesLoaded;
/// <summary>
/// Indicates whether the entire load process has completed.
/// </summary>
private bool loadingComplete;
/// <summary>
/// Instance of the player panel control
/// </summary>
private PlayerPanel playerPanel;
/// <summary>
/// Holds the last sack that had mouse focus
/// Used for Automoving
/// </summary>
private SackCollection lastSackHighlighted;
/// <summary>
/// Holds the last sack panel that had mouse focus
/// Used for Automoving
/// /// </summary>
private SackPanel lastSackPanelHighlighted;
/// <summary>
/// Info for the current item being dragged by the mouse
/// </summary>
private ItemDragInfo dragInfo;
/// <summary>
/// Holds the coordinates of the last drag item
/// </summary>
private Point lastDragPoint;
/// <summary>
/// User current data context
/// </summary>
private SessionContext userContext = new SessionContext();
/// <summary>
/// Instance of the vault panel control
/// </summary>
private VaultPanel vaultPanel;
/// <summary>
/// Instance of the second vault panel control
/// This gets toggled with the player panel
/// </summary>
private VaultPanel secondaryVaultPanel;
/// <summary>
/// Instance of the stash panel control
/// </summary>
private StashPanel stashPanel;
/// <summary>
/// Holds that last stash that had focus
/// </summary>
private Stash lastStash;
/// <summary>
/// Bag number of the last bag with focus
/// </summary>
private int lastBag;
/// <summary>
/// Instance of the Action Button
/// This is the animated button which pops relics and separates stacks
/// </summary>
private ActionButton actionButton;
/// <summary>
/// Holds the current program version
/// </summary>
private string currentVersion;
/// <summary>
/// Instance of the popup tool tip.
/// </summary>
private TTLib tooltip;
/// <summary>
/// Text in the tool tip
/// </summary>
private string tooltipText;
/// <summary>
/// Signals that the configuration UI was loaded and the user changed something in there.
/// </summary>
private bool configChanged;
/// <summary>
/// Flag which holds whether we are showing the secondary vault panel or the player panel.
/// </summary>
private bool showSecondaryVault;
/// <summary>
/// Form for the splash screen.
/// </summary>
private SplashScreenForm splashScreen;
/// <summary>
/// Holds the opacity interval for fading the form.
/// </summary>
private double fadeInterval;
#endregion
/// <summary>
/// Initializes a new instance of the MainForm class.
/// </summary>
[PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)]
public MainForm()
{
Log = Logger.Get(this);
Log.Info("TQVaultAE Initialization !");
this.Enabled = false;
this.ShowInTaskbar = false;
this.Opacity = 0;
this.Hide();
this.InitializeComponent();
this.SetupFormSize();
#region Apply custom font & scaling
this.exitButton.Font = FontHelper.GetFontAlbertusMTLight(12F, UIService.UI.Scale);
ScaleControl(this.exitButton);
this.characterComboBox.Font = FontHelper.GetFontAlbertusMTLight(13F, UIService.UI.Scale);
ScaleControl(this.characterComboBox);
ScaleControl(this.characterLabel);
ScaleControl(this.itemTextPanel);
ScaleControl(this.itemText);
this.vaultListComboBox.Font = FontHelper.GetFontAlbertusMTLight(13F, UIService.UI.Scale);
ScaleControl(this.vaultListComboBox);
this.vaultLabel.Font = FontHelper.GetFontAlbertusMTLight(11F, UIService.UI.Scale);
ScaleControl(this.vaultLabel);
this.configureButton.Font = FontHelper.GetFontAlbertusMTLight(12F, UIService.UI.Scale);
ScaleControl(this.configureButton);
this.customMapText.Font = FontHelper.GetFontAlbertusMT(11.25F, UIService.UI.Scale);
ScaleControl(this.customMapText);
this.panelSelectButton.Font = FontHelper.GetFontAlbertusMTLight(12F, UIService.UI.Scale);
ScaleControl(this.panelSelectButton);
this.secondaryVaultListComboBox.Font = FontHelper.GetFontAlbertusMTLight(11F, UIService.UI.Scale);
ScaleControl(this.secondaryVaultListComboBox);
this.aboutButton.Font = FontHelper.GetFontMicrosoftSansSerif(8.25F, UIService.UI.Scale);
ScaleControl(this.aboutButton);
this.titleLabel.Font = FontHelper.GetFontAlbertusMTLight(24F, UIService.UI.Scale);
ScaleControl(this.titleLabel);
this.searchButton.Font = FontHelper.GetFontAlbertusMTLight(12F, UIService.UI.Scale);
ScaleControl(this.searchButton);
#endregion
try
{
this.tooltip = new TTLib();
}
catch (Exception ex)
{
Log.Error("Get TTLib fail !", ex);
MessageBox.Show(Log.FormatException(ex));
// Handle failure to create to tooltip here
// VXPlib not registered
checkVXPlibrary();
this.tooltip = new TTLib();
}
// Changed to a global for versions in tqdebug
AssemblyName aname = Assembly.GetExecutingAssembly().GetName();
this.currentVersion = aname.Version.ToString();
this.Text = string.Format(CultureInfo.CurrentCulture, "{0} {1}", aname.Name, this.currentVersion);
if (TQDebug.DebugEnabled)
{
// Write this version into the debug file.
Log.DebugFormat(CultureInfo.InvariantCulture, "Current TQVault Version: {0}", this.currentVersion);
Log.Debug(string.Empty);
Log.Debug("Debug Levels");
Log.DebugFormat(CultureInfo.InvariantCulture, "ARCFileDebugLevel: {0}", TQDebug.ArcFileDebugLevel);
Log.DebugFormat(CultureInfo.InvariantCulture, "DatabaseDebugLevel: {0}", TQDebug.DatabaseDebugLevel);
Log.DebugFormat(CultureInfo.InvariantCulture, "ItemAttributesDebugLevel: {0}", TQDebug.ItemAttributesDebugLevel);
Log.DebugFormat(CultureInfo.InvariantCulture, "ItemDebugLevel: {0}", TQDebug.ItemDebugLevel);
Log.Debug(string.Empty);
}
// Setup localized strings.
this.characterLabel.Text = Resources.MainFormLabel1;
this.vaultLabel.Text = Resources.MainFormLabel2;
this.configureButton.Text = Resources.MainFormBtnConfigure;
this.exitButton.Text = Resources.GlobalExit;
this.panelSelectButton.Text = Resources.MainFormBtnPanelSelect;
this.Icon = Resources.TQVIcon;
this.searchButton.Text = Resources.MainFormSearchButtonText;
// Set up Item strings
Item.ItemWith = Resources.ItemWith;
Item.ItemRelicBonus = Resources.ItemRelicBonus;
Item.ItemRelicCompleted = Resources.ItemRelicCompleted;
Item.ItemQuest = Resources.ItemQuest;
Item.ItemSeed = Resources.ItemSeed;
Item.ItemIT = Resources.ItemIT;
Item.ItemRagnarok = Resources.ItemRagnarok;
Item.ItemAtlantis = Resources.ItemAtlantis;
Item.ShowSkillLevel = Config.Settings.Default.ShowSkillLevel;
if (Config.Settings.Default.NoToolTipDelay)
{
this.tooltip.SetNoDelay();
}
this.lastDragPoint.X = -1;
this.dragInfo = new ItemDragInfo();
this.CreatePanels();
// Process the mouse scroll wheel to cycle through the vaults.
this.MouseWheel += new MouseEventHandler(this.MainFormMouseWheel);
this.splashScreen = new SplashScreenForm();
this.splashScreen.MaximumValue = 1;
this.splashScreen.FormClosed += new FormClosedEventHandler(this.SplashScreenClosed);
if (Config.Settings.Default.LoadAllFiles)
{
this.splashScreen.MaximumValue += LoadAllFilesTotal();
}
this.splashScreen.Show();
this.splashScreen.Update();
}
#region VXPlibrary
/// <summary>
/// Handles the registering and placement of the VXPlibrary.dll for tooltip creation.
/// </summary>
private void checkVXPlibrary()
{
if (File.Exists(Directory.GetCurrentDirectory() + "\\VXPlibrary.dll"))
{
// VXPlibrary.dll exists, but if it is not registered --> register it
registerVXPlibrary();
}
else
{
var ex = new FileNotFoundException("VXPlibrary.dll missing from TQVault directory!");
Log.ErrorException(ex);
throw ex;
}
}
/// <summary>
/// Registers the VXPlibrary.dll
/// </summary>
private void registerVXPlibrary()
{
Process proc = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.UseShellExecute = true;
info.WorkingDirectory = "\"" + Directory.GetCurrentDirectory() + "\"";
info.FileName = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\Regsvr32.exe";
info.Verb = "runas";
info.Arguments = "/c \"" + Directory.GetCurrentDirectory() + "\\VXPlib.dll\"";
try
{
proc.StartInfo = info;
proc.Start();
proc.WaitForExit();
}
catch (Exception ex)
{
Log.ErrorException(ex);
MessageBox.Show(Log.FormatException(ex));
}
}
#endregion
#region Mainform Events
/// <summary>
/// Handler for the ResizeEnd event. Used to scale the internal controls after the window has been resized.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
protected override void ResizeEndCallback(object sender, EventArgs e)
{
// That override Look dumb but needed by Visual Studio WInform Designer
base.ResizeEndCallback(sender, e);
}
/// <summary>
/// Handler for the Resize event. Used for handling the maximize and minimize functions.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
protected override void ResizeBeginCallback(object sender, EventArgs e)
{
// That override Look dumb but needed by Visual Studio WInform Designer
base.ResizeBeginCallback(sender, e);
}
/// <summary>
/// Handler for closing the main form
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">CancelEventArgs data</param>
private void MainFormClosing(object sender, CancelEventArgs e)
{
if (this.DoCloseStuff())
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
/// <summary>
/// Shows things that you may want to know before a close.
/// Like holding an item
/// </summary>
/// <returns>TRUE if none of the conditions exist or the user selected to ignore the message</returns>
private bool DoCloseStuff()
{
bool ok = false;
try
{
// Make sure we are not dragging anything
if (this.dragInfo.IsActive)
{
MessageBox.Show(Resources.MainFormHoldingItem, Resources.MainFormHoldingItem2, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, RightToLeftOptions);
return false;
}
this.SaveAllModifiedFiles();
// Added by VillageIdiot
this.SaveConfiguration();
ok = true;
}
catch (IOException exception)
{
Log.Error("Save files failed !", exception);
MessageBox.Show(Log.FormatException(exception), Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, RightToLeftOptions);
}
return ok;
}
/// <summary>
/// Handler for loading the main form
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void MainFormLoad(object sender, EventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
}
/// <summary>
/// Handler for key presses on the main form
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">KeyPressEventArgs data</param>
private void MainFormKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)27)
{
e.Handled = true;
}
}
/// <summary>
/// Handler for showing the main form.
/// Used to switch focus to the search text box.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void MainFormShown(object sender, EventArgs e)
{
this.vaultPanel.SackPanel.Focus();
}
/// <summary>
/// Handler for moving the mouse wheel.
/// Used to scroll through the vault list.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">MouseEventArgs data</param>
private void MainFormMouseWheel(object sender, MouseEventArgs e)
{
// Force a single line regardless of the delta value.
int numberOfTextLinesToMove = ((e.Delta > 0) ? 1 : 0) - ((e.Delta < 0) ? 1 : 0);
if (numberOfTextLinesToMove != 0)
{
int vaultSelection = this.vaultListComboBox.SelectedIndex;
vaultSelection -= numberOfTextLinesToMove;
if (vaultSelection < 1)
{
vaultSelection = 1;
}
if (vaultSelection >= this.vaultListComboBox.Items.Count)
{
vaultSelection = this.vaultListComboBox.Items.Count - 1;
}
this.vaultListComboBox.SelectedIndex = vaultSelection;
}
}
/// <summary>
/// Key Handler for the main form. Most keystrokes should be handled by the individual panels or the search text box.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">KeyEventArgs data</param>
private void MainFormKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.Control | Keys.F))
{
this.ActivateSearchCallback(this, new SackPanelEventArgs(null, null));
}
if (e.KeyData == (Keys.Control | Keys.Add) || e.KeyData == (Keys.Control | Keys.Oemplus))
{
this.ResizeFormCallback(this, new ResizeEventArgs(0.1F));
}
if (e.KeyData == (Keys.Control | Keys.Subtract) || e.KeyData == (Keys.Control | Keys.OemMinus))
{
this.ResizeFormCallback(this, new ResizeEventArgs(-0.1F));
}
if (e.KeyData == (Keys.Control | Keys.Home))
{
this.ResizeFormCallback(this, new ResizeEventArgs(1.0F));
}
}
/// <summary>
/// Handles Timer ticks for fading in the main form.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void FadeInTimerTick(object sender, EventArgs e)
{
if (this.Opacity < 1)
{
this.Opacity = Math.Min(1.0F, this.Opacity + this.fadeInterval);
}
else
{
this.fadeInTimer.Stop();
}
}
/// <summary>
/// Handler for the exit button.
/// Closes the main form
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void ExitButtonClick(object sender, EventArgs e)
{
this.Close();
}
#endregion
#region About
/// <summary>
/// Handler for clicking the about button.
/// Shows the about dialog box.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void AboutButtonClick(object sender, EventArgs e)
{
AboutBox dlg = new AboutBox();
dlg.Scale(new SizeF(UIService.UI.Scale, UIService.UI.Scale));
dlg.ShowDialog();
}
#endregion
#region Scaling
/// <summary>
/// Scales the main form according to the scale factor.
/// </summary>
/// <param name="scaleFactor">Float which signifies the scale factor of the form. This is an absolute from the original size unless useRelativeScaling is set to true.</param>
/// <param name="useRelativeScaling">Indicates whether the scale factor is relative. Used to support a resize operation.</param>
protected override void ScaleForm(float scaleFactor, bool useRelativeScaling)
{
base.ScaleForm(scaleFactor, useRelativeScaling);
this.itemText.Text = string.Empty;
// hide the tooltip
this.tooltipText = null;
this.tooltip.ChangeText(this.tooltipText);
this.Invalidate();
}
/// <summary>
/// Sets the size of the main form along with scaling the internal controls for startup.
/// </summary>
private void SetupFormSize()
{
this.DrawCustomBorder = true;
this.ResizeCustomAllowed = true;
this.fadeInterval = Config.Settings.Default.FadeInInterval;
Rectangle workingArea = Screen.FromControl(this).WorkingArea;
int formWidth = 1350;
int formHeight = 910;
float initialScale = 1.0F;
Config.Settings.Default.Scale = initialScale;
// Ninakoru: trick to force close/min/max buttons to reposition...
this.ScaleOnResize = false;
if (workingArea.Width < formWidth || workingArea.Height < formHeight)
{
initialScale = Math.Min(Convert.ToSingle(workingArea.Width) / Convert.ToSingle(formWidth), Convert.ToSingle(workingArea.Height) / Convert.ToSingle(formHeight));
if (Config.Settings.Default.Scale > initialScale)
{
Config.Settings.Default.Scale = initialScale;
}
this.ClientSize = new System.Drawing.Size((int)System.Math.Round(formWidth * Config.Settings.Default.Scale), (int)System.Math.Round(formHeight * Config.Settings.Default.Scale));
}
else
{
this.ClientSize = new System.Drawing.Size(formWidth, formHeight);
}
this.ScaleOnResize = true;
UIService.UI.Scale = Config.Settings.Default.Scale;
Config.Settings.Default.Save();
// Save the height / width ratio for resizing.
this.FormDesignRatio = (float)this.Height / (float)this.Width;
this.FormMaximumSize = new Size(this.Width * 2, this.Height * 2);
this.FormMinimumSize = new Size(
Convert.ToInt32((float)this.Width * 0.4F),
Convert.ToInt32((float)this.Height * 0.4F));
this.OriginalFormSize = this.Size;
this.OriginalFormScale = Config.Settings.Default.Scale;
if (CurrentAutoScaleDimensions.Width != UIService.DESIGNDPI)
{
// We do not need to scale the main form controls since autoscaling will handle it.
// Scale internally to 96 dpi for the drawing functions.
UIService.UI.Scale = this.CurrentAutoScaleDimensions.Width / UIService.DESIGNDPI;
this.OriginalFormScale = UIService.UI.Scale;
}
this.LastFormSize = this.Size;
// Set the maximized size but keep the aspect ratio.
if (Convert.ToInt32((float)workingArea.Width * this.FormDesignRatio) < workingArea.Height)
{
this.MaximizedBounds = new Rectangle(
0,
(workingArea.Height - Convert.ToInt32((float)workingArea.Width * this.FormDesignRatio)) / 2,
workingArea.Width,
Convert.ToInt32((float)workingArea.Width * this.FormDesignRatio));
}
else
{
this.MaximizedBounds = new Rectangle(
(workingArea.Width - Convert.ToInt32((float)workingArea.Height / this.FormDesignRatio)) / 2,
0,
Convert.ToInt32((float)workingArea.Height / this.FormDesignRatio),
workingArea.Height);
}
this.Location = new Point(workingArea.Left + Convert.ToInt16((workingArea.Width - this.ClientSize.Width) / 2), workingArea.Top + Convert.ToInt16((workingArea.Height - this.ClientSize.Height) / 2));
}
#endregion
#region Files
/// <summary>
/// Counts the number of files which LoadAllFiles will load. Used to set the max value of the progress bar.
/// </summary>
/// <returns>Total number of files that LoadAllFiles() will load.</returns>
private static int LoadAllFilesTotal()
{
string[] list;
list = TQData.GetCharacterList();
int numIT = list?.Length ?? 0;
list = TQData.GetVaultList();
int numVaults = list?.Length ?? 0;
return Math.Max(0, numIT + numIT + numVaults - 1);
}
/// <summary>
/// Loads all of the players, stashes, and vaults.
/// Shows a progress dialog.
/// Used for the searching function.
/// </summary>
private void LoadAllFiles()
{
// Check to see if we failed the last time we tried loading all of the files.
// If we did fail then turn it off and skip it.
if (!Config.Settings.Default.LoadAllFilesCompleted)
{
if (MessageBox.Show(
Resources.MainFormDisableLoadAllFiles,
Resources.MainFormDisableLoadAllFilesCaption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1,
RightToLeftOptions) == DialogResult.Yes)
{
Config.Settings.Default.LoadAllFilesCompleted = true;
Config.Settings.Default.LoadAllFiles = false;
Config.Settings.Default.Save();
return;
}
}
string[] vaults = TQData.GetVaultList();
string[] charactersIT = TQData.GetCharacterList();
int numIT = charactersIT?.Length ?? 0;
int numVaults = vaults?.Length ?? 0;
// Since this takes a while, show a progress dialog box.
int total = numIT + numIT + numVaults - 1;
if (total > 0)
{
// We were successful last time so we reset the flag for this attempt.
Config.Settings.Default.LoadAllFilesCompleted = false;
Config.Settings.Default.Save();
}
else
return;
// Load all of the Immortal Throne player files and stashes.
for (int i = 0; i < numIT; ++i)
{
// Get the player & player's stash
try
{
var result = this.playerService.LoadPlayer(charactersIT[i], true);
if (result.PlayerArgumentException != null)
{
string msg = string.Format(CultureInfo.CurrentUICulture, "{0}\n{1}\n{2}", Resources.MainFormPlayerReadError, result.PlayerFile, result.PlayerArgumentException.Message);
MessageBox.Show(msg, Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, RightToLeftOptions);
}
if (result.StashArgumentException != null)
{
string msg = string.Format(CultureInfo.CurrentUICulture, "{0}\n{1}\n{2}", Resources.MainFormPlayerReadError, result.StashFile, result.StashArgumentException.Message);
MessageBox.Show(msg, Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, RightToLeftOptions);
}
}
catch (IOException exception)
{
Log.ErrorException(exception);
MessageBox.Show(Log.FormatException(exception), Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, RightToLeftOptions);
}
this.backgroundWorker1.ReportProgress(1);
}
// Load all of the vaults.
for (int i = 0; i < numVaults; ++i)
{
var result = this.vaultService.LoadVault(vaults[i]);
if (result.ArgumentException != null)
{
string msg = string.Format(CultureInfo.CurrentUICulture, "{0}\n{1}\n{2}", Resources.MainFormPlayerReadError, result.Filename, result.ArgumentException.Message);
MessageBox.Show(msg, Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, RightToLeftOptions);
}
this.backgroundWorker1.ReportProgress(1);
}
// We made it so set the flag to indicate we were successful.
Config.Settings.Default.LoadAllFilesCompleted = true;
Config.Settings.Default.Save();
}
/// <summary>
/// Attempts to save all modified files.
/// </summary>
/// <returns>true if players have been modified</returns>
private bool SaveAllModifiedFiles()
{
bool playersModified = this.SaveAllModifiedPlayers();
this.SaveAllModifiedVaults();
this.SaveAllModifiedStashes();
return playersModified;
}
#endregion
#region SplashScreen & Tooltip
/// <summary>
/// Handler for closing the splash screen
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">FormClosedEventArgs data</param>
private void SplashScreenClosed(object sender, FormClosedEventArgs e)
{
if (this.resourcesLoaded)
{
if (!this.loadingComplete)
{
this.backgroundWorker1.CancelAsync();
}
this.ShowMainForm();
// the tooltip must be initialized after the main form is shown and active.
this.tooltip.Initialize(this);
this.tooltip.ActivateCallback = new TTLibToolTipActivate(this.ToolTipCallback);
}
else
{
Application.Exit();
}
}
/// <summary>
/// Starts the fade in of the main form.
/// </summary>
private void ShowMainForm()
{
this.fadeInTimer.Start();
this.ShowInTaskbar = true;
this.Enabled = true;
this.Show();
this.Activate();
}
/// <summary>
/// Tooltip callback
/// </summary>
/// <param name="windowHandle">handle of the main window form</param>
/// <returns>tooltip string</returns>
private string ToolTipCallback(int windowHandle)
{
string answer;
answer = this.vaultPanel.ToolTipCallback(windowHandle);
if (answer != null)
{
return answer;
}
answer = this.playerPanel.ToolTipCallback(windowHandle);
if (answer != null)
{
return answer;
}
answer = this.stashPanel.ToolTipCallback(windowHandle);
if (answer != null)
{
return answer;
}
answer = this.secondaryVaultPanel.ToolTipCallback(windowHandle);
if (answer != null)
{
return answer;
}
// Changed by VillageIdiot
// If we are dragging something around, clear the tooltip and text box.
if (this.dragInfo.IsActive)
{
this.itemText.Text = string.Empty;
this.tooltipText = null;
this.tooltip.ChangeText(this.tooltipText);
return null;
}
// If nothing else returned a tooltip then display the current item text
return this.tooltipText;
}
#endregion
#region Game Resources
/// <summary>
/// Loads the resources.
/// </summary>
/// <param name="worker">Background worker</param>
/// <param name="e">DoWorkEventArgs data</param>
/// <returns>true when resource loading has completed successfully</returns>
private bool LoadResources(BackgroundWorker worker, DoWorkEventArgs e)
{
// Abort the operation if the user has canceled.
// Note that a call to CancelAsync may have set
// CancellationPending to true just after the
// last invocation of this method exits, so this
// code will not have the opportunity to set the
// DoWorkEventArgs.Cancel flag to true. This means
// that RunWorkerCompletedEventArgs.Cancelled will
// not be set to true in your RunWorkerCompleted
// event handler. This is a race condition.
if (worker.CancellationPending)
{
e.Cancel = true;
return this.resourcesLoaded;
}
else
{
//read map name from ini file, main section
if (!String.IsNullOrEmpty(Config.Settings.Default.Mod))
{
TQData.MapName = Config.Settings.Default.Mod;
}
if (!Config.Settings.Default.AllowCheats)
{
Config.Settings.Default.AllowItemCopy = false;
Config.Settings.Default.AllowItemEdit = false;
Config.Settings.Default.AllowCharacterEdit = false;
}
CommandLineArgs args = new CommandLineArgs();
// Check to see if we loaded something from the command line.
if (args.HasMapName)
{
TQData.MapName = args.MapName;
}
this.resourcesLoaded = true;
this.backgroundWorker1.ReportProgress(1);
if (Config.Settings.Default.LoadAllFiles)
{
this.LoadAllFiles();
}
// Notify the form that the resources are loaded.
return true;
}
}
/// <summary>
/// Background worker call to load the resources.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">DoWorkEventArgs data</param>
private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker worker = sender as BackgroundWorker;
// Assign the result of the resource loader
// to the Result property of the DoWorkEventArgs
// object. This is will be available to the
// RunWorkerCompleted eventhandler.
e.Result = this.LoadResources(worker, e);
}
/// <summary>
/// Background worker has finished
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">RunWorkerCompletedEventArgs data</param>
private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// First, handle the case where an exception was thrown.
if (e.Error != null)
{
if (MessageBox.Show(
string.Concat(e.Error.Message, Resources.Form1BadLanguage),
Resources.Form1ErrorLoadingResources,
MessageBoxButtons.YesNo,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1,
RightToLeftOptions) == DialogResult.Yes)
{
Application.Restart();
}
else
{
Application.Exit();
}
}
else if (e.Cancelled && !this.resourcesLoaded)
{
Application.Exit();
}
else if (e.Result.Equals(true))
{
this.loadingComplete = true;
this.Enabled = true;
this.LoadTransferStash();
this.LoadRelicVaultStash();
// Load last character here if selected
if (Config.Settings.Default.LoadLastCharacter)
{
int ind = this.characterComboBox.FindStringExact(Config.Settings.Default.LastCharacterName);
if (ind != -1)
{
this.characterComboBox.SelectedIndex = ind;
}
}
string currentVault = VaultService.MAINVAULT;
// See if we should load the last loaded vault
if (Config.Settings.Default.LoadLastVault)
{
currentVault = Config.Settings.Default.LastVaultName;
// Make sure there is something in the config file to load else load the Main Vault
// We do not want to create new here.
if (string.IsNullOrEmpty(currentVault) || !File.Exists(TQData.GetVaultFile(currentVault)))
{
currentVault = VaultService.MAINVAULT;
}
}
this.vaultListComboBox.SelectedItem = currentVault;
// Finally load Vault
this.LoadVault(currentVault, false);
this.splashScreen.UpdateText();
this.splashScreen.ShowMainForm = true;
CommandLineArgs args = new CommandLineArgs();
// Allows skipping of title screen with setting
if (args.IsAutomatic || Config.Settings.Default.SkipTitle == true)
{
string player = args.Player;
int index = this.characterComboBox.FindStringExact(player);
if (index != -1)
{
this.characterComboBox.SelectedIndex = index;
}
this.splashScreen.CloseForm();
}
}
else
{
// If for some reason the loading failed, but there was no error raised.
MessageBox.Show(
Resources.Form1ErrorLoadingResources,
Resources.Form1ErrorLoadingResources,
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1,
RightToLeftOptions);
Application.Exit();
}
}
/// <summary>
/// Handler for updating the splash screen progress bar.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">ProgressChangedEventArgs data</param>
private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.splashScreen.IncrementValue();
}
#endregion
#region Settings Dialog
/// <summary>
/// Updates configuration settings
/// </summary>
private void SaveConfiguration()
{
// Update last loaded vault
if (Config.Settings.Default.LoadLastVault)
{
// Changed by VillageIdiot
// Now check to see if the value is changed since the Main Vault would never auto load
if (this.vaultListComboBox.SelectedItem != null && this.vaultListComboBox.SelectedItem.ToString().ToUpperInvariant() != Config.Settings.Default.LastVaultName.ToUpperInvariant())
{
Config.Settings.Default.LastVaultName = this.vaultListComboBox.SelectedItem.ToString();
this.configChanged = true;
}
}
// Update last loaded character
if (Config.Settings.Default.LoadLastCharacter)
{
// Changed by VillageIdiot
// Now check the last value to see if it has changed since the logic would
// always load a character even if no character was selected on the last run
if (this.characterComboBox.SelectedItem.ToString().ToUpperInvariant() != Config.Settings.Default.LastCharacterName.ToUpperInvariant())
{
// Clear the value if no character is selected
string name = this.characterComboBox.SelectedItem.ToString();
if (name == Resources.MainFormSelectCharacter)
{
name = string.Empty;
}
Config.Settings.Default.LastCharacterName = name;
this.configChanged = true;
}
}
// Update custom map settings
if (Config.Settings.Default.ModEnabled)
{
this.configChanged = true;
}
// Clear out the key if we are autodetecting.
if (Config.Settings.Default.AutoDetectLanguage)
{
Config.Settings.Default.TQLanguage = string.Empty;
}
// Clear out the settings if auto detecting.
if (Config.Settings.Default.AutoDetectGamePath)
{
Config.Settings.Default.TQITPath = string.Empty;
Config.Settings.Default.TQPath = string.Empty;
}
if (UIService.UI.Scale != 1.0F)
{
Config.Settings.Default.Scale = UIService.UI.Scale;
this.configChanged = true;
}
if (this.configChanged)
{
Config.Settings.Default.Save();
}
}
/// <summary>
/// Handler for clicking the configure button.
/// Shows the Settings Dialog.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void ConfigureButtonClick(object sender, EventArgs e)
{
SettingsDialog settingsDialog = new SettingsDialog();
DialogResult result = DialogResult.Cancel;
settingsDialog.Scale(new SizeF(UIService.UI.Scale, UIService.UI.Scale));
string title = string.Empty;
string message = string.Empty;
if (settingsDialog.ShowDialog() == DialogResult.OK && settingsDialog.ConfigurationChanged)
{
if (settingsDialog.PlayerFilterChanged)
{
this.characterComboBox.SelectedItem = Resources.MainFormSelectCharacter;
if (this.playerPanel.Player != null)
{
this.playerPanel.Player = null;
}
this.GetPlayerList();
}
if (settingsDialog.VaultPathChanged)
{
TQData.TQVaultSaveFolder = settingsDialog.VaultPath;
this.vaultService.UpdateVaultPath(settingsDialog.VaultPath);
this.GetVaultList(true);
}
if (settingsDialog.LanguageChanged || settingsDialog.GamePathChanged || settingsDialog.CustomMapsChanged || settingsDialog.UISettingChanged)
{
if ((settingsDialog.GamePathChanged && settingsDialog.LanguageChanged) || settingsDialog.UISettingChanged)
{
title = Resources.MainFormSettingsChanged;
message = Resources.MainFormSettingsChangedMsg;
}
else if (settingsDialog.GamePathChanged)
{
title = Resources.MainFormPathsChanged;
message = Resources.MainFormPathsChangedMsg;
}
else if (settingsDialog.CustomMapsChanged)
{
title = Resources.MainFormMapsChanged;
message = Resources.MainFormMapsChangedMsg;
}
else
{
title = Resources.MainFormLanguageChanged;
message = Resources.MainFormLanguageChangedMsg;
}
result = MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, RightToLeftOptions);
}
this.configChanged = true;
this.SaveConfiguration();
if (result == DialogResult.Yes)
{
if (this.DoCloseStuff())
{
Application.Restart();
}
}
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MessageTransferModule")]
public class MessageTransferModule : ISharedRegionModule, IMessageTransferModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
protected List<Scene> m_Scenes = new List<Scene>();
protected Dictionary<UUID, UUID> m_UserRegionMap = new Dictionary<UUID, UUID>();
public event UndeliveredMessage OnUndeliveredMessage;
private IPresenceService m_PresenceService;
protected IPresenceService PresenceService
{
get
{
if (m_PresenceService == null)
m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
return m_PresenceService;
}
}
public virtual void Initialise(IConfigSource config)
{
IConfig cnf = config.Configs["Messaging"];
if (cnf != null && cnf.GetString(
"MessageTransferModule", "MessageTransferModule") !=
"MessageTransferModule")
{
m_log.Debug("[MESSAGE TRANSFER]: Disabled by configuration");
return;
}
m_Enabled = true;
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_log.Debug("[MESSAGE TRANSFER]: Message transfer module active");
scene.RegisterModuleInterface<IMessageTransferModule>(this);
m_Scenes.Add(scene);
}
}
public virtual void PostInitialise()
{
if (!m_Enabled)
return;
MainServer.Instance.AddXmlRPCHandler(
"grid_instant_message", processXMLRPCGridInstantMessage);
}
public virtual void RegionLoaded(Scene scene)
{
}
public virtual void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_Scenes.Remove(scene);
}
}
public virtual void Close()
{
}
public virtual string Name
{
get { return "MessageTransferModule"; }
}
public virtual Type ReplaceableInterface
{
get { return null; }
}
public virtual void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
{
UUID toAgentID = new UUID(im.toAgentID);
// Try root avatar only first
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[INSTANT MESSAGE]: Looking for root agent {0} in {1}",
// toAgentID.ToString(), scene.RegionInfo.RegionName);
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null && !sp.IsChildAgent)
{
// Local message
// m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to root agent {0} {1}", sp.Name, toAgentID);
sp.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
// try child avatar second
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[INSTANT MESSAGE]: Looking for child of {0} in {1}", toAgentID, scene.RegionInfo.RegionName);
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null)
{
// Local message
// m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to child agent {0} {1}", sp.Name, toAgentID);
sp.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
// m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to {0} via XMLRPC", im.toAgentID);
SendGridInstantMessageViaXMLRPC(im, result);
}
private void HandleUndeliveredMessage(GridInstantMessage im, MessageResultNotification result)
{
UndeliveredMessage handlerUndeliveredMessage = OnUndeliveredMessage;
// If this event has handlers, then an IM from an agent will be
// considered delivered. This will suppress the error message.
//
if (handlerUndeliveredMessage != null)
{
handlerUndeliveredMessage(im);
if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
result(true);
else
result(false);
return;
}
//m_log.DebugFormat("[INSTANT MESSAGE]: Undeliverable");
result(false);
}
/// <summary>
/// Process a XMLRPC Grid Instant Message
/// </summary>
/// <param name="request">XMLRPC parameters
/// </param>
/// <returns>Nothing much</returns>
protected virtual XmlRpcResponse processXMLRPCGridInstantMessage(XmlRpcRequest request, IPEndPoint remoteClient)
{
bool successful = false;
// TODO: For now, as IMs seem to be a bit unreliable on OSGrid, catch all exception that
// happen here and aren't caught and log them.
try
{
// various rational defaults
UUID fromAgentID = UUID.Zero;
UUID toAgentID = UUID.Zero;
UUID imSessionID = UUID.Zero;
uint timestamp = 0;
string fromAgentName = "";
string message = "";
byte dialog = (byte)0;
bool fromGroup = false;
byte offline = (byte)0;
uint ParentEstateID=0;
Vector3 Position = Vector3.Zero;
UUID RegionID = UUID.Zero ;
byte[] binaryBucket = new byte[0];
float pos_x = 0;
float pos_y = 0;
float pos_z = 0;
//m_log.Info("Processing IM");
Hashtable requestData = (Hashtable)request.Params[0];
// Check if it's got all the data
if (requestData.ContainsKey("from_agent_id")
&& requestData.ContainsKey("to_agent_id") && requestData.ContainsKey("im_session_id")
&& requestData.ContainsKey("timestamp") && requestData.ContainsKey("from_agent_name")
&& requestData.ContainsKey("message") && requestData.ContainsKey("dialog")
&& requestData.ContainsKey("from_group")
&& requestData.ContainsKey("offline") && requestData.ContainsKey("parent_estate_id")
&& requestData.ContainsKey("position_x") && requestData.ContainsKey("position_y")
&& requestData.ContainsKey("position_z") && requestData.ContainsKey("region_id")
&& requestData.ContainsKey("binary_bucket"))
{
// Do the easy way of validating the UUIDs
UUID.TryParse((string)requestData["from_agent_id"], out fromAgentID);
UUID.TryParse((string)requestData["to_agent_id"], out toAgentID);
UUID.TryParse((string)requestData["im_session_id"], out imSessionID);
UUID.TryParse((string)requestData["region_id"], out RegionID);
try
{
timestamp = (uint)Convert.ToInt32((string)requestData["timestamp"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
fromAgentName = (string)requestData["from_agent_name"];
message = (string)requestData["message"];
if (message == null)
message = string.Empty;
// Bytes don't transfer well over XMLRPC, so, we Base64 Encode them.
string requestData1 = (string)requestData["dialog"];
if (string.IsNullOrEmpty(requestData1))
{
dialog = 0;
}
else
{
byte[] dialogdata = Convert.FromBase64String(requestData1);
dialog = dialogdata[0];
}
if ((string)requestData["from_group"] == "TRUE")
fromGroup = true;
string requestData2 = (string)requestData["offline"];
if (String.IsNullOrEmpty(requestData2))
{
offline = 0;
}
else
{
byte[] offlinedata = Convert.FromBase64String(requestData2);
offline = offlinedata[0];
}
try
{
ParentEstateID = (uint)Convert.ToInt32((string)requestData["parent_estate_id"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_x = (uint)Convert.ToInt32((string)requestData["position_x"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_y = (uint)Convert.ToInt32((string)requestData["position_y"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_z = (uint)Convert.ToInt32((string)requestData["position_z"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
Position = new Vector3(pos_x, pos_y, pos_z);
string requestData3 = (string)requestData["binary_bucket"];
if (string.IsNullOrEmpty(requestData3))
{
binaryBucket = new byte[0];
}
else
{
binaryBucket = Convert.FromBase64String(requestData3);
}
// Create a New GridInstantMessageObject the the data
GridInstantMessage gim = new GridInstantMessage();
gim.fromAgentID = fromAgentID.Guid;
gim.fromAgentName = fromAgentName;
gim.fromGroup = fromGroup;
gim.imSessionID = imSessionID.Guid;
gim.RegionID = UUID.Zero.Guid; // RegionID.Guid;
gim.timestamp = timestamp;
gim.toAgentID = toAgentID.Guid;
gim.message = message;
gim.dialog = dialog;
gim.offline = offline;
gim.ParentEstateID = ParentEstateID;
gim.Position = Position;
gim.binaryBucket = binaryBucket;
// Trigger the Instant message in the scene.
foreach (Scene scene in m_Scenes)
{
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null && !sp.IsChildAgent)
{
scene.EventManager.TriggerIncomingInstantMessage(gim);
successful = true;
}
}
if (!successful)
{
// If the message can't be delivered to an agent, it
// is likely to be a group IM. On a group IM, the
// imSessionID = toAgentID = group id. Raise the
// unhandled IM event to give the groups module
// a chance to pick it up. We raise that in a random
// scene, since the groups module is shared.
//
m_Scenes[0].EventManager.TriggerUnhandledInstantMessage(gim);
}
}
}
catch (Exception e)
{
m_log.Error("[INSTANT MESSAGE]: Caught unexpected exception:", e);
successful = false;
}
//Send response back to region calling if it was successful
// calling region uses this to know when to look up a user's location again.
XmlRpcResponse resp = new XmlRpcResponse();
Hashtable respdata = new Hashtable();
if (successful)
respdata["success"] = "TRUE";
else
respdata["success"] = "FALSE";
resp.Value = respdata;
return resp;
}
/// <summary>
/// delegate for sending a grid instant message asynchronously
/// </summary>
public delegate void GridInstantMessageDelegate(GridInstantMessage im, MessageResultNotification result, UUID prevRegionID);
protected virtual void GridInstantMessageCompleted(IAsyncResult iar)
{
GridInstantMessageDelegate icon =
(GridInstantMessageDelegate)iar.AsyncState;
icon.EndInvoke(iar);
}
protected virtual void SendGridInstantMessageViaXMLRPC(GridInstantMessage im, MessageResultNotification result)
{
GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsync;
d.BeginInvoke(im, result, UUID.Zero, GridInstantMessageCompleted, d);
}
/// <summary>
/// Recursive SendGridInstantMessage over XMLRPC method.
/// This is called from within a dedicated thread.
/// The first time this is called, prevRegionHandle will be 0 Subsequent times this is called from
/// itself, prevRegionHandle will be the last region handle that we tried to send.
/// If the handles are the same, we look up the user's location using the grid.
/// If the handles are still the same, we end. The send failed.
/// </summary>
/// <param name="prevRegionHandle">
/// Pass in 0 the first time this method is called. It will be called recursively with the last
/// regionhandle tried
/// </param>
protected virtual void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, MessageResultNotification result, UUID prevRegionID)
{
UUID toAgentID = new UUID(im.toAgentID);
PresenceInfo upd = null;
bool lookupAgent = false;
lock (m_UserRegionMap)
{
if (m_UserRegionMap.ContainsKey(toAgentID))
{
upd = new PresenceInfo();
upd.RegionID = m_UserRegionMap[toAgentID];
// We need to compare the current regionhandle with the previous region handle
// or the recursive loop will never end because it will never try to lookup the agent again
if (prevRegionID == upd.RegionID)
{
lookupAgent = true;
}
}
else
{
lookupAgent = true;
}
}
// Are we needing to look-up an agent?
if (lookupAgent)
{
// Non-cached user agent lookup.
PresenceInfo[] presences = PresenceService.GetAgents(new string[] { toAgentID.ToString() });
if (presences != null && presences.Length > 0)
{
foreach (PresenceInfo p in presences)
{
if (p.RegionID != UUID.Zero)
{
upd = p;
break;
}
}
}
if (upd != null)
{
// check if we've tried this before..
// This is one way to end the recursive loop
//
if (upd.RegionID == prevRegionID)
{
// m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
HandleUndeliveredMessage(im, result);
return;
}
}
else
{
// m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
HandleUndeliveredMessage(im, result);
return;
}
}
if (upd != null)
{
GridRegion reginfo = m_Scenes[0].GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID,
upd.RegionID);
if (reginfo != null)
{
Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im);
// Not actually used anymore, left in for compatibility
// Remove at next interface change
//
msgdata["region_handle"] = 0;
bool imresult = doIMSending(reginfo, msgdata);
if (imresult)
{
// IM delivery successful, so store the Agent's location in our local cache.
lock (m_UserRegionMap)
{
if (m_UserRegionMap.ContainsKey(toAgentID))
{
m_UserRegionMap[toAgentID] = upd.RegionID;
}
else
{
m_UserRegionMap.Add(toAgentID, upd.RegionID);
}
}
result(true);
}
else
{
// try again, but lookup user this time.
// Warning, this must call the Async version
// of this method or we'll be making thousands of threads
// The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync
// The version that spawns the thread is SendGridInstantMessageViaXMLRPC
// This is recursive!!!!!
SendGridInstantMessageViaXMLRPCAsync(im, result,
upd.RegionID);
}
}
else
{
m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find region {0}", upd.RegionID);
HandleUndeliveredMessage(im, result);
}
}
else
{
HandleUndeliveredMessage(im, result);
}
}
/// <summary>
/// This actually does the XMLRPC Request
/// </summary>
/// <param name="reginfo">RegionInfo we pull the data out of to send the request to</param>
/// <param name="xmlrpcdata">The Instant Message data Hashtable</param>
/// <returns>Bool if the message was successfully delivered at the other side.</returns>
protected virtual bool doIMSending(GridRegion reginfo, Hashtable xmlrpcdata)
{
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
XmlRpcRequest GridReq = new XmlRpcRequest("grid_instant_message", SendParams);
try
{
XmlRpcResponse GridResp = GridReq.Send(reginfo.ServerURI, 3000);
Hashtable responseData = (Hashtable)GridResp.Value;
if (responseData.ContainsKey("success"))
{
if ((string)responseData["success"] == "TRUE")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
catch (WebException e)
{
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: Error sending message to {0} the host didn't respond " + e.ToString(), reginfo.ServerURI.ToString());
}
return false;
}
/// <summary>
/// Get ulong region handle for region by it's Region UUID.
/// We use region handles over grid comms because there's all sorts of free and cool caching.
/// </summary>
/// <param name="regionID">UUID of region to get the region handle for</param>
/// <returns></returns>
// private virtual ulong getLocalRegionHandleFromUUID(UUID regionID)
// {
// ulong returnhandle = 0;
//
// lock (m_Scenes)
// {
// foreach (Scene sn in m_Scenes)
// {
// if (sn.RegionInfo.RegionID == regionID)
// {
// returnhandle = sn.RegionInfo.RegionHandle;
// break;
// }
// }
// }
// return returnhandle;
// }
/// <summary>
/// Takes a GridInstantMessage and converts it into a Hashtable for XMLRPC
/// </summary>
/// <param name="msg">The GridInstantMessage object</param>
/// <returns>Hashtable containing the XMLRPC request</returns>
protected virtual Hashtable ConvertGridInstantMessageToXMLRPC(GridInstantMessage msg)
{
Hashtable gim = new Hashtable();
gim["from_agent_id"] = msg.fromAgentID.ToString();
// Kept for compatibility
gim["from_agent_session"] = UUID.Zero.ToString();
gim["to_agent_id"] = msg.toAgentID.ToString();
gim["im_session_id"] = msg.imSessionID.ToString();
gim["timestamp"] = msg.timestamp.ToString();
gim["from_agent_name"] = msg.fromAgentName;
gim["message"] = msg.message;
byte[] dialogdata = new byte[1];dialogdata[0] = msg.dialog;
gim["dialog"] = Convert.ToBase64String(dialogdata,Base64FormattingOptions.None);
if (msg.fromGroup)
gim["from_group"] = "TRUE";
else
gim["from_group"] = "FALSE";
byte[] offlinedata = new byte[1]; offlinedata[0] = msg.offline;
gim["offline"] = Convert.ToBase64String(offlinedata, Base64FormattingOptions.None);
gim["parent_estate_id"] = msg.ParentEstateID.ToString();
gim["position_x"] = msg.Position.X.ToString();
gim["position_y"] = msg.Position.Y.ToString();
gim["position_z"] = msg.Position.Z.ToString();
gim["region_id"] = msg.RegionID.ToString();
gim["binary_bucket"] = Convert.ToBase64String(msg.binaryBucket,Base64FormattingOptions.None);
return gim;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.