context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Services.GridService
{
public class GridService : GridServiceBase, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string LogHeader = "[GRID SERVICE]";
private bool m_DeleteOnUnregister = true;
private static GridService m_RootInstance = null;
protected IConfigSource m_config;
protected static HypergridLinker m_HypergridLinker;
protected IAuthenticationService m_AuthenticationService = null;
protected bool m_AllowDuplicateNames = false;
protected bool m_AllowHypergridMapSearch = false;
private static Dictionary<string,object> m_ExtraFeatures = new Dictionary<string, object>();
public GridService(IConfigSource config)
: base(config)
{
m_log.DebugFormat("[GRID SERVICE]: Starting...");
m_config = config;
IConfig gridConfig = config.Configs["GridService"];
if (gridConfig != null)
{
m_DeleteOnUnregister = gridConfig.GetBoolean("DeleteOnUnregister", true);
string authService = gridConfig.GetString("AuthenticationService", String.Empty);
if (authService != String.Empty)
{
Object[] args = new Object[] { config };
m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args);
}
m_AllowDuplicateNames = gridConfig.GetBoolean("AllowDuplicateNames", m_AllowDuplicateNames);
m_AllowHypergridMapSearch = gridConfig.GetBoolean("AllowHypergridMapSearch", m_AllowHypergridMapSearch);
}
if (m_RootInstance == null)
{
m_RootInstance = this;
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand("Regions", true,
"deregister region id",
"deregister region id <region-id>+",
"Deregister a region manually.",
String.Empty,
HandleDeregisterRegion);
// A messy way of stopping this command being added if we are in standalone (since the simulator
// has an identically named command
//
// XXX: We're relying on the OpenSimulator version being registered first, which is not well defined.
if (MainConsole.Instance.Commands.Resolve(new string[] { "show", "regions" }).Length == 0)
MainConsole.Instance.Commands.AddCommand("Regions", true,
"show regions",
"show regions",
"Show details on all regions",
String.Empty,
HandleShowRegions);
MainConsole.Instance.Commands.AddCommand("Regions", true,
"show region name",
"show region name <Region name>",
"Show details on a region",
String.Empty,
HandleShowRegion);
MainConsole.Instance.Commands.AddCommand("Regions", true,
"show region at",
"show region at <x-coord> <y-coord>",
"Show details on a region at the given co-ordinate.",
"For example, show region at 1000 1000",
HandleShowRegionAt);
MainConsole.Instance.Commands.AddCommand("Regions", true,
"set region flags",
"set region flags <Region name> <flags>",
"Set database flags for region",
String.Empty,
HandleSetFlags);
}
SetExtraServiceURLs(config);
m_HypergridLinker = new HypergridLinker(m_config, this, m_Database);
}
}
private void SetExtraServiceURLs(IConfigSource config)
{
IConfig loginConfig = config.Configs["LoginService"];
IConfig gridConfig = config.Configs["GridService"];
if (loginConfig == null || gridConfig == null)
return;
string configVal;
configVal = loginConfig.GetString("SearchURL", string.Empty);
if (!string.IsNullOrEmpty(configVal))
m_ExtraFeatures["search-server-url"] = configVal;
configVal = loginConfig.GetString("MapTileURL", string.Empty);
if (!string.IsNullOrEmpty(configVal))
{
// This URL must end with '/', the viewer doesn't check
configVal = configVal.Trim();
if (!configVal.EndsWith("/"))
configVal = configVal + "/";
m_ExtraFeatures["map-server-url"] = configVal;
}
configVal = loginConfig.GetString("DestinationGuide", string.Empty);
if (!string.IsNullOrEmpty(configVal))
m_ExtraFeatures["destination-guide-url"] = configVal;
m_ExtraFeatures["ExportSupported"] = gridConfig.GetString("ExportSupported", "true");
}
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfos)
{
IConfig gridConfig = m_config.Configs["GridService"];
if (regionInfos.RegionID == UUID.Zero)
return "Invalid RegionID - cannot be zero UUID";
String reason = "Region overlaps another region";
RegionData region = FindAnyConflictingRegion(regionInfos, scopeID, out reason);
// If there is a conflicting region, if it has the same ID and same coordinates
// then it is a region re-registering (permissions and ownership checked later).
if ((region != null)
&& ((region.coordX != regionInfos.RegionCoordX)
|| (region.coordY != regionInfos.RegionCoordY)
|| (region.RegionID != regionInfos.RegionID))
)
{
// If not same ID and same coordinates, this new region has conflicts and can't be registered.
m_log.WarnFormat("{0} Register region conflict in scope {1}. {2}", LogHeader, scopeID, reason);
return reason;
}
if (region != null)
{
// There is a preexisting record
//
// Get it's flags
//
OpenSim.Framework.RegionFlags rflags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(region.Data["flags"]);
// Is this a reservation?
//
if ((rflags & OpenSim.Framework.RegionFlags.Reservation) != 0)
{
// Regions reserved for the null key cannot be taken.
if ((string)region.Data["PrincipalID"] == UUID.Zero.ToString())
return "Region location is reserved";
// Treat it as an auth request
//
// NOTE: Fudging the flags value here, so these flags
// should not be used elsewhere. Don't optimize
// this with the later retrieval of the same flags!
rflags |= OpenSim.Framework.RegionFlags.Authenticate;
}
if ((rflags & OpenSim.Framework.RegionFlags.Authenticate) != 0)
{
// Can we authenticate at all?
//
if (m_AuthenticationService == null)
return "No authentication possible";
if (!m_AuthenticationService.Verify(new UUID(region.Data["PrincipalID"].ToString()), regionInfos.Token, 30))
return "Bad authentication";
}
}
// If we get here, the destination is clear. Now for the real check.
if (!m_AllowDuplicateNames)
{
List<RegionData> dupe = m_Database.Get(Util.EscapeForLike(regionInfos.RegionName), scopeID);
if (dupe != null && dupe.Count > 0)
{
foreach (RegionData d in dupe)
{
if (d.RegionID != regionInfos.RegionID)
{
m_log.WarnFormat("[GRID SERVICE]: Region tried to register using a duplicate name. New region: {0} ({1}), existing region: {2} ({3}).",
regionInfos.RegionName, regionInfos.RegionID, d.RegionName, d.RegionID);
return "Duplicate region name";
}
}
}
}
// If there is an old record for us, delete it if it is elsewhere.
region = m_Database.Get(regionInfos.RegionID, scopeID);
if ((region != null) && (region.RegionID == regionInfos.RegionID) &&
((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY)))
{
if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.NoMove) != 0)
return "Can't move this region";
if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.LockedOut) != 0)
return "Region locked out";
// Region reregistering in other coordinates. Delete the old entry
m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.",
regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY);
try
{
m_Database.Delete(regionInfos.RegionID);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
}
}
// Everything is ok, let's register
RegionData rdata = RegionInfo2RegionData(regionInfos);
rdata.ScopeID = scopeID;
if (region != null)
{
int oldFlags = Convert.ToInt32(region.Data["flags"]);
oldFlags &= ~(int)OpenSim.Framework.RegionFlags.Reservation;
rdata.Data["flags"] = oldFlags.ToString(); // Preserve flags
}
else
{
rdata.Data["flags"] = "0";
if ((gridConfig != null) && rdata.RegionName != string.Empty)
{
int newFlags = 0;
string regionName = rdata.RegionName.Trim().Replace(' ', '_');
newFlags = ParseFlags(newFlags, gridConfig.GetString("DefaultRegionFlags", String.Empty));
newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + regionName, String.Empty));
newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + rdata.RegionID.ToString(), String.Empty));
rdata.Data["flags"] = newFlags.ToString();
}
}
int flags = Convert.ToInt32(rdata.Data["flags"]);
flags |= (int)OpenSim.Framework.RegionFlags.RegionOnline;
rdata.Data["flags"] = flags.ToString();
try
{
rdata.Data["last_seen"] = Util.UnixTimeSinceEpoch();
m_Database.Store(rdata);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
}
m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) registered successfully at {2}-{3} with flags {4}",
regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionCoordX, regionInfos.RegionCoordY,
(OpenSim.Framework.RegionFlags)flags);
return String.Empty;
}
/// <summary>
/// Search the region map for regions conflicting with this region.
/// The region to be added is passed and we look for any existing regions that are
/// in the requested location, that are large varregions that overlap this region, or
/// are previously defined regions that would lie under this new region.
/// </summary>
/// <param name="regionInfos">Information on region requested to be added to the world map</param>
/// <param name="scopeID">Grid id for region</param>
/// <param name="reason">The reason the returned region conflicts with passed region</param>
/// <returns></returns>
private RegionData FindAnyConflictingRegion(GridRegion regionInfos, UUID scopeID, out string reason)
{
reason = "Reregistration";
// First see if there is an existing region right where this region is trying to go
// (We keep this result so it can be returned if suppressing errors)
RegionData noErrorRegion = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);
RegionData region = noErrorRegion;
if (region != null
&& region.RegionID == regionInfos.RegionID
&& region.sizeX == regionInfos.RegionSizeX
&& region.sizeY == regionInfos.RegionSizeY)
{
// If this seems to be exactly the same region, return this as it could be
// a re-registration (permissions checked by calling routine).
m_log.DebugFormat("{0} FindAnyConflictingRegion: re-register of {1}",
LogHeader, RegionString(regionInfos));
return region;
}
// No region exactly there or we're resizing an existing region.
// Fetch regions that could be varregions overlapping requested location.
int xmin = regionInfos.RegionLocX - (int)Constants.MaximumRegionSize + 10;
int xmax = regionInfos.RegionLocX;
int ymin = regionInfos.RegionLocY - (int)Constants.MaximumRegionSize + 10;
int ymax = regionInfos.RegionLocY;
List<RegionData> rdatas = m_Database.Get(xmin, ymin, xmax, ymax, scopeID);
foreach (RegionData rdata in rdatas)
{
// m_log.DebugFormat("{0} FindAnyConflictingRegion: find existing. Checking {1}", LogHeader, RegionString(rdata) );
if ((rdata.posX + rdata.sizeX > regionInfos.RegionLocX)
&& (rdata.posY + rdata.sizeY > regionInfos.RegionLocY))
{
region = rdata;
m_log.WarnFormat("{0} FindAnyConflictingRegion: conflict of {1} by existing varregion {2}",
LogHeader, RegionString(regionInfos), RegionString(region));
reason = String.Format("Region location is overlapped by existing varregion {0}",
RegionString(region));
return region;
}
}
// There isn't a region that overlaps this potential region.
// See if this potential region overlaps an existing region.
// First, a shortcut of not looking for overlap if new region is legacy region sized
// and connot overlap anything.
if (regionInfos.RegionSizeX != Constants.RegionSize
|| regionInfos.RegionSizeY != Constants.RegionSize)
{
// trim range looked for so we don't pick up neighbor regions just off the edges
xmin = regionInfos.RegionLocX;
xmax = regionInfos.RegionLocX + regionInfos.RegionSizeX - 10;
ymin = regionInfos.RegionLocY;
ymax = regionInfos.RegionLocY + regionInfos.RegionSizeY - 10;
rdatas = m_Database.Get(xmin, ymin, xmax, ymax, scopeID);
// If the region is being resized, the found region could be ourself.
foreach (RegionData rdata in rdatas)
{
// m_log.DebugFormat("{0} FindAnyConflictingRegion: see if overlap. Checking {1}", LogHeader, RegionString(rdata) );
if (region == null || region.RegionID != regionInfos.RegionID)
{
region = rdata;
m_log.WarnFormat("{0} FindAnyConflictingRegion: conflict of varregion {1} overlaps existing region {2}",
LogHeader, RegionString(regionInfos), RegionString(region));
reason = String.Format("Region {0} would overlap existing region {1}",
RegionString(regionInfos), RegionString(region));
return region;
}
}
}
// If we get here, region is either null (nothing found here) or
// is the non-conflicting region found at the location being requested.
return region;
}
// String describing name and region location of passed region
private String RegionString(RegionData reg)
{
return String.Format("{0}/{1} at <{2},{3}>",
reg.RegionName, reg.RegionID, reg.coordX, reg.coordY);
}
// String describing name and region location of passed region
private String RegionString(GridRegion reg)
{
return String.Format("{0}/{1} at <{2},{3}>",
reg.RegionName, reg.RegionID, reg.RegionCoordX, reg.RegionCoordY);
}
public bool DeregisterRegion(UUID regionID)
{
RegionData region = m_Database.Get(regionID, UUID.Zero);
if (region == null)
return false;
m_log.DebugFormat(
"[GRID SERVICE]: Deregistering region {0} ({1}) at {2}-{3}",
region.RegionName, region.RegionID, region.coordX, region.coordY);
int flags = Convert.ToInt32(region.Data["flags"]);
if (!m_DeleteOnUnregister || (flags & (int)OpenSim.Framework.RegionFlags.Persistent) != 0)
{
flags &= ~(int)OpenSim.Framework.RegionFlags.RegionOnline;
region.Data["flags"] = flags.ToString();
region.Data["last_seen"] = Util.UnixTimeSinceEpoch();
try
{
m_Database.Store(region);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
}
return true;
}
return m_Database.Delete(regionID);
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
List<GridRegion> rinfos = new List<GridRegion>();
RegionData region = m_Database.Get(regionID, scopeID);
if (region != null)
{
// Not really? Maybe?
// The adjacent regions are presumed to be the same size as the current region
List<RegionData> rdatas = m_Database.Get(
region.posX - region.sizeX - 1, region.posY - region.sizeY - 1,
region.posX + region.sizeX + 1, region.posY + region.sizeY + 1, scopeID);
foreach (RegionData rdata in rdatas)
{
if (rdata.RegionID != regionID)
{
int flags = Convert.ToInt32(rdata.Data["flags"]);
if ((flags & (int)Framework.RegionFlags.Hyperlink) == 0) // no hyperlinks as neighbours
rinfos.Add(RegionData2RegionInfo(rdata));
}
}
// m_log.DebugFormat("[GRID SERVICE]: region {0} has {1} neighbours", region.RegionName, rinfos.Count);
}
else
{
m_log.WarnFormat(
"[GRID SERVICE]: GetNeighbours() called for scope {0}, region {1} but no such region found",
scopeID, regionID);
}
return rinfos;
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
RegionData rdata = m_Database.Get(regionID, scopeID);
if (rdata != null)
return RegionData2RegionInfo(rdata);
return null;
}
// Get a region given its base coordinates.
// NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST
// be the base coordinate of the region.
// The snapping is technically unnecessary but is harmless because regions are always
// multiples of the legacy region size (256).
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
int snapX = (int)(x / Constants.RegionSize) * (int)Constants.RegionSize;
int snapY = (int)(y / Constants.RegionSize) * (int)Constants.RegionSize;
RegionData rdata = m_Database.Get(snapX, snapY, scopeID);
if (rdata != null)
return RegionData2RegionInfo(rdata);
return null;
}
public GridRegion GetRegionByName(UUID scopeID, string name)
{
List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(name), scopeID);
if ((rdatas != null) && (rdatas.Count > 0))
return RegionData2RegionInfo(rdatas[0]); // get the first
if (m_AllowHypergridMapSearch)
{
GridRegion r = GetHypergridRegionByName(scopeID, name);
if (r != null)
return r;
}
return null;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
// m_log.DebugFormat("[GRID SERVICE]: GetRegionsByName {0}", name);
List<RegionData> rdatas = m_Database.Get(Util.EscapeForLike(name) + "%", scopeID);
int count = 0;
List<GridRegion> rinfos = new List<GridRegion>();
if (rdatas != null)
{
// m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count);
foreach (RegionData rdata in rdatas)
{
if (count++ < maxNumber)
rinfos.Add(RegionData2RegionInfo(rdata));
}
}
if (m_AllowHypergridMapSearch && (rdatas == null || (rdatas != null && rdatas.Count == 0)))
{
GridRegion r = GetHypergridRegionByName(scopeID, name);
if (r != null)
rinfos.Add(r);
}
return rinfos;
}
/// <summary>
/// Get a hypergrid region.
/// </summary>
/// <param name="scopeID"></param>
/// <param name="name"></param>
/// <returns>null if no hypergrid region could be found.</returns>
protected GridRegion GetHypergridRegionByName(UUID scopeID, string name)
{
if (name.Contains("."))
return m_HypergridLinker.LinkRegion(scopeID, name);
else
return null;
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
int xminSnap = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize;
int xmaxSnap = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;
int yminSnap = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize;
int ymaxSnap = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize;
List<RegionData> rdatas = m_Database.Get(xminSnap, yminSnap, xmaxSnap, ymaxSnap, scopeID);
List<GridRegion> rinfos = new List<GridRegion>();
foreach (RegionData rdata in rdatas)
rinfos.Add(RegionData2RegionInfo(rdata));
return rinfos;
}
#endregion
#region Data structure conversions
public RegionData RegionInfo2RegionData(GridRegion rinfo)
{
RegionData rdata = new RegionData();
rdata.posX = (int)rinfo.RegionLocX;
rdata.posY = (int)rinfo.RegionLocY;
rdata.sizeX = rinfo.RegionSizeX;
rdata.sizeY = rinfo.RegionSizeY;
rdata.RegionID = rinfo.RegionID;
rdata.RegionName = rinfo.RegionName;
rdata.Data = rinfo.ToKeyValuePairs();
rdata.Data["regionHandle"] = Utils.UIntsToLong((uint)rdata.posX, (uint)rdata.posY);
rdata.Data["owner_uuid"] = rinfo.EstateOwner.ToString();
return rdata;
}
public GridRegion RegionData2RegionInfo(RegionData rdata)
{
GridRegion rinfo = new GridRegion(rdata.Data);
rinfo.RegionLocX = rdata.posX;
rinfo.RegionLocY = rdata.posY;
rinfo.RegionSizeX = rdata.sizeX;
rinfo.RegionSizeY = rdata.sizeY;
rinfo.RegionID = rdata.RegionID;
rinfo.RegionName = rdata.RegionName;
rinfo.ScopeID = rdata.ScopeID;
return rinfo;
}
#endregion
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetDefaultRegions(scopeID);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
m_log.DebugFormat("[GRID SERVICE]: GetDefaultRegions returning {0} regions", ret.Count);
return ret;
}
public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetDefaultHypergridRegions(scopeID);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
int hgDefaultRegionsFoundOnline = regions.Count;
// For now, hypergrid default regions will always be given precedence but we will also return simple default
// regions in case no specific hypergrid regions are specified.
ret.AddRange(GetDefaultRegions(scopeID));
int normalDefaultRegionsFoundOnline = ret.Count - hgDefaultRegionsFoundOnline;
m_log.DebugFormat(
"[GRID SERVICE]: GetDefaultHypergridRegions returning {0} hypergrid default and {1} normal default regions",
hgDefaultRegionsFoundOnline, normalDefaultRegionsFoundOnline);
return ret;
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetFallbackRegions(scopeID, x, y);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
m_log.DebugFormat("[GRID SERVICE]: Fallback returned {0} regions", ret.Count);
return ret;
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetHyperlinks(scopeID);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Framework.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
m_log.DebugFormat("[GRID SERVICE]: Hyperlinks returned {0} regions", ret.Count);
return ret;
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
RegionData region = m_Database.Get(regionID, scopeID);
if (region != null)
{
int flags = Convert.ToInt32(region.Data["flags"]);
//m_log.DebugFormat("[GRID SERVICE]: Request for flags of {0}: {1}", regionID, flags);
return flags;
}
else
return -1;
}
private void HandleDeregisterRegion(string module, string[] cmd)
{
if (cmd.Length < 4)
{
MainConsole.Instance.Output("Usage: degregister region id <region-id>+");
return;
}
for (int i = 3; i < cmd.Length; i++)
{
string rawRegionUuid = cmd[i];
UUID regionUuid;
if (!UUID.TryParse(rawRegionUuid, out regionUuid))
{
MainConsole.Instance.OutputFormat("{0} is not a valid region uuid", rawRegionUuid);
return;
}
GridRegion region = GetRegionByUUID(UUID.Zero, regionUuid);
if (region == null)
{
MainConsole.Instance.OutputFormat("No region with UUID {0}", regionUuid);
return;
}
if (DeregisterRegion(regionUuid))
{
MainConsole.Instance.OutputFormat("Deregistered {0} {1}", region.RegionName, regionUuid);
}
else
{
// I don't think this can ever occur if we know that the region exists.
MainConsole.Instance.OutputFormat("Error deregistering {0} {1}", region.RegionName, regionUuid);
}
}
}
private void HandleShowRegions(string module, string[] cmd)
{
if (cmd.Length != 2)
{
MainConsole.Instance.Output("Syntax: show regions");
return;
}
List<RegionData> regions = m_Database.Get(int.MinValue, int.MinValue, int.MaxValue, int.MaxValue, UUID.Zero);
OutputRegionsToConsoleSummary(regions);
}
private void HandleShowRegion(string module, string[] cmd)
{
if (cmd.Length != 4)
{
MainConsole.Instance.Output("Syntax: show region name <region name>");
return;
}
string regionName = cmd[3];
List<RegionData> regions = m_Database.Get(Util.EscapeForLike(regionName), UUID.Zero);
if (regions == null || regions.Count < 1)
{
MainConsole.Instance.Output("No region with name {0} found", regionName);
return;
}
OutputRegionsToConsole(regions);
}
private void HandleShowRegionAt(string module, string[] cmd)
{
if (cmd.Length != 5)
{
MainConsole.Instance.Output("Syntax: show region at <x-coord> <y-coord>");
return;
}
uint x, y;
if (!uint.TryParse(cmd[3], out x))
{
MainConsole.Instance.Output("x-coord must be an integer");
return;
}
if (!uint.TryParse(cmd[4], out y))
{
MainConsole.Instance.Output("y-coord must be an integer");
return;
}
RegionData region = m_Database.Get((int)Util.RegionToWorldLoc(x), (int)Util.RegionToWorldLoc(y), UUID.Zero);
if (region == null)
{
MainConsole.Instance.OutputFormat("No region found at {0},{1}", x, y);
return;
}
OutputRegionToConsole(region);
}
private void OutputRegionToConsole(RegionData r)
{
OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]);
ConsoleDisplayList dispList = new ConsoleDisplayList();
dispList.AddRow("Region Name", r.RegionName);
dispList.AddRow("Region ID", r.RegionID);
dispList.AddRow("Position", string.Format("{0},{1}", r.coordX, r.coordY));
dispList.AddRow("Size", string.Format("{0}x{1}", r.sizeX, r.sizeY));
dispList.AddRow("URI", r.Data["serverURI"]);
dispList.AddRow("Owner ID", r.Data["owner_uuid"]);
dispList.AddRow("Flags", flags);
MainConsole.Instance.Output(dispList.ToString());
}
private void OutputRegionsToConsole(List<RegionData> regions)
{
foreach (RegionData r in regions)
OutputRegionToConsole(r);
}
private void OutputRegionsToConsoleSummary(List<RegionData> regions)
{
ConsoleDisplayTable dispTable = new ConsoleDisplayTable();
dispTable.AddColumn("Name", 44);
dispTable.AddColumn("ID", 36);
dispTable.AddColumn("Position", 11);
dispTable.AddColumn("Size", 11);
dispTable.AddColumn("Flags", 60);
foreach (RegionData r in regions)
{
OpenSim.Framework.RegionFlags flags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(r.Data["flags"]);
dispTable.AddRow(
r.RegionName,
r.RegionID.ToString(),
string.Format("{0},{1}", r.coordX, r.coordY),
string.Format("{0}x{1}", r.sizeX, r.sizeY),
flags.ToString());
}
MainConsole.Instance.Output(dispTable.ToString());
}
private int ParseFlags(int prev, string flags)
{
OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)prev;
string[] parts = flags.Split(new char[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);
foreach (string p in parts)
{
int val;
try
{
if (p.StartsWith("+"))
{
val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1));
f |= (OpenSim.Framework.RegionFlags)val;
}
else if (p.StartsWith("-"))
{
val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p.Substring(1));
f &= ~(OpenSim.Framework.RegionFlags)val;
}
else
{
val = (int)Enum.Parse(typeof(OpenSim.Framework.RegionFlags), p);
f |= (OpenSim.Framework.RegionFlags)val;
}
}
catch (Exception)
{
MainConsole.Instance.Output("Error in flag specification: " + p);
}
}
return (int)f;
}
private void HandleSetFlags(string module, string[] cmd)
{
if (cmd.Length < 5)
{
MainConsole.Instance.Output("Syntax: set region flags <region name> <flags>");
return;
}
List<RegionData> regions = m_Database.Get(Util.EscapeForLike(cmd[3]), UUID.Zero);
if (regions == null || regions.Count < 1)
{
MainConsole.Instance.Output("Region not found");
return;
}
foreach (RegionData r in regions)
{
int flags = Convert.ToInt32(r.Data["flags"]);
flags = ParseFlags(flags, cmd[4]);
r.Data["flags"] = flags.ToString();
OpenSim.Framework.RegionFlags f = (OpenSim.Framework.RegionFlags)flags;
MainConsole.Instance.Output(String.Format("Set region {0} to {1}", r.RegionName, f));
m_Database.Store(r);
}
}
/// <summary>
/// Gets the grid extra service URls we wish for the region to send in OpenSimExtras to dynamically refresh
/// parameters in the viewer used to access services like map, search and destination guides.
/// <para>see "SimulatorFeaturesModule" </para>
/// </summary>
/// <returns>
/// The grid extra service URls.
/// </returns>
public Dictionary<string,object> GetExtraFeatures()
{
return m_ExtraFeatures;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Threading;
using SQLite;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
using WPCordovaClassLib.Cordova.JSON;
namespace Cordova.Extension.Commands
{
public class SQLitePlugin : BaseCommand
{
#region SQLitePlugin options
[DataContract]
public class SQLitePluginOpenOptions
{
[DataMember(IsRequired = true, Name = "name")]
public string name { get; set; }
[DataMember(IsRequired = false, Name = "bgType", EmitDefaultValue = false)]
public int bgType = 0;
}
[DataContract]
public class SQLitePluginCloseDeleteOptions
{
[DataMember(IsRequired = true, Name = "path")]
public string name { get; set; }
}
[DataContract]
public class SQLitePluginExecuteSqlBatchArgs
{
[DataMember(IsRequired = true, Name = "dbname")]
public string name { get; set; }
}
[DataContract]
public class SQLitePluginExecuteSqlBatchOptions
{
[DataMember(IsRequired = true, Name = "dbargs")]
public SQLitePluginExecuteSqlBatchArgs dbargs { get; set; }
[DataMember(IsRequired = true, Name = "executes")]
public TransactionsCollection executes { get; set; }
}
[CollectionDataContract]
public class TransactionsCollection : Collection<SQLitePluginTransaction>
{
}
[DataContract]
public class SQLitePluginTransaction
{
/// <summary>
/// Identifier for transaction
/// </summary>
[DataMember(IsRequired = false, Name = "trans_id")]
public string transId { get; set; }
/// <summary>
/// Callback identifer
/// </summary>
[DataMember(IsRequired = true, Name = "qid")]
public string queryId { get; set; }
/// <summary>
/// Query string
/// </summary>
[DataMember(IsRequired = true, Name = "sql")]
public string query { get; set; }
/// <summary>
/// Query parameters
/// </summary>
/// <remarks>TODO: broken in WP8 & 8.1; interprets ["1.5"] as [1.5]</remarks>
[DataMember(IsRequired = true, Name = "params")]
public object[] query_params { get; set; }
}
#endregion
private readonly DatabaseManager databaseManager;
public SQLitePlugin()
{
this.databaseManager = new DatabaseManager(this);
}
public void open(string options)
{
string mycbid = this.CurrentCommandCallbackId;
//System.Diagnostics.Debug.WriteLine("SQLitePlugin.open() with cbid " + mycbid + " options:" + options);
try
{
String [] jsonOptions = JsonHelper.Deserialize<string[]>(options);
mycbid = jsonOptions[1];
var dbOptions = JsonHelper.Deserialize<SQLitePluginOpenOptions>(jsonOptions[0]);
this.databaseManager.Open(dbOptions.name, mycbid);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), mycbid);
}
}
public void close(string options)
{
string mycbid = this.CurrentCommandCallbackId;
try
{
String[] jsonOptions = JsonHelper.Deserialize<string[]>(options);
mycbid = jsonOptions[1];
var dbOptions = JsonHelper.Deserialize<SQLitePluginCloseDeleteOptions>(jsonOptions[0]);
this.databaseManager.Close(dbOptions.name, mycbid);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), mycbid);
}
}
public void delete(string options)
{
string mycbid = this.CurrentCommandCallbackId;
try
{
String[] jsonOptions = JsonHelper.Deserialize<string[]>(options);
mycbid = jsonOptions[1];
var dbOptions = JsonHelper.Deserialize<SQLitePluginCloseDeleteOptions>(jsonOptions[0]);
this.databaseManager.Delete(dbOptions.name, mycbid);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), mycbid);
}
}
public void backgroundExecuteSqlBatch(string options)
{
string mycbid = this.CurrentCommandCallbackId;
try
{
String[] jsonOptions = JsonHelper.Deserialize<string[]>(options);
mycbid = jsonOptions[1];
SQLitePluginExecuteSqlBatchOptions batch = JsonHelper.Deserialize<SQLitePluginExecuteSqlBatchOptions>(jsonOptions[0]);
this.databaseManager.Query(batch.dbargs.name, batch.executes, mycbid);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), mycbid);
}
}
/// <summary>
/// Manage the collection of currently open databases and queue requests for them
/// </summary>
public class DatabaseManager
{
private readonly BaseCommand plugin;
private readonly IDictionary<string, DBRunner> runners = new Dictionary<string, DBRunner>();
private readonly object runnersLock = new object();
public DatabaseManager(BaseCommand plugin)
{
this.plugin = plugin;
}
public void Open(string dbname, string cbc)
{
DBRunner runner;
lock (runnersLock)
{
if (!runners.TryGetValue(dbname, out runner))
{
runner = new DBRunner(this, dbname, cbc);
runner.Start();
runners[dbname] = runner;
}
else
{
// acknowledge open if it is scheduled after first query.
// Also works for re-opening a database, but means that one cannot close a single instance of a database.
this.Ok(cbc);
}
}
}
public void Query(string dbname, TransactionsCollection queries, string callbackId)
{
lock (runnersLock)
{
DBRunner runner;
if (!runners.TryGetValue(dbname, out runner))
{
// query may start before open is scheduled
runner = new DBRunner(this, dbname, null);
runner.Start();
runners[dbname] = runner;
}
var query = new DBQuery(queries, callbackId);
runner.Enqueue(query);
}
}
public void Close(string dbname, string callbackId)
{
lock (runnersLock)
{
DBRunner runner;
if (runners.TryGetValue(dbname, out runner))
{
var query = new DBQuery(false, callbackId);
runner.Enqueue(query);
// As we cannot determine the order in which query/open requests arrive,
// any such requests should start a new thread rather than being lost on the dying queue.
// Hence synchronoous wait for thread-end within request and within lock.
runner.WaitForStopped();
runners.Remove(dbname);
}
else
{
// closing a closed database is trivial
Ok(callbackId);
}
}
}
public void Delete(string dbname, string callbackId)
{
var query = new DBQuery(false, callbackId);
lock (runnersLock)
{
DBRunner runner;
if (runners.TryGetValue(dbname, out runner))
{
runner.Enqueue(query);
// As we cannot determine the order in which query/open requests arrive,
// any such requests should start a new thread rather than being lost on the dying queue.
// Hence synchronoous wait for thread-end within request and within lock.
runner.WaitForStopped();
runners.Remove(dbname);
}
else
{
// Deleting a closed database, so no runner to queue the request on
// Must be inside lock so databases are not opened while being deleted
DBRunner.DeleteDatabaseNow(this, dbname, callbackId);
}
}
}
public void Finished(DBRunner runner)
{
lock (runnersLock)
{
runners.Remove(runner.DatabaseName);
}
}
public void Ok(string callbackId, string result)
{
this.plugin.DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId);
}
public void Ok(string callbackId)
{
this.plugin.DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
}
public void Error(string callbackId, string message)
{
this.plugin.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, message), callbackId);
}
}
/// <summary>
/// Maintain a single database with a thread/queue pair to feed requests to it
/// </summary>
public class DBRunner
{
private DatabaseManager databases;
private SQLiteConnection db;
public string DatabaseName { get; private set; }
private readonly string openCalllbackId;
private readonly Thread thread;
private readonly BlockingQueue<DBQuery> queue;
public DBRunner(DatabaseManager databases, string dbname, string cbc)
{
this.databases = databases;
this.DatabaseName = dbname;
this.queue = new BlockingQueue<DBQuery>();
this.openCalllbackId = cbc;
this.thread = new Thread(this.Run) { Name = dbname };
}
public void Start()
{
this.thread.Start();
}
public void WaitForStopped()
{
this.thread.Join();
}
public void Enqueue(DBQuery dbq)
{
this.queue.Enqueue(dbq);
}
private void Run()
{
try
{
// As a query can be requested for the callback for "open" has been completed,
// the thread may not be started by the open request, in which case no open callback id
this.db = new SQLiteConnection(this.DatabaseName);
if (openCalllbackId != null)
{
this.databases.Ok(openCalllbackId);
}
}
catch (Exception ex)
{
LogError("Failed to open database " + DatabaseName, ex);
if (openCalllbackId != null)
{
this.databases.Error(openCalllbackId, "Failed to open database " + ex.Message);
}
databases.Finished(this);
return;
}
DBQuery dbq = queue.Take();
while (!dbq.Stop)
{
executeSqlBatch(dbq);
dbq = queue.Take();
}
if (!dbq.Delete)
{
// close and callback
CloseDatabaseNow(dbq.CallbackId);
}
else
{
// close, then delete and callback
CloseDatabaseNow(null);
DeleteDatabaseNow(this.databases, DatabaseName, dbq.CallbackId);
}
}
public void CloseDatabaseNow(string callBackId)
{
bool success = true;
string error = null;
try
{
this.db.Close();
}
catch (Exception e)
{
LogError("couldn't close " + this.DatabaseName, e);
success = false;
error = e.Message;
}
if (callBackId != null)
{
if (success)
{
this.databases.Ok(callBackId);
}
else
{
this.databases.Error(callBackId, error);
}
}
}
// Needs to be static to support deleting closed databases
public static void DeleteDatabaseNow(DatabaseManager databases, string dbname, string callBackId)
{
bool success = true;
string error = null;
try
{
var folderPath = Path.GetDirectoryName(dbname);
if (folderPath == "")
{
folderPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
}
var fileName = Path.GetFileName(dbname);
if (!System.IO.File.Exists(Path.Combine(folderPath, fileName)))
{
databases.Error(callBackId, "Database does not exist: " + dbname);
}
var fileExtension = new[] { "", "-journal", "-wal", "-shm" };
foreach (var extension in fileExtension)
{
var fullPath = Path.Combine(folderPath, fileName + extension);
System.IO.File.Delete(fullPath);
}
}
catch (Exception ex)
{
error = ex.Message;
success = false;
}
if (success)
{
databases.Ok(callBackId);
}
else
{
databases.Error(callBackId, error);
}
}
public void executeSqlBatch(DBQuery dbq)
{
string batchResultsStr = "";
// loop through the sql in the transaction
foreach (SQLitePluginTransaction transaction in dbq.Queries)
{
string resultString = "";
string errorMessage = "unknown";
bool needQuery = true;
// begin
if (transaction.query.StartsWith("BEGIN", StringComparison.OrdinalIgnoreCase))
{
needQuery = false;
try
{
this.db.BeginTransaction();
resultString = "\"rowsAffected\":0";
}
catch (Exception e)
{
errorMessage = e.Message;
}
}
// commit
if (transaction.query.StartsWith("COMMIT", StringComparison.OrdinalIgnoreCase))
{
needQuery = false;
try
{
this.db.Commit();
resultString = "\"rowsAffected\":0";
}
catch (Exception e)
{
errorMessage = e.Message;
}
}
// rollback
if (transaction.query.StartsWith("ROLLBACK", StringComparison.OrdinalIgnoreCase))
{
needQuery = false;
try
{
this.db.Rollback();
resultString = "\"rowsAffected\":0";
}
catch (Exception e)
{
errorMessage = e.Message;
}
}
// create/drop table
if (transaction.query.IndexOf("DROP TABLE", StringComparison.OrdinalIgnoreCase) > -1 || transaction.query.IndexOf("CREATE TABLE", StringComparison.OrdinalIgnoreCase) > -1)
{
needQuery = false;
try
{
var results = db.Execute(transaction.query, transaction.query_params);
resultString = "\"rowsAffected\":0";
}
catch (Exception e)
{
errorMessage = e.Message;
}
}
// insert/update/delete
if (transaction.query.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase) ||
transaction.query.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) ||
transaction.query.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
{
needQuery = false;
try
{
// execute our query
var res = db.Execute(transaction.query, transaction.query_params);
// get the primary key of the last inserted row
var insertId = SQLite3.LastInsertRowid(db.Handle);
resultString = String.Format("\"rowsAffected\":{0}", res);
if (transaction.query.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
{
resultString += String.Format(",\"insertId\":{0}", insertId);
}
}
catch (Exception e)
{
errorMessage = e.Message;
}
}
if (needQuery)
{
try
{
var results = this.db.Query2(transaction.query, transaction.query_params);
string rowsString = "";
foreach (SQLiteQueryRow res in results)
{
string rowString = "";
if (rowsString.Length != 0) rowsString += ",";
foreach (SQLiteQueryColumn column in res.column)
{
if (rowString.Length != 0) rowString += ",";
if (column.Value != null)
{
if (column.Value.GetType().Equals(typeof(Int32)))
{
rowString += String.Format("\"{0}\":{1}",
column.Key, Convert.ToInt32(column.Value));
}
else if (column.Value.GetType().Equals(typeof(Double)))
{
rowString += String.Format(CultureInfo.InvariantCulture, "\"{0}\":{1}",
column.Key, Convert.ToDouble(column.Value, CultureInfo.InvariantCulture));
}
else
{
rowString += String.Format("\"{0}\":\"{1}\"",
column.Key,
column.Value.ToString()
.Replace("\\","\\\\")
.Replace("\"","\\\"")
.Replace("\t","\\t")
.Replace("\r","\\r")
.Replace("\n","\\n")
);
}
}
else
{
rowString += String.Format("\"{0}\":null", column.Key);
}
}
rowsString += "{" + rowString + "}";
}
resultString = "\"rows\":[" + rowsString + "]";
}
catch (Exception e)
{
errorMessage = e.Message;
}
}
if (batchResultsStr.Length != 0) batchResultsStr += ",";
if (resultString.Length != 0)
{
batchResultsStr += "{\"qid\":\"" + transaction.queryId + "\",\"type\":\"success\",\"result\":{" + resultString + "}}";
//System.Diagnostics.Debug.WriteLine("batchResultsStr: " + batchResultsStr);
}
else
{
batchResultsStr += "{\"qid\":\"" + transaction.queryId + "\",\"type\":\"error\",\"result\":{\"message\":\"" + errorMessage.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"}}";
}
}
this.databases.Ok(dbq.CallbackId, "[" + batchResultsStr + "]");
}
private static void LogError(string message, Exception e)
{
// TODO - good place for a breakpoint
}
private static void LogWarning(string message)
{
// TODO - good place for a breakpoint
}
}
/// <summary>
/// A single, queueable, request for a database
/// </summary>
public class DBQuery
{
public bool Stop { get; private set; }
public bool Delete { get; private set; }
public TransactionsCollection Queries { get; private set; }
public string CallbackId { get; private set; }
/// <summary>
/// Create a request to run a query
/// </summary>
public DBQuery(TransactionsCollection queries, string callbackId)
{
this.Stop = false;
this.Delete = false;
this.Queries = queries;
this.CallbackId = callbackId;
}
/// <summary>
/// Create a request to close, and optionally delete, a database
/// </summary>
public DBQuery(bool delete, string callbackId)
{
this.Stop = true;
this.Delete = delete;
this.Queries = null;
this.CallbackId = callbackId;
}
}
/// <summary>
/// Minimal blocking queue
/// </summary>
/// <remarks>
/// Expects one reader and n writers - no support for a reader closing down the queue and releasing other readers.
/// </remarks>
/// <typeparam name="T"></typeparam>
class BlockingQueue<T>
{
private readonly Queue<T> items = new Queue<T>();
private readonly object locker = new object();
public T Take()
{
lock (locker)
{
while (items.Count == 0)
{
Monitor.Wait(locker);
}
return items.Dequeue();
}
}
public void Enqueue(T value)
{
lock (locker)
{
items.Enqueue(value);
Monitor.PulseAll(locker);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
namespace Umbraco.Core.Services
{
/// <summary>
/// Defines the ContentTypeService, which is an easy access to operations involving <see cref="IContentType"/>
/// </summary>
public interface IContentTypeService : IService
{
/// <summary>
/// Given the path of a content item, this will return true if the content item exists underneath a list view content item
/// </summary>
/// <param name="contentPath"></param>
/// <returns></returns>
bool HasContainerInPath(string contentPath);
int CountContentTypes();
int CountMediaTypes();
/// <summary>
/// Validates the composition, if its invalid a list of property type aliases that were duplicated is returned
/// </summary>
/// <param name="compo"></param>
/// <returns></returns>
Attempt<string[]> ValidateComposition(IContentTypeComposition compo);
Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateContentTypeContainer(int parentId, string name, int userId = 0);
Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateMediaTypeContainer(int parentId, string name, int userId = 0);
Attempt<OperationStatus> SaveContentTypeContainer(EntityContainer container, int userId = 0);
Attempt<OperationStatus> SaveMediaTypeContainer(EntityContainer container, int userId = 0);
EntityContainer GetContentTypeContainer(int containerId);
EntityContainer GetContentTypeContainer(Guid containerId);
IEnumerable<EntityContainer> GetContentTypeContainers(int[] containerIds);
IEnumerable<EntityContainer> GetContentTypeContainers(IContentType contentType);
IEnumerable<EntityContainer> GetContentTypeContainers(string folderName, int level);
EntityContainer GetMediaTypeContainer(int containerId);
EntityContainer GetMediaTypeContainer(Guid containerId);
IEnumerable<EntityContainer> GetMediaTypeContainers(int[] containerIds);
IEnumerable<EntityContainer> GetMediaTypeContainers(string folderName, int level);
IEnumerable<EntityContainer> GetMediaTypeContainers(IMediaType mediaType);
Attempt<OperationStatus> DeleteMediaTypeContainer(int folderId, int userId = 0);
Attempt<OperationStatus> DeleteContentTypeContainer(int containerId, int userId = 0);
/// <summary>
/// Gets all property type aliases.
/// </summary>
/// <returns></returns>
IEnumerable<string> GetAllPropertyTypeAliases();
/// <summary>
/// Gets all content type aliases
/// </summary>
/// <param name="objectTypes">
/// If this list is empty, it will return all content type aliases for media, members and content, otherwise
/// it will only return content type aliases for the object types specified
/// </param>
/// <returns></returns>
IEnumerable<string> GetAllContentTypeAliases(params Guid[] objectTypes);
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parentId">
/// The parent to copy the content type to, default is -1 (root)
/// </param>
/// <returns></returns>
IContentType Copy(IContentType original, string alias, string name, int parentId = -1);
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parent">
/// The parent to copy the content type to
/// </param>
/// <returns></returns>
IContentType Copy(IContentType original, string alias, string name, IContentType parent);
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
IContentType GetContentType(int id);
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
IContentType GetContentType(string alias);
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Key
/// </summary>
/// <param name="id">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
IContentType GetContentType(Guid id);
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
IEnumerable<IContentType> GetAllContentTypes(params int[] ids);
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
IEnumerable<IContentType> GetAllContentTypes(IEnumerable<Guid> ids);
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
IEnumerable<IContentType> GetContentTypeChildren(int id);
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
IEnumerable<IContentType> GetContentTypeChildren(Guid id);
/// <summary>
/// Saves a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to save</param>
/// <param name="userId">Optional Id of the User saving the ContentType</param>
void Save(IContentType contentType, int userId = 0);
/// <summary>
/// Saves a collection of <see cref="IContentType"/> objects
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to save</param>
/// <param name="userId">Optional Id of the User saving the ContentTypes</param>
void Save(IEnumerable<IContentType> contentTypes, int userId = 0);
/// <summary>
/// Deletes a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to delete</param>
/// <remarks>Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/></remarks>
/// <param name="userId">Optional Id of the User deleting the ContentType</param>
void Delete(IContentType contentType, int userId = 0);
/// <summary>
/// Deletes a collection of <see cref="IContentType"/> objects
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to delete</param>
/// <remarks>Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/></remarks>
/// <param name="userId">Optional Id of the User deleting the ContentTypes</param>
void Delete(IEnumerable<IContentType> contentTypes, int userId = 0);
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
IMediaType GetMediaType(int id);
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
IMediaType GetMediaType(string alias);
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
IMediaType GetMediaType(Guid id);
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
IEnumerable<IMediaType> GetAllMediaTypes(params int[] ids);
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
IEnumerable<IMediaType> GetAllMediaTypes(IEnumerable<Guid> ids);
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
IEnumerable<IMediaType> GetMediaTypeChildren(int id);
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
IEnumerable<IMediaType> GetMediaTypeChildren(Guid id);
/// <summary>
/// Saves a single <see cref="IMediaType"/> object
/// </summary>
/// <param name="mediaType"><see cref="IMediaType"/> to save</param>
/// <param name="userId">Optional Id of the User saving the MediaType</param>
void Save(IMediaType mediaType, int userId = 0);
/// <summary>
/// Saves a collection of <see cref="IMediaType"/> objects
/// </summary>
/// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to save</param>
/// <param name="userId">Optional Id of the User saving the MediaTypes</param>
void Save(IEnumerable<IMediaType> mediaTypes, int userId = 0);
/// <summary>
/// Deletes a single <see cref="IMediaType"/> object
/// </summary>
/// <param name="mediaType"><see cref="IMediaType"/> to delete</param>
/// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks>
/// <param name="userId">Optional Id of the User deleting the MediaType</param>
void Delete(IMediaType mediaType, int userId = 0);
/// <summary>
/// Deletes a collection of <see cref="IMediaType"/> objects
/// </summary>
/// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to delete</param>
/// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks>
/// <param name="userId">Optional Id of the User deleting the MediaTypes</param>
void Delete(IEnumerable<IMediaType> mediaTypes, int userId = 0);
/// <summary>
/// Generates the complete (simplified) XML DTD.
/// </summary>
/// <returns>The DTD as a string</returns>
string GetDtd();
/// <summary>
/// Generates the complete XML DTD without the root.
/// </summary>
/// <returns>The DTD as a string</returns>
string GetContentTypesDtd();
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
bool HasChildren(int id);
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
bool HasChildren(Guid id);
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
bool MediaTypeHasChildren(int id);
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
bool MediaTypeHasChildren(Guid id);
Attempt<OperationStatus<MoveOperationStatusType>> MoveMediaType(IMediaType toMove, int containerId);
Attempt<OperationStatus<MoveOperationStatusType>> MoveContentType(IContentType toMove, int containerId);
Attempt<OperationStatus<IMediaType, MoveOperationStatusType>> CopyMediaType(IMediaType toCopy, int containerId);
Attempt<OperationStatus<IContentType, MoveOperationStatusType>> CopyContentType(IContentType toCopy, int containerId);
}
}
| |
// 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.Concurrent;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Storage;
using Microsoft.Isam.Esent;
using Microsoft.Isam.Esent.Interop;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Esent
{
internal partial class EsentPersistentStorage : AbstractPersistentStorage
{
// cache delegates so that we don't re-create it every times
private readonly Func<int, object, object, object, CancellationToken, Stream> _readStreamSolution;
private readonly Func<EsentStorage.Key, int, object, object, CancellationToken, Stream> _readStream;
private readonly Func<int, Stream, object, object, CancellationToken, bool> _writeStreamSolution;
private readonly Func<EsentStorage.Key, int, Stream, object, CancellationToken, bool> _writeStream;
private readonly ConcurrentDictionary<string, int> _nameTableCache;
private readonly EsentStorage _esentStorage;
public EsentPersistentStorage(
IOptionService optionService,
string workingFolderPath,
string solutionFilePath,
string databaseFile,
Action<AbstractPersistentStorage> disposer)
: base(optionService, workingFolderPath, solutionFilePath, databaseFile, disposer)
{
// cache delegates
_readStreamSolution = ReadStreamSolution;
_readStream = ReadStream;
_writeStreamSolution = WriteStreamSolution;
_writeStream = WriteStream;
// solution must exist in disk. otherwise, we shouldn't be here at all.
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(solutionFilePath));
_nameTableCache = new ConcurrentDictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var enablePerformanceMonitor = optionService.GetOption(PersistentStorageOptions.EsentPerformanceMonitor);
_esentStorage = new EsentStorage(DatabaseFile, enablePerformanceMonitor);
}
public override void Initialize(Solution solution)
{
_esentStorage.Initialize();
}
public override Task<Stream> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
if (!PersistenceEnabled)
{
return SpecializedTasks.Default<Stream>();
}
if (!TryGetProjectAndDocumentKey(document, out var key) ||
!TryGetUniqueNameId(name, out var nameId))
{
return SpecializedTasks.Default<Stream>();
}
var stream = EsentExceptionWrapper(key, nameId, _readStream, cancellationToken);
return SpecializedTasks.DefaultOrResult(stream);
}
public override Task<Stream> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
if (!PersistenceEnabled)
{
return SpecializedTasks.Default<Stream>();
}
if (!TryGetProjectKey(project, out var key) ||
!TryGetUniqueNameId(name, out var nameId))
{
return SpecializedTasks.Default<Stream>();
}
var stream = EsentExceptionWrapper(key, nameId, _readStream, cancellationToken);
return SpecializedTasks.DefaultOrResult(stream);
}
public override Task<Stream> ReadStreamAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
if (!PersistenceEnabled)
{
return SpecializedTasks.Default<Stream>();
}
if (!TryGetUniqueNameId(name, out var nameId))
{
return SpecializedTasks.Default<Stream>();
}
var stream = EsentExceptionWrapper(nameId, _readStreamSolution, cancellationToken);
return SpecializedTasks.DefaultOrResult(stream);
}
private Stream ReadStream(EsentStorage.Key key, int nameId, object unused1, object unused2, CancellationToken cancellationToken)
{
using (var accessor = GetAccessor(key))
using (var esentStream = accessor.GetReadStream(key, nameId))
{
if (esentStream == null)
{
return null;
}
// this will copy over esent stream and let it go.
return SerializableBytes.CreateReadableStream(esentStream, cancellationToken);
}
}
private Stream ReadStreamSolution(int nameId, object unused1, object unused2, object unused3, CancellationToken cancellationToken)
{
using (var accessor = _esentStorage.GetSolutionTableAccessor())
using (var esentStream = accessor.GetReadStream(nameId))
{
if (esentStream == null)
{
return null;
}
// this will copy over esent stream and let it go.
return SerializableBytes.CreateReadableStream(esentStream, cancellationToken);
}
}
public override Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
Contract.ThrowIfNull(stream);
if (!PersistenceEnabled)
{
return SpecializedTasks.False;
}
if (!TryGetProjectAndDocumentKey(document, out var key) ||
!TryGetUniqueNameId(name, out var nameId))
{
return SpecializedTasks.False;
}
var success = EsentExceptionWrapper(key, nameId, stream, _writeStream, cancellationToken);
return success ? SpecializedTasks.True : SpecializedTasks.False;
}
public override Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
Contract.ThrowIfNull(stream);
if (!PersistenceEnabled)
{
return SpecializedTasks.False;
}
if (!TryGetProjectKey(project, out var key) ||
!TryGetUniqueNameId(name, out var nameId))
{
return SpecializedTasks.False;
}
var success = EsentExceptionWrapper(key, nameId, stream, _writeStream, cancellationToken);
return success ? SpecializedTasks.True : SpecializedTasks.False;
}
public override Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken))
{
Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name));
Contract.ThrowIfNull(stream);
if (!PersistenceEnabled)
{
return SpecializedTasks.False;
}
if (!TryGetUniqueNameId(name, out var nameId))
{
return SpecializedTasks.False;
}
var success = EsentExceptionWrapper(nameId, stream, _writeStreamSolution, cancellationToken);
return success ? SpecializedTasks.True : SpecializedTasks.False;
}
private bool WriteStream(EsentStorage.Key key, int nameId, Stream stream, object unused1, CancellationToken cancellationToken)
{
using (var accessor = GetAccessor(key))
using (var esentStream = accessor.GetWriteStream(key, nameId))
{
WriteToStream(stream, esentStream, cancellationToken);
return accessor.ApplyChanges();
}
}
private bool WriteStreamSolution(int nameId, Stream stream, object unused1, object unused2, CancellationToken cancellationToken)
{
using (var accessor = _esentStorage.GetSolutionTableAccessor())
using (var esentStream = accessor.GetWriteStream(nameId))
{
WriteToStream(stream, esentStream, cancellationToken);
return accessor.ApplyChanges();
}
}
public override void Close()
{
_esentStorage.Close();
}
private bool TryGetUniqueNameId(string name, out int id)
{
return TryGetUniqueId(name, false, out id);
}
private bool TryGetUniqueFileId(string path, out int id)
{
return TryGetUniqueId(path, true, out id);
}
private bool TryGetUniqueId(string value, bool fileCheck, out int id)
{
id = default(int);
if (string.IsNullOrWhiteSpace(value))
{
return false;
}
// if we already know, get the id
if (_nameTableCache.TryGetValue(value, out id))
{
return true;
}
// we only persist for things that actually exist
if (fileCheck && !File.Exists(value))
{
return false;
}
try
{
var uniqueIdValue = fileCheck ? PathUtilities.GetRelativePath(Path.GetDirectoryName(SolutionFilePath), value) : value;
id = _nameTableCache.GetOrAdd(value, _esentStorage.GetUniqueId(uniqueIdValue));
return true;
}
catch (Exception ex)
{
// if we get fatal errors from esent such as disk out of space or log file corrupted by other process and etc
// don't crash VS, but let VS know it can't use esent. we will gracefully recover issue by using memory.
StorageDatabaseLogger.LogException(ex);
return false;
}
}
private static void WriteToStream(Stream inputStream, Stream esentStream, CancellationToken cancellationToken)
{
var buffer = SharedPools.ByteArray.Allocate();
try
{
int bytesRead;
do
{
cancellationToken.ThrowIfCancellationRequested();
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
esentStream.Write(buffer, 0, bytesRead);
}
}
while (bytesRead > 0);
// flush the data and trim column size of necessary
esentStream.Flush();
}
finally
{
SharedPools.ByteArray.Free(buffer);
}
}
private EsentStorage.ProjectDocumentTableAccessor GetAccessor(EsentStorage.Key key)
{
return key.DocumentIdOpt.HasValue ?
_esentStorage.GetDocumentTableAccessor() :
(EsentStorage.ProjectDocumentTableAccessor)_esentStorage.GetProjectTableAccessor();
}
private bool TryGetProjectAndDocumentKey(Document document, out EsentStorage.Key key)
{
key = default(EsentStorage.Key);
if (!TryGetProjectId(document.Project, out var projectId, out var projectNameId) ||
!TryGetUniqueFileId(document.FilePath, out var documentId))
{
return false;
}
key = new EsentStorage.Key(projectId, projectNameId, documentId);
return true;
}
private bool TryGetProjectKey(Project project, out EsentStorage.Key key)
{
key = default(EsentStorage.Key);
if (!TryGetProjectId(project, out var projectId, out var projectNameId))
{
return false;
}
key = new EsentStorage.Key(projectId, projectNameId);
return true;
}
private bool TryGetProjectId(Project project, out int projectId, out int projectNameId)
{
projectId = default(int);
projectNameId = default(int);
return TryGetUniqueFileId(project.FilePath, out projectId) && TryGetUniqueNameId(project.Name, out projectNameId);
}
private TResult EsentExceptionWrapper<TArg1, TResult>(TArg1 arg1, Func<TArg1, object, object, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TResult>(
TArg1 arg1, TArg2 arg2, Func<TArg1, TArg2, object, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, arg2, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TArg3, TResult>(
TArg1 arg1, TArg2 arg2, TArg3 arg3, Func<TArg1, TArg2, TArg3, object, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
return EsentExceptionWrapper(arg1, arg2, arg3, (object)null, func, cancellationToken);
}
private TResult EsentExceptionWrapper<TArg1, TArg2, TArg3, TArg4, TResult>(
TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, Func<TArg1, TArg2, TArg3, TArg4, CancellationToken, TResult> func, CancellationToken cancellationToken)
{
try
{
return func(arg1, arg2, arg3, arg4, cancellationToken);
}
catch (EsentInvalidSesidException)
{
// operation was in-fly when Esent instance was shutdown - ignore the error
}
catch (OperationCanceledException)
{
}
catch (EsentException ex)
{
if (!_esentStorage.IsClosed)
{
// ignore esent exception if underlying storage was closed
// there is not much we can do here.
// internally we use it as a way to cache information between sessions anyway.
// no functionality will be affected by this except perf
Logger.Log(FunctionId.PersistenceService_WriteAsyncFailed, "Esent Failed : " + ex.Message);
}
}
catch (Exception ex)
{
// ignore exception
// there is not much we can do here.
// internally we use it as a way to cache information between sessions anyway.
// no functionality will be affected by this except perf
Logger.Log(FunctionId.PersistenceService_WriteAsyncFailed, "Failed : " + ex.Message);
}
return default(TResult);
}
}
}
| |
//
// TestSuite.System.Security.Cryptography.FromBase64Transform.cs
//
// Author:
// Martin Baulig (martin@gnome.org)
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2002 Ximian, Inc. http://www.ximian.com
// (C) 2004 Novell http://www.novell.com
//
using System;
using System.Security.Cryptography;
using NUnit.Framework;
namespace MonoTests.System.Security.Cryptography {
[TestFixture]
public class FromBase64TransformTest : Assertion {
private FromBase64Transform _algo;
[SetUp]
public void SetUp ()
{
_algo = new FromBase64Transform ();
}
protected void TransformFinalBlock (string name, byte[] input, byte[] expected,
int inputOffset, int inputCount)
{
byte[] output = _algo.TransformFinalBlock (input, inputOffset, inputCount);
AssertEquals (name, expected.Length, output.Length);
for (int i = 0; i < expected.Length; i++)
AssertEquals (name + "(" + i + ")", expected [i], output [i]);
}
protected void TransformFinalBlock (string name, byte[] input, byte[] expected)
{
TransformFinalBlock (name, input, expected, 0, input.Length);
}
[Test]
public void Properties ()
{
Assert ("CanReuseTransform", _algo.CanReuseTransform);
Assert ("CanTransformMultipleBlocks", !_algo.CanTransformMultipleBlocks);
AssertEquals ("InputBlockSize", 1, _algo.InputBlockSize);
AssertEquals ("OutputBlockSize", 3, _algo.OutputBlockSize);
}
[Test]
public void A0 ()
{
byte[] input = { 114, 108, 112, 55, 81, 115, 110, 69 };
byte[] expected = { 174, 90, 123, 66, 201, 196 };
_algo = new FromBase64Transform (FromBase64TransformMode.DoNotIgnoreWhiteSpaces);
TransformFinalBlock ("#A0", input, expected);
}
[Test]
public void A1 ()
{
byte[] input = { 114, 108, 112, 55, 81, 115, 110, 69 };
byte[] expected = { 174, 90, 123, 66, 201, 196 };
TransformFinalBlock ("#A1", input, expected);
}
[Test]
public void A2 ()
{
byte[] input = { 114, 108, 112, 55, 81, 115, 61, 61 };
byte[] expected = { 174, 90, 123, 66 };
TransformFinalBlock ("#A2", input, expected);
}
[Test]
public void A3 ()
{
byte[] input = { 114, 108, 112, 55, 81, 115, 61, 61 };
byte[] expected = { 150, 158, 208 };
TransformFinalBlock ("#A3", input, expected, 1, 5);
}
[Test]
public void IgnoreTAB ()
{
byte[] input = { 9, 114, 108, 112, 55, 9, 81, 115, 61, 61, 9 };
byte[] expected = { 174, 90, 123, 66 };
TransformFinalBlock ("IgnoreTAB", input, expected);
}
[Test]
public void IgnoreLF ()
{
byte[] input = { 10, 114, 108, 112, 55, 10, 81, 115, 61, 61, 10 };
byte[] expected = { 174, 90, 123, 66 };
TransformFinalBlock ("IgnoreLF", input, expected);
}
[Test]
public void IgnoreCR ()
{
byte[] input = { 13, 114, 108, 112, 55, 13, 81, 115, 61, 61, 13 };
byte[] expected = { 174, 90, 123, 66 };
TransformFinalBlock ("IgnoreCR", input, expected);
}
[Test]
public void IgnoreSPACE ()
{
byte[] input = { 32, 114, 108, 112, 55, 32, 81, 115, 61, 61, 32 };
byte[] expected = { 174, 90, 123, 66 };
TransformFinalBlock ("IgnoreSPACE", input, expected);
}
[Test]
[ExpectedException (typeof (FormatException))]
public void DontIgnore ()
{
byte[] input = { 7, 114, 108, 112, 55, 81, 115, 61, 61 };
byte[] expected = { 174, 90, 123, 66 };
TransformFinalBlock ("DontIgnore", input, expected);
}
[Test]
public void ReuseTransform ()
{
byte[] input = { 114, 108, 112, 55, 81, 115, 61, 61 };
byte[] expected = { 174, 90, 123, 66 };
TransformFinalBlock ("UseTransform", input, expected);
TransformFinalBlock ("ReuseTransform", input, expected);
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void ReuseDisposedTransform ()
{
byte[] input = { 114, 108, 112, 55, 81, 115, 61, 61 };
byte[] output = new byte [16];
_algo.Clear ();
_algo.TransformBlock (input, 0, input.Length, output, 0);
}
[Test]
[ExpectedException (typeof (ObjectDisposedException))]
public void ReuseDisposedTransformFinal ()
{
byte[] input = { 114, 108, 112, 55, 81, 115, 61, 61 };
_algo.Clear ();
_algo.TransformFinalBlock (input, 0, input.Length);
}
[Test]
public void InvalidLength ()
{
byte[] input = { 114, 108, 112 };
byte[] result = _algo.TransformFinalBlock (input, 0, input.Length);
AssertEquals ("No result", 0, result.Length);
}
[Test]
public void InvalidData ()
{
byte[] input = { 114, 108, 112, 32 };
byte[] result = _algo.TransformFinalBlock (input, 0, input.Length);
AssertEquals ("No result", 0, result.Length);
}
[Test]
public void Dispose ()
{
byte[] input = { 114, 108, 112, 55, 81, 115, 61, 61 };
byte[] expected = { 174, 90, 123, 66 };
byte[] output = null;
using (ICryptoTransform t = new FromBase64Transform ()) {
output = t.TransformFinalBlock (input, 0, input.Length);
}
AssertEquals ("IDisposable", expected.Length, output.Length);
for (int i = 0; i < expected.Length; i++)
AssertEquals ("IDisposable(" + i + ")", expected [i], output [i]);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void TransformBlock_Input_Null ()
{
byte[] output = new byte [16];
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformBlock (null, 0, output.Length, output, 0);
}
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void TransformBlock_InputOffset_Negative ()
{
byte[] input = new byte [16];
byte[] output = new byte [16];
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformBlock (input, -1, input.Length, output, 0);
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TransformBlock_InputOffset_Overflow ()
{
byte[] input = new byte [16];
byte[] output = new byte [16];
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformBlock (input, Int32.MaxValue, input.Length, output, 0);
}
}
[Test]
[ExpectedException (typeof (OverflowException))]
public void TransformBlock_InputCount_Negative ()
{
byte[] input = new byte [16];
byte[] output = new byte [16];
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformBlock (input, 0, -1, output, 0);
}
}
[Test]
[ExpectedException (typeof (OutOfMemoryException))]
public void TransformBlock_InputCount_Overflow ()
{
byte[] input = new byte [16];
byte[] output = new byte [16];
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformBlock (input, 0, Int32.MaxValue, output, 0);
}
}
[Test]
[ExpectedException (typeof (FormatException))]
public void TransformBlock_Output_Null ()
{
byte[] input = new byte [16];
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformBlock (input, 0, input.Length, null, 0);
}
}
[Test]
[ExpectedException (typeof (FormatException))]
public void TransformBlock_OutputOffset_Negative ()
{
byte[] input = new byte [16];
byte[] output = new byte [16];
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformBlock (input, 0, input.Length, output, -1);
}
}
[Test]
[ExpectedException (typeof (FormatException))]
public void TransformBlock_OutputOffset_Overflow ()
{
byte[] input = new byte [16];
byte[] output = new byte [16];
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformBlock (input, 0, input.Length, output, Int32.MaxValue);
}
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void TransformFinalBlock_Input_Null ()
{
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformFinalBlock (null, 0, 16);
}
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void TransformFinalBlock_InputOffset_Negative ()
{
byte[] input = new byte [16];
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformFinalBlock (input, -1, input.Length);
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TransformFinalBlock_InputOffset_Overflow ()
{
byte[] input = new byte [16];
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformFinalBlock (input, Int32.MaxValue, input.Length);
}
}
[Test]
[ExpectedException (typeof (OverflowException))]
public void TransformFinalBlock_InputCount_Negative ()
{
byte[] input = new byte [16];
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformFinalBlock (input, 0, -1);
}
}
[Test]
[ExpectedException (typeof (OutOfMemoryException))]
public void TransformFinalBlock_InputCount_Overflow ()
{
byte[] input = new byte [16];
using (ICryptoTransform t = new FromBase64Transform ()) {
t.TransformFinalBlock (input, 0, Int32.MaxValue);
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="EntityDataReader.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.EntityClient
{
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
/// <summary>
/// A data reader class for the entity client provider
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
public class EntityDataReader : DbDataReader, IExtendedDataRecord
{
// The command object that owns this reader
private EntityCommand _command;
private CommandBehavior _behavior;
// Store data reader, _storeExtendedDataRecord points to the same reader as _storeDataReader, it's here to just
// save the casting wherever it's used
private DbDataReader _storeDataReader;
private IExtendedDataRecord _storeExtendedDataRecord;
/// <summary>
/// The constructor for the data reader, each EntityDataReader must always be associated with a EntityCommand and an underlying
/// DbDataReader. It is expected that EntityDataReader only has a reference to EntityCommand and doesn't assume responsibility
/// of cleaning the command object, but it does assume responsibility of cleaning up the store data reader object.
/// </summary>
internal EntityDataReader(EntityCommand command, DbDataReader storeDataReader, CommandBehavior behavior)
: base()
{
Debug.Assert(command != null && storeDataReader != null);
this._command = command;
this._storeDataReader = storeDataReader;
this._storeExtendedDataRecord = storeDataReader as IExtendedDataRecord;
this._behavior = behavior;
}
/// <summary>
/// Get the depth of nesting for the current row
/// </summary>
public override int Depth
{
get
{
return this._storeDataReader.Depth;
}
}
/// <summary>
/// Get the number of columns in the current row
/// </summary>
public override int FieldCount
{
get
{
return this._storeDataReader.FieldCount;
}
}
/// <summary>
/// Get whether the data reader has any rows
/// </summary>
public override bool HasRows
{
get
{
return this._storeDataReader.HasRows;
}
}
/// <summary>
/// Get whether the data reader has been closed
/// </summary>
public override bool IsClosed
{
get
{
return this._storeDataReader.IsClosed;
}
}
/// <summary>
/// Get whether the data reader has any rows
/// </summary>
public override int RecordsAffected
{
get
{
return this._storeDataReader.RecordsAffected;
}
}
/// <summary>
/// Get the value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
public override object this[int ordinal]
{
get
{
return this._storeDataReader[ordinal];
}
}
/// <summary>
/// Get the value of a column with the given name
/// </summary>
/// <param name="name">The name of the column to retrieve the value</param>
public override object this[string name]
{
get
{
EntityUtil.CheckArgumentNull(name, "name");
return this._storeDataReader[name];
}
}
/// <summary>
/// Get the number of non-hidden fields in the reader
/// </summary>
public override int VisibleFieldCount
{
get
{
return this._storeDataReader.VisibleFieldCount;
}
}
/// <summary>
/// DataRecordInfo property describing the contents of the record.
/// </summary>
public DataRecordInfo DataRecordInfo
{
get
{
if (null == this._storeExtendedDataRecord)
{
// if a command has no results (e.g. FunctionImport with no return type),
// there is nothing to report.
return null;
}
return this._storeExtendedDataRecord.DataRecordInfo;
}
}
/// <summary>
/// Close this data reader
/// </summary>
public override void Close()
{
if (this._command != null)
{
this._storeDataReader.Close();
// Notify the command object that we are closing, so clean up operations such as copying output parameters can be done
this._command.NotifyDataReaderClosing();
if ((this._behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection)
{
Debug.Assert(this._command.Connection != null);
this._command.Connection.Close();
}
this._command = null;
}
}
/// <summary>
/// Releases the resources used by this data reader
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources, false to release only unmanaged resources</param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
this._storeDataReader.Dispose();
}
}
/// <summary>
/// Get the boolean value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The boolean value</returns>
public override bool GetBoolean(int ordinal)
{
return this._storeDataReader.GetBoolean(ordinal);
}
/// <summary>
/// Get the byte value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The byte value</returns>
public override byte GetByte(int ordinal)
{
return this._storeDataReader.GetByte(ordinal);
}
/// <summary>
/// Get the byte array value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <param name="dataOffset">The index within the row to start reading</param>
/// <param name="buffer">The buffer to copy into</param>
/// <param name="bufferOffset">The index in the buffer indicating where the data is copied into</param>
/// <param name="length">The maximum number of bytes to read</param>
/// <returns>The actual number of bytes read</returns>
public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
{
return this._storeDataReader.GetBytes(ordinal, dataOffset, buffer, bufferOffset, length);
}
/// <summary>
/// Get the char value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The char value</returns>
public override char GetChar(int ordinal)
{
return this._storeDataReader.GetChar(ordinal);
}
/// <summary>
/// Get the char array value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <param name="dataOffset">The index within the row to start reading</param>
/// <param name="buffer">The buffer to copy into</param>
/// <param name="bufferOffset">The index in the buffer indicating where the data is copied into</param>
/// <param name="length">The maximum number of bytes to read</param>
/// <returns>The actual number of characters read</returns>
public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length)
{
return this._storeDataReader.GetChars(ordinal, dataOffset, buffer, bufferOffset, length);
}
/// <summary>
/// Get the name of the data type of the column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the name of the data type</param>
/// <returns>The name of the data type of the column</returns>
public override string GetDataTypeName(int ordinal)
{
return this._storeDataReader.GetDataTypeName(ordinal);
}
/// <summary>
/// Get the datetime value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The datetime value</returns>
public override DateTime GetDateTime(int ordinal)
{
return this._storeDataReader.GetDateTime(ordinal);
}
/// <summary>
/// Get the data reader of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the reader</param>
/// <returns>The data reader</returns>
protected override DbDataReader GetDbDataReader(int ordinal)
{
return this._storeDataReader.GetData(ordinal);
}
/// <summary>
/// Get the decimal value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The decimal value</returns>
public override decimal GetDecimal(int ordinal)
{
return this._storeDataReader.GetDecimal(ordinal);
}
/// <summary>
/// Get the double value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The double value</returns>
public override double GetDouble(int ordinal)
{
return this._storeDataReader.GetDouble(ordinal);
}
/// <summary>
/// Get the data type of the column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the data type</param>
/// <returns>The data type of the column</returns>
public override Type GetFieldType(int ordinal)
{
return this._storeDataReader.GetFieldType(ordinal);
}
/// <summary>
/// Get the float value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The float value</returns>
public override float GetFloat(int ordinal)
{
return this._storeDataReader.GetFloat(ordinal);
}
/// <summary>
/// Get the guid value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The guid value</returns>
public override Guid GetGuid(int ordinal)
{
return this._storeDataReader.GetGuid(ordinal);
}
/// <summary>
/// Get the int16 value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The int16 value</returns>
public override short GetInt16(int ordinal)
{
return this._storeDataReader.GetInt16(ordinal);
}
/// <summary>
/// Get the int32 value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The int32 value</returns>
public override int GetInt32(int ordinal)
{
return this._storeDataReader.GetInt32(ordinal);
}
/// <summary>
/// Get the int64 value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The int64 value</returns>
public override long GetInt64(int ordinal)
{
return this._storeDataReader.GetInt64(ordinal);
}
/// <summary>
/// Get the name of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the name</param>
/// <returns>The name</returns>
public override string GetName(int ordinal)
{
return this._storeDataReader.GetName(ordinal);
}
/// <summary>
/// Get the ordinal of a column with the given name
/// </summary>
/// <param name="name">The name of the column to retrieve the ordinal</param>
/// <returns>The ordinal of the column</returns>
public override int GetOrdinal(string name)
{
EntityUtil.CheckArgumentNull(name, "name");
return this._storeDataReader.GetOrdinal(name);
}
/// <summary>
/// implementation for DbDataReader.GetProviderSpecificFieldType() method
/// </summary>
/// <param name="ordinal"></param>
/// <returns></returns>
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
override public Type GetProviderSpecificFieldType(int ordinal)
{
return _storeDataReader.GetProviderSpecificFieldType(ordinal);
}
/// <summary>
/// implementation for DbDataReader.GetProviderSpecificValue() method
/// </summary>
/// <param name="ordinal"></param>
/// <returns></returns>
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
public override object GetProviderSpecificValue(int ordinal)
{
return _storeDataReader.GetProviderSpecificValue(ordinal);
}
/// <summary>
/// implementation for DbDataReader.GetProviderSpecificValues() method
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
public override int GetProviderSpecificValues(object[] values)
{
return _storeDataReader.GetProviderSpecificValues(values);
}
/// <summary>
/// Get the DataTable that describes the columns of this data reader
/// </summary>
/// <returns>The DataTable describing the columns</returns>
public override DataTable GetSchemaTable()
{
return this._storeDataReader.GetSchemaTable();
}
/// <summary>
/// Get the string value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The string value</returns>
public override string GetString(int ordinal)
{
return this._storeDataReader.GetString(ordinal);
}
/// <summary>
/// Get the value of a column with the given ordinal
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>The value</returns>
public override object GetValue(int ordinal)
{
return this._storeDataReader.GetValue(ordinal);
}
/// <summary>
/// Get the values for all the columns and for the current row
/// </summary>
/// <param name="values">The array where values are copied into</param>
/// <returns>The number of System.Object instances in the array</returns>
public override int GetValues(object[] values)
{
return this._storeDataReader.GetValues(values);
}
/// <summary>
/// Get whether the value of a column is DBNull
/// </summary>
/// <param name="ordinal">The ordinal of the column to retrieve the value</param>
/// <returns>true if the column value is DBNull</returns>
public override bool IsDBNull(int ordinal)
{
return this._storeDataReader.IsDBNull(ordinal);
}
/// <summary>
/// Move the reader to the next result set when reading a batch of statements
/// </summary>
/// <returns>true if there are more result sets</returns>
public override bool NextResult()
{
try
{
return this._storeDataReader.NextResult();
}
catch (Exception e)
{
if (EntityUtil.IsCatchableExceptionType(e))
{
throw EntityUtil.CommandExecution(System.Data.Entity.Strings.EntityClient_StoreReaderFailed, e);
}
throw;
}
}
/// <summary>
/// Move the reader to the next row of the current result set
/// </summary>
/// <returns>true if there are more rows</returns>
public override bool Read()
{
return this._storeDataReader.Read();
}
/// <summary>
/// Get an enumerator for enumerating results over this data reader
/// </summary>
/// <returns>An enumerator for this data reader</returns>
public override IEnumerator GetEnumerator()
{
return this._storeDataReader.GetEnumerator();
}
/// <summary>
/// Used to return a nested DbDataRecord.
/// </summary>
public DbDataRecord GetDataRecord(int i)
{
if (null == this._storeExtendedDataRecord)
{
Debug.Assert(this.FieldCount == 0, "we have fields but no metadata?");
// for a query with no results, any request is out of range...
EntityUtil.ThrowArgumentOutOfRangeException("i");
}
return this._storeExtendedDataRecord.GetDataRecord(i);
}
/// <summary>
/// Used to return a nested result
/// </summary>
public DbDataReader GetDataReader(int i)
{
return this.GetDbDataReader(i);
}
}
}
| |
namespace Python.Test
{
/// <summary>
/// Supports units tests for indexer access.
/// </summary>
public class PublicArrayTest
{
public int[] items;
public PublicArrayTest()
{
items = new int[5] { 0, 1, 2, 3, 4 };
}
}
public class ProtectedArrayTest
{
protected int[] items;
public ProtectedArrayTest()
{
items = new int[5] { 0, 1, 2, 3, 4 };
}
}
public class InternalArrayTest
{
internal int[] items;
public InternalArrayTest()
{
items = new int[5] { 0, 1, 2, 3, 4 };
}
}
public class PrivateArrayTest
{
private int[] items;
public PrivateArrayTest()
{
items = new int[5] { 0, 1, 2, 3, 4 };
}
}
public class BooleanArrayTest
{
public bool[] items;
public BooleanArrayTest()
{
items = new bool[5] { true, false, true, false, true };
}
}
public class ByteArrayTest
{
public byte[] items;
public ByteArrayTest()
{
items = new byte[5] { 0, 1, 2, 3, 4 };
}
}
public class SByteArrayTest
{
public sbyte[] items;
public SByteArrayTest()
{
items = new sbyte[5] { 0, 1, 2, 3, 4 };
}
}
public class CharArrayTest
{
public char[] items;
public CharArrayTest()
{
items = new char[5] { 'a', 'b', 'c', 'd', 'e' };
}
}
public class Int16ArrayTest
{
public short[] items;
public Int16ArrayTest()
{
items = new short[5] { 0, 1, 2, 3, 4 };
}
}
public class Int32ArrayTest
{
public int[] items;
public Int32ArrayTest()
{
items = new int[5] { 0, 1, 2, 3, 4 };
}
}
public class Int64ArrayTest
{
public long[] items;
public Int64ArrayTest()
{
items = new long[5] { 0, 1, 2, 3, 4 };
}
}
public class UInt16ArrayTest
{
public ushort[] items;
public UInt16ArrayTest()
{
items = new ushort[5] { 0, 1, 2, 3, 4 };
}
}
public class UInt32ArrayTest
{
public uint[] items;
public UInt32ArrayTest()
{
items = new uint[5] { 0, 1, 2, 3, 4 };
}
}
public class UInt64ArrayTest
{
public ulong[] items;
public UInt64ArrayTest()
{
items = new ulong[5] { 0, 1, 2, 3, 4 };
}
}
public class SingleArrayTest
{
public float[] items;
public SingleArrayTest()
{
items = new float[5] { 0.0F, 1.0F, 2.0F, 3.0F, 4.0F };
}
}
public class DoubleArrayTest
{
public double[] items;
public DoubleArrayTest()
{
items = new double[5] { 0.0, 1.0, 2.0, 3.0, 4.0 };
}
}
public class DecimalArrayTest
{
public decimal[] items;
public DecimalArrayTest()
{
items = new decimal[5] { 0, 1, 2, 3, 4 };
}
}
public class StringArrayTest
{
public string[] items;
public StringArrayTest()
{
items = new string[5] { "0", "1", "2", "3", "4" };
}
}
public class EnumArrayTest
{
public ShortEnum[] items;
public EnumArrayTest()
{
items = new ShortEnum[5]
{
ShortEnum.Zero,
ShortEnum.One,
ShortEnum.Two,
ShortEnum.Three,
ShortEnum.Four
};
}
}
public class NullArrayTest
{
public object[] items;
public object[] empty;
public NullArrayTest()
{
items = new object[5] { null, null, null, null, null };
empty = new object[0] { };
}
}
public class ObjectArrayTest
{
public object[] items;
public ObjectArrayTest()
{
items = new object[5];
items[0] = new Spam("0");
items[1] = new Spam("1");
items[2] = new Spam("2");
items[3] = new Spam("3");
items[4] = new Spam("4");
}
}
public class InterfaceArrayTest
{
public ISpam[] items;
public InterfaceArrayTest()
{
items = new ISpam[5];
items[0] = new Spam("0");
items[1] = new Spam("1");
items[2] = new Spam("2");
items[3] = new Spam("3");
items[4] = new Spam("4");
}
}
public class TypedArrayTest
{
public Spam[] items;
public TypedArrayTest()
{
items = new Spam[5];
items[0] = new Spam("0");
items[1] = new Spam("1");
items[2] = new Spam("2");
items[3] = new Spam("3");
items[4] = new Spam("4");
}
}
public class MultiDimensionalArrayTest
{
public int[,] items;
public MultiDimensionalArrayTest()
{
items = new int[5, 5]
{
{ 0, 1, 2, 3, 4 },
{ 5, 6, 7, 8, 9 },
{ 10, 11, 12, 13, 14 },
{ 15, 16, 17, 18, 19 },
{ 20, 21, 22, 23, 24 }
};
}
}
public class ArrayConversionTest
{
public static Spam[] EchoRange(Spam[] items)
{
return items;
}
public static Spam[,] EchoRangeMD(Spam[,] items)
{
return items;
}
public static Spam[][] EchoRangeAA(Spam[][] items)
{
return items;
}
}
}
| |
namespace InControl
{
using UnityEngine;
public class TwoAxisInputControl : IInputControl
{
public static readonly TwoAxisInputControl Null = new TwoAxisInputControl();
public float X { get; protected set; }
public float Y { get; protected set; }
public OneAxisInputControl Left { get; protected set; }
public OneAxisInputControl Right { get; protected set; }
public OneAxisInputControl Up { get; protected set; }
public OneAxisInputControl Down { get; protected set; }
public ulong UpdateTick { get; protected set; }
float sensitivity = 1.0f;
float lowerDeadZone = 0.0f;
float upperDeadZone = 1.0f;
float stateThreshold = 0.0f;
public bool Raw;
bool thisState;
bool lastState;
Vector2 thisValue;
Vector2 lastValue;
bool clearInputState;
public TwoAxisInputControl()
{
Left = new OneAxisInputControl();
Right = new OneAxisInputControl();
Up = new OneAxisInputControl();
Down = new OneAxisInputControl();
}
public void ClearInputState()
{
Left.ClearInputState();
Right.ClearInputState();
Up.ClearInputState();
Down.ClearInputState();
lastState = false;
lastValue = Vector2.zero;
thisState = false;
thisValue = Vector2.zero;
X = 0.0f;
Y = 0.0f;
clearInputState = true;
}
// TODO: Is there a better way to handle this? Maybe calculate deltaTime internally.
public void Filter( TwoAxisInputControl twoAxisInputControl, float deltaTime )
{
UpdateWithAxes( twoAxisInputControl.X, twoAxisInputControl.Y, InputManager.CurrentTick, deltaTime );
}
internal void UpdateWithAxes( float x, float y, ulong updateTick, float deltaTime )
{
lastState = thisState;
lastValue = thisValue;
thisValue = Raw ? new Vector2( x, y ) : Utility.ApplyCircularDeadZone( x, y, LowerDeadZone, UpperDeadZone );
X = thisValue.x;
Y = thisValue.y;
Left.CommitWithValue( Mathf.Max( 0.0f, -X ), updateTick, deltaTime );
Right.CommitWithValue( Mathf.Max( 0.0f, X ), updateTick, deltaTime );
if (InputManager.InvertYAxis)
{
Up.CommitWithValue( Mathf.Max( 0.0f, -Y ), updateTick, deltaTime );
Down.CommitWithValue( Mathf.Max( 0.0f, Y ), updateTick, deltaTime );
}
else
{
Up.CommitWithValue( Mathf.Max( 0.0f, Y ), updateTick, deltaTime );
Down.CommitWithValue( Mathf.Max( 0.0f, -Y ), updateTick, deltaTime );
}
thisState = Up.State || Down.State || Left.State || Right.State;
if (clearInputState)
{
lastState = thisState;
lastValue = thisValue;
clearInputState = false;
HasChanged = false;
return;
}
if (thisValue != lastValue)
{
UpdateTick = updateTick;
HasChanged = true;
}
else
{
HasChanged = false;
}
}
public float Sensitivity
{
get
{
return sensitivity;
}
set
{
sensitivity = Mathf.Clamp01( value );
Left.Sensitivity = sensitivity;
Right.Sensitivity = sensitivity;
Up.Sensitivity = sensitivity;
Down.Sensitivity = sensitivity;
}
}
public float StateThreshold
{
get
{
return stateThreshold;
}
set
{
stateThreshold = Mathf.Clamp01( value );
Left.StateThreshold = stateThreshold;
Right.StateThreshold = stateThreshold;
Up.StateThreshold = stateThreshold;
Down.StateThreshold = stateThreshold;
}
}
public float LowerDeadZone
{
get
{
return lowerDeadZone;
}
set
{
lowerDeadZone = Mathf.Clamp01( value );
Left.LowerDeadZone = lowerDeadZone;
Right.LowerDeadZone = lowerDeadZone;
Up.LowerDeadZone = lowerDeadZone;
Down.LowerDeadZone = lowerDeadZone;
}
}
public float UpperDeadZone
{
get
{
return upperDeadZone;
}
set
{
upperDeadZone = Mathf.Clamp01( value );
Left.UpperDeadZone = upperDeadZone;
Right.UpperDeadZone = upperDeadZone;
Up.UpperDeadZone = upperDeadZone;
Down.UpperDeadZone = upperDeadZone;
}
}
public bool State
{
get { return thisState; }
}
public bool LastState
{
get { return lastState; }
}
public Vector2 Value
{
get { return thisValue; }
}
public Vector2 LastValue
{
get { return lastValue; }
}
public Vector2 Vector
{
get { return thisValue; }
}
public bool HasChanged
{
get;
protected set;
}
public bool IsPressed
{
get { return thisState; }
}
public bool WasPressed
{
get { return thisState && !lastState; }
}
public bool WasReleased
{
get { return !thisState && lastState; }
}
public float Angle
{
get
{
return Utility.VectorToAngle( thisValue );
}
}
public static implicit operator bool( TwoAxisInputControl instance )
{
return instance.thisState;
}
public static implicit operator Vector2( TwoAxisInputControl instance )
{
return instance.thisValue;
}
public static implicit operator Vector3( TwoAxisInputControl instance )
{
return instance.thisValue;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="CellTreeNode.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Mapping.ViewGeneration.Structures
{
using System.Collections.Generic;
using System.Data.Common.Utils;
using System.Data.Mapping.ViewGeneration.CqlGeneration;
using System.Data.Mapping.ViewGeneration.QueryRewriting;
using System.Linq;
using System.Text;
// This class represents a node in the update or query mapping view tree
// (of course, the root node represents the full view)
// Each node represents an expression of the form:
// SELECT <Attributes> FROM <Expression> WHERE <Clause>
// The WHERE clause is of the form X1 OR X2 OR ... where each Xi is a multiconstant
internal abstract partial class CellTreeNode : InternalBase
{
#region Constructor
// effects: Creates a cell tree node with a reference to projectedSlotMap for
// deciphering the fields in this
protected CellTreeNode(ViewgenContext context)
{
m_viewgenContext = context;
}
// effects: returns a copy of the tree below node
internal CellTreeNode MakeCopy()
{
DefaultCellTreeVisitor<bool> visitor = new DefaultCellTreeVisitor<bool>();
CellTreeNode result = Accept<bool, CellTreeNode>(visitor, true);
return result;
}
#endregion
#region Fields
private ViewgenContext m_viewgenContext;
#endregion
#region Properties
// effects: Returns the operation being performed by this node
internal abstract CellTreeOpType OpType { get; }
// effects: Returns the right domain map associated with this celltreenode
internal abstract MemberDomainMap RightDomainMap { get; }
internal abstract FragmentQuery LeftFragmentQuery { get; }
internal abstract FragmentQuery RightFragmentQuery { get; }
internal bool IsEmptyRightFragmentQuery
{
get { return !m_viewgenContext.RightFragmentQP.IsSatisfiable(RightFragmentQuery); }
}
// effects: Returns the attributes available/projected from this node
internal abstract Set<MemberPath> Attributes { get; }
// effects: Returns the children of this node
internal abstract List<CellTreeNode> Children { get; }
// effects: Returns the number of slots projected from this node
internal abstract int NumProjectedSlots { get; }
// effects: Returns the number of boolean slots in this node
internal abstract int NumBoolSlots { get; }
internal MemberProjectionIndex ProjectedSlotMap
{
get { return m_viewgenContext.MemberMaps.ProjectedSlotMap; }
}
internal ViewgenContext ViewgenContext
{
get { return m_viewgenContext; }
}
#endregion
#region Abstract Methods
// effects: Given a leaf cell node and the slots required by the parent, returns
// a CqlBlock corresponding to the tree rooted at this
internal abstract CqlBlock ToCqlBlock(bool[] requiredSlots, CqlIdentifiers identifiers, ref int blockAliasNum,
ref List<WithRelationship> withRelationships);
// Effects: Returns true if slot at slot number "slot" is projected
// by some node in tree rooted at this
internal abstract bool IsProjectedSlot(int slot);
// Standard accept method for visitor pattern. TOutput is the return
// type for visitor methods.
internal abstract TOutput Accept<TInput, TOutput>(CellTreeVisitor<TInput, TOutput> visitor, TInput param);
internal abstract TOutput Accept<TInput, TOutput>(SimpleCellTreeVisitor<TInput, TOutput> visitor, TInput param);
#endregion
#region Visitor methods
// effects: Given a cell tree node , removes unnecessary
// "nesting" that occurs in the tree -- an unnecessary nesting
// occurs when a node has exactly one child.
internal CellTreeNode Flatten()
{
return FlatteningVisitor.Flatten(this);
}
// effects: Gets all the leaves in this
internal List<LeftCellWrapper> GetLeaves()
{
return GetLeafNodes().Select(leafNode => leafNode.LeftCellWrapper).ToList();
}
// effects: Gets all the leaves in this
internal IEnumerable<LeafCellTreeNode> GetLeafNodes()
{
return LeafVisitor.GetLeaves(this);
}
// effects: Like Flatten, flattens the tree and then collapses
// associative operators, e.g., (A IJ B) IJ C is changed to A IJ B IJ C
internal CellTreeNode AssociativeFlatten()
{
return AssociativeOpFlatteningVisitor.Flatten(this);
}
#endregion
#region Helper methods, e.g., for slots and strings
// effects: Returns true iff the Op (e.g., IJ) is associative, i.e.,
// A OP (B OP C) is the same as (A OP B) OP C or A OP B OP C
internal static bool IsAssociativeOp(CellTreeOpType opType)
{
// This is not true for LOJ and LASJ
return opType == CellTreeOpType.IJ || opType == CellTreeOpType.Union ||
opType == CellTreeOpType.FOJ;
}
// effects: Returns an array of booleans where bool[i] is set to true
// iff some node in the tree rooted at node projects that slot
internal bool[] GetProjectedSlots()
{
// Gets the information on the normal and the boolean slots
int totalSlots = ProjectedSlotMap.Count + NumBoolSlots;
bool[] slots = new bool[totalSlots];
for (int i = 0; i < totalSlots; i++)
{
slots[i] = IsProjectedSlot(i);
}
return slots;
}
// effects: Given a slot number, slotNum, returns the output member path
// that this slot contributes/corresponds to in the extent view. If
// the slot corresponds to one of the boolean variables, returns null
protected MemberPath GetMemberPath(int slotNum)
{
return ProjectedSlotMap.GetMemberPath(slotNum, NumBoolSlots);
}
// effects: Given the index of a boolean variable (e.g., of from1),
// returns the slot number for that boolean in this
protected int BoolIndexToSlot(int boolIndex)
{
// Booleans appear after the regular slot
return ProjectedSlotMap.BoolIndexToSlot(boolIndex, NumBoolSlots);
}
// effects: Given a slotNum corresponding to a boolean slot, returns
// the cel number that the cell corresponds to
protected int SlotToBoolIndex(int slotNum)
{
return ProjectedSlotMap.SlotToBoolIndex(slotNum, NumBoolSlots);
}
// effects: Returns true if slotNum corresponds to a key slot in the
// output extent view
protected bool IsKeySlot(int slotNum)
{
return ProjectedSlotMap.IsKeySlot(slotNum, NumBoolSlots);
}
// effects: Returns true if slotNum corresponds to a bool slot and
// not a regular field
protected bool IsBoolSlot(int slotNum)
{
return ProjectedSlotMap.IsBoolSlot(slotNum, NumBoolSlots);
}
// effects: Returns the slot numbers corresponding to the key fields
// in the m_projectedSlotMap
protected IEnumerable<int> KeySlots
{
get
{
int numMembers = ProjectedSlotMap.Count;
for (int slotNum = 0; slotNum < numMembers; slotNum++)
{
if (true == IsKeySlot(slotNum))
{
yield return slotNum;
}
}
}
}
// effects: Modifies builder to contain a Cql query corresponding to
// the tree rooted at this
internal override void ToFullString(StringBuilder builder)
{
int blockAliasNum = 0;
// Get the required slots, get the block and then get the string
bool[] requiredSlots = GetProjectedSlots();
// Using empty identifiers over here since we do not use this for the actual CqlGeneration
CqlIdentifiers identifiers = new CqlIdentifiers();
List<WithRelationship> withRelationships = new List<WithRelationship>();
CqlBlock block = ToCqlBlock(requiredSlots, identifiers, ref blockAliasNum, ref withRelationships);
block.AsEsql(builder, false, 1);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using Xunit;
namespace System.Globalization.CalendarTests
{
// GregorianCalendar.GetMonth(DateTime)
public class GregorianCalendarGetMonth
{
private const int c_DAYS_IN_LEAP_YEAR = 366;
private const int c_DAYS_IN_COMMON_YEAR = 365;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
#region Positive tests
// PosTest1: the speicified time is in leap year, February
[Fact]
public void PosTest1()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
DateTime time;
int year, month;
int expectedMonth, actualMonth;
year = GetALeapYear(myCalendar);
month = 2;
time = myCalendar.ToDateTime(year, month, 29, 10, 30, 12, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest2: the speicified time is in leap year, any month other than February
[Fact]
public void PosTest2()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = GetALeapYear(myCalendar);
//Get a random value beween 1 and 12 not including 2.
do
{
month = _generator.GetInt32(-55) % 12 + 1;
} while (2 == month);
time = myCalendar.ToDateTime(year, month, 28, 10, 30, 20, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest3: the speicified time is in common year, February
[Fact]
public void PosTest3()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = GetACommonYear(myCalendar);
month = 2;
time = myCalendar.ToDateTime(year, month, 28, 10, 20, 30, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest4: the speicified time is in common year, any month other than February
[Fact]
public void PosTest4()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = GetACommonYear(myCalendar);
//Get a random value beween 1 and 12 not including 2.
do
{
month = _generator.GetInt32(-55) % 12 + 1;
} while (2 == month);
time = myCalendar.ToDateTime(year, month, 28, 10, 30, 20, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest5: the speicified time is in minimum supported year, any month
[Fact]
public void PosTest5()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = myCalendar.MinSupportedDateTime.Year;
month = _generator.GetInt32(-55) % 12 + 1;
time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest6: the speicified time is in maximum supported year, any month
[Fact]
public void PosTest6()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = myCalendar.MaxSupportedDateTime.Year;
month = _generator.GetInt32(-55) % 12 + 1;
time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest7: the speicified time is in any year, minimum month
[Fact]
public void PosTest7()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = myCalendar.MinSupportedDateTime.Year;
month = 1;
time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest8: the speicified time is in any year, maximum month
[Fact]
public void PosTest8()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = myCalendar.MaxSupportedDateTime.Year;
month = 12;
time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest9: the speicified time is in any year, any month
[Fact]
public void PosTest9()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = GetAYear(myCalendar);
month = _generator.GetInt32(-55) % 12 + 1;
time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
#endregion
#region Helper methods for all the tests
//Indicate whether the specified year is leap year or not
private bool IsLeapYear(int year)
{
if (0 == year % 400 || (0 != year % 100 && 0 == (year & 0x3)))
{
return true;
}
return false;
}
//Get a random year beween minmum supported year and maximum supported year of the specified calendar
private int GetAYear(Calendar calendar)
{
int retVal;
int maxYear, minYear;
maxYear = calendar.MaxSupportedDateTime.Year;
minYear = calendar.MinSupportedDateTime.Year;
retVal = minYear + _generator.GetInt32(-55) % (maxYear + 1 - minYear);
return retVal;
}
//Get a leap year of the specified calendar
private int GetALeapYear(Calendar calendar)
{
int retVal;
// A leap year is any year divisible by 4 except for centennial years(those ending in 00)
// which are only leap years if they are divisible by 400.
retVal = ~(~GetAYear(calendar) | 0x3); // retVal will be divisible by 4 since the 2 least significant bits will be 0
retVal = (0 != retVal % 100) ? retVal : (retVal - retVal % 400); // if retVal is divisible by 100 subtract years from it to make it divisible by 400
// if retVal was 100, 200, or 300 the above logic will result in 0
if (0 == retVal)
{
retVal = 400;
}
return retVal;
}
//Get a common year of the specified calendar
private int GetACommonYear(Calendar calendar)
{
int retVal;
do
{
retVal = GetAYear(calendar);
}
while ((0 == (retVal & 0x3) && 0 != retVal % 100) || 0 == retVal % 400);
return retVal;
}
//Get text represntation of the input parmeters
private string GetParamsInfo(int year)
{
string str;
str = string.Format("\nThe specified year is {0:04}(yyyy).", year);
return str;
}
//Get text represntation of the input parmeters
private string GetParamsInfo(DateTime time)
{
string str;
str = string.Format("\nThe specified time is ({0}).", time);
return str;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.MirrorSequences
{
using Microsoft.Rest;
using Models;
/// <summary>
/// A sample API that uses a petstore as an example to demonstrate
/// features in the swagger-2.0 specification
/// </summary>
public partial class SequenceRequestResponseTest : Microsoft.Rest.ServiceClient<SequenceRequestResponseTest>, ISequenceRequestResponseTest
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the SequenceRequestResponseTest class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SequenceRequestResponseTest(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SequenceRequestResponseTest class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SequenceRequestResponseTest(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SequenceRequestResponseTest class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SequenceRequestResponseTest(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SequenceRequestResponseTest class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SequenceRequestResponseTest(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new System.Uri("http://petstore.swagger.wordnik.com/api");
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <summary>
/// Creates a new pet in the store. Duplicates are allowed
/// </summary>
/// <param name='pets'>
/// Pets to add to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorModelException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Pet>>> AddPetWithHttpMessagesAsync(System.Collections.Generic.IList<Pet> pets, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (pets == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "pets");
}
if (pets != null)
{
foreach (var element in pets)
{
if (element != null)
{
element.Validate();
}
}
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("pets", pets);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "AddPet", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(pets != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(pets, this.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorModel _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorModel>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Pet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<Pet>>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Adds new pet stylesin the store. Duplicates are allowed
/// </summary>
/// <param name='petStyle'>
/// Pet style to add to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<int?>>> AddPetStylesWithHttpMessagesAsync(System.Collections.Generic.IList<int?> petStyle, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (petStyle == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "petStyle");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("petStyle", petStyle);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "AddPetStyles", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "primitives").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(petStyle != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
System.Collections.Generic.IList<ErrorModel> _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<ErrorModel>>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<int?>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<int?>>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates new pet stylesin the store. Duplicates are allowed
/// </summary>
/// <param name='petStyle'>
/// Pet style to add to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<int?>>> UpdatePetStylesWithHttpMessagesAsync(System.Collections.Generic.IList<int?> petStyle, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (petStyle == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "petStyle");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("petStyle", petStyle);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "UpdatePetStyles", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "primitives").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(petStyle != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
System.Collections.Generic.IList<ErrorModel> _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<ErrorModel>>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<int?>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<int?>>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
namespace TestSimpleTypes1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Test
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
/*
* Assumes CLR supports:
* - Native types (int*, uint*, string)
* - Native binary/unary operations
* - Copying and changing context
* - Arraies
* - System.Object API
* - System.Console.Write*
* - System.String API (=string)
*
* CLR will not be tested for:
* - Pointers (See TestSimpleTypes2)
* - Exceptions (See TestSimpleTypes2)
* - References (See TestSimpleTypes3)
* - Classes (See TestSimpleTypes3)
* - ValueTypes (See TestSimpleTypes3)
* - Corlib (See TestSimpleTypes4)
*
* - Floating points
* (Which is not implemented in ring0 only as emulator)
*/
public static void Main(string[] args)
{
System.Console.WriteLine("Hello eric!");
System.Console.WriteLine("TestSimpleTypes1::Test::Main()");
System.Console.WriteLine();
System.Console.WriteLine("Executing first test: Native Type test...");
testCopying();
System.Console.WriteLine("Executing second test: boxed objects...");
testNativeBoxedObjects();
System.Console.WriteLine();
System.Console.WriteLine();
System.Console.WriteLine("Tests: OK!");
}
// Static variable with initializer
public static int m6 = 6;
/*
* Transform a number into binary string
*/
static unsafe string printBinary(uint number)
{
string ret = "";
uint numberOfBits = sizeof(uint) * 8;
for (uint i = 0; i < numberOfBits; i++)
{
if ((number & 1) == 1)
ret = "1" + ret;
else
ret = "0" + ret;
number = number >> 1;
}
return ret;
}
/*
* Test:
* Binary operators:
* - Arithmetic + - * / %
* - Logical (boolean and bitwise) & | ^ ! ~ && ||
* true false
* - Relational == != < > <= >=
* - Shift << >>
* Unary operators:
* - Increment, decrement ++ --
*
* Assignment = += -= *= /= %= &= |= ^= <<= >>=
*/
static void testCopying()
{
// Local stack: Define the default system integer types
System.Byte uint8; System.SByte int8;
System.UInt16 uint16; System.Int16 int16;
System.UInt16 uint16_2;
System.UInt32 uint32; System.Int32 int32;
System.UInt64 uint64; System.Int64 int64;
bool boolean;
uint16 = 6655;
uint16_2 = uint16;
uint16 = 7788;
if (uint16_2 != 6655)
{
System.Console.WriteLine(" ERROR Copy-on-write " + uint16_2 + uint16);
}
else
{
System.Console.WriteLine(" PASS " + uint16 + " " + uint16_2 +
" = 7788 6655");
}
uint8 = (byte)m6; // operator = (static)
int8 = 2; // operator = (immediate)
int64 = -13;
int64+= (m6 * 3); // operator *
int64++;
int32 = int8; // operator = (local)
int32*= 3;
if (int32 != int64) // Test operator != and block jump
{
System.Console.Write(" ERROR1 ");
System.Console.WriteLine("(" + int32 + " != " + int64 + ")");
}
if (int64 == m6)
{
System.Console.Write(" PASS ");
System.Console.WriteLine("(" + int32 + " == " + int64 + " == " + m6 + ")");
} else
{
System.Console.Write(" ERROR2 ");
System.Console.WriteLine("(" + int32 + " != " + int64 + ")");
}
// Test operator <, > signed and unsigned
int16 = -5;
uint16 = (System.UInt16)int16;
if (int16 < 0)
System.Console.WriteLine(" PASS (" + int16 + " (unsigned) " + uint16 + ")");
if (uint16 < 0)
System.Console.WriteLine(" ERROR3 ");
// Signed / unsigned convert
if (int16 == uint16)
System.Console.WriteLine(" ERROR4 ");
if (int16 >= uint16)
System.Console.WriteLine(" ERROR5 ");
else
System.Console.WriteLine(" PASS (signed.unsigned)");
// Test boolean operations
boolean = true;
boolean = boolean && false;
if (boolean)
System.Console.WriteLine(" ERROR6");
else
System.Console.WriteLine(" PASS");
boolean = boolean || true;
if (boolean)
System.Console.WriteLine(" PASS");
else
System.Console.WriteLine(" ERROR7");
if (!boolean)
System.Console.WriteLine(" ERROR8");
else
System.Console.WriteLine(" PASS");
// Test bitwise operation
uint32 = 0xAA;
System.Console.WriteLine(" PASS (" + printBinary(uint32) + ")");
uint32 = ~uint32;
System.Console.WriteLine(" PASS (" + printBinary(uint32) + ")");
uint64 = uint32;
if (System.Object.ReferenceEquals(uint64, uint32))
System.Console.WriteLine(" ERROR10");
else
System.Console.WriteLine(" PASS");
printBinaryFormat(1 +
0x100 +
0x102 +
0x1000 +
0x1001 +
0x1002 +
0xF000000,
5);
}
/*
* Recursive function which print a 2D triangle picture from a number
*/
static void printBinaryFormat(uint num, int itr)
{
if (itr <= 0)
return;
System.Console.WriteLine(printBinary(num));
printBinaryFormat((num << 1) | num, itr - 1);
System.Console.WriteLine(printBinary(num));
}
/*
*
*/
static unsafe void testNativeBoxedObjects()
{
// Local stack: Define the default system integer types
System.Byte uint8; System.SByte int8;
System.UInt16 uint16; System.Int16 int16;
System.UInt32 uint32; System.Int32 int32;
System.UInt64 uint64; System.Int64 int64;
char character;
bool boolean;
uint8 = 255;
int8 = (System.SByte)uint8; // signed to unsigned cast
if ((int8.ToString() == "-1") &&
(uint8.ToString() == "255") &&
(int8.GetType().ToString() == "System.SByte") &&
(uint8.GetType().ToString() != "System.SByte") &&
(uint8.GetType().ToString() == "System.Byte"))
{
System.Console.WriteLine(" PASS [" +
uint8.GetType().ToString() + ", " +
int8.GetType().ToString() + "]");
} else
{
System.Console.WriteLine(" ERROR1");
System.Console.WriteLine(" Repeating tests...");
if ((int8.ToString() != "-1")) {
System.Console.WriteLine(" int8.ToString(): ", int8.ToString());
}
if ((uint8.ToString() != "255"))
{
System.Console.WriteLine(" uint8.ToString(): ", uint8.ToString());
}
System.Console.WriteLine(" ", int8.GetType().ToString());
System.Console.WriteLine(" ", uint8.GetType().ToString());
}
}
/*
* String concatenation +
* Member access .
* Indexing []
* Cast ()
* Conditional ?:
* Delegate concatenation and removal + -
* Object creation new
* Type information is sizeof typeof
* Overflow exception control: checked unchecked
* Indirection and Address * -> [] &
*/
}
}
| |
// <copyright file=HandleUtils company=Hydra>
// Copyright (c) 2015 All Rights Reserved
// </copyright>
// <author>Christopher Cameron</author>
using System;
using System.Reflection;
using Hydra.HydraCommon.Utils;
using Hydra.HydraCommon.Utils.Shapes._3d;
using UnityEditor;
using UnityEngine;
namespace Hydra.HydraCommon.Editor.Utils
{
/// <summary>
/// HandleUtils provides utility methods for drawing handles.
/// </summary>
public static class HandleUtils
{
public const float DOT_SIZE = 0.04f;
public const string HANDLE_WIRE_MATERIAL_PROPERTY_NAME = "handleWireMaterial";
private static Triangle3d[] s_WireTriangles;
private static readonly PropertyInfo s_HandleWireMaterialProperty;
/// <summary>
/// Initializes the HandleUtils class.
/// </summary>
static HandleUtils()
{
s_HandleWireMaterialProperty = ReflectionUtils.GetPropertyByName(typeof(HandleUtility),
HANDLE_WIRE_MATERIAL_PROPERTY_NAME);
if (s_HandleWireMaterialProperty == null)
throw new Exception("The handles wire material property has been moved. Unity, please make this property public.");
}
#region Properties
/// <summary>
/// Gets the handle wire material.
/// </summary>
/// <value>The handle wire material.</value>
public static Material handleWireMaterial
{
get { return s_HandleWireMaterialProperty.GetValue(null, new object[0]) as Material; }
}
#endregion
#region Methods
/// <summary>
/// Begins GL drawing with the current handles settings.
/// (this is taken from the Handles.DrawLine method)
/// </summary>
/// <param name="mode">Mode.</param>
/// <param name="material">Material.</param>
public static void BeginGL(int mode, Material material)
{
material.SetPass(0);
GL.PushMatrix();
GL.MultMatrix(Handles.matrix);
GL.Begin(mode);
Color color = Handles.color * new Color(1.0f, 1.0f, 1.0f, 0.75f);
GL.Color(color);
}
/// <summary>
/// Ends GL drawing for handles.
/// </summary>
public static void EndGL()
{
GL.End();
GL.PopMatrix();
}
/// <summary>
/// Returns a normalized direction towards the camera from the given position,
/// considering the current handles matrix.
/// </summary>
/// <returns>The direction to the camera.</returns>
/// <param name="position">Position.</param>
public static Vector3 ToCamera(Vector3 position)
{
Matrix4x4 matrix = Handles.inverseMatrix;
Vector3 cameraPos = Camera.current.transform.position;
return matrix.MultiplyPoint(cameraPos) - position;
}
/// <summary>
/// Gets the dot size.
/// </summary>
/// <returns>The dot size.</returns>
/// <param name="position">Position.</param>
public static float GetDotSize(Vector3 position)
{
return HandleUtility.GetHandleSize(position) * DOT_SIZE;
}
/// <summary>
/// Draws a dot at the given position.
/// </summary>
/// <param name="position">Position.</param>
public static void DrawDot(Vector3 position)
{
Handles.DotCap(0, position, Quaternion.identity, GetDotSize(position));
}
/// <summary>
/// Draws the wireframe.
/// </summary>
/// <param name="mesh">Mesh.</param>
public static void DrawWireframe(Mesh mesh)
{
MeshUtils.ToTriangles(mesh, ref s_WireTriangles);
BeginGL(GL.LINES, handleWireMaterial);
for (int index = 0; index < s_WireTriangles.Length; index++)
{
Triangle3d triangle = s_WireTriangles[index];
if (Vector3.Dot(triangle.normal, ToCamera(triangle.centroid)) < 0.0f)
continue;
GL.Vertex(triangle.pointA);
GL.Vertex(triangle.pointB);
GL.Vertex(triangle.pointB);
GL.Vertex(triangle.pointC);
GL.Vertex(triangle.pointC);
GL.Vertex(triangle.pointA);
}
EndGL();
}
/// <summary>
/// Draws the verts.
/// </summary>
/// <param name="mesh">Mesh.</param>
public static void DrawVerts(Mesh mesh)
{
Vector3[] verts = mesh.vertices;
Vector3[] normals = mesh.normals;
for (int index = 0; index < verts.Length; index++)
{
Vector3 position = verts[index];
if (Vector3.Dot(normals[index], ToCamera(position)) > 0.0f)
DrawDot(position);
}
}
/// <summary>
/// Draws a box size handle.
/// </summary>
/// <returns>The new box size.</returns>
/// <param name="rotation">Rotation.</param>
/// <param name="position">Position.</param>
/// <param name="size">Size.</param>
public static Vector3 BoxSizeHandle(Quaternion rotation, Vector3 position, Vector3 size)
{
float xMin = size.x * -0.5f + position.x;
float xMax = size.x * 0.5f + position.x;
float yMin = size.y * -0.5f + position.y;
float yMax = size.y * 0.5f + position.y;
float zMin = size.z * -0.5f + position.z;
float zMax = size.z * 0.5f + position.z;
// Bottom square
Handles.DrawLine(rotation * new Vector3(xMin, yMin, zMin), rotation * new Vector3(xMin, yMin, zMax));
Handles.DrawLine(rotation * new Vector3(xMax, yMin, zMin), rotation * new Vector3(xMax, yMin, zMax));
Handles.DrawLine(rotation * new Vector3(xMin, yMin, zMin), rotation * new Vector3(xMax, yMin, zMin));
Handles.DrawLine(rotation * new Vector3(xMin, yMin, zMax), rotation * new Vector3(xMax, yMin, zMax));
// Top square
Handles.DrawLine(rotation * new Vector3(xMin, yMax, zMin), rotation * new Vector3(xMin, yMax, zMax));
Handles.DrawLine(rotation * new Vector3(xMax, yMax, zMin), rotation * new Vector3(xMax, yMax, zMax));
Handles.DrawLine(rotation * new Vector3(xMin, yMax, zMin), rotation * new Vector3(xMax, yMax, zMin));
Handles.DrawLine(rotation * new Vector3(xMin, yMax, zMax), rotation * new Vector3(xMax, yMax, zMax));
// Struts
Handles.DrawLine(rotation * new Vector3(xMin, yMin, zMin), rotation * new Vector3(xMin, yMax, zMin));
Handles.DrawLine(rotation * new Vector3(xMin, yMin, zMax), rotation * new Vector3(xMin, yMax, zMax));
Handles.DrawLine(rotation * new Vector3(xMax, yMin, zMin), rotation * new Vector3(xMax, yMax, zMin));
Handles.DrawLine(rotation * new Vector3(xMax, yMin, zMax), rotation * new Vector3(xMax, yMax, zMax));
// Dots
Vector3 dotPosition = rotation * new Vector3(position.x, yMax, position.z);
size += Vector3.up * NormalMoveHandle(dotPosition, rotation, rotation * Vector3.up) * 2.0f;
dotPosition = rotation * new Vector3(position.x, yMin, position.z);
size += Vector3.up * NormalMoveHandle(dotPosition, rotation, rotation * Vector3.down) * 2.0f;
dotPosition = rotation * new Vector3(position.x, position.y, zMax);
size += Vector3.forward * NormalMoveHandle(dotPosition, rotation, rotation * Vector3.forward) * 2.0f;
dotPosition = rotation * new Vector3(position.x, position.y, zMin);
size += Vector3.forward * NormalMoveHandle(dotPosition, rotation, rotation * Vector3.back) * 2.0f;
dotPosition = rotation * new Vector3(xMax, position.y, position.z);
size += Vector3.right * NormalMoveHandle(dotPosition, rotation, rotation * Vector3.right) * 2.0f;
dotPosition = rotation * new Vector3(xMin, position.y, position.z);
size += Vector3.right * NormalMoveHandle(dotPosition, rotation, rotation * Vector3.left) * 2.0f;
return size;
}
/// <summary>
/// Draws a dot cap handle that returns the distance it was dragged along its normal.
/// </summary>
/// <returns>The distance the cap was dragged.</returns>
/// <param name="position">Position.</param>
/// <param name="rotation">Rotation.</param>
/// <param name="normal">Normal.</param>
public static float NormalMoveHandle(Vector3 position, Quaternion rotation, Vector3 normal)
{
Color oldColor = Handles.color;
// Check if the face is facing the other direction
if (Vector3.Dot(normal, ToCamera(position)) < 0.0f)
Handles.color *= new Color(1.0f, 1.0f, 1.0f, 0.5f);
Vector3 newPosition = Handles.FreeMoveHandle(position, rotation, GetDotSize(position), Vector3.zero, Handles.DotCap);
Handles.color = oldColor;
if (newPosition == position)
return 0.0f;
Vector3 newVector = newPosition - position;
if (HydraMathUtils.Approximately(Vector3.Dot(newVector, normal), 0.0f))
return 0.0f;
// Calculate how far the point was dragged along the normal
float angle = Vector3.Angle(normal, newVector);
bool positive = (angle < 90.0f);
if (angle > 90.0f)
angle = 180.0f - angle;
float adjacent = Mathf.Cos(Mathf.Deg2Rad * angle) * newVector.magnitude;
return (positive) ? adjacent * 1.0f : adjacent * -1.0f;
}
/// <summary>
/// As of writing, the Unity radius handle is visually broken when setting the handles matrix.
/// </summary>
/// <returns>The radius.</returns>
/// <param name="rotation">Rotation.</param>
/// <param name="position">Position.</param>
/// <param name="radius">Radius.</param>
public static float RadiusHandle(Quaternion rotation, Vector3 position, float radius)
{
radius = CircleRadiusHandle(rotation, position, radius);
radius = CircleRadiusHandle(rotation * Quaternion.Euler(90.0f, 0.0f, 0.0f), position, radius);
return CircleRadiusHandle(rotation * Quaternion.Euler(0.0f, 90.0f, 0.0f), position, radius);
}
/// <summary>
/// Draws a HemiSphere radius handle.
/// </summary>
/// <returns>The new HemiSphere radius.</returns>
/// <param name="rotation">Rotation.</param>
/// <param name="position">Position.</param>
/// <param name="radius">Radius.</param>
public static float HemiSphereRadiusHandle(Quaternion rotation, Vector3 position, float radius)
{
// Draw the circle
radius = CircleRadiusHandle(rotation, position, radius);
// Draw the arcs
Quaternion arcRotation = Quaternion.Euler(0.0f, 90.0f, 0.0f);
Handles.DrawWireArc(position, rotation * arcRotation * Vector3.forward, rotation * arcRotation * Vector3.up, 180.0f,
radius);
arcRotation = Quaternion.Euler(90.0f, 90.0f, 0.0f);
Handles.DrawWireArc(position, rotation * arcRotation * Vector3.forward, rotation * arcRotation * Vector3.up, 180.0f,
radius);
// Draw the arcs dot
Vector3 dotPosition = position + rotation * Vector3.forward * radius;
radius += NormalMoveHandle(dotPosition, rotation, rotation * Vector3.forward);
return radius;
}
/// <summary>
/// Draws a circle radius handle.
/// </summary>
/// <returns>The new radius.</returns>
/// <param name="rotation">Rotation.</param>
/// <param name="position">Position.</param>
/// <param name="radius">Radius.</param>
public static float CircleRadiusHandle(Quaternion rotation, Vector3 position, float radius)
{
Handles.DrawWireDisc(position, rotation * Vector3.forward, radius);
Vector3 dotPosition = position + rotation * Vector3.up * radius;
radius += NormalMoveHandle(dotPosition, rotation, rotation * Vector3.up);
dotPosition = position + rotation * Vector3.down * radius;
radius += NormalMoveHandle(dotPosition, rotation, rotation * Vector3.down);
dotPosition = position + rotation * Vector3.left * radius;
radius += NormalMoveHandle(dotPosition, rotation, rotation * Vector3.left);
dotPosition = position + rotation * Vector3.right * radius;
radius += NormalMoveHandle(dotPosition, rotation, rotation * Vector3.right);
return radius;
}
/// <summary>
/// Draws a cone size handle.
/// </summary>
/// <returns>The radius, angle and length in a Vector3 tuple.</returns>
/// <param name="rotation">Rotation.</param>
/// <param name="position">Position.</param>
/// <param name="radius">Radius.</param>
/// <param name="angle">Angle.</param>
/// <param name="length">Length.</param>
public static Vector3 ConeSizeHandle(Quaternion rotation, Vector3 position, float radius, float angle, float length)
{
// Base circle
radius = CircleRadiusHandle(rotation, position, radius);
// Now we need to do some maths to get the radius of the secondary circle
float secondaryRadius = radius + Mathf.Tan(Mathf.Deg2Rad * angle) * length;
// Draw the struts
Vector3 secondaryCirclePosition = position + rotation * Vector3.forward * length;
Handles.DrawLine(position + rotation * Vector3.up * radius,
secondaryCirclePosition + rotation * Vector3.up * secondaryRadius);
Handles.DrawLine(position + rotation * Vector3.down * radius,
secondaryCirclePosition + rotation * Vector3.down * secondaryRadius);
Handles.DrawLine(position + rotation * Vector3.left * radius,
secondaryCirclePosition + rotation * Vector3.left * secondaryRadius);
Handles.DrawLine(position + rotation * Vector3.right * radius,
secondaryCirclePosition + rotation * Vector3.right * secondaryRadius);
// Draw the secondary circle
float newSecondaryRadius = CircleRadiusHandle(rotation, secondaryCirclePosition, secondaryRadius);
newSecondaryRadius = HydraMathUtils.Max(newSecondaryRadius, radius);
if (!HydraMathUtils.Approximately(newSecondaryRadius, secondaryRadius))
{
float delta = newSecondaryRadius - radius;
angle = Mathf.Rad2Deg * Mathf.Atan(delta / length);
}
// Draw the dot in the middle of the secondary circle
length += NormalMoveHandle(secondaryCirclePosition, rotation, rotation * Vector3.forward);
return new Vector3(radius, angle, length);
}
#endregion
}
}
| |
using Xunit;
using System.Reflection;
using DotNetCoreKoans.Engine;
using System;
using System.Text;
using System.Linq;
namespace DotNetCoreKoans.Koans
{
public class AboutDelegates : Koan
{
//A delegate is a user defined type just like a class.
//A delegate lets you reference methods with the same signature and return type.
//Once you have the reference to the method, pass them as parameters or call it via the delegate.
//In other languages this is known as functions as first class citizens.
//Here is a delegate declaration
delegate int BinaryOp(int lhs, int rhs);
private class MyMath
{
//Add has the same signature as BinaryOp
public int Add(int lhs, int rhs)
{
return lhs + rhs;
}
public static int Subtract(int lhs, int rhs)
{
return lhs - rhs;
}
}
[Step(1)]
public void DelegatesAreReferenceTypes()
{
//If you don't initialize a delegate it will be a null value, just as any other refrence type.
BinaryOp op;
Assert.Null(FILL_ME_IN);
}
[Step(2)]
public void DelegatesCanBeInstantiated()
{
MyMath math = new MyMath();
BinaryOp op = new BinaryOp(math.Add);
Assert.Equal(FILL_ME_IN, op.GetMethodInfo().Name);
}
[Step(3)]
public void DelegatesCanBeAssigned()
{
MyMath math = new MyMath();
BinaryOp op = math.Add;
Assert.Equal(FILL_ME_IN, op.GetMethodInfo().Name);
}
[Step(4)]
public void DelegatesCanReferenceStaticMethods()
{
BinaryOp op = MyMath.Subtract;
Assert.Equal(FILL_ME_IN, op.GetMethodInfo().Name);
}
[Step(5)]
public void MethodsCalledViaDelegate()
{
MyMath math = new MyMath();
BinaryOp op = math.Add;
Assert.Equal(FILL_ME_IN, op(3, 3));
}
private void PassMeTheDelegate(BinaryOp passed)
{
Assert.Equal(FILL_ME_IN, passed(3, 3));
}
[Step(6)]
public void DelegatesCanBePassed()
{
MyMath math = new MyMath();
BinaryOp op = math.Add;
PassMeTheDelegate(op);
}
[Step(7)]
public void MethodCanBePassedDirectly()
{
MyMath math = new MyMath();
PassMeTheDelegate(math.Add);
}
[Step(8)]
public void DelegatesAreImmutable()
{
//Like strings it looks like you can change what a delegate references, but really they are immutable objects
MyMath m = new MyMath();
BinaryOp a = m.Add;
BinaryOp original = a;
Assert.Same(a, original);
a = MyMath.Subtract;
//a is now a different instance
Assert.Same(a, original);
}
delegate int Curry(int val);
public class FunctionalTricks
{
public int Add5(int x)
{
return x + 5;
}
public int Add10(int x)
{
return x + 10;
}
}
[Step(9)]
public void DelegatesHaveAnInvocationList()
{
FunctionalTricks f = new FunctionalTricks();
Curry adding = f.Add5;
//So far we've only seen one method attached to a delegate.
Assert.Equal(FILL_ME_IN, adding.GetInvocationList().Length);
//However, you can attach multiple methods to a delegate
adding += f.Add10;
Assert.Equal(FILL_ME_IN, adding.GetInvocationList().Length);
}
[Step(10)]
public void OnlyLastResultReturned()
{
FunctionalTricks f = new FunctionalTricks();
Curry adding = f.Add5;
adding += f.Add10;
//Delegates may have more than one method attached, but only the result of the last method is returned.
Assert.Equal(FILL_ME_IN, adding(5));
}
[Step(11)]
public void RemovingMethods()
{
FunctionalTricks f = new FunctionalTricks();
Curry adding = f.Add5;
adding += f.Add10;
Assert.Equal(2, adding.GetInvocationList().Length);
//Remove Add5 from the invocation list
Assert.Equal(1, adding.GetInvocationList().Length);
Assert.Equal("Add10", adding.GetMethodInfo().Name);
}
private void AssertIntEqualsFourtyTwo(int x)
{
Assert.Equal(42, x);
}
private void AssertStringEqualsFourtyTwo(string s)
{
Assert.Equal("42", s);
}
private void AssertAddEqualsFourtyTwo(int x, string s)
{
int y = int.Parse(s);
Assert.Equal(42, x + y);
}
[Step(12)]
public void BuiltInActionDelegateTakesInt()
{
//With the release of generics in .Net 2.0 we got some delegates which will cover most of our needs.
//You will see them in the base class libraries, so knowing about them will be helpful.
//The first is Action<>. Action<> can take a variety of parameters and has a void return type.
// public delgate void Action<T>(T obj);
Action<int> i = AssertIntEqualsFourtyTwo;
i((int)FILL_ME_IN);
}
[Step(13)]
public void BuiltInActionDelegateTakesString()
{
// Because the delegate is a template, it also works with any other type.
Action<string> s = AssertStringEqualsFourtyTwo;
s((string)FILL_ME_IN);
}
[Step(14)]
public void BuiltInActionDelegateIsOverloaded()
{
//Action is an overloaded delegate so it can take more than one paramter
Action<int, string> a = AssertAddEqualsFourtyTwo;
a(12, (string)FILL_ME_IN);
}
public class Seen
{
private StringBuilder _letters = new StringBuilder();
public string Letters
{
get { return _letters.ToString(); }
}
public void Look(char letter)
{
_letters.Append(letter);
}
}
[Step(15)]
public void ActionInTheBcl()
{
//You will find Action used within the BCL, often when iterating over a container
string greeting = "Hello world";
Seen s = new Seen();
Array.ForEach(greeting.ToCharArray(), s.Look);
Assert.Equal(FILL_ME_IN, s.Letters);
}
private bool IntEqualsFourtyTwo(int x)
{
return 42 == x;
}
private bool StringEqualsFourtyTwo(string s)
{
return "42" == s;
}
[Step(16)]
public void BuiltInPredicateDelegateIntSatisfied()
{
//The Predicate<T> delegate
// public delgate bool Predicate<T>(T obj);
//Predicate allows you to codify a condition and pass it around.
//You use it to determine if an object satisfies some criteria.
Predicate<int> i = (Predicate<int>)FILL_ME_IN;
Assert.True(i(42));
}
[Step(17)]
public void BuiltInPredicateDelegateStringSatisfied()
{
//Because it is a template, you can work with any type
Predicate<string> s = (Predicate<string>)FILL_ME_IN;
Assert.True(s("42"));
//Predicate is not overloaded, so unlike Action<> you cannot do this...
//Predicate<int, string> a = (Predicate<int, string>)FILL_ME_IN;
//Assert.True(a(42, "42"));
}
private bool StartsWithS(string country)
{
return country.StartsWith("S");
}
[Step(18)]
public void FindingWithPredicate()
{
//Predicate can be used to find an element in an array
var countries = new[] { "Greece", "Spain", "Uruguay", "Japan" };
Assert.Equal(FILL_ME_IN, Array.Find(countries, StartsWithS));
}
private bool IsInSouthAmerica(string country)
{
var countries = new[] { "Argentina", "Bolivia", "Brazil", "Chile", "Colombia", "Ecuador", "French Guiana", "Guyana", "Paraguay", "Peru", "Suriname", "Uruguay", "Venezuela" };
return countries.Contains(country);
}
[Step(19)]
public void ValidationWithPredicate()
{
//Predicate can also be used when verifying
var countries = new[] { "Greece", "Spain", "Uruguay", "Japan" };
Assert.Equal(FILL_ME_IN, Array.TrueForAll(countries, IsInSouthAmerica));
}
private string FirstMonth()
{
return "January";
}
private int Add(int x, int y)
{
return x + y;
}
[Step(20)]
public void FuncWithNoParameters()
{
//The Func<> delegate
// public delegate TResult Func<T, TResult>(T arg);
//Is very similar to the Action<> delegate. However, Func<> does not require any parameters, while does require returns a value.
//The last type parameter specifies the return type. If you only specify a single
//type, Func<int>, then the method takes no paramters and returns an int.
//If you specify more than one parameter, then you are specifying the paramter types as well.
Func<string> d = FirstMonth;
Assert.Equal(FILL_ME_IN, d());
}
[Step(21)]
public void FunctionReturnsInt()
{
//Like Action<>, Func<> is overloaded and can take a variable number of parameters.
//The first type parameters define the parameter types and the last one is the return type. So the following matches
//a method which takes two int parameters and returns a int.
Func<int, int, int> a = Add;
Assert.Equal(FILL_ME_IN, a(1, 1));
}
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public Car(string make, string model, int year)
{
Make = make;
Model = model;
Year = year;
}
}
private int SortByModel(Car lhs, Car rhs)
{
return lhs.Model.CompareTo(rhs.Model);
}
[Step(22)]
public void SortingWithComparison()
{
//You could make classes sortable by implementing IComparable or IComparer. But the Comparison<> delegate makes it easier
// public delegate int Comparison<T>(T x, T y);
//All you need is a method which takes two of the same type and returns -1, 0, or 1 depending upon what order they should go in.
var cars = new[] { new Car("BMC", "Mini", 1959), new Car("Alfa Romero", "GTV-6", 1986) };
Comparison<Car> by = SortByModel;
Array.Sort(cars, by);
Assert.Equal(FILL_ME_IN, cars[0].Model);
}
private string Stringify(int x)
{
return x.ToString();
}
[Step(23)]
public void ChangingTypesWithConverter()
{
//The Converter<> delegate
// public delegate U Converter<T, U>(T from);
//Can be used to change an object from one type to another
var numbers = new[] { 1, 2, 3, 4 };
Converter<int, string> c = Stringify;
var result = Array.ConvertAll(numbers, c);
Assert.Equal(FILL_ME_IN, result);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Services.Connectors
{
public class UserAccountServicesConnector : IUserAccountService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
public UserAccountServicesConnector()
{
}
public UserAccountServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public UserAccountServicesConnector(IConfigSource source)
{
Initialise(source);
}
public virtual UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "getaccount";
sendData["ScopeID"] = scopeID;
sendData["FirstName"] = firstName.ToString();
sendData["LastName"] = lastName.ToString();
return SendAndGetReply(sendData);
}
public virtual UserAccount GetUserAccount(UUID scopeID, string email)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "getaccount";
sendData["ScopeID"] = scopeID;
sendData["Email"] = email;
return SendAndGetReply(sendData);
}
public virtual UserAccount GetUserAccount(UUID scopeID, UUID userID)
{
//m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccount {0}", userID);
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "getaccount";
sendData["ScopeID"] = scopeID;
sendData["UserID"] = userID.ToString();
return SendAndGetReply(sendData);
}
public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "getaccounts";
sendData["ScopeID"] = scopeID.ToString();
sendData["query"] = query;
string reply = string.Empty;
string reqString = ServerUtils.BuildQueryString(sendData);
string uri = m_ServerURI + "/accounts";
// m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
reqString);
if (reply == null || (reply != null && reply == string.Empty))
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received null or empty reply");
return null;
}
}
catch (Exception e)
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user accounts server at {0}: {1}", uri, e.Message);
}
List<UserAccount> accounts = new List<UserAccount>();
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
if (replyData.ContainsKey("result") && replyData["result"].ToString() == "null")
{
return accounts;
}
Dictionary<string, object>.ValueCollection accountList = replyData.Values;
//m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count);
foreach (object acc in accountList)
{
if (acc is Dictionary<string, object>)
{
UserAccount pinfo = new UserAccount((Dictionary<string, object>)acc);
accounts.Add(pinfo);
}
else
m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received invalid response type {0}",
acc.GetType());
}
}
else
m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccounts received null response");
return accounts;
}
public virtual void Initialise(IConfigSource source)
{
IConfig assetConfig = source.Configs["UserAccountService"];
if (assetConfig == null)
{
m_log.Error("[ACCOUNT CONNECTOR]: UserAccountService missing from OpenSim.ini");
throw new Exception("User account connector init error");
}
string serviceURI = assetConfig.GetString("UserAccountServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[ACCOUNT CONNECTOR]: No Server URI named in section UserAccountService");
throw new Exception("User account connector init error");
}
m_ServerURI = serviceURI;
}
public void InvalidateCache(UUID userID)
{
}
public virtual bool StoreUserAccount(UserAccount data)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "setaccount";
Dictionary<string, object> structData = data.ToKeyValuePairs();
foreach (KeyValuePair<string, object> kvp in structData)
{
if (kvp.Value == null)
{
m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Null value for {0}", kvp.Key);
continue;
}
sendData[kvp.Key] = kvp.Value.ToString();
}
return SendAndGetBoolReply(sendData);
}
private bool SendAndGetBoolReply(Dictionary<string, object> sendData)
{
string reqString = ServerUtils.BuildQueryString(sendData);
string uri = m_ServerURI + "/accounts";
// m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
reqString);
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData.ContainsKey("result"))
{
if (replyData["result"].ToString().ToLower() == "success")
return true;
else
return false;
}
else
m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Set or Create UserAccount reply data does not contain result field");
}
else
m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Set or Create UserAccount received empty reply");
}
catch (Exception e)
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user accounts server at {0}: {1}", uri, e.Message);
}
return false;
}
private UserAccount SendAndGetReply(Dictionary<string, object> sendData)
{
string reply = string.Empty;
string reqString = ServerUtils.BuildQueryString(sendData);
string uri = m_ServerURI + "/accounts";
// m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
reqString);
if (reply == null || (reply != null && reply == string.Empty))
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccount received null or empty reply");
return null;
}
}
catch (Exception e)
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user accounts server at {0}: {1}", uri, e.Message);
}
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
UserAccount account = null;
if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
{
account = new UserAccount((Dictionary<string, object>)replyData["result"]);
}
}
return account;
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes a volume.
/// </summary>
public partial class Volume
{
private List<VolumeAttachment> _attachments = new List<VolumeAttachment>();
private string _availabilityZone;
private DateTime? _createTime;
private bool? _encrypted;
private int? _iops;
private string _kmsKeyId;
private int? _size;
private string _snapshotId;
private VolumeState _state;
private List<Tag> _tags = new List<Tag>();
private string _volumeId;
private VolumeType _volumeType;
/// <summary>
/// Gets and sets the property Attachments.
/// <para>
/// Information about the volume attachments.
/// </para>
/// </summary>
public List<VolumeAttachment> Attachments
{
get { return this._attachments; }
set { this._attachments = value; }
}
// Check to see if Attachments property is set
internal bool IsSetAttachments()
{
return this._attachments != null && this._attachments.Count > 0;
}
/// <summary>
/// Gets and sets the property AvailabilityZone.
/// <para>
/// The Availability Zone for the volume.
/// </para>
/// </summary>
public string AvailabilityZone
{
get { return this._availabilityZone; }
set { this._availabilityZone = value; }
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this._availabilityZone != null;
}
/// <summary>
/// Gets and sets the property CreateTime.
/// <para>
/// The time stamp when volume creation was initiated.
/// </para>
/// </summary>
public DateTime CreateTime
{
get { return this._createTime.GetValueOrDefault(); }
set { this._createTime = value; }
}
// Check to see if CreateTime property is set
internal bool IsSetCreateTime()
{
return this._createTime.HasValue;
}
/// <summary>
/// Gets and sets the property Encrypted.
/// <para>
/// Indicates whether the volume will be encrypted.
/// </para>
/// </summary>
public bool Encrypted
{
get { return this._encrypted.GetValueOrDefault(); }
set { this._encrypted = value; }
}
// Check to see if Encrypted property is set
internal bool IsSetEncrypted()
{
return this._encrypted.HasValue;
}
/// <summary>
/// Gets and sets the property Iops.
/// <para>
/// The number of I/O operations per second (IOPS) that the volume supports. For Provisioned
/// IOPS (SSD) volumes, this represents the number of IOPS that are provisioned for the
/// volume. For General Purpose (SSD) volumes, this represents the baseline performance
/// of the volume and the rate at which the volume accumulates I/O credits for bursting.
/// For more information on General Purpose (SSD) baseline performance, I/O credits, and
/// bursting, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon
/// EBS Volume Types</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
///
/// <para>
/// Constraint: Range is 100 to 20000 for Provisioned IOPS (SSD) volumes and 3 to 10000
/// for General Purpose (SSD) volumes.
/// </para>
///
/// <para>
/// Condition: This parameter is required for requests to create <code>io1</code> volumes;
/// it is not used in requests to create <code>standard</code> or <code>gp2</code> volumes.
/// </para>
/// </summary>
public int Iops
{
get { return this._iops.GetValueOrDefault(); }
set { this._iops = value; }
}
// Check to see if Iops property is set
internal bool IsSetIops()
{
return this._iops.HasValue;
}
/// <summary>
/// Gets and sets the property KmsKeyId.
/// <para>
/// The full ARN of the AWS Key Management Service (AWS KMS) customer master key (CMK)
/// that was used to protect the volume encryption key for the volume.
/// </para>
/// </summary>
public string KmsKeyId
{
get { return this._kmsKeyId; }
set { this._kmsKeyId = value; }
}
// Check to see if KmsKeyId property is set
internal bool IsSetKmsKeyId()
{
return this._kmsKeyId != null;
}
/// <summary>
/// Gets and sets the property Size.
/// <para>
/// The size of the volume, in GiBs.
/// </para>
/// </summary>
public int Size
{
get { return this._size.GetValueOrDefault(); }
set { this._size = value; }
}
// Check to see if Size property is set
internal bool IsSetSize()
{
return this._size.HasValue;
}
/// <summary>
/// Gets and sets the property SnapshotId.
/// <para>
/// The snapshot from which the volume was created, if applicable.
/// </para>
/// </summary>
public string SnapshotId
{
get { return this._snapshotId; }
set { this._snapshotId = value; }
}
// Check to see if SnapshotId property is set
internal bool IsSetSnapshotId()
{
return this._snapshotId != null;
}
/// <summary>
/// Gets and sets the property State.
/// <para>
/// The volume state.
/// </para>
/// </summary>
public VolumeState State
{
get { return this._state; }
set { this._state = value; }
}
// Check to see if State property is set
internal bool IsSetState()
{
return this._state != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// Any tags assigned to the volume.
/// </para>
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property VolumeId.
/// <para>
/// The ID of the volume.
/// </para>
/// </summary>
public string VolumeId
{
get { return this._volumeId; }
set { this._volumeId = value; }
}
// Check to see if VolumeId property is set
internal bool IsSetVolumeId()
{
return this._volumeId != null;
}
/// <summary>
/// Gets and sets the property VolumeType.
/// <para>
/// The volume type. This can be <code>gp2</code> for General Purpose (SSD) volumes, <code>io1</code>
/// for Provisioned IOPS (SSD) volumes, or <code>standard</code> for Magnetic volumes.
/// </para>
/// </summary>
public VolumeType VolumeType
{
get { return this._volumeType; }
set { this._volumeType = value; }
}
// Check to see if VolumeType property is set
internal bool IsSetVolumeType()
{
return this._volumeType != null;
}
}
}
| |
/*
* Copyright 2017 ZXing.Net authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using ZXing.Common;
using ZXing.OneD;
namespace ZXing.CoreCompat.Rendering
{
/// <summary>
/// Renders a <see cref="BitMatrix" /> to a <see cref="Bitmap" /> image
/// </summary>
public class BitmapRenderer : ZXing.Rendering.IBarcodeRenderer<Bitmap>
{
/// <summary>
/// Gets or sets the foreground color.
/// </summary>
/// <value>The foreground color.</value>
public Color Foreground { get; set; }
/// <summary>
/// Gets or sets the background color.
/// </summary>
/// <value>The background color.</value>
public Color Background { get; set; }
/// <summary>
/// Gets or sets the resolution which should be used to create the bitmap
/// If nothing is set the current system settings are used
/// </summary>
public float? DpiX { get; set; }
/// <summary>
/// Gets or sets the resolution which should be used to create the bitmap
/// If nothing is set the current system settings are used
/// </summary>
public float? DpiY { get; set; }
/// <summary>
/// Gets or sets the text font.
/// </summary>
/// <value>
/// The text font.
/// </value>
public Font TextFont { get; set; }
private static readonly Font DefaultTextFont;
static BitmapRenderer()
{
try
{
DefaultTextFont = new Font("Arial", 10, FontStyle.Regular);
}
catch (Exception)
{
// have to ignore, no better idea
}
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapRenderer"/> class.
/// </summary>
public BitmapRenderer()
{
Foreground = Color.Black;
Background = Color.White;
TextFont = DefaultTextFont;
}
/// <summary>
/// Renders the specified matrix.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <param name="format">The format.</param>
/// <param name="content">The content.</param>
/// <returns></returns>
public Bitmap Render(BitMatrix matrix, BarcodeFormat format, string content)
{
return Render(matrix, format, content, new EncodingOptions());
}
/// <summary>
/// Renders the specified matrix.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <param name="format">The format.</param>
/// <param name="content">The content.</param>
/// <param name="options">The options.</param>
/// <returns></returns>
public Bitmap Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
{
var width = matrix.Width;
var height = matrix.Height;
var font = TextFont ?? DefaultTextFont;
var emptyArea = 0;
var outputContent = font != null &&
(options == null || !options.PureBarcode) &&
!String.IsNullOrEmpty(content) &&
(format == BarcodeFormat.CODE_39 ||
format == BarcodeFormat.CODE_93 ||
format == BarcodeFormat.CODE_128 ||
format == BarcodeFormat.EAN_13 ||
format == BarcodeFormat.EAN_8 ||
format == BarcodeFormat.CODABAR ||
format == BarcodeFormat.ITF ||
format == BarcodeFormat.UPC_A ||
format == BarcodeFormat.UPC_E ||
format == BarcodeFormat.MSI ||
format == BarcodeFormat.PLESSEY);
if (options != null)
{
if (options.Width > width)
{
width = options.Width;
}
if (options.Height > height)
{
height = options.Height;
}
}
// calculating the scaling factor
var pixelsizeWidth = width / matrix.Width;
var pixelsizeHeight = height / matrix.Height;
// create the bitmap and lock the bits because we need the stride
// which is the width of the image and possible padding bytes
var bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
var dpiX = DpiX ?? DpiY;
var dpiY = DpiY ?? DpiX;
if (dpiX != null)
bmp.SetResolution(dpiX.Value, dpiY.Value);
using (var g = Graphics.FromImage(bmp))
{
var bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly,
PixelFormat.Format24bppRgb);
try
{
var pixels = new byte[bmpData.Stride * height];
var padding = bmpData.Stride - (3 * width);
var index = 0;
var color = Background;
// going through the lines of the matrix
for (int y = 0; y < matrix.Height; y++)
{
// stretching the line by the scaling factor
for (var pixelsizeHeightProcessed = 0;
pixelsizeHeightProcessed < pixelsizeHeight;
pixelsizeHeightProcessed++)
{
// going through the columns of the current line
for (var x = 0; x < matrix.Width; x++)
{
color = matrix[x, y] ? Foreground : Background;
// stretching the columns by the scaling factor
for (var pixelsizeWidthProcessed = 0;
pixelsizeWidthProcessed < pixelsizeWidth;
pixelsizeWidthProcessed++)
{
pixels[index++] = color.B;
pixels[index++] = color.G;
pixels[index++] = color.R;
}
}
// fill up to the right if the barcode doesn't fully fit in
for (var x = pixelsizeWidth * matrix.Width; x < width; x++)
{
pixels[index++] = Background.B;
pixels[index++] = Background.G;
pixels[index++] = Background.R;
}
index += padding;
}
}
// fill up to the bottom if the barcode doesn't fully fit in
for (var y = pixelsizeHeight * matrix.Height; y < height; y++)
{
for (var x = 0; x < width; x++)
{
pixels[index++] = Background.B;
pixels[index++] = Background.G;
pixels[index++] = Background.R;
}
index += padding;
}
// fill the bottom area with the background color if the content should be written below the barcode
if (outputContent)
{
var textAreaHeight = font.Height;
emptyArea = height + 10 > textAreaHeight ? textAreaHeight : 0;
if (emptyArea > 0)
{
index = (width * 3 + padding) * (height - emptyArea);
for (int y = height - emptyArea; y < height; y++)
{
for (var x = 0; x < width; x++)
{
pixels[index++] = Background.B;
pixels[index++] = Background.G;
pixels[index++] = Background.R;
}
index += padding;
}
}
}
//Copy the data from the byte array into BitmapData.Scan0
Marshal.Copy(pixels, 0, bmpData.Scan0, pixels.Length);
}
finally
{
//Unlock the pixels
bmp.UnlockBits(bmpData);
}
// output content text below the barcode
if (emptyArea > 0)
{
switch (format)
{
case BarcodeFormat.UPC_E:
case BarcodeFormat.EAN_8:
if (content.Length < 8)
content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
if (content.Length > 4)
content = content.Insert(4, " ");
break;
case BarcodeFormat.EAN_13:
if (content.Length < 13)
content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
if (content.Length > 7)
content = content.Insert(7, " ");
if (content.Length > 1)
content = content.Insert(1, " ");
break;
case BarcodeFormat.UPC_A:
if (content.Length < 12)
content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
if (content.Length > 11)
content = content.Insert(11, " ");
if (content.Length > 6)
content = content.Insert(6, " ");
if (content.Length > 1)
content = content.Insert(1, " ");
break;
}
var brush = new SolidBrush(Foreground);
var drawFormat = new StringFormat { Alignment = StringAlignment.Center };
g.DrawString(content, font, brush, pixelsizeWidth * matrix.Width / 2, height - emptyArea, drawFormat);
}
}
return bmp;
}
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public sealed partial class NamedPipeServerStream : PipeStream
{
private SharedServer _instance;
private PipeDirection _direction;
private PipeOptions _options;
private int _inBufferSize;
private int _outBufferSize;
private HandleInheritability _inheritability;
private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
HandleInheritability inheritability)
{
Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
Debug.Assert((maxNumberOfServerInstances >= 1) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
if (transmissionMode == PipeTransmissionMode.Message)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode);
}
// We don't have a good way to enforce maxNumberOfServerInstances across processes; we only factor it in
// for streams created in this process. Between processes, we behave similarly to maxNumberOfServerInstances == 1,
// in that the second process to come along and create a stream will find the pipe already in existence and will fail.
_instance = SharedServer.Get(
GetPipePath(".", pipeName),
(maxNumberOfServerInstances == MaxAllowedServerInstances) ? int.MaxValue : maxNumberOfServerInstances);
_direction = direction;
_options = options;
_inBufferSize = inBufferSize;
_outBufferSize = outBufferSize;
_inheritability = inheritability;
}
public void WaitForConnection()
{
CheckConnectOperationsServer();
if (State == PipeState.Connected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected);
}
// Use and block on AcceptAsync() rather than using Accept() in order to provide
// behavior more akin to Windows if the Stream is closed while a connection is pending.
Socket accepted = _instance.ListeningSocket.AcceptAsync().GetAwaiter().GetResult();
HandleAcceptedSocket(accepted);
}
public Task WaitForConnectionAsync(CancellationToken cancellationToken)
{
CheckConnectOperationsServer();
if (State == PipeState.Connected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected);
}
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
WaitForConnectionAsyncCore();
async Task WaitForConnectionAsyncCore() =>
HandleAcceptedSocket(await _instance.ListeningSocket.AcceptAsync().ConfigureAwait(false));
}
private void HandleAcceptedSocket(Socket acceptedSocket)
{
var serverHandle = new SafePipeHandle(acceptedSocket);
try
{
if (IsCurrentUserOnly)
{
uint serverEUID = Interop.Sys.GetEUid();
uint peerID;
if (Interop.Sys.GetPeerID(serverHandle, out peerID) == -1)
{
throw CreateExceptionForLastError(_instance?.PipeName);
}
if (serverEUID != peerID)
{
throw new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_ClientIsNotCurrentUser, peerID, serverEUID));
}
}
ConfigureSocket(acceptedSocket, serverHandle, _direction, _inBufferSize, _outBufferSize, _inheritability);
}
catch
{
serverHandle.Dispose();
acceptedSocket.Dispose();
throw;
}
InitializeHandle(serverHandle, isExposed: false, isAsync: (_options & PipeOptions.Asynchronous) != 0);
State = PipeState.Connected;
}
internal override void DisposeCore(bool disposing) =>
Interlocked.Exchange(ref _instance, null)?.Dispose(disposing); // interlocked to avoid shared state problems from erroneous double/concurrent disposes
public void Disconnect()
{
CheckDisconnectOperations();
State = PipeState.Disconnected;
InternalHandle.Dispose();
InitializeHandle(null, false, false);
}
// Gets the username of the connected client. Not that we will not have access to the client's
// username until it has written at least once to the pipe (and has set its impersonationLevel
// argument appropriately).
public string GetImpersonationUserName()
{
CheckWriteOperations();
SafeHandle handle = InternalHandle?.NamedPipeSocketHandle;
if (handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
string name = Interop.Sys.GetPeerUserName(handle);
if (name != null)
{
return name;
}
throw CreateExceptionForLastError(_instance?.PipeName);
}
public override int InBufferSize
{
get
{
CheckPipePropertyOperations();
if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream);
return InternalHandle?.NamedPipeSocket?.ReceiveBufferSize ?? _inBufferSize;
}
}
public override int OutBufferSize
{
get
{
CheckPipePropertyOperations();
if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream);
return InternalHandle?.NamedPipeSocket?.SendBufferSize ?? _outBufferSize;
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
// This method calls a delegate while impersonating the client.
public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker)
{
CheckWriteOperations();
SafeHandle handle = InternalHandle?.NamedPipeSocketHandle;
if (handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// Get the current effective ID to fallback to after the impersonationWorker is run
uint currentEUID = Interop.Sys.GetEUid();
// Get the userid of the client process at the end of the pipe
uint peerID;
if (Interop.Sys.GetPeerID(handle, out peerID) == -1)
{
throw CreateExceptionForLastError(_instance?.PipeName);
}
// set the effective userid of the current (server) process to the clientid
if (Interop.Sys.SetEUid(peerID) == -1)
{
throw CreateExceptionForLastError(_instance?.PipeName);
}
try
{
impersonationWorker();
}
finally
{
// set the userid of the current (server) process back to its original value
Interop.Sys.SetEUid(currentEUID);
}
}
/// <summary>Shared resources for NamedPipeServerStreams in the same process created for the same path.</summary>
private sealed class SharedServer
{
/// <summary>Path to shared instance mapping.</summary>
private static readonly Dictionary<string, SharedServer> s_servers = new Dictionary<string, SharedServer>();
/// <summary>The pipe name for this instance.</summary>
internal string PipeName { get; }
/// <summary>Gets the shared socket used to accept connections.</summary>
internal Socket ListeningSocket { get; }
/// <summary>The maximum number of server streams allowed to use this instance concurrently.</summary>
private readonly int _maxCount;
/// <summary>The concurrent number of concurrent streams using this instance.</summary>
private int _currentCount;
internal static SharedServer Get(string path, int maxCount)
{
Debug.Assert(!string.IsNullOrEmpty(path));
Debug.Assert(maxCount >= 1);
lock (s_servers)
{
SharedServer server;
if (s_servers.TryGetValue(path, out server))
{
// On Windows, if a subsequent server stream is created for the same pipe and with a different
// max count, the subsequent count is largely ignored in that it doesn't change the number of
// allowed concurrent instances, however that particular instance being created does take its
// own into account, so if its creation would put it over either the original or its own limit,
// it's an error that results in an exception. We do the same for Unix here.
if (server._currentCount == server._maxCount)
{
throw new IOException(SR.IO_AllPipeInstancesAreBusy);
}
else if (server._currentCount == maxCount)
{
throw new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, path));
}
}
else
{
// No instance exists yet for this path. Create one a new.
server = new SharedServer(path, maxCount);
s_servers.Add(path, server);
}
Debug.Assert(server._currentCount >= 0 && server._currentCount < server._maxCount);
server._currentCount++;
return server;
}
}
internal void Dispose(bool disposing)
{
lock (s_servers)
{
Debug.Assert(_currentCount >= 1 && _currentCount <= _maxCount);
if (_currentCount == 1)
{
bool removed = s_servers.Remove(PipeName);
Debug.Assert(removed);
Interop.Sys.Unlink(PipeName); // ignore any failures
if (disposing)
{
ListeningSocket.Dispose();
}
}
else
{
_currentCount--;
}
}
}
private SharedServer(string path, int maxCount)
{
// Binding to an existing path fails, so we need to remove anything left over at this location.
// There's of course a race condition here, where it could be recreated by someone else between this
// deletion and the bind below, in which case we'll simply let the bind fail and throw.
Interop.Sys.Unlink(path); // ignore any failures
// Start listening for connections on the path.
var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
try
{
socket.Bind(new UnixDomainSocketEndPoint(path));
socket.Listen(int.MaxValue);
}
catch
{
socket.Dispose();
throw;
}
PipeName = path;
ListeningSocket = socket;
_maxCount = maxCount;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using CURLcode = Interop.Http.CURLcode;
using CURLINFO = Interop.Http.CURLINFO;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
private static class SslProvider
{
private static readonly Interop.Http.SslCtxCallback s_sslCtxCallback = SslCtxCallback;
private static readonly Interop.Ssl.AppVerifyCallback s_sslVerifyCallback = VerifyCertChain;
private static readonly Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1");
private static string _sslCaPath;
private static string _sslCaInfo;
internal static void SetSslOptions(EasyRequest easy, ClientCertificateOption clientCertOption)
{
EventSourceTrace("ClientCertificateOption: {0}", clientCertOption, easy:easy);
Debug.Assert(clientCertOption == ClientCertificateOption.Automatic || clientCertOption == ClientCertificateOption.Manual);
// Create a client certificate provider if client certs may be used.
X509Certificate2Collection clientCertificates = easy._handler._clientCertificates;
ClientCertificateProvider certProvider =
clientCertOption == ClientCertificateOption.Automatic ? new ClientCertificateProvider(null) : // automatic
clientCertificates?.Count > 0 ? new ClientCertificateProvider(clientCertificates) : // manual with certs
null; // manual without certs
IntPtr userPointer = IntPtr.Zero;
if (certProvider != null)
{
EventSourceTrace("Created certificate provider", easy:easy);
// The client cert provider needs to be passed through to the callback, and thus
// we create a GCHandle to keep it rooted. This handle needs to be cleaned up
// when the request has completed, and a simple and pay-for-play way to do that
// is by cleaning it up in a continuation off of the request.
userPointer = GCHandle.ToIntPtr(certProvider._gcHandle);
easy.Task.ContinueWith((_, state) => ((IDisposable)state).Dispose(), certProvider,
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
// Configure the options. Our best support is when targeting OpenSSL/1.0. For other backends,
// we fall back to a minimal amount of support, and may throw a PNSE based on the options requested.
if (Interop.Http.HasMatchingOpenSslVersion)
{
// Register the callback with libcurl. We need to register even if there's no user-provided
// server callback and even if there are no client certificates, because we support verifying
// server certificates against more than those known to OpenSSL.
SetSslOptionsForSupportedBackend(easy, certProvider, userPointer);
}
else
{
// Newer versions of OpenSSL, and other non-OpenSSL backends, do not currently support callbacks.
// That means we'll throw a PNSE if a callback is required.
SetSslOptionsForUnsupportedBackend(easy, certProvider);
}
}
private static void SetSslOptionsForSupportedBackend(EasyRequest easy, ClientCertificateProvider certProvider, IntPtr userPointer)
{
CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback, userPointer);
EventSourceTrace("Callback registration result: {0}", answer, easy: easy);
switch (answer)
{
case CURLcode.CURLE_OK:
// We successfully registered. If we'll be invoking a user-provided callback to verify the server
// certificate as part of that, disable libcurl's verification of the host name; we need to get
// the callback from libcurl even if the host name doesn't match, so we take on the responsibility
// of doing the host name match in the callback prior to invoking the user's delegate.
if (easy._handler.ServerCertificateCustomValidationCallback != null)
{
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0);
// But don't change the CURLOPT_SSL_VERIFYPEER setting, as setting it to 0 will
// cause SSL and libcurl to ignore the result of the server callback.
}
SetSslOptionsForCertificateStore(easy);
// The allowed SSL protocols will be set in the configuration callback.
break;
case CURLcode.CURLE_UNKNOWN_OPTION: // Curl 7.38 and prior
case CURLcode.CURLE_NOT_BUILT_IN: // Curl 7.39 and later
SetSslOptionsForUnsupportedBackend(easy, certProvider);
break;
default:
ThrowIfCURLEError(answer);
break;
}
}
private static void GetSslCaLocations(out string path, out string info)
{
// We only provide curl option values when SSL_CERT_FILE or SSL_CERT_DIR is set.
// When that is the case, we set the options so curl ends up using the same certificates as the
// X509 machine store.
path = _sslCaPath;
info = _sslCaInfo;
if (path == null || info == null)
{
bool hasEnvironmentVariables = Environment.GetEnvironmentVariable("SSL_CERT_FILE") != null ||
Environment.GetEnvironmentVariable("SSL_CERT_DIR") != null;
if (hasEnvironmentVariables)
{
path = Interop.Crypto.GetX509RootStorePath();
if (!Directory.Exists(path))
{
// X509 store ignores non-existing.
path = string.Empty;
}
info = Interop.Crypto.GetX509RootStoreFile();
if (!File.Exists(info))
{
// X509 store ignores non-existing.
info = string.Empty;
}
}
else
{
path = string.Empty;
info = string.Empty;
}
_sslCaPath = path;
_sslCaInfo = info;
}
}
private static void SetSslOptionsForCertificateStore(EasyRequest easy)
{
// Support specifying certificate directory/bundle via environment variables: SSL_CERT_DIR, SSL_CERT_FILE.
GetSslCaLocations(out string sslCaPath, out string sslCaInfo);
if (sslCaPath != string.Empty)
{
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_CAPATH, sslCaPath);
// https proxy support requires libcurl 7.52.0+
easy.TrySetCurlOption(Interop.Http.CURLoption.CURLOPT_PROXY_CAPATH, sslCaPath);
}
if (sslCaInfo != string.Empty)
{
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_CAINFO, sslCaInfo);
// https proxy support requires libcurl 7.52.0+
easy.TrySetCurlOption(Interop.Http.CURLoption.CURLOPT_PROXY_CAINFO, sslCaInfo);
}
}
private static void SetSslOptionsForUnsupportedBackend(EasyRequest easy, ClientCertificateProvider certProvider)
{
if (certProvider != null)
{
throw new PlatformNotSupportedException(SR.Format(SR.net_http_libcurl_clientcerts_notsupported_sslbackend, CurlVersionDescription, CurlSslVersionDescription, Interop.Http.RequiredOpenSslDescription));
}
if (easy._handler.CheckCertificateRevocationList)
{
throw new PlatformNotSupportedException(SR.Format(SR.net_http_libcurl_revocation_notsupported_sslbackend, CurlVersionDescription, CurlSslVersionDescription, Interop.Http.RequiredOpenSslDescription));
}
if (easy._handler.ServerCertificateCustomValidationCallback != null)
{
if (easy.ServerCertificateValidationCallbackAcceptsAll)
{
EventSourceTrace("Warning: Disabling peer and host verification per {0}", nameof(HttpClientHandler.DangerousAcceptAnyServerCertificateValidator), easy: easy);
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYPEER, 0);
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0);
}
else
{
throw new PlatformNotSupportedException(SR.Format(SR.net_http_libcurl_callback_notsupported_sslbackend, CurlVersionDescription, CurlSslVersionDescription, Interop.Http.RequiredOpenSslDescription));
}
}
else
{
SetSslOptionsForCertificateStore(easy);
}
// In case of defaults configure the allowed SSL protocols.
SetSslVersion(easy);
}
private static void SetSslVersion(EasyRequest easy, IntPtr sslCtx = default(IntPtr))
{
// Get the requested protocols.
SslProtocols protocols = easy._handler.SslProtocols;
if (protocols == SslProtocols.None)
{
// Let libcurl use its defaults if None is set.
return;
}
// libcurl supports options for either enabling all of the TLS1.* protocols or enabling
// just one protocol; it doesn't currently support enabling two of the three, e.g. you can't
// pick TLS1.1 and TLS1.2 but not TLS1.0, but you can select just TLS1.2.
Interop.Http.CurlSslVersion curlSslVersion;
switch (protocols)
{
#pragma warning disable 0618 // SSL2/3 are deprecated
case SslProtocols.Ssl2:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_SSLv2;
break;
case SslProtocols.Ssl3:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_SSLv3;
break;
#pragma warning restore 0618
case SslProtocols.Tls:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_0;
break;
case SslProtocols.Tls11:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_1;
break;
case SslProtocols.Tls12:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_2;
break;
case SslProtocols.Tls13:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_3;
break;
case SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12:
case SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1;
break;
default:
throw new NotSupportedException(SR.net_securityprotocolnotsupported);
}
try
{
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSLVERSION, (long)curlSslVersion);
}
catch (CurlException e) when (e.HResult == (int)CURLcode.CURLE_UNKNOWN_OPTION)
{
throw new NotSupportedException(SR.net_securityprotocolnotsupported, e);
}
}
private static CURLcode SslCtxCallback(IntPtr curl, IntPtr sslCtx, IntPtr userPointer)
{
EasyRequest easy;
if (!TryGetEasyRequest(curl, out easy))
{
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
EventSourceTrace(null, easy: easy);
// Configure the SSL protocols allowed.
SslProtocols protocols = easy._handler.SslProtocols;
if (protocols == SslProtocols.None)
{
// If None is selected, let OpenSSL use its defaults, but with SSL2/3 explicitly disabled.
// Since the shim/OpenSSL work on a disabling system, where any protocols for which bits aren't
// set are disabled, we set all of the bits other than those we want disabled.
#pragma warning disable 0618 // the enum values are obsolete
protocols = ~(SslProtocols.Ssl2 | SslProtocols.Ssl3);
#pragma warning restore 0618
}
Interop.Ssl.SetProtocolOptions(sslCtx, protocols);
// Configure the SSL server certificate verification callback.
Interop.Ssl.SslCtxSetCertVerifyCallback(sslCtx, s_sslVerifyCallback, curl);
// If a client certificate provider was provided, also configure the client certificate callback.
if (userPointer != IntPtr.Zero)
{
try
{
// Provider is passed in via a GCHandle. Get the provider, which contains
// the client certificate callback delegate.
GCHandle handle = GCHandle.FromIntPtr(userPointer);
ClientCertificateProvider provider = (ClientCertificateProvider)handle.Target;
if (provider == null)
{
Debug.Fail($"Expected non-null provider in {nameof(SslCtxCallback)}");
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
// Register the callback.
Interop.Ssl.SslCtxSetClientCertCallback(sslCtx, provider._callback);
EventSourceTrace("Registered client certificate callback.", easy: easy);
}
catch (Exception e)
{
Debug.Fail($"Exception in {nameof(SslCtxCallback)}", e.ToString());
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
}
return CURLcode.CURLE_OK;
}
private static bool TryGetEasyRequest(IntPtr curlPtr, out EasyRequest easy)
{
Debug.Assert(curlPtr != IntPtr.Zero, "curlPtr is not null");
IntPtr gcHandlePtr;
CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(curlPtr, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr);
if (getInfoResult == CURLcode.CURLE_OK)
{
return MultiAgent.TryGetEasyRequestFromGCHandle(gcHandlePtr, out easy);
}
Debug.Fail($"Failed to get info on a completing easy handle: {getInfoResult}");
easy = null;
return false;
}
private static int VerifyCertChain(IntPtr storeCtxPtr, IntPtr curlPtr)
{
const int SuccessResult = 1, FailureResult = 0;
EasyRequest easy;
if (!TryGetEasyRequest(curlPtr, out easy))
{
EventSourceTrace("Could not find associated easy request: {0}", curlPtr);
return FailureResult;
}
var storeCtx = new SafeX509StoreCtxHandle(storeCtxPtr, ownsHandle: false);
try
{
return VerifyCertChain(storeCtx, easy) ? SuccessResult : FailureResult;
}
catch (Exception exc)
{
EventSourceTrace("Unexpected exception: {0}", exc, easy: easy);
easy.FailRequest(CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_ABORTED_BY_CALLBACK, exc)));
return FailureResult;
}
finally
{
storeCtx.Dispose();
}
}
private static bool VerifyCertChain(SafeX509StoreCtxHandle storeCtx, EasyRequest easy)
{
IntPtr leafCertPtr = Interop.Crypto.X509StoreCtxGetTargetCert(storeCtx);
if (leafCertPtr == IntPtr.Zero)
{
EventSourceTrace("Invalid certificate pointer", easy: easy);
return false;
}
X509Certificate2[] otherCerts = null;
int otherCertsCount = 0;
var leafCert = new X509Certificate2(leafCertPtr);
try
{
// We need to respect the user's server validation callback if there is one. If there isn't one,
// we can start by first trying to use OpenSSL's verification, though only if CRL checking is disabled,
// as OpenSSL doesn't do that.
if (easy._handler.ServerCertificateCustomValidationCallback == null &&
!easy._handler.CheckCertificateRevocationList)
{
// Start by using the default verification provided directly by OpenSSL.
// If it succeeds in verifying the cert chain, we're done. Employing this instead of
// our custom implementation will need to be revisited if we ever decide to introduce a
// "disallowed" store that enables users to "untrust" certs the system trusts.
if (Interop.Crypto.X509VerifyCert(storeCtx))
{
return true;
}
}
// Either OpenSSL verification failed, or there was a server validation callback
// or certificate revocation checking was enabled. Either way, fall back to manual
// and more expensive verification that includes checking the user's certs (not
// just the system store ones as OpenSSL does).
using (var chain = new X509Chain())
{
chain.ChainPolicy.RevocationMode = easy._handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
using (SafeSharedX509StackHandle extraStack = Interop.Crypto.X509StoreCtxGetSharedUntrusted(storeCtx))
{
if (extraStack.IsInvalid)
{
otherCerts = Array.Empty<X509Certificate2>();
}
else
{
int extraSize = Interop.Crypto.GetX509StackFieldCount(extraStack);
otherCerts = new X509Certificate2[extraSize];
for (int i = 0; i < extraSize; i++)
{
IntPtr certPtr = Interop.Crypto.GetX509StackField(extraStack, i);
if (certPtr != IntPtr.Zero)
{
X509Certificate2 cert = new X509Certificate2(certPtr);
otherCerts[otherCertsCount++] = cert;
chain.ChainPolicy.ExtraStore.Add(cert);
}
}
}
}
var serverCallback = easy._handler._serverCertificateValidationCallback;
if (serverCallback == null)
{
SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
checkCertName: false, hostName: null); // libcurl already verifies the host name
return errors == SslPolicyErrors.None;
}
else
{
// Authenticate the remote party: (e.g. when operating in client mode, authenticate the server).
chain.ChainPolicy.ApplicationPolicy.Add(s_serverAuthOid);
SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
checkCertName: true, hostName: easy._requestMessage.RequestUri.Host); // we disabled automatic host verification, so we do it here
return serverCallback(easy._requestMessage, leafCert, chain, errors);
}
}
}
finally
{
for (int i = 0; i < otherCertsCount; i++)
{
otherCerts[i].Dispose();
}
leafCert.Dispose();
}
}
}
}
}
| |
// Copyright 2022 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 gatv = Google.Area120.Tables.V1Alpha1;
using sys = System;
namespace Google.Area120.Tables.V1Alpha1
{
/// <summary>Resource name for the <c>Table</c> resource.</summary>
public sealed partial class TableName : gax::IResourceName, sys::IEquatable<TableName>
{
/// <summary>The possible contents of <see cref="TableName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>tables/{table}</c>.</summary>
Table = 1,
}
private static gax::PathTemplate s_table = new gax::PathTemplate("tables/{table}");
/// <summary>Creates a <see cref="TableName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="TableName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static TableName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new TableName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="TableName"/> with the pattern <c>tables/{table}</c>.</summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="TableName"/> constructed from the provided ids.</returns>
public static TableName FromTable(string tableId) =>
new TableName(ResourceNameType.Table, tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TableName"/> with pattern
/// <c>tables/{table}</c>.
/// </summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TableName"/> with pattern <c>tables/{table}</c>.
/// </returns>
public static string Format(string tableId) => FormatTable(tableId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TableName"/> with pattern
/// <c>tables/{table}</c>.
/// </summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TableName"/> with pattern <c>tables/{table}</c>.
/// </returns>
public static string FormatTable(string tableId) =>
s_table.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)));
/// <summary>Parses the given resource name string into a new <see cref="TableName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>tables/{table}</c></description></item></list>
/// </remarks>
/// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="TableName"/> if successful.</returns>
public static TableName Parse(string tableName) => Parse(tableName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="TableName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>tables/{table}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="TableName"/> if successful.</returns>
public static TableName Parse(string tableName, bool allowUnparsed) =>
TryParse(tableName, allowUnparsed, out TableName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TableName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>tables/{table}</c></description></item></list>
/// </remarks>
/// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TableName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string tableName, out TableName result) => TryParse(tableName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TableName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>tables/{table}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TableName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string tableName, bool allowUnparsed, out TableName result)
{
gax::GaxPreconditions.CheckNotNull(tableName, nameof(tableName));
gax::TemplatedResourceName resourceName;
if (s_table.TryParseName(tableName, out resourceName))
{
result = FromTable(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(tableName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private TableName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string tableId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
TableId = tableId;
}
/// <summary>
/// Constructs a new instance of a <see cref="TableName"/> class from the component parts of pattern
/// <c>tables/{table}</c>
/// </summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
public TableName(string tableId) : this(ResourceNameType.Table, tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Table</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TableId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Table: return s_table.Expand(TableId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as TableName);
/// <inheritdoc/>
public bool Equals(TableName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(TableName a, TableName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(TableName a, TableName b) => !(a == b);
}
/// <summary>Resource name for the <c>Row</c> resource.</summary>
public sealed partial class RowName : gax::IResourceName, sys::IEquatable<RowName>
{
/// <summary>The possible contents of <see cref="RowName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>tables/{table}/rows/{row}</c>.</summary>
TableRow = 1,
}
private static gax::PathTemplate s_tableRow = new gax::PathTemplate("tables/{table}/rows/{row}");
/// <summary>Creates a <see cref="RowName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="RowName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static RowName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new RowName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="RowName"/> with the pattern <c>tables/{table}/rows/{row}</c>.</summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="rowId">The <c>Row</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="RowName"/> constructed from the provided ids.</returns>
public static RowName FromTableRow(string tableId, string rowId) =>
new RowName(ResourceNameType.TableRow, tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)), rowId: gax::GaxPreconditions.CheckNotNullOrEmpty(rowId, nameof(rowId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RowName"/> with pattern
/// <c>tables/{table}/rows/{row}</c>.
/// </summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="rowId">The <c>Row</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RowName"/> with pattern <c>tables/{table}/rows/{row}</c>.
/// </returns>
public static string Format(string tableId, string rowId) => FormatTableRow(tableId, rowId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RowName"/> with pattern
/// <c>tables/{table}/rows/{row}</c>.
/// </summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="rowId">The <c>Row</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RowName"/> with pattern <c>tables/{table}/rows/{row}</c>.
/// </returns>
public static string FormatTableRow(string tableId, string rowId) =>
s_tableRow.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)), gax::GaxPreconditions.CheckNotNullOrEmpty(rowId, nameof(rowId)));
/// <summary>Parses the given resource name string into a new <see cref="RowName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>tables/{table}/rows/{row}</c></description></item></list>
/// </remarks>
/// <param name="rowName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="RowName"/> if successful.</returns>
public static RowName Parse(string rowName) => Parse(rowName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="RowName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>tables/{table}/rows/{row}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="rowName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="RowName"/> if successful.</returns>
public static RowName Parse(string rowName, bool allowUnparsed) =>
TryParse(rowName, allowUnparsed, out RowName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>Tries to parse the given resource name string into a new <see cref="RowName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>tables/{table}/rows/{row}</c></description></item></list>
/// </remarks>
/// <param name="rowName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RowName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string rowName, out RowName result) => TryParse(rowName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RowName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>tables/{table}/rows/{row}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="rowName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RowName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string rowName, bool allowUnparsed, out RowName result)
{
gax::GaxPreconditions.CheckNotNull(rowName, nameof(rowName));
gax::TemplatedResourceName resourceName;
if (s_tableRow.TryParseName(rowName, out resourceName))
{
result = FromTableRow(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(rowName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private RowName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string rowId = null, string tableId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
RowId = rowId;
TableId = tableId;
}
/// <summary>
/// Constructs a new instance of a <see cref="RowName"/> class from the component parts of pattern
/// <c>tables/{table}/rows/{row}</c>
/// </summary>
/// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="rowId">The <c>Row</c> ID. Must not be <c>null</c> or empty.</param>
public RowName(string tableId, string rowId) : this(ResourceNameType.TableRow, tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId)), rowId: gax::GaxPreconditions.CheckNotNullOrEmpty(rowId, nameof(rowId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Row</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string RowId { get; }
/// <summary>
/// The <c>Table</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TableId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.TableRow: return s_tableRow.Expand(TableId, RowId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as RowName);
/// <inheritdoc/>
public bool Equals(RowName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(RowName a, RowName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(RowName a, RowName b) => !(a == b);
}
/// <summary>Resource name for the <c>Workspace</c> resource.</summary>
public sealed partial class WorkspaceName : gax::IResourceName, sys::IEquatable<WorkspaceName>
{
/// <summary>The possible contents of <see cref="WorkspaceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>workspaces/{workspace}</c>.</summary>
Workspace = 1,
}
private static gax::PathTemplate s_workspace = new gax::PathTemplate("workspaces/{workspace}");
/// <summary>Creates a <see cref="WorkspaceName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="WorkspaceName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static WorkspaceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new WorkspaceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="WorkspaceName"/> with the pattern <c>workspaces/{workspace}</c>.</summary>
/// <param name="workspaceId">The <c>Workspace</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="WorkspaceName"/> constructed from the provided ids.</returns>
public static WorkspaceName FromWorkspace(string workspaceId) =>
new WorkspaceName(ResourceNameType.Workspace, workspaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(workspaceId, nameof(workspaceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WorkspaceName"/> with pattern
/// <c>workspaces/{workspace}</c>.
/// </summary>
/// <param name="workspaceId">The <c>Workspace</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WorkspaceName"/> with pattern <c>workspaces/{workspace}</c>.
/// </returns>
public static string Format(string workspaceId) => FormatWorkspace(workspaceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WorkspaceName"/> with pattern
/// <c>workspaces/{workspace}</c>.
/// </summary>
/// <param name="workspaceId">The <c>Workspace</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WorkspaceName"/> with pattern <c>workspaces/{workspace}</c>.
/// </returns>
public static string FormatWorkspace(string workspaceId) =>
s_workspace.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(workspaceId, nameof(workspaceId)));
/// <summary>Parses the given resource name string into a new <see cref="WorkspaceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>workspaces/{workspace}</c></description></item></list>
/// </remarks>
/// <param name="workspaceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="WorkspaceName"/> if successful.</returns>
public static WorkspaceName Parse(string workspaceName) => Parse(workspaceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="WorkspaceName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>workspaces/{workspace}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="workspaceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="WorkspaceName"/> if successful.</returns>
public static WorkspaceName Parse(string workspaceName, bool allowUnparsed) =>
TryParse(workspaceName, allowUnparsed, out WorkspaceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="WorkspaceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>workspaces/{workspace}</c></description></item></list>
/// </remarks>
/// <param name="workspaceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="WorkspaceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string workspaceName, out WorkspaceName result) => TryParse(workspaceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="WorkspaceName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>workspaces/{workspace}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="workspaceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="WorkspaceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string workspaceName, bool allowUnparsed, out WorkspaceName result)
{
gax::GaxPreconditions.CheckNotNull(workspaceName, nameof(workspaceName));
gax::TemplatedResourceName resourceName;
if (s_workspace.TryParseName(workspaceName, out resourceName))
{
result = FromWorkspace(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(workspaceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private WorkspaceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string workspaceId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
WorkspaceId = workspaceId;
}
/// <summary>
/// Constructs a new instance of a <see cref="WorkspaceName"/> class from the component parts of pattern
/// <c>workspaces/{workspace}</c>
/// </summary>
/// <param name="workspaceId">The <c>Workspace</c> ID. Must not be <c>null</c> or empty.</param>
public WorkspaceName(string workspaceId) : this(ResourceNameType.Workspace, workspaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(workspaceId, nameof(workspaceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Workspace</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string WorkspaceId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Workspace: return s_workspace.Expand(WorkspaceId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as WorkspaceName);
/// <inheritdoc/>
public bool Equals(WorkspaceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(WorkspaceName a, WorkspaceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(WorkspaceName a, WorkspaceName b) => !(a == b);
}
public partial class GetTableRequest
{
/// <summary>
/// <see cref="gatv::TableName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::TableName TableName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::TableName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetWorkspaceRequest
{
/// <summary>
/// <see cref="gatv::WorkspaceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::WorkspaceName WorkspaceName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::WorkspaceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetRowRequest
{
/// <summary>
/// <see cref="gatv::RowName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::RowName RowName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::RowName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeleteRowRequest
{
/// <summary>
/// <see cref="gatv::RowName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::RowName RowName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::RowName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class BatchDeleteRowsRequest
{
/// <summary><see cref="TableName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public TableName ParentAsTableName
{
get => string.IsNullOrEmpty(Parent) ? null : TableName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary><see cref="RowName"/>-typed view over the <see cref="Names"/> resource name property.</summary>
public gax::ResourceNameList<RowName> RowNames
{
get => new gax::ResourceNameList<RowName>(Names, s => string.IsNullOrEmpty(s) ? null : RowName.Parse(s, allowUnparsed: true));
}
}
public partial class Table
{
/// <summary>
/// <see cref="gatv::TableName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::TableName TableName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::TableName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Row
{
/// <summary>
/// <see cref="gatv::RowName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::RowName RowName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::RowName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Workspace
{
/// <summary>
/// <see cref="gatv::WorkspaceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gatv::WorkspaceName WorkspaceName
{
get => string.IsNullOrEmpty(Name) ? null : gatv::WorkspaceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// 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.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview
{
[Export(typeof(IPreviewFactoryService)), Shared]
internal class PreviewFactoryService : ForegroundThreadAffinitizedObject, IPreviewFactoryService
{
private const double DefaultZoomLevel = 0.75;
private readonly ITextViewRoleSet _previewRoleSet;
private readonly ITextBufferFactoryService _textBufferFactoryService;
private readonly IContentTypeRegistryService _contentTypeRegistryService;
private readonly IProjectionBufferFactoryService _projectionBufferFactoryService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly ITextDifferencingSelectorService _differenceSelectorService;
private readonly IDifferenceBufferFactoryService _differenceBufferService;
private readonly IWpfDifferenceViewerFactoryService _differenceViewerService;
[ImportingConstructor]
public PreviewFactoryService(
ITextBufferFactoryService textBufferFactoryService,
IContentTypeRegistryService contentTypeRegistryService,
IProjectionBufferFactoryService projectionBufferFactoryService,
ITextEditorFactoryService textEditorFactoryService,
IEditorOptionsFactoryService editorOptionsFactoryService,
ITextDifferencingSelectorService differenceSelectorService,
IDifferenceBufferFactoryService differenceBufferService,
IWpfDifferenceViewerFactoryService differenceViewerService)
{
_textBufferFactoryService = textBufferFactoryService;
_contentTypeRegistryService = contentTypeRegistryService;
_projectionBufferFactoryService = projectionBufferFactoryService;
_editorOptionsFactoryService = editorOptionsFactoryService;
_differenceSelectorService = differenceSelectorService;
_differenceBufferService = differenceBufferService;
_differenceViewerService = differenceViewerService;
_previewRoleSet = textEditorFactoryService.CreateTextViewRoleSet(
TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable);
}
public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, CancellationToken cancellationToken)
{
return GetSolutionPreviews(oldSolution, newSolution, DefaultZoomLevel, cancellationToken);
}
public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Note: The order in which previews are added to the below list is significant.
// Preview for a changed document is preferred over preview for changed references and so on.
var previewItems = new List<SolutionPreviewItem>();
SolutionChangeSummary changeSummary = null;
if (newSolution != null)
{
var solutionChanges = newSolution.GetChanges(oldSolution);
foreach (var projectChanges in solutionChanges.GetProjectChanges())
{
cancellationToken.ThrowIfCancellationRequested();
var projectId = projectChanges.ProjectId;
var oldProject = projectChanges.OldProject;
var newProject = projectChanges.NewProject;
foreach (var documentId in projectChanges.GetChangedDocuments())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c =>
CreateChangedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), newSolution.GetDocument(documentId), zoomLevel, c)));
}
foreach (var documentId in projectChanges.GetAddedDocuments())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c =>
CreateAddedDocumentPreviewViewAsync(newSolution.GetDocument(documentId), zoomLevel, c)));
}
foreach (var documentId in projectChanges.GetRemovedDocuments())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, c =>
CreateRemovedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), zoomLevel, c)));
}
foreach (var documentId in projectChanges.GetChangedAdditionalDocuments())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c =>
CreateChangedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), newSolution.GetAdditionalDocument(documentId), zoomLevel, c)));
}
foreach (var documentId in projectChanges.GetAddedAdditionalDocuments())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c =>
CreateAddedAdditionalDocumentPreviewViewAsync(newSolution.GetAdditionalDocument(documentId), zoomLevel, c)));
}
foreach (var documentId in projectChanges.GetRemovedAdditionalDocuments())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, c =>
CreateRemovedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), zoomLevel, c)));
}
foreach (var metadataReference in projectChanges.GetAddedMetadataReferences())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, null,
string.Format(EditorFeaturesResources.AddingReferenceTo, metadataReference.Display, oldProject.Name)));
}
foreach (var metadataReference in projectChanges.GetRemovedMetadataReferences())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, null,
string.Format(EditorFeaturesResources.RemovingReferenceFrom, metadataReference.Display, oldProject.Name)));
}
foreach (var projectReference in projectChanges.GetAddedProjectReferences())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, null,
string.Format(EditorFeaturesResources.AddingReferenceTo, newSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name)));
}
foreach (var projectReference in projectChanges.GetRemovedProjectReferences())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, null,
string.Format(EditorFeaturesResources.RemovingReferenceFrom, oldSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name)));
}
foreach (var analyzer in projectChanges.GetAddedAnalyzerReferences())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, null,
string.Format(EditorFeaturesResources.AddingAnalyzerReferenceTo, analyzer.Display, oldProject.Name)));
}
foreach (var analyzer in projectChanges.GetRemovedAnalyzerReferences())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(oldProject.Id, null,
string.Format(EditorFeaturesResources.RemovingAnalyzerReferenceFrom, analyzer.Display, oldProject.Name)));
}
}
foreach (var project in solutionChanges.GetAddedProjects())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(project.Id, null,
string.Format(EditorFeaturesResources.AddingProject, project.Name)));
}
foreach (var project in solutionChanges.GetRemovedProjects())
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(project.Id, null,
string.Format(EditorFeaturesResources.RemovingProject, project.Name)));
}
foreach (var projectChanges in solutionChanges.GetProjectChanges().Where(ProjectReferencesChanged))
{
cancellationToken.ThrowIfCancellationRequested();
previewItems.Add(new SolutionPreviewItem(projectChanges.OldProject.Id, null,
string.Format(EditorFeaturesResources.ChangingProjectReferencesFor, projectChanges.OldProject.Name)));
}
changeSummary = new SolutionChangeSummary(oldSolution, newSolution, solutionChanges);
}
return new SolutionPreviewResult(previewItems, changeSummary);
}
private bool ProjectReferencesChanged(ProjectChanges projectChanges)
{
var oldProjectReferences = projectChanges.OldProject.ProjectReferences.ToDictionary(r => r.ProjectId);
var newProjectReferences = projectChanges.NewProject.ProjectReferences.ToDictionary(r => r.ProjectId);
// These are the set of project reference that remained in the project. We don't care
// about project references that were added or removed. Those will already be reported.
var preservedProjectIds = oldProjectReferences.Keys.Intersect(newProjectReferences.Keys);
foreach (var projectId in preservedProjectIds)
{
var oldProjectReference = oldProjectReferences[projectId];
var newProjectReference = newProjectReferences[projectId];
if (!oldProjectReference.Equals(newProjectReference))
{
return true;
}
}
return false;
}
public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken)
{
return CreateAddedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken);
}
private Task<object> CreateAddedDocumentPreviewViewCoreAsync(ITextBuffer newBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var firstLine = string.Format(EditorFeaturesResources.AddingToWithContent,
document.Name, document.Project.Name);
var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer(
sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService);
var span = new SnapshotSpan(newBuffer.CurrentSnapshot, Span.FromBounds(0, newBuffer.CurrentSnapshot.Length))
.CreateTrackingSpan(SpanTrackingMode.EdgeExclusive);
var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer(
sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService);
return CreateNewDifferenceViewerAsync(null, workspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken);
}
public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var newBuffer = CreateNewBuffer(document, cancellationToken);
// Create PreviewWorkspace around the buffer to be displayed in the diff preview
// so that all IDE services (colorizer, squiggles etc.) light up in this buffer.
var rightWorkspace = new PreviewWorkspace(
document.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution);
rightWorkspace.OpenDocument(document.Id);
return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken);
}
public Task<object> CreateAddedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var newBuffer = CreateNewPlainTextBuffer(document, cancellationToken);
// Create PreviewWorkspace around the buffer to be displayed in the diff preview
// so that all IDE services (colorizer, squiggles etc.) light up in this buffer.
var rightWorkspace = new PreviewWorkspace(
document.Project.Solution.WithAdditionalDocumentText(document.Id, newBuffer.AsTextContainer().CurrentText));
rightWorkspace.OpenAdditionalDocument(document.Id);
return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken);
}
public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken)
{
return CreateRemovedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken);
}
private Task<object> CreateRemovedDocumentPreviewViewCoreAsync(ITextBuffer oldBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var firstLine = string.Format(EditorFeaturesResources.RemovingFromWithContent,
document.Name, document.Project.Name);
var span = new SnapshotSpan(oldBuffer.CurrentSnapshot, Span.FromBounds(0, oldBuffer.CurrentSnapshot.Length))
.CreateTrackingSpan(SpanTrackingMode.EdgeExclusive);
var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer(
sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService);
var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer(
sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService);
return CreateNewDifferenceViewerAsync(workspace, null, originalBuffer, changedBuffer, zoomLevel, cancellationToken);
}
public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Note: We don't use the original buffer that is associated with oldDocument
// (and possibly open in the editor) for oldBuffer below. This is because oldBuffer
// will be used inside a projection buffer inside our inline diff preview below
// and platform's implementation currently has a bug where projection buffers
// are being leaked. This leak means that if we use the original buffer that is
// currently visible in the editor here, the projection buffer span calculation
// would be triggered every time user changes some code in this buffer (even though
// the diff view would long have been dismissed by the time user edits the code)
// resulting in crashes. Instead we create a new buffer from the same content.
// TODO: We could use ITextBufferCloneService instead here to clone the original buffer.
var oldBuffer = CreateNewBuffer(document, cancellationToken);
// Create PreviewWorkspace around the buffer to be displayed in the diff preview
// so that all IDE services (colorizer, squiggles etc.) light up in this buffer.
var leftDocument = document.Project
.RemoveDocument(document.Id)
.AddDocument(document.Name, oldBuffer.AsTextContainer().CurrentText);
var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution);
leftWorkspace.OpenDocument(leftDocument.Id);
return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken);
}
public Task<object> CreateRemovedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Note: We don't use the original buffer that is associated with oldDocument
// (and possibly open in the editor) for oldBuffer below. This is because oldBuffer
// will be used inside a projection buffer inside our inline diff preview below
// and platform's implementation currently has a bug where projection buffers
// are being leaked. This leak means that if we use the original buffer that is
// currently visible in the editor here, the projection buffer span calculation
// would be triggered every time user changes some code in this buffer (even though
// the diff view would long have been dismissed by the time user edits the code)
// resulting in crashes. Instead we create a new buffer from the same content.
// TODO: We could use ITextBufferCloneService instead here to clone the original buffer.
var oldBuffer = CreateNewPlainTextBuffer(document, cancellationToken);
// Create PreviewWorkspace around the buffer to be displayed in the diff preview
// so that all IDE services (colorizer, squiggles etc.) light up in this buffer.
var leftDocumentId = DocumentId.CreateNewId(document.Project.Id);
var leftSolution = document.Project.Solution
.RemoveAdditionalDocument(document.Id)
.AddAdditionalDocument(leftDocumentId, document.Name, oldBuffer.AsTextContainer().CurrentText);
var leftDocument = leftSolution.GetAdditionalDocument(leftDocumentId);
var leftWorkspace = new PreviewWorkspace(leftSolution);
leftWorkspace.OpenAdditionalDocument(leftDocumentId);
return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken);
}
public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken)
{
return CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, DefaultZoomLevel, cancellationToken);
}
public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Note: We don't use the original buffer that is associated with oldDocument
// (and currently open in the editor) for oldBuffer below. This is because oldBuffer
// will be used inside a projection buffer inside our inline diff preview below
// and platform's implementation currently has a bug where projection buffers
// are being leaked. This leak means that if we use the original buffer that is
// currently visible in the editor here, the projection buffer span calculation
// would be triggered every time user changes some code in this buffer (even though
// the diff view would long have been dismissed by the time user edits the code)
// resulting in crashes. Instead we create a new buffer from the same content.
// TODO: We could use ITextBufferCloneService instead here to clone the original buffer.
var oldBuffer = CreateNewBuffer(oldDocument, cancellationToken);
var newBuffer = CreateNewBuffer(newDocument, cancellationToken);
// Convert the diffs to be line based.
// Compute the diffs between the old text and the new.
var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken);
// Need to show the spans in the right that are different.
// We also need to show the spans that are in conflict.
var originalSpans = GetOriginalSpans(diffResult, cancellationToken);
var changedSpans = GetChangedSpans(diffResult, cancellationToken);
var description = default(string);
var allSpans = default(NormalizedSpanCollection);
if (newDocument.SupportsSyntaxTree)
{
var newRoot = newDocument.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var conflictNodes = newRoot.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind);
var conflictSpans = conflictNodes.Select(n => n.Span.ToSpan()).ToList();
var conflictDescriptions = conflictNodes.SelectMany(n => n.GetAnnotations(ConflictAnnotation.Kind))
.Select(a => ConflictAnnotation.GetDescription(a))
.Distinct();
var warningNodes = newRoot.GetAnnotatedNodesAndTokens(WarningAnnotation.Kind);
var warningSpans = warningNodes.Select(n => n.Span.ToSpan()).ToList();
var warningDescriptions = warningNodes.SelectMany(n => n.GetAnnotations(WarningAnnotation.Kind))
.Select(a => WarningAnnotation.GetDescription(a))
.Distinct();
AttachConflictAndWarningAnnotationToBuffer(newBuffer, conflictSpans, warningSpans);
description = conflictSpans.Count == 0 && warningSpans.Count == 0
? null
: string.Join(Environment.NewLine, conflictDescriptions.Concat(warningDescriptions));
allSpans = new NormalizedSpanCollection(conflictSpans.Concat(warningSpans).Concat(changedSpans));
}
else
{
allSpans = new NormalizedSpanCollection(changedSpans);
}
var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken);
var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, allSpans, cancellationToken);
if (!originalLineSpans.Any())
{
// This means that we have no differences (likely because of conflicts).
// In such cases, use the same spans for the left (old) buffer as the right (new) buffer.
originalLineSpans = changedLineSpans;
}
// Create PreviewWorkspaces around the buffers to be displayed on the left and right
// so that all IDE services (colorizer, squiggles etc.) light up in these buffers.
var leftDocument = oldDocument.Project
.RemoveDocument(oldDocument.Id)
.AddDocument(oldDocument.Name, oldBuffer.AsTextContainer().CurrentText, oldDocument.Folders, oldDocument.FilePath);
var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution);
leftWorkspace.OpenDocument(leftDocument.Id);
var rightWorkspace = new PreviewWorkspace(
newDocument.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution);
rightWorkspace.OpenDocument(newDocument.Id);
return CreateChangedDocumentViewAsync(
oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans,
leftWorkspace, rightWorkspace, zoomLevel, cancellationToken);
}
public Task<object> CreateChangedAdditionalDocumentPreviewViewAsync(TextDocument oldDocument, TextDocument newDocument, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Note: We don't use the original buffer that is associated with oldDocument
// (and currently open in the editor) for oldBuffer below. This is because oldBuffer
// will be used inside a projection buffer inside our inline diff preview below
// and platform's implementation currently has a bug where projection buffers
// are being leaked. This leak means that if we use the original buffer that is
// currently visible in the editor here, the projection buffer span calculation
// would be triggered every time user changes some code in this buffer (even though
// the diff view would long have been dismissed by the time user edits the code)
// resulting in crashes. Instead we create a new buffer from the same content.
// TODO: We could use ITextBufferCloneService instead here to clone the original buffer.
var oldBuffer = CreateNewPlainTextBuffer(oldDocument, cancellationToken);
var newBuffer = CreateNewPlainTextBuffer(newDocument, cancellationToken);
// Convert the diffs to be line based.
// Compute the diffs between the old text and the new.
var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken);
// Need to show the spans in the right that are different.
var originalSpans = GetOriginalSpans(diffResult, cancellationToken);
var changedSpans = GetChangedSpans(diffResult, cancellationToken);
string description = null;
var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken);
var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, changedSpans, cancellationToken);
// TODO: Why aren't we attaching conflict / warning annotations here like we do for regular documents above?
// Create PreviewWorkspaces around the buffers to be displayed on the left and right
// so that all IDE services (colorizer, squiggles etc.) light up in these buffers.
var leftDocumentId = DocumentId.CreateNewId(oldDocument.Project.Id);
var leftSolution = oldDocument.Project.Solution
.RemoveAdditionalDocument(oldDocument.Id)
.AddAdditionalDocument(leftDocumentId, oldDocument.Name, oldBuffer.AsTextContainer().CurrentText);
var leftWorkspace = new PreviewWorkspace(leftSolution);
leftWorkspace.OpenAdditionalDocument(leftDocumentId);
var rightWorkSpace = new PreviewWorkspace(
oldDocument.Project.Solution.WithAdditionalDocumentText(oldDocument.Id, newBuffer.AsTextContainer().CurrentText));
rightWorkSpace.OpenAdditionalDocument(newDocument.Id);
return CreateChangedDocumentViewAsync(
oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans,
leftWorkspace, rightWorkSpace, zoomLevel, cancellationToken);
}
private Task<object> CreateChangedDocumentViewAsync(ITextBuffer oldBuffer, ITextBuffer newBuffer, string description,
List<LineSpan> originalSpans, List<LineSpan> changedSpans, PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace,
double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (!(originalSpans.Any() && changedSpans.Any()))
{
// Both line spans must be non-empty. Otherwise, below projection buffer factory API call will throw.
// So if either is empty (signaling that there are no changes to preview in the document), then we bail out.
// This can happen in cases where the user has already applied the fix and light bulb has already been dismissed,
// but platform hasn't cancelled the preview operation yet. Since the light bulb has already been dismissed at
// this point, the preview that we return will never be displayed to the user. So returning null here is harmless.
return SpecializedTasks.Default<object>();
}
var originalBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation(
_contentTypeRegistryService,
_editorOptionsFactoryService.GlobalOptions,
oldBuffer.CurrentSnapshot,
"...",
description,
originalSpans.ToArray());
var changedBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation(
_contentTypeRegistryService,
_editorOptionsFactoryService.GlobalOptions,
newBuffer.CurrentSnapshot,
"...",
description,
changedSpans.ToArray());
return CreateNewDifferenceViewerAsync(leftWorkspace, rightWorkspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken);
}
private static void AttachConflictAndWarningAnnotationToBuffer(ITextBuffer newBuffer, IEnumerable<Span> conflictSpans, IEnumerable<Span> warningSpans)
{
// Attach the spans to the buffer.
newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.ConflictSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, conflictSpans));
newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.WarningSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, warningSpans));
}
private ITextBuffer CreateNewBuffer(Document document, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// is it okay to create buffer from threads other than UI thread?
var contentTypeService = document.Project.LanguageServices.GetService<IContentTypeLanguageService>();
var contentType = contentTypeService.GetDefaultContentType();
return _textBufferFactoryService.CreateTextBuffer(document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType);
}
private ITextBuffer CreateNewPlainTextBuffer(TextDocument document, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var contentType = _textBufferFactoryService.TextContentType;
return _textBufferFactoryService.CreateTextBuffer(document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType);
}
private async Task<object> CreateNewDifferenceViewerAsync(PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace,
IProjectionBuffer originalBuffer, IProjectionBuffer changedBuffer, double zoomLevel, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// leftWorkspace can be null if the change is adding a document.
// rightWorkspace can be null if the change is removing a document.
// However both leftWorkspace and rightWorkspace can't be null at the same time.
Contract.ThrowIfTrue((leftWorkspace == null) && (rightWorkspace == null));
var diffBuffer = _differenceBufferService.CreateDifferenceBuffer(
originalBuffer, changedBuffer,
new StringDifferenceOptions(), disableEditing: true);
var diffViewer = _differenceViewerService.CreateDifferenceView(diffBuffer, _previewRoleSet);
diffViewer.Closed += (s, e) =>
{
if (leftWorkspace != null)
{
leftWorkspace.Dispose();
leftWorkspace = null;
}
if (rightWorkspace != null)
{
rightWorkspace.Dispose();
rightWorkspace = null;
}
};
const string DiffOverviewMarginName = "deltadifferenceViewerOverview";
if (leftWorkspace == null)
{
diffViewer.ViewMode = DifferenceViewMode.RightViewOnly;
diffViewer.RightView.ZoomLevel *= zoomLevel;
diffViewer.RightHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed;
}
else if (rightWorkspace == null)
{
diffViewer.ViewMode = DifferenceViewMode.LeftViewOnly;
diffViewer.LeftView.ZoomLevel *= zoomLevel;
diffViewer.LeftHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed;
}
else
{
diffViewer.ViewMode = DifferenceViewMode.Inline;
diffViewer.InlineView.ZoomLevel *= zoomLevel;
diffViewer.InlineHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed;
}
// Disable focus / tab stop for the diff viewer.
diffViewer.RightView.VisualElement.Focusable = false;
diffViewer.LeftView.VisualElement.Focusable = false;
diffViewer.InlineView.VisualElement.Focusable = false;
// This code path must be invoked on UI thread.
AssertIsForeground();
// We use ConfigureAwait(true) to stay on the UI thread.
await diffViewer.SizeToFitAsync().ConfigureAwait(true);
if (leftWorkspace != null)
{
leftWorkspace.EnableDiagnostic();
}
if (rightWorkspace != null)
{
rightWorkspace.EnableDiagnostic();
}
return diffViewer;
}
private List<LineSpan> CreateLineSpans(ITextSnapshot textSnapshot, NormalizedSpanCollection allSpans, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var result = new List<LineSpan>();
foreach (var span in allSpans)
{
cancellationToken.ThrowIfCancellationRequested();
var lineSpan = GetLineSpan(textSnapshot, span);
MergeLineSpans(result, lineSpan);
}
return result;
}
// Find the lines that surround the span of the difference. Try to expand the span to
// include both the previous and next lines so that we can show more context to the
// user.
private LineSpan GetLineSpan(
ITextSnapshot snapshot,
Span span)
{
var startLine = snapshot.GetLineNumberFromPosition(span.Start);
var endLine = snapshot.GetLineNumberFromPosition(span.End);
if (startLine > 0)
{
startLine--;
}
if (endLine < snapshot.LineCount)
{
endLine++;
}
return LineSpan.FromBounds(startLine, endLine);
}
// Adds a line span to the spans we've been collecting. If the line span overlaps or
// abuts a previous span then the two are merged.
private static void MergeLineSpans(List<LineSpan> lineSpans, LineSpan nextLineSpan)
{
if (lineSpans.Count > 0)
{
var lastLineSpan = lineSpans.Last();
// We merge them if there's no more than one line between the two. Otherwise
// we'd show "..." between two spans where we could just show the actual code.
if (nextLineSpan.Start >= lastLineSpan.Start && nextLineSpan.Start <= (lastLineSpan.End + 1))
{
nextLineSpan = LineSpan.FromBounds(lastLineSpan.Start, nextLineSpan.End);
lineSpans.RemoveAt(lineSpans.Count - 1);
}
}
lineSpans.Add(nextLineSpan);
}
private IHierarchicalDifferenceCollection ComputeEditDifferences(TextDocument oldDocument, TextDocument newDocument, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Get the text that's actually in the editor.
var oldText = oldDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var newText = newDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
// Defer to the editor to figure out what changes the client made.
var diffService = _differenceSelectorService.GetTextDifferencingService(
oldDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType());
diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService;
return diffService.DiffStrings(oldText.ToString(), newText.ToString(), new StringDifferenceOptions()
{
DifferenceType = StringDifferenceTypes.Word | StringDifferenceTypes.Line,
});
}
private NormalizedSpanCollection GetOriginalSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var lineSpans = new List<Span>();
foreach (var difference in diffResult)
{
cancellationToken.ThrowIfCancellationRequested();
var mappedSpan = diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left);
lineSpans.Add(mappedSpan);
}
return new NormalizedSpanCollection(lineSpans);
}
private NormalizedSpanCollection GetChangedSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var lineSpans = new List<Span>();
foreach (var difference in diffResult)
{
cancellationToken.ThrowIfCancellationRequested();
var mappedSpan = diffResult.RightDecomposition.GetSpanInOriginal(difference.Right);
lineSpans.Add(mappedSpan);
}
return new NormalizedSpanCollection(lineSpans);
}
}
}
| |
/*
Copyright 2010 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.CodeDom;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Google.Apis.Discovery;
using Google.Apis.Json;
namespace Google.Apis.Tools.CodeGen.Tests
{
/// <summary> Tests for the GeneratorUtils class. </summary>
[TestFixture]
public class GeneratorUtilsTest
{
/// <summary>
/// Tests the generation of safe parameter names
/// </summary>
[Test]
public void GetParameterNameTest()
{
var factory = ServiceFactory.Default;
var param = factory.CreateParameter("safeName", new JsonDictionary());
Assert.AreEqual("safeName", GeneratorUtils.GetParameterName(param, Enumerable.Empty<string>()));
param = factory.CreateParameter("string", new JsonDictionary());
Assert.AreEqual("stringValue", GeneratorUtils.GetParameterName(param, Enumerable.Empty<string>()));
param = factory.CreateParameter("String", new JsonDictionary());
Assert.AreEqual("stringValue", GeneratorUtils.GetParameterName(param, Enumerable.Empty<string>()));
param = factory.CreateParameter("SafeName", new JsonDictionary());
Assert.AreEqual("safeName", GeneratorUtils.GetParameterName(param, Enumerable.Empty<string>()));
}
/// <summary>
/// Tests the generation of safe member names
/// </summary>
[Test]
public void GetSafeMemberNameTest()
{
IList<string> simpleSafeWords = new List<string> { "unsafe", "words", "abound" };
Assert.AreEqual(
"fishBurger",
GeneratorUtils.GetSafeMemberName(simpleSafeWords, 0, "fishBurger"));
Assert.AreEqual(
"member",
GeneratorUtils.GetSafeMemberName(
simpleSafeWords, GeneratorUtils.TargetCase.ToLower, "!@#$$%^&^&**((())+}{|\":\\\t\r"));
foreach (string word in GeneratorUtils.UnsafeWords)
{
Assert.AreEqual(word + "Member", GeneratorUtils.GetSafeMemberName(GeneratorUtils.UnsafeWords, 0, word));
}
// Test the "basenameMember"-pattern
string[] unsafeWords = new string[GeneratorUtils.SafeMemberMaximumIndex];
for (int i = 0; i < unsafeWords.Length; i++)
unsafeWords[i] = "test" + (i == 0 ? "" : (i + 1).ToString());
Assert.AreEqual("testMember", GeneratorUtils.GetSafeMemberName(unsafeWords, 0, "test"));
}
/// <summary>
/// Tests if the LowerFirstLetter method works
/// </summary>
[Test]
public void LowwerFirstTest()
{
string upper = "ABC";
string lower = "aBC";
Assert.AreEqual(lower, GeneratorUtils.LowerFirstLetter(lower));
Assert.AreEqual(lower, GeneratorUtils.LowerFirstLetter(upper));
Assert.AreEqual("", GeneratorUtils.LowerFirstLetter(""));
Assert.AreEqual(null, GeneratorUtils.LowerFirstLetter(null));
}
/// <summary>
/// Tests if the UpperfirstLetter method works
/// </summary>
[Test]
public void UpperFirstTest()
{
string upper = "ABC";
string lower = "aBC";
Assert.AreEqual(upper, GeneratorUtils.UpperFirstLetter(lower));
Assert.AreEqual(upper, GeneratorUtils.UpperFirstLetter(upper));
Assert.AreEqual("", GeneratorUtils.UpperFirstLetter(""));
Assert.AreEqual(null, GeneratorUtils.UpperFirstLetter(null));
}
/// <summary>
/// Tests if the generator can generate valid body names
/// </summary>
[Test]
public void ValidBodyCharTest()
{
for (char c = 'A'; c <= 'Z'; c++)
{
Assert.IsTrue(GeneratorUtils.IsValidBodyChar(c), "Char " + c + " should be valid");
}
for (char c = 'a'; c <= 'z'; c++)
{
Assert.IsTrue(GeneratorUtils.IsValidBodyChar(c), "Char " + c + " should be valid");
}
for (char c = '0'; c <= '9'; c++)
{
Assert.IsTrue(GeneratorUtils.IsValidBodyChar(c), "Char " + c + " should be valid");
}
Assert.IsTrue(GeneratorUtils.IsValidBodyChar('_'));
for (char c = Char.MinValue; c < '0'; c++)
{
Assert.IsFalse(GeneratorUtils.IsValidBodyChar(c), "Char " + (int)c + " should be invalid");
}
for (char c = (char)('9' + 1); c < 'A'; c++)
{
Assert.IsFalse(GeneratorUtils.IsValidBodyChar(c), "Char " + (int)c + " should be invalid");
}
for (char c = (char)('Z' + 1); c < 'a'; c++)
{
if (c == '_')
{
continue;
}
Assert.IsFalse(GeneratorUtils.IsValidBodyChar(c), "Char " + (int)c + " should be invalid");
}
for (char c = (char)('z' + 1); c < Char.MaxValue; c++)
{
Assert.IsFalse(GeneratorUtils.IsValidBodyChar(c), "Char " + (int)c + " should be invalid");
}
}
/// <summary>
/// Tests if the generator will only generate valid first chars
/// </summary>
[Test]
public void ValidFirstCharTest()
{
for (char c = 'A'; c <= 'Z'; c++)
{
Assert.IsTrue(GeneratorUtils.IsValidFirstChar(c), "Char " + c + " should be valid");
}
for (char c = 'a'; c <= 'z'; c++)
{
Assert.IsTrue(GeneratorUtils.IsValidFirstChar(c), "Char " + c + " should be valid");
}
Assert.IsTrue(GeneratorUtils.IsValidBodyChar('_'));
for (char c = Char.MinValue; c < 'A'; c++)
{
Assert.IsFalse(GeneratorUtils.IsValidFirstChar(c), "Char " + (int)c + " should be invalid");
}
for (char c = (char)('Z' + 1); c < 'a'; c++)
{
if (c == '_')
{
continue;
}
Assert.IsFalse(GeneratorUtils.IsValidFirstChar(c), "Char " + (int)c + " should be invalid");
}
for (char c = (char)('z' + 1); c < Char.MaxValue; c++)
{
Assert.IsFalse(GeneratorUtils.IsValidFirstChar(c), "Char " + (int)c + " should be invalid");
}
}
/// <summary>
/// Tests the GetWordContextListFromClass method
/// </summary>
[Test]
public void GetWordContextListFromClassTest()
{
// Test validation.
Assert.Throws<ArgumentNullException>(() => GeneratorUtils.GetWordContextListFromClass(null).First());
// Test normal operation
var decl = new CodeTypeDeclaration();
decl.Name = "MockClass";
decl.Members.Add(new CodeMemberField(typeof(int), "FieldA"));
decl.Members.Add(new CodeMemberProperty() { Name = "FieldB" });
decl.Members.Add(new CodeTypeDeclaration() { Name = "NestedClassC" });
CollectionAssert.AreEqual(
new[] { "MockClass", "FieldA", "FieldB", "NestedClassC" },
GeneratorUtils.GetWordContextListFromClass(decl));
}
/// <summary>
/// Checks that the MakeValidMemberName method returns valid member names.
/// </summary>
[Test]
public void MakeValidMemberNameTest()
{
// Test empty strings.
Assert.AreEqual(null, GeneratorUtils.MakeValidMemberName(null));
Assert.AreEqual(null, GeneratorUtils.MakeValidMemberName(""));
// Tests strings consisting only out of invalid characters
Assert.AreEqual(null, GeneratorUtils.MakeValidMemberName("!@#"));
Assert.AreEqual(null, GeneratorUtils.MakeValidMemberName(" "));
Assert.AreEqual(null, GeneratorUtils.MakeValidMemberName("123456789"));
// Test valid names
Assert.AreEqual("SomeClassName2", GeneratorUtils.MakeValidMemberName("SomeClassName2"));
Assert.AreEqual("_memberName", GeneratorUtils.MakeValidMemberName("_memberName"));
// Test that invalid characters are removed
Assert.AreEqual("ref", GeneratorUtils.MakeValidMemberName("$ref"));
Assert.AreEqual("unknown", GeneratorUtils.MakeValidMemberName("(unknown)"));
Assert.AreEqual("FooBar", GeneratorUtils.MakeValidMemberName("Foo@bar"));
Assert.AreEqual("fooBar", GeneratorUtils.MakeValidMemberName("foo!@#$bar"));
}
/// <summary>
/// Confirms that the IsNameValidInContext method will recognize invalid names.
/// </summary>
[Test]
public void IsNameValidInContextTest()
{
string[] emptyList = new string[0];
string[] forbiddenContext = new[] { "evil", "foo", "bar", "INVALID" };
// Test with an empty name.
Assert.IsFalse(GeneratorUtils.IsNameValidInContext(null, emptyList));
Assert.IsFalse(GeneratorUtils.IsNameValidInContext("", emptyList));
// Test with a valid name.
Assert.IsTrue(GeneratorUtils.IsNameValidInContext("foobar", emptyList));
Assert.IsTrue(GeneratorUtils.IsNameValidInContext("foobar", forbiddenContext));
// Test with some invalid names.
Assert.IsFalse(GeneratorUtils.IsNameValidInContext("foo", forbiddenContext));
Assert.IsFalse(GeneratorUtils.IsNameValidInContext("evil", forbiddenContext));
// Confirm that character casing is valued.
Assert.IsTrue(GeneratorUtils.IsNameValidInContext("Foo", forbiddenContext));
Assert.IsTrue(GeneratorUtils.IsNameValidInContext("Evil", forbiddenContext));
Assert.IsTrue(GeneratorUtils.IsNameValidInContext("invalid", forbiddenContext));
Assert.IsFalse(GeneratorUtils.IsNameValidInContext("INVALID", forbiddenContext));
}
/// <summary>
/// Tests the AlterCase method.
/// </summary>
[Test]
public void AlterFirstCharCaseTest()
{
// Test empty strings.
Assert.IsNull(GeneratorUtils.AlterFirstCharCase(null, GeneratorUtils.TargetCase.ToLower));
Assert.AreEqual("", GeneratorUtils.AlterFirstCharCase("", GeneratorUtils.TargetCase.ToLower));
// Test the ToLower variant.
Assert.AreEqual("a", GeneratorUtils.AlterFirstCharCase("A", GeneratorUtils.TargetCase.ToLower));
Assert.AreEqual("a", GeneratorUtils.AlterFirstCharCase("a", GeneratorUtils.TargetCase.ToLower));
// Test the ToUpper variant.
Assert.AreEqual("A", GeneratorUtils.AlterFirstCharCase("a", GeneratorUtils.TargetCase.ToUpper));
Assert.AreEqual("A", GeneratorUtils.AlterFirstCharCase("A", GeneratorUtils.TargetCase.ToUpper));
// Test the DontChange variant.
Assert.AreEqual("a", GeneratorUtils.AlterFirstCharCase("a", GeneratorUtils.TargetCase.DontChange));
Assert.AreEqual("A", GeneratorUtils.AlterFirstCharCase("A", GeneratorUtils.TargetCase.DontChange));
// Test a more complex string.
Assert.AreEqual("FooBar", GeneratorUtils.AlterFirstCharCase("fooBar", GeneratorUtils.TargetCase.ToUpper));
Assert.AreEqual("fooBar", GeneratorUtils.AlterFirstCharCase("FooBar", GeneratorUtils.TargetCase.ToLower));
}
/// <summary>
/// Confirm the returned enumeration of the AppendIndices method.
/// </summary>
[Test]
public void AppendIndicesTest()
{
Assert.Throws<ArgumentException>(() => GeneratorUtils.AppendIndices("test", 10, 1).First());
CollectionAssert.AreEqual(new string[0], GeneratorUtils.AppendIndices(null, 1, 5));
CollectionAssert.AreEqual(new string[0], GeneratorUtils.AppendIndices("", 1, 5));
CollectionAssert.AreEqual(new[] { "abc1", "abc2", "abc3" }, GeneratorUtils.AppendIndices("abc", 1, 3));
}
/// <summary>
/// Test for GenerateAlternativeNamesFor method.
/// </summary>
[Test]
public void GenerateAlternativeNamesForTest()
{
// Generate the list of expected values.
IEnumerable<string> expect = new[] { "to", "toMember" };
expect = expect.Concat(GeneratorUtils.AppendIndices("to", 2, GeneratorUtils.SafeMemberMaximumIndex));
expect = expect.Concat(GeneratorUtils.AppendIndices("toMember", 2, GeneratorUtils.SafeMemberMaximumIndex));
// Compare with the implementation.
IEnumerable<string> alternatives = GeneratorUtils.GenerateAlternativeNamesFor("to");
CollectionAssert.AreEquivalent(expect, alternatives);
}
/// <summary>
/// Tests the GetPropertyName method.
/// </summary>
[Test]
public void GetPropertyNameTest()
{
Assert.AreEqual("Test", GeneratorUtils.GetPropertyName("test", new string[0]));
Assert.AreEqual("ETag", GeneratorUtils.GetPropertyName("etag", new string[0]));
Assert.AreEqual("ETagValue", GeneratorUtils.GetPropertyName("etag", new[] { "ETag" }));
}
/// <summary>
/// Tests the GetEnumName method.
/// </summary>
[Test]
public void GetEnumNameTest()
{
Assert.AreEqual("Test", GeneratorUtils.GetEnumName("test", new string[0]));
Assert.AreEqual("TestEnum", GeneratorUtils.GetEnumName("test", new[] { "Test" }));
Assert.AreEqual("TestMember", GeneratorUtils.GetEnumName("test", new[] { "Test", "TestEnum" }));
}
/// <summary>
/// Tests the GetEnumValueName method.
/// </summary>
[Test]
public void GetEnumValueNameTest()
{
Assert.AreEqual("Test", GeneratorUtils.GetEnumValueName("test", new string[0]));
Assert.AreEqual("TestValue", GeneratorUtils.GetEnumValueName("test", new[] { "Test" }));
Assert.AreEqual("TestMember", GeneratorUtils.GetEnumValueName("test", new[] { "Test", "TestValue" }));
}
/// <summary>
/// Tests the GetSchemaReference method.
/// </summary>
[Test]
public void GetSchemaReferenceTest()
{
Assert.Throws<ArgumentNullException>(() => GeneratorUtils.GetSchemaReference("Namespace", null));
Assert.Throws<ArgumentException>(() => GeneratorUtils.GetSchemaReference("Namespace", ""));
Assert.Throws<ArgumentNullException>(() => GeneratorUtils.GetSchemaReference(null, "Type"));
Assert.Throws<ArgumentException>(() => GeneratorUtils.GetSchemaReference("", "Type"));
Assert.AreEqual("Namespace.Type", GeneratorUtils.GetSchemaReference("Namespace", "Type").BaseType);
}
/// <summary>
/// Tests the FindPropertyByName method.
/// </summary>
[Test]
public void FindPropertyByNameTest()
{
CodeTypeMemberCollection collection = null;
Assert.Throws(typeof(ArgumentNullException), () => collection.FindPropertyByName(null));
Assert.Throws(typeof(ArgumentNullException), () => collection.FindPropertyByName("name"));
collection = new CodeTypeMemberCollection(new[] { new CodeTypeMember(), });
Assert.Throws(typeof(ArgumentNullException), () => collection.FindPropertyByName(null));
Assert.Throws(typeof(ArgumentException), () => collection.FindPropertyByName(""));
Assert.IsNull(collection.FindPropertyByName("AnyString"));
collection.Add(CreateMemberProperty("Fish"));
collection.Add(CreateMemberProperty("Cat"));
collection.Add(CreateMemberProperty("Tree"));
collection.Add(CreateMemberProperty("House"));
CodeTypeMember willNotFind = new CodeMemberMethod();
willNotFind.Name = "WillNotFindMethod";
collection.Add(willNotFind);
willNotFind = new CodeMemberField();
willNotFind.Name = "WillNotFindField";
collection.Add(willNotFind);
willNotFind = new CodeMemberEvent();
willNotFind.Name = "WillNotFindEvent";
collection.Add(willNotFind);
Assert.IsNull(collection.FindPropertyByName("AnyString"));
Assert.IsNull(collection.FindPropertyByName("WillNotFindMethod"));
Assert.IsNull(collection.FindPropertyByName("WillNotFindField"));
Assert.IsNull(collection.FindPropertyByName("WillNotFindEvent"));
Assert.IsNotNull(collection.FindPropertyByName("Fish"));
Assert.IsNotNull(collection.FindPropertyByName("Cat"));
Assert.IsNotNull(collection.FindPropertyByName("Tree"));
Assert.IsNotNull(collection.FindPropertyByName("House"));
Assert.AreEqual("Fish", collection.FindPropertyByName("Fish").Name);
Assert.AreEqual("Cat", collection.FindPropertyByName("Cat").Name);
Assert.AreEqual("Tree", collection.FindPropertyByName("Tree").Name);
Assert.AreEqual("House", collection.FindPropertyByName("House").Name);
}
/// <summary>
/// Tests the FindMemberByName method.
/// </summary>
[Test]
public void FindMemberByNameTest()
{
CodeTypeMemberCollection collection = null;
Assert.Throws(typeof(ArgumentNullException), () => collection.FindMemberByName(null));
Assert.Throws(typeof(ArgumentNullException), () => collection.FindMemberByName("name"));
collection = new CodeTypeMemberCollection(new[] { new CodeTypeMember(), });
Assert.Throws(typeof(ArgumentNullException), () => collection.FindMemberByName(null));
Assert.Throws(typeof(ArgumentException), () => collection.FindMemberByName(""));
Assert.IsNull(collection.FindMemberByName("AnyString"));
collection.Add(CreateMemberProperty("Fish"));
collection.Add(CreateMemberProperty("Cat"));
collection.Add(CreateMemberProperty("Tree"));
collection.Add(CreateMemberProperty("House"));
CodeTypeMember willAlsoFind = new CodeMemberMethod();
willAlsoFind.Name = "WillAlsoFindMethod";
collection.Add(willAlsoFind);
willAlsoFind = new CodeMemberField();
willAlsoFind.Name = "WillAlsoFindField";
collection.Add(willAlsoFind);
willAlsoFind = new CodeMemberEvent();
willAlsoFind.Name = "WillAlsoFindEvent";
collection.Add(willAlsoFind);
Assert.IsNull(collection.FindMemberByName("AnyString"));
Assert.IsNotNull(collection.FindMemberByName("WillAlsoFindMethod"));
Assert.IsNotNull(collection.FindMemberByName("WillAlsoFindField"));
Assert.IsNotNull(collection.FindMemberByName("WillAlsoFindEvent"));
Assert.IsNotNull(collection.FindMemberByName("Fish"));
Assert.IsNotNull(collection.FindMemberByName("Cat"));
Assert.IsNotNull(collection.FindMemberByName("Tree"));
Assert.IsNotNull(collection.FindMemberByName("House"));
Assert.AreEqual("Fish", collection.FindMemberByName("Fish").Name);
Assert.AreEqual("Cat", collection.FindMemberByName("Cat").Name);
Assert.AreEqual("Tree", collection.FindMemberByName("Tree").Name);
Assert.AreEqual("House", collection.FindMemberByName("House").Name);
}
private CodeMemberProperty CreateMemberProperty(string name)
{
var member = new CodeMemberProperty();
member.Name = name;
return member;
}
/// <summary>
/// Tests the FindMemberByName method.
/// </summary>
[Test]
public void FindTypeMemberByNameTest()
{
CodeTypeMemberCollection collection = null;
Assert.Throws(typeof(ArgumentNullException), () => collection.FindTypeMemberByName(null));
Assert.Throws(typeof(ArgumentNullException), () => collection.FindTypeMemberByName("name"));
collection = new CodeTypeMemberCollection(new[] { new CodeTypeMember(), });
Assert.Throws(typeof(ArgumentNullException), () => collection.FindTypeMemberByName(null));
Assert.Throws(typeof(ArgumentException), () => collection.FindTypeMemberByName(""));
Assert.IsNull(collection.FindTypeMemberByName("AnyString"));
collection.Add(CreateMemberProperty("Fish"));
CodeTypeMember member = new CodeMemberMethod();
member.Name = "Method";
collection.Add(member);
member = new CodeMemberField();
member.Name = "Field";
collection.Add(member);
member = new CodeMemberEvent();
member.Name = "Event";
collection.Add(member);
collection.Add(new CodeTypeDeclaration() { Name = "Class" });
Assert.IsNull(collection.FindTypeMemberByName("AnyString"));
Assert.IsNull(collection.FindTypeMemberByName("Method"));
Assert.IsNull(collection.FindTypeMemberByName("Field"));
Assert.IsNull(collection.FindTypeMemberByName("Event"));
Assert.IsNull(collection.FindTypeMemberByName("Fish"));
Assert.IsNotNull(collection.FindTypeMemberByName("Class"));
Assert.AreEqual("Class", collection.FindTypeMemberByName("Class").Name);
}
[Test, Sequential]
public void GetNamespaceNameTest(
[Values("v1", "__", "1.1", "v1-sandbox", "")] string inName,
[Values("v1", "__", "_1_1", "v1_sandbox", null)] string outName)
{
Assert.That(GeneratorUtils.GetNamespaceName(inName), Is.EqualTo(outName));
}
}
}
| |
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Mono.Security.Protocol.Tls.Handshake;
namespace Mono.Security.Protocol.Tls
{
#region Delegates
public delegate bool CertificateValidationCallback(
X509Certificate certificate,
int[] certificateErrors);
public class ValidationResult {
bool trusted;
bool user_denied;
int error_code;
public ValidationResult (bool trusted, bool user_denied, int error_code)
{
this.trusted = trusted;
this.user_denied = user_denied;
this.error_code = error_code;
}
public bool Trusted {
get { return trusted; }
}
public bool UserDenied {
get { return user_denied; }
}
public int ErrorCode {
get { return error_code; }
}
}
#if MOONLIGHT
internal
#else
public
#endif
delegate ValidationResult CertificateValidationCallback2 (Mono.Security.X509.X509CertificateCollection collection);
public delegate X509Certificate CertificateSelectionCallback(
X509CertificateCollection clientCertificates,
X509Certificate serverCertificate,
string targetHost,
X509CertificateCollection serverRequestedCertificates);
public delegate AsymmetricAlgorithm PrivateKeySelectionCallback(
X509Certificate certificate,
string targetHost);
#endregion
public class SslClientStream : SslStreamBase
{
#region Internal Events
internal event CertificateValidationCallback ServerCertValidation;
internal event CertificateSelectionCallback ClientCertSelection;
internal event PrivateKeySelectionCallback PrivateKeySelection;
#endregion
#region Properties
// required by HttpsClientStream for proxy support
internal Stream InputBuffer
{
get { return base.inputBuffer; }
}
public X509CertificateCollection ClientCertificates
{
get { return this.context.ClientSettings.Certificates; }
}
public X509Certificate SelectedClientCertificate
{
get { return this.context.ClientSettings.ClientCertificate; }
}
#endregion
#region Callback Properties
public CertificateValidationCallback ServerCertValidationDelegate
{
get { return this.ServerCertValidation; }
set { this.ServerCertValidation = value; }
}
public CertificateSelectionCallback ClientCertSelectionDelegate
{
get { return this.ClientCertSelection; }
set { this.ClientCertSelection = value; }
}
public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate
{
get { return this.PrivateKeySelection; }
set { this.PrivateKeySelection = value; }
}
#endregion
#if MOONLIGHT
internal event CertificateValidationCallback2 ServerCertValidation2;
#else
public event CertificateValidationCallback2 ServerCertValidation2;
#endif
#region Constructors
public SslClientStream(
Stream stream,
string targetHost,
bool ownsStream)
: this(
stream, targetHost, ownsStream,
SecurityProtocolType.Default, null)
{
}
public SslClientStream(
Stream stream,
string targetHost,
X509Certificate clientCertificate)
: this(
stream, targetHost, false, SecurityProtocolType.Default,
new X509CertificateCollection(new X509Certificate[]{clientCertificate}))
{
}
public SslClientStream(
Stream stream,
string targetHost,
X509CertificateCollection clientCertificates) :
this(
stream, targetHost, false, SecurityProtocolType.Default,
clientCertificates)
{
}
public SslClientStream(
Stream stream,
string targetHost,
bool ownsStream,
SecurityProtocolType securityProtocolType)
: this(
stream, targetHost, ownsStream, securityProtocolType,
new X509CertificateCollection())
{
}
public SslClientStream(
Stream stream,
string targetHost,
bool ownsStream,
SecurityProtocolType securityProtocolType,
X509CertificateCollection clientCertificates):
base(stream, ownsStream)
{
if (targetHost == null || targetHost.Length == 0)
{
throw new ArgumentNullException("targetHost is null or an empty string.");
}
this.context = new ClientContext(
this,
securityProtocolType,
targetHost,
clientCertificates);
this.protocol = new ClientRecordProtocol(innerStream, (ClientContext)this.context);
}
#endregion
#region Finalizer
~SslClientStream()
{
base.Dispose(false);
}
#endregion
#region IDisposable Methods
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
this.ServerCertValidation = null;
this.ClientCertSelection = null;
this.PrivateKeySelection = null;
this.ServerCertValidation2 = null;
}
}
#endregion
#region Handshake Methods
/*
Client Server
ClientHello -------->
ServerHello
Certificate*
ServerKeyExchange*
CertificateRequest*
<-------- ServerHelloDone
Certificate*
ClientKeyExchange
CertificateVerify*
[ChangeCipherSpec]
Finished -------->
[ChangeCipherSpec]
<-------- Finished
Application Data <-------> Application Data
Fig. 1 - Message flow for a full handshake
*/
internal override IAsyncResult OnBeginNegotiateHandshake(AsyncCallback callback, object state)
{
try
{
if (this.context.HandshakeState != HandshakeState.None)
{
this.context.Clear();
}
// Obtain supported cipher suites
this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(this.context.SecurityProtocol);
// Set handshake state
this.context.HandshakeState = HandshakeState.Started;
// Send client hello
return this.protocol.BeginSendRecord(HandshakeType.ClientHello, callback, state);
}
catch (TlsException ex)
{
this.protocol.SendAlert(ex.Alert);
throw new IOException("The authentication or decryption has failed.", ex);
}
catch (Exception ex)
{
this.protocol.SendAlert(AlertDescription.InternalError);
throw new IOException("The authentication or decryption has failed.", ex);
}
}
private void SafeReceiveRecord (Stream s)
{
byte[] record = this.protocol.ReceiveRecord (s);
if ((record == null) || (record.Length == 0)) {
throw new TlsException (
AlertDescription.HandshakeFailiure,
"The server stopped the handshake.");
}
}
internal override void OnNegotiateHandshakeCallback(IAsyncResult asyncResult)
{
this.protocol.EndSendRecord(asyncResult);
// Read server response
while (this.context.LastHandshakeMsg != HandshakeType.ServerHelloDone)
{
// Read next record
SafeReceiveRecord (this.innerStream);
// special case for abbreviated handshake where no ServerHelloDone is sent from the server
if (this.context.AbbreviatedHandshake && (this.context.LastHandshakeMsg == HandshakeType.ServerHello))
break;
}
// the handshake is much easier if we can reuse a previous session settings
if (this.context.AbbreviatedHandshake)
{
ClientSessionCache.SetContextFromCache (this.context);
this.context.Negotiating.Cipher.ComputeKeys ();
this.context.Negotiating.Cipher.InitializeCipher ();
// Send Cipher Spec protocol
this.protocol.SendChangeCipherSpec ();
// Read record until server finished is received
while (this.context.HandshakeState != HandshakeState.Finished)
{
// If all goes well this will process messages:
// Change Cipher Spec
// Server finished
SafeReceiveRecord (this.innerStream);
}
// Send Finished message
this.protocol.SendRecord (HandshakeType.Finished);
}
else
{
// Send client certificate if requested
// even if the server ask for it it _may_ still be optional
bool clientCertificate = this.context.ServerSettings.CertificateRequest;
// NOTE: sadly SSL3 and TLS1 differs in how they handle this and
// the current design doesn't allow a very cute way to handle
// SSL3 alert warning for NoCertificate (41).
if (this.context.SecurityProtocol == SecurityProtocolType.Ssl3)
{
clientCertificate = ((this.context.ClientSettings.Certificates != null) &&
(this.context.ClientSettings.Certificates.Count > 0));
// this works well with OpenSSL (but only for SSL3)
}
if (clientCertificate)
{
this.protocol.SendRecord(HandshakeType.Certificate);
}
// Send Client Key Exchange
this.protocol.SendRecord(HandshakeType.ClientKeyExchange);
// Now initialize session cipher with the generated keys
this.context.Negotiating.Cipher.InitializeCipher();
// Send certificate verify if requested (optional)
if (clientCertificate && (this.context.ClientSettings.ClientCertificate != null))
{
this.protocol.SendRecord(HandshakeType.CertificateVerify);
}
// Send Cipher Spec protocol
this.protocol.SendChangeCipherSpec ();
// Send Finished message
this.protocol.SendRecord (HandshakeType.Finished);
// Read record until server finished is received
while (this.context.HandshakeState != HandshakeState.Finished) {
// If all goes well this will process messages:
// Change Cipher Spec
// Server finished
SafeReceiveRecord (this.innerStream);
}
}
// Reset Handshake messages information
this.context.HandshakeMessages.Reset ();
// Clear Key Info
this.context.ClearKeyInfo();
}
#endregion
#region Event Methods
internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
{
if (this.ClientCertSelection != null)
{
return this.ClientCertSelection(
clientCertificates,
serverCertificate,
targetHost,
serverRequestedCertificates);
}
return null;
}
internal override bool HaveRemoteValidation2Callback {
get { return ServerCertValidation2 != null; }
}
internal override ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
{
CertificateValidationCallback2 cb = ServerCertValidation2;
if (cb != null)
return cb (collection);
return null;
}
internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors)
{
if (this.ServerCertValidation != null)
{
return this.ServerCertValidation(certificate, errors);
}
return (errors != null && errors.Length == 0);
}
internal virtual bool RaiseServerCertificateValidation(
X509Certificate certificate,
int[] certificateErrors)
{
return base.RaiseRemoteCertificateValidation(certificate, certificateErrors);
}
internal virtual ValidationResult RaiseServerCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
{
return base.RaiseRemoteCertificateValidation2 (collection);
}
internal X509Certificate RaiseClientCertificateSelection(
X509CertificateCollection clientCertificates,
X509Certificate serverCertificate,
string targetHost,
X509CertificateCollection serverRequestedCertificates)
{
return base.RaiseLocalCertificateSelection(clientCertificates, serverCertificate, targetHost, serverRequestedCertificates);
}
internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost)
{
if (this.PrivateKeySelection != null)
{
return this.PrivateKeySelection(certificate, targetHost);
}
return null;
}
internal AsymmetricAlgorithm RaisePrivateKeySelection(
X509Certificate certificate,
string targetHost)
{
return base.RaiseLocalPrivateKeySelection(certificate, targetHost);
}
#endregion
}
}
| |
/*
* XslCompiledTransform.cs - Implementation of "System.Xml.Xsl.XslCompiledTransform"
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* Contributed by Klaus.T.
*
* 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
*/
#if !ECMA_COMPAT
#if CONFIG_FRAMEWORK_2_0
#if CONFIG_XPATH && CONFIG_XSL
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.CodeDom.Compiler;
using System.Security.Policy;
namespace System.Xml.Xsl
{
public sealed class XslCompiledTransform
{
private Boolean debugEnabled;
public XslCompiledTransform()
{
debugEnabled = false;
}
public XslCompiledTransform(Boolean enableDebug)
{
debugEnabled = enableDebug;
}
[TODO]
public XmlWriterSettings OutputSettings
{
get
{
// derieved from the xsl::output element of a compiled
// stylesheet.
return null;
}
}
[TODO]
public TempFileCollection TemporaryFiles
{
get
{
// is null if debugging is not enabled and Load was not
// successfully called
return null;
}
}
[TODO]
public void Load(IXPathNavigable stylesheet)
{
throw new NotImplementedException("Load");
}
[TODO]
public void Load(String stylesheetUri)
{
throw new NotImplementedException("Load(String)");
}
[TODO]
public void Load(XmlReader stylesheet)
{
throw new NotImplementedException("Load(XmlReader)");
}
[TODO]
public void Load(IXPathNavigable stylesheet, XsltSettings settings,
XmlResolver stylesheetResolver)
{
throw new NotImplementedException("Load(IXPathNavigable, XsltSettings, XmlResolver)");
}
[TODO]
public void Load(String stylesheetUri, XsltSettings settings,
XmlResolver stylesheetResolver)
{
throw new NotImplementedException("Load(String, XsltSettings, XmlResolver)");
}
[TODO]
public void Load(XmlReader stylesheet, XsltSettings settings,
XmlResolver stylesheetResolver)
{
throw new NotImplementedException("Load(XmlReader, XsltSettings, XmlResolver)");
}
[TODO]
public void Transform(IXPathNavigable input, XmlWriter results)
{
throw new NotImplementedException("Transform(IXPathNavigable, XmlWriter)");
}
[TODO]
public void Transform(String inputUri, String resultsFile)
{
if(inputUri == null)
{
throw new ArgumentNullException("inputUri");
}
if(resultsFile == null)
{
throw new ArgumentNullException("resultsFile");
}
throw new NotImplementedException("Transform(String, String)");
}
[TODO]
public void Transform(String inputUri, XmlWriter results)
{
if(inputUri == null)
{
throw new ArgumentNullException("inputUri");
}
if(results == null)
{
throw new ArgumentNullException("results");
}
throw new NotImplementedException("Transform(String, XmlWriter)");
}
[TODO]
public void Transform(XmlReader input, XmlWriter results)
{
if(input == null)
{
throw new ArgumentNullException("input");
}
if(results == null)
{
throw new ArgumentNullException("results");
}
throw new NotImplementedException("Transform(XmlReader, XmlWriter)");
}
[TODO]
public void Transform(IXPathNavigable input, XsltArgumentList arguments,
Stream results)
{
if(input == null)
{
throw new ArgumentNullException("input");
}
if(results == null)
{
throw new ArgumentNullException("results");
}
throw new NotImplementedException("Transform(IXPathNavigable, XsltArgumentList, Stream)");
}
[TODO]
public void Transform(IXPathNavigable input, XsltArgumentList arguments,
TextWriter results)
{
if(input == null)
{
throw new ArgumentNullException("input");
}
if(results == null)
{
throw new ArgumentNullException("results");
}
throw new NotImplementedException("Transform(IXPathNavigable, XsltArgumentList, TextWriter)");
}
[TODO]
public void Transform(IXPathNavigable input, XsltArgumentList arguments,
XmlWriter results)
{
if(input == null)
{
throw new ArgumentNullException("input");
}
if(results == null)
{
throw new ArgumentNullException("results");
}
throw new NotImplementedException("Transform(IXPathNavigable, XsltArgumentList, XmlWriter)");
}
[TODO]
public void Transform(String inputUri, XsltArgumentList arguments,
Stream results)
{
if(inputUri == null)
{
throw new ArgumentNullException("inputUri");
}
if(results == null)
{
throw new ArgumentNullException("results");
}
throw new NotImplementedException("Transform(String, XsltArgumentList, Stream)");
}
[TODO]
public void Transform(String inputUri, XsltArgumentList arguments,
TextWriter results)
{
if(inputUri == null)
{
throw new ArgumentNullException("inputUri");
}
if(results == null)
{
throw new ArgumentNullException("results");
}
throw new NotImplementedException("Transform(String, XsltArgumentList, TextWriter)");
}
[TODO]
public void Transform(String inputUri, XsltArgumentList arguments,
XmlWriter results)
{
if(inputUri == null)
{
throw new ArgumentNullException("inputUri");
}
if(results == null)
{
throw new ArgumentNullException("results");
}
throw new NotImplementedException("Transform(String, XsltArgumentList, XmlWriter)");
}
[TODO]
public void Transform(XmlReader input, XsltArgumentList arguments,
Stream results)
{
if(input == null)
{
throw new ArgumentNullException("input");
}
if(results == null)
{
throw new ArgumentNullException("results");
}
throw new NotImplementedException("Transform(XmlReader, XsltArgumentList, Stream)");
}
[TODO]
public void Transform(XmlReader input, XsltArgumentList arguments,
TextWriter results)
{
if(input == null)
{
throw new ArgumentNullException("input");
}
if(results == null)
{
throw new ArgumentNullException("results");
}
throw new NotImplementedException("Transform(XmlReader, XsltArgumentList, TextWriter)");
}
[TODO]
public void Transform(XmlReader input, XsltArgumentList arguments,
XmlWriter results)
{
if(input == null)
{
throw new ArgumentNullException("input");
}
if(results == null)
{
throw new ArgumentNullException("results");
}
throw new NotImplementedException("Transform(XmlReader, XsltArgumentList, XmlWriter)");
}
[TODO]
public void Transform(XmlReader input, XsltArgumentList arguments,
XmlWriter results, XmlResolver documentResolver)
{
if(input == null)
{
throw new ArgumentNullException("input");
}
if(results == null)
{
throw new ArgumentNullException("results");
}
throw new NotImplementedException("Transform(XmlReader, XsltArgumentList, XmlWriter, XmlResolver)");
}
}
} //namespace
#endif // CONFIG_XPATH && CONFIG_XSL
#endif // CONFIG_FRAMEWORK_2_0
#endif // !ECMA_COMPAT
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A convenience store.
/// </summary>
public class ConvenienceStore_Core : TypeCore, IStore
{
public ConvenienceStore_Core()
{
this._TypeId = 72;
this._Id = "ConvenienceStore";
this._Schema_Org_Url = "http://schema.org/ConvenienceStore";
string label = "";
GetLabel(out label, "ConvenienceStore", typeof(ConvenienceStore_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,252};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{252};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.ML.Data;
namespace Encog.MathUtil.Error
{
/// <summary>
/// Calculate the error of a neural network. Encog currently supports three error
/// calculation modes. See ErrorCalculationMode for more info.
/// </summary>
public class ErrorCalculation
{
/// <summary>
/// The current error calculation mode.
/// </summary>
private static ErrorCalculationMode _mode = ErrorCalculationMode.MSE;
/// <summary>
/// The overall error.
/// </summary>
private double _globalError;
/// <summary>
/// The size of a set.
/// </summary>
private int _setSize;
/// <summary>
/// The error calculation mode, this is static and therefore global to
/// all Encog training. If a particular training method only supports a
/// particular error calculation method, it may override this value. It will
/// not change the value set here, rather the training will occur with its
/// preferred training method. Currently the only training method that does
/// this is Levenberg Marquardt (LMA).
///
/// The default error mode for Encog is RMS.
/// </summary>
public static ErrorCalculationMode Mode
{
get { return _mode; }
set { _mode = value; }
}
/// <summary>
/// Returns the root mean square error for a complete training set.
/// </summary>
/// <returns>The current error for the neural network.</returns>
public double Calculate()
{
if (_setSize == 0)
{
return 0;
}
switch (Mode)
{
case ErrorCalculationMode.RMS:
return CalculateRMS();
case ErrorCalculationMode.MSE:
return CalculateMSE();
default:
return CalculateMSE();
}
}
/// <summary>
/// Calculate the error with MSE.
/// </summary>
/// <returns>The current error for the neural network.</returns>
public double CalculateMSE()
{
if (_setSize == 0)
{
return 0;
}
double err = _globalError/_setSize;
return err;
}
/// <summary>
/// Calculate the error with RMS.
/// </summary>
/// <returns>The current error for the neural network.</returns>
public double CalculateRMS()
{
if (_setSize == 0)
{
return 0;
}
double err = Math.Sqrt(_globalError/_setSize);
return err;
}
/// <summary>
/// Reset the error accumulation to zero.
/// </summary>
public void Reset()
{
_globalError = 0;
_setSize = 0;
}
/// <summary>
/// Called to update for each number that should be checked.
/// </summary>
/// <param name="actual">The actual number.</param>
/// <param name="ideal">The ideal number.</param>
/// <param name="significance">The significance of this error, 1.0 is the baseline.</param>
public void UpdateError(double[] actual, double[] ideal, double significance)
{
for (int i = 0; i < actual.Length; i++)
{
double delta = ideal[i] - actual[i];
_globalError += delta*delta;
}
_setSize += ideal.Length;
}
/// <summary>
/// Called to update for each number that should be checked.
/// </summary>
public void UpdateError(IMLData actual, IMLData ideal, double significance)
{
for(int i = 0; i < actual.Count; i++)
{
double delta = ideal[i] - actual[i];
_globalError += delta * delta;
}
_setSize += ideal.Count;
}
/// <summary>
/// Called to update for each number that should be checked.
/// </summary>
public void UpdateError(double[] actual, IMLData ideal, double significance)
{
for(int i = 0; i < actual.Length; i++)
{
double delta = ideal[i] - actual[i];
_globalError += delta * delta;
}
_setSize += ideal.Count;
}
/// <summary>
/// Called to update for each number that should be checked.
/// </summary>
public void UpdateError(IMLData actual, double[] ideal, double significance)
{
for(int i = 0; i < actual.Count; i++)
{
double delta = ideal[i] - actual[i];
_globalError += delta * delta;
}
_setSize += ideal.Length;
}
/// <summary>
/// Update the error with single values.
/// </summary>
/// <param name="actual">The actual value.</param>
/// <param name="ideal">The ideal value.</param>
public void UpdateError(double actual, double ideal)
{
double delta = ideal - actual;
_globalError += delta*delta;
_setSize++;
}
/// <summary>
/// Calculate the error as sum of squares.
/// </summary>
/// <returns>The error.</returns>
public double CalculateSSE()
{
return _globalError / 2;
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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 SensusService.Probes;
using SensusUI.UiProperties;
using System.Collections.Generic;
using System;
using Newtonsoft.Json;
using System.Threading;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
#if __ANDROID__
using Java.IO;
using Java.Util.Zip;
#elif __IOS__
using MiniZip.ZipArchive;
#else
#error "Unrecognized platform."
#endif
namespace SensusService.DataStores.Local
{
/// <summary>
/// Responsible for transferring data from probes to local media.
/// </summary>
public abstract class LocalDataStore : DataStore
{
private bool _uploadToRemoteDataStore;
[OnOffUiProperty("Upload to Remote:", true, 3)]
public bool UploadToRemoteDataStore
{
get { return _uploadToRemoteDataStore; }
set { _uploadToRemoteDataStore = value; }
}
protected LocalDataStore()
{
_uploadToRemoteDataStore = true;
#if DEBUG || UNIT_TESTING
CommitDelayMS = 5000; // 5 seconds...so we can see debugging output quickly
#else
CommitDelayMS = 60000;
#endif
}
protected sealed override List<Datum> GetDataToCommit(CancellationToken cancellationToken)
{
List<Datum> dataToCommit = new List<Datum>();
foreach (Probe probe in Protocol.Probes)
{
if (cancellationToken.IsCancellationRequested)
break;
// the collected data object comes directly from the probe, so lock it down before working with it.
ICollection<Datum> collectedData = probe.GetCollectedData();
if (collectedData != null)
lock (collectedData)
if (collectedData.Count > 0)
dataToCommit.AddRange(collectedData);
}
SensusServiceHelper.Get().Logger.Log("Retrieved " + dataToCommit.Count + " data elements from probes.", LoggingLevel.Normal, GetType());
return dataToCommit;
}
protected sealed override void ProcessCommittedData(List<Datum> committedData)
{
SensusServiceHelper.Get().Logger.Log("Clearing " + committedData.Count + " committed data elements from probes.", LoggingLevel.Normal, GetType());
foreach (Probe probe in Protocol.Probes)
probe.ClearDataCommittedToLocalDataStore(committedData);
SensusServiceHelper.Get().Logger.Log("Done clearing committed data elements from probes.", LoggingLevel.Normal, GetType());
}
public abstract List<Datum> GetDataForRemoteDataStore(CancellationToken cancellationToken);
public abstract void ClearDataCommittedToRemoteDataStore(List<Datum> dataCommittedToRemote);
public int WriteDataToZipFile(string zipPath, CancellationToken cancellationToken, Action<string, double> progressCallback)
{
// create a zip file to hold all data
#if __ANDROID__
ZipOutputStream zipFile = null;
#elif __IOS__
ZipArchive zipFile = null;
#endif
// write all data to separate JSON files. zip files for convenience.
string directory = null;
Dictionary<string, StreamWriter> datumTypeFile = new Dictionary<string, StreamWriter>();
try
{
string directoryName = Protocol.Name + "_Data_" + DateTime.UtcNow.ToShortDateString() + "_" + DateTime.UtcNow.ToShortTimeString();
directoryName = new Regex("[^a-zA-Z0-9]").Replace(directoryName, "_");
directory = Path.Combine(SensusServiceHelper.SHARE_DIRECTORY, directoryName);
if (Directory.Exists(directory))
Directory.Delete(directory, true);
Directory.CreateDirectory(directory);
if (progressCallback != null)
progressCallback("Gathering data...", 0);
int totalDataCount = 0;
foreach (Tuple<string, string> datumTypeLine in GetDataLinesToWrite(cancellationToken, progressCallback))
{
string datumType = datumTypeLine.Item1;
string line = datumTypeLine.Item2;
StreamWriter file;
if (datumTypeFile.TryGetValue(datumType, out file))
file.WriteLine(",");
else
{
file = new StreamWriter(Path.Combine(directory, datumType + ".json"));
file.WriteLine("[");
datumTypeFile.Add(datumType, file);
}
file.Write(line);
++totalDataCount;
}
// close all files
foreach (StreamWriter file in datumTypeFile.Values)
{
file.Write(Environment.NewLine + "]");
file.Close();
}
cancellationToken.ThrowIfCancellationRequested();
if (progressCallback != null)
progressCallback("Compressing data...", 0);
#if __ANDROID__
directoryName += '/';
zipFile = new ZipOutputStream(new FileStream(zipPath, FileMode.Create, FileAccess.Write));
zipFile.PutNextEntry(new ZipEntry(directoryName));
int dataWritten = 0;
foreach (string path in Directory.GetFiles(directory))
{
// start json file for data of current type
zipFile.PutNextEntry(new ZipEntry(directoryName + Path.GetFileName(path)));
using (StreamReader file = new StreamReader(path))
{
string line;
while ((line = file.ReadLine()) != null)
{
if (progressCallback != null && totalDataCount >= 10 && (dataWritten % (totalDataCount / 10)) == 0)
progressCallback(null, dataWritten / (double)totalDataCount);
cancellationToken.ThrowIfCancellationRequested();
zipFile.Write(file.CurrentEncoding.GetBytes(line + Environment.NewLine));
if (line != "[" && line != "]")
++dataWritten;
}
}
zipFile.CloseEntry();
System.IO.File.Delete(path);
}
// close entry for directory
zipFile.CloseEntry();
#elif __IOS__
zipFile = new ZipArchive();
zipFile.CreateZipFile(zipPath);
zipFile.AddFolder(directory, null);
#endif
if (progressCallback != null)
progressCallback(null, 1);
return totalDataCount;
}
finally
{
// ensure that zip file is closed.
try
{
if (zipFile != null)
{
#if __ANDROID__
zipFile.Close();
#elif __IOS__
zipFile.CloseZipFile();
#endif
}
}
catch (Exception)
{
}
// ensure that all temporary files are closed/deleted.
foreach (string datumType in datumTypeFile.Keys)
{
try
{
datumTypeFile[datumType].Close();
}
catch (Exception)
{
}
}
try
{
Directory.Delete(directory, true);
}
catch (Exception)
{
}
}
}
protected abstract IEnumerable<Tuple<string, string>> GetDataLinesToWrite(CancellationToken cancellationToken, Action<string, double> progressCallback);
}
}
| |
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 Commerce.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;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using John.Doyle.Mediocore.Developer.Areas.HelpPage.ModelDescriptions;
using John.Doyle.Mediocore.Developer.Areas.HelpPage.Models;
namespace John.Doyle.Mediocore.Developer.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Signum.Entities.Reflection;
using Signum.Utilities;
using Signum.Utilities.Reflection;
using Signum.Utilities.ExpressionTrees;
namespace Signum.Entities
{
[Serializable, DescriptionOptions(DescriptionOptions.Members), InTypeScript(false)]
public abstract class MixinEntity : ModifiableEntity
{
protected MixinEntity(ModifiableEntity mainEntity, MixinEntity? next)
{
this.mainEntity = mainEntity;
this.next = next;
}
[Ignore]
readonly MixinEntity? next;
[HiddenProperty]
public MixinEntity? Next
{
get { return next; }
}
[Ignore]
readonly ModifiableEntity mainEntity;
[HiddenProperty]
public ModifiableEntity MainEntity
{
get { return mainEntity; }
}
protected internal virtual void CopyFrom(MixinEntity mixin, object[] args)
{
}
}
public static class MixinDeclarations
{
public static readonly MethodInfo miMixin = ReflectionTools.GetMethodInfo((Entity i) => i.Mixin<CorruptMixin>()).GetGenericMethodDefinition();
public static ConcurrentDictionary<Type, HashSet<Type>> Declarations = new ConcurrentDictionary<Type, HashSet<Type>>();
public static ConcurrentDictionary<Type, Func<ModifiableEntity, MixinEntity?, MixinEntity>> Constructors = new ConcurrentDictionary<Type, Func<ModifiableEntity, MixinEntity?, MixinEntity>>();
public static Action<Type> AssertNotIncluded = t => { throw new NotImplementedException("Call MixinDeclarations.Register in the server, after the Connector is created."); };
public static void Register<T, M>()
where T : ModifiableEntity, IRootEntity
where M : MixinEntity
{
Register(typeof(T), typeof(M));
}
public static void Register(Type mainEntity, Type mixinEntity)
{
if (!typeof(ModifiableEntity).IsAssignableFrom(mainEntity))
throw new InvalidOperationException("{0} is not a {1}".FormatWith(mainEntity.Name, typeof(Entity).Name));
if (mainEntity.IsAbstract)
throw new InvalidOperationException("{0} is abstract".FormatWith(mainEntity.Name));
if (!typeof(MixinEntity).IsAssignableFrom(mixinEntity))
throw new InvalidOperationException("{0} is not a {1}".FormatWith(mixinEntity.Name, typeof(MixinEntity).Name));
AssertNotIncluded(mainEntity);
GetMixinDeclarations(mainEntity).Add(mixinEntity);
AddConstructor(mixinEntity);
}
public static void Import(Dictionary<Type, HashSet<Type>> declarations)
{
Declarations = new ConcurrentDictionary<Type, HashSet<Type>>(declarations);
foreach (var t in declarations.SelectMany(d => d.Value).Distinct())
AddConstructor(t);
}
static void AddConstructor(Type mixinEntity)
{
Constructors.GetOrAdd(mixinEntity, me =>
{
var constructors = me.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (constructors.Length != 1)
throw new InvalidOperationException($"{me.Name} should have just one non-public construtor with parameters (ModifiableEntity mainEntity, MixinEntity next)"
.FormatWith(me.Name));
var ci = constructors.Single();
var pi = ci.GetParameters();
if (ci.IsPublic || pi.Length != 2 || pi[0].ParameterType != typeof(ModifiableEntity) || pi[1].ParameterType != typeof(MixinEntity))
throw new InvalidOperationException($"{me.Name} does not have a non-public construtor with parameters (ModifiableEntity mainEntity, MixinEntity next)." +
(pi[0].ParameterType == typeof(Entity) ? "\r\nBREAKING CHANGE: The first parameter has changed from Entity -> ModifiableEntity" : null)
);
return (Func<ModifiableEntity, MixinEntity?, MixinEntity>)Expression.Lambda(Expression.New(ci, pMainEntity, pNext), pMainEntity, pNext).Compile();
});
}
static readonly ParameterExpression pMainEntity = ParameterExpression.Parameter(typeof(ModifiableEntity));
static readonly ParameterExpression pNext = ParameterExpression.Parameter(typeof(MixinEntity));
public static HashSet<Type> GetMixinDeclarations(Type mainEntity)
{
return Declarations.GetOrAdd(mainEntity, me =>
{
var hs = new HashSet<Type>(me.GetCustomAttributes(typeof(MixinAttribute), inherit: false)
.Cast<MixinAttribute>()
.Select(t => t.MixinType));
foreach (var t in hs)
AddConstructor(t);
return hs;
});
}
public static bool IsDeclared(Type mainEntity, Type mixinType)
{
return GetMixinDeclarations(mainEntity).Contains(mixinType);
}
public static void AssertDeclared(Type mainEntity, Type mixinType)
{
if (!IsDeclared(mainEntity, mixinType))
throw new InvalidOperationException("Mixin {0} is not registered for {1}. Consider writing MixinDeclarations.Register<{1}, {0}>() at the beginning of Starter.Start".FormatWith(mixinType.TypeName(), mainEntity.TypeName()));
}
internal static MixinEntity? CreateMixins(ModifiableEntity mainEntity)
{
var types = GetMixinDeclarations(mainEntity.GetType());
MixinEntity? result = null;
foreach (var t in types)
result = Constructors[t](mainEntity, result);
return result;
}
public static T SetMixin<T, M, V>(this T entity, Expression<Func<M, V>> mixinProperty, V value)
where T : IModifiableEntity
where M : MixinEntity
{
M mixin = ((ModifiableEntity)(IModifiableEntity)entity).Mixin<M>();
var pi = ReflectionTools.BasePropertyInfo(mixinProperty);
var setter = MixinSetterCache<M>.Setter<V>(pi);
setter(mixin, value);
return entity;
}
static class MixinSetterCache<T> where T : MixinEntity
{
static ConcurrentDictionary<string, Delegate> cache = new ConcurrentDictionary<string, Delegate>();
internal static Action<T, V> Setter<V>(PropertyInfo pi)
{
return (Action<T, V>)cache.GetOrAdd(pi.Name, s => ReflectionTools.CreateSetter<T, V>(Reflector.FindFieldInfo(typeof(T), pi))!);
}
}
public static T CopyMixinsFrom<T>(this T newEntity, IModifiableEntity original, params object[] args)
where T: IModifiableEntity
{
var list = (from nm in ((ModifiableEntity)(IModifiableEntity)newEntity).Mixins
join om in ((ModifiableEntity)(IModifiableEntity)original).Mixins
on nm.GetType() equals om.GetType()
select new { nm, om });
foreach (var pair in list)
{
pair.nm!.CopyFrom(pair.om!, args); /*CSBUG*/
}
return newEntity;
}
}
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
public sealed class MixinAttribute : Attribute
{
readonly Type mixinType;
public MixinAttribute(Type mixinType)
{
this.mixinType = mixinType;
}
public Type MixinType
{
get { return this.mixinType; }
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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 System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// Profile
/// </summary>
[DataContract]
public partial class Profile : IEquatable<Profile>
{
/// <summary>
/// Initializes a new instance of the <see cref="Profile" /> class.
/// </summary>
/// <param name="Username">Username.</param>
/// <param name="Userid">Userid.</param>
/// <param name="Url">Url.</param>
/// <param name="Bio">Bio.</param>
/// <param name="Service">Service.</param>
/// <param name="Followers">Followers.</param>
/// <param name="Following">Following.</param>
/// <param name="Score">Score.</param>
public Profile(string Username = null, string Userid = null, string Url = null, string Bio = null, string Service = null, int? Followers = null, int? Following = null, int? Score = null)
{
this.Username = Username;
this.Userid = Userid;
this.Url = Url;
this.Bio = Bio;
this.Service = Service;
this.Followers = Followers;
this.Following = Following;
this.Score = Score;
}
/// <summary>
/// Gets or Sets Username
/// </summary>
[DataMember(Name="username", EmitDefaultValue=false)]
public string Username { get; set; }
/// <summary>
/// Gets or Sets Userid
/// </summary>
[DataMember(Name="userid", EmitDefaultValue=false)]
public string Userid { get; set; }
/// <summary>
/// Gets or Sets Url
/// </summary>
[DataMember(Name="url", EmitDefaultValue=false)]
public string Url { get; set; }
/// <summary>
/// Gets or Sets Bio
/// </summary>
[DataMember(Name="bio", EmitDefaultValue=false)]
public string Bio { get; set; }
/// <summary>
/// Gets or Sets Service
/// </summary>
[DataMember(Name="service", EmitDefaultValue=false)]
public string Service { get; set; }
/// <summary>
/// Gets or Sets Followers
/// </summary>
[DataMember(Name="followers", EmitDefaultValue=false)]
public int? Followers { get; set; }
/// <summary>
/// Gets or Sets Following
/// </summary>
[DataMember(Name="following", EmitDefaultValue=false)]
public int? Following { get; set; }
/// <summary>
/// Gets or Sets Score
/// </summary>
[DataMember(Name="score", EmitDefaultValue=false)]
public int? Score { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Profile {\n");
sb.Append(" Username: ").Append(Username).Append("\n");
sb.Append(" Userid: ").Append(Userid).Append("\n");
sb.Append(" Url: ").Append(Url).Append("\n");
sb.Append(" Bio: ").Append(Bio).Append("\n");
sb.Append(" Service: ").Append(Service).Append("\n");
sb.Append(" Followers: ").Append(Followers).Append("\n");
sb.Append(" Following: ").Append(Following).Append("\n");
sb.Append(" Score: ").Append(Score).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Profile);
}
/// <summary>
/// Returns true if Profile instances are equal
/// </summary>
/// <param name="other">Instance of Profile to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Profile other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Username == other.Username ||
this.Username != null &&
this.Username.Equals(other.Username)
) &&
(
this.Userid == other.Userid ||
this.Userid != null &&
this.Userid.Equals(other.Userid)
) &&
(
this.Url == other.Url ||
this.Url != null &&
this.Url.Equals(other.Url)
) &&
(
this.Bio == other.Bio ||
this.Bio != null &&
this.Bio.Equals(other.Bio)
) &&
(
this.Service == other.Service ||
this.Service != null &&
this.Service.Equals(other.Service)
) &&
(
this.Followers == other.Followers ||
this.Followers != null &&
this.Followers.Equals(other.Followers)
) &&
(
this.Following == other.Following ||
this.Following != null &&
this.Following.Equals(other.Following)
) &&
(
this.Score == other.Score ||
this.Score != null &&
this.Score.Equals(other.Score)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Username != null)
hash = hash * 59 + this.Username.GetHashCode();
if (this.Userid != null)
hash = hash * 59 + this.Userid.GetHashCode();
if (this.Url != null)
hash = hash * 59 + this.Url.GetHashCode();
if (this.Bio != null)
hash = hash * 59 + this.Bio.GetHashCode();
if (this.Service != null)
hash = hash * 59 + this.Service.GetHashCode();
if (this.Followers != null)
hash = hash * 59 + this.Followers.GetHashCode();
if (this.Following != null)
hash = hash * 59 + this.Following.GetHashCode();
if (this.Score != null)
hash = hash * 59 + this.Score.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Collections;
using Raksha.Asn1.Iana;
using Raksha.Asn1.Misc;
using Raksha.Security.Certificates;
using Raksha.Asn1;
using Raksha.Asn1.CryptoPro;
using Raksha.Asn1.Eac;
using Raksha.Asn1.Nist;
using Raksha.Asn1.Oiw;
using Raksha.Asn1.Pkcs;
using Raksha.Asn1.TeleTrust;
using Raksha.Asn1.X509;
using Raksha.Asn1.X9;
using Raksha.Crypto;
using Raksha.Security;
using Raksha.Utilities;
using Raksha.X509;
using Raksha.X509.Store;
namespace Raksha.Cms
{
internal class CmsSignedHelper
{
internal static readonly CmsSignedHelper Instance = new CmsSignedHelper();
private static readonly IDictionary encryptionAlgs = Platform.CreateHashtable();
private static readonly IDictionary digestAlgs = Platform.CreateHashtable();
private static readonly IDictionary digestAliases = Platform.CreateHashtable();
private static void AddEntries(DerObjectIdentifier oid, string digest, string encryption)
{
string alias = oid.Id;
digestAlgs.Add(alias, digest);
encryptionAlgs.Add(alias, encryption);
}
static CmsSignedHelper()
{
AddEntries(NistObjectIdentifiers.DsaWithSha224, "SHA224", "DSA");
AddEntries(NistObjectIdentifiers.DsaWithSha256, "SHA256", "DSA");
AddEntries(NistObjectIdentifiers.DsaWithSha384, "SHA384", "DSA");
AddEntries(NistObjectIdentifiers.DsaWithSha512, "SHA512", "DSA");
AddEntries(OiwObjectIdentifiers.DsaWithSha1, "SHA1", "DSA");
AddEntries(OiwObjectIdentifiers.MD4WithRsa, "MD4", "RSA");
AddEntries(OiwObjectIdentifiers.MD4WithRsaEncryption, "MD4", "RSA");
AddEntries(OiwObjectIdentifiers.MD5WithRsa, "MD5", "RSA");
AddEntries(OiwObjectIdentifiers.Sha1WithRsa, "SHA1", "RSA");
AddEntries(PkcsObjectIdentifiers.MD2WithRsaEncryption, "MD2", "RSA");
AddEntries(PkcsObjectIdentifiers.MD4WithRsaEncryption, "MD4", "RSA");
AddEntries(PkcsObjectIdentifiers.MD5WithRsaEncryption, "MD5", "RSA");
AddEntries(PkcsObjectIdentifiers.Sha1WithRsaEncryption, "SHA1", "RSA");
AddEntries(PkcsObjectIdentifiers.Sha224WithRsaEncryption, "SHA224", "RSA");
AddEntries(PkcsObjectIdentifiers.Sha256WithRsaEncryption, "SHA256", "RSA");
AddEntries(PkcsObjectIdentifiers.Sha384WithRsaEncryption, "SHA384", "RSA");
AddEntries(PkcsObjectIdentifiers.Sha512WithRsaEncryption, "SHA512", "RSA");
AddEntries(X9ObjectIdentifiers.ECDsaWithSha1, "SHA1", "ECDSA");
AddEntries(X9ObjectIdentifiers.ECDsaWithSha224, "SHA224", "ECDSA");
AddEntries(X9ObjectIdentifiers.ECDsaWithSha256, "SHA256", "ECDSA");
AddEntries(X9ObjectIdentifiers.ECDsaWithSha384, "SHA384", "ECDSA");
AddEntries(X9ObjectIdentifiers.ECDsaWithSha512, "SHA512", "ECDSA");
AddEntries(X9ObjectIdentifiers.IdDsaWithSha1, "SHA1", "DSA");
AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_1, "SHA1", "ECDSA");
AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_224, "SHA224", "ECDSA");
AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_256, "SHA256", "ECDSA");
AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_384, "SHA384", "ECDSA");
AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_512, "SHA512", "ECDSA");
AddEntries(EacObjectIdentifiers.id_TA_RSA_v1_5_SHA_1, "SHA1", "RSA");
AddEntries(EacObjectIdentifiers.id_TA_RSA_v1_5_SHA_256, "SHA256", "RSA");
AddEntries(EacObjectIdentifiers.id_TA_RSA_PSS_SHA_1, "SHA1", "RSAandMGF1");
AddEntries(EacObjectIdentifiers.id_TA_RSA_PSS_SHA_256, "SHA256", "RSAandMGF1");
encryptionAlgs.Add(X9ObjectIdentifiers.IdDsa.Id, "DSA");
encryptionAlgs.Add(PkcsObjectIdentifiers.RsaEncryption.Id, "RSA");
encryptionAlgs.Add(TeleTrusTObjectIdentifiers.TeleTrusTRsaSignatureAlgorithm, "RSA");
encryptionAlgs.Add(X509ObjectIdentifiers.IdEARsa.Id, "RSA");
encryptionAlgs.Add(CmsSignedGenerator.EncryptionRsaPss, "RSAandMGF1");
encryptionAlgs.Add(CryptoProObjectIdentifiers.GostR3410x94.Id, "GOST3410");
encryptionAlgs.Add(CryptoProObjectIdentifiers.GostR3410x2001.Id, "ECGOST3410");
encryptionAlgs.Add("1.3.6.1.4.1.5849.1.6.2", "ECGOST3410");
encryptionAlgs.Add("1.3.6.1.4.1.5849.1.1.5", "GOST3410");
digestAlgs.Add(PkcsObjectIdentifiers.MD2.Id, "MD2");
digestAlgs.Add(PkcsObjectIdentifiers.MD4.Id, "MD4");
digestAlgs.Add(PkcsObjectIdentifiers.MD5.Id, "MD5");
digestAlgs.Add(OiwObjectIdentifiers.IdSha1.Id, "SHA1");
digestAlgs.Add(NistObjectIdentifiers.IdSha224.Id, "SHA224");
digestAlgs.Add(NistObjectIdentifiers.IdSha256.Id, "SHA256");
digestAlgs.Add(NistObjectIdentifiers.IdSha384.Id, "SHA384");
digestAlgs.Add(NistObjectIdentifiers.IdSha512.Id, "SHA512");
digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD128.Id, "RIPEMD128");
digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD160.Id, "RIPEMD160");
digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD256.Id, "RIPEMD256");
digestAlgs.Add(CryptoProObjectIdentifiers.GostR3411.Id, "GOST3411");
digestAlgs.Add("1.3.6.1.4.1.5849.1.2.1", "GOST3411");
digestAliases.Add("SHA1", new string[] { "SHA-1" });
digestAliases.Add("SHA224", new string[] { "SHA-224" });
digestAliases.Add("SHA256", new string[] { "SHA-256" });
digestAliases.Add("SHA384", new string[] { "SHA-384" });
digestAliases.Add("SHA512", new string[] { "SHA-512" });
}
/**
* Return the digest algorithm using one of the standard JCA string
* representations rather than the algorithm identifier (if possible).
*/
internal string GetDigestAlgName(
string digestAlgOid)
{
string algName = (string)digestAlgs[digestAlgOid];
if (algName != null)
{
return algName;
}
return digestAlgOid;
}
internal string[] GetDigestAliases(
string algName)
{
string[] aliases = (string[]) digestAliases[algName];
return aliases == null ? new String[0] : (string[]) aliases.Clone();
}
/**
* Return the digest encryption algorithm using one of the standard
* JCA string representations rather than the algorithm identifier (if
* possible).
*/
internal string GetEncryptionAlgName(
string encryptionAlgOid)
{
string algName = (string) encryptionAlgs[encryptionAlgOid];
if (algName != null)
{
return algName;
}
return encryptionAlgOid;
}
internal IDigest GetDigestInstance(
string algorithm)
{
try
{
return DigestUtilities.GetDigest(algorithm);
}
catch (SecurityUtilityException e)
{
// This is probably superfluous on C#, since no provider infrastructure,
// assuming DigestUtilities already knows all the aliases
foreach (string alias in GetDigestAliases(algorithm))
{
try { return DigestUtilities.GetDigest(alias); }
catch (SecurityUtilityException) {}
}
throw e;
}
}
internal ISigner GetSignatureInstance(
string algorithm)
{
return SignerUtilities.GetSigner(algorithm);
}
internal IX509Store CreateAttributeStore(
string type,
Asn1Set certSet)
{
IList certs = Platform.CreateArrayList();
if (certSet != null)
{
foreach (Asn1Encodable ae in certSet)
{
try
{
Asn1Object obj = ae.ToAsn1Object();
if (obj is Asn1TaggedObject)
{
Asn1TaggedObject tagged = (Asn1TaggedObject)obj;
if (tagged.TagNo == 2)
{
certs.Add(
new X509V2AttributeCertificate(
Asn1Sequence.GetInstance(tagged, false).GetEncoded()));
}
}
}
catch (Exception ex)
{
throw new CmsException("can't re-encode attribute certificate!", ex);
}
}
}
try
{
return X509StoreFactory.Create(
"AttributeCertificate/" + type,
new X509CollectionStoreParameters(certs));
}
catch (ArgumentException e)
{
throw new CmsException("can't setup the X509Store", e);
}
}
internal IX509Store CreateCertificateStore(
string type,
Asn1Set certSet)
{
IList certs = Platform.CreateArrayList();
if (certSet != null)
{
AddCertsFromSet(certs, certSet);
}
try
{
return X509StoreFactory.Create(
"Certificate/" + type,
new X509CollectionStoreParameters(certs));
}
catch (ArgumentException e)
{
throw new CmsException("can't setup the X509Store", e);
}
}
internal IX509Store CreateCrlStore(
string type,
Asn1Set crlSet)
{
IList crls = Platform.CreateArrayList();
if (crlSet != null)
{
AddCrlsFromSet(crls, crlSet);
}
try
{
return X509StoreFactory.Create(
"CRL/" + type,
new X509CollectionStoreParameters(crls));
}
catch (ArgumentException e)
{
throw new CmsException("can't setup the X509Store", e);
}
}
private void AddCertsFromSet(
IList certs,
Asn1Set certSet)
{
X509CertificateParser cf = new X509CertificateParser();
foreach (Asn1Encodable ae in certSet)
{
try
{
Asn1Object obj = ae.ToAsn1Object();
if (obj is Asn1Sequence)
{
// TODO Build certificate directly from sequence?
certs.Add(cf.ReadCertificate(obj.GetEncoded()));
}
}
catch (Exception ex)
{
throw new CmsException("can't re-encode certificate!", ex);
}
}
}
private void AddCrlsFromSet(
IList crls,
Asn1Set crlSet)
{
X509CrlParser cf = new X509CrlParser();
foreach (Asn1Encodable ae in crlSet)
{
try
{
// TODO Build CRL directly from ae.ToAsn1Object()?
crls.Add(cf.ReadCrl(ae.GetEncoded()));
}
catch (Exception ex)
{
throw new CmsException("can't re-encode CRL!", ex);
}
}
}
internal AlgorithmIdentifier FixAlgID(
AlgorithmIdentifier algId)
{
if (algId.Parameters == null)
return new AlgorithmIdentifier(algId.ObjectID, DerNull.Instance);
return algId;
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using wwtlib;
//using TerraViewer;
//
//Module : AAELLIPTICAL.CPP
//Purpose: Implementation for the algorithms for an elliptical orbit
//Created: PJN / 29-12-2003
//History: PJN / 24-05-2004 1. Fixed a missing break statement in CAAElliptical::Calculate. Thanks to
// Carsten A. Arnholm for reporting this bug.
// 2. Also fixed an issue with the calculation of the apparent distance to
// the Sun.
// PJN / 31-12-2004 1. Fix for CAAElliptical::MinorPlanetMagnitude where the phase angle was
// being incorrectly converted from Radians to Degress when it was already
// in degrees. Thanks to Martin Burri for reporting this problem.
// PJN / 05-06-2006 1. Fixed a bug in CAAElliptical::Calculate(double JD, EllipticalObject object)
// where the correction for nutation was incorrectly using the Mean obliquity of
// the ecliptic instead of the true value. The results from the test program now
// agree much more closely with the example Meeus provides which is the position
// of Venus on 1992 Dec. 20 at 0h Dynamical Time. I've also checked the positions
// against the JPL Horizons web site and the agreement is much better. Because the
// True obliquity of the Ecliptic is defined as the mean obliquity of the ecliptic
// plus the nutation in obliquity, it is relatively easy to determine the magnitude
// of error this was causing. From the chapter on Nutation in the book, and
// specifically the table which gives the cosine coefficients for nutation in
// obliquity you can see that the absolute worst case error would be the sum of the
// absolute values of all of the coefficients and would have been c. 10 arc seconds
// of degree, which is not a small amount!. This value would be an absolute worst
// case and I would expect the average error value to be much much smaller
// (probably much less than an arc second). Anyway the bug has now been fixed.
// Thanks to Patrick Wong for pointing out this rather significant bug.
//
//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com)
//
//All rights reserved.
//
//Copyright / Usage Details:
//
//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise)
//when your product is released in binary form. You are allowed to modify the source code in any way you want
//except you cannot modify the copyright details at the top of each module. If you want to distribute source
//code with your application, then you are only allowed to distribute versions released by the author. This is
//to maintain a single distribution point for the source code.
//
//
////////////////////////////// Includes ///////////////////////////////////////
/////////////////////// Includes //////////////////////////////////////////////
/////////////////////// Classes ///////////////////////////////////////////////
public class EOE // was CAAEllipticalObjectElements
{
//Constructors / Destructors
public EOE()
{
a = 0;
e = 0;
i = 0;
w = 0;
omega = 0;
JDEquinox = 0;
T = 0;
}
//public CAAEllipticalObjectElements(BinaryReader br)
//{
// a = br.ReadSingle();
// e = br.ReadSingle();
// i = br.ReadSingle();
// w = br.ReadSingle();
// omega = br.ReadSingle();
// JDEquinox = br.ReadSingle();
// T = br.ReadSingle();
//}
//public CAAEllipticalObjectElements(string line1, string line2, double gravity)
//{
// JDEquinox = SpaceTimeController.TwoLineDateToJulian(line1.Substring(18,14));
// e = double.Parse("0." + line2.Substring(26, 7));
// i = double.Parse(line2.Substring(8, 8));
// omega = double.Parse(line2.Substring(17, 8));
// w = double.Parse(line2.Substring(34, 8));
// double revs = double.Parse(line2.Substring(52, 11));
// double meanAnomoly = double.Parse(line2.Substring(43, 8));
// n = revs * 360.0;
// double part =(86400.0/revs)/(Math.PI*2.0);
// a = Math.Pow((part*part)*gravity,1.0/3.0);
// T = JDEquinox - (meanAnomoly / n);
//}
//public void WriteBin(BinaryWriter bw)
//{
// bw.Write((float)a);
// bw.Write((float)e);
// bw.Write((float)i);
// bw.Write((float)w);
// bw.Write((float)omega);
// bw.Write((float)JDEquinox);
// bw.Write((float)T);
//}
//member variables
public double a;
public double e;
public double i;
public double w;
public double omega;
public double JDEquinox;
public double T;
public double n;
public double meanAnnomolyOut;
}
public class EPD // was CAAEllipticalPlanetaryDetails
{
//Constructors / Destructors
public EPD()
{
ApparentGeocentricLongitude = 0;
ApparentGeocentricLatitude = 0;
ApparentGeocentricDistance = 0;
ApparentLightTime = 0;
ApparentGeocentricRA = 0;
ApparentGeocentricDeclination = 0;
}
//Member variables
public double ApparentGeocentricLongitude;
public double ApparentGeocentricLatitude;
public double ApparentGeocentricDistance;
public double ApparentLightTime;
public double ApparentGeocentricRA;
public double ApparentGeocentricDeclination;
}
public class EOD // was CAAEllipticalObjectDetails
{
//Constructors / Destructors
public EOD()
{
HeliocentricEclipticLongitude = 0;
HeliocentricEclipticLatitude = 0;
TrueGeocentricRA = 0;
TrueGeocentricDeclination = 0;
TrueGeocentricDistance = 0;
TrueGeocentricLightTime = 0;
AstrometricGeocenticRA = 0;
AstrometricGeocentricDeclination = 0;
AstrometricGeocentricDistance = 0;
AstrometricGeocentricLightTime = 0;
Elongation = 0;
PhaseAngle = 0;
}
//Member variables
public C3D HeliocentricRectangularEquatorial = new C3D();
public C3D HeliocentricRectangularEcliptical = new C3D();
public double HeliocentricEclipticLongitude;
public double HeliocentricEclipticLatitude;
public double TrueGeocentricRA;
public double TrueGeocentricDeclination;
public double TrueGeocentricDistance;
public double TrueGeocentricLightTime;
public double AstrometricGeocenticRA;
public double AstrometricGeocentricDeclination;
public double AstrometricGeocentricDistance;
public double AstrometricGeocentricLightTime;
public double Elongation;
public double PhaseAngle;
}
public enum EO : int // was EllipticalObject
{
SUN = 0,
MERCURY = 1,
VENUS = 2,
MARS = 3,
JUPITER = 4,
SATURN = 5,
URANUS = 6,
NEPTUNE = 7,
PLUTO = 8
}
public class ELL // was CAAElliptical
{
//Enums
//Static methods
//Tangible Process Only End
////////////////////////////// Implementation /////////////////////////////////
public static double DistanceToLightTime(double Distance)
{
return Distance * 0.0057755183;
}
public static EPD Calculate(double JD, EO @object)
{
//What will the the return value
EPD details = new EPD();
double JD0 = JD;
double L0 = 0;
double B0 = 0;
double R0 = 0;
double cosB0 = 0;
if (@object != EO.SUN)
{
L0 = CAAEarth.EclipticLongitude(JD0);
B0 = CAAEarth.EclipticLatitude(JD0);
R0 = CAAEarth.RadiusVector(JD0);
L0 = CT.D2R(L0);
B0 = CT.D2R(B0);
cosB0 = Math.Cos(B0);
}
//Calculate the initial values
double L = 0;
double B = 0;
double R = 0;
double Lrad;
double Brad;
double cosB;
double cosL;
double x;
double y;
double z;
bool bRecalc = true;
bool bFirstRecalc = true;
double LPrevious = 0;
double BPrevious = 0;
double RPrevious = 0;
while (bRecalc)
{
switch (@object)
{
case EO.SUN:
{
L = CAASun.GeometricEclipticLongitude(JD0);
B = CAASun.GeometricEclipticLatitude(JD0);
R = CAAEarth.RadiusVector(JD0);
break;
}
case EO.MERCURY:
{
L = CAAMercury.EclipticLongitude(JD0);
B = CAAMercury.EclipticLatitude(JD0);
R = CAAMercury.RadiusVector(JD0);
break;
}
case EO.VENUS:
{
L = CAAVenus.EclipticLongitude(JD0);
B = CAAVenus.EclipticLatitude(JD0);
R = CAAVenus.RadiusVector(JD0);
break;
}
case EO.MARS:
{
L = CAAMars.EclipticLongitude(JD0);
B = CAAMars.EclipticLatitude(JD0);
R = CAAMars.RadiusVector(JD0);
break;
}
case EO.JUPITER:
{
L = CAAJupiter.EclipticLongitude(JD0);
B = CAAJupiter.EclipticLatitude(JD0);
R = CAAJupiter.RadiusVector(JD0);
break;
}
case EO.SATURN:
{
L = CAASaturn.EclipticLongitude(JD0);
B = CAASaturn.EclipticLatitude(JD0);
R = CAASaturn.RadiusVector(JD0);
break;
}
case EO.URANUS:
{
L = CAAUranus.EclipticLongitude(JD0);
B = CAAUranus.EclipticLatitude(JD0);
R = CAAUranus.RadiusVector(JD0);
break;
}
case EO.NEPTUNE:
{
L = CAANeptune.EclipticLongitude(JD0);
B = CAANeptune.EclipticLatitude(JD0);
R = CAANeptune.RadiusVector(JD0);
break;
}
case EO.PLUTO:
{
L = CAAPluto.EclipticLongitude(JD0);
B = CAAPluto.EclipticLatitude(JD0);
R = CAAPluto.RadiusVector(JD0);
break;
}
default:
{
Debug.Assert(false);
break;
}
}
if (!bFirstRecalc)
{
bRecalc = ((Math.Abs(L - LPrevious) > 0.00001) || (Math.Abs(B - BPrevious) > 0.00001) || (Math.Abs(R - RPrevious) > 0.000001));
LPrevious = L;
BPrevious = B;
RPrevious = R;
}
else
bFirstRecalc = false;
//Calculate the new value
if (bRecalc)
{
double distance = 0;
if (@object != EO.SUN)
{
Lrad = CT.D2R(L);
Brad = CT.D2R(B);
cosB = Math.Cos(Brad);
cosL = Math.Cos(Lrad);
x = R * cosB * cosL - R0 * cosB0 * Math.Cos(L0);
y = R * cosB * Math.Sin(Lrad) - R0 * cosB0 * Math.Sin(L0);
z = R * Math.Sin(Brad) - R0 * Math.Sin(B0);
distance = Math.Sqrt(x *x + y *y + z *z);
}
else
distance = R; //Distance to the sun from the earth is in fact the radius vector
//Prepare for the next loop around
JD0 = JD - ELL.DistanceToLightTime(distance);
}
}
Lrad = CT.D2R(L);
Brad = CT.D2R(B);
cosB = Math.Cos(Brad);
cosL = Math.Cos(Lrad);
x = R * cosB * cosL - R0 * cosB0 * Math.Cos(L0);
y = R * cosB * Math.Sin(Lrad) - R0 * cosB0 * Math.Sin(L0);
z = R * Math.Sin(Brad) - R0 * Math.Sin(B0);
double x2 = x *x;
double y2 = y *y;
details.ApparentGeocentricLatitude = CT.R2D(Math.Atan2(z, Math.Sqrt(x2 + y2)));
details.ApparentGeocentricDistance = Math.Sqrt(x2 + y2 + z *z);
details.ApparentGeocentricLongitude = CT.M360(CT.R2D(Math.Atan2(y, x)));
details.ApparentLightTime = ELL.DistanceToLightTime(details.ApparentGeocentricDistance);
//Adjust for Aberration
COR Aberration = ABR.EclipticAberration(details.ApparentGeocentricLongitude, details.ApparentGeocentricLatitude, JD);
details.ApparentGeocentricLongitude += Aberration.X;
details.ApparentGeocentricLatitude += Aberration.Y;
//convert to the FK5 system
double DeltaLong = CAAFK5.CorrectionInLongitude(details.ApparentGeocentricLongitude, details.ApparentGeocentricLatitude, JD);
details.ApparentGeocentricLatitude += CAAFK5.CorrectionInLatitude(details.ApparentGeocentricLongitude, JD);
details.ApparentGeocentricLongitude += DeltaLong;
//Correct for nutation
double NutationInLongitude = CAANutation.NutationInLongitude(JD);
double Epsilon = CAANutation.TrueObliquityOfEcliptic(JD);
details.ApparentGeocentricLongitude += CT.DMS2D(0, 0, NutationInLongitude);
//Convert to RA and Dec
COR ApparentEqu = CT.Ec2Eq(details.ApparentGeocentricLongitude, details.ApparentGeocentricLatitude, Epsilon);
details.ApparentGeocentricRA = ApparentEqu.X;
details.ApparentGeocentricDeclination = ApparentEqu.Y;
return details;
}
public static double SemiMajorAxisFromPerihelionDistance(double q, double e)
{
return q / (1 - e);
}
public static double MeanMotionFromSemiMajorAxis(double a)
{
return 0.9856076686 / (a * Math.Sqrt(a));
}
public static Vector3d CalculateRectangularJD(double JD, EOE elements)
{
double JD0 = JD;
double omega = CT.D2R(elements.omega);
double w = CT.D2R(elements.w);
double i = CT.D2R(elements.i);
double sinEpsilon = 0;
double cosEpsilon = 1;
double sinOmega = Math.Sin(omega);
double cosOmega = Math.Cos(omega);
double cosi = Math.Cos(i);
double sini = Math.Sin(i);
double F = cosOmega;
double G = sinOmega * cosEpsilon;
double H = sinOmega * sinEpsilon;
double P = -sinOmega * cosi;
double Q = cosOmega * cosi * cosEpsilon - sini * sinEpsilon;
double R = cosOmega * cosi * sinEpsilon + sini * cosEpsilon;
double a = Math.Sqrt(F * F + P * P);
double b = Math.Sqrt(G * G + Q * Q);
double c = Math.Sqrt(H * H + R * R);
double A = Math.Atan2(F, P);
double B = Math.Atan2(G, Q);
double C = Math.Atan2(H, R);
//double n = CAAElliptical.MeanMotionFromSemiMajorAxis(elements.a);
// double n = ;
double M = elements.n * (JD0 - elements.T);
elements.meanAnnomolyOut = M;
double E = CAAKepler.Calculate(M, elements.e);
E = CT.D2R(E);
double v = 2 * Math.Atan(Math.Sqrt((1 + elements.e) / (1 - elements.e)) * Math.Tan(E / 2));
double r = elements.a * (1 - elements.e * Math.Cos(E));
double x = r * a * Math.Sin(A + w + v);
double y = r * b * Math.Sin(B + w + v);
double z = r * c * Math.Sin(C + w + v);
//elements.meanAnnomolyOut contains the mean annomoly
return Vector3d.Create(x, y, z);
}
public static Vector3d CalculateRectangular(EOE elements, double meanAnomoly)
{
// double JD0 = JD;
double omega = CT.D2R(elements.omega);
double w = CT.D2R(elements.w);
double i = CT.D2R(elements.i);
double sinEpsilon = 0;
double cosEpsilon = 1;
double sinOmega = Math.Sin(omega);
double cosOmega = Math.Cos(omega);
double cosi = Math.Cos(i);
double sini = Math.Sin(i);
double F = cosOmega;
double G = sinOmega * cosEpsilon;
double H = sinOmega * sinEpsilon;
double P = -sinOmega * cosi;
double Q = cosOmega * cosi * cosEpsilon - sini * sinEpsilon;
double R = cosOmega * cosi * sinEpsilon + sini * cosEpsilon;
double a = Math.Sqrt(F * F + P * P);
double b = Math.Sqrt(G * G + Q * Q);
double c = Math.Sqrt(H * H + R * R);
double A = Math.Atan2(F, P);
double B = Math.Atan2(G, Q);
double C = Math.Atan2(H, R);
double n = elements.n;
double M = meanAnomoly;
double E = CAAKepler.Calculate(M, elements.e);
E = CT.D2R(E);
double v = 2 * Math.Atan(Math.Sqrt((1 + elements.e) / (1 - elements.e)) * Math.Tan(E / 2));
double r = elements.a * (1 - elements.e * Math.Cos(E));
double x = r * a * Math.Sin(A + w + v);
double y = r * b * Math.Sin(B + w + v);
double z = r * c * Math.Sin(C + w + v);
return Vector3d.Create(x, y, z);
}
public static EOD CalculateElements(double JD, EOE elements)
{
double Epsilon = CAANutation.MeanObliquityOfEcliptic(elements.JDEquinox);
double JD0 = JD;
//What will be the return value
EOD details = new EOD();
Epsilon = CT.D2R(Epsilon);
double omega = CT.D2R(elements.omega);
double w = CT.D2R(elements.w);
double i = CT.D2R(elements.i);
double sinEpsilon = Math.Sin(Epsilon);
double cosEpsilon = Math.Cos(Epsilon);
double sinOmega = Math.Sin(omega);
double cosOmega = Math.Cos(omega);
double cosi = Math.Cos(i);
double sini = Math.Sin(i);
double F = cosOmega;
double G = sinOmega * cosEpsilon;
double H = sinOmega * sinEpsilon;
double P = -sinOmega * cosi;
double Q = cosOmega *cosi *cosEpsilon - sini *sinEpsilon;
double R = cosOmega *cosi *sinEpsilon + sini *cosEpsilon;
double a = Math.Sqrt(F *F + P *P);
double b = Math.Sqrt(G *G + Q *Q);
double c = Math.Sqrt(H *H + R *R);
double A = Math.Atan2(F, P);
double B = Math.Atan2(G, Q);
double C = Math.Atan2(H, R);
double n = ELL.MeanMotionFromSemiMajorAxis(elements.a);
C3D SunCoord = CAASun.EquatorialRectangularCoordinatesAnyEquinox(JD, elements.JDEquinox);
for (int j =0; j<2; j++)
{
double M = n * (JD0 - elements.T);
double E = CAAKepler.Calculate(M, elements.e);
E = CT.D2R(E);
double v = 2 *Math.Atan(Math.Sqrt((1 + elements.e) / (1 - elements.e)) * Math.Tan(E/2));
double r = elements.a * (1 - elements.e *Math.Cos(E));
double x = r * a * Math.Sin(A + w + v);
double y = r * b * Math.Sin(B + w + v);
double z = r * c * Math.Sin(C + w + v);
if (j == 0)
{
details.HeliocentricRectangularEquatorial.X = x;
details.HeliocentricRectangularEquatorial.Y = y;
details.HeliocentricRectangularEquatorial.Z = z;
//Calculate the heliocentric ecliptic coordinates also
double u = omega + v;
double cosu = Math.Cos(u);
double sinu = Math.Sin(u);
details.HeliocentricRectangularEcliptical.X = r * (cosOmega *cosu - sinOmega *sinu *cosi);
details.HeliocentricRectangularEcliptical.Y = r * (sinOmega *cosu + cosOmega *sinu *cosi);
details.HeliocentricRectangularEcliptical.Z = r *sini *sinu;
details.HeliocentricEclipticLongitude = Math.Atan2(y, x);
details.HeliocentricEclipticLongitude = CT.M24(CT.R2D(details.HeliocentricEclipticLongitude) / 15);
details.HeliocentricEclipticLatitude = Math.Asin(z / r);
details.HeliocentricEclipticLatitude = CT.R2D(details.HeliocentricEclipticLatitude);
}
double psi = SunCoord.X + x;
double nu = SunCoord.Y + y;
double sigma = SunCoord.Z + z;
double Alpha = Math.Atan2(nu, psi);
Alpha = CT.R2D(Alpha);
double Delta = Math.Atan2(sigma, Math.Sqrt(psi *psi + nu *nu));
Delta = CT.R2D(Delta);
double Distance = Math.Sqrt(psi *psi + nu *nu + sigma *sigma);
if (j == 0)
{
details.TrueGeocentricRA = CT.M24(Alpha / 15);
details.TrueGeocentricDeclination = Delta;
details.TrueGeocentricDistance = Distance;
details.TrueGeocentricLightTime = DistanceToLightTime(Distance);
}
else
{
details.AstrometricGeocenticRA = CT.M24(Alpha / 15);
details.AstrometricGeocentricDeclination = Delta;
details.AstrometricGeocentricDistance = Distance;
details.AstrometricGeocentricLightTime = DistanceToLightTime(Distance);
double RES = Math.Sqrt(SunCoord.X *SunCoord.X + SunCoord.Y *SunCoord.Y + SunCoord.Z *SunCoord.Z);
details.Elongation = Math.Acos((RES *RES + Distance *Distance - r *r) / (2 * RES * Distance));
details.Elongation = CT.R2D(details.Elongation);
details.PhaseAngle = Math.Acos((r *r + Distance *Distance - RES *RES) / (2 * r * Distance));
details.PhaseAngle = CT.R2D(details.PhaseAngle);
}
if (j == 0) //Prepare for the next loop around
JD0 = JD - details.TrueGeocentricLightTime;
}
return details;
}
public static double InstantaneousVelocity(double r, double a)
{
return 42.1219 * Math.Sqrt((1/r) - (1/(2 *a)));
}
public static double VelocityAtPerihelion(double e, double a)
{
return 29.7847 / Math.Sqrt(a) * Math.Sqrt((1+e)/(1-e));
}
public static double VelocityAtAphelion(double e, double a)
{
return 29.7847 / Math.Sqrt(a) * Math.Sqrt((1-e)/(1+e));
}
public static double LengthOfEllipse(double e, double a)
{
double b = a * Math.Sqrt(1 - e *e);
return CT.PI() * (3 * (a+b) - Math.Sqrt((a+3 *b)*(3 *a + b)));
}
public static double CometMagnitude(double g, double delta, double k, double r)
{
return g + 5 * Util.Log10(delta) + k * Util.Log10(r);
}
public static double MinorPlanetMagnitude(double H, double delta, double G, double r, double PhaseAngle)
{
//Convert from degrees to radians
PhaseAngle = CT.D2R(PhaseAngle);
double phi1 = Math.Exp(-3.33 *Math.Pow(Math.Tan(PhaseAngle/2), 0.63));
double phi2 = Math.Exp(-1.87 *Math.Pow(Math.Tan(PhaseAngle/2), 1.22));
return H + 5 * Util.Log10(r * delta) - 2.5 * Util.Log10((1 - G) * phi1 + G * phi2);
}
}
| |
// 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.Text;
using System;
using System.Diagnostics;
namespace System.Text
{
// An Encoder is used to encode a sequence of blocks of characters into
// a sequence of blocks of bytes. Following instantiation of an encoder,
// sequential blocks of characters are converted into blocks of bytes through
// calls to the GetBytes method. The encoder maintains state between the
// conversions, allowing it to correctly encode character sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Encoder abstract base
// class are typically obtained through calls to the GetEncoder method
// of Encoding objects.
//
public abstract class Encoder
{
internal EncoderFallback _fallback = null;
internal EncoderFallbackBuffer _fallbackBuffer = null;
protected Encoder()
{
// We don't call default reset because default reset probably isn't good if we aren't initialized.
}
public EncoderFallback Fallback
{
get
{
return _fallback;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
// Can't change fallback if buffer is wrong
if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0)
throw new ArgumentException(
SR.Argument_FallbackBufferNotEmpty, nameof(value));
_fallback = value;
_fallbackBuffer = null;
}
}
// Note: we don't test for threading here because async access to Encoders and Decoders
// doesn't work anyway.
public EncoderFallbackBuffer FallbackBuffer
{
get
{
if (_fallbackBuffer == null)
{
if (_fallback != null)
_fallbackBuffer = _fallback.CreateFallbackBuffer();
else
_fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer();
}
return _fallbackBuffer;
}
}
internal bool InternalHasFallbackBuffer
{
get
{
return _fallbackBuffer != null;
}
}
// Reset the Encoder
//
// Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder. This
// would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.)
//
// If the caller doesn't want to try again after GetBytes() throws an error, then they need to call Reset().
//
// Virtual implementation has to call GetBytes with flush and a big enough buffer to clear a 0 char string
// We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big.
public virtual void Reset()
{
char[] charTemp = { };
byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)];
GetBytes(charTemp, 0, 0, byteTemp, 0, true);
if (_fallbackBuffer != null)
_fallbackBuffer.Reset();
}
// Returns the number of bytes the next call to GetBytes will
// produce if presented with the given range of characters and the given
// value of the flush parameter. The returned value takes into
// account the state in which the encoder was left following the last call
// to GetBytes. The state of the encoder is not affected by a call
// to this method.
//
public abstract int GetByteCount(char[] chars, int index, int count, bool flush);
// We expect this to be the workhorse for NLS encodings
// unfortunately for existing overrides, it has to call the [] version,
// which is really slow, so avoid this method if you might be calling external encodings.
[CLSCompliant(false)]
public virtual unsafe int GetByteCount(char* chars, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_NeedNonNegNum);
char[] arrChar = new char[count];
int index;
for (index = 0; index < count; index++)
arrChar[index] = chars[index];
return GetByteCount(arrChar, 0, count, flush);
}
public virtual unsafe int GetByteCount(ReadOnlySpan<char> chars, bool flush)
{
fixed (char* charsPtr = &chars.DangerousGetPinnableReference())
{
return GetByteCount(charsPtr, chars.Length, flush);
}
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. The method encodes charCount characters from
// chars starting at index charIndex, storing the resulting
// bytes in bytes starting at index byteIndex. The encoding
// takes into account the state in which the encoder was left following the
// last call to this method. The flush parameter indicates whether
// the encoder should flush any shift-states and partial characters at the
// end of the conversion. To ensure correct termination of a sequence of
// blocks of encoded bytes, the last call to GetBytes should specify
// a value of true for the flush parameter.
//
// An exception occurs if the byte array is not large enough to hold the
// complete encoding of the characters. The GetByteCount method can
// be used to determine the exact number of bytes that will be produced for
// a given range of characters. Alternatively, the GetMaxByteCount
// method of the Encoding that produced this encoder can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
//
public abstract int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, bool flush);
// We expect this to be the workhorse for NLS Encodings, but for existing
// ones we need a working (if slow) default implementation)
//
// WARNING WARNING WARNING
//
// WARNING: If this breaks it could be a security threat. Obviously we
// call this internally, so you need to make sure that your pointers, counts
// and indexes are correct when you call this method.
//
// In addition, we have internal code, which will be marked as "safe" calling
// this code. However this code is dependent upon the implementation of an
// external GetBytes() method, which could be overridden by a third party and
// the results of which cannot be guaranteed. We use that result to copy
// the byte[] to our byte* output buffer. If the result count was wrong, we
// could easily overflow our output buffer. Therefore we do an extra test
// when we copy the buffer so that we don't overflow byteCount either.
[CLSCompliant(false)]
public virtual unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, bool flush)
{
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
// Get the char array to convert
char[] arrChar = new char[charCount];
int index;
for (index = 0; index < charCount; index++)
arrChar[index] = chars[index];
// Get the byte array to fill
byte[] arrByte = new byte[byteCount];
// Do the work
int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush);
Debug.Assert(result <= byteCount, "Returned more bytes than we have space for");
// Copy the byte array
// WARNING: We MUST make sure that we don't copy too many bytes. We can't
// rely on result because it could be a 3rd party implementation. We need
// to make sure we never copy more than byteCount bytes no matter the value
// of result
if (result < byteCount)
byteCount = result;
// Don't copy too many bytes!
for (index = 0; index < byteCount; index++)
bytes[index] = arrByte[index];
return byteCount;
}
public virtual unsafe int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush)
{
fixed (char* charsPtr = &chars.DangerousGetPinnableReference())
fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference())
{
return GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length, flush);
}
}
// This method is used to avoid running out of output buffer space.
// It will encode until it runs out of chars, and then it will return
// true if it the entire input was converted. In either case it
// will also return the number of converted chars and output bytes used.
// It will only throw a buffer overflow exception if the entire lenght of bytes[] is
// too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings)
// We're done processing this buffer only if completed returns true.
//
// Might consider checking Max...Count to avoid the extra counting step.
//
// Note that if all of the input chars are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many chars as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
public virtual void Convert(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
SR.ArgumentOutOfRange_IndexCountBuffer);
charsUsed = charCount;
// Its easy to do if it won't overrun our buffer.
// Note: We don't want to call unsafe version because that might be an untrusted version
// which could be really unsafe and we don't want to mix it up.
while (charsUsed > 0)
{
if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount)
{
bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush);
completed = (charsUsed == charCount &&
(_fallbackBuffer == null || _fallbackBuffer.Remaining == 0));
return;
}
// Try again with 1/2 the count, won't flush then 'cause won't read it all
flush = false;
charsUsed /= 2;
}
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(SR.Argument_ConversionOverflow);
}
// Same thing, but using pointers
//
// Might consider checking Max...Count to avoid the extra counting step.
//
// Note that if all of the input chars are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many chars as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
[CLSCompliant(false)]
public virtual unsafe void Convert(char* chars, int charCount,
byte* bytes, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
// Get ready to do it
charsUsed = charCount;
// Its easy to do if it won't overrun our buffer.
while (charsUsed > 0)
{
if (GetByteCount(chars, charsUsed, flush) <= byteCount)
{
bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush);
completed = (charsUsed == charCount &&
(_fallbackBuffer == null || _fallbackBuffer.Remaining == 0));
return;
}
// Try again with 1/2 the count, won't flush then 'cause won't read it all
flush = false;
charsUsed /= 2;
}
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(SR.Argument_ConversionOverflow);
}
public virtual unsafe void Convert(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush, out int charsUsed, out int bytesUsed, out bool completed)
{
fixed (char* charsPtr = &chars.DangerousGetPinnableReference())
fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference())
{
Convert(charsPtr, chars.Length, bytesPtr, bytes.Length, flush, out charsUsed, out bytesUsed, out completed);
}
}
}
}
| |
//
// 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.
//
namespace DiscUtils
{
using System;
using System.Collections.Generic;
using System.IO;
internal class StripedStream : SparseStream
{
private List<SparseStream> _wrapped;
private long _stripeSize;
private Ownership _ownsWrapped;
private bool _canRead;
private bool _canWrite;
private long _length;
private long _position;
public StripedStream(long stripeSize, Ownership ownsWrapped, params SparseStream[] wrapped)
{
_wrapped = new List<SparseStream>(wrapped);
_stripeSize = stripeSize;
_ownsWrapped = ownsWrapped;
_canRead = _wrapped[0].CanRead;
_canWrite = _wrapped[0].CanWrite;
long subStreamLength = _wrapped[0].Length;
foreach (var stream in _wrapped)
{
if (stream.CanRead != _canRead || stream.CanWrite != _canWrite)
{
throw new ArgumentException("All striped streams must have the same read/write permissions", "wrapped");
}
if (stream.Length != subStreamLength)
{
throw new ArgumentException("All striped streams must have the same length", "wrapped");
}
}
_length = subStreamLength * wrapped.Length;
}
public override bool CanRead
{
get { return _canRead; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return _canWrite; }
}
public override long Length
{
get { return _length; }
}
public override long Position
{
get
{
return _position;
}
set
{
_position = value;
}
}
public override IEnumerable<StreamExtent> Extents
{
get
{
// Temporary, indicate there are no 'unstored' extents.
// Consider combining extent information from all wrapped streams in future.
yield return new StreamExtent(0, _length);
}
}
public override void Flush()
{
foreach (var stream in _wrapped)
{
stream.Flush();
}
}
public override int Read(byte[] buffer, int offset, int count)
{
if (!CanRead)
{
throw new InvalidOperationException("Attempt to read to non-readable stream");
}
int maxToRead = (int)Math.Min(_length - _position, count);
int totalRead = 0;
while (totalRead < maxToRead)
{
long stripe = _position / _stripeSize;
long stripeOffset = _position % _stripeSize;
int stripeToRead = (int)Math.Min(maxToRead - totalRead, _stripeSize - stripeOffset);
int streamIdx = (int)(stripe % _wrapped.Count);
long streamStripe = stripe / _wrapped.Count;
Stream targetStream = _wrapped[streamIdx];
targetStream.Position = (streamStripe * _stripeSize) + stripeOffset;
int numRead = targetStream.Read(buffer, offset + totalRead, stripeToRead);
_position += numRead;
totalRead += numRead;
}
return totalRead;
}
public override long Seek(long offset, SeekOrigin origin)
{
long effectiveOffset = offset;
if (origin == SeekOrigin.Current)
{
effectiveOffset += _position;
}
else if (origin == SeekOrigin.End)
{
effectiveOffset += _length;
}
if (effectiveOffset < 0)
{
throw new IOException("Attempt to move before beginning of stream");
}
else
{
_position = effectiveOffset;
return _position;
}
}
public override void SetLength(long value)
{
if (value != _length)
{
throw new InvalidOperationException("Changing the stream length is not permitted for striped streams");
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (!CanWrite)
{
throw new InvalidOperationException("Attempt to write to read-only stream");
}
if (_position + count > _length)
{
throw new IOException("Attempt to write beyond end of stream");
}
int totalWritten = 0;
while (totalWritten < count)
{
long stripe = _position / _stripeSize;
long stripeOffset = _position % _stripeSize;
int stripeToWrite = (int)Math.Min(count - totalWritten, _stripeSize - stripeOffset);
int streamIdx = (int)(stripe % _wrapped.Count);
long streamStripe = stripe / _wrapped.Count;
Stream targetStream = _wrapped[streamIdx];
targetStream.Position = (streamStripe * _stripeSize) + stripeOffset;
targetStream.Write(buffer, offset + totalWritten, stripeToWrite);
_position += stripeToWrite;
totalWritten += stripeToWrite;
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && _ownsWrapped == Ownership.Dispose && _wrapped != null)
{
foreach (var stream in _wrapped)
{
stream.Dispose();
}
_wrapped = null;
}
}
finally
{
base.Dispose(disposing);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.DocumentationCommentFormatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal partial class AbstractSymbolDisplayService
{
protected abstract partial class AbstractSymbolDescriptionBuilder
{
private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance |
SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions: SymbolDisplayParameterOptions.None,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
propertyStyle:
SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeOptionalBrackets,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_descriptionStyle =
new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword);
private static readonly SymbolDisplayFormat s_globalNamespaceStyle =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included);
private readonly ISymbolDisplayService _displayService;
private readonly SemanticModel _semanticModel;
private readonly int _position;
private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService;
private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap =
new Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>>();
protected readonly Workspace Workspace;
protected readonly CancellationToken CancellationToken;
protected AbstractSymbolDescriptionBuilder(
ISymbolDisplayService displayService,
SemanticModel semanticModel,
int position,
Workspace workspace,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
CancellationToken cancellationToken)
{
_displayService = displayService;
_anonymousTypeDisplayService = anonymousTypeDisplayService;
this.Workspace = workspace;
this.CancellationToken = cancellationToken;
_semanticModel = semanticModel;
_position = position;
}
protected abstract void AddExtensionPrefix();
protected abstract void AddAwaitablePrefix();
protected abstract void AddAwaitableExtensionPrefix();
protected abstract void AddDeprecatedPrefix();
protected abstract Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol);
protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; }
protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; }
protected void AddPrefixTextForAwaitKeyword()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
PlainText(FeaturesResources.PrefixTextForAwaitKeyword),
Space());
}
protected void AddTextForSystemVoid()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
PlainText(FeaturesResources.TextForSystemVoid));
}
protected SemanticModel GetSemanticModel(SyntaxTree tree)
{
if (_semanticModel.SyntaxTree == tree)
{
return _semanticModel;
}
var model = _semanticModel.GetOriginalSemanticModel();
if (model.Compilation.ContainsSyntaxTree(tree))
{
return model.Compilation.GetSemanticModel(tree);
}
// it is from one of its p2p references
foreach (var reference in model.Compilation.References.OfType<CompilationReference>())
{
// find the reference that contains the given tree
if (reference.Compilation.ContainsSyntaxTree(tree))
{
return reference.Compilation.GetSemanticModel(tree);
}
}
// the tree, a source symbol is defined in, doesn't exist in universe
// how this can happen?
Contract.Requires(false, "How?");
return null;
}
private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols)
{
await AddDescriptionPartAsync(symbols[0]).ConfigureAwait(false);
AddOverloadCountPart(symbols);
FixAllAnonymousTypes(symbols[0]);
AddExceptions(symbols[0]);
}
private void AddExceptions(ISymbol symbol)
{
var exceptionTypes = symbol.GetDocumentationComment().ExceptionTypes;
if (exceptionTypes.Any())
{
var parts = new List<SymbolDisplayPart>();
parts.Add(new SymbolDisplayPart(kind: SymbolDisplayPartKind.Text, symbol: null, text: $"\r\n{WorkspacesResources.Exceptions}"));
foreach (var exceptionString in exceptionTypes)
{
parts.AddRange(LineBreak());
parts.AddRange(Space(count: 2));
parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel));
}
AddToGroup(SymbolDescriptionGroups.Exceptions, parts);
}
}
public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync(
ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return this.BuildDescription(groups);
}
public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return this.BuildDescriptionSections();
}
private async Task AddDescriptionPartAsync(ISymbol symbol)
{
if (symbol.GetAttributes().Any(x => x.AttributeClass.MetadataName == "ObsoleteAttribute"))
{
AddDeprecatedPrefix();
}
if (symbol is IDynamicTypeSymbol)
{
AddDescriptionForDynamicType();
}
else if (symbol is IFieldSymbol)
{
await AddDescriptionForFieldAsync((IFieldSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is ILocalSymbol)
{
await AddDescriptionForLocalAsync((ILocalSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is IMethodSymbol)
{
AddDescriptionForMethod((IMethodSymbol)symbol);
}
else if (symbol is ILabelSymbol)
{
AddDescriptionForLabel((ILabelSymbol)symbol);
}
else if (symbol is INamedTypeSymbol)
{
AddDescriptionForNamedType((INamedTypeSymbol)symbol);
}
else if (symbol is INamespaceSymbol)
{
AddDescriptionForNamespace((INamespaceSymbol)symbol);
}
else if (symbol is IParameterSymbol)
{
await AddDescriptionForParameterAsync((IParameterSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is IPropertySymbol)
{
AddDescriptionForProperty((IPropertySymbol)symbol);
}
else if (symbol is IRangeVariableSymbol)
{
AddDescriptionForRangeVariable((IRangeVariableSymbol)symbol);
}
else if (symbol is ITypeParameterSymbol)
{
AddDescriptionForTypeParameter((ITypeParameterSymbol)symbol);
}
else if (symbol is IAliasSymbol)
{
await AddDescriptionPartAsync(((IAliasSymbol)symbol).Target).ConfigureAwait(false);
}
else
{
AddDescriptionForArbitrarySymbol(symbol);
}
}
private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups)
{
var finalParts = new List<SymbolDisplayPart>();
var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2);
foreach (var group in orderedGroups)
{
if ((groups & group) == 0)
{
continue;
}
if (!finalParts.IsEmpty())
{
var newLines = GetPrecedingNewLineCount(group);
finalParts.AddRange(LineBreak(newLines));
}
var parts = _groupMap[group];
finalParts.AddRange(parts);
}
return finalParts.AsImmutable();
}
private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group)
{
switch (group)
{
case SymbolDescriptionGroups.MainDescription:
// these parts are continuations of whatever text came before them
return 0;
case SymbolDescriptionGroups.Documentation:
return 1;
case SymbolDescriptionGroups.AnonymousTypes:
return 0;
case SymbolDescriptionGroups.Exceptions:
case SymbolDescriptionGroups.TypeParameterMap:
// Everything else is in a group on its own
return 2;
default:
return Contract.FailWithReturn<int>("unknown part kind");
}
}
private IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>> BuildDescriptionSections()
{
return _groupMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.AsImmutableOrEmpty());
}
private void AddDescriptionForDynamicType()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Keyword("dynamic"));
AddToGroup(SymbolDescriptionGroups.Documentation,
PlainText(FeaturesResources.RepresentsAnObjectWhoseOperations));
}
private void AddDescriptionForNamedType(INamedTypeSymbol symbol)
{
if (symbol.IsAwaitable(_semanticModel, _position))
{
AddAwaitablePrefix();
}
var token = _semanticModel.SyntaxTree.GetTouchingToken(_position, this.CancellationToken);
if (token != default(SyntaxToken))
{
var syntaxFactsService = this.Workspace.Services.GetLanguageServices(token.Language).GetService<ISyntaxFactsService>();
if (syntaxFactsService.IsAwaitKeyword(token))
{
AddPrefixTextForAwaitKeyword();
if (symbol.SpecialType == SpecialType.System_Void)
{
AddTextForSystemVoid();
return;
}
}
}
if (symbol.TypeKind == TypeKind.Delegate)
{
var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol.OriginalDefinition, style));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol.OriginalDefinition, s_descriptionStyle));
}
if (!symbol.IsUnboundGenericType && !TypeArgumentsAndParametersAreSame(symbol))
{
var allTypeParameters = symbol.GetAllTypeParameters().ToList();
var allTypeArguments = symbol.GetAllTypeArguments().ToList();
AddTypeParameterMapPart(allTypeParameters, allTypeArguments);
}
}
private bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol)
{
var typeArguments = symbol.GetAllTypeArguments().ToList();
var typeParameters = symbol.GetAllTypeParameters().ToList();
for (int i = 0; i < typeArguments.Count; i++)
{
var typeArgument = typeArguments[i];
var typeParameter = typeParameters[i];
if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name)
{
continue;
}
return false;
}
return true;
}
private void AddDescriptionForNamespace(INamespaceSymbol symbol)
{
if (symbol.IsGlobalNamespace)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol, s_globalNamespaceStyle));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol, s_descriptionStyle));
}
}
private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol)
{
var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false);
// Don't bother showing disambiguating text for enum members. The icon displayed
// on Quick Info should be enough.
if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum)
{
AddToGroup(SymbolDescriptionGroups.MainDescription, parts);
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.Constant)
: Description(FeaturesResources.Field),
parts);
}
}
private async Task<IEnumerable<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts;
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol)
{
var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false);
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.LocalConstant)
: Description(FeaturesResources.LocalVariable),
parts);
}
private async Task<IEnumerable<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts;
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private void AddDescriptionForLabel(ILabelSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.Label),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.RangeVariable),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForMethod(IMethodSymbol method)
{
// TODO : show duplicated member case
// TODO : a way to check whether it is a member call off dynamic type?
var awaitable = method.IsAwaitable(_semanticModel, _position);
var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension;
if (awaitable && extension)
{
AddAwaitableExtensionPrefix();
}
else if (awaitable)
{
AddAwaitablePrefix();
}
else if (extension)
{
AddExtensionPrefix();
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat));
if (awaitable)
{
AddAwaitableUsageText(method, _semanticModel, _position);
}
}
protected abstract void AddAwaitableUsageText(IMethodSymbol method, SemanticModel semanticModel, int position);
private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol)
{
IEnumerable<SymbolDisplayPart> initializerParts;
if (symbol.IsOptional)
{
initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.Parameter), parts);
return;
}
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.Parameter),
ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants));
}
private void AddDescriptionForProperty(IPropertySymbol symbol)
{
if (symbol.IsIndexer)
{
// TODO : show duplicated member case
// TODO : a way to check whether it is a member call off dynamic type?
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat));
return;
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat));
}
private void AddDescriptionForArbitrarySymbol(ISymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol)
{
Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol),
Space(),
PlainText(FeaturesResources.In),
Space(),
ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat));
}
private void AddOverloadCountPart(
ImmutableArray<ISymbol> symbolGroup)
{
var count = GetOverloadCount(symbolGroup);
if (count >= 1)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Space(),
Punctuation("("),
Punctuation("+"),
Space(),
PlainText(count.ToString()),
Space(),
count == 1 ? PlainText(FeaturesResources.Overload) : PlainText(FeaturesResources.Overloads),
Punctuation(")"));
}
}
private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup)
{
return symbolGroup.Select(s => s.OriginalDefinition)
.Where(s => !s.Equals(symbolGroup.First().OriginalDefinition))
.Where(s => s is IMethodSymbol || s.IsIndexer())
.Count();
}
protected void AddTypeParameterMapPart(
List<ITypeParameterSymbol> typeParameters,
List<ITypeSymbol> typeArguments)
{
var parts = new List<SymbolDisplayPart>();
var count = typeParameters.Count;
for (int i = 0; i < count; i++)
{
parts.AddRange(TypeParameterName(typeParameters[i].Name));
parts.AddRange(Space());
parts.AddRange(PlainText(FeaturesResources.Is));
parts.AddRange(Space());
parts.AddRange(ToMinimalDisplayParts(typeArguments[i]));
if (i < count - 1)
{
parts.AddRange(LineBreak());
}
}
AddToGroup(SymbolDescriptionGroups.TypeParameterMap,
parts);
}
protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray)
{
AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray);
}
protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray)
{
var partsList = partsArray.Flatten().ToList();
if (partsList.Count > 0)
{
IList<SymbolDisplayPart> existingParts;
if (!_groupMap.TryGetValue(group, out existingParts))
{
existingParts = new List<SymbolDisplayPart>();
_groupMap.Add(group, existingParts);
}
existingParts.AddRange(partsList);
}
}
private IEnumerable<SymbolDisplayPart> Description(string description)
{
return Punctuation("(")
.Concat(PlainText(description))
.Concat(Punctuation(")"))
.Concat(Space());
}
protected IEnumerable<SymbolDisplayPart> Keyword(string text)
{
return Part(SymbolDisplayPartKind.Keyword, text);
}
protected IEnumerable<SymbolDisplayPart> LineBreak(int count = 1)
{
for (int i = 0; i < count; i++)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n");
}
}
protected IEnumerable<SymbolDisplayPart> PlainText(string text)
{
return Part(SymbolDisplayPartKind.Text, text);
}
protected IEnumerable<SymbolDisplayPart> Punctuation(string text)
{
return Part(SymbolDisplayPartKind.Punctuation, text);
}
protected IEnumerable<SymbolDisplayPart> Space(int count = 1)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count));
}
protected IEnumerable<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
format = format ?? MinimallyQualifiedFormat;
return _displayService.ToMinimalDisplayParts(_semanticModel, _position, symbol, format);
}
protected IEnumerable<SymbolDisplayPart> ToDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
return _displayService.ToDisplayParts(symbol, format);
}
private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text)
{
yield return new SymbolDisplayPart(kind, symbol, text);
}
private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text)
{
return Part(kind, null, text);
}
private IEnumerable<SymbolDisplayPart> TypeParameterName(string text)
{
return Part(SymbolDisplayPartKind.TypeParameterName, text);
}
protected IEnumerable<SymbolDisplayPart> ConvertClassifications(SourceText text, IEnumerable<ClassifiedSpan> classifications)
{
var parts = new List<SymbolDisplayPart>();
ClassifiedSpan? lastSpan = null;
foreach (var span in classifications)
{
// If there is space between this span and the last one, then add a space.
if (lastSpan != null && lastSpan.Value.TextSpan.End != span.TextSpan.Start)
{
parts.AddRange(Space());
}
var kind = GetClassificationKind(span.ClassificationType);
if (kind != null)
{
parts.Add(new SymbolDisplayPart(kind.Value, null, text.ToString(span.TextSpan)));
lastSpan = span;
}
}
return parts;
}
private SymbolDisplayPartKind? GetClassificationKind(string type)
{
switch (type)
{
default:
return null;
case ClassificationTypeNames.Identifier:
return SymbolDisplayPartKind.Text;
case ClassificationTypeNames.Keyword:
return SymbolDisplayPartKind.Keyword;
case ClassificationTypeNames.NumericLiteral:
return SymbolDisplayPartKind.NumericLiteral;
case ClassificationTypeNames.StringLiteral:
return SymbolDisplayPartKind.StringLiteral;
case ClassificationTypeNames.WhiteSpace:
return SymbolDisplayPartKind.Space;
case ClassificationTypeNames.Operator:
return SymbolDisplayPartKind.Operator;
case ClassificationTypeNames.Punctuation:
return SymbolDisplayPartKind.Punctuation;
case ClassificationTypeNames.ClassName:
return SymbolDisplayPartKind.ClassName;
case ClassificationTypeNames.StructName:
return SymbolDisplayPartKind.StructName;
case ClassificationTypeNames.InterfaceName:
return SymbolDisplayPartKind.InterfaceName;
case ClassificationTypeNames.DelegateName:
return SymbolDisplayPartKind.DelegateName;
case ClassificationTypeNames.EnumName:
return SymbolDisplayPartKind.EnumName;
case ClassificationTypeNames.TypeParameterName:
return SymbolDisplayPartKind.TypeParameterName;
case ClassificationTypeNames.ModuleName:
return SymbolDisplayPartKind.ModuleName;
case ClassificationTypeNames.VerbatimStringLiteral:
return SymbolDisplayPartKind.StringLiteral;
}
}
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.DirectConnect.Model
{
/// <summary>
/// <para> Detailed information about an offering, including basic offering information plus order steps. </para>
/// </summary>
public class DescribeOfferingDetailResult
{
private string offeringId;
private string region;
private string location;
private string offeringName;
private string description;
private string bandwidth;
private List<ConnectionCost> connectionCosts = new List<ConnectionCost>();
private List<OfferingOrderStep> orderSteps = new List<OfferingOrderStep>();
/// <summary>
/// The ID of the offering. Example: us-west-1_EqSV5_1G Default: None
///
/// </summary>
public string OfferingId
{
get { return this.offeringId; }
set { this.offeringId = value; }
}
/// <summary>
/// Sets the OfferingId property
/// </summary>
/// <param name="offeringId">The value to set for the OfferingId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeOfferingDetailResult WithOfferingId(string offeringId)
{
this.offeringId = offeringId;
return this;
}
// Check to see if OfferingId property is set
internal bool IsSetOfferingId()
{
return this.offeringId != null;
}
/// <summary>
/// The AWS region where the offering is located. Example: us-east-1 Default: None
///
/// </summary>
public string Region
{
get { return this.region; }
set { this.region = value; }
}
/// <summary>
/// Sets the Region property
/// </summary>
/// <param name="region">The value to set for the Region property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeOfferingDetailResult WithRegion(string region)
{
this.region = region;
return this;
}
// Check to see if Region property is set
internal bool IsSetRegion()
{
return this.region != null;
}
/// <summary>
/// The AWS Direct Connect location where the offering is located. Example: EqSV5 Default: None
///
/// </summary>
public string Location
{
get { return this.location; }
set { this.location = value; }
}
/// <summary>
/// Sets the Location property
/// </summary>
/// <param name="location">The value to set for the Location property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeOfferingDetailResult WithLocation(string location)
{
this.location = location;
return this;
}
// Check to see if Location property is set
internal bool IsSetLocation()
{
return this.location != null;
}
public string OfferingName
{
get { return this.offeringName; }
set { this.offeringName = value; }
}
/// <summary>
/// Sets the OfferingName property
/// </summary>
/// <param name="offeringName">The value to set for the OfferingName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeOfferingDetailResult WithOfferingName(string offeringName)
{
this.offeringName = offeringName;
return this;
}
// Check to see if OfferingName property is set
internal bool IsSetOfferingName()
{
return this.offeringName != null;
}
/// <summary>
/// Description of the offering. Example: "<i>1Gbps Cross Connect in us-east-1 via Equinix</i>" Default: None
///
/// </summary>
public string Description
{
get { return this.description; }
set { this.description = value; }
}
/// <summary>
/// Sets the Description property
/// </summary>
/// <param name="description">The value to set for the Description property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeOfferingDetailResult WithDescription(string description)
{
this.description = description;
return this;
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this.description != null;
}
/// <summary>
/// Bandwidth of the connection. Example: 1Gpbs Default: None
///
/// </summary>
public string Bandwidth
{
get { return this.bandwidth; }
set { this.bandwidth = value; }
}
/// <summary>
/// Sets the Bandwidth property
/// </summary>
/// <param name="bandwidth">The value to set for the Bandwidth property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeOfferingDetailResult WithBandwidth(string bandwidth)
{
this.bandwidth = bandwidth;
return this;
}
// Check to see if Bandwidth property is set
internal bool IsSetBandwidth()
{
return this.bandwidth != null;
}
/// <summary>
/// A list of connection costs.
///
/// </summary>
public List<ConnectionCost> ConnectionCosts
{
get { return this.connectionCosts; }
set { this.connectionCosts = value; }
}
/// <summary>
/// Adds elements to the ConnectionCosts collection
/// </summary>
/// <param name="connectionCosts">The values to add to the ConnectionCosts collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeOfferingDetailResult WithConnectionCosts(params ConnectionCost[] connectionCosts)
{
foreach (ConnectionCost element in connectionCosts)
{
this.connectionCosts.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the ConnectionCosts collection
/// </summary>
/// <param name="connectionCosts">The values to add to the ConnectionCosts collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeOfferingDetailResult WithConnectionCosts(IEnumerable<ConnectionCost> connectionCosts)
{
foreach (ConnectionCost element in connectionCosts)
{
this.connectionCosts.Add(element);
}
return this;
}
// Check to see if ConnectionCosts property is set
internal bool IsSetConnectionCosts()
{
return this.connectionCosts.Count > 0;
}
/// <summary>
/// A list of connection order steps.
///
/// </summary>
public List<OfferingOrderStep> OrderSteps
{
get { return this.orderSteps; }
set { this.orderSteps = value; }
}
/// <summary>
/// Adds elements to the OrderSteps collection
/// </summary>
/// <param name="orderSteps">The values to add to the OrderSteps collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeOfferingDetailResult WithOrderSteps(params OfferingOrderStep[] orderSteps)
{
foreach (OfferingOrderStep element in orderSteps)
{
this.orderSteps.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the OrderSteps collection
/// </summary>
/// <param name="orderSteps">The values to add to the OrderSteps collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeOfferingDetailResult WithOrderSteps(IEnumerable<OfferingOrderStep> orderSteps)
{
foreach (OfferingOrderStep element in orderSteps)
{
this.orderSteps.Add(element);
}
return this;
}
// Check to see if OrderSteps property is set
internal bool IsSetOrderSteps()
{
return this.orderSteps.Count > 0;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright company="LeanKit Inc.">
// Copyright (c) LeanKit Inc. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using LeanKit.API.Client.Library.TransferObjects;
namespace LeanKit.API.Client.Library
{
/// <summary>
/// The <see cref="LeanKit.API.Client.Library" /> provides a wrapper library designed to simplify the integration of
/// external systems
/// and utilities with your LeanKit Kanban account. This library exposes both mechanisms that support interactions
/// with LeanKit as
/// well as a strongly typed object model representing the main entities within LeanKit.
/// </summary>
/// <remarks>
/// This library exposes two primary ways to interact with LeanKit LeanKit. These are the <see cref="LeanKitClient" />
/// and
/// <see cref="LeanKitIntegration" /> classes. Both of these are explained below.
/// <list type="bullet">
/// <item>
/// <term>
/// <see cref="LeanKitClient" />
/// </term>
/// <description>
/// This class exposes methods that interact directly with LeanKit API. This class
/// exposed the same methods exposed through the REST API but hides the complexity of working with HTTP and
/// JSON. This
/// class allows you to send commands and queries to LeanKit using the strongly-typed native objects. This
/// class should
/// be used if you are building a simple stateless integration where you are not interested in interacting
/// with a LeanKit Board
/// over a period of time. This class should also be used if you cannot support a long running service or
/// process.
/// </description>
/// </item>
/// <item>
/// <term>
/// <see cref="LeanKitIntegration" />
/// </term>
/// <description>
/// This class is designed to be used in stateful implementations where you plan to interact with a LeanKit
/// Board and react to
/// change events within a the board. This class monitors the changes to the board and raises event as a
/// result of other users
/// interacting with the board. This prevents custom integrations from having to implement the complexity
/// of polling for changes.
/// In addition, this class exposes the same command and query methods that are exposed by the
/// <see cref="LeanKitClient" /> class.
/// Because this implementation is stateful, many of these queries and commands can be optimized and
/// provide more powerful validation.
/// This class is designed to retrieve and hold a reference to the board and therefore should not be
/// instantiated numerous times.
/// Each instantiation will be associated to a single LeanKit Board. You will need to create multiple
/// instances if you need to
/// interact with more than one Board.
/// </description>
/// </item>
/// </list>
/// The library will require the HostName(or URL) used by your organization to connect to LeanKit Kanban (ex. -
/// https://acme.leankit.com)
/// as well as valid account credentials (UserName and Password) used for the organization.
/// </remarks>
[CompilerGenerated]
internal class NamespaceDoc
{
}
/// <summary>
/// This class wraps the raw API of LeanKit and insulates the consumer of the LeanKit API
/// from many of the lower level details of working with the API. This class differs from
/// the LeanKitApi class because of it's composition-based approach, because it implements
/// ILeanKitClient (can be initialized), and because the logic of communicating with the
/// actual REST server is abstracted behind the IRestCommandProcessor.
/// </summary>
public class LeanKitClient : ILeanKitApi, ILeanKitClient
{
private const string DefaultOverrideReason = "WIP Override performed by external system";
private readonly IRestCommandProcessor _restCommandProcessor;
private ILeanKitAccountAuth _accountAuth;
public LeanKitClient(IRestCommandProcessor restCommandProcessor)
{
_restCommandProcessor = restCommandProcessor;
}
#region ILeanKitApi Members
#region Organization Methods
public IEnumerable<BoardListing> GetBoards()
{
const string resource = "/Kanban/API/Boards";
return _restCommandProcessor.Get<List<BoardListing>>(_accountAuth, resource);
}
public IEnumerable<BoardListing> ListNewBoards()
{
const string resource = "/Kanban/API/ListNewBoards";
return _restCommandProcessor.Get<List<BoardListing>>(_accountAuth, resource);
}
#endregion
#region Board Methods
public Board GetBoard(long boardId)
{
var resource = string.Format("/Kanban/API/Boards/{0}", boardId);
return _restCommandProcessor.Get<Board>(_accountAuth, resource);
}
public IEnumerable<Lane> GetBacklogLanes(long boardId)
{
var resource = string.Format("/Kanban/Api/Board/{0}/Backlog", boardId);
return _restCommandProcessor.Get<List<Lane>>(_accountAuth, resource);
}
public IEnumerable<HierarchicalLane> GetArchiveLanes(long boardId)
{
var resource = string.Format("/Kanban/Api/Board/{0}/Archive", boardId);
return _restCommandProcessor.Get<List<HierarchicalLane>>(_accountAuth, resource);
}
public IEnumerable<CardView> GetArchiveCards(long boardId)
{
var resource = string.Format("/Kanban/Api/Board/{0}/ArchiveCards", boardId);
return _restCommandProcessor.Get<List<CardView>>(_accountAuth, resource);
}
public Board GetNewerIfExists(long boardId, long version)
{
var resource = string.Format("/Kanban/Api/Board/{0}/BoardVersion/{1}/GetNewerIfExists", boardId, version);
return _restCommandProcessor.Get<Board>(_accountAuth, resource);
}
public IEnumerable<BoardHistoryEvent> GetBoardHistorySince(long boardId, long version)
{
var resource = string.Format("/Kanban/Api/Board/{0}/BoardVersion/{1}/GetBoardHistorySince", boardId, version);
return _restCommandProcessor.Get<List<BoardHistoryEvent>>(_accountAuth, resource);
}
public CardView GetCard(long boardId, long cardId)
{
var resource = string.Format("/Kanban/Api/Board/{0}/GetCard/{1}", boardId, cardId);
return _restCommandProcessor.Get<CardView>(_accountAuth, resource);
}
public Card GetCardByExternalId(long boardId, string externalCardId)
{
var resource = string.Format("/Kanban/Api/Board/{0}/GetCardByExternalId/{1}", boardId, externalCardId);
var cards = _restCommandProcessor.Get<List<Card>>(_accountAuth, resource);
return cards != null ? cards.FirstOrDefault() : null;
}
public BoardIdentifiers GetBoardIdentifiers(long boardId)
{
var resource = string.Format("/Kanban/Api/Board/{0}/GetBoardIdentifiers", boardId);
return _restCommandProcessor.Get<BoardIdentifiers>(_accountAuth, resource);
}
public long MoveCard(long boardId, long cardId, long toLaneId, int position, string wipOverrideReason)
{
var resource = "/Kanban/Api/Board/" + boardId + "/MoveCardWithWipOverride/" + cardId + "/Lane/" + toLaneId +
"/Position/" + position;
return _restCommandProcessor.Post<long>(_accountAuth, resource,
new {Comment = (string.IsNullOrEmpty(wipOverrideReason) ? DefaultOverrideReason : wipOverrideReason)});
}
public long MoveCardByExternalId(long boardId, string externalId, long toLaneId, int position,
string wipOverrideReason)
{
var resource = "/Kanban/Api/Board/" + boardId + "/MoveCardByExternalId/" + Uri.EscapeDataString(externalId) +
"/Lane/" + toLaneId + "/Position/" + position;
return _restCommandProcessor.Post<long>(_accountAuth, resource,
new {Comment = (string.IsNullOrEmpty(wipOverrideReason) ? DefaultOverrideReason : wipOverrideReason)});
}
public long MoveCard(long boardId, long cardId, long toLaneId, int position)
{
return MoveCard(boardId, cardId, toLaneId, position, DefaultOverrideReason);
}
public CardAddResult AddCard(long boardId, Card newCard)
{
return AddCard(boardId, newCard, DefaultOverrideReason);
}
public CardAddResult AddCard(long boardId, Card newCard, string wipOverrideReason)
{
var resource = string.Format("/Kanban/Api/Board/{0}/AddCardWithWipOverride/Lane/{1}/Position/{2}",
boardId, newCard.LaneId, newCard.Index);
newCard.UserWipOverrideComment = (string.IsNullOrEmpty(wipOverrideReason) ? DefaultOverrideReason : wipOverrideReason);
return _restCommandProcessor.Post<CardAddResult>(_accountAuth, resource, newCard);
}
public IEnumerable<Card> AddCards(long boardId, IEnumerable<Card> newCards)
{
return AddCards(boardId, newCards, DefaultOverrideReason);
}
public IEnumerable<Card> AddCards(long boardId, IEnumerable<Card> newCards, string wipOverrideReason)
{
var resource = "/Kanban/Api/Board/" + boardId + "/AddCards?wipOverrideComment=" +
(string.IsNullOrEmpty(wipOverrideReason) ? DefaultOverrideReason : wipOverrideReason);
return _restCommandProcessor.Post<List<Card>>(_accountAuth, resource, newCards);
}
public CardUpdateResult UpdateCard(long boardId, Card updatedCard)
{
return UpdateCard(boardId, updatedCard, DefaultOverrideReason);
}
public CardUpdateResult UpdateCard(long boardId, Card updatedCard, string wipOverrideReason)
{
var resource = "/Kanban/Api/Board/" + boardId + "/UpdateCardWithWipOverride";
updatedCard.UserWipOverrideComment = wipOverrideReason;
return _restCommandProcessor.Post<CardUpdateResult>(_accountAuth, resource, updatedCard);
}
public CardUpdateResult UpdateCard(IDictionary<string, object> cardFieldUpdates)
{
const string resource = "/Kanban/Api/Card/Update";
return _restCommandProcessor.Post<CardUpdateResult>(_accountAuth, resource, cardFieldUpdates);
}
public CardsUpdateResult UpdateCards(long boardId, IEnumerable<Card> updatedCards)
{
return UpdateCards(boardId, updatedCards, DefaultOverrideReason);
}
public CardsUpdateResult UpdateCards(long boardId, IEnumerable<Card> updatedCards, string wipOverrideReason)
{
var resource = "/Kanban/Api/Board/" + boardId + "/UpdateCards?wipOverrideComment=" +
(string.IsNullOrEmpty(wipOverrideReason) ? DefaultOverrideReason : wipOverrideReason);
return _restCommandProcessor.Post<CardsUpdateResult>(_accountAuth, resource, updatedCards);
}
public long DeleteCard(long boardId, long cardId)
{
var resource = "/Kanban/Api/Board/" + boardId + "/DeleteCard/" + cardId;
return _restCommandProcessor.Post<long>(_accountAuth, resource);
}
public CardsDeleteResult DeleteCards(long boardId, IEnumerable<long> cardIds)
{
var resource = "/Kanban/Api/Board/" + boardId + "/DeleteCards";
return _restCommandProcessor.Post<CardsDeleteResult>(_accountAuth, resource, cardIds);
}
public CardDelegationResult DelegateCard(long cardId, long delegationBoardId)
{
var resource = "Kanban/API/Card/Delegate/" + cardId + "/" + delegationBoardId;
return _restCommandProcessor.Post<CardDelegationResult>(_accountAuth, resource);
}
public BoardUpdates CheckForUpdates(long boardId, long version)
{
var resource = "/Kanban/Api/Board/" + boardId + "/BoardVersion/" + version + "/CheckForUpdates";
return _restCommandProcessor.Get<BoardUpdates>(_accountAuth, resource);
}
public IEnumerable<Comment> GetComments(long boardId, long cardId)
{
var resource = "/Kanban/Api/Card/GetComments/" + boardId + "/" + cardId;
return _restCommandProcessor.Get<List<Comment>>(_accountAuth, resource);
}
public long PostComment(long boardId, long cardId, Comment comment)
{
var resource = "/Kanban/Api/Card/SaveComment/" + boardId + "/" + cardId;
return _restCommandProcessor.Post<long>(_accountAuth, resource, comment);
}
public long PostCommentByExternalId(long boardId, string externalId, Comment comment)
{
var resource = "/Kanban/Api/Card/SaveCommentByExternalId/" + boardId + "/" + Uri.EscapeDataString(externalId);
return _restCommandProcessor.Post<long>(_accountAuth, resource, comment);
}
public IEnumerable<CardEvent> GetCardHistory(long boardId, long cardId)
{
var resource = "/Kanban/Api/Card/History/" + boardId + "/" + cardId;
return _restCommandProcessor.Get<List<CardEvent>>(_accountAuth, resource);
}
public IEnumerable<CardView> SearchCards(long boardId, SearchOptions options)
{
var resource = "/Kanban/Api/Board/" + boardId + "/SearchCards";
return _restCommandProcessor.Post<PaginationResult<CardView>>(_accountAuth, resource, options).Results;
}
public IEnumerable<CardList> ListNewCards(long boardId)
{
var resource = string.Format("/Kanban/Api/Board/{0}/ListNewCards",
boardId);
return _restCommandProcessor.Get<List<CardList>>(_accountAuth, resource);
}
public CardMoveBetweenBoardsResult MoveCardToAnotherBoard(long cardId, long destBoardId)
{
//http://kanban-cibuild.leankit.local/kanban/API/Card/MoveCardToAnotherBoard/7/101
var resource = string.Format("/Kanban/Api/Card/MoveCardToAnotherBoard/{0}/{1}", cardId, destBoardId);
return _restCommandProcessor.Post<CardMoveBetweenBoardsResult>(_accountAuth, resource);
}
public DrillThroughStatistics GetDrillThroughStatistics(long boardId, long cardId)
{
var resource = string.Format("/Kanban/Api/Card/{0}/GetDrillThroughStatistics/{1}", boardId, cardId);
return _restCommandProcessor.Get<DrillThroughStatistics>(_accountAuth, resource);
}
#endregion
#region Taskboard methods
public Taskboard GetTaskboardById(long boardId, long taskboardId)
{
var resource = "/Kanban/API/Board/" + boardId + "/TaskBoard/" + taskboardId + "/Get/";
return _restCommandProcessor.Get<Taskboard>(_accountAuth, resource);
}
public Taskboard GetTaskboard(long boardId, long cardId)
{
var resource = "/Kanban/API/v1/Board/" + boardId + "/Card/" + cardId + "/Taskboard";
return _restCommandProcessor.Get<Taskboard>(_accountAuth, resource);
}
public CardAddResult AddTask(long boardId, long cardId, Card newTask)
{
return AddTask(boardId, cardId, newTask, DefaultOverrideReason);
}
public CardAddResult AddTask(long boardId, long cardId, Card newTask, string wipOverrideReason)
{
var resource = string.Format("/Kanban/Api/v1/Board/{0}/Card/{1}/Tasks/Lane/{2}/Position/{3}",
boardId, cardId, newTask.LaneId, newTask.Index);
newTask.UserWipOverrideComment = wipOverrideReason;
return _restCommandProcessor.Post<CardAddResult>(_accountAuth, resource, newTask);
}
public CardUpdateResult UpdateTask(long boardId, long cardId, Card updatedTask)
{
return UpdateTask(boardId, cardId, updatedTask, DefaultOverrideReason);
}
public CardUpdateResult UpdateTask(long boardId, long cardId, Card updatedTask, string wipOverrideReason)
{
var resource = string.Format("/Kanban/Api/v1/Board/{0}/Update/Card/{1}/Tasks/{2}", boardId, cardId, updatedTask.Id);
updatedTask.UserWipOverrideComment = wipOverrideReason;
return _restCommandProcessor.Post<CardUpdateResult>(_accountAuth, resource, updatedTask);
}
public long DeleteTask(long boardId, long cardId, long taskId)
{
var resource = string.Format("/Kanban/Api/v1/Board/{0}/Delete/Card/{1}/Tasks/{2}", boardId, cardId, taskId);
return _restCommandProcessor.Post<long>(_accountAuth, resource);
}
public BoardUpdates CheckCardForTaskUpdates(long boardId, long cardId, long boardVersion)
{
var resource = string.Format("/Kanban/Api/v1/Board/{0}/Card/{1}/Tasks/BoardVersion/{2}",
boardId, cardId, boardVersion);
return _restCommandProcessor.Get<BoardUpdates>(_accountAuth, resource);
}
public CardMoveResult MoveTask(long boardId, long cardId, long taskId, long toLaneId, int position)
{
return MoveTask(boardId, cardId, taskId, toLaneId, position, DefaultOverrideReason);
}
public CardMoveResult MoveTask(long boardId, long cardId, long taskId, long toLaneId, int position,
string wipOverrideReason)
{
var resource =
string.Format("/Kanban/Api/v1/Board/{0}/Move/Card/{1}/Tasks/{2}/Lane/{3}/Position/{4}", boardId,
cardId, taskId, toLaneId, position);
return _restCommandProcessor.Post<CardMoveResult>(_accountAuth, resource,
new {Comment = (string.IsNullOrEmpty(wipOverrideReason) ? DefaultOverrideReason : wipOverrideReason)});
}
#region Obsolete
[Obsolete("Creating taskboards is no longer supported", true)]
public TaskboardCreateResult CreateTaskboard(long boardId, long containingCardId, TaskboardTemplateType templateType,
long cardContextId)
{
//var cmd = new CreateTaskBoardCommand
//{
// BoardId = boardId,
// CardContextId = cardContextId,
// ContainingCardId = containingCardId,
// TemplateId = (long) templateType
//};
//var resource = "/Kanban/Api/TaskBoard/Create";
//return _restCommandProcessor.Post<TaskboardCreateResult>(_accountAuth, resource, cmd);
throw new NotImplementedException("Creating taskboards is no longer supported");
}
[Obsolete("Deleting taskboards is no longer supported", true)]
public TaskboardDeleteResult DeleteTaskboard(long boardId, long taskBoardId)
{
//var resource = string.Format("/Kanban/API/Board/{0}/TaskBoard/{1}/Delete/", boardId, taskBoardId);
//return _restCommandProcessor.Post<TaskboardDeleteResult>(_accountAuth, resource);
throw new NotImplementedException("Deleting taskboards is no longer supported");
}
[Obsolete("Use AddTask instead.")]
public CardAddResult AddTaskboardCard(long boardId, long taskboardId, Card newCard)
{
return AddTaskboardCard(boardId, taskboardId, newCard, DefaultOverrideReason);
}
[Obsolete("Use AddTask instead.")]
public CardAddResult AddTaskboardCard(long boardId, long taskboardId, Card newCard, string wipOverrideReason)
{
var resource =
string.Format("/Kanban/Api/Board/{0}/TaskBoard/{1}/AddCardWithWipOverrideLite/Lane/{2}/Position/{3}",
boardId, taskboardId, newCard.LaneId, newCard.Index);
newCard.UserWipOverrideComment = wipOverrideReason;
return _restCommandProcessor.Post<CardAddResult>(_accountAuth, resource, newCard);
}
[Obsolete("Use UpdateTask instead")]
public CardUpdateResult UpdateTaskboardCard(long boardId, long taskboardId, Card updatedCard, string wipOverrideReason)
{
var resource = string.Format("/Kanban/Api/Board/{0}/TaskBoard/{1}/UpdateCardWithWipOverrideLite", boardId,
taskboardId);
updatedCard.UserWipOverrideComment = wipOverrideReason;
return _restCommandProcessor.Post<CardUpdateResult>(_accountAuth, resource, updatedCard);
}
[Obsolete("Use UpdateTask instead")]
public CardUpdateResult UpdateTaskboardCard(long boardId, long taskboardId, Card updatedCard)
{
return UpdateTaskboardCard(boardId, taskboardId, updatedCard, DefaultOverrideReason);
}
[Obsolete("Use DeleteTask instead")]
public long DeleteTaskboardCard(long boardId, long taskboardId, long cardId)
{
var resource = string.Format("/Kanban/Api/Board/{0}/TaskBoard/{1}/DeleteLite/{2}", boardId, taskboardId, cardId);
return _restCommandProcessor.Post<long>(_accountAuth, resource);
}
[Obsolete("Use CheckCardForTaskUpdates instead")]
public BoardUpdates CheckForTaskboardUpdates(long boardId, long taskBoardId, long taskBoardVersion)
{
var resource = string.Format("/Kanban/Api/Board/{0}/TaskBoard/{1}/BoardVersion/{2}/CheckForUpdates",
boardId, taskBoardId, taskBoardVersion);
return _restCommandProcessor.Get<BoardUpdates>(_accountAuth, resource);
}
[Obsolete("Use MoveTask instead")]
public CardMoveResult MoveTaskboardCard(long boardId, long taskboardId, long cardId, long toLaneId, int position,
string wipOverrideReason)
{
var resource =
string.Format("/Kanban/Api/Board/{0}/TaskBoard/{1}/MoveCardWithWipOverrideLite/{2}/Lane/{3}/Position/{4}", boardId,
taskboardId, cardId, toLaneId, position);
return _restCommandProcessor.Post<CardMoveResult>(_accountAuth, resource,
new {Comment = (string.IsNullOrEmpty(wipOverrideReason) ? DefaultOverrideReason : wipOverrideReason)});
}
[Obsolete("Use MoveTask instead")]
public CardMoveResult MoveTaskboardCard(long boardId, long taskboardId, long cardId, long toLaneId, int position)
{
return MoveTaskboardCard(boardId, taskboardId, cardId, toLaneId, position, DefaultOverrideReason);
}
#endregion
#endregion
#region Attachment Methods
public long SaveAttachment(long boardId, long cardId, string fileName, string description, string mimeType,
byte[] fileBytes)
{
var resource = string.Format("/kanban/api/card/SaveAttachment/{0}/{1}", boardId, cardId);
var parameters = new Dictionary<string, object> {{"Description", description}, {"Id", 0}};
return _restCommandProcessor.PostFile<long>(_accountAuth, resource, parameters, fileName, mimeType, fileBytes);
}
public long DeleteAttachment(long boardId, long cardId, long attachmentId)
{
var resource = string.Format("/Kanban/Api/Card/DeleteAttachment/{0}/{1}/{2}", boardId, cardId, attachmentId);
return _restCommandProcessor.Post<long>(_accountAuth, resource);
}
public Asset GetAttachment(long boardId, long cardId, long attachmentId)
{
var resource = string.Format("/Kanban/Api/Card/GetAttachments/{0}/{1}/{2}", boardId, cardId, attachmentId);
return _restCommandProcessor.Get<Asset>(_accountAuth, resource);
}
public IEnumerable<Asset> GetAttachments(long boardId, long cardId)
{
var resource = string.Format("/Kanban/Api/Card/GetAttachments/{0}/{1}", boardId, cardId);
return _restCommandProcessor.Get<List<Asset>>(_accountAuth, resource);
}
public AssetFile DownloadAttachment(long boardId, long attachmentId)
{
var resource = string.Format("/Kanban/Api/Card/DownloadAttachment/{0}/{1}", boardId, attachmentId);
return _restCommandProcessor.Download(_accountAuth, resource);
}
#endregion
#region User Methods
public User GetCurrentUser(long boardId)
{
var resource = "/Api/User/GetCurrentUserSettings/" + boardId;
return _restCommandProcessor.Get<User>(_accountAuth, resource);
}
#endregion
#endregion
#region ILeanKitClient Members
[Obsolete("This is deprecated. Please use ILeanKitAccountAuth instead.")]
public ILeanKitApi Initialize(LeanKitAccountAuth accountAuth)
{
_accountAuth = accountAuth.ToBasicAuth();
return this;
}
public ILeanKitApi Initialize(ILeanKitAccountAuth accountAuth)
{
_accountAuth = accountAuth;
return this;
}
#endregion
}
}
| |
using Signum.Engine.Maps;
using Signum.Entities;
using Signum.Entities.Reflection;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
using Signum.Utilities.Reflection;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
namespace Signum.Engine
{
public static class BulkInserter
{
public static int BulkInsert<T>(this IEnumerable<T> entities,
SqlBulkCopyOptions copyOptions = SqlBulkCopyOptions.Default,
bool preSaving = true,
bool validateFirst = true,
bool disableIdentity = false,
int? timeout = null,
string? message = null)
where T : Entity
{
using (HeavyProfiler.Log(nameof(BulkInsert), () => typeof(T).TypeName()))
using (Transaction tr = new Transaction())
{
var table = Schema.Current.Table(typeof(T));
if (!disableIdentity && table.IdentityBehaviour && table.TablesMList().Any())
throw new InvalidOperationException($@"Table {typeof(T)} contains MList but the entities have no IDs. Consider:
* Using BulkInsertQueryIds, that queries the inserted rows and uses the IDs to insert the MList elements.
* Set {nameof(disableIdentity)} = true, and set manually the Ids of the entities before inseting using {nameof(UnsafeEntityExtensions.SetId)}.
* If you know what you doing, call ${nameof(BulkInsertTable)} manually (MList wont be saved)."
);
var list = entities.ToList();
var rowNum = BulkInsertTable(list, copyOptions, preSaving, validateFirst, disableIdentity, timeout, message);
BulkInsertMLists<T>(list, copyOptions, timeout, message);
return tr.Commit(rowNum);
}
}
/// <param name="keySelector">Unique key to retrieve ids</param>
/// <param name="isNewPredicate">Optional filter to query only the recently inseted entities</param>
public static int BulkInsertQueryIds<T, K>(this IEnumerable<T> entities,
Expression<Func<T, K>> keySelector,
Expression<Func<T, bool>>? isNewPredicate = null,
SqlBulkCopyOptions copyOptions = SqlBulkCopyOptions.Default,
bool preSaving = true,
bool validateFirst = true,
int? timeout = null,
string? message = null)
where T : Entity
where K : notnull
{
using (HeavyProfiler.Log(nameof(BulkInsertQueryIds), () => typeof(T).TypeName()))
using (Transaction tr = new Transaction())
{
var t = Schema.Current.Table(typeof(T));
var list = entities.ToList();
if (isNewPredicate == null)
isNewPredicate = GetFilterAutomatic<T>(t);
var rowNum = BulkInsertTable<T>(list, copyOptions, preSaving, validateFirst, false, timeout, message);
var dictionary = Database.Query<T>().Where(isNewPredicate).Select(a => KeyValuePair.Create(keySelector.Evaluate(a), a.Id)).ToDictionaryEx();
var getKeyFunc = keySelector.Compile();
list.ForEach(e =>
{
e.SetId(dictionary.GetOrThrow(getKeyFunc(e)));
e.SetIsNew(false);
});
BulkInsertMLists(list, copyOptions, timeout, message);
GraphExplorer.CleanModifications(GraphExplorer.FromRoots(list));
return tr.Commit(rowNum);
}
}
static void BulkInsertMLists<T>(List<T> list, SqlBulkCopyOptions options, int? timeout, string? message) where T : Entity
{
var mlistPrs = PropertyRoute.GenerateRoutes(typeof(T), includeIgnored: false).Where(a => a.PropertyRouteType == PropertyRouteType.FieldOrProperty && a.Type.IsMList()).ToList();
foreach (var pr in mlistPrs)
{
giBulkInsertMListFromEntities.GetInvoker(typeof(T), pr.Type.ElementType()!)(list, pr, options, timeout, message);
}
}
static Expression<Func<T, bool>> GetFilterAutomatic<T>(Table table) where T : Entity
{
if (table.PrimaryKey.Identity)
{
var max = ExecutionMode.Global().Using(_ => Database.Query<T>().Max(a => (PrimaryKey?)a.Id));
if (max == null)
return a => true;
return a => a.Id > max;
}
var count = ExecutionMode.Global().Using(_ => Database.Query<T>().Count());
if (count == 0)
return a => true;
throw new InvalidOperationException($"Impossible to determine the filter for the IDs query automatically because the table is not Identity and has rows");
}
public static int BulkInsertTable<T>(IEnumerable<T> entities,
SqlBulkCopyOptions copyOptions = SqlBulkCopyOptions.Default,
bool preSaving = true,
bool validateFirst = true,
bool disableIdentity = false,
int? timeout = null,
string? message = null)
where T : Entity
{
using (HeavyProfiler.Log(nameof(BulkInsertTable), () => typeof(T).TypeName()))
{
if (message != null)
return SafeConsole.WaitRows(message == "auto" ? $"BulkInsering {entities.Count()} {typeof(T).TypeName()}" : message,
() => BulkInsertTable(entities, copyOptions, preSaving, validateFirst, disableIdentity, timeout, message: null));
if (disableIdentity)
copyOptions |= SqlBulkCopyOptions.KeepIdentity;
if (copyOptions.HasFlag(SqlBulkCopyOptions.UseInternalTransaction))
throw new InvalidOperationException("BulkInsertDisableIdentity not compatible with UseInternalTransaction");
var list = entities.ToList();
if (preSaving)
{
Saver.PreSaving(() => GraphExplorer.FromRoots(list));
}
if (validateFirst)
{
Validate<T>(list);
}
var t = Schema.Current.Table<T>();
bool disableIdentityBehaviour = copyOptions.HasFlag(SqlBulkCopyOptions.KeepIdentity);
DataTable dt = new DataTable();
var columns = t.Columns.Values.Where(c => !(c is SystemVersionedInfo.SqlServerPeriodColumn) && (disableIdentityBehaviour || !c.IdentityBehaviour)).ToList();
foreach (var c in columns)
dt.Columns.Add(new DataColumn(c.Name, ConvertType(c.Type)));
using (disableIdentityBehaviour ? Administrator.DisableIdentity(t, behaviourOnly: true) : null)
{
foreach (var e in list)
{
if (!e.IsNew)
throw new InvalidOperationException("Entites should be new");
t.SetToStrField(e);
dt.Rows.Add(t.BulkInsertDataRow(e));
}
}
using (Transaction tr = new Transaction())
{
Schema.Current.OnPreBulkInsert(typeof(T), inMListTable: false);
Executor.BulkCopy(dt, columns, t.Name, copyOptions, timeout);
foreach (var item in list)
item.SetNotModified();
return tr.Commit(list.Count);
}
}
}
private static Type ConvertType(Type type)
{
var result = type.UnNullify();
if (result == typeof(Date))
return typeof(DateTime);
return result;
}
static void Validate<T>(IEnumerable<T> entities) where T : Entity
{
foreach (var e in entities)
{
var ic = e.FullIntegrityCheck();
if (ic != null)
{
#if DEBUG
throw new IntegrityCheckException(ic.WithEntities(GraphExplorer.FromRoots(entities)));
#else
throw new IntegrityCheckException(ic);
#endif
}
}
}
static readonly GenericInvoker<Func<IList, PropertyRoute, SqlBulkCopyOptions, int?, string?, int>> giBulkInsertMListFromEntities =
new GenericInvoker<Func<IList, PropertyRoute, SqlBulkCopyOptions, int?, string?, int>>((entities, propertyRoute, options, timeout, message) =>
BulkInsertMListTablePropertyRoute<Entity, string>((List<Entity>)entities, propertyRoute, options, timeout, message));
static int BulkInsertMListTablePropertyRoute<E, V>(List<E> entities, PropertyRoute route, SqlBulkCopyOptions copyOptions, int? timeout, string? message)
where E : Entity
{
return BulkInsertMListTable<E, V>(entities, route.GetLambdaExpression<E, MList<V>>(safeNullAccess: false), copyOptions, timeout, message);
}
public static int BulkInsertMListTable<E, V>(
List<E> entities,
Expression<Func<E, MList<V>>> mListProperty,
SqlBulkCopyOptions copyOptions = SqlBulkCopyOptions.Default,
int? timeout = null,
string? message = null)
where E : Entity
{
using (HeavyProfiler.Log(nameof(BulkInsertMListTable), () => $"{mListProperty} ({typeof(E).TypeName()})"))
{
try
{
var func = mListProperty.Compile();
var mlistElements = (from e in entities
from mle in func(e).Select((iw, i) => new MListElement<E, V>
{
Order = i,
Element = iw,
Parent = e,
})
select mle).ToList();
return BulkInsertMListTable(mlistElements, mListProperty, copyOptions, timeout, updateParentTicks: false, message: message);
}
catch (InvalidOperationException e) when (e.Message.Contains("has no Id"))
{
throw new InvalidOperationException($"{nameof(BulkInsertMListTable)} requires that you set the Id of the entities manually using {nameof(UnsafeEntityExtensions.SetId)}");
}
}
}
public static int BulkInsertMListTable<E, V>(
this IEnumerable<MListElement<E, V>> mlistElements,
Expression<Func<E, MList<V>>> mListProperty,
SqlBulkCopyOptions copyOptions = SqlBulkCopyOptions.Default,
int? timeout = null,
bool? updateParentTicks = null, /*Needed for concurrency and Temporal tables*/
string? message = null)
where E : Entity
{
using (HeavyProfiler.Log(nameof(BulkInsertMListTable), () => $"{mListProperty} ({typeof(MListElement<E, V>).TypeName()})"))
{
if (message != null)
return SafeConsole.WaitRows(message == "auto" ? $"BulkInsering MList<{ typeof(V).TypeName()}> in { typeof(E).TypeName()}" : message,
() => BulkInsertMListTable(mlistElements, mListProperty, copyOptions, timeout, updateParentTicks, message: null));
if (copyOptions.HasFlag(SqlBulkCopyOptions.UseInternalTransaction))
throw new InvalidOperationException("BulkInsertDisableIdentity not compatible with UseInternalTransaction");
var mlistTable = ((FieldMList)Schema.Current.Field(mListProperty)).TableMList;
if (updateParentTicks == null)
{
updateParentTicks = mlistTable.PrimaryKey.Type != typeof(Guid) && mlistTable.BackReference.ReferenceTable.Ticks != null;
}
var maxRowId = updateParentTicks.Value ? Database.MListQuery(mListProperty).Max(a => (PrimaryKey?)a.RowId) : null;
DataTable dt = new DataTable();
var columns = mlistTable.Columns.Values.Where(c => !(c is SystemVersionedInfo.SqlServerPeriodColumn) && !c.IdentityBehaviour).ToList();
foreach (var c in columns)
dt.Columns.Add(new DataColumn(c.Name, ConvertType(c.Type)));
var list = mlistElements.ToList();
foreach (var e in list)
{
dt.Rows.Add(mlistTable.BulkInsertDataRow(e.Parent, e.Element, e.Order));
}
using (Transaction tr = new Transaction())
{
Schema.Current.OnPreBulkInsert(typeof(E), inMListTable: true);
Executor.BulkCopy(dt, columns, mlistTable.Name, copyOptions, timeout);
var result = list.Count;
if (updateParentTicks.Value)
{
Database.MListQuery(mListProperty)
.Where(a => maxRowId == null || a.RowId > maxRowId)
.Select(a => a.Parent)
.UnsafeUpdate()
.Set(e => e.Ticks, a => TimeZoneManager.Now.Ticks)
.Execute();
}
return tr.Commit(result);
}
}
}
public static int BulkInsertView<T>(this IEnumerable<T> entities,
SqlBulkCopyOptions copyOptions = SqlBulkCopyOptions.Default,
int? timeout = null,
string? message = null)
where T : IView
{
using (HeavyProfiler.Log(nameof(BulkInsertView), () => typeof(T).Name))
{
if (message != null)
return SafeConsole.WaitRows(message == "auto" ? $"BulkInsering {entities.Count()} {typeof(T).TypeName()}" : message,
() => BulkInsertView(entities, copyOptions, timeout, message: null));
if (copyOptions.HasFlag(SqlBulkCopyOptions.UseInternalTransaction))
throw new InvalidOperationException("BulkInsertDisableIdentity not compatible with UseInternalTransaction");
var t = Schema.Current.View<T>();
var list = entities.ToList();
bool disableIdentityBehaviour = copyOptions.HasFlag(SqlBulkCopyOptions.KeepIdentity);
var columns = t.Columns.Values.ToList();
DataTable dt = new DataTable();
foreach (var c in columns)
dt.Columns.Add(new DataColumn(c.Name, ConvertType(c.Type)));
foreach (var e in entities)
{
dt.Rows.Add(t.BulkInsertDataRow(e));
}
using (Transaction tr = new Transaction())
{
Schema.Current.OnPreBulkInsert(typeof(T), inMListTable: false);
Executor.BulkCopy(dt, columns, t.Name, copyOptions, timeout);
return tr.Commit(list.Count);
}
}
}
}
public class BulkSetterOptions
{
public SqlBulkCopyOptions CopyOptions = SqlBulkCopyOptions.Default;
public bool ValidateFirst = false;
public bool DisableIdentity = false;
public int? Timeout = null;
}
public class BulkSetterTableOptionsT
{
public SqlBulkCopyOptions CopyOptions = SqlBulkCopyOptions.Default;
public bool ValidateFirst = false;
public bool DisableIdentity = false;
public int? Timeout = null;
}
public class BulkSetterMListOptions
{
public SqlBulkCopyOptions CopyOptions = SqlBulkCopyOptions.Default;
public int? Timeout = null;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.ServiceModel.Security
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security.Tokens;
using System.Text;
using Microsoft.Xml;
//using HexBinary = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary;
using KeyIdentifierClauseEntry = WSSecurityTokenSerializer.KeyIdentifierClauseEntry;
using StrEntry = WSSecurityTokenSerializer.StrEntry;
using TokenEntry = WSSecurityTokenSerializer.TokenEntry;
internal class WSSecurityJan2004 : WSSecurityTokenSerializer.SerializerEntries
{
private WSSecurityTokenSerializer _tokenSerializer;
private SamlSerializer _samlSerializer;
public WSSecurityJan2004(WSSecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
{
_tokenSerializer = tokenSerializer;
_samlSerializer = samlSerializer;
}
public WSSecurityTokenSerializer WSSecurityTokenSerializer
{
get { return _tokenSerializer; }
}
public SamlSerializer SamlSerializer
{
get { return _samlSerializer; }
}
protected void PopulateJan2004TokenEntries(IList<TokenEntry> tokenEntryList)
{
tokenEntryList.Add(new GenericXmlTokenEntry());
tokenEntryList.Add(new UserNamePasswordTokenEntry(_tokenSerializer));
tokenEntryList.Add(new KerberosTokenEntry(_tokenSerializer));
tokenEntryList.Add(new X509TokenEntry(_tokenSerializer));
}
public override void PopulateTokenEntries(IList<TokenEntry> tokenEntryList)
{
PopulateJan2004TokenEntries(tokenEntryList);
tokenEntryList.Add(new SamlTokenEntry(_tokenSerializer, _samlSerializer));
tokenEntryList.Add(new WrappedKeyTokenEntry(_tokenSerializer));
}
internal abstract class BinaryTokenEntry : TokenEntry
{
internal static readonly XmlDictionaryString ElementName = XD.SecurityJan2004Dictionary.BinarySecurityToken;
internal static readonly XmlDictionaryString EncodingTypeAttribute = XD.SecurityJan2004Dictionary.EncodingType;
internal const string EncodingTypeAttributeString = SecurityJan2004Strings.EncodingType;
internal const string EncodingTypeValueBase64Binary = SecurityJan2004Strings.EncodingTypeValueBase64Binary;
internal const string EncodingTypeValueHexBinary = SecurityJan2004Strings.EncodingTypeValueHexBinary;
internal static readonly XmlDictionaryString ValueTypeAttribute = XD.SecurityJan2004Dictionary.ValueType;
private WSSecurityTokenSerializer _tokenSerializer;
private string[] _valueTypeUris = null;
protected BinaryTokenEntry(WSSecurityTokenSerializer tokenSerializer, string valueTypeUri)
{
_tokenSerializer = tokenSerializer;
_valueTypeUris = new string[1];
_valueTypeUris[0] = valueTypeUri;
}
protected BinaryTokenEntry(WSSecurityTokenSerializer tokenSerializer, string[] valueTypeUris)
{
if (valueTypeUris == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("valueTypeUris");
_tokenSerializer = tokenSerializer;
_valueTypeUris = new string[valueTypeUris.GetLength(0)];
for (int i = 0; i < _valueTypeUris.GetLength(0); ++i)
_valueTypeUris[i] = valueTypeUris[i];
}
protected override XmlDictionaryString LocalName { get { return ElementName; } }
protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.Namespace; } }
public override string TokenTypeUri { get { return _valueTypeUris[0]; } }
protected override string ValueTypeUri { get { return _valueTypeUris[0]; } }
public override bool SupportsTokenTypeUri(string tokenTypeUri)
{
for (int i = 0; i < _valueTypeUris.GetLength(0); ++i)
{
if (_valueTypeUris[i] == tokenTypeUri)
return true;
}
return false;
}
public abstract SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromBinaryCore(byte[] rawData);
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml,
SecurityTokenReferenceStyle tokenReferenceStyle)
{
throw new NotImplementedException();
}
public abstract SecurityToken ReadBinaryCore(string id, string valueTypeUri, byte[] rawData);
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
{
throw new NotImplementedException();
}
public abstract void WriteBinaryCore(SecurityToken token, out string id, out byte[] rawData);
public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
{
string id;
byte[] rawData;
WriteBinaryCore(token, out id, out rawData);
if (rawData == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rawData");
}
writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, ElementName, XD.SecurityJan2004Dictionary.Namespace);
if (id != null)
{
writer.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace, id);
}
if (_valueTypeUris != null)
{
writer.WriteAttributeString(ValueTypeAttribute, null, _valueTypeUris[0]);
}
if (_tokenSerializer.EmitBspRequiredAttributes)
{
writer.WriteAttributeString(EncodingTypeAttribute, null, EncodingTypeValueBase64Binary);
}
writer.WriteBase64(rawData, 0, rawData.Length);
writer.WriteEndElement(); // BinarySecurityToken
}
}
private class GenericXmlTokenEntry : TokenEntry
{
protected override XmlDictionaryString LocalName { get { return null; } }
protected override XmlDictionaryString NamespaceUri { get { return null; } }
protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(GenericXmlSecurityToken) }; }
public override string TokenTypeUri { get { return null; } }
protected override string ValueTypeUri { get { return null; } }
public GenericXmlTokenEntry()
{
}
public override bool CanReadTokenCore(XmlElement element)
{
return false;
}
public override bool CanReadTokenCore(XmlDictionaryReader reader)
{
return false;
}
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml,
SecurityTokenReferenceStyle tokenReferenceStyle)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
{
throw new NotImplementedException();
}
}
private class KerberosTokenEntry : BinaryTokenEntry
{
public KerberosTokenEntry(WSSecurityTokenSerializer tokenSerializer)
: base(tokenSerializer, new string[] { SecurityJan2004Strings.KerberosTokenTypeGSS, SecurityJan2004Strings.KerberosTokenType1510 })
{
}
protected override Type[] GetTokenTypesCore()
{
throw new NotImplementedException();
}
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromBinaryCore(byte[] rawData)
{
throw new NotImplementedException();
}
public override SecurityToken ReadBinaryCore(string id, string valueTypeUri, byte[] rawData)
{
throw new NotImplementedException();
}
public override void WriteBinaryCore(SecurityToken token, out string id, out byte[] rawData)
{
throw new NotImplementedException();
}
}
protected class SamlTokenEntry : TokenEntry
{
private const string samlAssertionId = "AssertionID";
private SamlSerializer _samlSerializer;
private SecurityTokenSerializer _tokenSerializer;
public SamlTokenEntry(SecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
{
_tokenSerializer = tokenSerializer;
if (samlSerializer != null)
{
_samlSerializer = samlSerializer;
}
else
{
_samlSerializer = new SamlSerializer();
}
_samlSerializer.PopulateDictionary(BinaryMessageEncoderFactory.XmlDictionary);
}
protected override XmlDictionaryString LocalName { get { return XD.SecurityJan2004Dictionary.SamlAssertion; } }
protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.SamlUri; } }
protected override Type[] GetTokenTypesCore()
{
throw new NotImplementedException();
}
public override string TokenTypeUri { get { return null; } }
protected override string ValueTypeUri { get { return null; } }
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml,
SecurityTokenReferenceStyle tokenReferenceStyle)
{
throw new NotImplementedException();
}
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
{
throw new NotImplementedException();
}
public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
{
throw new NotImplementedException();
}
}
private class UserNamePasswordTokenEntry : TokenEntry
{
private WSSecurityTokenSerializer _tokenSerializer;
public UserNamePasswordTokenEntry(WSSecurityTokenSerializer tokenSerializer)
{
_tokenSerializer = tokenSerializer;
}
protected override XmlDictionaryString LocalName { get { return XD.SecurityJan2004Dictionary.UserNameTokenElement; } }
protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.Namespace; } }
protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(UserNameSecurityToken) }; }
public override string TokenTypeUri { get { return SecurityJan2004Strings.UPTokenType; } }
protected override string ValueTypeUri { get { return null; } }
public override IAsyncResult BeginReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver, AsyncCallback callback, object state)
{
string id;
string userName;
string password;
ParseToken(reader, out id, out userName, out password);
SecurityToken token = new UserNameSecurityToken(userName, password, id);
return new CompletedAsyncResult<SecurityToken>(token, callback, state);
}
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml,
SecurityTokenReferenceStyle tokenReferenceStyle)
{
TokenReferenceStyleHelper.Validate(tokenReferenceStyle);
switch (tokenReferenceStyle)
{
case SecurityTokenReferenceStyle.Internal:
return CreateDirectReference(issuedTokenXml, UtilityStrings.IdAttribute, UtilityStrings.Namespace, typeof(UserNameSecurityToken));
case SecurityTokenReferenceStyle.External:
// UP tokens aren't referred to externally
return null;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenReferenceStyle"));
}
}
public override SecurityToken EndReadTokenCore(IAsyncResult result)
{
return CompletedAsyncResult<SecurityToken>.End(result);
}
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
{
string id;
string userName;
string password;
ParseToken(reader, out id, out userName, out password);
if (id == null)
id = SecurityUniqueId.Create().Value;
return new UserNameSecurityToken(userName, password, id);
}
public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
{
UserNameSecurityToken upToken = (UserNameSecurityToken)token;
WriteUserNamePassword(writer, upToken.Id, upToken.UserName, upToken.Password);
}
private void WriteUserNamePassword(XmlDictionaryWriter writer, string id, string userName, string password)
{
writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.UserNameTokenElement,
XD.SecurityJan2004Dictionary.Namespace); // <wsse:UsernameToken
writer.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute,
XD.UtilityDictionary.Namespace, id); // wsu:Id="..."
writer.WriteElementString(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.UserNameElement,
XD.SecurityJan2004Dictionary.Namespace, userName); // ><wsse:Username>...</wsse:Username>
if (password != null)
{
writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.PasswordElement,
XD.SecurityJan2004Dictionary.Namespace);
if (_tokenSerializer.EmitBspRequiredAttributes)
{
writer.WriteAttributeString(XD.SecurityJan2004Dictionary.TypeAttribute, null, SecurityJan2004Strings.UPTokenPasswordTextValue);
}
writer.WriteString(password); // <wsse:Password>...</wsse:Password>
writer.WriteEndElement();
}
writer.WriteEndElement(); // </wsse:UsernameToken>
}
private static string ParsePassword(XmlDictionaryReader reader)
{
string type = reader.GetAttribute(XD.SecurityJan2004Dictionary.TypeAttribute, null);
if (type != null && type.Length > 0 && type != SecurityJan2004Strings.UPTokenPasswordTextValue)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(string.Format(SRServiceModel.UnsupportedPasswordType, type)));
}
return reader.ReadElementString();
}
private static void ParseToken(XmlDictionaryReader reader, out string id, out string userName, out string password)
{
id = null;
userName = null;
password = null;
reader.MoveToContent();
id = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
reader.ReadStartElement(XD.SecurityJan2004Dictionary.UserNameTokenElement, XD.SecurityJan2004Dictionary.Namespace);
while (reader.IsStartElement())
{
if (reader.IsStartElement(XD.SecurityJan2004Dictionary.UserNameElement, XD.SecurityJan2004Dictionary.Namespace))
{
userName = reader.ReadElementString();
}
else if (reader.IsStartElement(XD.SecurityJan2004Dictionary.PasswordElement, XD.SecurityJan2004Dictionary.Namespace))
{
password = ParsePassword(reader);
}
else if (reader.IsStartElement(XD.SecurityJan2004Dictionary.NonceElement, XD.SecurityJan2004Dictionary.Namespace))
{
// Nonce can be safely ignored
reader.Skip();
}
else if (reader.IsStartElement(XD.UtilityDictionary.CreatedElement, XD.UtilityDictionary.Namespace))
{
// wsu:Created can be safely ignored
reader.Skip();
}
else
{
XmlHelper.OnUnexpectedChildNodeError(SecurityJan2004Strings.UserNameTokenElement, reader);
}
}
reader.ReadEndElement();
if (userName == null)
XmlHelper.OnRequiredElementMissing(SecurityJan2004Strings.UserNameElement, SecurityJan2004Strings.Namespace);
}
}
protected class WrappedKeyTokenEntry : TokenEntry
{
private WSSecurityTokenSerializer _tokenSerializer;
public WrappedKeyTokenEntry(WSSecurityTokenSerializer tokenSerializer)
{
_tokenSerializer = tokenSerializer;
}
protected override XmlDictionaryString LocalName { get { return EncryptedKey.ElementName; } }
protected override XmlDictionaryString NamespaceUri { get { return XD.XmlEncryptionDictionary.Namespace; } }
protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(WrappedKeySecurityToken) }; }
public override string TokenTypeUri { get { return null; } }
protected override string ValueTypeUri { get { return null; } }
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml,
SecurityTokenReferenceStyle tokenReferenceStyle)
{
TokenReferenceStyleHelper.Validate(tokenReferenceStyle);
switch (tokenReferenceStyle)
{
case SecurityTokenReferenceStyle.Internal:
return CreateDirectReference(issuedTokenXml, XmlEncryptionStrings.Id, null, null);
case SecurityTokenReferenceStyle.External:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(string.Format(SRServiceModel.CantInferReferenceForToken, EncryptedKey.ElementName.Value)));
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenReferenceStyle"));
}
}
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
{
EncryptedKey encryptedKey = new EncryptedKey();
encryptedKey.SecurityTokenSerializer = _tokenSerializer;
encryptedKey.ReadFrom(reader);
SecurityKeyIdentifier unwrappingTokenIdentifier = encryptedKey.KeyIdentifier;
byte[] wrappedKey = encryptedKey.GetWrappedKey();
WrappedKeySecurityToken wrappedKeyToken = CreateWrappedKeyToken(encryptedKey.Id, encryptedKey.EncryptionMethod,
encryptedKey.CarriedKeyName, unwrappingTokenIdentifier, wrappedKey, tokenResolver);
wrappedKeyToken.EncryptedKey = encryptedKey;
return wrappedKeyToken;
}
private WrappedKeySecurityToken CreateWrappedKeyToken(string id, string encryptionMethod, string carriedKeyName,
SecurityKeyIdentifier unwrappingTokenIdentifier, byte[] wrappedKey, SecurityTokenResolver tokenResolver)
{
throw new NotImplementedException();
}
public override void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token)
{
throw new NotImplementedException();
}
}
protected class X509TokenEntry : BinaryTokenEntry
{
internal const string ValueTypeAbsoluteUri = SecurityJan2004Strings.X509TokenType;
public X509TokenEntry(WSSecurityTokenSerializer tokenSerializer)
: base(tokenSerializer, ValueTypeAbsoluteUri)
{
}
protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(X509SecurityToken), typeof(X509WindowsSecurityToken) }; }
public override SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromBinaryCore(byte[] rawData)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(string.Format(SRServiceModel.CantInferReferenceForToken, ValueTypeAbsoluteUri)));
}
public override SecurityToken ReadBinaryCore(string id, string valueTypeUri, byte[] rawData)
{
X509Certificate2 certificate;
if (!SecurityUtils.TryCreateX509CertificateFromRawData(rawData, out certificate))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(string.Format(SRServiceModel.InvalidX509RawData)));
}
return new X509SecurityToken(certificate, id, false);
}
public override void WriteBinaryCore(SecurityToken token, out string id, out byte[] rawData)
{
throw new NotImplementedException();
}
}
public class IdManager : SignatureTargetIdManager
{
private static readonly IdManager s_instance = new IdManager();
private IdManager()
{
}
public override string DefaultIdNamespacePrefix
{
get { return UtilityStrings.Prefix; }
}
public override string DefaultIdNamespaceUri
{
get { return UtilityStrings.Namespace; }
}
internal static IdManager Instance
{
get { return s_instance; }
}
public override string ExtractId(XmlDictionaryReader reader)
{
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
if (reader.IsStartElement(EncryptedData.ElementName, XD.XmlEncryptionDictionary.Namespace))
{
return reader.GetAttribute(XD.XmlEncryptionDictionary.Id, null);
}
else
{
return reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
}
}
public override void WriteIdAttribute(XmlDictionaryWriter writer, string id)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
writer.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace, id);
}
}
}
}
| |
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 Snake.Api.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;
}
}
}
| |
#region License
//L
// 2007 - 2013 Copyright Northwestern University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
//L
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using ClearCanvas.Common;
using ClearCanvas.Common.Utilities;
using ClearCanvas.Desktop;
using ClearCanvas.Desktop.Validation;
using ClearCanvas.Dicom;
using ClearCanvas.Dicom.Network;
using ClearCanvas.Dicom.Network.Scu;
using ClearCanvas.ImageViewer;
using ClearCanvas.ImageViewer.Graphics;
using ClearCanvas.ImageViewer.RoiGraphics;
using ClearCanvas.ImageViewer.RoiGraphics.Analyzers;
using ClearCanvas.ImageViewer.Services.LocalDataStore;
using ClearCanvas.ImageViewer.StudyManagement;
using ClearCanvas.ImageViewer.Services.ServerTree;
using AIM.Annotation.Configuration;
using aim_dotnet;
using AnatomicEntity = aim_dotnet.AnatomicEntity;
using ImagingObservation = aim_dotnet.ImagingObservation;
using Inference = aim_dotnet.Inference;
namespace AIM.Annotation
{
[ExtensionPoint]
public sealed class AimAnnotationComponentViewExtensionPoint : ExtensionPoint<IApplicationComponentView>
{
}
[AssociateView(typeof(AimAnnotationComponentViewExtensionPoint))]
public class AimAnnotationComponent : ImageViewerToolComponent
{
private string _annotationName;
private List<AnatomicEntity> _anatomicEntities;
private List<ImagingObservation> _imagingObservations;
private List<Inference> _inferences;
private StandardCodeSequence _annotationTypeCode; // i.e. selected template code
private Template.TemplateContainer _loadedTemplateContainer;
private bool _isAimTemplateValid;
private Dictionary<string, string> _sopInstanceUidToAeTitle = new Dictionary<string, string>();
private object _mapLock = new object();
private ILocalDataStoreEventBroker _localDataStoreEventBroker;
public event EventHandler AnnotationCreated;
public event EventHandler AnnotationCreating;
public static StandardCodeSequence NullCodeValue = new StandardCodeSequence("C47840", "Null", "NCIt");
public AimAnnotationComponent(IDesktopWindow desktopWindow)
: base(desktopWindow)
{
if (AvailableAnnotationTypes.Count > 0)
_annotationTypeCode = AvailableAnnotationTypes[0];
AnnotationName = CreateDefaultAnnotationName();
}
[ValidateNotNull(Message = "AnnotationTypeCannotBeNull")]
public StandardCodeSequence AnnotationTypeCode
{
get { return _annotationTypeCode; }
set
{
if (_annotationTypeCode != value)
{
if (_annotationTypeCode != null && _annotationTypeCode.Equals(value))
return;
_annotationTypeCode = value;
NotifyPropertyChanged("SelectedAimTemplate");
NotifyPropertyChanged("AimTemplateVisible");
}
}
}
public List<StandardCodeSequence> AvailableAnnotationTypes
{
get { return AvailableAimTemplates; }
}
public bool AimTemplateVisible
{
get
{
return AnnotationTypeCode == null ||
AvailableAimTemplates.Find(code => code.Equals(AnnotationTypeCode)) != null;
}
}
[ValidateNotNull(Message = "AnnotationNameCannotBeNull")]
public string AnnotationName
{
get { return _annotationName; }
set
{
if (_annotationName != value)
{
_annotationName = value;
NotifyPropertyChanged("AnnotationName");
NotifyPropertyChanged("CreateAnnotationEnabled");
}
}
}
#region User Info
public string UserName
{
get { return AimSettings.Default.UserName; }
set
{
if (AimSettings.Default.UserName != value)
{
AimSettings.Default.UserName = value;
AimSettings.Default.Save();
}
}
}
public string LoginName
{
get { return AimSettings.Default.UserLoginName; }
set
{
if (AimSettings.Default.UserLoginName != value)
{
AimSettings.Default.UserLoginName = value;
AimSettings.Default.Save();
}
}
}
public string RoleInTrial
{
get { return AimSettings.Default.UserRoleInTrial; }
set
{
if (AimSettings.Default.UserRoleInTrial != value)
{
AimSettings.Default.UserRoleInTrial = value;
AimSettings.Default.Save();
}
}
}
public int NumberWithinRoleInTrial
{
get { return AimSettings.Default.UserNumberWitinRoleOfClinicalTrial; }
set
{
AimSettings.Default.UserNumberWitinRoleOfClinicalTrial = value;
AimSettings.Default.Save();
}
}
#endregion User Info
private string CreateDefaultAnnotationName()
{
var defaultName = "";
var dateTime = DateTime.Now;
var dateTimeStr = dateTime.ToString("yyyy-MM-dd HH:mm tt");
var iImageSopProvider = ImageViewer.SelectedPresentationImage as IImageSopProvider;
if (iImageSopProvider != null)
{
defaultName = iImageSopProvider.ImageSop.PatientId + "_" + AimSettings.Default.UserName + "_" + dateTimeStr;
}
return defaultName;
}
/// <summary>
/// Validates an XML template against the v19 and v23 schemas, while converting
/// v19 templates to v23 templates and returning the filename of the original
/// template if not converted, or a new filename if the template was converted.
/// </summary>
/// <param name="templateFilename">The filename of the validated v23 template. Empty
/// if validation fails.</param>
/// <returns></returns>
private string ValidateAndConvertAimTemplate(string templateFilename)
{
var validated = false;
Utilities.ValidationResult result;
// Validate against v19 schema first
try
{
result = Utilities.ValidateXML.Initialize(
"AIM.Annotation.Template.AIMTemplate_v1rv19.xsd",
"gme://caCORE.caCORE/3.2/edu.northwestern.radiology.AIMTemplate",
templateFilename);
// Convert to v23 if v19 template validated
if (result.Validated)
{
try
{
var newTemplateFilename = System.IO.Path.GetTempFileName();
var mapper = new AimTemplateConverter.ConverterToAimTemplateV1Rv23();
mapper.Run(templateFilename, newTemplateFilename);
templateFilename = newTemplateFilename;
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to convert template file: {0} from v19 to v23", templateFilename);
}
}
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to validate v19 template file: {0}", templateFilename);
}
// Validate against v23 template
try
{
result = Utilities.ValidateXML.Initialize(
"AIM.Annotation.Template.AIMTemplate_v1rv23.xsd",
"gme://caCORE.caCORE/3.2/edu.northwestern.radiology.AIMTemplate",
templateFilename);
validated = result.Validated;
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to validate v23 template file: {0}", templateFilename);
}
return validated ? templateFilename : string.Empty;
}
public Template.TemplateContainer LoadedTemplateDoc
{
get
{
if (_loadedTemplateContainer == null)
{
var templateDocPathName = AimSettings.Default.SelectedTemplatePathName ?? "";
if (System.IO.File.Exists(templateDocPathName))
{
try
{
var template = ValidateAndConvertAimTemplate(templateDocPathName);
if (!string.IsNullOrEmpty(template))
using (var fs = System.IO.File.OpenRead(template))
{
_loadedTemplateContainer = Template.TemplateContainerSerializer.ReadStream(fs);
}
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to open template file: {0}", templateDocPathName);
}
}
if (_loadedTemplateContainer == null)
{
var resolver = new ResourceResolver(GetType().Assembly);
try
{
using (var stream = resolver.OpenResource("Template.AIM_Template_v1rv18_TCGA_v5.xml"))
{
_loadedTemplateContainer = Template.TemplateContainerSerializer.ReadStream(stream);
}
}
catch (Exception)
{
_loadedTemplateContainer = null;
}
}
}
return _loadedTemplateContainer;
}
}
public Template.Template SelectedAimTemplate
{
get
{
return LoadedTemplateDoc == null
? null
: LoadedTemplateDoc.Template.Find(
t =>
t.CodeValue == AnnotationTypeCode.CodeValue &&
t.CodeMeaning == AnnotationTypeCode.CodeMeaning &&
t.CodingSchemeDesignator == AnnotationTypeCode.CodingSchemeDesignator &&
t.CodingSchemeVersion == AnnotationTypeCode.CodingSchemeVersion);
}
}
public List<StandardCodeSequence> AvailableAimTemplates
{
get
{
var retVal = new List<StandardCodeSequence>();
if (LoadedTemplateDoc != null)
{
LoadedTemplateDoc.Template.ForEach(
template =>
retVal.Add(new StandardCodeSequence(
template.CodeValue,
template.CodeMeaning,
template.CodingSchemeDesignator,
template.CodingSchemeVersion))
);
}
return retVal;
}
}
public string SelectedAimTemplateDocument
{
get { return AimSettings.Default.SelectedTemplatePathName ?? ""; }
set
{
if (AimSettings.Default.SelectedTemplatePathName != value &&
AvailableAnnotationTypes.Count > 0)
{
AimSettings.Default.SelectedTemplatePathName = value;
AimSettings.Default.Save();
_loadedTemplateContainer = null;
AnnotationTypeCode = AvailableAnnotationTypes[0];
NotifyPropertyChanged("AvailableAnnotationTypes");
}
}
}
public string SelectedAimTemplateLocalFolder
{
get
{
return System.IO.File.Exists(AimSettings.Default.SelectedTemplatePathName ?? "")
? System.IO.Path.GetFullPath(AimSettings.Default.SelectedTemplatePathName ?? "")
: (string.IsNullOrEmpty(AimSettings.Default.LocalTemplatesFolder)
? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
: AimSettings.Default.LocalTemplatesFolder);
}
}
public List<AnatomicEntity> SelectedAnatomicEntities
{
get { return _anatomicEntities; }
set
{
if (_anatomicEntities != value)
{
_anatomicEntities = (null == value || value.Count == 0) ? null : new List<AnatomicEntity>(value);
NotifyPropertyChanged("SelectedAnatomicEntities");
NotifyPropertyChanged("CreateAnnotationEnabled");
}
}
}
public List<ImagingObservation> SelectedImagingObservations
{
get { return _imagingObservations; }
set
{
if (_imagingObservations != value)
{
_imagingObservations = (null == value || value.Count == 0) ? null : new List<ImagingObservation>(value);
NotifyPropertyChanged("SelectedImagingObservations");
}
}
}
public List<Inference> SelectedInferences
{
get { return _inferences; }
set
{
if (_inferences != value)
{
_inferences = null == value || value.Count == 0 ? null : new List<Inference>(value);
NotifyPropertyChanged("SelectedInferences");
}
}
}
public bool AnnotationModuleEnabled
{
get { return ImageViewer != null && ImageViewer.SelectedPresentationImage != null; }
}
public bool CreateAnnotationEnabled
{
get
{
return !HasValidationErrors &&
AnnotationModuleEnabled && AnnotationTypeCode != null
&& !string.IsNullOrEmpty(_annotationName)
&& (!AimTemplateVisible || (AimTemplateVisible && IsAimTemplateValid))
&& HasValidUserData
&& HasRequiredMakup;
}
}
protected bool IsAnatomicEntityEmpty
{
get { return _anatomicEntities == null || _anatomicEntities.Count == 0; }
}
protected bool HasValidUserData
{
get { return !AimSettings.Default.RequireUserInfo || !string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(LoginName); }
}
protected bool HasRequiredMakup
{
get { return !AimSettings.Default.RequireMarkupInAnnotation || AimHelpers.IsImageMarkupPresent(ImageViewer.SelectedPresentationImage); }
}
public bool IsAimTemplateValid
{
get { return _isAimTemplateValid; }
set
{
if (_isAimTemplateValid != value)
{
_isAimTemplateValid = value;
NotifyPropertyChanged("CreateAnnotationEnabled");
}
}
}
protected override void OnActiveImageViewerChanged(ActiveImageViewerChangedEventArgs e)
{
if (e.ActivatedImageViewer != null)
{
e.ActivatedImageViewer.EventBroker.TileSelected += OnTileSelected;
e.ActivatedImageViewer.EventBroker.MouseCaptureChanged += OnMouseCaptureChanged;
e.ActivatedImageViewer.EventBroker.GraphicSelectionChanged += OnGraphicSelectionChanged;
}
NotifyPropertyChanged("AnnotationModuleEnabled");
NotifyPropertyChanged("CreateAnnotationEnabled");
NotifyPropertyChanged("CalculationInfo");
}
protected override void OnActiveImageViewerChanging(ActiveImageViewerChangedEventArgs e)
{
if (e.DeactivatedImageViewer != null)
{
e.DeactivatedImageViewer.EventBroker.TileSelected -= OnTileSelected;
e.DeactivatedImageViewer.EventBroker.MouseCaptureChanged -= OnMouseCaptureChanged;
e.DeactivatedImageViewer.EventBroker.GraphicSelectionChanged -= OnGraphicSelectionChanged;
}
}
private void OnTileSelected(object sender, TileSelectedEventArgs e)
{
NotifyPropertyChanged("AnnotationModuleEnabled");
NotifyPropertyChanged("CreateAnnotationEnabled");
NotifyPropertyChanged("CalculationInfo");
}
private void OnMouseCaptureChanged(object sender, ClearCanvas.ImageViewer.InputManagement.MouseCaptureChangedEventArgs e)
{
NotifyPropertyChanged("CalculationInfo");
}
private void OnGraphicSelectionChanged(object sender, GraphicSelectionChangedEventArgs e)
{
NotifyPropertyChanged("AnnotationModuleEnabled");
NotifyPropertyChanged("CreateAnnotationEnabled");
}
#region Start/Stop methods
public override void Start()
{
base.Start();
_localDataStoreEventBroker = LocalDataStoreActivityMonitor.CreatEventBroker();
_localDataStoreEventBroker.SopInstanceImported += OnSopInstanceImported;
AimSettings.Default.PropertyChanged += OnAimSettingsChanged;
try
{
// Create extension points that use this component
var xp = new AimAnnotationExtensionPoint();
foreach (var obj in xp.CreateExtensions())
{
var extension = (IAimAnnotationExtension)obj;
extension.Component = this;
}
}
catch (NotSupportedException)
{
}
}
public override void Stop()
{
AimSettings.Default.PropertyChanged -= OnAimSettingsChanged;
_localDataStoreEventBroker.SopInstanceImported -= OnSopInstanceImported;
_localDataStoreEventBroker.Dispose();
base.Stop();
}
#endregion
private void OnAimSettingsChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
NotifyPropertyChanged("CreateAnnotationEnabled");
}
public string[] CalculationInfo
{
get
{
if (ImageViewer != null)
{
var overlayGraphicProvider = ImageViewer.SelectedPresentationImage as IOverlayGraphicsProvider;
if (overlayGraphicProvider != null)
{
var sb = new StringBuilder();
var lineFeed = Environment.NewLine + " ";
var roiCnt = 0;
foreach (var graphic in overlayGraphicProvider.OverlayGraphics)
{
var currentRoiGraphic = graphic as RoiGraphic;
if (currentRoiGraphic != null)
{
if (sb.Length > 0)
sb.Append(Environment.NewLine);
if (string.IsNullOrEmpty(currentRoiGraphic.Name))
sb.AppendFormat("ROI #{0}:", ++roiCnt);
else
sb.AppendFormat("ROI #{0} ({1}):", ++roiCnt, currentRoiGraphic.Name);
var roi = currentRoiGraphic.Roi;
foreach (var analyzer in currentRoiGraphic.Callout.RoiAnalyzers)
{
if (analyzer.SupportsRoi(roi))
{
var text = analyzer.Analyze(roi, RoiAnalysisMode.Normal).Trim().Replace("\r\n", "{0}").Replace("\n", "{0}");
sb.Append(lineFeed);
sb.AppendFormat(text, lineFeed);
}
}
}
}
var strRetVal = sb.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
sb.Length = 0;
return strRetVal;
}
}
return new string[0];
}
set { }
}
private void ResetAnnotationData()
{
SelectedImagingObservations = null;
SelectedAnatomicEntities = null;
SelectedInferences = null;
AnnotationName = CreateDefaultAnnotationName();
EventsHelper.Fire(AnnotationCreated, this, EventArgs.Empty);
}
private List<aim_dotnet.Annotation> CreateAnnotationsFromUserInput(out List<IGraphic> annotationsGraphic)
{
var aimContext = new AimAnnotationCreationContext(AnnotationKind.AK_ImageAnnotation, AnnotationTypeCode, AnnotationName);
aimContext.SelectedAnatomicEntities = SelectedAnatomicEntities;
aimContext.SelectedImagingObservations = SelectedImagingObservations;
aimContext.SelectedInferences = SelectedInferences;
aimContext.AnnotationUser = (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(LoginName))
?
new User
{
Name = UserName,
LoginName = LoginName,
RoleInTrial = RoleInTrial,
NumberWithinRoleOfClinicalTrial = NumberWithinRoleInTrial >= 0 ? NumberWithinRoleInTrial : -1
}
: null;
aimContext.includeCalculations = true;
aimContext.SOPImageUIDs = new List<string> { ((IImageSopProvider)ImageViewer.SelectedPresentationImage).ImageSop.SopInstanceUid };
return AimHelpers.CreateAimAnnotations(ImageViewer.SelectedPresentationImage.ParentDisplaySet.PresentationImages, aimContext, out annotationsGraphic);
}
private List<IGraphic> _annotationGraphics;
public List<IGraphic> AnnotationGraphics { get { return _annotationGraphics; } }
public void CreateAnnotation()
{
if (!CreateAnnotationEnabled)
return;
if (base.HasValidationErrors)
{
Platform.Log(LogLevel.Info, "Cannot create annotation. Validation error(s): " + Validation.GetErrorsString(this));
ShowValidation(true);
return;
}
if (!LocalDataStoreActivityMonitor.IsConnected)
{
DesktopWindow.ShowMessageBox("Failed to save annotation. Not connected to the local data store. Is workstation service running?", MessageBoxActions.Ok);
return;
}
// Get new annotations
List<IGraphic> annotationsGraphic;
var annotations = CreateAnnotationsFromUserInput(out annotationsGraphic);
_annotationGraphics = annotationsGraphic;
if (annotations.Count == 0)
{
Platform.Log(LogLevel.Warn, "CreateAnnotation resulted in no annotations being created");
return;
}
EventsHelper.Fire(AnnotationCreating, this, EventArgs.Empty);
var isAnyOperationPerformed = false;
if (AimSettings.Default.StoreXmlAnnotationsLocally)
{
var destinationFolder = AimSettings.Default.ActualAnnotationStoreFolder;
try
{
if (!System.IO.Directory.Exists(destinationFolder))
System.IO.Directory.CreateDirectory(destinationFolder);
var annFiles = AimHelpers.WriteXmlAnnotationsToFolder(annotations, destinationFolder);
if (annotations.Count != annFiles.Length)
Platform.Log(LogLevel.Error, "Only {0} annotations(s) out of {1} written to \"{0}\"", annFiles.Length, annotations.Count, destinationFolder);
isAnyOperationPerformed = annFiles.Length > 0;
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to store annotations to local folder \"{0}\"", destinationFolder);
}
}
if (AimSettings.Default.SendNewXmlAnnotationsToGrid)
{
if (SendAnnotationsToGrid(annotations))
isAnyOperationPerformed = true;
else
Platform.Log(LogLevel.Error, "Failed to send annotations to the caGrid");
}
if (LocalDataStoreActivityMonitor.IsConnected)
isAnyOperationPerformed = SendAnnotationsToLocalStorageAndPacs(annotations) || isAnyOperationPerformed;
else
DesktopWindow.ShowMessageBox("Failed to save annotation. Not connected to the local data store. Is workstation service running?", MessageBoxActions.Ok);
if (isAnyOperationPerformed)
{
UpdateImagesWithProperAimGraphic(annotations, annotationsGraphic);
// Reset all controls on the template
//ResetAnnotationData();
}
}
private void UpdateImagesWithProperAimGraphic(List<aim_dotnet.Annotation> annotations, List<IGraphic> annotationsGraphic)
{
var hasChanges = false;
if (annotationsGraphic != null)
{
foreach (var graphic in annotationsGraphic)
{
Debug.Assert(graphic.ParentPresentationImage == null || graphic.ParentPresentationImage == ImageViewer.SelectedPresentationImage);
var currentOverlayGraphics = graphic.ParentPresentationImage as IOverlayGraphicsProvider;
if (currentOverlayGraphics != null && currentOverlayGraphics.OverlayGraphics != null)
hasChanges |= currentOverlayGraphics.OverlayGraphics.Remove(graphic);
}
}
if (annotations != null)
{
foreach (var annotation in annotations)
{
hasChanges |= AimHelpers.ReadGraphicsFromAnnotation(annotation, ImageViewer.SelectedPresentationImage);
}
}
if (hasChanges)
ImageViewer.SelectedPresentationImage.Draw();
}
private bool SendAnnotationsToLocalStorageAndPacs(List<aim_dotnet.Annotation> annotations)
{
var model = new DcmModel();
var instanceInfos = new Dictionary<string, string>();
foreach (var annotation in annotations)
{
var tempFileName = System.IO.Path.GetTempFileName();
try
{
model.WriteAnnotationToFile(annotation, tempFileName);
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, "Failed to save annotation to temp file.", ex);
try
{
System.IO.File.Delete(tempFileName);
}
catch
{
}
continue;
}
var annFile = new DicomFile(tempFileName);
annFile.Load(DicomReadOptions.Default | DicomReadOptions.DoNotStorePixelDataInDataSet);
var annSopInstanceUid = annFile.DataSet[DicomTags.SopInstanceUid].GetString(0, string.Empty);
annFile = null;
instanceInfos.Add(annSopInstanceUid, tempFileName);
}
model = null;
if (instanceInfos.Count < 1)
return false;
var imageAeTitle = string.Empty;
var imageSopProvider = ImageViewer.SelectedPresentationImage as IImageSopProvider;
if (imageSopProvider != null)
{
var localSopDataSource = imageSopProvider.ImageSop.DataSource as ILocalSopDataSource; //NativeDicomObject as DicomFile;
if (localSopDataSource != null)
imageAeTitle = localSopDataSource.File.SourceApplicationEntityTitle.Trim("\n\r".ToCharArray());
}
using (var localClient = new LocalDataStoreServiceClient())
{
try
{
localClient.Open();
var request = new FileImportRequest();
request.BadFileBehaviour = BadFileBehaviour.Delete;
request.FileImportBehaviour = FileImportBehaviour.Move;
var filePaths = new List<string>();
foreach (var instanceInfo in instanceInfos)
{
var annSopInstanceUid = instanceInfo.Key;
var tempFileName = instanceInfo.Value;
filePaths.Add(tempFileName);
if (!string.IsNullOrEmpty(imageAeTitle))
{
lock (_mapLock)
_sopInstanceUidToAeTitle.Add(annSopInstanceUid, imageAeTitle);
}
}
request.FilePaths = filePaths.ToArray();
request.IsBackground = true;
request.Recursive = false;
localClient.Import(request);
localClient.Close();
}
catch (Exception ex)
{
localClient.Abort();
Platform.Log(LogLevel.Error, ex);
DesktopWindow.ShowMessageBox("Failed to store your annotation(s).", "Annotation Import Error", MessageBoxActions.Ok);
return false;
}
}
return true;
}
private Server FindAETitle(ServerGroup serverGroup, string aeTitle)
{
foreach (var server in serverGroup.ChildServers)
{
if (server.AETitle == aeTitle)
return server;
}
foreach (var childeServerGroup in serverGroup.ChildGroups)
{
var server = FindAETitle(childeServerGroup, aeTitle);
if (server != null)
return server;
}
return null;
}
// Called when a SOP Instance is imported into the local datastore
private void OnSopInstanceImported(object sender, ItemEventArgs<ImportedSopInstanceInformation> e)
{
if (_sopInstanceUidToAeTitle.ContainsKey(e.Item.SopInstanceUid))
{
var destinationAeTitle = _sopInstanceUidToAeTitle[e.Item.SopInstanceUid];
var destinationServer = FindAETitle(new ServerTree().RootNode.ServerGroupNode, destinationAeTitle);
if (destinationServer == null)
{
Platform.Log(LogLevel.Error, "Study " + e.Item.SopInstanceUid + " cannot be send to server. Failed to find server infromation for AE Title " + destinationAeTitle + ".");
}
else
{
var storageScu = new StorageScu(ServerTree.GetClientAETitle(), destinationServer.AETitle, destinationServer.Host, destinationServer.Port);
storageScu.ImageStoreCompleted += OnStoreEachInstanceCompleted;
storageScu.AddFile(e.Item.SopInstanceFileName);
storageScu.BeginSend(OnAnnotationSendComplete, storageScu);
}
lock (_mapLock)
_sopInstanceUidToAeTitle.Remove(e.Item.SopInstanceUid);
}
}
private void OnStoreEachInstanceCompleted(object sender, StorageInstance e)
{
if (e.SendStatus.Status != DicomState.Success)
Platform.Log(LogLevel.Error, "Failed to send annotation to server. Status: " + e.SendStatus.Description);
}
private void OnAnnotationSendComplete(IAsyncResult ar)
{
var storageScu = (StorageScu)ar.AsyncState;
if (storageScu.TotalSubOperations - storageScu.SuccessSubOperations > 0)
Platform.Log(LogLevel.Error, "Not all annotations could be stored to server.");
storageScu.Dispose();
}
private bool SendAnnotationsToGrid(List<aim_dotnet.Annotation> annotations)
{
if (annotations == null || annotations.Count == 0)
return true;
var xmlAnnotations = new Dictionary<string, string>();
var xmlModel = new XmlModel();
foreach (var annotation in annotations)
{
try
{
xmlAnnotations.Add(annotation.UniqueIdentifier, xmlModel.WriteAnnotationToXmlString(annotation));
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to convert annotation to xml.");
}
}
xmlModel = null;
// Send Annotations to AIM Service
if (xmlAnnotations.Count > 0)
{
BackgroundTask task = null;
try
{
task = new BackgroundTask(BackgroundSendAnnotationsToAimService, false, xmlAnnotations);
ProgressDialog.Show(task, DesktopWindow, true);
return true;
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, e, "Failed to send annotation(s) to the AIM data service");
DesktopWindow.ShowMessageBox("Failed to send annotation(s) to the AIM data service. See log for details.", MessageBoxActions.Ok);
}
finally
{
if (task != null)
task.Dispose();
}
}
return false;
}
private void BackgroundSendAnnotationsToAimService(IBackgroundTaskContext context)
{
var xmlAnnotations = context.UserState as Dictionary<string, string>;
try
{
if (xmlAnnotations != null && xmlAnnotations.Count > 0)
{
var progress = new BackgroundTaskProgress(20, string.Format("Sending {0} annotation(s) to AIM data service.", xmlAnnotations.Count));
context.ReportProgress(progress);
AIMTCGAService.AIMTCGASubmit.sendAIMTCGAAnnotation(new List<string>(xmlAnnotations.Values).ToArray());
}
context.Complete();
}
catch (Exception ex)
{
SaveAnnotationsToQueue(xmlAnnotations, AIMTCGAService.AIMTCGASubmit.ServiceUrl);
context.Error(ex);
}
}
private void SaveAnnotationsToQueue(Dictionary<string, string> xmlAnnotations, string serverUrl)
{
Uri uri;
string folderName;
if (!string.IsNullOrEmpty(serverUrl) && Uri.TryCreate(serverUrl, UriKind.RelativeOrAbsolute, out uri))
{
if (AimSettings.Default.SendQueuesNames != null && AimSettings.Default.SendQueuesNames.ContainsKey(uri.AbsoluteUri))
{
Debug.Assert(!string.IsNullOrEmpty(AimSettings.Default.SendQueuesNames[uri.AbsoluteUri]));
folderName = AimSettings.Default.SendQueuesNames[uri.AbsoluteUri];
}
else
{
if (AimSettings.Default.SendQueuesNames == null)
AimSettings.Default.SendQueuesNames = new GeneralUtilities.Collections.XmlSerializableStringDictionary();
var hashCode = uri.AbsoluteUri.GetHashCode();
folderName = hashCode.ToString("X8");
AimSettings.Default.SendQueuesNames[uri.AbsoluteUri] = folderName;
AimSettings.Default.Save();
}
}
else
{
folderName = "invalid_server";
}
var folderPath = System.IO.Path.Combine(AimSettings.Default.AnnotationQueuesFolder, folderName);
try
{
if (!System.IO.Directory.Exists(folderPath))
System.IO.Directory.CreateDirectory(folderPath);
foreach (var xmlAnnotation in xmlAnnotations)
{
var fileName = string.IsNullOrEmpty(xmlAnnotation.Key) ? System.IO.Path.GetRandomFileName() : xmlAnnotation.Key;
var xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(xmlAnnotation.Value);
xmlDoc.Save(System.IO.Path.ChangeExtension(System.IO.Path.Combine(folderPath, fileName), "xml"));
Platform.Log(LogLevel.Info, "Added annotation to the queue: {0}", fileName);
}
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to queue annotaion(s) for subsequent Data Service submission.");
}
}
}
}
| |
// 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 RoundCurrentDirectionScalarDouble()
{
var test = new SimpleBinaryOpTest__RoundCurrentDirectionScalarDouble();
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__RoundCurrentDirectionScalarDouble
{
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(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, 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<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__RoundCurrentDirectionScalarDouble testClass)
{
var result = Sse41.RoundCurrentDirectionScalar(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__RoundCurrentDirectionScalarDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse41.RoundCurrentDirectionScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(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<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__RoundCurrentDirectionScalarDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleBinaryOpTest__RoundCurrentDirectionScalarDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.RoundCurrentDirectionScalar(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_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 = Sse41.RoundCurrentDirectionScalar(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_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 = Sse41.RoundCurrentDirectionScalar(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_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(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirectionScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirectionScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirectionScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.RoundCurrentDirectionScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
{
var result = Sse41.RoundCurrentDirectionScalar(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(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<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse41.RoundCurrentDirectionScalar(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((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse41.RoundCurrentDirectionScalar(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((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse41.RoundCurrentDirectionScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__RoundCurrentDirectionScalarDouble();
var result = Sse41.RoundCurrentDirectionScalar(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__RoundCurrentDirectionScalarDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
{
var result = Sse41.RoundCurrentDirectionScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.RoundCurrentDirectionScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse41.RoundCurrentDirectionScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(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 = Sse41.RoundCurrentDirectionScalar(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 = Sse41.RoundCurrentDirectionScalar(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&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<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Round(right[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(left[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundCurrentDirectionScalar)}<Double>(Vector128<Double>, Vector128<Double>): {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;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation accounts. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for more
/// information)
/// </summary>
internal partial class AutomationAccountOperations : IServiceOperations<AutomationManagementClient>, IAutomationAccountOperations
{
/// <summary>
/// Initializes a new instance of the AutomationAccountOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal AutomationAccountOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create an automation account. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create or update automation
/// account.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the create or update account operation.
/// </returns>
public async Task<AutomationAccountCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, AutomationAccountCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
if (parameters.Name != null)
{
url = url + Uri.EscapeDataString(parameters.Name);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject automationAccountCreateOrUpdateParametersValue = new JObject();
requestDoc = automationAccountCreateOrUpdateParametersValue;
if (parameters.Properties != null)
{
JObject propertiesValue = new JObject();
automationAccountCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Sku != null)
{
JObject skuValue = new JObject();
propertiesValue["sku"] = skuValue;
if (parameters.Properties.Sku.Name != null)
{
skuValue["name"] = parameters.Properties.Sku.Name;
}
if (parameters.Properties.Sku.Family != null)
{
skuValue["family"] = parameters.Properties.Sku.Family;
}
skuValue["capacity"] = parameters.Properties.Sku.Capacity;
}
}
if (parameters.Name != null)
{
automationAccountCreateOrUpdateParametersValue["name"] = parameters.Name;
}
if (parameters.Location != null)
{
automationAccountCreateOrUpdateParametersValue["location"] = parameters.Location;
}
if (parameters.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
automationAccountCreateOrUpdateParametersValue["tags"] = tagsDictionary;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AutomationAccountCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AutomationAccountCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
AutomationAccount automationAccountInstance = new AutomationAccount();
result.AutomationAccount = automationAccountInstance;
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
AutomationAccountProperties propertiesInstance = new AutomationAccountProperties();
automationAccountInstance.Properties = propertiesInstance;
JToken skuValue2 = propertiesValue2["sku"];
if (skuValue2 != null && skuValue2.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue = skuValue2["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
JToken familyValue = skuValue2["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue2["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken lastModifiedByValue = propertiesValue2["lastModifiedBy"];
if (lastModifiedByValue != null && lastModifiedByValue.Type != JTokenType.Null)
{
string lastModifiedByInstance = ((string)lastModifiedByValue);
propertiesInstance.LastModifiedBy = lastModifiedByInstance;
}
JToken stateValue = propertiesValue2["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
JToken creationTimeValue = propertiesValue2["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue2["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
automationAccountInstance.Id = idInstance;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
automationAccountInstance.Name = nameInstance2;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
automationAccountInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
automationAccountInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
automationAccountInstance.Type = typeInstance;
}
JToken etagValue = responseDoc["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
automationAccountInstance.Etag = etagInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create an automation account. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccountName'>
/// Required. Automation account name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccountName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccountName == null)
{
throw new ArgumentNullException("automationAccountName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccountName", automationAccountName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccountName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the account by account name. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get account operation.
/// </returns>
public async Task<AutomationAccountGetResponse> GetAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AutomationAccountGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AutomationAccountGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
AutomationAccount automationAccountInstance = new AutomationAccount();
result.AutomationAccount = automationAccountInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
AutomationAccountProperties propertiesInstance = new AutomationAccountProperties();
automationAccountInstance.Properties = propertiesInstance;
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue = skuValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken lastModifiedByValue = propertiesValue["lastModifiedBy"];
if (lastModifiedByValue != null && lastModifiedByValue.Type != JTokenType.Null)
{
string lastModifiedByInstance = ((string)lastModifiedByValue);
propertiesInstance.LastModifiedBy = lastModifiedByInstance;
}
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
automationAccountInstance.Id = idInstance;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
automationAccountInstance.Name = nameInstance2;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
automationAccountInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
automationAccountInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
automationAccountInstance.Type = typeInstance;
}
JToken etagValue = responseDoc["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
automationAccountInstance.Etag = etagInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve a list of accounts. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Optional. The name of the resource group
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list account operation.
/// </returns>
public async Task<AutomationAccountListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/";
if (resourceGroupName != null)
{
url = url + "resourceGroups/" + Uri.EscapeDataString(resourceGroupName) + "/";
}
url = url + "providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AutomationAccountListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AutomationAccountListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
AutomationAccount automationAccountInstance = new AutomationAccount();
result.AutomationAccounts.Add(automationAccountInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
AutomationAccountProperties propertiesInstance = new AutomationAccountProperties();
automationAccountInstance.Properties = propertiesInstance;
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue = skuValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken lastModifiedByValue = propertiesValue["lastModifiedBy"];
if (lastModifiedByValue != null && lastModifiedByValue.Type != JTokenType.Null)
{
string lastModifiedByInstance = ((string)lastModifiedByValue);
propertiesInstance.LastModifiedBy = lastModifiedByInstance;
}
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
automationAccountInstance.Id = idInstance;
}
JToken nameValue2 = valueValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
automationAccountInstance.Name = nameInstance2;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
automationAccountInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
automationAccountInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
automationAccountInstance.Type = typeInstance;
}
JToken etagValue = valueValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
automationAccountInstance.Etag = etagInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve next list of accounts. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list account operation.
/// </returns>
public async Task<AutomationAccountListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AutomationAccountListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AutomationAccountListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
AutomationAccount automationAccountInstance = new AutomationAccount();
result.AutomationAccounts.Add(automationAccountInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
AutomationAccountProperties propertiesInstance = new AutomationAccountProperties();
automationAccountInstance.Properties = propertiesInstance;
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue = skuValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken lastModifiedByValue = propertiesValue["lastModifiedBy"];
if (lastModifiedByValue != null && lastModifiedByValue.Type != JTokenType.Null)
{
string lastModifiedByInstance = ((string)lastModifiedByValue);
propertiesInstance.LastModifiedBy = lastModifiedByInstance;
}
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
automationAccountInstance.Id = idInstance;
}
JToken nameValue2 = valueValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
automationAccountInstance.Name = nameInstance2;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
automationAccountInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
automationAccountInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
automationAccountInstance.Type = typeInstance;
}
JToken etagValue = valueValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
automationAccountInstance.Etag = etagInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create an automation account. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the patch automation account.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the create account operation.
/// </returns>
public async Task<AutomationAccountPatchResponse> PatchAsync(string resourceGroupName, AutomationAccountPatchParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
if (parameters.Name != null)
{
url = url + Uri.EscapeDataString(parameters.Name);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject automationAccountPatchParametersValue = new JObject();
requestDoc = automationAccountPatchParametersValue;
JObject propertiesValue = new JObject();
automationAccountPatchParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Sku != null)
{
JObject skuValue = new JObject();
propertiesValue["sku"] = skuValue;
if (parameters.Properties.Sku.Name != null)
{
skuValue["name"] = parameters.Properties.Sku.Name;
}
if (parameters.Properties.Sku.Family != null)
{
skuValue["family"] = parameters.Properties.Sku.Family;
}
skuValue["capacity"] = parameters.Properties.Sku.Capacity;
}
if (parameters.Name != null)
{
automationAccountPatchParametersValue["name"] = parameters.Name;
}
if (parameters.Location != null)
{
automationAccountPatchParametersValue["location"] = parameters.Location;
}
if (parameters.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
automationAccountPatchParametersValue["tags"] = tagsDictionary;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AutomationAccountPatchResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AutomationAccountPatchResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
AutomationAccount automationAccountInstance = new AutomationAccount();
result.AutomationAccount = automationAccountInstance;
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
AutomationAccountProperties propertiesInstance = new AutomationAccountProperties();
automationAccountInstance.Properties = propertiesInstance;
JToken skuValue2 = propertiesValue2["sku"];
if (skuValue2 != null && skuValue2.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue = skuValue2["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
JToken familyValue = skuValue2["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue2["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken lastModifiedByValue = propertiesValue2["lastModifiedBy"];
if (lastModifiedByValue != null && lastModifiedByValue.Type != JTokenType.Null)
{
string lastModifiedByInstance = ((string)lastModifiedByValue);
propertiesInstance.LastModifiedBy = lastModifiedByInstance;
}
JToken stateValue = propertiesValue2["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
JToken creationTimeValue = propertiesValue2["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue2["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
automationAccountInstance.Id = idInstance;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
automationAccountInstance.Name = nameInstance2;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
automationAccountInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
automationAccountInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
automationAccountInstance.Type = typeInstance;
}
JToken etagValue = responseDoc["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
automationAccountInstance.Etag = etagInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
//
// In order to convert some functionality to Visual C#, the Java Language Conversion Assistant
// creates "support classes" that duplicate the original functionality.
//
// Support classes replicate the functionality of the original code, but in some cases they are
// substantially different architecturally. Although every effort is made to preserve the
// original architecture of the application in the converted project, the user should be aware that
// the primary goal of these support classes is to replicate functionality, and that at times
// the architecture of the resulting solution may differ somewhat.
//
using System;
/// <summary>
/// Contains conversion support elements such as classes, interfaces and static methods.
/// </summary>
public class SupportClass
{
/// <summary>
/// Converts an array of sbytes to an array of bytes
/// </summary>
/// <param name="sbyteArray">The array of sbytes to be converted</param>
/// <returns>The new array of bytes</returns>
public static byte[] ToByteArray(sbyte[] sbyteArray)
{
byte[] byteArray = null;
if (sbyteArray != null)
{
byteArray = new byte[sbyteArray.Length];
for(int index=0; index < sbyteArray.Length; index++)
byteArray[index] = (byte) sbyteArray[index];
}
return byteArray;
}
/// <summary>
/// Converts a string to an array of bytes
/// </summary>
/// <param name="sourceString">The string to be converted</param>
/// <returns>The new array of bytes</returns>
public static byte[] ToByteArray(System.String sourceString)
{
return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString);
}
/// <summary>
/// Converts a array of object-type instances to a byte-type array.
/// </summary>
/// <param name="tempObjectArray">Array to convert.</param>
/// <returns>An array of byte type elements.</returns>
public static byte[] ToByteArray(System.Object[] tempObjectArray)
{
byte[] byteArray = null;
if (tempObjectArray != null)
{
byteArray = new byte[tempObjectArray.Length];
for (int index = 0; index < tempObjectArray.Length; index++)
byteArray[index] = (byte)tempObjectArray[index];
}
return byteArray;
}
/*******************************/
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static int URShift(int number, int bits)
{
if ( number >= 0)
return number >> bits;
else
return (number >> bits) + (2 << ~bits);
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static int URShift(int number, long bits)
{
return URShift(number, (int)bits);
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static long URShift(long number, int bits)
{
if ( number >= 0)
return number >> bits;
else
return (number >> bits) + (2L << ~bits);
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static long URShift(long number, long bits)
{
return URShift(number, (int)bits);
}
/*******************************/
/// <summary>
/// This method returns the literal value received
/// </summary>
/// <param name="literal">The literal to return</param>
/// <returns>The received value</returns>
public static long Identity(long literal)
{
return literal;
}
/// <summary>
/// This method returns the literal value received
/// </summary>
/// <param name="literal">The literal to return</param>
/// <returns>The received value</returns>
public static ulong Identity(ulong literal)
{
return literal;
}
/// <summary>
/// This method returns the literal value received
/// </summary>
/// <param name="literal">The literal to return</param>
/// <returns>The received value</returns>
public static float Identity(float literal)
{
return literal;
}
/// <summary>
/// This method returns the literal value received
/// </summary>
/// <param name="literal">The literal to return</param>
/// <returns>The received value</returns>
public static double Identity(double literal)
{
return literal;
}
/*******************************/
/// <summary>
/// Copies an array of chars obtained from a String into a specified array of chars
/// </summary>
/// <param name="sourceString">The String to get the chars from</param>
/// <param name="sourceStart">Position of the String to start getting the chars</param>
/// <param name="sourceEnd">Position of the String to end getting the chars</param>
/// <param name="destinationArray">Array to return the chars</param>
/// <param name="destinationStart">Position of the destination array of chars to start storing the chars</param>
/// <returns>An array of chars</returns>
public static void GetCharsFromString(System.String sourceString, int sourceStart, int sourceEnd, char[] destinationArray, int destinationStart)
{
int sourceCounter;
int destinationCounter;
sourceCounter = sourceStart;
destinationCounter = destinationStart;
while (sourceCounter < sourceEnd)
{
destinationArray[destinationCounter] = (char) sourceString[sourceCounter];
sourceCounter++;
destinationCounter++;
}
}
/*******************************/
/// <summary>
/// Sets the capacity for the specified ArrayList
/// </summary>
/// <param name="vector">The ArrayList which capacity will be set</param>
/// <param name="newCapacity">The new capacity value</param>
public static void SetCapacity(System.Collections.ArrayList vector, int newCapacity)
{
if (newCapacity > vector.Count)
vector.AddRange(new Array[newCapacity-vector.Count]);
else if (newCapacity < vector.Count)
vector.RemoveRange(newCapacity, vector.Count - newCapacity);
vector.Capacity = newCapacity;
}
/*******************************/
/// <summary>
/// Receives a byte array and returns it transformed in an sbyte array
/// </summary>
/// <param name="byteArray">Byte array to process</param>
/// <returns>The transformed array</returns>
public static sbyte[] ToSByteArray(byte[] byteArray)
{
sbyte[] sbyteArray = null;
if (byteArray != null)
{
sbyteArray = new sbyte[byteArray.Length];
for(int index=0; index < byteArray.Length; index++)
sbyteArray[index] = (sbyte) byteArray[index];
}
return sbyteArray;
}
}
| |
using UnityEngine;
using System.Collections;
namespace Xft
{
public class GlowEvent : CameraEffectEvent
{
#region member
protected Color m_glowTint = new Color(1, 1, 1, 1);
#endregion
#region property
// --------------------------------------------------------
// The final composition shader:
// adds (glow color * glow alpha * amount) to the original image.
// In the combiner glow amount can be only in 0..1 range; we apply extra
// amount during the blurring phase.
public Shader compositeShader;
Material m_CompositeMaterial = null;
protected Material compositeMaterial
{
get
{
if (m_CompositeMaterial == null)
{
m_CompositeMaterial = new Material(compositeShader);
m_CompositeMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return m_CompositeMaterial;
}
}
// --------------------------------------------------------
// The blur iteration shader.
// Basically it just takes 4 texture samples and averages them.
// By applying it repeatedly and spreading out sample locations
// we get a Gaussian blur approximation.
// The alpha value in _Color would normally be 0.25 (to average 4 samples),
// however if we have glow amount larger than 1 then we increase this.
public Shader blurShader;
Material m_BlurMaterial = null;
protected Material blurMaterial
{
get
{
if (m_BlurMaterial == null)
{
m_BlurMaterial = new Material(blurShader);
m_BlurMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return m_BlurMaterial;
}
}
// --------------------------------------------------------
// The image downsample shaders for each brightness mode.
// It is in external assets as it's quite complex and uses Cg.
public Shader downsampleShader;
Material m_DownsampleMaterial = null;
protected Material downsampleMaterial
{
get
{
if (m_DownsampleMaterial == null)
{
m_DownsampleMaterial = new Material(downsampleShader);
m_DownsampleMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return m_DownsampleMaterial;
}
}
#endregion
public GlowEvent(XftEventComponent owner)
: base(CameraEffectEvent.EType.Glow, owner)
{
downsampleShader = owner.GlowDownSampleShader;
compositeShader = owner.GlowCompositeShader;
blurShader = owner.GlowBlurShader;
}
#region helper functions
// Performs one blur iteration.
void FourTapCone(RenderTexture source, RenderTexture dest, int iteration, float spread)
{
float off = 0.5f + iteration * spread;
Graphics.BlitMultiTap(source, dest, blurMaterial,
new Vector2(off, off),
new Vector2(-off, off),
new Vector2(off, -off),
new Vector2(-off, -off)
);
}
// Downsamples the texture to a quarter resolution.
void DownSample4x(RenderTexture source, RenderTexture dest)
{
downsampleMaterial.color = new Color(m_glowTint.r, m_glowTint.g, m_glowTint.b, m_glowTint.a / 4.0f);
Graphics.Blit(source, dest, downsampleMaterial);
}
void BlitGlow(RenderTexture source, RenderTexture dest, float intensity)
{
compositeMaterial.color = new Color(1F, 1F, 1F, Mathf.Clamp01(intensity));
Graphics.Blit(source, dest, compositeMaterial);
}
#endregion
#region override functions
public override bool CheckSupport()
{
bool ret = true;
if (!SystemInfo.supportsImageEffects)
{
ret = false;
}
// Disable the effect if no downsample shader is setup
if (downsampleShader == null)
{
Debug.Log("No downsample shader assigned! Disabling glow.");
ret = false;
}
// Disable if any of the shaders can't run on the users graphics card
else
{
if (!blurMaterial.shader.isSupported)
ret = false;
if (!compositeMaterial.shader.isSupported)
ret = false;
if (!downsampleMaterial.shader.isSupported)
ret = false;
}
return ret;
}
public override void OnRenderImage(RenderTexture source, RenderTexture destination)
{
int blurIterations = m_owner.GlowBlurIterations;
float blurSpread = m_owner.GlowBlurSpread;
float glowIntensity = m_owner.GlowIntensity;
// Clamp parameters to sane values
glowIntensity = Mathf.Clamp(glowIntensity, 0.0f, 10.0f);
blurIterations = Mathf.Clamp(blurIterations, 0, 30);
blurSpread = Mathf.Clamp(blurSpread, 0.5f, 1.0f);
RenderTexture buffer = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0);
RenderTexture buffer2 = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0);
// Copy source to the 4x4 smaller texture.
DownSample4x(source, buffer);
// Blur the small texture
float extraBlurBoost = Mathf.Clamp01((glowIntensity - 1.0f) / 4.0f);
blurMaterial.color = new Color(1F, 1F, 1F, 0.25f + extraBlurBoost);
bool oddEven = true;
for (int i = 0; i < blurIterations; i++)
{
if (oddEven)
{
FourTapCone(buffer, buffer2, i, blurSpread);
buffer.DiscardContents();
}
else
{
FourTapCone(buffer2, buffer, i, blurSpread);
buffer2.DiscardContents();
}
oddEven = !oddEven;
}
Graphics.Blit(source, destination);
if (oddEven)
BlitGlow(buffer, destination, glowIntensity);
else
BlitGlow(buffer2, destination, glowIntensity);
RenderTexture.ReleaseTemporary(buffer);
RenderTexture.ReleaseTemporary(buffer2);
}
public override void Update(float deltaTime)
{
m_elapsedTime += deltaTime;
float t = m_owner.ColorCurve.Evaluate(m_elapsedTime);
m_glowTint = Color.Lerp(m_owner.GlowColorStart, m_owner.GlowColorEnd, t);
}
#endregion
}
}
| |
// ZlibStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-July-31 14:53:33>
//
// ------------------------------------------------------------------
//
// This module defines the ZlibStream class, which is similar in idea to
// the System.IO.Compression.DeflateStream and
// System.IO.Compression.GZipStream classes in the .NET BCL.
//
// ------------------------------------------------------------------
using System;
using System.IO;
namespace Dune.Compression.Zlib
{
/// <summary>
/// Represents a Zlib stream for compression or decompression.
/// </summary>
/// <remarks>
///
/// <para>
/// The ZlibStream is a <see
/// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see
/// cref="System.IO.Stream"/>. It adds ZLIB compression or decompression to any
/// stream.
/// </para>
///
/// <para> Using this stream, applications can compress or decompress data via
/// stream <c>Read()</c> and <c>Write()</c> operations. Either compresssion or
/// decompression can occur through either reading or writing. The compression
/// format used is ZLIB, which is documented in <see
/// href="http://www.ietf.org/rfc/rfc1950.txt">IETF RFC 1950</see>, "ZLIB Compressed
/// Data Format Specification version 3.3". This implementation of ZLIB always uses
/// DEFLATE as the compression method. (see <see
/// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE
/// Compressed Data Format Specification version 1.3.") </para>
///
/// <para>
/// The ZLIB format allows for varying compression methods, window sizes, and dictionaries.
/// This implementation always uses the DEFLATE compression method, a preset dictionary,
/// and 15 window bits by default.
/// </para>
///
/// <para>
/// This class is similar to <see cref="DeflateStream"/>, except that it adds the
/// RFC1950 header and trailer bytes to a compressed stream when compressing, or expects
/// the RFC1950 header and trailer bytes when decompressing. It is also similar to the
/// <see cref="GZipStream"/>.
/// </para>
/// </remarks>
/// <seealso cref="DeflateStream" />
/// <seealso cref="GZipStream" />
public class ZlibStream : System.IO.Stream
{
internal ZlibBaseStream _baseStream;
bool _disposed;
/// <summary>
/// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>.
/// </summary>
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c>
/// will use the default compression level. The "captive" stream will be
/// closed when the <c>ZlibStream</c> is closed.
/// </para>
///
/// </remarks>
///
/// <example>
/// This example uses a <c>ZlibStream</c> to compress a file, and writes the
/// compressed data to another file.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
/// {
/// using (Stream compressor = new ZlibStream(raw, CompressionMode.Compress))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".zlib")
/// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
///
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param>
public ZlibStream(System.IO.Stream stream, CompressionMode mode)
: this(stream, mode, CompressionLevel.Default, false)
{
}
/// <summary>
/// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c> and
/// the specified <c>CompressionLevel</c>.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored.
/// The "captive" stream will be closed when the <c>ZlibStream</c> is closed.
/// </para>
///
/// </remarks>
///
/// <example>
/// This example uses a <c>ZlibStream</c> to compress data from a file, and writes the
/// compressed data to another file.
///
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
/// {
/// using (Stream compressor = new ZlibStream(raw,
/// CompressionMode.Compress,
/// CompressionLevel.BestCompression))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".zlib")
/// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
///
/// <param name="stream">The stream to be read or written while deflating or inflating.</param>
/// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level)
: this(stream, mode, level, false)
{
}
/// <summary>
/// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>, and
/// explicitly specify whether the captive stream should be left open after
/// Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> will use
/// the default compression level.
/// </para>
///
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// <see cref="System.IO.MemoryStream"/> that will be re-read after
/// compression. Specify true for the <paramref name="leaveOpen"/> parameter to leave the stream
/// open.
/// </para>
///
/// <para>
/// See the other overloads of this constructor for example code.
/// </para>
///
/// </remarks>
///
/// <param name="stream">The stream which will be read or written. This is called the
/// "captive" stream in other places in this documentation.</param>
/// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param>
/// <param name="leaveOpen">true if the application would like the stream to remain
/// open after inflation/deflation.</param>
public ZlibStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen)
: this(stream, mode, CompressionLevel.Default, leaveOpen)
{
}
/// <summary>
/// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>
/// and the specified <c>CompressionLevel</c>, and explicitly specify
/// whether the stream should be left open after Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// This constructor allows the application to request that the captive
/// stream remain open after the deflation or inflation occurs. By
/// default, after <c>Close()</c> is called on the stream, the captive
/// stream is also closed. In some cases this is not desired, for example
/// if the stream is a <see cref="System.IO.MemoryStream"/> that will be
/// re-read after compression. Specify true for the <paramref
/// name="leaveOpen"/> parameter to leave the stream open.
/// </para>
///
/// <para>
/// When mode is <c>CompressionMode.Decompress</c>, the level parameter is
/// ignored.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example shows how to use a ZlibStream to compress the data from a file,
/// and store the result into another file. The filestream remains open to allow
/// additional data to be written to it.
///
/// <code>
/// using (var output = System.IO.File.Create(fileToCompress + ".zlib"))
/// {
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (Stream compressor = new ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// // can write additional data to the output stream here
/// }
/// </code>
/// <code lang="VB">
/// Using output As FileStream = File.Create(fileToCompress & ".zlib")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using compressor As Stream = New ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// ' can write additional data to the output stream here.
/// End Using
/// </code>
/// </example>
///
/// <param name="stream">The stream which will be read or written.</param>
///
/// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param>
///
/// <param name="leaveOpen">
/// true if the application would like the stream to remain open after
/// inflation/deflation.
/// </param>
///
/// <param name="level">
/// A tuning knob to trade speed for effectiveness. This parameter is
/// effective only when mode is <c>CompressionMode.Compress</c>.
/// </param>
public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen)
{
_baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.ZLIB, leaveOpen);
}
#region Zlib properties
/// <summary>
/// This property sets the flush behavior on the stream.
/// Sorry, though, not sure exactly how to describe all the various settings.
/// </summary>
virtual public FlushType FlushMode
{
get { return (this._baseStream._flushMode); }
set
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
this._baseStream._flushMode = value;
}
}
/// <summary>
/// The size of the working buffer for the compression codec.
/// </summary>
///
/// <remarks>
/// <para>
/// The working buffer is used for all stream operations. The default size is
/// 1024 bytes. The minimum size is 128 bytes. You may get better performance
/// with a larger buffer. Then again, you might not. You would have to test
/// it.
/// </para>
///
/// <para>
/// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the
/// stream. If you try to set it afterwards, it will throw.
/// </para>
/// </remarks>
public int BufferSize
{
get
{
return this._baseStream._bufferSize;
}
set
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
if (this._baseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < ZlibConstants.WorkingBufferSizeMin)
throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin));
this._baseStream._bufferSize = value;
}
}
/// <summary> Returns the total number of bytes input so far.</summary>
virtual public long TotalIn
{
get { return this._baseStream._z.TotalBytesIn; }
}
/// <summary> Returns the total number of bytes output so far.</summary>
virtual public long TotalOut
{
get { return this._baseStream._z.TotalBytesOut; }
}
#endregion
#region System.IO.Stream methods
/// <summary>
/// Dispose the stream.
/// </summary>
/// <remarks>
/// <para>
/// This may or may not result in a <c>Close()</c> call on the captive
/// stream. See the constructors that have a <c>leaveOpen</c> parameter
/// for more information.
/// </para>
/// <para>
/// This method may be invoked in two distinct scenarios. If disposing
/// == true, the method has been called directly or indirectly by a
/// user's code, for example via the public Dispose() method. In this
/// case, both managed and unmanaged resources can be referenced and
/// disposed. If disposing == false, the method has been called by the
/// runtime from inside the object finalizer and this method should not
/// reference other objects; in that case only unmanaged resources must
/// be referenced or disposed.
/// </para>
/// </remarks>
/// <param name="disposing">
/// indicates whether the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing && (this._baseStream != null))
this._baseStream.Close();
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
return _baseStream._stream.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
return _baseStream._stream.CanWrite;
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
_baseStream.Flush();
}
/// <summary>
/// Reading this property always throws a <see cref="NotSupportedException"/>.
/// </summary>
public override long Length
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotSupportedException"/>. Reading will return the total bytes
/// written out, if used in writing, or the total bytes read in, if used in
/// reading. The count may refer to compressed bytes or uncompressed bytes,
/// depending on how you've used the stream.
/// </remarks>
public override long Position
{
get
{
if (this._baseStream._streamMode == ZlibBaseStream.StreamMode.Writer)
return this._baseStream._z.TotalBytesOut;
if (this._baseStream._streamMode == ZlibBaseStream.StreamMode.Reader)
return this._baseStream._z.TotalBytesIn;
return 0;
}
set { throw new NotSupportedException(); }
}
/// <summary>
/// Read data from the stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// If you wish to use the <c>ZlibStream</c> to compress data while reading,
/// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>,
/// providing an uncompressed data stream. Then call <c>Read()</c> on that
/// <c>ZlibStream</c>, and the data read will be compressed. If you wish to
/// use the <c>ZlibStream</c> to decompress data while reading, you can create
/// a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, providing a
/// readable compressed data stream. Then call <c>Read()</c> on that
/// <c>ZlibStream</c>, and the data will be decompressed as it is read.
/// </para>
///
/// <para>
/// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but
/// not both.
/// </para>
///
/// </remarks>
///
/// <param name="buffer">
/// The buffer into which the read data should be placed.</param>
///
/// <param name="offset">
/// the offset within that data array to put the first byte read.</param>
///
/// <param name="count">the number of bytes to read.</param>
///
/// <returns>the number of bytes read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
return _baseStream.Read(buffer, offset, count);
}
/// <summary>
/// Calling this method always throws a <see cref="NotSupportedException"/>.
/// </summary>
/// <param name="offset">
/// The offset to seek to....
/// IF THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
/// <param name="origin">
/// The reference specifying how to apply the offset.... IF
/// THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
///
/// <returns>nothing. This method always throws.</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotSupportedException"/>.
/// </summary>
/// <param name="value">
/// The new value for the stream length.... IF
/// THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Write data to the stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// If you wish to use the <c>ZlibStream</c> to compress data while writing,
/// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>,
/// and a writable output stream. Then call <c>Write()</c> on that
/// <c>ZlibStream</c>, providing uncompressed data as input. The data sent to
/// the output stream will be the compressed form of the data written. If you
/// wish to use the <c>ZlibStream</c> to decompress data while writing, you
/// can create a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, and a
/// writable output stream. Then call <c>Write()</c> on that stream,
/// providing previously compressed data. The data sent to the output stream
/// will be the decompressed form of the data written.
/// </para>
///
/// <para>
/// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both.
/// </para>
/// </remarks>
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("ZlibStream");
_baseStream.Write(buffer, offset, count);
}
#endregion
/// <summary>
/// Compress a string into a byte array using ZLIB.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="ZlibStream.UncompressString(byte[])"/>.
/// </remarks>
///
/// <seealso cref="ZlibStream.UncompressString(byte[])"/>
/// <seealso cref="ZlibStream.CompressBuffer(byte[])"/>
/// <seealso cref="GZipStream.CompressString(string)"/>
///
/// <param name="s">
/// A string to compress. The string will first be encoded
/// using UTF8, then compressed.
/// </param>
///
/// <returns>The string in compressed form</returns>
public static byte[] CompressString(String s)
{
using (var ms = new MemoryStream())
{
Stream compressor =
new ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);
ZlibBaseStream.CompressString(s, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Compress a byte array into a new byte array using ZLIB.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="ZlibStream.UncompressBuffer(byte[])"/>.
/// </remarks>
///
/// <seealso cref="ZlibStream.CompressString(string)"/>
/// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/>
///
/// <param name="b">
/// A buffer to compress.
/// </param>
///
/// <returns>The data in compressed form</returns>
public static byte[] CompressBuffer(byte[] b)
{
using (var ms = new MemoryStream())
{
Stream compressor =
new ZlibStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression );
ZlibBaseStream.CompressBuffer(b, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Uncompress a ZLIB-compressed byte array into a single string.
/// </summary>
///
/// <seealso cref="ZlibStream.CompressString(String)"/>
/// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/>
///
/// <param name="compressed">
/// A buffer containing ZLIB-compressed data.
/// </param>
///
/// <returns>The uncompressed string</returns>
public static String UncompressString(byte[] compressed)
{
using (var input = new MemoryStream(compressed))
{
Stream decompressor =
new ZlibStream(input, CompressionMode.Decompress);
return ZlibBaseStream.UncompressString(compressed, decompressor);
}
}
/// <summary>
/// Uncompress a ZLIB-compressed byte array into a byte array.
/// </summary>
///
/// <seealso cref="ZlibStream.CompressBuffer(byte[])"/>
/// <seealso cref="ZlibStream.UncompressString(byte[])"/>
///
/// <param name="compressed">
/// A buffer containing ZLIB-compressed data.
/// </param>
///
/// <returns>The data in uncompressed form</returns>
public static byte[] UncompressBuffer(byte[] compressed)
{
using (var input = new MemoryStream(compressed))
{
Stream decompressor =
new ZlibStream( input, CompressionMode.Decompress );
return ZlibBaseStream.UncompressBuffer(compressed, decompressor);
}
}
}
}
| |
using System;
using System.Net.Sockets;
using System.Threading;
using Microsoft.Extensions.Logging;
using Orleans.Runtime;
namespace Orleans.Messaging
{
/// <summary>
/// The GatewayConnection class does double duty as both the manager of the connection itself (the socket) and the sender of messages
/// to the gateway. It uses a single instance of the Receiver class to handle messages from the gateway.
///
/// Note that both sends and receives are synchronous.
/// </summary>
internal class GatewayConnection : OutgoingMessageSender
{
private int connectedCount;
private readonly MessageFactory messageFactory;
internal bool IsLive { get; private set; }
internal ClientMessageCenter MsgCenter { get; private set; }
private Uri addr;
internal Uri Address
{
get { return addr; }
private set
{
addr = value;
Silo = addr.ToSiloAddress();
}
}
internal SiloAddress Silo { get; private set; }
private readonly GatewayClientReceiver receiver;
private readonly TimeSpan openConnectionTimeout;
internal Socket Socket { get; private set; } // Shared by the receiver
private DateTime lastConnect;
internal GatewayConnection(Uri address, ClientMessageCenter mc, MessageFactory messageFactory, ExecutorService executorService, ILoggerFactory loggerFactory, TimeSpan openConnectionTimeout)
: base("GatewayClientSender_" + address, mc.SerializationManager, executorService, loggerFactory)
{
this.messageFactory = messageFactory;
this.openConnectionTimeout = openConnectionTimeout;
Address = address;
MsgCenter = mc;
receiver = new GatewayClientReceiver(this, mc.SerializationManager, executorService, loggerFactory);
lastConnect = new DateTime();
IsLive = true;
}
public override void Start()
{
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug(ErrorCode.ProxyClient_GatewayConnStarted, "Starting gateway connection for gateway {0}", Address);
lock (Lockable)
{
if (State == ThreadState.Running)
{
return;
}
Connect();
if (!IsLive) return;
// If the Connect succeeded
receiver.Start();
base.Start();
}
}
public override void Stop()
{
IsLive = false;
receiver.Stop();
base.Stop();
Socket s;
lock (Lockable)
{
s = Socket;
Socket = null;
}
if (s == null) return;
CloseSocket(s);
}
// passed the exact same socket on which it got SocketException. This way we prevent races between connect and disconnect.
public void MarkAsDisconnected(Socket socket2Disconnect)
{
Socket s = null;
lock (Lockable)
{
if (socket2Disconnect == null || Socket == null) return;
if (Socket == socket2Disconnect) // handles races between connect and disconnect, since sometimes we grab the socket outside lock.
{
s = Socket;
Socket = null;
Log.Warn(ErrorCode.ProxyClient_MarkGatewayDisconnected, $"Marking gateway at address {Address} as Disconnected");
if ( MsgCenter != null && MsgCenter.GatewayManager != null)
// We need a refresh...
MsgCenter.GatewayManager.ExpediteUpdateLiveGatewaysSnapshot();
}
}
if (s != null)
{
CloseSocket(s);
}
if (socket2Disconnect == s) return;
CloseSocket(socket2Disconnect);
}
public void MarkAsDead()
{
Log.Warn(ErrorCode.ProxyClient_MarkGatewayDead, $"Marking gateway at address {Address} as Dead in my client local gateway list.");
MsgCenter.GatewayManager.MarkAsDead(Address);
Stop();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void Connect()
{
if (!MsgCenter.Running)
{
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug(ErrorCode.ProxyClient_MsgCtrNotRunning, "Ignoring connection attempt to gateway {0} because the proxy message center is not running", Address);
return;
}
// Yes, we take the lock around a Sleep. The point is to ensure that no more than one thread can try this at a time.
// There's still a minor problem as written -- if the sending thread and receiving thread both get here, the first one
// will try to reconnect. eventually do so, and then the other will try to reconnect even though it doesn't have to...
// Hopefully the initial "if" statement will prevent that.
lock (Lockable)
{
if (!IsLive)
{
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug(ErrorCode.ProxyClient_DeadGateway, "Ignoring connection attempt to gateway {0} because this gateway connection is already marked as non live", Address);
return; // if the connection is already marked as dead, don't try to reconnect. It has been doomed.
}
for (var i = 0; i < ClientMessageCenter.CONNECT_RETRY_COUNT; i++)
{
try
{
if (Socket != null)
{
if (Socket.Connected)
return;
MarkAsDisconnected(Socket); // clean up the socket before reconnecting.
}
if (lastConnect != new DateTime())
{
// We already tried at least once in the past to connect to this GW.
// If we are no longer connected to this GW and it is no longer in the list returned
// from the GatewayProvider, consider directly this connection dead.
if (!MsgCenter.GatewayManager.GetLiveGateways().Contains(Address))
break;
// Wait at least ClientMessageCenter.MINIMUM_INTERCONNECT_DELAY before reconnection tries
var millisecondsSinceLastAttempt = DateTime.UtcNow - lastConnect;
if (millisecondsSinceLastAttempt < ClientMessageCenter.MINIMUM_INTERCONNECT_DELAY)
{
var wait = ClientMessageCenter.MINIMUM_INTERCONNECT_DELAY - millisecondsSinceLastAttempt;
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug(ErrorCode.ProxyClient_PauseBeforeRetry, "Pausing for {0} before trying to connect to gateway {1} on trial {2}", wait, Address, i);
Thread.Sleep(wait);
}
}
lastConnect = DateTime.UtcNow;
Socket = new Socket(Silo.Endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Socket.EnableFastpath();
SocketManager.Connect(Socket, Silo.Endpoint, this.openConnectionTimeout);
NetworkingStatisticsGroup.OnOpenedGatewayDuplexSocket();
Interlocked.Increment(ref this.connectedCount);
MsgCenter.OnGatewayConnectionOpen();
SocketManager.WriteConnectionPreamble(Socket, MsgCenter.ClientId); // Identifies this client
Log.Info(ErrorCode.ProxyClient_Connected, "Connected to gateway at address {0} on trial {1}.", Address, i);
return;
}
catch (Exception ex)
{
Log.Warn(ErrorCode.ProxyClient_CannotConnect, $"Unable to connect to gateway at address {Address} on trial {i} (Exception: {ex.Message})");
MarkAsDisconnected(Socket);
}
}
// Failed too many times -- give up
MarkAsDead();
}
}
protected override SocketDirection GetSocketDirection() { return SocketDirection.ClientToGateway; }
protected override bool PrepareMessageForSend(Message msg)
{
if (Cts == null)
{
return false;
}
// Check to make sure we're not stopped
if (Cts.IsCancellationRequested)
{
// Recycle the message we've dequeued. Note that this will recycle messages that were queued up to be sent when the gateway connection is declared dead
RerouteMessage(msg);
return false;
}
if (msg.TargetSilo != null) return true;
msg.TargetSilo = Silo;
if (msg.TargetGrain.IsSystemTarget)
msg.TargetActivation = ActivationId.GetSystemActivation(msg.TargetGrain, msg.TargetSilo);
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override bool GetSendingSocket(Message msg, out Socket socketCapture, out SiloAddress targetSilo, out string error)
{
error = null;
targetSilo = Silo;
socketCapture = null;
try
{
if (Socket == null || !Socket.Connected)
{
Connect();
}
socketCapture = Socket;
if (socketCapture == null || !socketCapture.Connected)
{
// Failed to connect -- Connect will have already declared this connection dead, so recycle the message
return false;
}
}
catch (Exception)
{
//No need to log any errors, as we alraedy do it inside Connect().
return false;
}
return true;
}
protected override void OnGetSendingSocketFailure(Message msg, string error)
{
msg.TargetSilo = null; // clear previous destination!
MsgCenter.SendMessage(msg);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override void OnMessageSerializationFailure(Message msg, Exception exc)
{
// we only get here if we failed to serialize the msg (or any other catastrophic failure).
// Request msg fails to serialize on the sender, so we just enqueue a rejection msg.
// Response msg fails to serialize on the responding silo, so we try to send an error response back.
this.Log.LogWarning(
(int) ErrorCode.ProxyClient_SerializationError,
"Unexpected error serializing message {Message}: {Exception}",
msg,
exc);
msg.ReleaseBodyAndHeaderBuffers();
MessagingStatisticsGroup.OnFailedSentMessage(msg);
var retryCount = msg.RetryCount ?? 0;
if (msg.Direction == Message.Directions.Request)
{
this.MsgCenter.RejectMessage(msg, $"Unable to serialize message. Encountered exception: {exc?.GetType()}: {exc?.Message}", exc);
}
else if (msg.Direction == Message.Directions.Response && retryCount < 1)
{
// if we failed sending an original response, turn the response body into an error and reply with it.
// unless we have already tried sending the response multiple times.
msg.Result = Message.ResponseTypes.Error;
msg.BodyObject = Response.ExceptionResponse(exc);
msg.RetryCount = retryCount + 1;
this.MsgCenter.SendMessage(msg);
}
else
{
this.Log.LogWarning(
(int)ErrorCode.ProxyClient_DroppingMsg,
"Gateway client is dropping message which failed during serialization: {Message}. Exception = {Exception}",
msg,
exc);
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
}
protected override void OnSendFailure(Socket socket, SiloAddress targetSilo)
{
MarkAsDisconnected(socket);
}
protected override void ProcessMessageAfterSend(Message msg, bool sendError, string sendErrorStr)
{
msg.ReleaseBodyAndHeaderBuffers();
if (sendError)
{
// We can't recycle the current message, because that might wind up with it getting delivered out of order, so we have to reject it
FailMessage(msg, sendErrorStr);
}
}
protected override void FailMessage(Message msg, string reason)
{
msg.ReleaseBodyAndHeaderBuffers();
MessagingStatisticsGroup.OnFailedSentMessage(msg);
if (MsgCenter.Running && msg.Direction == Message.Directions.Request)
{
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason);
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message error = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, reason);
MsgCenter.QueueIncomingMessage(error);
}
else
{
Log.Warn(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason);
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
}
protected override bool DrainAfterCancel => true;
private void RerouteMessage(Message msg)
{
msg.TargetActivation = null;
msg.TargetSilo = null;
MsgCenter.SendMessage(msg);
}
private void CloseSocket(Socket socket)
{
SocketManager.CloseSocket(socket);
NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket();
if (Interlocked.Decrement(ref this.connectedCount) == 0) MsgCenter.OnGatewayConnectionClosed();
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.RemoveUnusedUsings;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.RemoveUnnecessaryImports;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.RemoveUnnecessaryUsings
{
public partial class RemoveUnnecessaryUsingsTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
new CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer(), new RemoveUnnecessaryUsingsCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestNoReferences()
{
await TestAsync(
@"[|using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { } } |]",
@"class Program { static void Main ( string [ ] args ) { } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestIdentifierReferenceInTypeContext()
{
await TestAsync(
@"[|using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } |]",
@"using System ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestGenericReferenceInTypeContext()
{
await TestAsync(
@"[|using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { List < int > list ; } } |]",
@"using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { List < int > list ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestMultipleReferences()
{
await TestAsync(
@"[|using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { List < int > list ; DateTime d ; } } |]",
@"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { List < int > list ; DateTime d ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestExtensionMethodReference()
{
await TestAsync(
@"[|using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { args . Where ( a => a . Length > 10 ) ; } } |]",
@"using System . Linq ; class Program { static void Main ( string [ ] args ) { args . Where ( a => a . Length > 10 ) ; } } ");
}
[WorkItem(541827)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestExtensionMethodLinq()
{
// NOTE: Intentionally not running this test with Script options, because in Script,
// NOTE: class "Foo" is placed inside the script class, and can't be seen by the extension
// NOTE: method Select, which is not inside the script class.
await TestMissingAsync(
@"[|using System;
using System.Collections;
using SomeNS;
class Program
{
static void Main()
{
Foo qq = new Foo();
IEnumerable x = from q in qq select q;
}
}
public class Foo
{
public Foo()
{
}
}
namespace SomeNS
{
public static class SomeClass
{
public static IEnumerable Select(this Foo o, Func<object, object> f)
{
return null;
}
}
}|]");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestAliasQualifiedAliasReference()
{
await TestAsync(
@"[|using System ; using G = System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { G :: List < int > list ; } } |]",
@"using G = System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { G :: List < int > list ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestQualifiedAliasReference()
{
await TestAsync(
@"[|using System ; using G = System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { G . List < int > list ; } } |]",
@"using G = System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { G . List < int > list ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestNestedUnusedUsings()
{
await TestAsync(
@"[|using System ; using System . Collections . Generic ; using System . Linq ; namespace N { using System ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } } |]",
@"namespace N { using System ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestNestedUsedUsings()
{
await TestAsync(
@"[|using System ; using System . Collections . Generic ; using System . Linq ; namespace N { using System ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } } class F { DateTime d ; } |]",
@"using System ; namespace N { using System ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } } class F { DateTime d ; } ");
}
[WorkItem(712656)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestNestedUsedUsings2()
{
await TestAsync(
@"using System ; using System . Collections . Generic ; using System . Linq ; namespace N { [|using System ;|] using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } } class F { DateTime d ; } ",
@"using System ; namespace N { using System ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } } class F { DateTime d ; } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestAttribute()
{
await TestMissingAsync(
@"[|using SomeNamespace ; [ SomeAttr ] class Foo { } namespace SomeNamespace { public class SomeAttrAttribute : System . Attribute { } } |]");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestAttributeArgument()
{
await TestMissingAsync(
@"[|using foo ; [ SomeAttribute ( typeof ( SomeClass ) ) ] class Program { static void Main ( ) { } } public class SomeAttribute : System . Attribute { public SomeAttribute ( object f ) { } } namespace foo { public class SomeClass { } } |]");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveAllWithSurroundingPreprocessor()
{
await TestAsync(
@"#if true
[|using System;
using System.Collections.Generic;
#endif
class Program
{
static void Main(string[] args)
{
}
}|]",
@"#if true
#endif
class Program
{
static void Main(string[] args)
{
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveFirstWithSurroundingPreprocessor()
{
await TestAsync(
@"#if true
[|using System;
using System.Collections.Generic;
#endif
class Program
{
static void Main(string[] args)
{
List<int> list;
}
}|]",
@"#if true
using System.Collections.Generic;
#endif
class Program
{
static void Main(string[] args)
{
List<int> list;
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveAllWithSurroundingPreprocessor2()
{
await TestAsync(
@"[|namespace N
{
#if true
using System;
using System.Collections.Generic;
#endif
class Program
{
static void Main(string[] args)
{
}
}
}|]",
@"namespace N
{
#if true
#endif
class Program
{
static void Main(string[] args)
{
}
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveOneWithSurroundingPreprocessor2()
{
await TestAsync(
@"[|namespace N
{
#if true
using System;
using System.Collections.Generic;
#endif
class Program
{
static void Main(string[] args)
{
List<int> list;
}
}
}|]",
@"namespace N
{
#if true
using System.Collections.Generic;
#endif
class Program
{
static void Main(string[] args)
{
List<int> list;
}
}
}",
compareTokens: false);
}
[WorkItem(541817)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestComments8718()
{
await TestAsync(
@"[|using Foo; using System.Collections.Generic; /*comment*/ using Foo2;
class Program
{
static void Main(string[] args)
{
Bar q;
Bar2 qq;
}
}
namespace Foo
{
public class Bar
{
}
}
namespace Foo2
{
public class Bar2
{
}
}|]",
@"using Foo;
using Foo2;
class Program
{
static void Main(string[] args)
{
Bar q;
Bar2 qq;
}
}
namespace Foo
{
public class Bar
{
}
}
namespace Foo2
{
public class Bar2
{
}
}",
compareTokens: false);
}
[WorkItem(528609)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestComments()
{
await TestAsync(
@"//c1
/*c2*/
[|using/*c3*/ System/*c4*/; //c5
//c6
class Program
{
}
|]",
@"//c1
/*c2*/
//c6
class Program
{
}
",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUnusedUsing()
{
await TestAsync(
@"[|using System.Collections.Generic;
class Program
{
static void Main()
{
}
}|]",
@"class Program
{
static void Main()
{
}
}",
compareTokens: false);
}
[WorkItem(541827)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestSimpleQuery()
{
await TestAsync(
@"[|using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = from a in args where a . Length > 21 select a ; } } |]",
@"using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = from a in args where a . Length > 21 select a ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUsingStaticClassAccessField1()
{
await TestAsync(
@"[|using SomeNS . Foo ; class Program { static void Main ( ) { var q = x ; } } namespace SomeNS { static class Foo { public static int x ; } } |]",
@"class Program { static void Main ( ) { var q = x ; } } namespace SomeNS { static class Foo { public static int x ; } } ",
CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUsingStaticClassAccessField2()
{
await TestMissingAsync(
@"[|using static SomeNS . Foo ; class Program { static void Main ( ) { var q = x ; } } namespace SomeNS { static class Foo { public static int x ; } } |]");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUsingStaticClassAccessMethod1()
{
await TestAsync(
@"[|using SomeNS . Foo ; class Program { static void Main ( ) { var q = X ( ) ; } } namespace SomeNS { static class Foo { public static int X ( ) { return 42 ; } } } |]",
@"[|class Program { static void Main ( ) { var q = X ( ) ; } } namespace SomeNS { static class Foo { public static int X ( ) { return 42 ; } } } |]",
CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUsingStaticClassAccessMethod2()
{
await TestMissingAsync(
@"[|using static SomeNS . Foo ; class Program { static void Main ( ) { var q = X ( ) ; } } namespace SomeNS { static class Foo { public static int X ( ) { return 42 ; } } } |]");
}
[WorkItem(8846, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUnusedTypeImportIsRemoved()
{
await TestAsync(
@"[|using SomeNS.Foo;
class Program
{
static void Main()
{
}
}
namespace SomeNS
{
static class Foo
{
}
}|]",
@"
class Program
{
static void Main()
{
}
}
namespace SomeNS
{
static class Foo
{
}
}");
}
[WorkItem(541817)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveTrailingComment()
{
await TestAsync(
@"[|using System.Collections.Generic; // comment
class Program
{
static void Main(string[] args)
{
}
}
|]",
@"class Program
{
static void Main(string[] args)
{
}
}
",
compareTokens: false);
}
[WorkItem(541914)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemovingUnbindableUsing()
{
await TestAsync(
@"[|using gibberish ; public static class Program { } |]",
@"public static class Program { } ");
}
[WorkItem(541937)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestAliasInUse()
{
await TestMissingAsync(
@"[|using GIBBERISH = Foo.Bar;
class Program
{
static void Main(string[] args)
{
GIBBERISH x;
}
}
namespace Foo
{
public class Bar
{
}
}|]");
}
[WorkItem(541914)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveUnboundUsing()
{
await TestAsync(
@"[|using gibberish; public static class Program { }|]",
@"public static class Program { }");
}
[WorkItem(542016)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestLeadingNewlines1()
{
await TestAsync(
@"[|using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
}
}|]",
@"class Program
{
static void Main(string[] args)
{
}
}",
compareTokens: false);
}
[WorkItem(542016)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveLeadingNewLines2()
{
await TestAsync(
@"[|namespace N
{
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
}
}
}|]",
@"namespace N
{
class Program
{
static void Main(string[] args)
{
}
}
}",
compareTokens: false);
}
[WorkItem(542134)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestImportedTypeUsedAsGenericTypeArgument()
{
await TestMissingAsync(
@"[|using GenericThingie;
public class GenericType<T>
{
}
namespace GenericThingie
{
public class Something
{ }
}
public class Program
{
void foo()
{
GenericType<Something> type;
}
}|]");
}
[WorkItem(542723)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveCorrectUsing1()
{
await TestAsync(
@"[|using System . Collections . Generic ; namespace Foo { using Bar = Dictionary < string , string > ; } |]",
@"using System . Collections . Generic ; namespace Foo { } ",
parseOptions: null);
}
[WorkItem(542723)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveCorrectUsing2()
{
await TestMissingAsync(
@"[|using System . Collections . Generic ; namespace Foo { using Bar = Dictionary < string , string > ; class C { Bar b; } } |]",
parseOptions: null);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestSpan()
{
await TestSpansAsync(
@"[|namespace N
{
using System;
}|]",
@"namespace N
{
[|using System;|]
}");
}
[WorkItem(543000)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestMissingWhenErrorsWouldBeGenerated()
{
await TestMissingAsync(
@"[|using System ; using X ; using Y ; class B { static void Main ( ) { Bar ( x => x . Foo ( ) ) ; } static void Bar ( Action < int > x ) { } static void Bar ( Action < string > x ) { } } namespace X { public static class A { public static void Foo ( this int x ) { } public static void Foo ( this string x ) { } } } namespace Y { public static class B { public static void Foo ( this int x ) { } } } |]");
}
[WorkItem(544976)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestMissingWhenMeaningWouldChangeInLambda()
{
await TestMissingAsync(
@"[|using System;
using X;
using Y;
class B
{
static void Main()
{
Bar(x => x.Foo(), null); // Prints 1
}
static void Bar(Action<string> x, object y) { Console.WriteLine(1); }
static void Bar(Action<int> x, string y) { Console.WriteLine(2); }
}
namespace X
{
public static class A
{
public static void Foo(this int x) { }
public static void Foo(this string x) { }
}
}
namespace Y
{
public static class B
{
public static void Foo(this int x) { }
}
}|]");
}
[WorkItem(544976)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestCasesWithLambdas1()
{
// NOTE: Y is used when speculatively binding "x => x.Foo()". As such, it is marked as
// used even though it isn't in the final bind, and could be removed. However, as we do
// not know if it was necessary to eliminate a speculative lambda bind, we must leave
// it.
await TestMissingAsync(
@"[|using System;
using X;
using Y;
class B
{
static void Main()
{
Bar(x => x.Foo(), null); // Prints 1
}
static void Bar(Action<string> x, object y) { }
}
namespace X
{
public static class A
{
public static void Foo(this string x) { }
}
}
namespace Y
{
public static class B
{
public static void Foo(this int x) { }
}
}|]");
}
[WorkItem(545646)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestCasesWithLambdas2()
{
await TestMissingAsync(
@"[|using System;
using N; // Falsely claimed as unnecessary
static class C
{
static void Ex(this string x) { }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, string y) { Console.WriteLine(2); }
static void Main()
{
Outer(y => Inner(x => x.Ex(), y), null);
}
}
namespace N
{
static class E
{
public static void Ex(this int x) { }
}
}|]");
}
[WorkItem(545741)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestMissingOnAliasedVar()
{
await TestMissingAsync(
@"[|using var = var ; class var { } class B { static void Main ( ) { var a = 1 ; } }|] ");
}
[WorkItem(546115)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestBrokenCode()
{
await TestMissingAsync(
@"[|using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var expr1 = new[] { };
var expr2 = new[] { };
var query8 = from int i in expr1 join int fixed in expr2 on i equals fixed select new { i, fixed };
var query9 = from object i in expr1 join object fixed in expr2 on i equals fixed select new { i, fixed };
}
}|]");
}
[WorkItem(530980)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestReferenceInCref()
{
// parsing doc comments as simple trivia; System is unnecessary
await TestAsync(@"[|using System ;
/// <summary><see cref=""String"" /></summary>
class C { }|] ",
@"/// <summary><see cref=""String"" /></summary>
class C { } ");
// fully parsing doc comments; System is necessary
await TestMissingAsync(
@"[|using System ;
/// <summary><see cref=""String"" /></summary>
class C { }|] ", Options.Regular.WithDocumentationMode(DocumentationMode.Diagnose));
}
[WorkItem(751283)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUnusedUsingOverLinq()
{
await TestAsync(
@"using System ; [|using System . Linq ; using System . Threading . Tasks ;|] class Program { static void Main ( string [ ] args ) { Console . WriteLine ( ) ; } } ",
@"using System ; class Program { static void Main ( string [ ] args ) { Console . WriteLine ( ) ; } } ");
}
}
}
| |
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
using Parse.Internal;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Parse {
/// <summary>
/// Represents this app installed on this device. Use this class to track information you want
/// to sample from (i.e. if you update a field on app launch, you can issue a query to see
/// the number of devices which were active in the last N hours).
/// </summary>
[ParseClassName("_Installation")]
public partial class ParseInstallation : ParseObject {
private static readonly HashSet<string> readOnlyKeys = new HashSet<string> {
"deviceType", "deviceUris", "installationId", "timeZone", "localeIdentifier", "parseVersion", "appName", "appIdentifier", "appVersion", "pushType"
};
internal static IParseCurrentInstallationController CurrentInstallationController {
get {
return ParseCorePlugins.Instance.CurrentInstallationController;
}
}
/// <summary>
/// Constructs a new ParseInstallation. Generally, you should not need to construct
/// ParseInstallations yourself. Instead use <see cref="CurrentInstallation"/>.
/// </summary>
public ParseInstallation()
: base() {
}
/// <summary>
/// Gets the ParseInstallation representing this app on this device.
/// </summary>
public static ParseInstallation CurrentInstallation {
get {
var task = CurrentInstallationController.GetAsync(CancellationToken.None);
// TODO (hallucinogen): this will absolutely break on Unity, but how should we resolve this?
task.Wait();
return task.Result;
}
}
internal static void ClearInMemoryInstallation() {
CurrentInstallationController.ClearFromMemory();
}
/// <summary>
/// Constructs a <see cref="ParseQuery{ParseInstallation}"/> for ParseInstallations.
/// </summary>
/// <remarks>
/// Only the following types of queries are allowed for installations:
///
/// <code>
/// query.GetAsync(objectId)
/// query.WhereEqualTo(key, value)
/// query.WhereMatchesKeyInQuery<TOther>(key, keyInQuery, otherQuery)
/// </code>
///
/// You can add additional query conditions, but one of the above must appear as a top-level <c>AND</c>
/// clause in the query.
/// </remarks>
public static ParseQuery<ParseInstallation> Query {
get {
return new ParseQuery<ParseInstallation>();
}
}
/// <summary>
/// A GUID that uniquely names this app installed on this device.
/// </summary>
[ParseFieldName("installationId")]
public Guid InstallationId {
get {
string installationIdString = GetProperty<string>("InstallationId");
Guid? installationId = null;
try {
installationId = new Guid(installationIdString);
} catch (Exception) {
// Do nothing.
}
return installationId.Value;
}
internal set {
Guid installationId = value;
SetProperty<string>(installationId.ToString(), "InstallationId");
}
}
/// <summary>
/// The runtime target of this installation object.
/// </summary>
[ParseFieldName("deviceType")]
public string DeviceType {
get { return GetProperty<string>("DeviceType"); }
internal set { SetProperty<string>(value, "DeviceType"); }
}
/// <summary>
/// The user-friendly display name of this application.
/// </summary>
[ParseFieldName("appName")]
public string AppName {
get { return GetProperty<string>("AppName"); }
internal set { SetProperty<string>(value, "AppName"); }
}
/// <summary>
/// A version string consisting of Major.Minor.Build.Revision.
/// </summary>
[ParseFieldName("appVersion")]
public string AppVersion {
get { return GetProperty<string>("AppVersion"); }
internal set { SetProperty<string>(value, "AppVersion"); }
}
/// <summary>
/// The system-dependent unique identifier of this installation. This identifier should be
/// sufficient to distinctly name an app on stores which may allow multiple apps with the
/// same display name.
/// </summary>
[ParseFieldName("appIdentifier")]
public string AppIdentifier {
get { return GetProperty<string>("AppIdentifier"); }
internal set { SetProperty<string>(value, "AppIdentifier"); }
}
/// <summary>
/// The time zone in which this device resides. This string is in the tz database format
/// Parse uses for local-time pushes. Due to platform restrictions, the mapping is less
/// granular on Windows than it may be on other systems. E.g. The zones
/// America/Vancouver America/Dawson America/Whitehorse, America/Tijuana, PST8PDT, and
/// America/Los_Angeles are all reported as America/Los_Angeles.
/// </summary>
[ParseFieldName("timeZone")]
public string TimeZone {
get { return GetProperty<string>("TimeZone"); }
private set { SetProperty<string>(value, "TimeZone"); }
}
/// <summary>
/// The users locale. This field gets automatically populated by the SDK.
/// Can be null (Parse Push uses default language in this case).
/// </summary>
[ParseFieldName("localeIdentifier")]
public string LocaleIdentifier {
get { return GetProperty<string>("LocaleIdentifier"); }
private set { SetProperty<string>(value, "LocaleIdentifier"); }
}
/// <summary>
/// Gets the locale identifier in the format: [language code]-[COUNTRY CODE].
/// </summary>
/// <returns>The locale identifier in the format: [language code]-[COUNTRY CODE].</returns>
private string GetLocaleIdentifier() {
String languageCode = null;
String countryCode = null;
if (CultureInfo.CurrentCulture != null) {
languageCode = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
}
if (RegionInfo.CurrentRegion != null) {
countryCode = RegionInfo.CurrentRegion.TwoLetterISORegionName;
}
if (string.IsNullOrEmpty(countryCode)) {
return languageCode;
} else {
return string.Format("{0}-{1}", languageCode, countryCode);
}
}
/// <summary>
/// The version of the Parse SDK used to build this application.
/// </summary>
[ParseFieldName("parseVersion")]
public Version ParseVersion {
get {
var versionString = GetProperty<string>("ParseVersion");
Version version = null;
try {
version = new Version(versionString);
} catch (Exception) {
// Do nothing.
}
return version;
}
private set {
Version version = value;
SetProperty<string>(version.ToString(), "ParseVersion");
}
}
private Version GetParseVersion() {
return ParseClient.Version;
}
/// <summary>
/// A sequence of arbitrary strings which are used to identify this installation for push notifications.
/// By convention, the empty string is known as the "Broadcast" channel.
/// </summary>
[ParseFieldName("channels")]
public IList<string> Channels {
get { return GetProperty<IList<string>>("Channels"); }
set { SetProperty(value, "Channels"); }
}
internal override bool IsKeyMutable(string key) {
return !readOnlyKeys.Contains(key);
}
internal override Task SaveAsync(Task toAwait, CancellationToken cancellationToken) {
Task platformHookTask = null;
if (CurrentInstallationController.IsCurrent(this)) {
SetIfDifferent("deviceType", ParseClient.PlatformHooks.DeviceType);
SetIfDifferent("timeZone", ParseClient.PlatformHooks.DeviceTimeZone);
SetIfDifferent("localeIdentifier", GetLocaleIdentifier());
SetIfDifferent("parseVersion", GetParseVersion().ToString());
SetIfDifferent("appVersion", ParseClient.PlatformHooks.AppBuildVersion);
SetIfDifferent("appIdentifier", ParseClient.PlatformHooks.AppIdentifier);
SetIfDifferent("appName", ParseClient.PlatformHooks.AppName);
// TODO (hallucinogen): this probably should have been a controller.
platformHookTask = ParseClient.PlatformHooks.ExecuteParseInstallationSaveHookAsync(this);
}
return platformHookTask.Safe().OnSuccess(_ => {
return base.SaveAsync(toAwait, cancellationToken);
}).Unwrap()
.OnSuccess(_ => {
if (CurrentInstallationController.IsCurrent(this)) {
return Task.FromResult(0);
}
return CurrentInstallationController.SetAsync(this, cancellationToken);
}).Unwrap();
}
/// <summary>
/// This mapping of Windows names to a standard everyone else uses is maintained
/// by the Unicode consortium, which makes this officially the first helpful
/// interaction between Unicode and Microsoft.
/// Unfortunately this is a little lossy in that we only store the first mapping in each zone because
/// Microsoft does not give us more granular location information.
/// Built from http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/zone_tzid.html
/// </summary>
internal static readonly Dictionary<string, string> TimeZoneNameMap = new Dictionary<string, string>() {
{"Dateline Standard Time", "Etc/GMT+12"},
{"UTC-11", "Etc/GMT+11"},
{"Hawaiian Standard Time", "Pacific/Honolulu"},
{"Alaskan Standard Time", "America/Anchorage"},
{"Pacific Standard Time (Mexico)", "America/Santa_Isabel"},
{"Pacific Standard Time", "America/Los_Angeles"},
{"US Mountain Standard Time", "America/Phoenix"},
{"Mountain Standard Time (Mexico)", "America/Chihuahua"},
{"Mountain Standard Time", "America/Denver"},
{"Central America Standard Time", "America/Guatemala"},
{"Central Standard Time", "America/Chicago"},
{"Central Standard Time (Mexico)", "America/Mexico_City"},
{"Canada Central Standard Time", "America/Regina"},
{"SA Pacific Standard Time", "America/Bogota"},
{"Eastern Standard Time", "America/New_York"},
{"US Eastern Standard Time", "America/Indianapolis"},
{"Venezuela Standard Time", "America/Caracas"},
{"Paraguay Standard Time", "America/Asuncion"},
{"Atlantic Standard Time", "America/Halifax"},
{"Central Brazilian Standard Time", "America/Cuiaba"},
{"SA Western Standard Time", "America/La_Paz"},
{"Pacific SA Standard Time", "America/Santiago"},
{"Newfoundland Standard Time", "America/St_Johns"},
{"E. South America Standard Time", "America/Sao_Paulo"},
{"Argentina Standard Time", "America/Buenos_Aires"},
{"SA Eastern Standard Time", "America/Cayenne"},
{"Greenland Standard Time", "America/Godthab"},
{"Montevideo Standard Time", "America/Montevideo"},
{"Bahia Standard Time", "America/Bahia"},
{"UTC-02", "Etc/GMT+2"},
{"Azores Standard Time", "Atlantic/Azores"},
{"Cape Verde Standard Time", "Atlantic/Cape_Verde"},
{"Morocco Standard Time", "Africa/Casablanca"},
{"UTC", "Etc/GMT"},
{"GMT Standard Time", "Europe/London"},
{"Greenwich Standard Time", "Atlantic/Reykjavik"},
{"W. Europe Standard Time", "Europe/Berlin"},
{"Central Europe Standard Time", "Europe/Budapest"},
{"Romance Standard Time", "Europe/Paris"},
{"Central European Standard Time", "Europe/Warsaw"},
{"W. Central Africa Standard Time", "Africa/Lagos"},
{"Namibia Standard Time", "Africa/Windhoek"},
{"GTB Standard Time", "Europe/Bucharest"},
{"Middle East Standard Time", "Asia/Beirut"},
{"Egypt Standard Time", "Africa/Cairo"},
{"Syria Standard Time", "Asia/Damascus"},
{"E. Europe Standard Time", "Asia/Nicosia"},
{"South Africa Standard Time", "Africa/Johannesburg"},
{"FLE Standard Time", "Europe/Kiev"},
{"Turkey Standard Time", "Europe/Istanbul"},
{"Israel Standard Time", "Asia/Jerusalem"},
{"Jordan Standard Time", "Asia/Amman"},
{"Arabic Standard Time", "Asia/Baghdad"},
{"Kaliningrad Standard Time", "Europe/Kaliningrad"},
{"Arab Standard Time", "Asia/Riyadh"},
{"E. Africa Standard Time", "Africa/Nairobi"},
{"Iran Standard Time", "Asia/Tehran"},
{"Arabian Standard Time", "Asia/Dubai"},
{"Azerbaijan Standard Time", "Asia/Baku"},
{"Russian Standard Time", "Europe/Moscow"},
{"Mauritius Standard Time", "Indian/Mauritius"},
{"Georgian Standard Time", "Asia/Tbilisi"},
{"Caucasus Standard Time", "Asia/Yerevan"},
{"Afghanistan Standard Time", "Asia/Kabul"},
{"Pakistan Standard Time", "Asia/Karachi"},
{"West Asia Standard Time", "Asia/Tashkent"},
{"India Standard Time", "Asia/Calcutta"},
{"Sri Lanka Standard Time", "Asia/Colombo"},
{"Nepal Standard Time", "Asia/Katmandu"},
{"Central Asia Standard Time", "Asia/Almaty"},
{"Bangladesh Standard Time", "Asia/Dhaka"},
{"Ekaterinburg Standard Time", "Asia/Yekaterinburg"},
{"Myanmar Standard Time", "Asia/Rangoon"},
{"SE Asia Standard Time", "Asia/Bangkok"},
{"N. Central Asia Standard Time", "Asia/Novosibirsk"},
{"China Standard Time", "Asia/Shanghai"},
{"North Asia Standard Time", "Asia/Krasnoyarsk"},
{"Singapore Standard Time", "Asia/Singapore"},
{"W. Australia Standard Time", "Australia/Perth"},
{"Taipei Standard Time", "Asia/Taipei"},
{"Ulaanbaatar Standard Time", "Asia/Ulaanbaatar"},
{"North Asia East Standard Time", "Asia/Irkutsk"},
{"Tokyo Standard Time", "Asia/Tokyo"},
{"Korea Standard Time", "Asia/Seoul"},
{"Cen. Australia Standard Time", "Australia/Adelaide"},
{"AUS Central Standard Time", "Australia/Darwin"},
{"E. Australia Standard Time", "Australia/Brisbane"},
{"AUS Eastern Standard Time", "Australia/Sydney"},
{"West Pacific Standard Time", "Pacific/Port_Moresby"},
{"Tasmania Standard Time", "Australia/Hobart"},
{"Yakutsk Standard Time", "Asia/Yakutsk"},
{"Central Pacific Standard Time", "Pacific/Guadalcanal"},
{"Vladivostok Standard Time", "Asia/Vladivostok"},
{"New Zealand Standard Time", "Pacific/Auckland"},
{"UTC+12", "Etc/GMT-12"},
{"Fiji Standard Time", "Pacific/Fiji"},
{"Magadan Standard Time", "Asia/Magadan"},
{"Tonga Standard Time", "Pacific/Tongatapu"},
{"Samoa Standard Time", "Pacific/Apia"}
};
/// <summary>
/// This is a mapping of odd TimeZone offsets to their respective IANA codes across the world.
/// This list was compiled from painstakingly pouring over the information available at
/// https://en.wikipedia.org/wiki/List_of_tz_database_time_zones.
/// </summary>
internal static readonly Dictionary<TimeSpan, String> TimeZoneOffsetMap = new Dictionary<TimeSpan, string>() {
{ new TimeSpan(12, 45, 0), "Pacific/Chatham" },
{ new TimeSpan(10, 30, 0), "Australia/Lord_Howe" },
{ new TimeSpan(9, 30, 0), "Australia/Adelaide" },
{ new TimeSpan(8, 45, 0), "Australia/Eucla" },
{ new TimeSpan(8, 30, 0), "Asia/Pyongyang" }, // Parse in North Korea confirmed.
{ new TimeSpan(6, 30, 0), "Asia/Rangoon" },
{ new TimeSpan(5, 45, 0), "Asia/Kathmandu" },
{ new TimeSpan(5, 30, 0), "Asia/Colombo" },
{ new TimeSpan(4, 30, 0), "Asia/Kabul" },
{ new TimeSpan(3, 30, 0), "Asia/Tehran" },
{ new TimeSpan(-3, 30, 0), "America/St_Johns" },
{ new TimeSpan(-4, 30, 0), "America/Caracas" },
{ new TimeSpan(-9, 30, 0), "Pacific/Marquesas" },
};
}
}
| |
// 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.
/*============================================================
**
** Class: AsyncStreamReader
**
** Purpose: For reading text from streams using a particular
** encoding in an asynchronous manner used by the process class
**
**
===========================================================*/
using System.Collections.Generic;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Diagnostics
{
internal sealed class AsyncStreamReader : IDisposable
{
private const int DefaultBufferSize = 1024; // Byte buffer size
private readonly Stream _stream;
private readonly Decoder _decoder;
private readonly byte[] _byteBuffer;
private readonly char[] _charBuffer;
// Delegate to call user function.
private readonly Action<string> _userCallBack;
private readonly CancellationTokenSource _cts;
private Task _readToBufferTask;
private readonly Queue<string> _messageQueue;
private StringBuilder _sb;
private bool _bLastCarriageReturn;
private bool _cancelOperation;
// Cache the last position scanned in sb when searching for lines.
private int _currentLinePos;
// Creates a new AsyncStreamReader for the given stream. The
// character encoding is set by encoding and the buffer size,
// in number of 16-bit characters, is set by bufferSize.
internal AsyncStreamReader(Stream stream, Action<string> callback, Encoding encoding)
{
Debug.Assert(stream != null && encoding != null && callback != null, "Invalid arguments!");
Debug.Assert(stream.CanRead, "Stream must be readable!");
_stream = stream;
_userCallBack = callback;
_decoder = encoding.GetDecoder();
_byteBuffer = new byte[DefaultBufferSize];
// This is the maximum number of chars we can get from one iteration in loop inside ReadBuffer.
// Used so ReadBuffer can tell when to copy data into a user's char[] directly, instead of our internal char[].
int maxCharsPerBuffer = encoding.GetMaxCharCount(DefaultBufferSize);
_charBuffer = new char[maxCharsPerBuffer];
_cts = new CancellationTokenSource();
_messageQueue = new Queue<string>();
}
// User calls BeginRead to start the asynchronous read
internal void BeginReadLine()
{
_cancelOperation = false;
if (_sb == null)
{
_sb = new StringBuilder(DefaultBufferSize);
_readToBufferTask = Task.Run((Func<Task>)ReadBufferAsync);
}
else
{
FlushMessageQueue(rethrowInNewThread: false);
}
}
internal void CancelOperation()
{
_cancelOperation = true;
}
// This is the async callback function. Only one thread could/should call this.
private async Task ReadBufferAsync()
{
while (true)
{
try
{
int bytesRead = await _stream.ReadAsync(new Memory<byte>(_byteBuffer), _cts.Token).ConfigureAwait(false);
if (bytesRead == 0)
break;
int charLen = _decoder.GetChars(_byteBuffer, 0, bytesRead, _charBuffer, 0);
_sb.Append(_charBuffer, 0, charLen);
MoveLinesFromStringBuilderToMessageQueue();
}
catch (IOException)
{
// We should ideally consume errors from operations getting cancelled
// so that we don't crash the unsuspecting parent with an unhandled exc.
// This seems to come in 2 forms of exceptions (depending on platform and scenario),
// namely OperationCanceledException and IOException (for errorcode that we don't
// map explicitly).
break; // Treat this as EOF
}
catch (OperationCanceledException)
{
// We should consume any OperationCanceledException from child read here
// so that we don't crash the parent with an unhandled exc
break; // Treat this as EOF
}
// If user's delegate throws exception we treat this as EOF and
// completing without processing current buffer content
if (FlushMessageQueue(rethrowInNewThread: true))
{
return;
}
}
// We're at EOF, process current buffer content and flush message queue.
lock (_messageQueue)
{
if (_sb.Length != 0)
{
_messageQueue.Enqueue(_sb.ToString());
_sb.Length = 0;
}
_messageQueue.Enqueue(null);
}
FlushMessageQueue(rethrowInNewThread: true);
}
// Read lines stored in StringBuilder and the buffer we just read into.
// A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
private void MoveLinesFromStringBuilderToMessageQueue()
{
int currentIndex = _currentLinePos;
int lineStart = 0;
int len = _sb.Length;
// skip a beginning '\n' character of new block if last block ended
// with '\r'
if (_bLastCarriageReturn && (len > 0) && _sb[0] == '\n')
{
currentIndex = 1;
lineStart = 1;
_bLastCarriageReturn = false;
}
while (currentIndex < len)
{
char ch = _sb[currentIndex];
// Note the following common line feed chars:
// \n - UNIX \r\n - DOS \r - Mac
if (ch == '\r' || ch == '\n')
{
string line = _sb.ToString(lineStart, currentIndex - lineStart);
lineStart = currentIndex + 1;
// skip the "\n" character following "\r" character
if ((ch == '\r') && (lineStart < len) && (_sb[lineStart] == '\n'))
{
lineStart++;
currentIndex++;
}
lock (_messageQueue)
{
_messageQueue.Enqueue(line);
}
}
currentIndex++;
}
if ((len > 0) && _sb[len - 1] == '\r')
{
_bLastCarriageReturn = true;
}
// Keep the rest characters which can't form a new line in string builder.
if (lineStart < len)
{
if (lineStart == 0)
{
// we found no breaklines, in this case we cache the position
// so next time we don't have to restart from the beginning
_currentLinePos = currentIndex;
}
else
{
_sb.Remove(0, lineStart);
_currentLinePos = 0;
}
}
else
{
_sb.Length = 0;
_currentLinePos = 0;
}
}
// If everything runs without exception, returns false.
// If an exception occurs and rethrowInNewThread is true, returns true.
// If an exception occurs and rethrowInNewThread is false, the exception propagates.
private bool FlushMessageQueue(bool rethrowInNewThread)
{
try
{
// Keep going until we're out of data to process.
while (true)
{
// Get the next line (if there isn't one, we're done) and
// invoke the user's callback with it.
string line;
lock (_messageQueue)
{
if (_messageQueue.Count == 0)
{
break;
}
line = _messageQueue.Dequeue();
}
if (!_cancelOperation)
{
_userCallBack(line); // invoked outside of the lock
}
}
return false;
}
catch (Exception e)
{
// If rethrowInNewThread is true, we can't let the exception propagate synchronously on this thread,
// so propagate it in a thread pool thread and return true to indicate to the caller that this failed.
// Otherwise, let the exception propagate.
if (rethrowInNewThread)
{
ThreadPool.QueueUserWorkItem(edi => ((ExceptionDispatchInfo)edi).Throw(), ExceptionDispatchInfo.Capture(e));
return true;
}
throw;
}
}
// Wait until we hit EOF. This is called from Process.WaitForExit
// We will lose some information if we don't do this.
internal void WaitUtilEOF()
{
if (_readToBufferTask != null)
{
_readToBufferTask.GetAwaiter().GetResult();
_readToBufferTask = null;
}
}
public void Dispose()
{
_cts.Cancel();
}
}
}
| |
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode MergeKLists(ListNode[] lists) {
var preAnswer = new ListNode(0);
var temp = preAnswer;
MinHeap<ListNode> mh = new MinHeap<ListNode>(new ListNodeComparer());
foreach (var list in lists)
{
if (list != null)
{
mh.Add(list);
}
}
while (mh.Count > 0)
{
temp.next = mh.ExtractDominating();
temp = temp.next;
if (temp.next != null)
{
mh.Add(temp.next);
}
}
return preAnswer.next;
}
public class ListNodeComparer : Comparer<ListNode>
{
public override int Compare(ListNode x, ListNode y)
{
return x.val.CompareTo(y.val);
}
}
public abstract class Heap<T> : IEnumerable<T>
{
private const int InitialCapacity = 0;
private const int GrowFactor = 2;
private const int MinGrow = 1;
private int _capacity = InitialCapacity;
private T[] _heap = new T[InitialCapacity];
private int _tail = 0;
public int Count { get { return _tail; } }
public int Capacity { get { return _capacity; } }
protected Comparer<T> Comparer { get; private set; }
protected abstract bool Dominates(T x, T y);
protected Heap()
: this(Comparer<T>.Default)
{
}
protected Heap(Comparer<T> comparer)
: this(Enumerable.Empty<T>(), comparer)
{
}
protected Heap(IEnumerable<T> collection)
: this(collection, Comparer<T>.Default)
{
}
protected Heap(IEnumerable<T> collection, Comparer<T> comparer)
{
if (collection == null) throw new ArgumentNullException("collection");
if (comparer == null) throw new ArgumentNullException("comparer");
Comparer = comparer;
foreach (var item in collection)
{
if (Count == Capacity)
Grow();
_heap[_tail++] = item;
}
for (int i = Parent(_tail - 1); i >= 0; i--)
BubbleDown(i);
}
public void Add(T item)
{
if (Count == Capacity)
Grow();
_heap[_tail++] = item;
BubbleUp(_tail - 1);
}
private void BubbleUp(int i)
{
if (i == 0 || Dominates(_heap[Parent(i)], _heap[i]))
return; //correct domination (or root)
Swap(i, Parent(i));
BubbleUp(Parent(i));
}
public T GetDominating()
{
if (Count == 0) throw new InvalidOperationException("Heap is empty");
return _heap[0];
}
public T ExtractDominating()
{
if (Count == 0) throw new InvalidOperationException("Heap is empty");
T ret = _heap[0];
_tail--;
Swap(_tail, 0);
BubbleDown(0);
return ret;
}
private void BubbleDown(int i)
{
int dominatingNode = Dominating(i);
if (dominatingNode == i) return;
Swap(i, dominatingNode);
BubbleDown(dominatingNode);
}
private int Dominating(int i)
{
int dominatingNode = i;
dominatingNode = GetDominating(YoungChild(i), dominatingNode);
dominatingNode = GetDominating(OldChild(i), dominatingNode);
return dominatingNode;
}
private int GetDominating(int newNode, int dominatingNode)
{
if (newNode < _tail && !Dominates(_heap[dominatingNode], _heap[newNode]))
return newNode;
else
return dominatingNode;
}
private void Swap(int i, int j)
{
T tmp = _heap[i];
_heap[i] = _heap[j];
_heap[j] = tmp;
}
private static int Parent(int i)
{
return (i + 1) / 2 - 1;
}
private static int YoungChild(int i)
{
return (i + 1) * 2 - 1;
}
private static int OldChild(int i)
{
return YoungChild(i) + 1;
}
private void Grow()
{
int newCapacity = _capacity * GrowFactor + MinGrow;
var newHeap = new T[newCapacity];
Array.Copy(_heap, newHeap, _capacity);
_heap = newHeap;
_capacity = newCapacity;
}
public IEnumerator<T> GetEnumerator()
{
return _heap.Take(Count).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class MinHeap<T> : Heap<T>
{
public MinHeap()
: this(Comparer<T>.Default)
{
}
public MinHeap(Comparer<T> comparer)
: base(comparer)
{
}
public MinHeap(IEnumerable<T> collection)
: base(collection)
{
}
public MinHeap(IEnumerable<T> collection, Comparer<T> comparer)
: base(collection, comparer)
{
}
protected override bool Dominates(T x, T y)
{
return Comparer.Compare(x, y) <= 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Collections.Generic {
public class Queue<T> : IEnumerable<T>, ICollection, IEnumerable, IReadOnlyCollection<T> {
T[] _array;
int _head;
int _tail;
int _size;
int _version;
private const int INITIAL_SIZE = 16;
public Queue() {
}
public Queue(int count) {
if (count < 0)
throw new ArgumentOutOfRangeException("count");
_array = new T[count];
}
public Queue(IEnumerable<T> collection) {
if (collection == null)
throw new ArgumentNullException("collection");
foreach (T t in collection)
Enqueue(t);
}
public void Clear() {
if (_array != null)
Array.Clear(_array, 0, _array.Length);
_head = _tail = _size = 0;
_version++;
}
public bool Contains(T item) {
if (item == null) {
foreach (T t in this)
if (t == null)
return true;
} else {
foreach (T t in this)
if (item.Equals(t))
return true;
}
return false;
}
public void CopyTo(T[] array, int idx) {
if (array == null)
throw new ArgumentNullException();
if ((uint)idx > (uint)array.Length)
throw new ArgumentOutOfRangeException();
if (array.Length - idx < _size)
throw new ArgumentOutOfRangeException();
if (_size == 0)
return;
int contents_length = _array.Length;
int length_from_head = contents_length - _head;
Array.Copy(_array, _head, array, idx, Math.Min(_size, length_from_head));
if (_size > length_from_head)
Array.Copy(_array, 0, array,
idx + length_from_head,
_size - length_from_head);
}
void ICollection.CopyTo(Array array, int idx) {
if (array == null)
throw new ArgumentNullException();
if ((uint)idx < (uint)array.Length)
throw new ArgumentOutOfRangeException();
if (array.Length - idx < _size)
throw new ArgumentOutOfRangeException();
if (_size == 0)
return;
try {
int contents_length = _array.Length;
int length_from_head = contents_length - _head;
Array.Copy(_array, _head, array, idx, Math.Min(_size, length_from_head));
if (_size > length_from_head)
Array.Copy(_array, 0, array,
idx + length_from_head,
_size - length_from_head);
} catch (ArrayTypeMismatchException) {
throw new ArgumentException();
}
}
public T Dequeue() {
T ret = Peek();
// clear stuff out to make the GC happy
_array[_head] = default(T);
if (++_head == _array.Length)
_head = 0;
_size--;
_version++;
return ret;
}
public T Peek() {
if (_size == 0)
throw new InvalidOperationException();
return _array[_head];
}
public void Enqueue(T item) {
if (_array == null || _size == _array.Length)
SetCapacity(Math.Max(_size * 2, 4));
_array[_tail] = item;
if (++_tail == _array.Length)
_tail = 0;
_size++;
_version++;
}
public T[] ToArray() {
T[] t = new T[_size];
CopyTo(t, 0);
return t;
}
public void TrimExcess() {
if (_array != null && (_size < _array.Length * 0.9))
SetCapacity(_size);
}
void SetCapacity(int new_size) {
if (_array != null && new_size == _array.Length)
return;
if (new_size < _size)
throw new InvalidOperationException("shouldnt happen");
T[] new_data = new T[new_size];
if (_size > 0)
CopyTo(new_data, 0);
_array = new_data;
_tail = _size;
_head = 0;
_version++;
}
public int Count {
get { return _size; }
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get { return this; }
}
public Enumerator GetEnumerator() {
return new Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public struct Enumerator : IEnumerator<T>, IEnumerator, IDisposable {
const int NOT_STARTED = -2;
// this MUST be -1, because we depend on it in move next.
// we just decr the _size, so, 0 - 1 == FINISHED
const int FINISHED = -1;
Queue<T> q;
int idx;
int ver;
internal Enumerator(Queue<T> q) {
this.q = q;
idx = NOT_STARTED;
ver = q._version;
}
public void Dispose() {
idx = NOT_STARTED;
}
public bool MoveNext() {
if (ver != q._version)
throw new InvalidOperationException();
if (idx == NOT_STARTED)
idx = q._size;
return idx != FINISHED && --idx != FINISHED;
}
public T Current {
get {
if (idx < 0)
throw new InvalidOperationException();
return q._array[(q._size - 1 - idx + q._head) % q._array.Length];
}
}
void IEnumerator.Reset() {
if (ver != q._version)
throw new InvalidOperationException();
idx = NOT_STARTED;
}
object IEnumerator.Current {
get { return Current; }
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.Setup;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Orders;
using QuantConnect.Packets;
namespace QuantConnect.Lean.Engine.Results
{
/// <summary>
/// Handle the results of the backtest: where should we send the profit, portfolio updates:
/// Backtester or the Live trading platform:
/// </summary>
[InheritedExport(typeof(IResultHandler))]
public interface IResultHandler
{
/// <summary>
/// Put messages to process into the queue so they are processed by this thread.
/// </summary>
ConcurrentQueue<Packet> Messages
{
get;
set;
}
/// <summary>
/// Charts collection for storing the master copy of user charting data.
/// </summary>
ConcurrentDictionary<string, Chart> Charts
{
get;
set;
}
/// <summary>
/// Sampling period for timespans between resamples of the charting equity.
/// </summary>
/// <remarks>Specifically critical for backtesting since with such long timeframes the sampled data can get extreme.</remarks>
TimeSpan ResamplePeriod
{
get;
}
/// <summary>
/// How frequently the backtests push messages to the browser.
/// </summary>
/// <remarks>Update frequency of notification packets</remarks>
TimeSpan NotificationPeriod
{
get;
}
/// <summary>
/// Boolean flag indicating the result hander thread is busy.
/// False means it has completely finished and ready to dispose.
/// </summary>
bool IsActive
{
get;
}
/// <summary>
/// Initialize the result handler with this result packet.
/// </summary>
/// <param name="job">Algorithm job packet for this result handler</param>
/// <param name="messagingHandler"></param>
/// <param name="api"></param>
/// <param name="dataFeed"></param>
/// <param name="setupHandler"></param>
/// <param name="transactionHandler"></param>
void Initialize(AlgorithmNodePacket job, IMessagingHandler messagingHandler, IApi api, IDataFeed dataFeed, ISetupHandler setupHandler, ITransactionHandler transactionHandler);
/// <summary>
/// Primary result thread entry point to process the result message queue and send it to whatever endpoint is set.
/// </summary>
void Run();
/// <summary>
/// Process debug messages with the preconfigured settings.
/// </summary>
/// <param name="message">String debug message</param>
void DebugMessage(string message);
/// <summary>
/// Send a list of security types to the browser
/// </summary>
/// <param name="types">Security types list inside algorithm</param>
void SecurityType(List<SecurityType> types);
/// <summary>
/// Send a logging message to the log list for storage.
/// </summary>
/// <param name="message">Message we'd in the log.</param>
void LogMessage(string message);
/// <summary>
/// Send an error message back to the browser highlighted in red with a stacktrace.
/// </summary>
/// <param name="error">Error message we'd like shown in console.</param>
/// <param name="stacktrace">Stacktrace information string</param>
void ErrorMessage(string error, string stacktrace = "");
/// <summary>
/// Send a runtime error message back to the browser highlighted with in red
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="stacktrace">Stacktrace information string</param>
void RuntimeError(string message, string stacktrace = "");
/// <summary>
/// Add a sample to the chart specified by the chartName, and seriesName.
/// </summary>
/// <param name="chartName">String chart name to place the sample.</param>
/// <param name="chartType">Type of chart we should create if it doesn't already exist.</param>
/// <param name="seriesName">Series name for the chart.</param>
/// <param name="seriesType">Series type for the chart.</param>
/// <param name="time">Time for the sample</param>
/// <param name="value">Value for the chart sample.</param>
/// <param name="unit">Unit for the sample chart</param>
/// <remarks>Sample can be used to create new charts or sample equity - daily performance.</remarks>
void Sample(string chartName, ChartType chartType, string seriesName, SeriesType seriesType, DateTime time, decimal value, string unit = "$");
/// <summary>
/// Wrapper methond on sample to create the equity chart.
/// </summary>
/// <param name="time">Time of the sample.</param>
/// <param name="value">Equity value at this moment in time.</param>
/// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/>
void SampleEquity(DateTime time, decimal value);
/// <summary>
/// Sample the current daily performance directly with a time-value pair.
/// </summary>
/// <param name="time">Current backtest date.</param>
/// <param name="value">Current daily performance value.</param>
/// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/>
void SamplePerformance(DateTime time, decimal value);
/// <summary>
/// Sample the current benchmark performance directly with a time-value pair.
/// </summary>
/// <param name="time">Current backtest date.</param>
/// <param name="value">Current benchmark value.</param>
/// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/>
void SampleBenchmark(DateTime time, decimal value);
/// <summary>
/// Sample the asset prices to generate plots.
/// </summary>
/// <param name="symbol">Symbol we're sampling.</param>
/// <param name="time">Time of sample</param>
/// <param name="value">Value of the asset price</param>
/// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/>
void SampleAssetPrices(string symbol, DateTime time, decimal value);
/// <summary>
/// Add a range of samples from the users algorithms to the end of our current list.
/// </summary>
/// <param name="samples">Chart updates since the last request.</param>
/// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/>
void SampleRange(List<Chart> samples);
/// <summary>
/// Set the algorithm of the result handler after its been initialized.
/// </summary>
/// <param name="algorithm">Algorithm object matching IAlgorithm interface</param>
void SetAlgorithm(IAlgorithm algorithm);
/// <summary>
/// Save the snapshot of the total results to storage.
/// </summary>
/// <param name="packet">Packet to store.</param>
/// <param name="async">Store the packet asyncronously to speed up the thread.</param>
/// <remarks>Async creates crashes in Mono 3.10 if the thread disappears before the upload is complete so it is disabled for now.</remarks>
void StoreResult(Packet packet, bool async = false);
/// <summary>
/// Post the final result back to the controller worker if backtesting, or to console if local.
/// </summary>
void SendFinalResult(AlgorithmNodePacket job, Dictionary<int, Order> orders, Dictionary<DateTime, decimal> profitLoss, Dictionary<string, Holding> holdings, Dictionary<string, string> statistics, Dictionary<string, string> banner);
/// <summary>
/// Send a algorithm status update to the user of the algorithms running state.
/// </summary>
/// <param name="algorithmId">String Id of the algorithm.</param>
/// <param name="status">Status enum of the algorithm.</param>
/// <param name="message">Optional string message describing reason for status change.</param>
void SendStatusUpdate(string algorithmId, AlgorithmStatus status, string message = "");
/// <summary>
/// Set the chart name:
/// </summary>
/// <param name="symbol">Symbol of the chart we want.</param>
void SetChartSubscription(string symbol);
/// <summary>
/// Set a dynamic runtime statistic to show in the (live) algorithm header
/// </summary>
/// <param name="key">Runtime headline statistic name</param>
/// <param name="value">Runtime headline statistic value</param>
void RuntimeStatistic(string key, string value);
/// <summary>
/// Send a new order event.
/// </summary>
/// <param name="newEvent">Update, processing or cancellation of an order, update the IDE in live mode or ignore in backtesting.</param>
void OrderEvent(OrderEvent newEvent);
/// <summary>
/// Terminate the result thread and apply any required exit proceedures.
/// </summary>
void Exit();
/// <summary>
/// Purge/clear any outstanding messages in message queue.
/// </summary>
void PurgeQueue();
/// <summary>
/// Process any synchronous events in here that are primarily triggered from the algorithm loop
/// </summary>
void ProcessSynchronousEvents(bool forceProcess = false);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Braintree.Exceptions;
namespace Braintree.Tests
{
//NOTE: good
[TestFixture]
public class CustomerTest
{
private BraintreeGateway gateway;
private BraintreeService service;
[SetUp]
public void Setup()
{
gateway = new BraintreeGateway();
service = new BraintreeService(gateway.Configuration);
}
[Test]
public void Find_FindsCustomerWithGivenId()
{
string id = Guid.NewGuid().ToString();
var createRequest = new CustomerRequest
{
Id = id,
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
CreditCard = new CreditCardRequest
{
Number = "5555555555554444",
ExpirationDate = "05/22",
CVV = "123",
CardholderName = "Michael Angelo",
BillingAddress = new CreditCardAddressRequest()
{
FirstName = "Mike",
LastName = "Smith",
Company = "Smith Co.",
StreetAddress = "1 W Main St",
ExtendedAddress = "Suite 330",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America"
}
}
};
Customer createdCustomer = gateway.Customer.Create(createRequest).Target;
Customer customer = gateway.Customer.Find(createdCustomer.Id);
Assert.AreEqual(id, customer.Id);
Assert.AreEqual("Michael", customer.FirstName);
Assert.AreEqual("Angelo", customer.LastName);
Assert.AreEqual("Some Company", customer.Company);
Assert.AreEqual("hansolo64@example.com", customer.Email);
Assert.AreEqual("312.555.1111", customer.Phone);
Assert.AreEqual("312.555.1112", customer.Fax);
Assert.AreEqual("www.example.com", customer.Website);
Assert.AreEqual(DateTime.Now.Year, customer.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.UpdatedAt.Value.Year);
Assert.AreEqual(1, customer.CreditCards.Length);
Assert.AreEqual("555555", customer.CreditCards[0].Bin);
Assert.AreEqual("4444", customer.CreditCards[0].LastFour);
Assert.AreEqual("05", customer.CreditCards[0].ExpirationMonth);
Assert.AreEqual("2022", customer.CreditCards[0].ExpirationYear);
Assert.AreEqual("Michael Angelo", customer.CreditCards[0].CardholderName);
Assert.IsTrue(Regex.IsMatch(customer.CreditCards[0].UniqueNumberIdentifier, "\\A\\w{32}\\z"));
Assert.AreEqual(DateTime.Now.Year, customer.CreditCards[0].CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.CreditCards[0].UpdatedAt.Value.Year);
Assert.AreEqual("Mike", customer.Addresses[0].FirstName);
Assert.AreEqual("Smith", customer.Addresses[0].LastName);
Assert.AreEqual("Smith Co.", customer.Addresses[0].Company);
Assert.AreEqual("1 W Main St", customer.Addresses[0].StreetAddress);
Assert.AreEqual("Suite 330", customer.Addresses[0].ExtendedAddress);
Assert.AreEqual("Chicago", customer.Addresses[0].Locality);
Assert.AreEqual("IL", customer.Addresses[0].Region);
Assert.AreEqual("60622", customer.Addresses[0].PostalCode);
Assert.AreEqual("United States of America", customer.Addresses[0].CountryName);
}
[Test]
public void Find_IncludesApplePayCardsInPaymentMethods()
{
var createRequest = new CustomerRequest
{
PaymentMethodNonce = Nonce.ApplePayAmex
};
Customer createdCustomer = gateway.Customer.Create(createRequest).Target;
Customer customer = gateway.Customer.Find(createdCustomer.Id);
Assert.IsNotNull(customer.ApplePayCards);
Assert.IsNotNull(customer.PaymentMethods);
ApplePayCard card = customer.ApplePayCards[0];
Assert.IsNotNull(card.Token);
Assert.AreEqual(card, customer.PaymentMethods[0]);
}
[Test]
public void Find_IncludesAndroidPayProxyCardsInPaymentMethods()
{
var createRequest = new CustomerRequest
{
PaymentMethodNonce = Nonce.AndroidPayDiscover
};
var resp = gateway.Customer.Create(createRequest);
Assert.IsNotNull(resp);
Customer createdCustomer = resp.Target;
if (createdCustomer != null)
{
Customer customer = gateway.Customer.Find(createdCustomer.Id);
Assert.IsNotNull(customer.AndroidPayCards);
Assert.IsNotNull(customer.PaymentMethods);
AndroidPayCard card = customer.AndroidPayCards[0];
Assert.IsNotNull(card.Token);
Assert.IsNotNull(card.GoogleTransactionId);
Assert.AreEqual(card, customer.PaymentMethods[0]);
}
else
Assert.Inconclusive(resp.Message);
}
[Test]
public void Find_IncludesAndroidPayNetworkTokensInPaymentMethods()
{
var createRequest = new CustomerRequest
{
PaymentMethodNonce = Nonce.AndroidPayMasterCard
};
var resp = gateway.Customer.Create(createRequest);
Assert.IsNotNull(resp);
Customer createdCustomer = resp.Target;
if (createdCustomer != null)
{
Customer customer = gateway.Customer.Find(createdCustomer.Id);
Assert.IsNotNull(customer.AndroidPayCards);
Assert.IsNotNull(customer.PaymentMethods);
AndroidPayCard card = customer.AndroidPayCards[0];
Assert.IsNotNull(card.Token);
Assert.IsNotNull(card.GoogleTransactionId);
Assert.AreEqual(card, customer.PaymentMethods[0]);
}
else
Assert.Inconclusive(resp.Message);
}
[Test]
public void Find_RaisesIfIdIsInvalid()
{
try
{
gateway.Customer.Find("DOES_NOT_EXIST_999");
Assert.Fail("Expected NotFoundException.");
}
catch (NotFoundException)
{
// expected
}
}
[Test]
public void Find_RaisesIfIdIsBlank()
{
try
{
gateway.Customer.Find(" ");
Assert.Fail("Expected NotFoundException.");
}
catch (NotFoundException)
{
// expected
}
}
[Test]
public void Create_CanSetCustomFields()
{
var customFields = new Dictionary<string, string>();
customFields.Add("store_me", "a custom value");
var createRequest = new CustomerRequest()
{
CustomFields = customFields
};
var resp = gateway.Customer.Create(createRequest);
Assert.IsNotNull(resp);
Customer customer = resp.Target;
Assert.IsNotNull(customer, resp.Message);
Assert.AreEqual("a custom value", customer.CustomFields["store_me"]);
}
[Test]
public void Create_CreatesCustomerWithSpecifiedValues()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
CreditCard = new CreditCardRequest()
{
Number = "5555555555554444",
ExpirationDate = "05/22",
BillingAddress = new CreditCardAddressRequest
{
CountryName = "Macau",
CountryCodeAlpha2 = "MO",
CountryCodeAlpha3 = "MAC",
CountryCodeNumeric = "446"
}
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.AreEqual("Michael", customer.FirstName);
Assert.AreEqual("Angelo", customer.LastName);
Assert.AreEqual("Some Company", customer.Company);
Assert.AreEqual("hansolo64@example.com", customer.Email);
Assert.AreEqual("312.555.1111", customer.Phone);
Assert.AreEqual("312.555.1112", customer.Fax);
Assert.AreEqual("www.example.com", customer.Website);
Assert.AreEqual(DateTime.Now.Year, customer.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.UpdatedAt.Value.Year);
Address billingAddress = customer.CreditCards[0].BillingAddress;
Assert.AreEqual("Macau", billingAddress.CountryName);
Assert.AreEqual("MO", billingAddress.CountryCodeAlpha2);
Assert.AreEqual("MAC", billingAddress.CountryCodeAlpha3);
Assert.AreEqual("446", billingAddress.CountryCodeNumeric);
}
[Test]
public void Create_withSecurityParams()
{
var createRequest = new CustomerRequest()
{
CreditCard = new CreditCardRequest()
{
Number = "5555555555554444",
ExpirationDate = "05/22",
CVV = "123",
DeviceSessionId = "my_dsid"
}
};
Result<Customer> result = gateway.Customer.Create(createRequest);
Assert.IsTrue(result.IsSuccess());
}
[Test]
public void Create_withErrorsOnCountry()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
CreditCard = new CreditCardRequest()
{
Number = "5555555555554444",
ExpirationDate = "05/22",
BillingAddress = new CreditCardAddressRequest
{
CountryName = "zzzzzz",
CountryCodeAlpha2 = "zz",
CountryCodeAlpha3 = "zzz",
CountryCodeNumeric = "000"
}
}
};
Result<Customer> result = gateway.Customer.Create(createRequest);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED,
result.Errors.ForObject("Customer").ForObject("CreditCard").ForObject("BillingAddress").OnField("CountryName")[0].Code
);
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED,
result.Errors.ForObject("Customer").ForObject("CreditCard").ForObject("BillingAddress").OnField("CountryCodeAlpha2")[0].Code
);
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED,
result.Errors.ForObject("Customer").ForObject("CreditCard").ForObject("BillingAddress").OnField("CountryCodeAlpha3")[0].Code
);
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED,
result.Errors.ForObject("Customer").ForObject("CreditCard").ForObject("BillingAddress").OnField("CountryCodeNumeric")[0].Code
);
}
[Test]
public void Create_CreateCustomerWithCreditCard()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
CreditCard = new CreditCardRequest()
{
Number = "5555555555554444",
ExpirationDate = "05/22",
CVV = "123",
CardholderName = "Michael Angelo"
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.AreEqual("Michael", customer.FirstName);
Assert.AreEqual("Angelo", customer.LastName);
Assert.AreEqual("Some Company", customer.Company);
Assert.AreEqual("hansolo64@example.com", customer.Email);
Assert.AreEqual("312.555.1111", customer.Phone);
Assert.AreEqual("312.555.1112", customer.Fax);
Assert.AreEqual("www.example.com", customer.Website);
Assert.AreEqual(DateTime.Now.Year, customer.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.UpdatedAt.Value.Year);
Assert.AreEqual(1, customer.CreditCards.Length);
Assert.AreEqual("555555", customer.CreditCards[0].Bin);
Assert.AreEqual("4444", customer.CreditCards[0].LastFour);
Assert.AreEqual("05", customer.CreditCards[0].ExpirationMonth);
Assert.AreEqual("2022", customer.CreditCards[0].ExpirationYear);
Assert.AreEqual("Michael Angelo", customer.CreditCards[0].CardholderName);
Assert.AreEqual(DateTime.Now.Year, customer.CreditCards[0].CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.CreditCards[0].UpdatedAt.Value.Year);
}
[Ignore("Not sure why this isn't working")]
[Test]
public void Create_CreateCustomerUsingAccessToken()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
};
//BraintreeGateway oauthGateway = new BraintreeGateway(
// "client_id$development$integration_client_id",
// "client_secret$development$integration_client_secret"
//);
//string code = OAuthTestHelper.CreateGrant(oauthGateway, "integration_merchant_id", "read_write");
BraintreeGateway oauthGateway = new BraintreeGateway(
"client_id$" + Environment.CONFIGURED.EnvironmentName + "$integration_client_id",
"client_secret$" + Environment.CONFIGURED.EnvironmentName + "$integration_client_secret"
);
string code = OAuthTestHelper.CreateGrant(oauthGateway, gateway.Configuration.MerchantId, "read_write");
ResultImpl<OAuthCredentials> accessTokenResult = oauthGateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest {
Code = code,
Scope = "read_write"
});
gateway = new BraintreeGateway(accessTokenResult.Target.AccessToken);
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.AreEqual("Michael", customer.FirstName);
Assert.AreEqual("Angelo", customer.LastName);
Assert.AreEqual("Some Company", customer.Company);
Assert.AreEqual("hansolo64@example.com", customer.Email);
Assert.AreEqual("312.555.1111", customer.Phone);
Assert.AreEqual("312.555.1112", customer.Fax);
Assert.AreEqual("www.example.com", customer.Website);
Assert.AreEqual(DateTime.Now.Year, customer.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.UpdatedAt.Value.Year);
}
[Test]
public void Create_CreateCustomerWithCreditCardAndBillingAddress()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
CreditCard = new CreditCardRequest()
{
Number = "5555555555554444",
ExpirationDate = "05/22",
CVV = "123",
CardholderName = "Michael Angelo",
BillingAddress = new CreditCardAddressRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America"
}
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.AreEqual("Michael", customer.FirstName);
Assert.AreEqual("Angelo", customer.LastName);
Assert.AreEqual("Some Company", customer.Company);
Assert.AreEqual("hansolo64@example.com", customer.Email);
Assert.AreEqual("312.555.1111", customer.Phone);
Assert.AreEqual("312.555.1112", customer.Fax);
Assert.AreEqual("www.example.com", customer.Website);
Assert.AreEqual(DateTime.Now.Year, customer.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.UpdatedAt.Value.Year);
Assert.AreEqual(1, customer.CreditCards.Length);
Assert.AreEqual("555555", customer.CreditCards[0].Bin);
Assert.AreEqual("4444", customer.CreditCards[0].LastFour);
Assert.AreEqual("05", customer.CreditCards[0].ExpirationMonth);
Assert.AreEqual("2022", customer.CreditCards[0].ExpirationYear);
Assert.AreEqual("Michael Angelo", customer.CreditCards[0].CardholderName);
Assert.AreEqual(DateTime.Now.Year, customer.CreditCards[0].CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.CreditCards[0].UpdatedAt.Value.Year);
Assert.AreEqual(customer.Addresses[0].Id, customer.CreditCards[0].BillingAddress.Id);
Assert.AreEqual("Michael", customer.Addresses[0].FirstName);
Assert.AreEqual("Angelo", customer.Addresses[0].LastName);
Assert.AreEqual("Angelo Co.", customer.Addresses[0].Company);
Assert.AreEqual("1 E Main St", customer.Addresses[0].StreetAddress);
Assert.AreEqual("Apt 3", customer.Addresses[0].ExtendedAddress);
Assert.AreEqual("Chicago", customer.Addresses[0].Locality);
Assert.AreEqual("IL", customer.Addresses[0].Region);
Assert.AreEqual("60622", customer.Addresses[0].PostalCode);
Assert.AreEqual("United States of America", customer.Addresses[0].CountryName);
}
[Test]
public void Create_WithVenmoSdkPaymentMethodCode()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
CreditCard = new CreditCardRequest()
{
VenmoSdkPaymentMethodCode = SandboxValues.VenmoSdk.VISA_PAYMENT_METHOD_CODE
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.AreEqual("Michael", customer.FirstName);
Assert.AreEqual("Angelo", customer.LastName);
Assert.AreEqual("411111", customer.CreditCards[0].Bin);
Assert.AreEqual("1111", customer.CreditCards[0].LastFour);
}
[Test]
public void Create_WithVenmoSdkSession()
{
var createRequest = new CustomerRequest()
{
CreditCard = new CreditCardRequest()
{
Number = "5555555555554444",
ExpirationDate = "05/22",
Options = new CreditCardOptionsRequest() {
VenmoSdkSession = SandboxValues.VenmoSdk.SESSION
}
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.IsTrue(customer.CreditCards[0].IsVenmoSdk.Value);
}
[Test]
public void Create_WithPaymentMethodNonce()
{
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest{
CreditCard = new CreditCardRequest{
PaymentMethodNonce = nonce
}
});
Assert.IsTrue(result.IsSuccess());
}
[Test]
public void Create_WithPayPalPaymentMethodNonce()
{
string nonce = TestHelper.GenerateFuturePaymentPayPalNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest{
PaymentMethodNonce = nonce
});
Assert.IsTrue(result.IsSuccess());
var customer = result.Target;
Assert.AreEqual(1, customer.PayPalAccounts.Length);
Assert.AreEqual(customer.PayPalAccounts[0].Token, customer.DefaultPaymentMethod.Token);
}
#pragma warning disable 0618
[Test]
public void ConfirmTransparentRedirect_CreatesTheCustomer()
{
CustomerRequest trParams = new CustomerRequest();
CustomerRequest request = new CustomerRequest
{
FirstName = "John",
LastName = "Doe"
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.Customer.TransparentRedirectURLForCreate(), service);
Result<Customer> result = gateway.Customer.ConfirmTransparentRedirect(queryString);
Assert.IsTrue(result.IsSuccess());
Customer customer = result.Target;
Assert.AreEqual("John", customer.FirstName);
Assert.AreEqual("Doe", customer.LastName);
}
#pragma warning restore 0618
#pragma warning disable 0618
[Test]
public void ConfirmTransparentRedirect_CreatesNestedElementsAndCustomFields()
{
CustomerRequest trParams = new CustomerRequest();
CustomerRequest request = new CustomerRequest
{
FirstName = "John",
LastName = "Doe",
CreditCard = new CreditCardRequest
{
Number = SandboxValues.CreditCardNumber.VISA,
CardholderName = "John Doe",
ExpirationDate = "05/10",
BillingAddress = new CreditCardAddressRequest
{
CountryName = "Mexico",
CountryCodeAlpha2 = "MX",
CountryCodeAlpha3 = "MEX",
CountryCodeNumeric = "484"
}
},
CustomFields = new Dictionary<string, string>
{
{ "store_me", "a custom value" }
}
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.Customer.TransparentRedirectURLForCreate(), service);
Result<Customer> result = gateway.Customer.ConfirmTransparentRedirect(queryString);
Assert.IsTrue(result.IsSuccess());
Customer customer = result.Target;
Assert.AreEqual("John", customer.FirstName);
Assert.AreEqual("Doe", customer.LastName);
Assert.AreEqual("John Doe", customer.CreditCards[0].CardholderName);
Assert.AreEqual("a custom value", customer.CustomFields["store_me"]);
Address address = customer.CreditCards[0].BillingAddress;
Assert.AreEqual("Mexico", address.CountryName);
Assert.AreEqual("MX", address.CountryCodeAlpha2);
Assert.AreEqual("MEX", address.CountryCodeAlpha3);
Assert.AreEqual("484", address.CountryCodeNumeric);
}
#pragma warning restore 0618
#pragma warning disable 0618
[Test]
public void ConfirmTransparentRedirect_UpdatesTheCustomer()
{
CustomerRequest createRequest = new CustomerRequest
{
FirstName = "Jane",
LastName = "Deer"
};
Customer createdCustomer = gateway.Customer.Create(createRequest).Target;
CustomerRequest trParams = new CustomerRequest
{
CustomerId = createdCustomer.Id
};
CustomerRequest request = new CustomerRequest
{
FirstName = "John",
LastName = "Doe"
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.Customer.TransparentRedirectURLForUpdate(), service);
Result<Customer> result = gateway.Customer.ConfirmTransparentRedirect(queryString);
Assert.IsTrue(result.IsSuccess());
Customer customer = result.Target;
Assert.AreEqual("John", customer.FirstName);
Assert.AreEqual("Doe", customer.LastName);
}
#pragma warning restore 0618
#pragma warning disable 0618
[Test]
public void Update_UpdatesCustomerAndNestedValuesViaTr()
{
var createRequest = new CustomerRequest()
{
FirstName = "Old First",
LastName = "Old Last",
CreditCard = new CreditCardRequest()
{
Number = "4111111111111111",
ExpirationDate = "10/10",
BillingAddress = new CreditCardAddressRequest()
{
PostalCode = "11111"
}
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
CreditCard creditCard = customer.CreditCards[0];
Address address = creditCard.BillingAddress;
var trParams = new CustomerRequest()
{
CustomerId = customer.Id,
FirstName = "New First",
LastName = "New Last",
CreditCard = new CreditCardRequest()
{
ExpirationDate = "12/12",
Options = new CreditCardOptionsRequest()
{
UpdateExistingToken = creditCard.Token
},
BillingAddress = new CreditCardAddressRequest()
{
PostalCode = "44444",
CountryName = "Chad",
CountryCodeAlpha2 = "TD",
CountryCodeAlpha3 = "TCD",
CountryCodeNumeric = "148",
Options = new CreditCardAddressOptionsRequest()
{
UpdateExisting = true
}
}
}
};
string queryString = TestHelper.QueryStringForTR(trParams, new CustomerRequest(), gateway.Customer.TransparentRedirectURLForUpdate(), service);
Customer updatedCustomer = gateway.Customer.ConfirmTransparentRedirect(queryString).Target;
CreditCard updatedCreditCard = gateway.CreditCard.Find(creditCard.Token);
Address updatedAddress = gateway.Address.Find(customer.Id, address.Id);
Assert.AreEqual("New First", updatedCustomer.FirstName);
Assert.AreEqual("New Last", updatedCustomer.LastName);
Assert.AreEqual("12/2012", updatedCreditCard.ExpirationDate);
Assert.AreEqual("44444", updatedAddress.PostalCode);
Assert.AreEqual("Chad", updatedAddress.CountryName);
Assert.AreEqual("TD", updatedAddress.CountryCodeAlpha2);
Assert.AreEqual("TCD", updatedAddress.CountryCodeAlpha3);
Assert.AreEqual("148", updatedAddress.CountryCodeNumeric);
}
#pragma warning restore 0618
[Test]
public void Update_UpdatesCustomerWithNewValues()
{
string oldId = Guid.NewGuid().ToString();
string newId = Guid.NewGuid().ToString();
var createRequest = new CustomerRequest()
{
Id = oldId,
FirstName = "Old First",
LastName = "Old Last",
Company = "Old Company",
Email = "old@example.com",
Phone = "312.555.1111 xOld",
Fax = "312.555.1112 xOld",
Website = "old.example.com"
};
gateway.Customer.Create(createRequest);
var updateRequest = new CustomerRequest()
{
Id = newId,
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com"
};
Customer updatedCustomer = gateway.Customer.Update(oldId, updateRequest).Target;
Assert.AreEqual(newId, updatedCustomer.Id);
Assert.AreEqual("Michael", updatedCustomer.FirstName);
Assert.AreEqual("Angelo", updatedCustomer.LastName);
Assert.AreEqual("Some Company", updatedCustomer.Company);
Assert.AreEqual("hansolo64@example.com", updatedCustomer.Email);
Assert.AreEqual("312.555.1111", updatedCustomer.Phone);
Assert.AreEqual("312.555.1112", updatedCustomer.Fax);
Assert.AreEqual("www.example.com", updatedCustomer.Website);
Assert.AreEqual(DateTime.Now.Year, updatedCustomer.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, updatedCustomer.UpdatedAt.Value.Year);
}
[Test]
public void Update_UpdatesCustomerAndNestedValues()
{
var createRequest = new CustomerRequest()
{
FirstName = "Old First",
LastName = "Old Last",
CreditCard = new CreditCardRequest()
{
Number = "4111111111111111",
ExpirationDate = "10/10",
BillingAddress = new CreditCardAddressRequest()
{
PostalCode = "11111"
}
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
CreditCard creditCard = customer.CreditCards[0];
Address address = creditCard.BillingAddress;
var updateRequest = new CustomerRequest()
{
FirstName = "New First",
LastName = "New Last",
CreditCard = new CreditCardRequest()
{
ExpirationDate = "12/12",
Options = new CreditCardOptionsRequest()
{
UpdateExistingToken = creditCard.Token
},
BillingAddress = new CreditCardAddressRequest()
{
PostalCode = "44444",
CountryName = "Chad",
CountryCodeAlpha2 = "TD",
CountryCodeAlpha3 = "TCD",
CountryCodeNumeric = "148",
Options = new CreditCardAddressOptionsRequest()
{
UpdateExisting = true
}
}
}
};
Customer updatedCustomer = gateway.Customer.Update(customer.Id, updateRequest).Target;
CreditCard updatedCreditCard = gateway.CreditCard.Find(creditCard.Token);
Address updatedAddress = gateway.Address.Find(customer.Id, address.Id);
Assert.AreEqual("New First", updatedCustomer.FirstName);
Assert.AreEqual("New Last", updatedCustomer.LastName);
Assert.AreEqual("12/2012", updatedCreditCard.ExpirationDate);
Assert.AreEqual("44444", updatedAddress.PostalCode);
Assert.AreEqual("Chad", updatedAddress.CountryName);
Assert.AreEqual("TD", updatedAddress.CountryCodeAlpha2);
Assert.AreEqual("TCD", updatedAddress.CountryCodeAlpha3);
Assert.AreEqual("148", updatedAddress.CountryCodeNumeric);
}
[Test]
public void Update_AcceptsNestedBillingAddressId()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest addressRequest = new AddressRequest
{
FirstName = "John",
LastName = "Doe"
};
Address address = gateway.Address.Create(customer.Id, addressRequest).Target;
var updateRequest = new CustomerRequest
{
CreditCard = new CreditCardRequest
{
Number = "4111111111111111",
ExpirationDate = "10/10",
BillingAddressId = address.Id
}
};
Customer updatedCustomer = gateway.Customer.Update(customer.Id, updateRequest).Target;
Address billingAddress = updatedCustomer.CreditCards[0].BillingAddress;
Assert.AreEqual(address.Id, billingAddress.Id);
Assert.AreEqual("John", billingAddress.FirstName);
Assert.AreEqual("Doe", billingAddress.LastName);
}
[Test]
public void Update_AcceptsPaymentMethodNonce()
{
var create = new CustomerRequest
{
CreditCard = new CreditCardRequest
{
Number = "4111111111111111",
ExpirationDate = "10/18",
}
};
var customer = gateway.Customer.Create(create).Target;
var update = new CustomerRequest
{
PaymentMethodNonce = Nonce.PayPalFuturePayment
};
var updatedCustomer = gateway.Customer.Update(customer.Id, update).Target;
Assert.AreEqual(1, updatedCustomer.PayPalAccounts.Length);
Assert.AreEqual(1, updatedCustomer.CreditCards.Length);
Assert.AreEqual(2, updatedCustomer.PaymentMethods.Length);
}
[Test]
public void Delete_DeletesTheCustomer()
{
string id = Guid.NewGuid().ToString();
gateway.Customer.Create(new CustomerRequest() { Id = id });
Assert.AreEqual(id, gateway.Customer.Find(id).Id);
gateway.Customer.Delete(id);
try
{
gateway.Customer.Find(id);
Assert.Fail("Expected NotFoundException.");
}
catch (NotFoundException)
{
// expected
}
}
[Test]
public void All() {
ResourceCollection<Customer> collection = gateway.Customer.All();
Assert.IsTrue(collection.MaximumCount > 100);
List<string> items = new List<string>();
foreach (Customer item in collection) {
items.Add(item.Id);
}
HashSet<string> uniqueItems = new HashSet<string>(items);
Assert.AreEqual(uniqueItems.Count, collection.MaximumCount);
}
[Test]
public void Search_FindDuplicateCardsGivenPaymentMethodToken()
{
CreditCardRequest creditCard = new CreditCardRequest
{
Number = "4111111111111111",
ExpirationDate = "05/2012"
};
CustomerRequest jimRequest = new CustomerRequest
{
FirstName = "Jim",
CreditCard = creditCard
};
CustomerRequest joeRequest = new CustomerRequest
{
FirstName = "Jim",
CreditCard = creditCard
};
Customer jim = gateway.Customer.Create(jimRequest).Target;
Customer joe = gateway.Customer.Create(joeRequest).Target;
CustomerSearchRequest searchRequest = new CustomerSearchRequest().
PaymentMethodTokenWithDuplicates.Is(jim.CreditCards[0].Token);
ResourceCollection<Customer> collection = gateway.Customer.Search(searchRequest);
List<string> customerIds = new List<string>();
foreach (Customer customer in collection) {
customerIds.Add(customer.Id);
}
Assert.IsTrue(customerIds.Contains(jim.Id));
Assert.IsTrue(customerIds.Contains(joe.Id));
}
[Test]
public void Search_OnAllTextFields()
{
string creditCardToken = string.Format("cc{0}", new Random().Next(1000000).ToString());
CustomerRequest request = new CustomerRequest
{
Company = "Braintree",
Email = "smith@example.com",
Fax = "5551231234",
FirstName = "Tom",
LastName = "Smith",
Phone = "5551231235",
Website = "http://example.com",
CreditCard = new CreditCardRequest
{
CardholderName = "Tim Toole",
Number = "4111111111111111",
ExpirationDate = "05/2012",
Token = creditCardToken,
BillingAddress = new CreditCardAddressRequest
{
Company = "Braintree",
CountryName = "United States of America",
ExtendedAddress = "Suite 123",
FirstName = "Drew",
LastName = "Michaelson",
Locality = "Chicago",
PostalCode = "12345",
Region = "IL",
StreetAddress = "123 Main St"
}
}
};
Customer customer = gateway.Customer.Create(request).Target;
customer = gateway.Customer.Find(customer.Id);
CustomerSearchRequest searchRequest = new CustomerSearchRequest().
Id.Is(customer.Id).
FirstName.Is("Tom").
LastName.Is("Smith").
Company.Is("Braintree").
Email.Is("smith@example.com").
Website.Is("http://example.com").
Fax.Is("5551231234").
Phone.Is("5551231235").
AddressFirstName.Is("Drew").
AddressLastName.Is("Michaelson").
AddressLocality.Is("Chicago").
AddressPostalCode.Is("12345").
AddressRegion.Is("IL").
AddressCountryName.Is("United States of America").
AddressStreetAddress.Is("123 Main St").
AddressExtendedAddress.Is("Suite 123").
PaymentMethodToken.Is(creditCardToken).
CardholderName.Is("Tim Toole").
CreditCardNumber.Is("4111111111111111").
CreditCardExpirationDate.Is("05/2012");
ResourceCollection<Customer> collection = gateway.Customer.Search(searchRequest);
Assert.AreEqual(1, collection.MaximumCount);
Assert.AreEqual(customer.Id, collection.FirstItem.Id);
}
[Test]
public void Search_OnCreatedAt()
{
CustomerRequest request = new CustomerRequest();
Customer customer = gateway.Customer.Create(request).Target;
DateTime createdAt = customer.CreatedAt.Value;
DateTime threeHoursEarlier = createdAt.AddHours(-3);
DateTime oneHourEarlier = createdAt.AddHours(-1);
DateTime oneHourLater = createdAt.AddHours(1);
CustomerSearchRequest searchRequest = new CustomerSearchRequest().
Id.Is(customer.Id).
CreatedAt.Between(oneHourEarlier, oneHourLater);
Assert.AreEqual(1, gateway.Customer.Search(searchRequest).MaximumCount);
searchRequest = new CustomerSearchRequest().
Id.Is(customer.Id).
CreatedAt.GreaterThanOrEqualTo(oneHourEarlier);
Assert.AreEqual(1, gateway.Customer.Search(searchRequest).MaximumCount);
searchRequest = new CustomerSearchRequest().
Id.Is(customer.Id).
CreatedAt.LessThanOrEqualTo(oneHourLater);
Assert.AreEqual(1, gateway.Customer.Search(searchRequest).MaximumCount);
searchRequest = new CustomerSearchRequest().
Id.Is(customer.Id).
CreatedAt.Between(threeHoursEarlier, oneHourEarlier);
Assert.AreEqual(0, gateway.Customer.Search(searchRequest).MaximumCount);
}
[Test]
public void Search_OnPayPalAccountEmail()
{
var request = new CustomerRequest
{
PaymentMethodNonce = Nonce.PayPalFuturePayment
};
var customer = gateway.Customer.Create(request).Target;
var search = new CustomerSearchRequest().
Id.Is(customer.Id).
PayPalAccountEmail.Is(customer.PayPalAccounts[0].Email);
Assert.AreEqual(1, gateway.Customer.Search(search).MaximumCount);
}
}
}
| |
namespace SandcastleBuilder.Gui.ContentEditors
{
partial class ContentLayoutWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if(disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ContentLayoutWindow));
this.tvContent = new System.Windows.Forms.TreeView();
this.ilImages = new System.Windows.Forms.ImageList(this.components);
this.miPasteAsChild = new System.Windows.Forms.ToolStripMenuItem();
this.cmsTopics = new System.Windows.Forms.ContextMenuStrip(this.components);
this.miDefaultTopic = new System.Windows.Forms.ToolStripMenuItem();
this.miMarkAsMSHVRoot = new System.Windows.Forms.ToolStripMenuItem();
this.miApiContent = new System.Windows.Forms.ToolStripMenuItem();
this.miCtxInsertApiAfter = new System.Windows.Forms.ToolStripMenuItem();
this.miCtxInsertApiBefore = new System.Windows.Forms.ToolStripMenuItem();
this.miCtxInsertApiAsChild = new System.Windows.Forms.ToolStripMenuItem();
this.miCtxClearInsertionPoint = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.miMoveUp = new System.Windows.Forms.ToolStripMenuItem();
this.miMoveDown = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripSeparator();
this.miAddSibling = new System.Windows.Forms.ToolStripMenuItem();
this.cmsNewSiblingTopic = new System.Windows.Forms.ContextMenuStrip(this.components);
this.miStandardSibling = new System.Windows.Forms.ToolStripMenuItem();
this.miCustomSibling = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.addExistingTopicFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addAllTopicsInFolderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.miAddEmptySibling = new System.Windows.Forms.ToolStripMenuItem();
this.tsbAddSiblingTopic = new System.Windows.Forms.ToolStripSplitButton();
this.miAddChild = new System.Windows.Forms.ToolStripMenuItem();
this.cmsNewChildTopic = new System.Windows.Forms.ContextMenuStrip(this.components);
this.miStandardChild = new System.Windows.Forms.ToolStripMenuItem();
this.miCustomChild = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.miAddEmptyChild = new System.Windows.Forms.ToolStripMenuItem();
this.miAssociateTopic = new System.Windows.Forms.ToolStripMenuItem();
this.miClearTopic = new System.Windows.Forms.ToolStripMenuItem();
this.miRefreshAssociations = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator();
this.miDelete = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripSeparator();
this.miCut = new System.Windows.Forms.ToolStripMenuItem();
this.miPaste = new System.Windows.Forms.ToolStripMenuItem();
this.miCopyAsLink = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator();
this.miEditTopic = new System.Windows.Forms.ToolStripMenuItem();
this.miSortTopics = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator();
this.miHelp = new System.Windows.Forms.ToolStripMenuItem();
this.tsbAddChildTopic = new System.Windows.Forms.ToolStripSplitButton();
this.pgProps = new SandcastleBuilder.Utils.Controls.CustomPropertyGrid();
this.tsTopics = new System.Windows.Forms.ToolStrip();
this.tsbApiInsertionPoint = new System.Windows.Forms.ToolStripSplitButton();
this.miInsertApiAfter = new System.Windows.Forms.ToolStripMenuItem();
this.miInsertApiBefore = new System.Windows.Forms.ToolStripMenuItem();
this.miInsertApiAsChild = new System.Windows.Forms.ToolStripMenuItem();
this.miClearApiInsertionPoint = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.tsbMoveUp = new System.Windows.Forms.ToolStripButton();
this.tsbMoveDown = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.tsbDeleteTopic = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.tsbCut = new System.Windows.Forms.ToolStripButton();
this.tsbPaste = new System.Windows.Forms.ToolStripSplitButton();
this.tsmiPasteAsSibling = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiPasteAsChild = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.tsbEditTopic = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.tsbHelp = new System.Windows.Forms.ToolStripButton();
this.sbStatusBarText = new SandcastleBuilder.Utils.Controls.StatusBarTextProvider(this.components);
this.txtFindId = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.tsbDefaultTopic = new System.Windows.Forms.ToolStripButton();
this.cmsTopics.SuspendLayout();
this.cmsNewSiblingTopic.SuspendLayout();
this.cmsNewChildTopic.SuspendLayout();
this.tsTopics.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// tvContent
//
this.tvContent.AllowDrop = true;
this.tvContent.Dock = System.Windows.Forms.DockStyle.Fill;
this.tvContent.HideSelection = false;
this.tvContent.ImageIndex = 0;
this.tvContent.ImageList = this.ilImages;
this.tvContent.Location = new System.Drawing.Point(0, 0);
this.tvContent.Name = "tvContent";
this.tvContent.SelectedImageIndex = 0;
this.tvContent.ShowNodeToolTips = true;
this.tvContent.Size = new System.Drawing.Size(383, 300);
this.sbStatusBarText.SetStatusBarText(this.tvContent, "Content: Drag an item and drop it in the topic");
this.tvContent.TabIndex = 0;
this.tvContent.NodeMouseDoubleClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.tvContent_NodeMouseDoubleClick);
this.tvContent.DragDrop += new System.Windows.Forms.DragEventHandler(this.tvContent_DragDrop);
this.tvContent.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvContent_AfterSelect);
this.tvContent.MouseDown += new System.Windows.Forms.MouseEventHandler(this.tvContent_MouseDown);
this.tvContent.DragEnter += new System.Windows.Forms.DragEventHandler(this.tvContent_DragOver);
this.tvContent.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tvContent_KeyDown);
this.tvContent.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.tvContent_ItemDrag);
this.tvContent.DragOver += new System.Windows.Forms.DragEventHandler(this.tvContent_DragOver);
//
// ilImages
//
this.ilImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ilImages.ImageStream")));
this.ilImages.TransparentColor = System.Drawing.Color.Magenta;
this.ilImages.Images.SetKeyName(0, "NormalTopic.bmp");
this.ilImages.Images.SetKeyName(1, "DefaultTopic.bmp");
this.ilImages.Images.SetKeyName(2, "MoveUp.bmp");
this.ilImages.Images.SetKeyName(3, "MoveDown.bmp");
this.ilImages.Images.SetKeyName(4, "AddRootItem.bmp");
this.ilImages.Images.SetKeyName(5, "AddChildItem.bmp");
this.ilImages.Images.SetKeyName(6, "Cut.bmp");
this.ilImages.Images.SetKeyName(7, "Copy.bmp");
this.ilImages.Images.SetKeyName(8, "Paste.bmp");
this.ilImages.Images.SetKeyName(9, "Delete.bmp");
this.ilImages.Images.SetKeyName(10, "InsertApiAfter.bmp");
this.ilImages.Images.SetKeyName(11, "InsertApiBefore.bmp");
this.ilImages.Images.SetKeyName(12, "InsertApiAsChild.bmp");
this.ilImages.Images.SetKeyName(13, "DefaultApiAfter.bmp");
this.ilImages.Images.SetKeyName(14, "DefaultApiBefore.bmp");
this.ilImages.Images.SetKeyName(15, "DefaultApiAsChild.bmp");
this.ilImages.Images.SetKeyName(16, "RootContentContainer.bmp");
//
// miPasteAsChild
//
this.miPasteAsChild.Name = "miPasteAsChild";
this.miPasteAsChild.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miPasteAsChild, "Paste the topic in the clipboard as a sibling of the selected item");
this.miPasteAsChild.Text = "&Paste as Child";
this.miPasteAsChild.Click += new System.EventHandler(this.tsbPaste_ButtonClick);
//
// cmsTopics
//
this.cmsTopics.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F);
this.cmsTopics.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miDefaultTopic,
this.miMarkAsMSHVRoot,
this.miApiContent,
this.toolStripMenuItem1,
this.miMoveUp,
this.miMoveDown,
this.toolStripMenuItem9,
this.miAddSibling,
this.miAddChild,
this.miAssociateTopic,
this.miClearTopic,
this.miRefreshAssociations,
this.toolStripMenuItem4,
this.miDelete,
this.toolStripMenuItem7,
this.miCut,
this.miPaste,
this.miPasteAsChild,
this.miCopyAsLink,
this.toolStripSeparator10,
this.miEditTopic,
this.miSortTopics,
this.toolStripSeparator11,
this.miHelp});
this.cmsTopics.Name = "ctxTasks";
this.cmsTopics.Size = new System.Drawing.Size(327, 508);
//
// miDefaultTopic
//
this.miDefaultTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.DefaultTopic;
this.miDefaultTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miDefaultTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miDefaultTopic.Name = "miDefaultTopic";
this.miDefaultTopic.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miDefaultTopic, "Mark the selected topic as the default topic");
this.miDefaultTopic.Text = "Toggle De&fault Topic";
this.miDefaultTopic.Click += new System.EventHandler(this.tsbDefaultTopic_Click);
//
// miMarkAsMSHVRoot
//
this.miMarkAsMSHVRoot.Image = global::SandcastleBuilder.Gui.Properties.Resources.RootContentContainer;
this.miMarkAsMSHVRoot.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miMarkAsMSHVRoot.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miMarkAsMSHVRoot.Name = "miMarkAsMSHVRoot";
this.miMarkAsMSHVRoot.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miMarkAsMSHVRoot, "Mark the selected topic as the root content container for MS Help Viewer output");
this.miMarkAsMSHVRoot.Text = "Toggle MS Help Viewer Root Container";
this.miMarkAsMSHVRoot.Click += new System.EventHandler(this.miMarkAsMSHVRoot_Click);
//
// miApiContent
//
this.miApiContent.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miCtxInsertApiAfter,
this.miCtxInsertApiBefore,
this.miCtxInsertApiAsChild,
this.miCtxClearInsertionPoint});
this.miApiContent.Name = "miApiContent";
this.miApiContent.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miApiContent, "Specify how the API content is inserted relative to the selected topic");
this.miApiContent.Text = "API Content Insertion Point";
//
// miCtxInsertApiAfter
//
this.miCtxInsertApiAfter.Image = global::SandcastleBuilder.Gui.Properties.Resources.InsertApiAfter;
this.miCtxInsertApiAfter.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miCtxInsertApiAfter.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miCtxInsertApiAfter.Name = "miCtxInsertApiAfter";
this.miCtxInsertApiAfter.Size = new System.Drawing.Size(358, 22);
this.sbStatusBarText.SetStatusBarText(this.miCtxInsertApiAfter, "Insert the API content after the selected topic");
this.miCtxInsertApiAfter.Text = "Insert API content &after selected topic";
this.miCtxInsertApiAfter.Click += new System.EventHandler(this.ApiInsertionPoint_Click);
//
// miCtxInsertApiBefore
//
this.miCtxInsertApiBefore.Image = global::SandcastleBuilder.Gui.Properties.Resources.InsertApiBefore;
this.miCtxInsertApiBefore.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miCtxInsertApiBefore.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miCtxInsertApiBefore.Name = "miCtxInsertApiBefore";
this.miCtxInsertApiBefore.Size = new System.Drawing.Size(358, 22);
this.sbStatusBarText.SetStatusBarText(this.miCtxInsertApiBefore, "Insert the API content before the selected topic");
this.miCtxInsertApiBefore.Text = "Insert API content &before selected topic";
this.miCtxInsertApiBefore.Click += new System.EventHandler(this.ApiInsertionPoint_Click);
//
// miCtxInsertApiAsChild
//
this.miCtxInsertApiAsChild.Image = global::SandcastleBuilder.Gui.Properties.Resources.InsertApiAsChild;
this.miCtxInsertApiAsChild.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miCtxInsertApiAsChild.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miCtxInsertApiAsChild.Name = "miCtxInsertApiAsChild";
this.miCtxInsertApiAsChild.Size = new System.Drawing.Size(358, 22);
this.sbStatusBarText.SetStatusBarText(this.miCtxInsertApiAsChild, "Insert the API content as a child of the selected topic");
this.miCtxInsertApiAsChild.Text = "Insert API content as a &child of selected topic";
this.miCtxInsertApiAsChild.Click += new System.EventHandler(this.ApiInsertionPoint_Click);
//
// miCtxClearInsertionPoint
//
this.miCtxClearInsertionPoint.Name = "miCtxClearInsertionPoint";
this.miCtxClearInsertionPoint.Size = new System.Drawing.Size(358, 22);
this.sbStatusBarText.SetStatusBarText(this.miCtxClearInsertionPoint, "Clear the API insertion point");
this.miCtxClearInsertionPoint.Text = "Clear the API &insertion point";
this.miCtxClearInsertionPoint.Click += new System.EventHandler(this.ApiInsertionPoint_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(323, 6);
//
// miMoveUp
//
this.miMoveUp.Image = global::SandcastleBuilder.Gui.Properties.Resources.MoveUp;
this.miMoveUp.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miMoveUp.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miMoveUp.Name = "miMoveUp";
this.miMoveUp.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miMoveUp, "Move the selected topic up within its group");
this.miMoveUp.Text = "Move &Up";
this.miMoveUp.Click += new System.EventHandler(this.tsbMoveItem_Click);
//
// miMoveDown
//
this.miMoveDown.Image = global::SandcastleBuilder.Gui.Properties.Resources.MoveDown;
this.miMoveDown.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miMoveDown.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miMoveDown.Name = "miMoveDown";
this.miMoveDown.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miMoveDown, "Move the selected topic down within its group");
this.miMoveDown.Text = "Move Do&wn";
this.miMoveDown.Click += new System.EventHandler(this.tsbMoveItem_Click);
//
// toolStripMenuItem9
//
this.toolStripMenuItem9.Name = "toolStripMenuItem9";
this.toolStripMenuItem9.Size = new System.Drawing.Size(323, 6);
//
// miAddSibling
//
this.miAddSibling.DropDown = this.cmsNewSiblingTopic;
this.miAddSibling.Image = global::SandcastleBuilder.Gui.Properties.Resources.AddRootItem;
this.miAddSibling.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miAddSibling.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miAddSibling.Name = "miAddSibling";
this.miAddSibling.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miAddSibling, "Add a new topic as a sibling of the selected item");
this.miAddSibling.Text = "&Add Sibling Topic";
//
// cmsNewSiblingTopic
//
this.cmsNewSiblingTopic.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miStandardSibling,
this.miCustomSibling,
this.toolStripMenuItem2,
this.addExistingTopicFileToolStripMenuItem,
this.addAllTopicsInFolderToolStripMenuItem,
this.toolStripSeparator6,
this.miAddEmptySibling});
this.cmsNewSiblingTopic.Name = "cmsNewTopic";
this.cmsNewSiblingTopic.OwnerItem = this.miAddSibling;
this.cmsNewSiblingTopic.Size = new System.Drawing.Size(262, 136);
//
// miStandardSibling
//
this.miStandardSibling.Name = "miStandardSibling";
this.miStandardSibling.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.miStandardSibling, "Select a standard template");
this.miStandardSibling.Text = "Standard Templates";
//
// miCustomSibling
//
this.miCustomSibling.Name = "miCustomSibling";
this.miCustomSibling.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.miCustomSibling, "Select a custom template");
this.miCustomSibling.Text = "Custom Templates";
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(258, 6);
//
// addExistingTopicFileToolStripMenuItem
//
this.addExistingTopicFileToolStripMenuItem.Name = "addExistingTopicFileToolStripMenuItem";
this.addExistingTopicFileToolStripMenuItem.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.addExistingTopicFileToolStripMenuItem, "Add an existing topic file");
this.addExistingTopicFileToolStripMenuItem.Text = "&Add Existing Topic File...";
this.addExistingTopicFileToolStripMenuItem.Click += new System.EventHandler(this.AddExistingTopicFile_Click);
//
// addAllTopicsInFolderToolStripMenuItem
//
this.addAllTopicsInFolderToolStripMenuItem.Name = "addAllTopicsInFolderToolStripMenuItem";
this.addAllTopicsInFolderToolStripMenuItem.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.addAllTopicsInFolderToolStripMenuItem, "Add all topics found in a folder and its subfolders");
this.addAllTopicsInFolderToolStripMenuItem.Text = "Add All Topics in &Folder...";
this.addAllTopicsInFolderToolStripMenuItem.Click += new System.EventHandler(this.AddAllTopicsInFolder_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(258, 6);
//
// miAddEmptySibling
//
this.miAddEmptySibling.Image = global::SandcastleBuilder.Gui.Properties.Resources.AddRootItem;
this.miAddEmptySibling.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miAddEmptySibling.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miAddEmptySibling.Name = "miAddEmptySibling";
this.miAddEmptySibling.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.miAddEmptySibling, "Add a container not associated with a topic file");
this.miAddEmptySibling.Text = "Add &Empty Container Node";
this.miAddEmptySibling.Click += new System.EventHandler(this.tsbAddTopic_ButtonClick);
//
// tsbAddSiblingTopic
//
this.tsbAddSiblingTopic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbAddSiblingTopic.DropDown = this.cmsNewSiblingTopic;
this.tsbAddSiblingTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.AddRootItem;
this.tsbAddSiblingTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbAddSiblingTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbAddSiblingTopic.Name = "tsbAddSiblingTopic";
this.tsbAddSiblingTopic.Size = new System.Drawing.Size(32, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbAddSiblingTopic, "Add a topic as a sibling of the selected item");
this.tsbAddSiblingTopic.ToolTipText = "Add topic as sibling of selected item";
this.tsbAddSiblingTopic.ButtonClick += new System.EventHandler(this.tsbAddTopic_ButtonClick);
//
// miAddChild
//
this.miAddChild.DropDown = this.cmsNewChildTopic;
this.miAddChild.Image = global::SandcastleBuilder.Gui.Properties.Resources.AddChildItem;
this.miAddChild.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miAddChild.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miAddChild.Name = "miAddChild";
this.miAddChild.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miAddChild, "Add a topic as a child of the selected topic");
this.miAddChild.Text = "Add C&hild Topic";
//
// cmsNewChildTopic
//
this.cmsNewChildTopic.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miStandardChild,
this.miCustomChild,
this.toolStripSeparator7,
this.toolStripMenuItem5,
this.toolStripMenuItem6,
this.toolStripSeparator8,
this.miAddEmptyChild});
this.cmsNewChildTopic.Name = "cmsNewTopic";
this.cmsNewChildTopic.OwnerItem = this.tsbAddChildTopic;
this.cmsNewChildTopic.Size = new System.Drawing.Size(262, 136);
//
// miStandardChild
//
this.miStandardChild.Name = "miStandardChild";
this.miStandardChild.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.miStandardChild, "Select a standard template");
this.miStandardChild.Text = "Standard Templates";
//
// miCustomChild
//
this.miCustomChild.Name = "miCustomChild";
this.miCustomChild.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.miCustomChild, "Select a custom template");
this.miCustomChild.Text = "Custom Templates";
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(258, 6);
//
// toolStripMenuItem5
//
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.toolStripMenuItem5, "Add an existing topic file");
this.toolStripMenuItem5.Text = "&Add Existing Topic File...";
this.toolStripMenuItem5.Click += new System.EventHandler(this.AddExistingTopicFile_Click);
//
// toolStripMenuItem6
//
this.toolStripMenuItem6.Name = "toolStripMenuItem6";
this.toolStripMenuItem6.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.toolStripMenuItem6, "Add all topics found in a folder and its subfolders");
this.toolStripMenuItem6.Text = "Add All Topics in &Folder...";
this.toolStripMenuItem6.Click += new System.EventHandler(this.AddAllTopicsInFolder_Click);
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
this.toolStripSeparator8.Size = new System.Drawing.Size(258, 6);
//
// miAddEmptyChild
//
this.miAddEmptyChild.Image = global::SandcastleBuilder.Gui.Properties.Resources.AddChildItem;
this.miAddEmptyChild.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miAddEmptyChild.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miAddEmptyChild.Name = "miAddEmptyChild";
this.miAddEmptyChild.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.miAddEmptyChild, "Add a container not associated with a topic file");
this.miAddEmptyChild.Text = "Add &Empty Container Node";
this.miAddEmptyChild.Click += new System.EventHandler(this.tsbAddTopic_ButtonClick);
//
// miAssociateTopic
//
this.miAssociateTopic.Name = "miAssociateTopic";
this.miAssociateTopic.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miAssociateTopic, "Associate a topic file with the selected entry");
this.miAssociateTopic.Text = "Ass&ociate Topic File...";
this.miAssociateTopic.Click += new System.EventHandler(this.miAssociateTopic_Click);
//
// miClearTopic
//
this.miClearTopic.Name = "miClearTopic";
this.miClearTopic.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miClearTopic, "Clear the topic assoicated with the selected entry");
this.miClearTopic.Text = "Clear Topic Assoc&iation";
this.miClearTopic.Click += new System.EventHandler(this.miClearTopic_Click);
//
// miRefreshAssociations
//
this.miRefreshAssociations.Name = "miRefreshAssociations";
this.miRefreshAssociations.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miRefreshAssociations, "Refresh the file associations to reflect changes made to the project");
this.miRefreshAssociations.Text = "&Refresh Associations";
this.miRefreshAssociations.Click += new System.EventHandler(this.miRefreshAssociations_Click);
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.Size = new System.Drawing.Size(323, 6);
//
// miDelete
//
this.miDelete.Image = global::SandcastleBuilder.Gui.Properties.Resources.Delete;
this.miDelete.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miDelete.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miDelete.Name = "miDelete";
this.miDelete.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miDelete, "Delete the selected topic");
this.miDelete.Text = "&Delete";
this.miDelete.Click += new System.EventHandler(this.tsbDeleteTopic_Click);
//
// toolStripMenuItem7
//
this.toolStripMenuItem7.Name = "toolStripMenuItem7";
this.toolStripMenuItem7.Size = new System.Drawing.Size(323, 6);
//
// miCut
//
this.miCut.Image = global::SandcastleBuilder.Gui.Properties.Resources.Cut;
this.miCut.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miCut.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miCut.Name = "miCut";
this.miCut.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miCut, "Cut the selected topic to the clipboard");
this.miCut.Text = "&Cut";
this.miCut.Click += new System.EventHandler(this.tsbCutCopy_Click);
//
// miPaste
//
this.miPaste.Image = global::SandcastleBuilder.Gui.Properties.Resources.Paste;
this.miPaste.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miPaste.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miPaste.Name = "miPaste";
this.miPaste.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miPaste, "Paste the topic on the clipboard as a sibling of the selected topic");
this.miPaste.Text = "Pa&ste as Sibling";
this.miPaste.Click += new System.EventHandler(this.tsbPaste_ButtonClick);
//
// miCopyAsLink
//
this.miCopyAsLink.Name = "miCopyAsLink";
this.miCopyAsLink.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miCopyAsLink, "Copy as a topic link");
this.miCopyAsLink.Text = "Cop&y as Topic Link";
this.miCopyAsLink.Click += new System.EventHandler(this.miCopyAsLink_Click);
//
// toolStripSeparator10
//
this.toolStripSeparator10.Name = "toolStripSeparator10";
this.toolStripSeparator10.Size = new System.Drawing.Size(323, 6);
//
// miEditTopic
//
this.miEditTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.PageEdit;
this.miEditTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miEditTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miEditTopic.Name = "miEditTopic";
this.miEditTopic.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miEditTopic, "Edit the selected topic");
this.miEditTopic.Text = "&Edit Topic";
this.miEditTopic.Click += new System.EventHandler(this.tsbEditTopic_Click);
//
// miSortTopics
//
this.miSortTopics.Name = "miSortTopics";
this.miSortTopics.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miSortTopics, "Sort this topics and its siblings by their display title");
this.miSortTopics.Text = "Sor&t Topics";
this.miSortTopics.Click += new System.EventHandler(this.miSortTopics_Click);
//
// toolStripSeparator11
//
this.toolStripSeparator11.Name = "toolStripSeparator11";
this.toolStripSeparator11.Size = new System.Drawing.Size(323, 6);
//
// miHelp
//
this.miHelp.Image = global::SandcastleBuilder.Gui.Properties.Resources.About;
this.miHelp.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miHelp.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miHelp.Name = "miHelp";
this.miHelp.Size = new System.Drawing.Size(326, 26);
this.sbStatusBarText.SetStatusBarText(this.miHelp, "View help for this form");
this.miHelp.Text = "Help";
this.miHelp.Click += new System.EventHandler(this.tsbHelp_Click);
//
// tsbAddChildTopic
//
this.tsbAddChildTopic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbAddChildTopic.DropDown = this.cmsNewChildTopic;
this.tsbAddChildTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.AddChildItem;
this.tsbAddChildTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbAddChildTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbAddChildTopic.Name = "tsbAddChildTopic";
this.tsbAddChildTopic.Size = new System.Drawing.Size(32, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbAddChildTopic, "Add a topic as a child of the selected item");
this.tsbAddChildTopic.ToolTipText = "Add topic as child of selected item";
this.tsbAddChildTopic.ButtonClick += new System.EventHandler(this.tsbAddTopic_ButtonClick);
//
// pgProps
//
this.pgProps.Dock = System.Windows.Forms.DockStyle.Fill;
this.pgProps.Location = new System.Drawing.Point(0, 0);
this.pgProps.Name = "pgProps";
this.pgProps.PropertyNamePaneWidth = 150;
this.pgProps.Size = new System.Drawing.Size(383, 295);
this.sbStatusBarText.SetStatusBarText(this.pgProps, "Properties for the selected content item");
this.pgProps.TabIndex = 0;
this.pgProps.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.pgProps_PropertyValueChanged);
//
// tsTopics
//
this.tsTopics.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.tsTopics.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsbDefaultTopic,
this.tsbApiInsertionPoint,
this.toolStripSeparator1,
this.tsbMoveUp,
this.tsbMoveDown,
this.toolStripSeparator2,
this.tsbAddSiblingTopic,
this.tsbAddChildTopic,
this.toolStripSeparator4,
this.tsbDeleteTopic,
this.toolStripSeparator3,
this.tsbCut,
this.tsbPaste,
this.toolStripSeparator9,
this.tsbEditTopic,
this.toolStripSeparator5,
this.tsbHelp});
this.tsTopics.Location = new System.Drawing.Point(0, 0);
this.tsTopics.Name = "tsTopics";
this.tsTopics.Size = new System.Drawing.Size(385, 27);
this.tsTopics.TabIndex = 3;
//
// tsbApiInsertionPoint
//
this.tsbApiInsertionPoint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbApiInsertionPoint.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miInsertApiAfter,
this.miInsertApiBefore,
this.miInsertApiAsChild,
this.miClearApiInsertionPoint});
this.tsbApiInsertionPoint.Image = global::SandcastleBuilder.Gui.Properties.Resources.InsertApiAfter;
this.tsbApiInsertionPoint.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbApiInsertionPoint.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbApiInsertionPoint.Name = "tsbApiInsertionPoint";
this.tsbApiInsertionPoint.Size = new System.Drawing.Size(32, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbApiInsertionPoint, "Set the API content insertion point");
this.tsbApiInsertionPoint.ToolTipText = "Set API insertion point";
this.tsbApiInsertionPoint.ButtonClick += new System.EventHandler(this.ApiInsertionPoint_Click);
//
// miInsertApiAfter
//
this.miInsertApiAfter.Image = global::SandcastleBuilder.Gui.Properties.Resources.InsertApiAfter;
this.miInsertApiAfter.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miInsertApiAfter.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miInsertApiAfter.Name = "miInsertApiAfter";
this.miInsertApiAfter.Size = new System.Drawing.Size(375, 24);
this.sbStatusBarText.SetStatusBarText(this.miInsertApiAfter, "Insert the API content after the selected topic");
this.miInsertApiAfter.Text = "Insert API content &after selected topic";
this.miInsertApiAfter.Click += new System.EventHandler(this.ApiInsertionPoint_Click);
//
// miInsertApiBefore
//
this.miInsertApiBefore.Image = global::SandcastleBuilder.Gui.Properties.Resources.InsertApiBefore;
this.miInsertApiBefore.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miInsertApiBefore.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miInsertApiBefore.Name = "miInsertApiBefore";
this.miInsertApiBefore.Size = new System.Drawing.Size(375, 24);
this.sbStatusBarText.SetStatusBarText(this.miInsertApiBefore, "Insert the API content before the selected topic");
this.miInsertApiBefore.Text = "Insert API content &before selected topic";
this.miInsertApiBefore.Click += new System.EventHandler(this.ApiInsertionPoint_Click);
//
// miInsertApiAsChild
//
this.miInsertApiAsChild.Image = global::SandcastleBuilder.Gui.Properties.Resources.InsertApiAsChild;
this.miInsertApiAsChild.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miInsertApiAsChild.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miInsertApiAsChild.Name = "miInsertApiAsChild";
this.miInsertApiAsChild.Size = new System.Drawing.Size(375, 24);
this.sbStatusBarText.SetStatusBarText(this.miInsertApiAsChild, "Insert the API content as a child of the selected topic");
this.miInsertApiAsChild.Text = "Insert API content as a &child of selected topic";
this.miInsertApiAsChild.Click += new System.EventHandler(this.ApiInsertionPoint_Click);
//
// miClearApiInsertionPoint
//
this.miClearApiInsertionPoint.Name = "miClearApiInsertionPoint";
this.miClearApiInsertionPoint.Size = new System.Drawing.Size(375, 24);
this.sbStatusBarText.SetStatusBarText(this.miClearApiInsertionPoint, "Clear the API insertion point");
this.miClearApiInsertionPoint.Text = "Clear the API &insertion point";
this.miClearApiInsertionPoint.Click += new System.EventHandler(this.ApiInsertionPoint_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 27);
//
// tsbMoveUp
//
this.tsbMoveUp.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbMoveUp.Image = global::SandcastleBuilder.Gui.Properties.Resources.MoveUp;
this.tsbMoveUp.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbMoveUp.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbMoveUp.Name = "tsbMoveUp";
this.tsbMoveUp.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbMoveUp, "Move the selected topic up within its group");
this.tsbMoveUp.ToolTipText = "Move the selected topic up within its group";
this.tsbMoveUp.Click += new System.EventHandler(this.tsbMoveItem_Click);
//
// tsbMoveDown
//
this.tsbMoveDown.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbMoveDown.Image = global::SandcastleBuilder.Gui.Properties.Resources.MoveDown;
this.tsbMoveDown.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbMoveDown.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbMoveDown.Name = "tsbMoveDown";
this.tsbMoveDown.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbMoveDown, "Move the selected topic down within its group");
this.tsbMoveDown.ToolTipText = "Move the selected topic down within its group";
this.tsbMoveDown.Click += new System.EventHandler(this.tsbMoveItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 27);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(6, 27);
//
// tsbDeleteTopic
//
this.tsbDeleteTopic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbDeleteTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.Delete;
this.tsbDeleteTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbDeleteTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbDeleteTopic.Name = "tsbDeleteTopic";
this.tsbDeleteTopic.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbDeleteTopic, "Delete the selected topic and all of its children");
this.tsbDeleteTopic.ToolTipText = "Delete topic and all children";
this.tsbDeleteTopic.Click += new System.EventHandler(this.tsbDeleteTopic_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(6, 27);
//
// tsbCut
//
this.tsbCut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbCut.Image = global::SandcastleBuilder.Gui.Properties.Resources.Cut;
this.tsbCut.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbCut.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbCut.Name = "tsbCut";
this.tsbCut.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbCut, "Cut the selected topic and its children to the clipboard");
this.tsbCut.ToolTipText = "Cut topic and children to clipboard";
this.tsbCut.Click += new System.EventHandler(this.tsbCutCopy_Click);
//
// tsbPaste
//
this.tsbPaste.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbPaste.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmiPasteAsSibling,
this.tsmiPasteAsChild});
this.tsbPaste.Image = global::SandcastleBuilder.Gui.Properties.Resources.Paste;
this.tsbPaste.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbPaste.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbPaste.Name = "tsbPaste";
this.tsbPaste.Size = new System.Drawing.Size(32, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbPaste, "Paste the clipboard item as a sibling of the selected item");
this.tsbPaste.ToolTipText = "Paste clipboard item as sibling of selected item";
this.tsbPaste.ButtonClick += new System.EventHandler(this.tsbPaste_ButtonClick);
//
// tsmiPasteAsSibling
//
this.tsmiPasteAsSibling.Image = global::SandcastleBuilder.Gui.Properties.Resources.Paste;
this.tsmiPasteAsSibling.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsmiPasteAsSibling.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsmiPasteAsSibling.Name = "tsmiPasteAsSibling";
this.tsmiPasteAsSibling.Size = new System.Drawing.Size(179, 24);
this.sbStatusBarText.SetStatusBarText(this.tsmiPasteAsSibling, "Paste the clipboard item as a sibiling of the selected item");
this.tsmiPasteAsSibling.Text = "Paste as sibling";
this.tsmiPasteAsSibling.Click += new System.EventHandler(this.tsbPaste_ButtonClick);
//
// tsmiPasteAsChild
//
this.tsmiPasteAsChild.Name = "tsmiPasteAsChild";
this.tsmiPasteAsChild.Size = new System.Drawing.Size(179, 24);
this.sbStatusBarText.SetStatusBarText(this.tsmiPasteAsChild, "Paste the clipboard item as a child of the selected item");
this.tsmiPasteAsChild.Text = "Paste as child";
this.tsmiPasteAsChild.Click += new System.EventHandler(this.tsbPaste_ButtonClick);
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
this.toolStripSeparator9.Size = new System.Drawing.Size(6, 27);
//
// tsbEditTopic
//
this.tsbEditTopic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbEditTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.PageEdit;
this.tsbEditTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbEditTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbEditTopic.Name = "tsbEditTopic";
this.tsbEditTopic.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbEditTopic, "Edit the selected topic");
this.tsbEditTopic.ToolTipText = "Edit the selected topic";
this.tsbEditTopic.Click += new System.EventHandler(this.tsbEditTopic_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(6, 27);
//
// tsbHelp
//
this.tsbHelp.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbHelp.Image = global::SandcastleBuilder.Gui.Properties.Resources.About;
this.tsbHelp.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbHelp.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbHelp.Name = "tsbHelp";
this.tsbHelp.Size = new System.Drawing.Size(24, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbHelp, "View help for this editor");
this.tsbHelp.ToolTipText = "View help for this editor";
this.tsbHelp.Click += new System.EventHandler(this.tsbHelp_Click);
//
// txtFindId
//
this.txtFindId.AllowDrop = true;
this.txtFindId.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtFindId.Location = new System.Drawing.Point(74, 28);
this.txtFindId.MaxLength = 36;
this.txtFindId.Name = "txtFindId";
this.txtFindId.Size = new System.Drawing.Size(305, 22);
this.sbStatusBarText.SetStatusBarText(this.txtFindId, "Find ID: Enter the ID of the item to find and hit Enter");
this.txtFindId.TabIndex = 1;
this.txtFindId.DragDrop += new System.Windows.Forms.DragEventHandler(this.txtFindId_DragDrop);
this.txtFindId.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtFindId_KeyDown);
this.txtFindId.DragEnter += new System.Windows.Forms.DragEventHandler(this.txtFindId_DragEnter);
//
// label1
//
this.label1.Location = new System.Drawing.Point(5, 28);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(63, 23);
this.label1.TabIndex = 0;
this.label1.Text = "Find &ID";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// splitContainer1
//
this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer1.Location = new System.Drawing.Point(1, 56);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.tvContent);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.pgProps);
this.splitContainer1.Size = new System.Drawing.Size(383, 603);
this.splitContainer1.SplitterDistance = 300;
this.splitContainer1.SplitterWidth = 8;
this.splitContainer1.TabIndex = 2;
//
// tsbDefaultTopic
//
this.tsbDefaultTopic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbDefaultTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.DefaultTopic;
this.tsbDefaultTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbDefaultTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbDefaultTopic.Name = "tsbDefaultTopic";
this.tsbDefaultTopic.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbDefaultTopic, "Toggle the default topic");
this.tsbDefaultTopic.ToolTipText = "Toggle the default topic";
this.tsbDefaultTopic.Click += new System.EventHandler(this.tsbDefaultTopic_Click);
//
// ContentLayoutWindow
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
this.ClientSize = new System.Drawing.Size(385, 660);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.tsTopics);
this.Controls.Add(this.txtFindId);
this.Controls.Add(this.label1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimizeBox = false;
this.Name = "ContentLayoutWindow";
this.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.DockLeft;
this.ShowInTaskbar = false;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ContentLayoutWindow_FormClosing);
this.cmsTopics.ResumeLayout(false);
this.cmsNewSiblingTopic.ResumeLayout(false);
this.cmsNewChildTopic.ResumeLayout(false);
this.tsTopics.ResumeLayout(false);
this.tsTopics.PerformLayout();
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TreeView tvContent;
private SandcastleBuilder.Utils.Controls.StatusBarTextProvider sbStatusBarText;
private System.Windows.Forms.ImageList ilImages;
private System.Windows.Forms.ContextMenuStrip cmsTopics;
private System.Windows.Forms.ToolStripMenuItem miCut;
private System.Windows.Forms.ToolStripMenuItem miPasteAsChild;
private System.Windows.Forms.ToolStripMenuItem miPaste;
private System.Windows.Forms.ToolStripMenuItem miAddSibling;
private System.Windows.Forms.ToolStripMenuItem miAddChild;
private System.Windows.Forms.ToolStripMenuItem miDelete;
private System.Windows.Forms.ToolStripMenuItem miMoveUp;
private System.Windows.Forms.ToolStripMenuItem miMoveDown;
private System.Windows.Forms.ToolStripMenuItem miDefaultTopic;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem7;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem9;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private SandcastleBuilder.Utils.Controls.CustomPropertyGrid pgProps;
private System.Windows.Forms.ToolStripMenuItem miApiContent;
private System.Windows.Forms.ToolStrip tsTopics;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton tsbMoveUp;
private System.Windows.Forms.ToolStripButton tsbMoveDown;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripSplitButton tsbAddSiblingTopic;
private System.Windows.Forms.ToolStripSplitButton tsbAddChildTopic;
private System.Windows.Forms.ToolStripButton tsbDeleteTopic;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripButton tsbCut;
private System.Windows.Forms.ToolStripSplitButton tsbPaste;
private System.Windows.Forms.ToolStripMenuItem tsmiPasteAsChild;
private System.Windows.Forms.ToolStripMenuItem tsmiPasteAsSibling;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ContextMenuStrip cmsNewSiblingTopic;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem addExistingTopicFileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addAllTopicsInFolderToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripMenuItem miAddEmptySibling;
private System.Windows.Forms.ContextMenuStrip cmsNewChildTopic;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem5;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem6;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripMenuItem miAddEmptyChild;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
private System.Windows.Forms.ToolStripButton tsbEditTopic;
private System.Windows.Forms.ToolStripMenuItem miStandardSibling;
private System.Windows.Forms.ToolStripMenuItem miCustomSibling;
private System.Windows.Forms.ToolStripMenuItem miStandardChild;
private System.Windows.Forms.ToolStripMenuItem miCustomChild;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator10;
private System.Windows.Forms.ToolStripMenuItem miEditTopic;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtFindId;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.ToolStripMenuItem miSortTopics;
private System.Windows.Forms.ToolStripMenuItem miClearTopic;
private System.Windows.Forms.ToolStripMenuItem miAssociateTopic;
private System.Windows.Forms.ToolStripMenuItem miCopyAsLink;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator11;
private System.Windows.Forms.ToolStripMenuItem miHelp;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripButton tsbHelp;
private System.Windows.Forms.ToolStripMenuItem miRefreshAssociations;
private System.Windows.Forms.ToolStripSplitButton tsbApiInsertionPoint;
private System.Windows.Forms.ToolStripMenuItem miInsertApiBefore;
private System.Windows.Forms.ToolStripMenuItem miInsertApiAfter;
private System.Windows.Forms.ToolStripMenuItem miInsertApiAsChild;
private System.Windows.Forms.ToolStripMenuItem miClearApiInsertionPoint;
private System.Windows.Forms.ToolStripMenuItem miCtxInsertApiAfter;
private System.Windows.Forms.ToolStripMenuItem miCtxInsertApiBefore;
private System.Windows.Forms.ToolStripMenuItem miCtxInsertApiAsChild;
private System.Windows.Forms.ToolStripMenuItem miCtxClearInsertionPoint;
private System.Windows.Forms.ToolStripMenuItem miMarkAsMSHVRoot;
private System.Windows.Forms.ToolStripButton tsbDefaultTopic;
}
}
| |
// 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.Runtime.CompilerServices;
namespace System.Numerics
{
// This file contains the definitions for all of the JIT intrinsic methods and properties that are recognized by the current x64 JIT compiler.
// The implementation defined here is used in any circumstance where the JIT fails to recognize these members as intrinsic.
// The JIT recognizes these methods and properties by name and signature: if either is changed, the JIT will no longer recognize the member.
// Some methods declared here are not strictly intrinsic, but delegate to an intrinsic method. For example, only one overload of CopyTo()
// is actually recognized by the JIT, but both are here for simplicity.
public partial struct Vector3
{
/// <summary>
/// The X component of the vector.
/// </summary>
public float X;
/// <summary>
/// The Y component of the vector.
/// </summary>
public float Y;
/// <summary>
/// The Z component of the vector.
/// </summary>
public float Z;
#region Constructors
/// <summary>
/// Constructs a vector whose elements are all the single specified value.
/// </summary>
/// <param name="value">The element to fill the vector with.</param>
[Intrinsic]
public Vector3(float value) : this(value, value, value) { }
/// <summary>
/// Constructs a Vector3 from the given Vector2 and a third value.
/// </summary>
/// <param name="value">The Vector to extract X and Y components from.</param>
/// <param name="z">The Z component.</param>
public Vector3(Vector2 value, float z) : this(value.X, value.Y, z) { }
/// <summary>
/// Constructs a vector with the given individual elements.
/// </summary>
/// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param>
/// <param name="z">The Z component.</param>
[Intrinsic]
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
#endregion Constructors
#region Public Instance Methods
/// <summary>
/// Copies the contents of the vector into the given array.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(float[] array)
{
CopyTo(array, 0);
}
/// <summary>
/// Copies the contents of the vector into the given array, starting from index.
/// </summary>
/// <exception cref="ArgumentNullException">If array is null.</exception>
/// <exception cref="RankException">If array is multidimensional.</exception>
/// <exception cref="ArgumentOutOfRangeException">If index is greater than end of the array or index is less than zero.</exception>
/// <exception cref="ArgumentException">If number of elements in source vector is greater than those available in destination array.</exception>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(float[] array, int index)
{
if (array == null)
{
// Match the JIT's exception type here. For perf, a NullReference is thrown instead of an ArgumentNull.
throw new NullReferenceException(SR.Arg_NullArgumentNullRef);
}
if (index < 0 || index >= array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.Arg_ArgumentOutOfRangeException, index));
}
if ((array.Length - index) < 3)
{
throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index));
}
array[index] = X;
array[index + 1] = Y;
array[index + 2] = Z;
}
/// <summary>
/// Returns a boolean indicating whether the given Vector3 is equal to this Vector3 instance.
/// </summary>
/// <param name="other">The Vector3 to compare this instance to.</param>
/// <returns>True if the other Vector3 is equal to this instance; False otherwise.</returns>
[Intrinsic]
public bool Equals(Vector3 other)
{
return X == other.X &&
Y == other.Y &&
Z == other.Z;
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="vector1">The first vector.</param>
/// <param name="vector2">The second vector.</param>
/// <returns>The dot product.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector3 vector1, Vector3 vector2)
{
return vector1.X * vector2.X +
vector1.Y * vector2.Y +
vector1.Z * vector2.Z;
}
/// <summary>
/// Returns a vector whose elements are the minimum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The minimized vector.</returns>
[Intrinsic]
public static Vector3 Min(Vector3 value1, Vector3 value2)
{
return new Vector3(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y,
(value1.Z < value2.Z) ? value1.Z : value2.Z);
}
/// <summary>
/// Returns a vector whose elements are the maximum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The maximized vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Max(Vector3 value1, Vector3 value2)
{
return new Vector3(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y,
(value1.Z > value2.Z) ? value1.Z : value2.Z);
}
/// <summary>
/// Returns a vector whose elements are the absolute values of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The absolute value vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Abs(Vector3 value)
{
return new Vector3(MathF.Abs(value.X), MathF.Abs(value.Y), MathF.Abs(value.Z));
}
/// <summary>
/// Returns a vector whose elements are the square root of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The square root vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 SquareRoot(Vector3 value)
{
return new Vector3(MathF.Sqrt(value.X), MathF.Sqrt(value.Y), MathF.Sqrt(value.Z));
}
#endregion Public Static Methods
#region Public Static Operators
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator +(Vector3 left, Vector3 right)
{
return new Vector3(left.X + right.X, left.Y + right.Y, left.Z + right.Z);
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator -(Vector3 left, Vector3 right)
{
return new Vector3(left.X - right.X, left.Y - right.Y, left.Z - right.Z);
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Vector3 left, Vector3 right)
{
return new Vector3(left.X * right.X, left.Y * right.Y, left.Z * right.Z);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Vector3 left, float right)
{
return left * new Vector3(right);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(float left, Vector3 right)
{
return new Vector3(left) * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator /(Vector3 left, Vector3 right)
{
return new Vector3(left.X / right.X, left.Y / right.Y, left.Z / right.Z);
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator /(Vector3 value1, float value2)
{
return value1 / new Vector3(value2);
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator -(Vector3 value)
{
return Zero - value;
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are equal; False otherwise.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector3 left, Vector3 right)
{
return (left.X == right.X &&
left.Y == right.Y &&
left.Z == right.Z);
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are not equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are not equal; False if they are equal.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Vector3 left, Vector3 right)
{
return (left.X != right.X ||
left.Y != right.Y ||
left.Z != right.Z);
}
#endregion Public Static Operators
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Primitives
{
/// <summary>
/// Represents a contract name and metadata-based import
/// required by a <see cref="ComposablePart"/> object.
/// </summary>
public class ContractBasedImportDefinition : ImportDefinition
{
// Unlike contract name, both metadata and required metadata has a sensible default; set it to an empty
// enumerable, so that derived definitions only need to override ContractName by default.
private readonly IEnumerable<KeyValuePair<string, Type>> _requiredMetadata = Enumerable.Empty<KeyValuePair<string, Type>>();
private Expression<Func<ExportDefinition, bool>> _constraint;
private readonly CreationPolicy _requiredCreationPolicy = CreationPolicy.Any;
private readonly string _requiredTypeIdentity = null;
private bool _isRequiredMetadataValidated = false;
/// <summary>
/// Initializes a new instance of the <see cref="ContractBasedImportDefinition"/> class.
/// </summary>
/// <remarks>
/// <note type="inheritinfo">
/// Derived types calling this constructor can optionally override the
/// <see cref="ImportDefinition.ContractName"/>, <see cref="RequiredTypeIdentity"/>,
/// <see cref="RequiredMetadata"/>, <see cref="ImportDefinition.Cardinality"/>,
/// <see cref="ImportDefinition.IsPrerequisite"/>, <see cref="ImportDefinition.IsRecomposable"/>
/// and <see cref="RequiredCreationPolicy"/> properties.
/// </note>
/// </remarks>
protected ContractBasedImportDefinition()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ContractBasedImportDefinition"/> class
/// with the specified contract name, required metadataq, cardinality, value indicating
/// if the import definition is recomposable and a value indicating if the import definition
/// is a prerequisite.
/// </summary>
/// <param name="contractName">
/// A <see cref="string"/> containing the contract name of the
/// <see cref="Export"/> required by the <see cref="ContractBasedImportDefinition"/>.
/// </param>
/// <param name="requiredTypeIdentity">
/// The type identity of the export type expected. Use <see cref="AttributedModelServices.GetTypeIdentity(Type)"/>
/// to generate a type identity for a given type. If no specific type is required pass <see langword="null"/>.
/// </param>
/// <param name="requiredMetadata">
/// An <see cref="IEnumerable{T}"/> of <see cref="string"/> objects containing
/// the metadata names of the <see cref="Export"/> required by the
/// <see cref="ContractBasedImportDefinition"/>; or <see langword="null"/> to
/// set the <see cref="RequiredMetadata"/> property to an empty <see cref="IEnumerable{T}"/>.
/// </param>
/// <param name="cardinality">
/// One of the <see cref="ImportCardinality"/> values indicating the
/// cardinality of the <see cref="Export"/> objects required by the
/// <see cref="ContractBasedImportDefinition"/>.
/// </param>
/// <param name="isRecomposable">
/// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> can be satisfied
/// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise,
/// <see langword="false"/>.
/// </param>
/// <param name="isPrerequisite">
/// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> is required to be
/// satisfied before a <see cref="ComposablePart"/> can start producing exported
/// objects; otherwise, <see langword="false"/>.
/// </param>
/// <param name="requiredCreationPolicy">
/// A value indicating that the importer requires a specific <see cref="CreationPolicy"/> for
/// the exports used to satisfy this import. If no specific <see cref="CreationPolicy"/> is needed
/// pass the default <see cref="CreationPolicy.Any"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="contractName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="contractName"/> is an empty string ("").
/// <para>
/// -or-
/// </para>
/// <paramref name="requiredMetadata"/> contains an element that is <see langword="null"/>.
/// <para>
/// -or-
/// </para>
/// <paramref name="cardinality"/> is not one of the <see cref="ImportCardinality"/>
/// values.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy)
: this(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, MetadataServices.EmptyMetadata)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ContractBasedImportDefinition"/> class
/// with the specified contract name, required metadataq, cardinality, value indicating
/// if the import definition is recomposable and a value indicating if the import definition
/// is a prerequisite.
/// </summary>
/// <param name="contractName">
/// A <see cref="string"/> containing the contract name of the
/// <see cref="Export"/> required by the <see cref="ContractBasedImportDefinition"/>.
/// </param>
/// <param name="requiredTypeIdentity">
/// The type identity of the export type expected. Use <see cref="AttributedModelServices.GetTypeIdentity(Type)"/>
/// to generate a type identity for a given type. If no specific type is required pass <see langword="null"/>.
/// </param>
/// <param name="requiredMetadata">
/// An <see cref="IEnumerable{T}"/> of <see cref="string"/> objects containing
/// the metadata names of the <see cref="Export"/> required by the
/// <see cref="ContractBasedImportDefinition"/>; or <see langword="null"/> to
/// set the <see cref="RequiredMetadata"/> property to an empty <see cref="IEnumerable{T}"/>.
/// </param>
/// <param name="cardinality">
/// One of the <see cref="ImportCardinality"/> values indicating the
/// cardinality of the <see cref="Export"/> objects required by the
/// <see cref="ContractBasedImportDefinition"/>.
/// </param>
/// <param name="isRecomposable">
/// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> can be satisfied
/// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise,
/// <see langword="false"/>.
/// </param>
/// <param name="isPrerequisite">
/// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> is required to be
/// satisfied before a <see cref="ComposablePart"/> can start producing exported
/// objects; otherwise, <see langword="false"/>.
/// </param>
/// <param name="requiredCreationPolicy">
/// A value indicating that the importer requires a specific <see cref="CreationPolicy"/> for
/// the exports used to satisfy this import. If no specific <see cref="CreationPolicy"/> is needed
/// pass the default <see cref="CreationPolicy.Any"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="contractName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="contractName"/> is an empty string ("").
/// <para>
/// -or-
/// </para>
/// <paramref name="requiredMetadata"/> contains an element that is <see langword="null"/>.
/// <para>
/// -or-
/// </para>
/// <paramref name="cardinality"/> is not one of the <see cref="ImportCardinality"/>
/// values.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy, IDictionary<string, object> metadata)
: base(contractName, cardinality, isRecomposable, isPrerequisite, metadata)
{
Requires.NotNullOrEmpty(contractName, nameof(contractName));
_requiredTypeIdentity = requiredTypeIdentity;
if (requiredMetadata != null)
{
_requiredMetadata = requiredMetadata;
}
_requiredCreationPolicy = requiredCreationPolicy;
}
/// <summary>
/// The type identity of the export type expected.
/// </summary>
/// <value>
/// A <see cref="string"/> that is generated by <see cref="AttributedModelServices.GetTypeIdentity(Type)"/>
/// on the type that this import expects. If the value is <see langword="null"/> then this import
/// doesn't expect a particular type.
/// </value>
public virtual string RequiredTypeIdentity
{
get { return _requiredTypeIdentity; }
}
/// <summary>
/// Gets the metadata names of the export required by the import definition.
/// </summary>
/// <value>
/// An <see cref="IEnumerable{T}"/> of pairs of metadata keys and types of the <see cref="Export"/> required by the
/// <see cref="ContractBasedImportDefinition"/>. The default is an empty
/// <see cref="IEnumerable{T}"/>.
/// </value>
/// <remarks>
/// <note type="inheritinfo">
/// Overriders of this property should never return <see langword="null"/>
/// or return an <see cref="IEnumerable{T}"/> that contains an element that is
/// <see langword="null"/>. If the definition does not contain required metadata,
/// return an empty <see cref="IEnumerable{T}"/> instead.
/// </note>
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public virtual IEnumerable<KeyValuePair<string, Type>> RequiredMetadata
{
get
{
// NOTE : unlike other arguments, we validate this one as late as possible, because its validation may lead to type loading
ValidateRequiredMetadata();
Debug.Assert(_requiredMetadata != null);
return _requiredMetadata;
}
}
private void ValidateRequiredMetadata()
{
if (!_isRequiredMetadataValidated)
{
foreach (KeyValuePair<string, Type> metadataItem in _requiredMetadata)
{
if ((metadataItem.Key == null) || (metadataItem.Value == null))
{
throw new InvalidOperationException(
SR.Format(SR.Argument_NullElement, "requiredMetadata"));
}
}
_isRequiredMetadataValidated = true;
}
}
/// <summary>
/// Gets or sets a value indicating that the importer requires a specific
/// <see cref="CreationPolicy"/> for the exports used to satisfy this import. T
/// </summary>
/// <value>
/// <see cref="CreationPolicy.Any"/> - default value, used if the importer doesn't
/// require a specific <see cref="CreationPolicy"/>.
///
/// <see cref="CreationPolicy.Shared"/> - Requires that all exports used should be shared
/// by everyone in the container.
///
/// <see cref="CreationPolicy.NonShared"/> - Requires that all exports used should be
/// non-shared in a container and thus everyone gets their own instance.
/// </value>
public virtual CreationPolicy RequiredCreationPolicy
{
get { return _requiredCreationPolicy; }
}
/// <summary>
/// Gets an expression that defines conditions that must be matched for the import
/// described by the import definition to be satisfied.
/// </summary>
/// <returns>
/// A <see cref="Expression{TDelegate}"/> containing a <see cref="Func{T, TResult}"/>
/// that defines the conditions that must be matched for the
/// <see cref="ImportDefinition"/> to be satisfied by an <see cref="Export"/>.
/// </returns>
/// <remarks>
/// <para>
/// This property returns an expression that defines conditions based on the
/// <see cref="ImportDefinition.ContractName"/>, <see cref="RequiredTypeIdentity"/>,
/// <see cref="RequiredMetadata"/>, and <see cref="RequiredCreationPolicy"/>
/// properties.
/// </para>
/// </remarks>
public override Expression<Func<ExportDefinition, bool>> Constraint
{
get
{
if (_constraint == null)
{
_constraint = ConstraintServices.CreateConstraint(ContractName, RequiredTypeIdentity, RequiredMetadata, RequiredCreationPolicy);
}
return _constraint;
}
}
/// <summary>
/// Executes an optimized version of the contraint given by the <see cref="Constraint"/> property
/// </summary>
/// <param name="exportDefinition">
/// A definition for a <see cref="Export"/> used to determine if it satisfies the
/// requirements for this <see cref="ImportDefinition"/>.
/// </param>
/// <returns>
/// <see langword="True"/> if the <see cref="Export"/> satisfies the requirements for
/// this <see cref="ImportDefinition"/>, otherwise returns <see langword="False"/>.
/// </returns>
/// <remarks>
/// <note type="inheritinfo">
/// Overrides of this method can provide a more optimized execution of the
/// <see cref="Constraint"/> property but the result should remain consistent.
/// </note>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="exportDefinition"/> is <see langword="null"/>.
/// </exception>
public override bool IsConstraintSatisfiedBy(ExportDefinition exportDefinition)
{
Requires.NotNull(exportDefinition, nameof(exportDefinition));
if (!StringComparers.ContractName.Equals(ContractName, exportDefinition.ContractName))
{
return false;
}
return MatchRequiredMetadata(exportDefinition);
}
private bool MatchRequiredMetadata(ExportDefinition definition)
{
if (!string.IsNullOrEmpty(RequiredTypeIdentity))
{
string exportTypeIdentity = definition.Metadata.GetValue<string>(CompositionConstants.ExportTypeIdentityMetadataName);
if (!StringComparers.ContractName.Equals(RequiredTypeIdentity, exportTypeIdentity))
{
return false;
}
}
foreach (KeyValuePair<string, Type> metadataItem in RequiredMetadata)
{
string metadataKey = metadataItem.Key;
Type metadataValueType = metadataItem.Value;
object metadataValue = null;
if (!definition.Metadata.TryGetValue(metadataKey, out metadataValue))
{
return false;
}
if (metadataValue != null)
{
// the metadata value is not null, we can rely on IsInstanceOfType to do the right thing
if (!metadataValueType.IsInstanceOfType(metadataValue))
{
return false;
}
}
else
{
// this is an unfortunate special case - typeof(object).IsInstanceofType(null) == false
// basically nulls are not considered valid values for anything
// We want them to match anything that is a reference type
if (metadataValueType.IsValueType)
{
// this is a pretty expensive check, but we only invoke it when metadata values are null, which is very rare
return false;
}
}
}
if (RequiredCreationPolicy == CreationPolicy.Any)
{
return true;
}
CreationPolicy exportPolicy = definition.Metadata.GetValue<CreationPolicy>(CompositionConstants.PartCreationPolicyMetadataName);
return exportPolicy == CreationPolicy.Any ||
exportPolicy == RequiredCreationPolicy;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(string.Format("\n\tContractName\t{0}", ContractName));
sb.Append(string.Format("\n\tRequiredTypeIdentity\t{0}", RequiredTypeIdentity));
if (_requiredCreationPolicy != CreationPolicy.Any)
{
sb.Append(string.Format("\n\tRequiredCreationPolicy\t{0}", RequiredCreationPolicy));
}
if (_requiredMetadata.Count() > 0)
{
sb.Append("\n\tRequiredMetadata");
foreach (KeyValuePair<string, Type> metadataItem in _requiredMetadata)
{
sb.Append(string.Format("\n\t\t{0}\t({1})", metadataItem.Key, metadataItem.Value));
}
}
return sb.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Xml.Linq;
using System.Xml.Serialization;
using NUnit.Framework;
using XSerializer.Encryption;
namespace XSerializer.Tests.Encryption
{
[TestFixture]
public class EncryptionTests
{
private SerializationState _serializationState;
[SetUp]
public void Setup()
{
_serializationState = new SerializationState();
}
[Test]
public void CanEncryptAndDecryptEntireRootObjectViaOptions()
{
IEncryptionMechanism encryptionMechanism = new Base64EncryptionMechanism();
var serializer = new XmlSerializer<UnencryptedThing>(x => x.EncryptRootObject().WithEncryptionMechanism(encryptionMechanism));
var instance = new UnencryptedThing
{
Foo = 123,
Bar = true
};
var xml = serializer.Serialize(instance);
var doc = XDocument.Parse(xml);
Assert.That(encryptionMechanism.Decrypt(doc.Root.Value, null, _serializationState), Is.EqualTo("<Bar>true</Bar>"));
Assert.That(encryptionMechanism.Decrypt(doc.Root.Attribute("Foo").Value, null, _serializationState), Is.EqualTo("123"));
var roundTrip = serializer.Deserialize(xml);
Assert.That(roundTrip.Foo, Is.EqualTo(instance.Foo));
Assert.That(roundTrip.Bar, Is.EqualTo(instance.Bar));
}
[Test]
public void CanEncryptAndDecryptEntireRootObjectViaEncryptAttribute()
{
IEncryptionMechanism encryptionMechanism = new Base64EncryptionMechanism();
var serializer = new XmlSerializer<EncryptedThing>(x => x.WithEncryptionMechanism(encryptionMechanism));
var instance = new EncryptedThing
{
Foo = 123,
Bar = true
};
var xml = serializer.Serialize(instance);
var doc = XDocument.Parse(xml);
Assert.That(encryptionMechanism.Decrypt(doc.Root.Value, null, _serializationState), Is.EqualTo("<Bar>true</Bar>"));
Assert.That(encryptionMechanism.Decrypt(doc.Root.Attribute("Foo").Value, null, _serializationState), Is.EqualTo("123"));
var roundTrip = serializer.Deserialize(xml);
Assert.That(roundTrip.Foo, Is.EqualTo(instance.Foo));
Assert.That(roundTrip.Bar, Is.EqualTo(instance.Bar));
}
[Test]
public void EncryptsAndDecryptsPropertyWhenTheClassOfThePropertyTypeIsDecoratedWithEncryptAttribute()
{
IEncryptionMechanism encryptionMechanism = new Base64EncryptionMechanism();
var serializer = new XmlSerializer<Container<EncryptedThing>>(x => x.WithEncryptionMechanism(encryptionMechanism));
var instance = new Container<EncryptedThing>
{
Item = new EncryptedThing
{
Foo = 123,
Bar = true
}
};
var xml = serializer.Serialize(instance);
var doc = XDocument.Parse(xml);
Assert.That(encryptionMechanism.Decrypt(doc.Root.Element("Item").Value, null, _serializationState), Is.EqualTo("<Bar>true</Bar>"));
Assert.That(encryptionMechanism.Decrypt(doc.Root.Element("Item").Attribute("Foo").Value, null, _serializationState), Is.EqualTo("123"));
var roundTrip = serializer.Deserialize(xml);
Assert.That(roundTrip.Item.Foo, Is.EqualTo(instance.Item.Foo));
Assert.That(roundTrip.Item.Bar, Is.EqualTo(instance.Item.Bar));
}
[Test]
public void EncryptsAndDecryptsGenericListPropertyWhenTheListGenericArgumentClassIsDecoratedWithEncryptAttribute()
{
IEncryptionMechanism encryptionMechanism = new Base64EncryptionMechanism();
var serializer = new XmlSerializer<Container<List<EncryptedThing>>>(x => x.WithEncryptionMechanism(encryptionMechanism));
var instance = new Container<List<EncryptedThing>>
{
Item = new List<EncryptedThing>
{
new EncryptedThing
{
Foo = 123,
Bar = true
},
new EncryptedThing
{
Foo = 789,
Bar = false
},
}
};
var xml = serializer.Serialize(instance);
var doc = XDocument.Parse(xml);
var actualDecryptedItemElementValue = encryptionMechanism.Decrypt(doc.Root.Element("Item").Value, null, _serializationState);
const string expectedDecryptedItemElementValue =
@"<EncryptedThing Foo=""123""><Bar>true</Bar></EncryptedThing>"
+ @"<EncryptedThing Foo=""789""><Bar>false</Bar></EncryptedThing>";
Assert.That(actualDecryptedItemElementValue, Is.EqualTo(expectedDecryptedItemElementValue));
var roundTrip = serializer.Deserialize(xml);
Assert.That(roundTrip.Item.Count, Is.EqualTo(2));
Assert.That(roundTrip.Item[0].Foo, Is.EqualTo(instance.Item[0].Foo));
Assert.That(roundTrip.Item[0].Bar, Is.EqualTo(instance.Item[0].Bar));
Assert.That(roundTrip.Item[1].Foo, Is.EqualTo(instance.Item[1].Foo));
Assert.That(roundTrip.Item[1].Bar, Is.EqualTo(instance.Item[1].Bar));
}
[Test]
public void EncryptsAndDecryptsGenericDictionaryPropertyWhenTheKeyClassIsDecoratedWithEncryptAttribute()
{
IEncryptionMechanism encryptionMechanism = new Base64EncryptionMechanism();
var serializer = new XmlSerializer<Container<Dictionary<EncryptedThing, int>>>(x => x.WithEncryptionMechanism(encryptionMechanism));
var instance = new Container<Dictionary<EncryptedThing, int>>
{
Item = new Dictionary<EncryptedThing, int>
{
{
new EncryptedThing
{
Foo = 123,
Bar = true
},
1
},
{
new EncryptedThing
{
Foo = 789,
Bar = false
},
2
},
}
};
var xml = serializer.Serialize(instance);
var doc = XDocument.Parse(xml);
var actualDecryptedItemElementValue = encryptionMechanism.Decrypt(doc.Root.Element("Item").Value, null, _serializationState);
const string expectedDecryptedItemElementValue =
@"<Item><Key Foo=""123""><Bar>true</Bar></Key><Value>1</Value></Item>"
+ @"<Item><Key Foo=""789""><Bar>false</Bar></Key><Value>2</Value></Item>";
Assert.That(actualDecryptedItemElementValue, Is.EqualTo(expectedDecryptedItemElementValue));
var roundTrip = serializer.Deserialize(xml);
Assert.That(roundTrip.Item.Keys, Is.EquivalentTo(instance.Item.Keys));
var key = new EncryptedThing { Foo = 123, Bar = true };
Assert.That(roundTrip.Item[key], Is.EqualTo(instance.Item[key]));
key = new EncryptedThing { Foo = 789, Bar = false };
Assert.That(roundTrip.Item[key], Is.EqualTo(instance.Item[key]));
}
[Test]
public void EncryptsAndDecryptsGenericDictionaryPropertyWhenTheValueClassIsDecoratedWithEncryptAttribute()
{
IEncryptionMechanism encryptionMechanism = new Base64EncryptionMechanism();
var serializer = new XmlSerializer<Container<Dictionary<int, EncryptedThing>>>(x => x.WithEncryptionMechanism(encryptionMechanism));
var instance = new Container<Dictionary<int, EncryptedThing>>
{
Item = new Dictionary<int, EncryptedThing>
{
{
1,
new EncryptedThing
{
Foo = 123,
Bar = true
}
},
{
2,
new EncryptedThing
{
Foo = 789,
Bar = false
}
},
}
};
var xml = serializer.Serialize(instance);
var doc = XDocument.Parse(xml);
var actualDecryptedItemElementValue = encryptionMechanism.Decrypt(doc.Root.Element("Item").Value, null, _serializationState);
const string expectedDecryptedItemElementValue =
@"<Item><Key>1</Key><Value Foo=""123""><Bar>true</Bar></Value></Item>"
+ @"<Item><Key>2</Key><Value Foo=""789""><Bar>false</Bar></Value></Item>";
Assert.That(actualDecryptedItemElementValue, Is.EqualTo(expectedDecryptedItemElementValue));
var roundTrip = serializer.Deserialize(xml);
Assert.That(roundTrip.Item.Keys, Is.EquivalentTo(instance.Item.Keys));
Assert.That(roundTrip.Item[1], Is.EqualTo(instance.Item[1]));
Assert.That(roundTrip.Item[2], Is.EqualTo(instance.Item[2]));
}
[Encrypt]
public class EncryptedThing
{
[XmlAttribute]
public int Foo { get; set; }
public bool Bar { get; set; }
public override bool Equals(object obj)
{
var other = obj as EncryptedThing;
if (other == null)
{
return false;
}
return Foo == other.Foo && Bar == other.Bar;
}
public override int GetHashCode()
{
unchecked
{
return (Foo * 397) ^ Bar.GetHashCode();
}
}
}
public class UnencryptedThing
{
[XmlAttribute]
public int Foo { get; set; }
public bool Bar { get; set; }
}
[Test]
public void AListPropertyDecoratedWithXmlElementAndEncryptCannotExistWithOtherNonXmlAttributeProperties()
{
Assert.That(() => new XmlSerializer<Invalid>(), Throws.InvalidOperationException);
}
[Test]
public void AListPropertyDecoratedWithXmlElementAndEncryptCanExistWithOtherXmlAttributeProperties()
{
var serializer = new XmlSerializer<Valid>();
var instance = new Valid
{
CleartextAttribute = 123,
CiphertextAttribute = 789,
Items = new List<int> { 4, 5, 6 }
};
var xml = serializer.Serialize(instance);
var roundTrip = serializer.Deserialize(xml);
Assert.That(roundTrip.CleartextAttribute, Is.EqualTo(instance.CleartextAttribute));
Assert.That(roundTrip.CiphertextAttribute, Is.EqualTo(instance.CiphertextAttribute));
Assert.That(roundTrip.Items, Is.EqualTo(instance.Items));
}
public class Invalid
{
[XmlElement("Item")]
[Encrypt]
public List<int> Items { get; set; }
public int Wtf { get; set; }
}
public class Valid
{
[XmlElement("Item")]
[Encrypt]
public List<int> Items { get; set; }
[XmlAttribute]
public int CleartextAttribute { get; set; }
[XmlAttribute]
[Encrypt]
public int CiphertextAttribute { get; set; }
}
#region ByXmlStructure
[TestCaseSource("_byXmlStructureTestCases")]
public void ByXmlStructure(object objectToSerialize, Func<object, object> getTargetValue, Func<XElement, object> getTargetNodeValue, object expectedTargetNodeValue, Type[] extraTypes)
{
PerformTest(objectToSerialize, getTargetValue, getTargetNodeValue, expectedTargetNodeValue, extraTypes);
}
// ReSharper disable PossibleNullReferenceException
private static readonly TestCaseData[] _byXmlStructureTestCases =
{
GetTestCaseData(
"XmlElement",
new XmlElementExample { Value = 123 },
x => x.Value,
root => root.Element("Value").Value,
"MTIz"),
GetTestCaseData(
"XmlAttribute",
new XmlAttributeExample { Value = 123 },
x => x.Value,
root => root.Attribute("Value").Value,
"MTIz"),
GetTestCaseData(
"XmlText",
new Container<XmlTextExample> { Item = new XmlTextExample { Value = 123 } },
x => x.Item.Value,
root => root.Element("Item").Value,
"MTIz"),
GetTestCaseData(
"XmlArray + XmlArrayItem",
new XmlArrayAndItemExample { Items = new[] { 123 }},
x => x.Items[0],
root => root.Element("Items").Value,
"PEl0ZW0+MTIzPC9JdGVtPg=="),
GetTestCaseData(
"XmlElement decorating array property",
new XmlElementOnArrayPropertyExample { Items = new[] { 123 }},
x => x.Items[0],
root => root.Value,
"PEl0ZW0+MTIzPC9JdGVtPg==")
};
// ReSharper restore PossibleNullReferenceException
public class XmlElementExample
{
[Encrypt]
[XmlElement]
public int Value { get; set; }
public int Dummy { get; set; }
}
public class XmlAttributeExample
{
[Encrypt]
[XmlAttribute]
public int Value { get; set; }
public int Dummy { get; set; }
}
public class XmlTextExample
{
[Encrypt]
[XmlText]
public int Value { get; set; }
}
public class XmlArrayAndItemExample
{
[Encrypt]
[XmlArray]
[XmlArrayItem("Item")]
public int[] Items { get; set; }
public int Dummy { get; set; }
}
public class XmlElementOnArrayPropertyExample
{
[Encrypt]
[XmlElement("Item")]
public int[] Items { get; set; }
}
#endregion
#region ByType
[TestCaseSource("_byTypeTestCases")]
public void ByType(object objectToSerialize, Func<object, object> getTargetValue, Func<XElement, object> getTargetNodeValue, object expectedTargetNodeValue, Type[] extraTypes)
{
PerformTest(objectToSerialize, getTargetValue, getTargetNodeValue, expectedTargetNodeValue, extraTypes);
}
private static readonly Guid _exampleGuid = Guid.Parse("e3287204-92ab-4a54-a148-f554007beddd");
// ReSharper disable PossibleNullReferenceException
private static readonly TestCaseData[] _byTypeTestCases =
{
GetTestCaseData(
"string",
new TypeExample<string> { Value = "123" },
x => x.Value,
root => root.Element("Value").Value,
"MTIz"),
GetTestCaseData(
"int",
new TypeExample<int> { Value = 123 },
x => x.Value,
root => root.Element("Value").Value,
"MTIz"),
GetTestCaseData(
"Nullable int",
new TypeExample<int?> { Value = 123 },
x => x.Value,
root => root.Element("Value").Value,
"MTIz"),
GetTestCaseData(
"bool",
new TypeExample<bool> { Value = true },
x => x.Value,
root => root.Element("Value").Value,
"dHJ1ZQ=="),
GetTestCaseData(
"Nullable bool",
new TypeExample<bool?> { Value = true },
x => x.Value,
root => root.Element("Value").Value,
"dHJ1ZQ=="),
GetTestCaseData(
"double",
new TypeExample<double> { Value = 123.45 },
x => x.Value,
root => root.Element("Value").Value,
"MTIzLjQ1"),
GetTestCaseData(
"Nullable double",
new TypeExample<double?> { Value = 123.45 },
x => x.Value,
root => root.Element("Value").Value,
"MTIzLjQ1"),
GetTestCaseData(
"decimal",
new TypeExample<decimal> { Value = 123.45M },
x => x.Value,
root => root.Element("Value").Value,
"MTIzLjQ1"),
GetTestCaseData(
"Nullable decimal",
new TypeExample<decimal?> { Value = 123.45M },
x => x.Value,
root => root.Element("Value").Value,
"MTIzLjQ1"),
GetTestCaseData(
"enum (specific)",
new TypeExample<TestEnum> { Value = TestEnum.Second },
x => x.Value,
root => root.Element("Value").Value,
"U2Vjb25k"),
GetTestCaseData(
"Nullable enum (specific)",
new TypeExample<TestEnum?> { Value = TestEnum.Second },
x => x.Value,
root => root.Element("Value").Value,
"U2Vjb25k"),
GetTestCaseData(
"DateTime",
new TypeExample<DateTime> { Value = new DateTime(2000, 1, 1) },
x => x.Value,
root => root.Element("Value").Value,
"MjAwMC0wMS0wMVQwMDowMDowMC4wMDAwMDAw"),
GetTestCaseData(
"Nullable DateTime",
new TypeExample<DateTime?> { Value = new DateTime(2000, 1, 1) },
x => x.Value,
root => root.Element("Value").Value,
"MjAwMC0wMS0wMVQwMDowMDowMC4wMDAwMDAw"),
GetTestCaseData(
"Guid",
new TypeExample<Guid> { Value = _exampleGuid },
x => x.Value,
root => root.Element("Value").Value,
"ZTMyODcyMDQtOTJhYi00YTU0LWExNDgtZjU1NDAwN2JlZGRk"),
GetTestCaseData(
"Nullable Guid",
new TypeExample<Guid?> { Value = _exampleGuid },
x => x.Value,
root => root.Element("Value").Value,
"ZTMyODcyMDQtOTJhYi00YTU0LWExNDgtZjU1NDAwN2JlZGRk"),
GetTestCaseData(
"Enum (non-specific)",
new TypeExample<Enum> { Value = TestEnum.Second },
x => x.Value,
root => root.Element("Value").Value,
"VGVzdEVudW0uU2Vjb25k",
typeof(TestEnum)),
GetTestCaseData(
"Type",
new TypeExample<Type> { Value = typeof(string) },
x => x.Value,
root => root.Element("Value").Value,
"U3lzdGVtLlN0cmluZw=="),
GetTestCaseData(
"Uri",
new TypeExample<Uri> { Value = new Uri("http://google.com/") },
x => x.Value,
root => root.Element("Value").Value,
"aHR0cDovL2dvb2dsZS5jb20v"),
GetTestCaseData(
"Complex Object With Elements",
new TypeExample<Bar> { Value = new Bar { Baz = 123, Qux = true } },
x => x.Value,
root => root.Element("Value").Value,
"PEJhej4xMjM8L0Jhej48UXV4PnRydWU8L1F1eD4="),
GetTestCaseData(
"Complex Object With Elements And Non-Default Constructor",
new TypeExample<BarImmutable> { Value = new BarImmutable(123, true) },
x => x.Value,
root => root.Element("Value").Value,
"PEJhej4xMjM8L0Jhej48UXV4PnRydWU8L1F1eD4="),
GetTestCaseData(
"Complex Object With Attributes",
new TypeExample<Baz> { Value = new Baz { Qux = 123, Corge = true } },
x => x.Value,
root => root.Element("Value").Attribute("Qux").Value + "|" + root.Element("Value").Attribute("Corge").Value,
"MTIz|dHJ1ZQ=="),
GetTestCaseData(
"Complex Object With Attributes And Non-Default Constructor",
new TypeExample<BazImmutable> { Value = new BazImmutable(123, true) },
x => x.Value,
root => root.Element("Value").Attribute("Qux").Value + "|" + root.Element("Value").Attribute("Corge").Value,
"MTIz|dHJ1ZQ=="),
GetTestCaseData(
"Complex Object With Elements And Attributes",
new TypeExample<Foo> { Value = new Foo { Bar = 123, Baz = true, Qux = 123, Corge = true } },
x => x.Value,
root => root.Element("Value").Value + "|" + root.Element("Value").Attribute("Qux").Value + "|" + root.Element("Value").Attribute("Corge").Value,
"PEJhcj4xMjM8L0Jhcj48QmF6PnRydWU8L0Jhej4=|MTIz|dHJ1ZQ=="),
GetTestCaseData(
"Complex Object With Elements And Attributes And Non-Default Constructor",
new TypeExample<FooImmutable> { Value = new FooImmutable(123, true, 123, true) },
x => x.Value,
root => root.Element("Value").Value + "|" + root.Element("Value").Attribute("Qux").Value + "|" + root.Element("Value").Attribute("Corge").Value,
"PEJhcj4xMjM8L0Jhcj48QmF6PnRydWU8L0Jhej4=|MTIz|dHJ1ZQ=="),
GetTestCaseData(
"Dictionary",
new TypeExample<Dictionary<int, string>> { Value = new Dictionary<int, string> { { 123, "abc"}, { 789, "xyz" } } },
x => x.Value,
root => root.Element("Value").Value,
"PEl0ZW0+PEtleT4xMjM8L0tleT48VmFsdWU+YWJjPC9WYWx1ZT48L0l0ZW0+PEl0ZW0+PEtleT43ODk8L0tleT48VmFsdWU+eHl6PC9WYWx1ZT48L0l0ZW0+"),
GetTestCaseData(
"Dynamic With ExpandoObject Input",
new TypeExample<dynamic> { Value = GetExampleExpandoObject() },
x => x.Value,
root => root.Element("Value").Value,
"PEZvbz4xMjM8L0Zvbz48QmFyPmFiYzwvQmFyPjxCYXo+dHJ1ZTwvQmF6Pg=="),
GetTestCaseData(
"Dynamic With Anonymous Object Input",
new TypeExample<dynamic> { Value = new { Foo = 123, Bar = "abc", Baz = true } },
x => x.Value is ExpandoObject ? x.Value : ToExpandoObject(x.Value),
root => root.Element("Value").Value,
"PEZvbz4xMjM8L0Zvbz48QmFyPmFiYzwvQmFyPjxCYXo+dHJ1ZTwvQmF6Pg=="),
GetTestCaseData(
"Dynamic With Concrete Object Input",
new TypeExample<dynamic> { Value = new Example { Foo = 123, Bar = "abc", Baz = true } },
x => x.Value,
root => root.Element("Value").Value,
"PEZvbz4xMjM8L0Zvbz48QmFyPmFiYzwvQmFyPjxCYXo+dHJ1ZTwvQmF6Pg=="),
GetTestCaseData(
"ExpandoObject",
new TypeExample<ExpandoObject> { Value = GetExampleExpandoObject() },
x => x.Value,
root => root.Element("Value").Value,
"PEZvbz4xMjM8L0Zvbz48QmFyPmFiYzwvQmFyPjxCYXo+dHJ1ZTwvQmF6Pg=="),
};
private static ExpandoObject GetExampleExpandoObject()
{
var expandoObject = new ExpandoObject();
dynamic d = expandoObject;
d.Foo = 123;
d.Bar = "abc";
d.Baz = true;
return expandoObject;
}
private static object ToExpandoObject(object anonymousObject)
{
IDictionary<string, object> expndoObject = new ExpandoObject();
foreach (var property in anonymousObject.GetType().GetProperties())
{
expndoObject[property.Name] = property.GetValue(anonymousObject);
}
return expndoObject;
}
public class TypeExample<T>
{
[Encrypt]
public T Value { get; set; }
public int Dummy { get; set; }
}
public enum TestEnum
{
First, Second, Third
}
public class Bar
{
public int Baz { get; set; }
public bool Qux { get; set; }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
var expando = (IDictionary<string, object>)(obj as ExpandoObject);
if (expando != null)
{
object value;
return
(expando.TryGetValue("Baz", out value) && value is int && (int)value == Baz)
&& (expando.TryGetValue("Qux", out value) && value is bool && (bool)value == Qux);
}
if (obj.GetType() != this.GetType()) return false;
return Equals((Bar)obj);
}
protected bool Equals(Bar other)
{
return Baz == other.Baz && Qux.Equals(other.Qux);
}
public override int GetHashCode()
{
unchecked
{
return (Baz * 397) ^ Qux.GetHashCode();
}
}
}
public class BarImmutable
{
private readonly int _baz;
private readonly bool _qux;
public BarImmutable(int baz, bool qux)
{
_baz = baz;
_qux = qux;
}
public int Baz { get { return _baz; } }
public bool Qux { get { return _qux; } }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((BarImmutable)obj);
}
protected bool Equals(BarImmutable other)
{
return Baz == other.Baz && Qux.Equals(other.Qux);
}
public override int GetHashCode()
{
unchecked
{
return (Baz * 397) ^ Qux.GetHashCode();
}
}
}
public class Baz
{
[XmlAttribute]
public int Qux { get; set; }
[XmlAttribute]
public bool Corge { get; set; }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Baz)obj);
}
protected bool Equals(Baz other)
{
return Qux == other.Qux && Corge.Equals(other.Corge);
}
public override int GetHashCode()
{
unchecked
{
return (Qux * 397) ^ Corge.GetHashCode();
}
}
}
public class BazImmutable
{
private readonly int _qux;
private readonly bool _corge;
public BazImmutable(int qux, bool corge)
{
_qux = qux;
_corge = corge;
}
[XmlAttribute]
public int Qux { get { return _qux; } }
[XmlAttribute]
public bool Corge { get { return _corge; } }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((BazImmutable)obj);
}
protected bool Equals(BazImmutable other)
{
return Qux == other.Qux && Corge.Equals(other.Corge);
}
public override int GetHashCode()
{
unchecked
{
return (Qux * 397) ^ Corge.GetHashCode();
}
}
}
public class Foo
{
public double Bar { get; set; }
public bool Baz { get; set; }
[XmlAttribute]
public int Qux { get; set; }
[XmlAttribute]
public bool Corge { get; set; }
protected bool Equals(Foo other)
{
return Bar.Equals(other.Bar) && Baz.Equals(other.Baz) && Qux == other.Qux && Corge.Equals(other.Corge);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Foo)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = Bar.GetHashCode();
hashCode = (hashCode * 397) ^ Baz.GetHashCode();
hashCode = (hashCode * 397) ^ Qux;
hashCode = (hashCode * 397) ^ Corge.GetHashCode();
return hashCode;
}
}
}
public class FooImmutable
{
private readonly int _bar;
private readonly bool _baz;
private readonly int _qux;
private readonly bool _corge;
public FooImmutable(int bar, bool baz, int qux, bool corge)
{
_bar = bar;
_baz = baz;
_qux = qux;
_corge = corge;
}
public int Bar { get { return _bar; } }
public bool Baz { get { return _baz; } }
[XmlAttribute]
public int Qux { get { return _qux; } }
[XmlAttribute]
public bool Corge { get { return _corge; } }
protected bool Equals(FooImmutable other)
{
return Bar.Equals(other.Bar) && Baz.Equals(other.Baz) && Qux == other.Qux && Corge.Equals(other.Corge);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((FooImmutable)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = Bar.GetHashCode();
hashCode = (hashCode * 397) ^ Baz.GetHashCode();
hashCode = (hashCode * 397) ^ Qux;
hashCode = (hashCode * 397) ^ Corge.GetHashCode();
return hashCode;
}
}
}
public class Example
{
public int Foo { get; set; }
public string Bar { get; set; }
public bool Baz { get; set; }
protected bool Equals(Example other)
{
return Foo == other.Foo && string.Equals(Bar, other.Bar) && Baz.Equals(other.Baz);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Example)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = Foo;
hashCode = (hashCode * 397) ^ (Bar != null ? Bar.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ Baz.GetHashCode();
return hashCode;
}
}
}
#endregion
private static void PerformTest(object objectToSerialize, Func<object, object> getTargetValue, Func<XElement, object> getTargetNodeValue, object expectedTargetNodeValue, Type[] extraTypes)
{
var serializer = XmlSerializer.Create(objectToSerialize.GetType(), options => options.Indent().AlwaysEmitTypes(), extraTypes);
var xml = serializer.Serialize(objectToSerialize);
Console.WriteLine(xml);
var roundTrip = serializer.Deserialize(xml);
var targetValue = getTargetValue(roundTrip);
var expectedTargetValue = getTargetValue(objectToSerialize);
Assert.That(targetValue, Is.EqualTo(expectedTargetValue));
var targetNodeValue = getTargetNodeValue(XDocument.Parse(xml).Root);
Assert.That(targetNodeValue, Is.EqualTo(expectedTargetNodeValue));
}
private static TestCaseData GetTestCaseData<TToSerialize, TTargetValue>(
string name,
TToSerialize objectToSerialize,
Func<TToSerialize, TTargetValue> getTargetValue,
Func<XElement, object> getTargetNodeValue,
object expectedTargetNodeValue,
params Type[] extraTypes)
{
var testCaseData =
new TestCaseData(
objectToSerialize,
(Func<object, object>)(target => getTargetValue((TToSerialize)target)),
getTargetNodeValue,
expectedTargetNodeValue,
extraTypes);
return testCaseData.SetName(name);
}
public class Container<T>
{
public T Item { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using OrchardVNext.Environment.Extensions.Models;
using OrchardVNext.Utility;
using OrchardVNext.FileSystems.WebSite;
using OrchardVNext.Localization;
namespace OrchardVNext.Environment.Extensions.Folders {
public class ExtensionHarvester : IExtensionHarvester {
private const string NameSection = "name";
private const string PathSection = "path";
private const string DescriptionSection = "description";
private const string VersionSection = "version";
private const string OrchardVersionSection = "orchardversion";
private const string AuthorSection = "author";
private const string WebsiteSection = "website";
private const string TagsSection = "tags";
private const string AntiForgerySection = "antiforgery";
private const string ZonesSection = "zones";
private const string BaseThemeSection = "basetheme";
private const string DependenciesSection = "dependencies";
private const string CategorySection = "category";
private const string FeatureDescriptionSection = "featuredescription";
private const string FeatureNameSection = "featurename";
private const string PrioritySection = "priority";
private const string FeaturesSection = "features";
private const string SessionStateSection = "sessionstate";
private readonly IWebSiteFolder _webSiteFolder;
public ExtensionHarvester(IWebSiteFolder webSiteFolder) {
_webSiteFolder = webSiteFolder;
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
public bool DisableMonitoring { get; set; }
public IEnumerable<ExtensionDescriptor> HarvestExtensions(IEnumerable<string> paths, string extensionType, string manifestName, bool manifestIsOptional) {
return paths
.SelectMany(path => HarvestExtensions(path, extensionType, manifestName, manifestIsOptional))
.ToList();
}
private IEnumerable<ExtensionDescriptor> HarvestExtensions(string path, string extensionType, string manifestName, bool manifestIsOptional) {
string key = string.Format("{0}-{1}-{2}", path, manifestName, extensionType);
return AvailableExtensionsInFolder(path, extensionType, manifestName, manifestIsOptional).ToReadOnlyCollection();
}
private List<ExtensionDescriptor> AvailableExtensionsInFolder(string path, string extensionType, string manifestName, bool manifestIsOptional) {
Logger.Information("Start looking for extensions in '{0}'...", path);
var subfolderPaths = _webSiteFolder.ListDirectories(path);
var localList = new List<ExtensionDescriptor>();
foreach (var subfolderPath in subfolderPaths) {
var extensionId = Path.GetFileName(subfolderPath.TrimEnd('/', '\\'));
var manifestPath = Path.Combine(subfolderPath, manifestName);
try {
var descriptor = GetExtensionDescriptor(path, extensionId, extensionType, manifestPath, manifestIsOptional);
if (descriptor == null)
continue;
if (descriptor.Path != null && !descriptor.Path.IsValidUrlSegment()) {
Logger.Error("The module '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.",
extensionId,
descriptor.Path);
continue;
}
if (descriptor.Path == null) {
descriptor.Path = descriptor.Name.IsValidUrlSegment()
? descriptor.Name
: descriptor.Id;
}
localList.Add(descriptor);
}
catch (Exception ex) {
// Ignore invalid module manifests
Logger.Error(ex, "The module '{0}' could not be loaded. It was ignored.", extensionId);
}
}
Logger.Information("Done looking for extensions in '{0}': {1}", path, string.Join(", ", localList.Select(d => d.Id)));
return localList;
}
public static ExtensionDescriptor GetDescriptorForExtension(string locationPath, string extensionId, string extensionType, string manifestText) {
Dictionary<string, string> manifest = ParseManifest(manifestText);
var extensionDescriptor = new ExtensionDescriptor {
Location = locationPath,
Id = extensionId,
ExtensionType = extensionType,
Name = GetValue(manifest, NameSection) ?? extensionId,
Path = GetValue(manifest, PathSection),
Description = GetValue(manifest, DescriptionSection),
Version = GetValue(manifest, VersionSection),
OrchardVersion = GetValue(manifest, OrchardVersionSection),
Author = GetValue(manifest, AuthorSection),
WebSite = GetValue(manifest, WebsiteSection),
Tags = GetValue(manifest, TagsSection),
AntiForgery = GetValue(manifest, AntiForgerySection),
Zones = GetValue(manifest, ZonesSection),
BaseTheme = GetValue(manifest, BaseThemeSection),
SessionState = GetValue(manifest, SessionStateSection)
};
extensionDescriptor.Features = GetFeaturesForExtension(manifest, extensionDescriptor);
return extensionDescriptor;
}
private ExtensionDescriptor GetExtensionDescriptor(string locationPath, string extensionId, string extensionType, string manifestPath, bool manifestIsOptional) {
var manifestText = _webSiteFolder.ReadFile(manifestPath);
if (manifestText == null) {
if (manifestIsOptional) {
manifestText = string.Format("Id: {0}", extensionId);
}
else {
return null;
}
}
return GetDescriptorForExtension(locationPath, extensionId, extensionType, manifestText);
}
private static Dictionary<string, string> ParseManifest(string manifestText) {
var manifest = new Dictionary<string, string>();
using (StringReader reader = new StringReader(manifestText)) {
string line;
while ((line = reader.ReadLine()) != null) {
string[] field = line.Split(new[] { ":" }, 2, StringSplitOptions.None);
int fieldLength = field.Length;
if (fieldLength != 2)
continue;
for (int i = 0; i < fieldLength; i++) {
field[i] = field[i].Trim();
}
switch (field[0].ToLowerInvariant()) {
case NameSection:
manifest.Add(NameSection, field[1]);
break;
case PathSection:
manifest.Add(PathSection, field[1]);
break;
case DescriptionSection:
manifest.Add(DescriptionSection, field[1]);
break;
case VersionSection:
manifest.Add(VersionSection, field[1]);
break;
case OrchardVersionSection:
manifest.Add(OrchardVersionSection, field[1]);
break;
case AuthorSection:
manifest.Add(AuthorSection, field[1]);
break;
case WebsiteSection:
manifest.Add(WebsiteSection, field[1]);
break;
case TagsSection:
manifest.Add(TagsSection, field[1]);
break;
case AntiForgerySection:
manifest.Add(AntiForgerySection, field[1]);
break;
case ZonesSection:
manifest.Add(ZonesSection, field[1]);
break;
case BaseThemeSection:
manifest.Add(BaseThemeSection, field[1]);
break;
case DependenciesSection:
manifest.Add(DependenciesSection, field[1]);
break;
case CategorySection:
manifest.Add(CategorySection, field[1]);
break;
case FeatureDescriptionSection:
manifest.Add(FeatureDescriptionSection, field[1]);
break;
case FeatureNameSection:
manifest.Add(FeatureNameSection, field[1]);
break;
case PrioritySection:
manifest.Add(PrioritySection, field[1]);
break;
case SessionStateSection:
manifest.Add(SessionStateSection, field[1]);
break;
case FeaturesSection:
manifest.Add(FeaturesSection, reader.ReadToEnd());
break;
}
}
}
return manifest;
}
private static IEnumerable<FeatureDescriptor> GetFeaturesForExtension(IDictionary<string, string> manifest, ExtensionDescriptor extensionDescriptor) {
var featureDescriptors = new List<FeatureDescriptor>();
// Default feature
FeatureDescriptor defaultFeature = new FeatureDescriptor {
Id = extensionDescriptor.Id,
Name = GetValue(manifest, FeatureNameSection) ?? extensionDescriptor.Name,
Priority = GetValue(manifest, PrioritySection) != null ? int.Parse(GetValue(manifest, PrioritySection)) : 0,
Description = GetValue(manifest, FeatureDescriptionSection) ?? GetValue(manifest, DescriptionSection) ?? string.Empty,
Dependencies = ParseFeatureDependenciesEntry(GetValue(manifest, DependenciesSection)),
Extension = extensionDescriptor,
Category = GetValue(manifest, CategorySection)
};
featureDescriptors.Add(defaultFeature);
// Remaining features
string featuresText = GetValue(manifest, FeaturesSection);
if (featuresText != null) {
FeatureDescriptor featureDescriptor = null;
using (StringReader reader = new StringReader(featuresText)) {
string line;
while ((line = reader.ReadLine()) != null) {
if (IsFeatureDeclaration(line)) {
if (featureDescriptor != null) {
if (!featureDescriptor.Equals(defaultFeature)) {
featureDescriptors.Add(featureDescriptor);
}
featureDescriptor = null;
}
string[] featureDeclaration = line.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
string featureDescriptorId = featureDeclaration[0].Trim();
if (String.Equals(featureDescriptorId, extensionDescriptor.Id, StringComparison.OrdinalIgnoreCase)) {
featureDescriptor = defaultFeature;
featureDescriptor.Name = extensionDescriptor.Name;
}
else {
featureDescriptor = new FeatureDescriptor {
Id = featureDescriptorId,
Extension = extensionDescriptor
};
}
}
else if (IsFeatureFieldDeclaration(line)) {
if (featureDescriptor != null) {
string[] featureField = line.Split(new[] { ":" }, 2, StringSplitOptions.None);
int featureFieldLength = featureField.Length;
if (featureFieldLength != 2)
continue;
for (int i = 0; i < featureFieldLength; i++) {
featureField[i] = featureField[i].Trim();
}
switch (featureField[0].ToLowerInvariant()) {
case NameSection:
featureDescriptor.Name = featureField[1];
break;
case DescriptionSection:
featureDescriptor.Description = featureField[1];
break;
case CategorySection:
featureDescriptor.Category = featureField[1];
break;
case PrioritySection:
featureDescriptor.Priority = int.Parse(featureField[1]);
break;
case DependenciesSection:
featureDescriptor.Dependencies = ParseFeatureDependenciesEntry(featureField[1]);
break;
}
}
else {
string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id);
throw new ArgumentException(message);
}
}
else {
string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id);
throw new ArgumentException(message);
}
}
if (featureDescriptor != null && !featureDescriptor.Equals(defaultFeature))
featureDescriptors.Add(featureDescriptor);
}
}
return featureDescriptors;
}
private static bool IsFeatureFieldDeclaration(string line) {
if (line.StartsWith("\t\t") ||
line.StartsWith("\t ") ||
line.StartsWith(" ") ||
line.StartsWith(" \t"))
return true;
return false;
}
private static bool IsFeatureDeclaration(string line) {
int lineLength = line.Length;
if (line.StartsWith("\t") && lineLength >= 2) {
return !Char.IsWhiteSpace(line[1]);
}
if (line.StartsWith(" ") && lineLength >= 5)
return !Char.IsWhiteSpace(line[4]);
return false;
}
private static IEnumerable<string> ParseFeatureDependenciesEntry(string dependenciesEntry) {
if (string.IsNullOrEmpty(dependenciesEntry))
return Enumerable.Empty<string>();
var dependencies = new List<string>();
foreach (var s in dependenciesEntry.Split(',')) {
dependencies.Add(s.Trim());
}
return dependencies;
}
private static string GetValue(IDictionary<string, string> fields, string key) {
string value;
return fields.TryGetValue(key, out value) ? value : null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Diagnostics;
using System.Runtime.Serialization;
using System.Security;
using System.ServiceModel;
namespace System.Runtime
{
public static class Fx
{
private const string defaultEventSource = "System.Runtime";
#if DEBUG
private const string AssertsFailFastName = "AssertsFailFast";
private const string BreakOnExceptionTypesName = "BreakOnExceptionTypes";
private const string FastDebugName = "FastDebug";
private const string StealthDebuggerName = "StealthDebugger";
private static bool s_breakOnExceptionTypesRetrieved;
private static Type[] s_breakOnExceptionTypesCache;
#endif
private static ExceptionTrace s_exceptionTrace;
private static EtwDiagnosticTrace s_diagnosticTrace;
[Fx.Tag.SecurityNote(Critical = "This delegate is called from within a ConstrainedExecutionRegion, must not be settable from PT code")]
[SecurityCritical]
private static ExceptionHandler s_asynchronousThreadExceptionHandler;
internal static ExceptionTrace Exception
{
get
{
if (s_exceptionTrace == null)
{
// don't need a lock here since a true singleton is not required
s_exceptionTrace = new ExceptionTrace(defaultEventSource, Trace);
}
return s_exceptionTrace;
}
}
internal static EtwDiagnosticTrace Trace
{
get
{
if (s_diagnosticTrace == null)
{
s_diagnosticTrace = InitializeTracing();
}
return s_diagnosticTrace;
}
}
[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical field EtwProvider",
Safe = "Doesn't leak info\\resources")]
[SecuritySafeCritical]
[SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule,
Justification = "This is a method that creates ETW provider passing Guid Provider ID.")]
private static EtwDiagnosticTrace InitializeTracing()
{
EtwDiagnosticTrace trace = new EtwDiagnosticTrace(defaultEventSource, EtwDiagnosticTrace.DefaultEtwProviderId);
return trace;
}
public static ExceptionHandler AsynchronousThreadExceptionHandler
{
[Fx.Tag.SecurityNote(Critical = "access critical field", Safe = "ok for get-only access")]
[SecuritySafeCritical]
get
{
return Fx.s_asynchronousThreadExceptionHandler;
}
[Fx.Tag.SecurityNote(Critical = "sets a critical field")]
[SecurityCritical]
set
{
Fx.s_asynchronousThreadExceptionHandler = value;
}
}
// Do not call the parameter "message" or else FxCop thinks it should be localized.
[Conditional("DEBUG")]
public static void Assert(bool condition, string description)
{
if (!condition)
{
Assert(description);
}
}
[Conditional("DEBUG")]
public static void Assert(string description)
{
AssertHelper.FireAssert(description);
}
public static void AssertAndThrow(bool condition, string description)
{
if (!condition)
{
AssertAndThrow(description);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Exception AssertAndThrow(string description)
{
Fx.Assert(description);
TraceCore.ShipAssertExceptionMessage(Trace, description);
throw new InternalException(description);
}
public static void AssertAndThrowFatal(bool condition, string description)
{
if (!condition)
{
AssertAndThrowFatal(description);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Exception AssertAndThrowFatal(string description)
{
Fx.Assert(description);
TraceCore.ShipAssertExceptionMessage(Trace, description);
throw new FatalInternalException(description);
}
public static void AssertAndFailFast(bool condition, string description)
{
if (!condition)
{
AssertAndFailFast(description);
}
}
// This never returns. The Exception return type lets you write 'throw AssertAndFailFast()' which tells the compiler/tools that
// execution stops.
[Fx.Tag.SecurityNote(Critical = "Calls into critical method Environment.FailFast",
Safe = "The side affect of the app crashing is actually intended here")]
[SecuritySafeCritical]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Exception AssertAndFailFast(string description)
{
Fx.Assert(description);
string failFastMessage = InternalSR.FailFastMessage(description);
// The catch is here to force the finally to run, as finallys don't run until the stack walk gets to a catch.
// The catch makes sure that the finally will run before the stack-walk leaves the frame, but the code inside is impossible to reach.
try
{
try
{
Fx.Exception.TraceFailFast(failFastMessage);
}
finally
{
Environment.FailFast(failFastMessage);
}
}
catch
{
throw;
}
return null; // we'll never get here since we've just fail-fasted
}
public static bool IsFatal(Exception exception)
{
while (exception != null)
{
if (exception is FatalException ||
exception is OutOfMemoryException ||
exception is FatalInternalException)
{
return true;
}
// These exceptions aren't themselves fatal, but since the CLR uses them to wrap other exceptions,
// we want to check to see whether they've been used to wrap a fatal exception. If so, then they
// count as fatal.
if (exception is TypeInitializationException ||
exception is TargetInvocationException)
{
exception = exception.InnerException;
}
else if (exception is AggregateException)
{
// AggregateExceptions have a collection of inner exceptions, which may themselves be other
// wrapping exceptions (including nested AggregateExceptions). Recursively walk this
// hierarchy. The (singular) InnerException is included in the collection.
ReadOnlyCollection<Exception> innerExceptions = ((AggregateException)exception).InnerExceptions;
foreach (Exception innerException in innerExceptions)
{
if (IsFatal(innerException))
{
return true;
}
}
break;
}
else
{
break;
}
}
return false;
}
// This method should be only used for debug build.
internal static bool AssertsFailFast
{
get
{
return false;
}
}
// This property should be only used for debug build.
internal static Type[] BreakOnExceptionTypes
{
get
{
#if DEBUG
if (!Fx.s_breakOnExceptionTypesRetrieved)
{
object value;
if (TryGetDebugSwitch(Fx.BreakOnExceptionTypesName, out value))
{
string[] typeNames = value as string[];
if (typeNames != null && typeNames.Length > 0)
{
List<Type> types = new List<Type>(typeNames.Length);
for (int i = 0; i < typeNames.Length; i++)
{
types.Add(Type.GetType(typeNames[i], false));
}
if (types.Count != 0)
{
Fx.s_breakOnExceptionTypesCache = types.ToArray();
}
}
}
Fx.s_breakOnExceptionTypesRetrieved = true;
}
return Fx.s_breakOnExceptionTypesCache;
#else
return null;
#endif
}
}
// This property should be only used for debug build.
internal static bool StealthDebugger
{
get
{
return false;
}
}
#if DEBUG
private static bool TryGetDebugSwitch(string name, out object value)
{
value = null;
return false;
}
#endif
public static AsyncCallback ThunkCallback(AsyncCallback callback)
{
return (new AsyncThunk(callback)).ThunkFrame;
}
public static Action<T1> ThunkCallback<T1>(Action<T1> callback)
{
return (new ActionThunk<T1>(callback)).ThunkFrame;
}
[SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule,
Justification = "These are the core methods that should be used for all other Guid(string) calls.")]
public static Guid CreateGuid(string guidString)
{
bool success = false;
Guid result = Guid.Empty;
try
{
result = new Guid(guidString);
success = true;
}
finally
{
if (!success)
{
AssertAndThrow("Creation of the Guid failed.");
}
}
return result;
}
[SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule,
Justification = "These are the core methods that should be used for all other Guid(string) calls.")]
public static bool TryCreateGuid(string guidString, out Guid result)
{
bool success = false;
result = Guid.Empty;
try
{
result = new Guid(guidString);
success = true;
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
return success;
}
public static byte[] AllocateByteArray(int size)
{
try
{
// Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls).
return new byte[size];
}
catch (OutOfMemoryException exception)
{
// Desktop wraps the OOM inside a new InsufficientMemoryException, traces, and then throws it.
// Project N and K trace and throw the original OOM. InsufficientMemoryException does not exist in N and K.
Fx.Exception.AsError(exception);
throw;
}
}
public static char[] AllocateCharArray(int size)
{
try
{
// Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls).
return new char[size];
}
catch (OutOfMemoryException exception)
{
// Desktop wraps the OOM inside a new InsufficientMemoryException, traces, and then throws it.
// Project N and K trace and throw the original OOM. InsufficientMemoryException does not exist in N and K.
Fx.Exception.AsError(exception);
throw;
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes,
Justification = "Don't want to hide the exception which is about to crash the process.")]
[Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")]
private static void TraceExceptionNoThrow(Exception exception)
{
try
{
// This call exits the CER. However, when still inside a catch, normal ThreadAbort is prevented.
// Rude ThreadAbort will still be allowed to terminate processing.
Fx.Exception.TraceUnhandledException(exception);
}
catch
{
// This empty catch is only acceptable because we are a) in a CER and b) processing an exception
// which is about to crash the process anyway.
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes,
Justification = "Don't want to hide the exception which is about to crash the process.")]
[SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.IsFatalRule,
Justification = "Don't want to hide the exception which is about to crash the process.")]
[Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")]
private static bool HandleAtThreadBase(Exception exception)
{
// This area is too sensitive to do anything but return.
if (exception == null)
{
Fx.Assert("Null exception in HandleAtThreadBase.");
return false;
}
TraceExceptionNoThrow(exception);
try
{
ExceptionHandler handler = Fx.AsynchronousThreadExceptionHandler;
return handler == null ? false : handler.HandleException(exception);
}
catch (Exception secondException)
{
// Don't let a new exception hide the original exception.
TraceExceptionNoThrow(secondException);
}
return false;
}
private static void UpdateLevel(EtwDiagnosticTrace trace)
{
if (trace == null)
{
return;
}
if (TraceCore.ActionItemCallbackInvokedIsEnabled(trace) ||
TraceCore.ActionItemScheduledIsEnabled(trace))
{
trace.SetEnd2EndActivityTracingEnabled(true);
}
}
private static void UpdateLevel()
{
UpdateLevel(Fx.Trace);
}
public abstract class ExceptionHandler
{
[Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")]
public abstract bool HandleException(Exception exception);
}
public static class Tag
{
public enum CacheAttrition
{
None,
ElementOnTimer,
// A finalizer/WeakReference based cache, where the elements are held by WeakReferences (or hold an
// inner object by a WeakReference), and the weakly-referenced object has a finalizer which cleans the
// item from the cache.
ElementOnGC,
// A cache that provides a per-element token, delegate, interface, or other piece of context that can
// be used to remove the element (such as IDisposable).
ElementOnCallback,
FullPurgeOnTimer,
FullPurgeOnEachAccess,
PartialPurgeOnTimer,
PartialPurgeOnEachAccess,
}
public enum ThrottleAction
{
Reject,
Pause,
}
public enum ThrottleMetric
{
Count,
Rate,
Other,
}
public enum Location
{
InProcess,
OutOfProcess,
LocalSystem,
LocalOrRemoteSystem, // as in a file that might live on a share
RemoteSystem,
}
public enum SynchronizationKind
{
LockStatement,
MonitorWait,
MonitorExplicit,
InterlockedNoSpin,
InterlockedWithSpin,
// Same as LockStatement if the field type is object.
FromFieldType,
}
[Flags]
public enum BlocksUsing
{
MonitorEnter,
MonitorWait,
ManualResetEvent,
AutoResetEvent,
AsyncResult,
IAsyncResult,
PInvoke,
InputQueue,
ThreadNeutralSemaphore,
PrivatePrimitive,
OtherInternalPrimitive,
OtherFrameworkPrimitive,
OtherInterop,
Other,
NonBlocking, // For use by non-blocking SynchronizationPrimitives such as IOThreadScheduler
}
public static class Strings
{
internal const string ExternallyManaged = "externally managed";
internal const string AppDomain = "AppDomain";
internal const string DeclaringInstance = "instance of declaring class";
internal const string Unbounded = "unbounded";
internal const string Infinite = "infinite";
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property | AttributeTargets.Class,
AllowMultiple = true, Inherited = false)]
[Conditional("DEBUG")]
public sealed class FriendAccessAllowedAttribute : Attribute
{
public FriendAccessAllowedAttribute(string assemblyName) :
base()
{
this.AssemblyName = assemblyName;
}
public string AssemblyName { get; set; }
}
public static class Throws
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor,
AllowMultiple = true, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class TimeoutAttribute : ThrowsAttribute
{
public TimeoutAttribute() :
this("The operation timed out.")
{
}
public TimeoutAttribute(string diagnosis) :
base(typeof(TimeoutException), diagnosis)
{
}
}
}
[AttributeUsage(AttributeTargets.Field)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class CacheAttribute : Attribute
{
private readonly Type _elementType;
private readonly CacheAttrition _cacheAttrition;
public CacheAttribute(Type elementType, CacheAttrition cacheAttrition)
{
Scope = Strings.DeclaringInstance;
SizeLimit = Strings.Unbounded;
Timeout = Strings.Infinite;
if (elementType == null)
{
throw Fx.Exception.ArgumentNull("elementType");
}
_elementType = elementType;
_cacheAttrition = cacheAttrition;
}
public Type ElementType
{
get
{
return _elementType;
}
}
public CacheAttrition CacheAttrition
{
get
{
return _cacheAttrition;
}
}
public string Scope { get; set; }
public string SizeLimit { get; set; }
public string Timeout { get; set; }
}
[AttributeUsage(AttributeTargets.Field)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class QueueAttribute : Attribute
{
private readonly Type _elementType;
public QueueAttribute(Type elementType)
{
Scope = Strings.DeclaringInstance;
SizeLimit = Strings.Unbounded;
if (elementType == null)
{
throw Fx.Exception.ArgumentNull("elementType");
}
_elementType = elementType;
}
public Type ElementType
{
get
{
return _elementType;
}
}
public string Scope { get; set; }
public string SizeLimit { get; set; }
public bool StaleElementsRemovedImmediately { get; set; }
public bool EnqueueThrowsIfFull { get; set; }
}
[AttributeUsage(AttributeTargets.Field)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class ThrottleAttribute : Attribute
{
private readonly ThrottleAction _throttleAction;
private readonly ThrottleMetric _throttleMetric;
private readonly string _limit;
public ThrottleAttribute(ThrottleAction throttleAction, ThrottleMetric throttleMetric, string limit)
{
Scope = Strings.AppDomain;
if (string.IsNullOrEmpty(limit))
{
throw Fx.Exception.ArgumentNullOrEmpty("limit");
}
_throttleAction = throttleAction;
_throttleMetric = throttleMetric;
_limit = limit;
}
public ThrottleAction ThrottleAction
{
get
{
return _throttleAction;
}
}
public ThrottleMetric ThrottleMetric
{
get
{
return _throttleMetric;
}
}
public string Limit
{
get
{
return _limit;
}
}
public string Scope
{
get; set;
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Constructor,
AllowMultiple = true, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class ExternalResourceAttribute : Attribute
{
private readonly Location _location;
private readonly string _description;
public ExternalResourceAttribute(Location location, string description)
{
_location = location;
_description = description;
}
public Location Location
{
get
{
return _location;
}
}
public string Description
{
get
{
return _description;
}
}
}
// Set on a class when that class uses lock (this) - acts as though it were on a field
// private object this;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Class, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class SynchronizationObjectAttribute : Attribute
{
public SynchronizationObjectAttribute()
{
Blocking = true;
Scope = Strings.DeclaringInstance;
Kind = SynchronizationKind.FromFieldType;
}
public bool Blocking { get; set; }
public string Scope { get; set; }
public SynchronizationKind Kind { get; set; }
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class SynchronizationPrimitiveAttribute : Attribute
{
private readonly BlocksUsing _blocksUsing;
public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing)
{
_blocksUsing = blocksUsing;
}
public BlocksUsing BlocksUsing
{
get
{
return _blocksUsing;
}
}
public bool SupportsAsync { get; set; }
public bool Spins { get; set; }
public string ReleaseMethod { get; set; }
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class BlockingAttribute : Attribute
{
public BlockingAttribute()
{
}
public string CancelMethod { get; set; }
public Type CancelDeclaringType { get; set; }
public string Conditional { get; set; }
}
// Sometime a method will call a conditionally-blocking method in such a way that it is guaranteed
// not to block (i.e. the condition can be Asserted false). Such a method can be marked as
// GuaranteeNonBlocking as an assertion that the method doesn't block despite calling a blocking method.
//
// Methods that don't call blocking methods and aren't marked as Blocking are assumed not to block, so
// they do not require this attribute.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class GuaranteeNonBlockingAttribute : Attribute
{
public GuaranteeNonBlockingAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class NonThrowingAttribute : Attribute
{
public NonThrowingAttribute()
{
}
}
[SuppressMessage(FxCop.Category.Performance, "CA1813:AvoidUnsealedAttributes",
Justification = "This is intended to be an attribute heirarchy. It does not affect product perf.")]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor,
AllowMultiple = true, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public class ThrowsAttribute : Attribute
{
private readonly Type _exceptionType;
private readonly string _diagnosis;
public ThrowsAttribute(Type exceptionType, string diagnosis)
{
if (exceptionType == null)
{
throw Fx.Exception.ArgumentNull("exceptionType");
}
if (string.IsNullOrEmpty(diagnosis))
{
throw Fx.Exception.ArgumentNullOrEmpty("diagnosis");
}
_exceptionType = exceptionType;
_diagnosis = diagnosis;
}
public Type ExceptionType
{
get
{
return _exceptionType;
}
}
public string Diagnosis
{
get
{
return _diagnosis;
}
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class InheritThrowsAttribute : Attribute
{
public InheritThrowsAttribute()
{
}
public Type FromDeclaringType { get; set; }
public string From { get; set; }
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class KnownXamlExternalAttribute : Attribute
{
public KnownXamlExternalAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class XamlVisibleAttribute : Attribute
{
public XamlVisibleAttribute()
: this(true)
{
}
public XamlVisibleAttribute(bool visible)
{
this.Visible = visible;
}
public bool Visible
{
get;
private set;
}
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class |
AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface |
AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class SecurityNoteAttribute : Attribute
{
public SecurityNoteAttribute()
{
}
public string Critical
{
get;
set;
}
public string Safe
{
get;
set;
}
public string Miscellaneous
{
get;
set;
}
}
}
internal abstract class Thunk<T> where T : class
{
[Fx.Tag.SecurityNote(Critical = "Make these safe to use in SecurityCritical contexts.")]
[SecurityCritical]
private T _callback;
[Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data provided by caller.")]
[SecuritySafeCritical]
protected Thunk(T callback)
{
_callback = callback;
}
internal T Callback
{
[Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data is not privileged.")]
[SecuritySafeCritical]
get
{
return _callback;
}
}
}
internal sealed class ActionThunk<T1> : Thunk<Action<T1>>
{
public ActionThunk(Action<T1> callback) : base(callback)
{
}
public Action<T1> ThunkFrame
{
get
{
return new Action<T1>(UnhandledExceptionFrame);
}
}
[Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand",
Safe = "Guaranteed not to call into PT user code from the finally.")]
[SecuritySafeCritical]
private void UnhandledExceptionFrame(T1 result)
{
try
{
Callback(result);
}
catch (Exception exception)
{
if (!Fx.HandleAtThreadBase(exception))
{
throw;
}
}
}
}
internal sealed class AsyncThunk : Thunk<AsyncCallback>
{
public AsyncThunk(AsyncCallback callback) : base(callback)
{
}
public AsyncCallback ThunkFrame
{
get
{
return new AsyncCallback(UnhandledExceptionFrame);
}
}
[Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand",
Safe = "Guaranteed not to call into PT user code from the finally.")]
[SecuritySafeCritical]
private void UnhandledExceptionFrame(IAsyncResult result)
{
try
{
Callback(result);
}
catch (Exception exception)
{
if (!Fx.HandleAtThreadBase(exception))
{
throw;
}
}
}
}
internal class InternalException : Exception
{
public InternalException(string description)
: base(InternalSR.ShipAssertExceptionMessage(description))
{
}
protected InternalException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
throw new PlatformNotSupportedException();
}
}
[Serializable]
internal class FatalInternalException : InternalException
{
public FatalInternalException(string description)
: base(description)
{
}
protected FatalInternalException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
throw new PlatformNotSupportedException();
}
}
}
}
| |
using ClosedXML.Excel.CalcEngine;
using ClosedXML.Extensions;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
namespace ClosedXML.Excel
{
public enum XLEventTracking { Enabled, Disabled }
public enum XLCalculateMode
{
Auto,
AutoNoTable,
Manual,
Default
};
public enum XLReferenceStyle
{
R1C1,
A1,
Default
};
public enum XLCellSetValueBehavior
{
/// <summary>
/// Analyze input string and convert value. For avoid analyzing use escape symbol '
/// </summary>
Smart = 0,
/// <summary>
/// Direct set value. If value has unsupported type - value will be stored as string returned by <see
/// cref = "object.ToString()" />
/// </summary>
Simple = 1,
}
public partial class XLWorkbook : IXLWorkbook
{
#region Static
public static IXLStyle DefaultStyle
{
get
{
return XLStyle.Default;
}
}
internal static XLStyleValue DefaultStyleValue
{
get
{
return XLStyleValue.Default;
}
}
public static Double DefaultRowHeight { get; private set; }
public static Double DefaultColumnWidth { get; private set; }
public static IXLPageSetup DefaultPageOptions
{
get
{
var defaultPageOptions = new XLPageSetup(null, null)
{
PageOrientation = XLPageOrientation.Default,
Scale = 100,
PaperSize = XLPaperSize.LetterPaper,
Margins = new XLMargins
{
Top = 0.75,
Bottom = 0.5,
Left = 0.75,
Right = 0.75,
Header = 0.5,
Footer = 0.75
},
ScaleHFWithDocument = true,
AlignHFWithMargins = true,
PrintErrorValue = XLPrintErrorValues.Displayed,
ShowComments = XLShowCommentsValues.None
};
return defaultPageOptions;
}
}
public static IXLOutline DefaultOutline
{
get
{
return new XLOutline(null)
{
SummaryHLocation = XLOutlineSummaryHLocation.Right,
SummaryVLocation = XLOutlineSummaryVLocation.Bottom
};
}
}
/// <summary>
/// Behavior for <see cref = "IXLCell.set_Value" />
/// </summary>
public static XLCellSetValueBehavior CellSetValueBehavior { get; set; }
public static XLWorkbook OpenFromTemplate(String path)
{
return new XLWorkbook(path, true);
}
#endregion Static
internal readonly List<UnsupportedSheet> UnsupportedSheets =
new List<UnsupportedSheet>();
public XLEventTracking EventTracking { get; set; }
/// <summary>
/// Counter increasing at workbook data change. Serves to determine if the cell formula
/// has to be recalculated.
/// </summary>
internal long RecalculationCounter { get; private set; }
/// <summary>
/// Notify that workbook data has been changed which means that cached formula values
/// need to be re-evaluated.
/// </summary>
internal void InvalidateFormulas()
{
RecalculationCounter++;
}
#region Nested Type : XLLoadSource
private enum XLLoadSource
{
New,
File,
Stream
};
#endregion Nested Type: XLLoadSource
internal XLWorksheets WorksheetsInternal { get; private set; }
/// <summary>
/// Gets an object to manipulate the worksheets.
/// </summary>
public IXLWorksheets Worksheets
{
get { return WorksheetsInternal; }
}
/// <summary>
/// Gets an object to manipulate this workbook's named ranges.
/// </summary>
public IXLNamedRanges NamedRanges { get; private set; }
/// <summary>
/// Gets an object to manipulate this workbook's theme.
/// </summary>
public IXLTheme Theme { get; private set; }
/// <summary>
/// Gets or sets the default style for the workbook.
/// <para>All new worksheets will use this style.</para>
/// </summary>
public IXLStyle Style { get; set; }
/// <summary>
/// Gets or sets the default row height for the workbook.
/// <para>All new worksheets will use this row height.</para>
/// </summary>
public Double RowHeight { get; set; }
/// <summary>
/// Gets or sets the default column width for the workbook.
/// <para>All new worksheets will use this column width.</para>
/// </summary>
public Double ColumnWidth { get; set; }
/// <summary>
/// Gets or sets the default page options for the workbook.
/// <para>All new worksheets will use these page options.</para>
/// </summary>
public IXLPageSetup PageOptions { get; set; }
/// <summary>
/// Gets or sets the default outline options for the workbook.
/// <para>All new worksheets will use these outline options.</para>
/// </summary>
public IXLOutline Outline { get; set; }
/// <summary>
/// Gets or sets the workbook's properties.
/// </summary>
public XLWorkbookProperties Properties { get; set; }
/// <summary>
/// Gets or sets the workbook's calculation mode.
/// </summary>
public XLCalculateMode CalculateMode { get; set; }
public Boolean CalculationOnSave { get; set; }
public Boolean ForceFullCalculation { get; set; }
public Boolean FullCalculationOnLoad { get; set; }
public Boolean FullPrecision { get; set; }
/// <summary>
/// Gets or sets the workbook's reference style.
/// </summary>
public XLReferenceStyle ReferenceStyle { get; set; }
public IXLCustomProperties CustomProperties { get; private set; }
public Boolean ShowFormulas { get; set; }
public Boolean ShowGridLines { get; set; }
public Boolean ShowOutlineSymbols { get; set; }
public Boolean ShowRowColHeaders { get; set; }
public Boolean ShowRuler { get; set; }
public Boolean ShowWhiteSpace { get; set; }
public Boolean ShowZeros { get; set; }
public Boolean RightToLeft { get; set; }
public Boolean DefaultShowFormulas
{
get { return false; }
}
public Boolean DefaultShowGridLines
{
get { return true; }
}
public Boolean DefaultShowOutlineSymbols
{
get { return true; }
}
public Boolean DefaultShowRowColHeaders
{
get { return true; }
}
public Boolean DefaultShowRuler
{
get { return true; }
}
public Boolean DefaultShowWhiteSpace
{
get { return true; }
}
public Boolean DefaultShowZeros
{
get { return true; }
}
public Boolean DefaultRightToLeft
{
get { return false; }
}
private void InitializeTheme()
{
Theme = new XLTheme
{
Text1 = XLColor.FromHtml("#FF000000"),
Background1 = XLColor.FromHtml("#FFFFFFFF"),
Text2 = XLColor.FromHtml("#FF1F497D"),
Background2 = XLColor.FromHtml("#FFEEECE1"),
Accent1 = XLColor.FromHtml("#FF4F81BD"),
Accent2 = XLColor.FromHtml("#FFC0504D"),
Accent3 = XLColor.FromHtml("#FF9BBB59"),
Accent4 = XLColor.FromHtml("#FF8064A2"),
Accent5 = XLColor.FromHtml("#FF4BACC6"),
Accent6 = XLColor.FromHtml("#FFF79646"),
Hyperlink = XLColor.FromHtml("#FF0000FF"),
FollowedHyperlink = XLColor.FromHtml("#FF800080")
};
}
internal XLColor GetXLColor(XLThemeColor themeColor)
{
switch (themeColor)
{
case XLThemeColor.Text1:
return Theme.Text1;
case XLThemeColor.Background1:
return Theme.Background1;
case XLThemeColor.Text2:
return Theme.Text2;
case XLThemeColor.Background2:
return Theme.Background2;
case XLThemeColor.Accent1:
return Theme.Accent1;
case XLThemeColor.Accent2:
return Theme.Accent2;
case XLThemeColor.Accent3:
return Theme.Accent3;
case XLThemeColor.Accent4:
return Theme.Accent4;
case XLThemeColor.Accent5:
return Theme.Accent5;
case XLThemeColor.Accent6:
return Theme.Accent6;
default:
throw new ArgumentException("Invalid theme color");
}
}
public IXLNamedRange NamedRange(String rangeName)
{
if (rangeName.Contains("!"))
{
var split = rangeName.Split('!');
var first = split[0];
var wsName = first.StartsWith("'") ? first.Substring(1, first.Length - 2) : first;
var name = split[1];
if (TryGetWorksheet(wsName, out IXLWorksheet ws))
{
var range = ws.NamedRange(name);
return range ?? NamedRange(name);
}
return null;
}
return NamedRanges.NamedRange(rangeName);
}
public Boolean TryGetWorksheet(String name, out IXLWorksheet worksheet)
{
return Worksheets.TryGetWorksheet(name, out worksheet);
}
public IXLRange RangeFromFullAddress(String rangeAddress, out IXLWorksheet ws)
{
ws = null;
if (!rangeAddress.Contains('!')) return null;
var split = rangeAddress.Split('!');
var wsName = split[0].UnescapeSheetName();
if (TryGetWorksheet(wsName, out ws))
{
return ws.Range(split[1]);
}
return null;
}
public IXLCell CellFromFullAddress(String cellAddress, out IXLWorksheet ws)
{
ws = null;
if (!cellAddress.Contains('!')) return null;
var split = cellAddress.Split('!');
var wsName = split[0].UnescapeSheetName();
if (TryGetWorksheet(wsName, out ws))
{
return ws.Cell(split[1]);
}
return null;
}
/// <summary>
/// Saves the current workbook.
/// </summary>
public void Save()
{
#if DEBUG
Save(true, false);
#else
Save(false, false);
#endif
}
/// <summary>
/// Saves the current workbook and optionally performs validation
/// </summary>
public void Save(Boolean validate, Boolean evaluateFormulae = false)
{
Save(new SaveOptions
{
ValidatePackage = validate,
EvaluateFormulasBeforeSaving = evaluateFormulae,
GenerateCalculationChain = true
});
}
public void Save(SaveOptions options)
{
checkForWorksheetsPresent();
if (_loadSource == XLLoadSource.New)
throw new InvalidOperationException("This is a new file. Please use one of the 'SaveAs' methods.");
if (_loadSource == XLLoadSource.Stream)
{
CreatePackage(_originalStream, false, _spreadsheetDocumentType, options);
}
else
CreatePackage(_originalFile, _spreadsheetDocumentType, options);
}
/// <summary>
/// Saves the current workbook to a file.
/// </summary>
public void SaveAs(String file)
{
#if DEBUG
SaveAs(file, true, false);
#else
SaveAs(file, false, false);
#endif
}
/// <summary>
/// Saves the current workbook to a file and optionally validates it.
/// </summary>
public void SaveAs(String file, Boolean validate, Boolean evaluateFormulae = false)
{
SaveAs(file, new SaveOptions
{
ValidatePackage = validate,
EvaluateFormulasBeforeSaving = evaluateFormulae,
GenerateCalculationChain = true
});
}
public void SaveAs(String file, SaveOptions options)
{
checkForWorksheetsPresent();
PathHelper.CreateDirectory(Path.GetDirectoryName(file));
if (_loadSource == XLLoadSource.New)
{
if (File.Exists(file))
File.Delete(file);
CreatePackage(file, GetSpreadsheetDocumentType(file), options);
}
else if (_loadSource == XLLoadSource.File)
{
if (String.Compare(_originalFile.Trim(), file.Trim(), true) != 0)
{
File.Copy(_originalFile, file, true);
File.SetAttributes(file, FileAttributes.Normal);
}
CreatePackage(file, GetSpreadsheetDocumentType(file), options);
}
else if (_loadSource == XLLoadSource.Stream)
{
_originalStream.Position = 0;
using (var fileStream = File.Create(file))
{
CopyStream(_originalStream, fileStream);
CreatePackage(fileStream, false, _spreadsheetDocumentType, options);
}
}
_loadSource = XLLoadSource.File;
_originalFile = file;
_originalStream = null;
}
private static SpreadsheetDocumentType GetSpreadsheetDocumentType(string filePath)
{
var extension = Path.GetExtension(filePath);
if (extension == null) throw new ArgumentException("Empty extension is not supported.");
extension = extension.Substring(1).ToLowerInvariant();
switch (extension)
{
case "xlsm":
return SpreadsheetDocumentType.MacroEnabledWorkbook;
case "xltm":
return SpreadsheetDocumentType.MacroEnabledTemplate;
case "xlsx":
return SpreadsheetDocumentType.Workbook;
case "xltx":
return SpreadsheetDocumentType.Template;
default:
throw new ArgumentException(String.Format("Extension '{0}' is not supported. Supported extensions are '.xlsx', '.xslm', '.xltx' and '.xltm'.", extension));
}
}
private void checkForWorksheetsPresent()
{
if (!Worksheets.Any())
throw new InvalidOperationException("Workbooks need at least one worksheet.");
}
/// <summary>
/// Saves the current workbook to a stream.
/// </summary>
public void SaveAs(Stream stream)
{
#if DEBUG
SaveAs(stream, true, false);
#else
SaveAs(stream, false, false);
#endif
}
/// <summary>
/// Saves the current workbook to a stream and optionally validates it.
/// </summary>
public void SaveAs(Stream stream, Boolean validate, Boolean evaluateFormulae = false)
{
SaveAs(stream, new SaveOptions
{
ValidatePackage = validate,
EvaluateFormulasBeforeSaving = evaluateFormulae,
GenerateCalculationChain = true
});
}
public void SaveAs(Stream stream, SaveOptions options)
{
checkForWorksheetsPresent();
if (_loadSource == XLLoadSource.New)
{
// dm 20130422, this method or better the method SpreadsheetDocument.Create which is called
// inside of 'CreatePackage' need a stream which CanSeek & CanRead
// and an ordinary Response stream of a webserver can't do this
// so we have to ask and provide a way around this
if (stream.CanRead && stream.CanSeek && stream.CanWrite)
{
// all is fine the package can be created in a direct way
CreatePackage(stream, true, _spreadsheetDocumentType, options);
}
else
{
// the harder way
MemoryStream ms = new MemoryStream();
CreatePackage(ms, true, _spreadsheetDocumentType, options);
// not really nessesary, because I changed CopyStream too.
// but for better understanding and if somebody in the future
// provide an changed version of CopyStream
ms.Position = 0;
CopyStream(ms, stream);
}
}
else if (_loadSource == XLLoadSource.File)
{
using (var fileStream = new FileStream(_originalFile, FileMode.Open, FileAccess.Read))
{
CopyStream(fileStream, stream);
}
CreatePackage(stream, false, _spreadsheetDocumentType, options);
}
else if (_loadSource == XLLoadSource.Stream)
{
_originalStream.Position = 0;
if (_originalStream != stream)
CopyStream(_originalStream, stream);
CreatePackage(stream, false, _spreadsheetDocumentType, options);
}
_loadSource = XLLoadSource.Stream;
_originalStream = stream;
_originalFile = null;
}
internal static void CopyStream(Stream input, Stream output)
{
var buffer = new byte[8 * 1024];
int len;
// dm 20130422, it is always a good idea to rewind the input stream, or not?
if (input.CanSeek)
input.Seek(0, SeekOrigin.Begin);
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
output.Write(buffer, 0, len);
// dm 20130422, and flushing the output after write
output.Flush();
}
public IXLWorksheet Worksheet(String name)
{
return WorksheetsInternal.Worksheet(name);
}
public IXLWorksheet Worksheet(Int32 position)
{
return WorksheetsInternal.Worksheet(position);
}
public IXLCustomProperty CustomProperty(String name)
{
return CustomProperties.CustomProperty(name);
}
public IXLCells FindCells(Func<IXLCell, Boolean> predicate)
{
var cells = new XLCells(false, false);
foreach (XLWorksheet ws in WorksheetsInternal)
{
foreach (XLCell cell in ws.CellsUsed(true))
{
if (predicate(cell))
cells.Add(cell);
}
}
return cells;
}
public IXLRows FindRows(Func<IXLRow, Boolean> predicate)
{
var rows = new XLRows(null);
foreach (XLWorksheet ws in WorksheetsInternal)
{
foreach (IXLRow row in ws.Rows().Where(predicate))
rows.Add(row as XLRow);
}
return rows;
}
public IXLColumns FindColumns(Func<IXLColumn, Boolean> predicate)
{
var columns = new XLColumns(null);
foreach (XLWorksheet ws in WorksheetsInternal)
{
foreach (IXLColumn column in ws.Columns().Where(predicate))
columns.Add(column as XLColumn);
}
return columns;
}
/// <summary>
/// Searches the cells' contents for a given piece of text
/// </summary>
/// <param name="searchText">The search text.</param>
/// <param name="compareOptions">The compare options.</param>
/// <param name="searchFormulae">if set to <c>true</c> search formulae instead of cell values.</param>
/// <returns></returns>
public IEnumerable<IXLCell> Search(String searchText, CompareOptions compareOptions = CompareOptions.Ordinal, Boolean searchFormulae = false)
{
foreach (var ws in WorksheetsInternal)
{
foreach (var cell in ws.Search(searchText, compareOptions, searchFormulae))
yield return cell;
}
}
#region Fields
private XLLoadSource _loadSource = XLLoadSource.New;
private String _originalFile;
private Stream _originalStream;
#endregion Fields
#region Constructor
/// <summary>
/// Creates a new Excel workbook.
/// </summary>
public XLWorkbook()
: this(XLEventTracking.Enabled)
{
}
internal XLWorkbook(String file, Boolean asTemplate)
: this(XLEventTracking.Enabled)
{
LoadSheetsFromTemplate(file);
}
public XLWorkbook(XLEventTracking eventTracking)
{
EventTracking = eventTracking;
DefaultRowHeight = 15;
DefaultColumnWidth = 8.43;
Style = new XLStyle(null, DefaultStyle);
RowHeight = DefaultRowHeight;
ColumnWidth = DefaultColumnWidth;
PageOptions = DefaultPageOptions;
Outline = DefaultOutline;
Properties = new XLWorkbookProperties();
CalculateMode = XLCalculateMode.Default;
ReferenceStyle = XLReferenceStyle.Default;
InitializeTheme();
ShowFormulas = DefaultShowFormulas;
ShowGridLines = DefaultShowGridLines;
ShowOutlineSymbols = DefaultShowOutlineSymbols;
ShowRowColHeaders = DefaultShowRowColHeaders;
ShowRuler = DefaultShowRuler;
ShowWhiteSpace = DefaultShowWhiteSpace;
ShowZeros = DefaultShowZeros;
RightToLeft = DefaultRightToLeft;
WorksheetsInternal = new XLWorksheets(this);
NamedRanges = new XLNamedRanges(this);
CustomProperties = new XLCustomProperties(this);
ShapeIdManager = new XLIdManager();
Author = Environment.UserName;
}
/// <summary>
/// Opens an existing workbook from a file.
/// </summary>
/// <param name = "file">The file to open.</param>
public XLWorkbook(String file)
: this(file, XLEventTracking.Enabled)
{
}
public XLWorkbook(String file, XLEventTracking eventTracking)
: this(eventTracking)
{
_loadSource = XLLoadSource.File;
_originalFile = file;
_spreadsheetDocumentType = GetSpreadsheetDocumentType(_originalFile);
Load(file);
}
/// <summary>
/// Opens an existing workbook from a stream.
/// </summary>
/// <param name = "stream">The stream to open.</param>
public XLWorkbook(Stream stream) : this(stream, XLEventTracking.Enabled)
{
}
public XLWorkbook(Stream stream, XLEventTracking eventTracking)
: this(eventTracking)
{
_loadSource = XLLoadSource.Stream;
_originalStream = stream;
Load(stream);
}
#endregion Constructor
#region Nested type: UnsupportedSheet
internal sealed class UnsupportedSheet
{
public Boolean IsActive;
public UInt32 SheetId;
public Int32 Position;
}
#endregion Nested type: UnsupportedSheet
public IXLCell Cell(String namedCell)
{
var namedRange = NamedRange(namedCell);
if (namedRange != null)
{
return namedRange.Ranges?.FirstOrDefault()?.FirstCell();
}
else
return CellFromFullAddress(namedCell, out _);
}
public IXLCells Cells(String namedCells)
{
return Ranges(namedCells).Cells();
}
public IXLRange Range(String range)
{
var namedRange = NamedRange(range);
if (namedRange != null)
return namedRange.Ranges.FirstOrDefault();
else
return RangeFromFullAddress(range, out _);
}
public IXLRanges Ranges(String ranges)
{
var retVal = new XLRanges();
var rangePairs = ranges.Split(',');
foreach (var range in rangePairs.Select(r => Range(r.Trim())).Where(range => range != null))
{
retVal.Add(range);
}
return retVal;
}
internal XLIdManager ShapeIdManager { get; private set; }
public void Dispose()
{
Worksheets.ForEach(w => w.Dispose());
}
public Boolean Use1904DateSystem { get; set; }
public XLWorkbook SetUse1904DateSystem()
{
return SetUse1904DateSystem(true);
}
public XLWorkbook SetUse1904DateSystem(Boolean value)
{
Use1904DateSystem = value;
return this;
}
public IXLWorksheet AddWorksheet(String sheetName)
{
return Worksheets.Add(sheetName);
}
public IXLWorksheet AddWorksheet(String sheetName, Int32 position)
{
return Worksheets.Add(sheetName, position);
}
public IXLWorksheet AddWorksheet(DataTable dataTable)
{
return Worksheets.Add(dataTable);
}
public void AddWorksheet(DataSet dataSet)
{
Worksheets.Add(dataSet);
}
public void AddWorksheet(IXLWorksheet worksheet)
{
worksheet.CopyTo(this, worksheet.Name);
}
public IXLWorksheet AddWorksheet(DataTable dataTable, String sheetName)
{
return Worksheets.Add(dataTable, sheetName);
}
private XLCalcEngine _calcEngine;
private XLCalcEngine CalcEngine
{
get { return _calcEngine ?? (_calcEngine = new XLCalcEngine(this)); }
}
public Object Evaluate(String expression)
{
return CalcEngine.Evaluate(expression);
}
/// <summary>
/// Force recalculation of all cell formulas.
/// </summary>
public void RecalculateAllFormulas()
{
InvalidateFormulas();
Worksheets.ForEach(sheet => sheet.RecalculateAllFormulas());
}
private static XLCalcEngine _calcEngineExpr;
private SpreadsheetDocumentType _spreadsheetDocumentType;
private static XLCalcEngine CalcEngineExpr
{
get { return _calcEngineExpr ?? (_calcEngineExpr = new XLCalcEngine()); }
}
public static Object EvaluateExpr(String expression)
{
return CalcEngineExpr.Evaluate(expression);
}
public String Author { get; set; }
public Boolean LockStructure { get; set; }
public XLWorkbook SetLockStructure(Boolean value) { LockStructure = value; return this; }
public Boolean LockWindows { get; set; }
public XLWorkbook SetLockWindows(Boolean value) { LockWindows = value; return this; }
internal HexBinaryValue LockPassword { get; set; }
public Boolean IsPasswordProtected { get { return LockPassword != null; } }
public void Protect(Boolean lockStructure, Boolean lockWindows, String workbookPassword)
{
if (IsPasswordProtected && workbookPassword == null)
throw new InvalidOperationException("The workbook is password protected");
var hashPassword = workbookPassword.HashPassword();
if (IsPasswordProtected && LockPassword != hashPassword)
throw new ArgumentException("Invalid password");
if (IsPasswordProtected && (lockStructure || lockWindows))
throw new InvalidOperationException("The workbook is already protected");
if (IsPasswordProtected && hashPassword != null && !lockStructure && !lockWindows)
{
// Workbook currently protected, but we're unsetting the 2 flags
// Hence unprotect workbook using password.
LockPassword = null;
}
if (!IsPasswordProtected && hashPassword != null && (lockStructure || lockWindows))
{
//Protect workbook using password.
LockPassword = hashPassword;
}
LockStructure = lockStructure;
LockWindows = lockWindows;
}
public void Protect()
{
Protect(true);
}
public void Protect(string workbookPassword)
{
Protect(true, false, workbookPassword);
}
public void Protect(Boolean lockStructure)
{
Protect(lockStructure, false);
}
public void Protect(Boolean lockStructure, Boolean lockWindows)
{
Protect(lockStructure, lockWindows, null);
}
public void Unprotect()
{
Protect(false, false);
}
public void Unprotect(string workbookPassword)
{
Protect(false, false, workbookPassword);
}
public override string ToString()
{
switch (_loadSource)
{
case XLLoadSource.New:
return "XLWorkbook(new)";
case XLLoadSource.File:
return String.Format("XLWorkbook({0})", _originalFile);
case XLLoadSource.Stream:
return String.Format("XLWorkbook({0})", _originalStream.ToString());
default:
throw new NotImplementedException();
}
}
public void SuspendEvents()
{
foreach (var ws in WorksheetsInternal)
{
ws.SuspendEvents();
}
}
public void ResumeEvents()
{
foreach (var ws in WorksheetsInternal)
{
ws.ResumeEvents();
}
}
}
}
| |
// 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.Buffers;
using System.Diagnostics.Tracing;
using System.Threading;
using Xunit;
namespace System.Buffers.ArrayPool.Tests
{
public partial class ArrayPoolUnitTests
{
private const int MaxEventWaitTimeoutInMs = 200;
private struct TestStruct
{
internal string InternalRef;
}
/*
NOTE - due to test parallelism and sharing, use an instance pool for testing unless necessary
*/
[Fact]
public static void SharedInstanceCreatesAnInstanceOnFirstCall()
{
Assert.NotNull(ArrayPool<byte>.Shared);
}
[Fact]
public static void SharedInstanceOnlyCreatesOneInstanceOfOneTypep()
{
ArrayPool<byte> instance = ArrayPool<byte>.Shared;
Assert.Same(instance, ArrayPool<byte>.Shared);
}
[Fact]
public static void CreateWillCreateMultipleInstancesOfTheSameType()
{
Assert.NotSame(ArrayPool<byte>.Create(), ArrayPool<byte>.Create());
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public static void CreatingAPoolWithInvalidArrayCountThrows(int length)
{
Assert.Throws<ArgumentOutOfRangeException>("arraysPerBucket", () => ArrayPool<byte>.Create(maxArraysPerBucket: length, maxArrayLength: 16));
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public static void CreatingAPoolWithInvalidMaximumArraySizeThrows(int length)
{
Assert.Throws<ArgumentOutOfRangeException>("maxLength", () => ArrayPool<byte>.Create(maxArrayLength: length, maxArraysPerBucket: 1));
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public static void RentingWithInvalidLengthThrows(int length)
{
ArrayPool<byte> pool = ArrayPool<byte>.Create();
Assert.Throws<ArgumentOutOfRangeException>("minimumLength", () => pool.Rent(length));
}
[Fact]
public static void RentingAValidSizeArraySucceeds()
{
Assert.NotNull(ArrayPool<byte>.Create().Rent(100));
}
[Fact]
public static void RentingMultipleArraysGivesBackDifferentInstances()
{
ArrayPool<byte> instance = ArrayPool<byte>.Create(maxArraysPerBucket: 2, maxArrayLength: 16);
Assert.NotSame(instance.Rent(100), instance.Rent(100));
}
[Fact]
public static void RentingMoreArraysThanSpecifiedInCreateWillStillSucceed()
{
ArrayPool<byte> instance = ArrayPool<byte>.Create(maxArraysPerBucket: 1, maxArrayLength: 16);
Assert.NotNull(instance.Rent(100));
Assert.NotNull(instance.Rent(100));
}
[Fact]
public static void RentCanReturnBiggerArraySizeThanRequested()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArraysPerBucket: 1, maxArrayLength: 32);
byte[] rented = pool.Rent(27);
Assert.NotNull(rented);
Assert.Equal(rented.Length, 32);
}
[Fact]
public static void RentingAnArrayWithLengthGreaterThanSpecifiedInCreateStillSucceeds()
{
Assert.NotNull(ArrayPool<byte>.Create(maxArrayLength: 100, maxArraysPerBucket: 1).Rent(200));
}
[Fact]
public static void CallingReturnBufferWithNullBufferThrows()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create();
Assert.Throws<ArgumentNullException>("buffer", () => pool.Return(null));
}
private static void FillArray(byte[] buffer)
{
for (byte i = 0; i < buffer.Length; i++)
buffer[i] = i;
}
private static void CheckFilledArray(byte[] buffer, Action<byte, byte> assert)
{
for (byte i = 0; i < buffer.Length; i++)
{
assert(buffer[i], i);
}
}
[Fact]
public static void CallingReturnWithoutClearingDoesNotClearTheBuffer()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create();
byte[] buffer = pool.Rent(4);
FillArray(buffer);
pool.Return(buffer, clearArray: false);
CheckFilledArray(buffer, (byte b1, byte b2) => Assert.Equal(b1, b2));
}
[Fact]
public static void CallingReturnWithClearingDoesClearTheBuffer()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create();
byte[] buffer = pool.Rent(4);
FillArray(buffer);
// Note - yes this is bad to hold on to the old instance but we need to validate the contract
pool.Return(buffer, clearArray: true);
CheckFilledArray(buffer, (byte b1, byte b2) => Assert.Equal(b1, default(byte)));
}
[Fact]
public static void CallingReturnOnReferenceTypeArrayDoesNotClearTheArray()
{
ArrayPool<string> pool = ArrayPool<string>.Create();
string[] array = pool.Rent(2);
array[0] = "foo";
array[1] = "bar";
pool.Return(array, clearArray: false);
Assert.NotNull(array[0]);
Assert.NotNull(array[1]);
}
[Fact]
public static void CallingReturnOnReferenceTypeArrayAndClearingSetsTypesToNull()
{
ArrayPool<string> pool = ArrayPool<string>.Create();
string[] array = pool.Rent(2);
array[0] = "foo";
array[1] = "bar";
pool.Return(array, clearArray: true);
Assert.Null(array[0]);
Assert.Null(array[1]);
}
[Fact]
public static void CallingReturnOnValueTypeWithInternalReferenceTypesAndClearingSetsValueTypeToDefault()
{
ArrayPool<TestStruct> pool = ArrayPool<TestStruct>.Create();
TestStruct[] array = pool.Rent(2);
array[0].InternalRef = "foo";
array[1].InternalRef = "bar";
pool.Return(array, clearArray: true);
Assert.Equal(array[0], default(TestStruct));
Assert.Equal(array[1], default(TestStruct));
}
[Fact]
public static void TakingAllBuffersFromABucketPlusAnAllocatedOneShouldAllowReturningAllBuffers()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1);
byte[] rented = pool.Rent(16);
byte[] allocated = pool.Rent(16);
pool.Return(rented);
pool.Return(allocated);
}
[Fact]
public static void NewDefaultArrayPoolWithSmallBufferSizeRoundsToOurSmallestSupportedSize()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 8, maxArraysPerBucket: 1);
byte[] rented = pool.Rent(8);
Assert.True(rented.Length == 16);
}
[Fact]
public static void ReturningABufferGreaterThanMaxSizeDoesNotThrow()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1);
byte[] rented = pool.Rent(32);
pool.Return(rented);
}
[Fact]
public static void RentingAllBuffersAndCallingRentAgainWillAllocateBufferAndReturnIt()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1);
byte[] rented1 = pool.Rent(16);
byte[] rented2 = pool.Rent(16);
Assert.NotNull(rented1);
Assert.NotNull(rented2);
}
[Fact]
public static void RentingReturningThenRentingABufferShouldNotAllocate()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1);
byte[] bt = pool.Rent(16);
int id = bt.GetHashCode();
pool.Return(bt);
bt = pool.Rent(16);
Assert.Equal(id, bt.GetHashCode());
}
private static void ActionFiresSpecificEvent(Action body, int eventId, AutoResetEvent are)
{
using (TestEventListener listener = new TestEventListener("System.Buffers.BufferPoolEventSource", EventLevel.Verbose))
{
listener.RunWithCallback((EventWrittenEventArgs e) =>
{
if (e.EventId == eventId)
are.Set();
}, body);
}
}
[Fact]
public static void RentBufferFiresRentedDiagnosticEvent()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1);
AutoResetEvent are = new AutoResetEvent(false);
ActionFiresSpecificEvent(() =>
{
byte[] bt = pool.Rent(16);
Assert.True(are.WaitOne(MaxEventWaitTimeoutInMs));
}, 1, are);
}
[Fact]
public static void ReturnBufferFiresDiagnosticEvent()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1);
AutoResetEvent are = new AutoResetEvent(false);
ActionFiresSpecificEvent(() =>
{
byte[] bt = pool.Rent(16);
pool.Return(bt);
Assert.True(are.WaitOne(MaxEventWaitTimeoutInMs));
}, 3, are);
}
[Fact]
public static void FirstCallToRentBufferFiresCreatedDiagnosticEvent()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1);
AutoResetEvent are = new AutoResetEvent(false);
ActionFiresSpecificEvent(() =>
{
byte[] bt = pool.Rent(16);
Assert.True(are.WaitOne(MaxEventWaitTimeoutInMs));
}, 2, are);
}
[Fact]
public static void AllocatingABufferDueToBucketExhaustionFiresDiagnosticEvent()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1);
AutoResetEvent are = new AutoResetEvent(false);
ActionFiresSpecificEvent(() =>
{
byte[] bt = pool.Rent(16);
byte[] bt2 = pool.Rent(16);
Assert.True(are.WaitOne(MaxEventWaitTimeoutInMs));
}, 2, are);
}
[Fact]
public static void RentingBufferOverConfiguredMaximumSizeFiresDiagnosticEvent()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1);
AutoResetEvent are = new AutoResetEvent(false);
ActionFiresSpecificEvent(() =>
{
byte[] bt = pool.Rent(64);
Assert.True(are.WaitOne(MaxEventWaitTimeoutInMs));
}, 2, are);
}
[Fact]
public static void ExhaustingBufferBucketFiresDiagnosticEvent()
{
ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1);
AutoResetEvent are = new AutoResetEvent(false);
ActionFiresSpecificEvent(() =>
{
byte[] bt = pool.Rent(16);
byte[] bt2 = pool.Rent(16);
Assert.True(are.WaitOne(MaxEventWaitTimeoutInMs));
}, 4, are);
}
}
}
| |
// Copyright (c) .NET Foundation. 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.Globalization;
using System.IO;
using System.Text;
namespace Microsoft.AspNet.SignalR.Messaging
{
internal unsafe class Cursor
{
private static char[] _escapeChars = new[] { '\\', '|', ',' };
private string _escapedKey;
public string Key { get; private set; }
public ulong Id { get; set; }
public static Cursor Clone(Cursor cursor)
{
return new Cursor(cursor.Key, cursor.Id, cursor._escapedKey);
}
public Cursor(string key, ulong id)
: this(key, id, Escape(key))
{
}
public Cursor(string key, ulong id, string minifiedKey)
{
Key = key;
Id = id;
_escapedKey = minifiedKey;
}
public static void WriteCursors(TextWriter textWriter, IList<Cursor> cursors, string prefix)
{
textWriter.Write(prefix);
for (int i = 0; i < cursors.Count; i++)
{
if (i > 0)
{
textWriter.Write('|');
}
Cursor cursor = cursors[i];
textWriter.Write(cursor._escapedKey);
textWriter.Write(',');
WriteUlongAsHexToBuffer(cursor.Id, textWriter);
}
}
internal static void WriteUlongAsHexToBuffer(ulong value, TextWriter textWriter)
{
// This tracks the length of the output and serves as the index for the next character to be written into the pBuffer.
// The length could reach up to 16 characters, so at least that much space should remain in the pBuffer.
int length = 0;
// Write the hex value from left to right into the buffer without zero padding.
for (int i = 0; i < 16; i++)
{
// Convert the first 4 bits of the value to a valid hex character.
char hexChar = Int32ToHex((int)(value >> 60));
value <<= 4;
// Don't increment length if it would just add zero padding
if (length != 0 || hexChar != '0')
{
textWriter.Write(hexChar);
length++;
}
}
if (length == 0)
{
textWriter.Write('0');
}
}
private static char Int32ToHex(int value)
{
return (value < 10) ? (char)(value + '0') : (char)(value - 10 + 'A');
}
private static string Escape(string value)
{
// Nothing to do, so bail
if (value.IndexOfAny(_escapeChars) == -1)
{
return value;
}
var sb = new StringBuilder();
// \\ = \
// \| = |
// \, = ,
foreach (var ch in value)
{
switch (ch)
{
case '\\':
sb.Append('\\').Append(ch);
break;
case '|':
sb.Append('\\').Append(ch);
break;
case ',':
sb.Append('\\').Append(ch);
break;
default:
sb.Append(ch);
break;
}
}
return sb.ToString();
}
public static List<Cursor> GetCursors(string cursor, string prefix)
{
return GetCursors(cursor, prefix, s => s);
}
public static List<Cursor> GetCursors(string cursor, string prefix, Func<string, string> keyMaximizer)
{
return GetCursors(cursor, prefix, (key, state) => ((Func<string, string>)state).Invoke(key), keyMaximizer);
}
public static List<Cursor> GetCursors(string cursor, string prefix, Func<string, object, string> keyMaximizer, object state)
{
// Technically GetCursors should never be called with a null value, so this is extra cautious
if (String.IsNullOrEmpty(cursor))
{
throw new FormatException(Resources.Error_InvalidCursorFormat);
}
// If the cursor does not begin with the prefix stream, it isn't necessarily a formatting problem.
// The cursor with a different prefix might have had different, but also valid, formatting.
// Null should be returned so new cursors will be generated
if (!cursor.StartsWith(prefix, StringComparison.Ordinal))
{
return null;
}
var signals = new HashSet<string>();
var cursors = new List<Cursor>();
string currentKey = null;
string currentEscapedKey = null;
ulong currentId;
bool escape = false;
bool consumingKey = true;
var sb = new StringBuilder();
var sbEscaped = new StringBuilder();
Cursor parsedCursor;
for (int i = prefix.Length; i < cursor.Length; i++)
{
var ch = cursor[i];
// escape can only be true if we are consuming the key
if (escape)
{
if (ch != '\\' && ch != ',' && ch != '|')
{
throw new FormatException(Resources.Error_InvalidCursorFormat);
}
sb.Append(ch);
sbEscaped.Append(ch);
escape = false;
}
else
{
if (ch == '\\')
{
if (!consumingKey)
{
throw new FormatException(Resources.Error_InvalidCursorFormat);
}
sbEscaped.Append('\\');
escape = true;
}
else if (ch == ',')
{
if (!consumingKey)
{
throw new FormatException(Resources.Error_InvalidCursorFormat);
}
// For now String.Empty is an acceptable key, but this should change once we verify
// that empty keys cannot be created legitimately.
currentKey = keyMaximizer(sb.ToString(), state);
// If the keyMap cannot find a key, we cannot create an array of cursors.
// This most likely means there was an AppDomain restart or a misbehaving client.
if (currentKey == null)
{
return null;
}
// Don't allow duplicate keys
if (!signals.Add(currentKey))
{
throw new FormatException(Resources.Error_InvalidCursorFormat);
}
currentEscapedKey = sbEscaped.ToString();
sb.Clear();
sbEscaped.Clear();
consumingKey = false;
}
else if (ch == '|')
{
if (consumingKey)
{
throw new FormatException(Resources.Error_InvalidCursorFormat);
}
ParseCursorId(sb, out currentId);
parsedCursor = new Cursor(currentKey, currentId, currentEscapedKey);
cursors.Add(parsedCursor);
sb.Clear();
consumingKey = true;
}
else
{
sb.Append(ch);
if (consumingKey)
{
sbEscaped.Append(ch);
}
}
}
}
if (consumingKey)
{
throw new FormatException(Resources.Error_InvalidCursorFormat);
}
ParseCursorId(sb, out currentId);
parsedCursor = new Cursor(currentKey, currentId, currentEscapedKey);
cursors.Add(parsedCursor);
return cursors;
}
private static void ParseCursorId(StringBuilder sb, out ulong id)
{
string value = sb.ToString();
id = UInt64.Parse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
public override string ToString()
{
return Key;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Avx.IsSupported)
{
{
byte* inBuffer = stackalloc byte[64];
float* inArray = (float*)Align(inBuffer, 32);
float* outArray = stackalloc float[8];
var vf = Avx.LoadAlignedVector256(inArray);
Unsafe.Write(outArray, vf);
for (var i = 0; i < 8; i++)
{
if (BitConverter.SingleToInt32Bits(inArray[i]) != BitConverter.SingleToInt32Bits(outArray[i]))
{
Console.WriteLine("AVX LoadAlignedVector256 failed on float:");
for (var n = 0; n < 8; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
byte* inBuffer = stackalloc byte[64];
double* inArray = (double*)Align(inBuffer, 32);
double* outArray = stackalloc double[4];
var vf = Avx.LoadAlignedVector256(inArray);
Unsafe.Write(outArray, vf);
for (var i = 0; i < 4; i++)
{
if (BitConverter.DoubleToInt64Bits(inArray[i]) != BitConverter.DoubleToInt64Bits(outArray[i]))
{
Console.WriteLine("AVX LoadAlignedVector256 failed on double:");
for (var n = 0; n < 4; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
byte* inBuffer = stackalloc byte[64];
int* inArray = (int*)Align(inBuffer, 32);
int* outArray = stackalloc int[8];
var vf = Avx.LoadAlignedVector256(inArray);
Unsafe.Write(outArray, vf);
for (var i = 0; i < 8; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("AVX LoadAlignedVector256 failed on int:");
for (var n = 0; n < 8; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
byte* inBuffer = stackalloc byte[64];
long* inArray = (long*)Align(inBuffer, 32);
long* outArray = stackalloc long[4];
var vf = Avx.LoadAlignedVector256(inArray);
Unsafe.Write(outArray, vf);
for (var i = 0; i < 4; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("AVX LoadAlignedVector256 failed on long:");
for (var n = 0; n < 4; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
byte* inBuffer = stackalloc byte[64];
uint* inArray = (uint*)Align(inBuffer, 32);
uint* outArray = stackalloc uint[8];
var vf = Avx.LoadAlignedVector256(inArray);
Unsafe.Write(outArray, vf);
for (var i = 0; i < 8; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("AVX LoadAlignedVector256 failed on uint:");
for (var n = 0; n < 8; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
byte* inBuffer = stackalloc byte[64];
ulong* inArray = (ulong*)Align(inBuffer, 32);
ulong* outArray = stackalloc ulong[4];
var vf = Avx.LoadAlignedVector256(inArray);
Unsafe.Write(outArray, vf);
for (var i = 0; i < 4; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("AVX LoadAlignedVector256 failed on ulong:");
for (var n = 0; n < 4; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
byte* inBuffer = stackalloc byte[64];
short* inArray = (short*)Align(inBuffer, 32);
short* outArray = stackalloc short[16];
var vf = Avx.LoadAlignedVector256(inArray);
Unsafe.Write(outArray, vf);
for (var i = 0; i < 16; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("AVX LoadAlignedVector256 failed on short:");
for (var n = 0; n < 16; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
byte* inBuffer = stackalloc byte[64];
ushort* inArray = (ushort*)Align(inBuffer, 32);
ushort* outArray = stackalloc ushort[16];
var vf = Avx.LoadAlignedVector256(inArray);
Unsafe.Write(outArray, vf);
for (var i = 0; i < 16; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("AVX LoadAlignedVector256 failed on ushort:");
for (var n = 0; n < 16; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
byte* inBuffer = stackalloc byte[64];
sbyte* inArray = (sbyte*)Align(inBuffer, 32);
sbyte* outArray = stackalloc sbyte[32];
var vf = Avx.LoadAlignedVector256(inArray);
Unsafe.Write(outArray, vf);
for (var i = 0; i < 32; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("AVX LoadAlignedVector256 failed on sbyte:");
for (var n = 0; n < 32; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
byte* inBuffer = stackalloc byte[64];
byte* inArray = (byte*)Align(inBuffer, 32);
byte* outArray = stackalloc byte[32];
var vf = Avx.LoadAlignedVector256(inArray);
Unsafe.Write(outArray, vf);
for (var i = 0; i < 32; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("AVX LoadAlignedVector256 failed on byte:");
for (var n = 0; n < 32; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
}
return testResult;
}
static unsafe void* Align(byte* buffer, byte expectedAlignment)
{
// Compute how bad the misalignment is, which is at most (expectedAlignment - 1).
// Then subtract that from the expectedAlignment and add it to the original address
// to compute the aligned address.
var misalignment = expectedAlignment - ((ulong)(buffer) % expectedAlignment);
return (void*)(buffer + misalignment);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Securities.Future;
using QuantConnect.Util;
namespace QuantConnect.Tests.Common.Securities.Options
{
[TestFixture, Parallelizable(ParallelScope.Fixtures)]
public class OptionChainProviderTests
{
[Test]
public void BacktestingOptionChainProviderLoadsEquityOptionChain()
{
var provider = new BacktestingOptionChainProvider(TestGlobals.DataProvider);
var twxOptionChain = provider.GetOptionContractList(Symbol.Create("TWX", SecurityType.Equity, Market.USA), new DateTime(2014, 6, 5))
.ToList();
Assert.AreEqual(184, twxOptionChain.Count);
Assert.AreEqual(23m, twxOptionChain.OrderBy(s => s.ID.StrikePrice).First().ID.StrikePrice);
Assert.AreEqual(105m, twxOptionChain.OrderBy(s => s.ID.StrikePrice).Last().ID.StrikePrice);
}
[Test]
public void BacktestingOptionChainProviderLoadsFutureOptionChain()
{
var provider = new BacktestingOptionChainProvider(TestGlobals.DataProvider);
var esOptionChain = provider.GetOptionContractList(
Symbol.CreateFuture(
QuantConnect.Securities.Futures.Indices.SP500EMini,
Market.CME,
new DateTime(2020, 6, 19)),
new DateTime(2020, 1, 5))
.ToList();
Assert.AreEqual(107, esOptionChain.Count);
Assert.AreEqual(2900m, esOptionChain.OrderBy(s => s.ID.StrikePrice).First().ID.StrikePrice);
Assert.AreEqual(3500m, esOptionChain.OrderBy(s => s.ID.StrikePrice).Last().ID.StrikePrice);
}
[Test]
public void BacktestingOptionChainProviderResolvesSymbolMapping()
{
var ticker = "GOOCV"; // Old ticker, should resolve and fetch GOOG
var provider = new BacktestingOptionChainProvider(TestGlobals.DataProvider);
var underlyingSymbol = QuantConnect.Symbol.Create(ticker, SecurityType.Equity, Market.USA);
var alias = "?" + underlyingSymbol.Value;
var optionSymbol = Symbol.CreateOption(
underlyingSymbol,
underlyingSymbol.ID.Market,
Symbol.GetOptionTypeFromUnderlying(underlyingSymbol).DefaultOptionStyle(),
default(OptionRight),
0,
SecurityIdentifier.DefaultDate,
alias);
var googOptionChain = provider.GetOptionContractList(optionSymbol.Underlying, new DateTime(2015, 12, 23))
.ToList();
Assert.AreEqual(118, googOptionChain.Count);
Assert.AreEqual(600m, googOptionChain.OrderBy(s => s.ID.StrikePrice).First().ID.StrikePrice);
Assert.AreEqual(800m, googOptionChain.OrderBy(s => s.ID.StrikePrice).Last().ID.StrikePrice);
}
[Test]
public void CachingProviderCachesSymbolsByDate()
{
var provider = new CachingOptionChainProvider(new DelayedOptionChainProvider(1000));
var stopwatch = Stopwatch.StartNew();
var symbols = provider.GetOptionContractList(Symbol.Empty, new DateTime(2017, 7, 28));
stopwatch.Stop();
Assert.GreaterOrEqual(stopwatch.ElapsedMilliseconds, 1000);
Assert.AreEqual(2, symbols.Count());
stopwatch.Restart();
symbols = provider.GetOptionContractList(Symbol.Empty, new DateTime(2017, 7, 28));
stopwatch.Stop();
Assert.LessOrEqual(stopwatch.ElapsedMilliseconds, 10);
Assert.AreEqual(2, symbols.Count());
stopwatch.Restart();
symbols = provider.GetOptionContractList(Symbol.Empty, new DateTime(2017, 7, 29));
stopwatch.Stop();
Assert.GreaterOrEqual(stopwatch.ElapsedMilliseconds, 1000);
Assert.AreEqual(2, symbols.Count());
}
[Test]
public void LiveOptionChainProviderReturnsData()
{
var provider = new LiveOptionChainProvider();
foreach (var symbol in new[] { Symbols.SPY, Symbols.AAPL, Symbols.MSFT })
{
var result = provider.GetOptionContractList(symbol, DateTime.Today).ToList();
var countCall = result.Count(x => x.ID.OptionRight == OptionRight.Call);
var countPut = result.Count(x => x.ID.OptionRight == OptionRight.Put);
Assert.Greater(countCall, 0);
Assert.Greater(countPut, 0);
}
}
[Test]
public void LiveOptionChainProviderReturnsNoDataForInvalidSymbol()
{
var symbol = Symbol.Create("ABCDEF123", SecurityType.Equity, Market.USA);
var provider = new LiveOptionChainProvider();
var result = provider.GetOptionContractList(symbol, DateTime.Today);
Assert.IsFalse(result.Any());
}
[Test, Ignore("Failing due to timeout, track issue at #5645")]
public void LiveOptionChainProviderReturnsFutureOptionData()
{
var now = DateTime.Now;
var december = new DateTime(now.Year, 12, 1);
var canonicalFuture = Symbol.Create("ES", SecurityType.Future, Market.CME);
var expiry = FuturesExpiryFunctions.FuturesExpiryFunction(canonicalFuture)(december);
// When the current year's december contract expires, the test starts failing.
// This will happen around the last 10 days of December, but will start working
// once we've crossed into the new year.
// Let's try the next listed contract, which is in March of the next year if this is the case.
if (now >= expiry)
{
expiry = now.AddMonths(-now.Month).AddYears(1).AddMonths(3);
}
var underlyingFuture = Symbol.CreateFuture("ES", Market.CME, expiry);
var provider = new LiveOptionChainProvider();
var result = provider.GetOptionContractList(underlyingFuture, now).ToList();
Assert.AreNotEqual(0, result.Count);
foreach (var symbol in result)
{
Assert.IsTrue(symbol.HasUnderlying);
Assert.AreEqual(Market.CME, symbol.ID.Market);
Assert.AreEqual(OptionStyle.American, symbol.ID.OptionStyle);
Assert.GreaterOrEqual(symbol.ID.StrikePrice, 100m);
Assert.Less(symbol.ID.StrikePrice, 30000m);
}
}
[Test, Ignore("Failing due to timeout, track issue at #5645")]
public void LiveOptionChainProviderReturnsNoDataForOldFuture()
{
var now = DateTime.Now;
var december = now.AddMonths(-now.Month).AddYears(-1);
var underlyingFuture = Symbol.CreateFuture("ES", Market.CME, december);
var provider = new LiveOptionChainProvider();
var result = provider.GetOptionContractList(underlyingFuture, december);
Assert.AreEqual(0, result.Count());
}
[TestCase(OptionRight.Call, 1650, 2020, 3, 26)]
[TestCase(OptionRight.Put, 1540, 2020, 3, 26)]
[TestCase(OptionRight.Call, 1600, 2020, 2, 25)]
[TestCase(OptionRight.Put, 1545, 2020, 2, 25)]
public void BacktestingOptionChainProviderReturnsMultipleContractsForZipFileContainingMultipleContracts(
OptionRight right,
int strike,
int year,
int month,
int day)
{
var underlying = Symbol.CreateFuture("GC", Market.COMEX, new DateTime(2020, 4, 28));
var expiry = new DateTime(year, month, day);
var expectedOption = Symbol.CreateOption(
underlying,
Market.COMEX,
OptionStyle.American,
right,
strike,
expiry);
var provider = new BacktestingOptionChainProvider(TestGlobals.DataProvider);
var contracts = provider.GetOptionContractList(underlying, new DateTime(2020, 1, 5))
.ToHashSet();
Assert.IsTrue(
contracts.Contains(expectedOption),
$"Failed to find contract {expectedOption} in: [{string.Join(", ", contracts.Select(s => s.ToString()))}");
}
}
internal class DelayedOptionChainProvider : IOptionChainProvider
{
private readonly int _delayMilliseconds;
public DelayedOptionChainProvider(int delayMilliseconds)
{
_delayMilliseconds = delayMilliseconds;
}
public IEnumerable<Symbol> GetOptionContractList(Symbol symbol, DateTime date)
{
Thread.Sleep(_delayMilliseconds);
return new[] { Symbols.SPY_C_192_Feb19_2016, Symbols.SPY_P_192_Feb19_2016 };
}
}
}
| |
// Copyright 2016 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 Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks;
using Esri.ArcGISRuntime.Tasks.Geoprocessing;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Drawing;
using Windows.UI.Popups;
using Microsoft.UI.Xaml;
namespace ArcGISRuntime.WinUI.Samples.AnalyzeViewshed
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Analyze viewshed (geoprocessing)",
category: "Geoprocessing",
description: "Calculate a viewshed using a geoprocessing service, in this case showing what parts of a landscape are visible from points on mountainous terrain.",
instructions: "Click the map to see all areas visible from that point within a 15km radius. Clicking on an elevated area will highlight a larger part of the surrounding landscape. It may take a few seconds for the task to run and send back the results.",
tags: new[] { "geoprocessing", "heat map", "heatmap", "viewshed" })]
public partial class AnalyzeViewshed
{
// Url for the geoprocessing service
private const string _viewshedUrl =
"https://sampleserver6.arcgisonline.com/arcgis/rest/services/Elevation/ESRI_Elevation_World/GPServer/Viewshed";
// Used to store state of the geoprocessing task
private bool _isExecutingGeoprocessing;
// The graphics overlay to show where the user clicked in the map
private GraphicsOverlay _inputOverlay;
// The graphics overlay to display the result of the viewshed analysis
private GraphicsOverlay _resultOverlay;
public AnalyzeViewshed()
{
InitializeComponent();
// Create the UI, setup the control references and execute initialization
Initialize();
}
private void Initialize()
{
// Create a map with topographic basemap and an initial location
Map myMap = new Map(BasemapType.Topographic, 45.3790902612337, 6.84905317262762, 13);
// Hook into the tapped event
MyMapView.GeoViewTapped += OnMapViewTapped;
// Create empty overlays for the user clicked location and the results of the viewshed analysis
CreateOverlays();
// Assign the map to the MapView
MyMapView.Map = myMap;
}
private async void OnMapViewTapped(object sender, GeoViewInputEventArgs e)
{
// The geoprocessing task is still executing, don't do anything else (i.e. respond to
// more user taps) until the processing is complete.
if (_isExecutingGeoprocessing)
{
return;
}
// Indicate that the geoprocessing is running
SetBusy();
// Clear previous user click location and the viewshed geoprocessing task results
_inputOverlay.Graphics.Clear();
_resultOverlay.Graphics.Clear();
// Get the tapped point
MapPoint geometry = e.Location;
// Create a marker graphic where the user clicked on the map and add it to the existing graphics overlay
Graphic myInputGraphic = new Graphic(geometry);
_inputOverlay.Graphics.Add(myInputGraphic);
// Normalize the geometry if wrap-around is enabled
// This is necessary because of how wrapped-around map coordinates are handled by Runtime
// Without this step, the task may fail because wrapped-around coordinates are out of bounds.
if (MyMapView.IsWrapAroundEnabled) { geometry = (MapPoint)GeometryEngine.NormalizeCentralMeridian(geometry); }
try
{
// Execute the geoprocessing task using the user click location
await CalculateViewshed(geometry);
}
catch (Exception ex)
{
await new MessageDialog2(ex.ToString(), "Error").ShowAsync();
}
}
private async Task CalculateViewshed(MapPoint location)
{
// This function will define a new geoprocessing task that performs a custom viewshed analysis based upon a
// user click on the map and then display the results back as a polygon fill graphics overlay. If there
// is a problem with the execution of the geoprocessing task an error message will be displayed
// Create new geoprocessing task using the url defined in the member variables section
GeoprocessingTask myViewshedTask = await GeoprocessingTask.CreateAsync(new Uri(_viewshedUrl));
// Create a new feature collection table based upon point geometries using the current map view spatial reference
FeatureCollectionTable myInputFeatures = new FeatureCollectionTable(new List<Field>(), GeometryType.Point, MyMapView.SpatialReference);
// Create a new feature from the feature collection table. It will not have a coordinate location (x,y) yet
Feature myInputFeature = myInputFeatures.CreateFeature();
// Assign a physical location to the new point feature based upon where the user clicked in the map view
myInputFeature.Geometry = location;
// Add the new feature with (x,y) location to the feature collection table
await myInputFeatures.AddFeatureAsync(myInputFeature);
// Create the parameters that are passed to the used geoprocessing task
GeoprocessingParameters myViewshedParameters =
new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute)
{
// Request the output features to use the same SpatialReference as the map view
OutputSpatialReference = MyMapView.SpatialReference
};
// Add an input location to the geoprocessing parameters
myViewshedParameters.Inputs.Add("Input_Observation_Point", new GeoprocessingFeatures(myInputFeatures));
// Create the job that handles the communication between the application and the geoprocessing task
GeoprocessingJob myViewshedJob = myViewshedTask.CreateJob(myViewshedParameters);
try
{
// Execute analysis and wait for the results
GeoprocessingResult myAnalysisResult = await myViewshedJob.GetResultAsync();
// Get the results from the outputs
GeoprocessingFeatures myViewshedResultFeatures = (GeoprocessingFeatures)myAnalysisResult.Outputs["Viewshed_Result"];
// Add all the results as a graphics to the map
IFeatureSet myViewshedAreas = myViewshedResultFeatures.Features;
foreach (Feature myFeature in myViewshedAreas)
{
_resultOverlay.Graphics.Add(new Graphic(myFeature.Geometry));
}
}
catch (Exception ex)
{
// Display an error message if there is a problem
if (myViewshedJob.Status == JobStatus.Failed && myViewshedJob.Error != null)
{
var message = new MessageDialog2("Executing geoprocessing failed. " + myViewshedJob.Error.Message, "Geoprocessing error");
await message.ShowAsync();
}
else
{
var message = new MessageDialog2("An error occurred. " + ex, "Sample error");
await message.ShowAsync();
}
}
finally
{
// Indicate that the geoprocessing is not running
SetBusy(false);
}
}
private void CreateOverlays()
{
// This function will create the overlays that show the user clicked location and the results of the
// viewshed analysis. Note: the overlays will not be populated with any graphics at this point
// Create renderer for input graphic. Set the size and color properties for the simple renderer
SimpleRenderer myInputRenderer = new SimpleRenderer()
{
Symbol = new SimpleMarkerSymbol()
{
Size = 15,
Color = Color.Red
}
};
// Create overlay to where input graphic is shown
_inputOverlay = new GraphicsOverlay()
{
Renderer = myInputRenderer
};
// Create fill renderer for output of the viewshed analysis. Set the color property of the simple renderer
SimpleRenderer myResultRenderer = new SimpleRenderer()
{
Symbol = new SimpleFillSymbol()
{
Color = Color.FromArgb(100, 226, 119, 40)
}
};
// Create overlay to where viewshed analysis graphic is shown
_resultOverlay = new GraphicsOverlay()
{
Renderer = myResultRenderer
};
// Add the created overlays to the MapView
MyMapView.GraphicsOverlays.Add(_inputOverlay);
MyMapView.GraphicsOverlays.Add(_resultOverlay);
}
private void SetBusy(bool isBusy = true)
{
// This function toggles the visibility of the 'busyOverlay' Grid control defined in xaml,
// sets the 'progress' control feedback status and updates the _isExecutingGeoprocessing
// boolean to denote if the viewshed analysis is executing as a result of the user click
// on the map
if (isBusy)
{
// Change UI to indicate that the geoprocessing is running
_isExecutingGeoprocessing = true;
busyOverlay.Visibility = Visibility.Visible;
progress.IsIndeterminate = true;
}
else
{
// Change UI to indicate that the geoprocessing is not running
_isExecutingGeoprocessing = false;
busyOverlay.Visibility = Visibility.Collapsed;
progress.IsIndeterminate = false;
}
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Design;
using System.ComponentModel;
using SharpGL.SceneGraph.Core;
using System.Runtime.InteropServices;
namespace SharpGL.SceneGraph.Assets
{
/// <summary>
/// A Texture object is simply an array of bytes. It has OpenGL functions, but is
/// not limited to OpenGL, so DirectX or custom library functions could be later added.
/// </summary>
[Editor(typeof(NETDesignSurface.Editors.UITextureEditor), typeof(UITypeEditor))]
[TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
[Serializable()]
public class Texture : Asset, IBindable
{
public Texture()
{
}
/// <summary>
/// Bind to the specified OpenGL instance.
/// </summary>
/// <param name="gl">The OpenGL instance.</param>
public void Bind(OpenGL gl)
{
// Bind our texture object (make it the current texture).
gl.BindTexture(OpenGL.GL_TEXTURE_2D, TextureName);
}
/// <summary>
/// This function creates the underlying OpenGL object.
/// </summary>
/// <param name="gl"></param>
/// <returns></returns>
public virtual bool Create(OpenGL gl)
{
// If the texture currently exists in OpenGL, destroy it.
Destroy(gl);
// Generate and store a texture identifier.
gl.GenTextures(1, glTextureArray);
return true;
}
/// <summary>
/// This function creates the texture from an image file.
/// </summary>
/// <param name="gl">The OpenGL object.</param>
/// <param name="path">The path to the image file.</param>
/// <returns>True if the texture was successfully loaded.</returns>
public virtual bool Create(OpenGL gl, string path)
{
// Create the underlying OpenGL object.
Create(gl);
// Try and load the bitmap. Return false on failure.
Bitmap image = new Bitmap(path);
if (image == null)
return false;
// Get the maximum texture size supported by OpenGL.
int[] textureMaxSize = { 0 };
gl.GetInteger(OpenGL.GL_MAX_TEXTURE_SIZE, textureMaxSize);
// Find the target width and height sizes, which is just the highest
// posible power of two that'll fit into the image.
int targetWidth = textureMaxSize[0];
int targetHeight = textureMaxSize[0];
for (int size = 1; size <= textureMaxSize[0]; size *= 2)
{
if (image.Width < size)
{
targetWidth = size / 2;
break;
}
if (image.Width == size)
targetWidth = size;
}
for (int size = 1; size <= textureMaxSize[0]; size *= 2)
{
if (image.Height < size)
{
targetHeight = size / 2;
break;
}
if (image.Height == size)
targetHeight = size;
}
// If need to scale, do so now.
if(image.Width != targetWidth || image.Height != targetHeight)
{
// Resize the image.
Image newImage = image.GetThumbnailImage(targetWidth, targetHeight, null, IntPtr.Zero);
// Destory the old image, and reset.
image.Dispose();
image = (Bitmap)newImage;
}
// Lock the image bits (so that we can pass them to OGL).
BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// Set the width and height.
width = image.Width;
height = image.Height;
// Bind our texture object (make it the current texture).
gl.BindTexture(OpenGL.GL_TEXTURE_2D, TextureName);
// Set the image data.
gl.TexImage2D(OpenGL.GL_TEXTURE_2D, 0, (int)OpenGL.GL_RGBA,
width, height, 0, OpenGL.GL_BGRA, OpenGL.GL_UNSIGNED_BYTE,
bitmapData.Scan0);
// Unlock the image.
image.UnlockBits(bitmapData);
// Dispose of the image file.
image.Dispose();
// Set linear filtering mode.
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MIN_FILTER, OpenGL.GL_LINEAR);
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MAG_FILTER, OpenGL.GL_LINEAR);
// We're done!
return true;
}
/// <summary>
/// This function destroys the OpenGL object that is a representation of this texture.
/// </summary>
public virtual void Destroy(OpenGL gl)
{
// Only destroy if we have a valid id.
if(glTextureArray[0] != 0)
{
// Delete the texture object.
gl.DeleteTextures(1, glTextureArray);
glTextureArray[0] = 0;
// Destroy the pixel data.
pixelData = null;
// Reset width and height.
width = height = 0;
}
}
/// <summary>
/// This function (attempts) to make a bitmap from the raw data. The fact that
/// the byte array is a managed type makes it slightly more complicated.
/// </summary>
/// <returns>The texture object as a Bitmap.</returns>
public virtual Bitmap ToBitmap()
{
// Check for the trivial case.
if (pixelData == null)
return null;
// Pin the pixel data.
GCHandle handle = GCHandle.Alloc(pixelData, GCHandleType.Pinned);
// Create the bitmap.
Bitmap bitmap = new Bitmap(width, height, width * 4,
PixelFormat.Format32bppRgb, handle.AddrOfPinnedObject());
// Free the data.
handle.Free();
// Return the bitmap.
return bitmap;
}
/// <summary>
/// This is an array of bytes (r, g, b, a) that represent the pixels in this
/// texture object.
/// </summary>
private byte[] pixelData = null;
/// <summary>
/// The width of the texture image.
/// </summary>
private int width = 0;
/// <summary>
/// The height of the texture image.
/// </summary>
private int height = 0;
/// <summary>
/// This is for OpenGL textures, it is the unique ID for the OpenGL texture.
/// </summary>
private uint[] glTextureArray = new uint[1] { 0 };
/// <summary>
/// Gets the name of the texture.
/// </summary>
/// <value>
/// The name of the texture.
/// </value>
[Description("The internal texture code.."), Category("Texture")]
public uint TextureName
{
get { return glTextureArray[0]; }
}
}
}
| |
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// This class is defined only the editor does not natively support GVR, or if the current
/// VR player is the in-editor emulator.
#if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR
using UnityEngine;
/// Performs distortion correction on the rendered stereo screen. This script
/// and GvrPreRender work together to draw the whole screen in VR Mode.
/// There should be exactly one of each component in any GVR-enabled scene. It
/// is part of the _GvrCamera_ prefab, which is included in
/// _GvrMain_. The GvrViewer script will create one at runtime if the
/// scene doesn't already have it, so generally it is not necessary to manually
/// add it unless you wish to edit the Camera component that it controls.
///
/// In the Unity editor, this script also draws the analog of the UI layer on
/// the phone (alignment marker, settings gear, etc).
[RequireComponent(typeof(Camera))]
[AddComponentMenu("GoogleVR/GvrPostRender")]
public class GvrPostRender : MonoBehaviour {
// Convenient accessor to the camera component used through this script.
public Camera cam { get; private set; }
// Distortion mesh parameters.
// Size of one eye's distortion mesh grid. The whole mesh is two of these grids side by side.
private const int kMeshWidth = 40;
private const int kMeshHeight = 40;
// Whether to apply distortion in the grid coordinates or in the texture coordinates.
private const bool kDistortVertices = true;
private Mesh distortionMesh;
private Material meshMaterial;
// UI Layer parameters.
private Material uiMaterial;
private float centerWidthPx;
private float buttonWidthPx;
private float xScale;
private float yScale;
private Matrix4x4 xfm;
void Reset() {
#if UNITY_EDITOR
// Member variable 'cam' not always initialized when this method called in Editor.
// So, we'll just make a local of the same name.
var cam = GetComponent<Camera>();
#endif
cam.clearFlags = CameraClearFlags.Depth;
cam.backgroundColor = Color.magenta; // Should be noticeable if the clear flags change.
cam.orthographic = true;
cam.orthographicSize = 0.5f;
cam.cullingMask = 0;
cam.useOcclusionCulling = false;
cam.depth = 100;
}
void Awake() {
cam = GetComponent<Camera>();
Reset();
meshMaterial = new Material(Shader.Find("GoogleVR/UnlitTexture"));
uiMaterial = new Material(Shader.Find("GoogleVR/SolidColor"));
uiMaterial.color = new Color(0.8f, 0.8f, 0.8f);
if (!Application.isEditor) {
ComputeUIMatrix();
}
}
#if UNITY_EDITOR
private float aspectComparison;
void OnPreCull() {
// The Game window's aspect ratio may not match the fake device parameters.
float realAspect = (float)Screen.width / Screen.height;
float fakeAspect = GvrViewer.Instance.Profile.screen.width / GvrViewer.Instance.Profile.screen.height;
aspectComparison = fakeAspect / realAspect;
cam.orthographicSize = 0.5f * Mathf.Max(1, aspectComparison);
}
#endif
void OnRenderObject() {
if (Camera.current != cam)
return;
GvrViewer.Instance.UpdateState();
bool correctionEnabled = GvrViewer.Instance.DistortionCorrectionEnabled;
RenderTexture stereoScreen = GvrViewer.Instance.StereoScreen;
if (stereoScreen == null || !correctionEnabled) {
return;
}
if (distortionMesh == null || GvrViewer.Instance.ProfileChanged) {
RebuildDistortionMesh();
}
meshMaterial.mainTexture = stereoScreen;
meshMaterial.SetPass(0);
Graphics.DrawMeshNow(distortionMesh, transform.position, transform.rotation);
stereoScreen.DiscardContents();
if (!GvrViewer.Instance.NativeUILayerSupported) {
DrawUILayer();
}
}
private void RebuildDistortionMesh() {
distortionMesh = new Mesh();
Vector3[] vertices;
Vector2[] tex;
ComputeMeshPoints(kMeshWidth, kMeshHeight, kDistortVertices, out vertices, out tex);
int[] indices = ComputeMeshIndices(kMeshWidth, kMeshHeight, kDistortVertices);
Color[] colors = ComputeMeshColors(kMeshWidth, kMeshHeight, tex, indices, kDistortVertices);
distortionMesh.vertices = vertices;
distortionMesh.uv = tex;
distortionMesh.colors = colors;
distortionMesh.triangles = indices;
distortionMesh.Optimize();
distortionMesh.UploadMeshData(true);
}
private static void ComputeMeshPoints(int width, int height, bool distortVertices,
out Vector3[] vertices, out Vector2[] tex) {
float[] lensFrustum = new float[4];
float[] noLensFrustum = new float[4];
Rect viewport;
GvrProfile profile = GvrViewer.Instance.Profile;
profile.GetLeftEyeVisibleTanAngles(lensFrustum);
profile.GetLeftEyeNoLensTanAngles(noLensFrustum);
viewport = profile.GetLeftEyeVisibleScreenRect(noLensFrustum);
vertices = new Vector3[2 * width * height];
tex = new Vector2[2 * width * height];
for (int e = 0, vidx = 0; e < 2; e++) {
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++, vidx++) {
float u = (float)i / (width - 1);
float v = (float)j / (height - 1);
float s, t; // The texture coordinates in StereoScreen to read from.
if (distortVertices) {
// Grid points regularly spaced in StreoScreen, and barrel distorted in the mesh.
s = u;
t = v;
float x = Mathf.Lerp(lensFrustum[0], lensFrustum[2], u);
float y = Mathf.Lerp(lensFrustum[3], lensFrustum[1], v);
float d = Mathf.Sqrt(x * x + y * y);
float r = profile.viewer.distortion.distortInv(d);
float p = x * r / d;
float q = y * r / d;
u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
} else {
// Grid points regularly spaced in the mesh, and pincushion distorted in
// StereoScreen.
float p = Mathf.Lerp(noLensFrustum[0], noLensFrustum[2], u);
float q = Mathf.Lerp(noLensFrustum[3], noLensFrustum[1], v);
float r = Mathf.Sqrt(p * p + q * q);
float d = profile.viewer.distortion.distort(r);
float x = p * d / r;
float y = q * d / r;
s = Mathf.Clamp01((x - lensFrustum[0]) / (lensFrustum[2] - lensFrustum[0]));
t = Mathf.Clamp01((y - lensFrustum[3]) / (lensFrustum[1] - lensFrustum[3]));
}
// Convert u,v to mesh screen coordinates.
float aspect = profile.screen.width / profile.screen.height;
u = (viewport.x + u * viewport.width - 0.5f) * aspect;
v = viewport.y + v * viewport.height - 0.5f;
vertices[vidx] = new Vector3(u, v, 1);
// Adjust s to account for left/right split in StereoScreen.
s = (s + e) / 2;
tex[vidx] = new Vector2(s, t);
}
}
float w = lensFrustum[2] - lensFrustum[0];
lensFrustum[0] = -(w + lensFrustum[0]);
lensFrustum[2] = w - lensFrustum[2];
w = noLensFrustum[2] - noLensFrustum[0];
noLensFrustum[0] = -(w + noLensFrustum[0]);
noLensFrustum[2] = w - noLensFrustum[2];
viewport.x = 1 - (viewport.x + viewport.width);
}
}
private static Color[] ComputeMeshColors(int width, int height, Vector2[] tex, int[] indices,
bool distortVertices) {
Color[] colors = new Color[2 * width * height];
for (int e = 0, vidx = 0; e < 2; e++) {
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++, vidx++) {
colors[vidx] = Color.white;
if (distortVertices) {
if (i == 0 || j == 0 || i == (width - 1) || j == (height - 1)) {
colors[vidx] = Color.black;
}
} else {
Vector2 t = tex[vidx];
t.x = Mathf.Abs(t.x * 2 - 1);
if (t.x <= 0 || t.y <= 0 || t.x >= 1 || t.y >= 1) {
colors[vidx] = Color.black;
}
}
}
}
}
return colors;
}
private static int[] ComputeMeshIndices(int width, int height, bool distortVertices) {
int[] indices = new int[2 * (width - 1) * (height - 1) * 6];
int halfwidth = width / 2;
int halfheight = height / 2;
for (int e = 0, vidx = 0, iidx = 0; e < 2; e++) {
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++, vidx++) {
if (i == 0 || j == 0)
continue;
// Build a quad. Lower right and upper left quadrants have quads with the triangle
// diagonal flipped to get the vignette to interpolate correctly.
if ((i <= halfwidth) == (j <= halfheight)) {
// Quad diagonal lower left to upper right.
indices[iidx++] = vidx;
indices[iidx++] = vidx - width;
indices[iidx++] = vidx - width - 1;
indices[iidx++] = vidx - width - 1;
indices[iidx++] = vidx - 1;
indices[iidx++] = vidx;
} else {
// Quad diagonal upper left to lower right.
indices[iidx++] = vidx - 1;
indices[iidx++] = vidx;
indices[iidx++] = vidx - width;
indices[iidx++] = vidx - width;
indices[iidx++] = vidx - width - 1;
indices[iidx++] = vidx - 1;
}
}
}
}
return indices;
}
private void DrawUILayer() {
bool vrMode = GvrViewer.Instance.VRModeEnabled;
if (Application.isEditor) {
ComputeUIMatrix();
}
uiMaterial.SetPass(0);
DrawSettingsButton();
DrawAlignmentMarker();
if (vrMode) {
DrawVRBackButton();
}
}
// The gear has 6 identical sections, each spanning 60 degrees.
private const float kAnglePerGearSection = 60;
// Half-angle of the span of the outer rim.
private const float kOuterRimEndAngle = 12;
// Angle between the middle of the outer rim and the start of the inner rim.
private const float kInnerRimBeginAngle = 20;
// Distance from center to outer rim, normalized so that the entire model
// fits in a [-1, 1] x [-1, 1] square.
private const float kOuterRadius = 1;
// Distance from center to depressed rim, in model units.
private const float kMiddleRadius = 0.75f;
// Radius of the inner hollow circle, in model units.
private const float kInnerRadius = 0.3125f;
// Center line thickness in DP.
private const float kCenterLineThicknessDp = 4;
// Button width in DP.
private const int kButtonWidthDp = 28;
// Factor to scale the touch area that responds to the touch.
private const float kTouchSlopFactor = 1.5f;
private static readonly float[] Angles = {
0, kOuterRimEndAngle, kInnerRimBeginAngle,
kAnglePerGearSection - kInnerRimBeginAngle, kAnglePerGearSection - kOuterRimEndAngle
};
private void ComputeUIMatrix() {
centerWidthPx = kCenterLineThicknessDp / 160.0f * Screen.dpi / 2;
buttonWidthPx = kButtonWidthDp / 160.0f * Screen.dpi / 2;
xScale = buttonWidthPx / Screen.width;
yScale = buttonWidthPx / Screen.height;
xfm = Matrix4x4.TRS(new Vector3(0.5f, yScale, 0), Quaternion.identity,
new Vector3(xScale, yScale, 1));
}
private void DrawSettingsButton() {
GL.PushMatrix();
GL.LoadOrtho();
GL.MultMatrix(xfm);
GL.Begin(GL.TRIANGLE_STRIP);
for (int i = 0, n = Angles.Length * 6; i <= n; i++) {
float theta = (i / Angles.Length) * kAnglePerGearSection + Angles[i % Angles.Length];
float angle = (90 - theta) * Mathf.Deg2Rad;
float x = Mathf.Cos(angle);
float y = Mathf.Sin(angle);
float mod = Mathf.PingPong(theta, kAnglePerGearSection / 2);
float lerp = (mod - kOuterRimEndAngle) / (kInnerRimBeginAngle - kOuterRimEndAngle);
float r = Mathf.Lerp(kOuterRadius, kMiddleRadius, lerp);
GL.Vertex3(kInnerRadius * x, kInnerRadius * y, 0);
GL.Vertex3(r * x, r * y, 0);
}
GL.End();
GL.PopMatrix();
}
private void DrawAlignmentMarker() {
int x = Screen.width / 2;
int w = (int)centerWidthPx;
int h = (int)(2 * kTouchSlopFactor * buttonWidthPx);
GL.PushMatrix();
GL.LoadPixelMatrix(0, Screen.width, 0, Screen.height);
GL.Begin(GL.QUADS);
GL.Vertex3(x - w, h, 0);
GL.Vertex3(x - w, Screen.height - h, 0);
GL.Vertex3(x + w, Screen.height - h, 0);
GL.Vertex3(x + w, h, 0);
GL.End();
GL.PopMatrix();
}
private void DrawVRBackButton() {
}
}
#endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR
| |
/*
* 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 NAMESPACES
**********************************************************/
using System;
using QuantConnect.Orders;
using QuantConnect.Securities.Interfaces;
namespace QuantConnect.Securities
{
/********************************************************
* CLASS DEFINITIONS
*********************************************************/
/// <summary>
/// SecurityHolding is a base class for purchasing and holding a market item which manages the asset portfolio
/// </summary>
public class SecurityHolding
{
/********************************************************
* CLASS VARIABLES
*********************************************************/
//Working Variables
private decimal _averagePrice = 0;
private int _quantity = 0;
private decimal _price = 0;
private decimal _totalSaleVolume = 0;
private decimal _profit = 0;
private decimal _lastTradeProfit = 0;
private decimal _totalFees = 0;
private readonly Security _security;
protected readonly ISecurityMarginModel MarginModel;
protected readonly ISecurityTransactionModel TransactionModel;
/********************************************************
* CONSTRUCTOR DEFINITION
*********************************************************/
/// <summary>
/// Create a new holding class instance setting the initial properties to $0.
/// </summary>
/// <param name="security">The security being held</param>
/// <param name="transactionModel">The transaction model used for the security</param>
/// <param name="marginModel">The margin model used for the security</param>
public SecurityHolding(Security security, ISecurityTransactionModel transactionModel, ISecurityMarginModel marginModel)
{
_security = security;
TransactionModel = transactionModel;
MarginModel = marginModel;
//Total Sales Volume for the day
_totalSaleVolume = 0;
_lastTradeProfit = 0;
}
/********************************************************
* CLASS PROPERTIES
*********************************************************/
/// <summary>
/// Average price of the security holdings.
/// </summary>
public decimal AveragePrice
{
get
{
return _averagePrice;
}
}
/// <summary>
/// Quantity of the security held.
/// </summary>
/// <remarks>Positive indicates long holdings, negative quantity indicates a short holding</remarks>
/// <seealso cref="AbsoluteQuantity"/>
public int Quantity
{
get
{
return _quantity;
}
}
/// <summary>
/// Symbol identifier of the underlying security.
/// </summary>
public string Symbol
{
get
{
return _security.Symbol;
}
}
/// <summary>
/// The security type of the symbol
/// </summary>
public SecurityType Type
{
get
{
return _security.Type;
}
}
/// <summary>
/// Leverage of the underlying security.
/// </summary>
public virtual decimal Leverage
{
get
{
return MarginModel.GetLeverage(_security);
}
}
/// <summary>
/// Acquisition cost of the security total holdings.
/// </summary>
public virtual decimal HoldingsCost
{
get
{
return AveragePrice * Convert.ToDecimal(Quantity);
}
}
/// <summary>
/// Unlevered Acquisition cost of the security total holdings.
/// </summary>
public virtual decimal UnleveredHoldingsCost
{
get { return HoldingsCost/Leverage; }
}
/// <summary>
/// Current market price of the security.
/// </summary>
public virtual decimal Price
{
get
{
return _price;
}
}
/// <summary>
/// Absolute holdings cost for current holdings in units of the account's currency
/// </summary>
/// <seealso cref="HoldingsCost"/>
public virtual decimal AbsoluteHoldingsCost
{
get
{
return Math.Abs(HoldingsCost);
}
}
/// <summary>
/// Unlevered absolute acquisition cost of the security total holdings.
/// </summary>
public virtual decimal UnleveredAbsoluteHoldingsCost
{
get
{
return Math.Abs(UnleveredHoldingsCost);
}
}
/// <summary>
/// Market value of our holdings.
/// </summary>
public virtual decimal HoldingsValue
{
get
{
return _price * Convert.ToDecimal(Quantity);
}
}
/// <summary>
/// Absolute of the market value of our holdings.
/// </summary>
/// <seealso cref="HoldingsValue"/>
public virtual decimal AbsoluteHoldingsValue
{
get
{
return Math.Abs(HoldingsValue);
}
}
/// <summary>
/// Boolean flat indicating if we hold any of the security
/// </summary>
public virtual bool HoldStock
{
get
{
return (AbsoluteQuantity > 0);
}
}
/// <summary>
/// Boolean flat indicating if we hold any of the security
/// </summary>
/// <remarks>Alias of HoldStock</remarks>
/// <seealso cref="HoldStock"/>
public virtual bool Invested
{
get
{
return HoldStock;
}
}
/// <summary>
/// The total transaction volume for this security since the algorithm started.
/// </summary>
public virtual decimal TotalSaleVolume
{
get { return _totalSaleVolume; }
}
/// <summary>
/// Total fees for this company since the algorithm started.
/// </summary>
public virtual decimal TotalFees
{
get { return _totalFees; }
}
/// <summary>
/// Boolean flag indicating we have a net positive holding of the security.
/// </summary>
/// <seealso cref="IsShort"/>
public virtual bool IsLong
{
get
{
return Quantity > 0;
}
}
/// <summary>
/// BBoolean flag indicating we have a net negative holding of the security.
/// </summary>
/// <seealso cref="IsLong"/>
public virtual bool IsShort
{
get
{
return Quantity < 0;
}
}
/// <summary>
/// Absolute quantity of holdings of this security
/// </summary>
/// <seealso cref="Quantity"/>
public virtual decimal AbsoluteQuantity
{
get
{
return Math.Abs(Quantity);
}
}
/// <summary>
/// Record of the closing profit from the last trade conducted.
/// </summary>
public virtual decimal LastTradeProfit
{
get
{
return _lastTradeProfit;
}
}
/// <summary>
/// Calculate the total profit for this security.
/// </summary>
/// <seealso cref="NetProfit"/>
public virtual decimal Profit
{
get { return _profit; }
}
/// <summary>
/// Return the net for this company measured by the profit less fees.
/// </summary>
/// <seealso cref="Profit"/>
/// <seealso cref="TotalFees"/>
public virtual decimal NetProfit
{
get
{
return Profit - TotalFees;
}
}
/// <summary>
/// Unrealized profit of this security when absolute quantity held is more than zero.
/// </summary>
public virtual decimal UnrealizedProfit
{
get { return TotalCloseProfit(); }
}
/********************************************************
* CLASS METHODS
*********************************************************/
/// <summary>
/// Adds a fee to the running total of total fees.
/// </summary>
/// <param name="newFee"></param>
public void AddNewFee(decimal newFee)
{
_totalFees += newFee;
}
/// <summary>
/// Adds a profit record to the running total of profit.
/// </summary>
/// <param name="profitLoss">The cash change in portfolio from closing a position</param>
public void AddNewProfit(decimal profitLoss)
{
_profit += profitLoss;
}
/// <summary>
/// Adds a new sale value to the running total trading volume in terms of the account currency
/// </summary>
/// <param name="saleValue"></param>
public void AddNewSale(decimal saleValue)
{
_totalSaleVolume += saleValue;
}
/// <summary>
/// Set the last trade profit for this security from a Portfolio.ProcessFill call.
/// </summary>
/// <param name="lastTradeProfit">Value of the last trade profit</param>
public void SetLastTradeProfit(decimal lastTradeProfit)
{
_lastTradeProfit = lastTradeProfit;
}
/// <summary>
/// Set the quantity of holdings and their average price after processing a portfolio fill.
/// </summary>
public virtual void SetHoldings(decimal averagePrice, int quantity)
{
_averagePrice = averagePrice;
_quantity = quantity;
}
/// <summary>
/// Update local copy of closing price value.
/// </summary>
/// <param name="closingPrice">Price of the underlying asset to be used for calculating market price / portfolio value</param>
public virtual void UpdateMarketPrice(decimal closingPrice)
{
_price = closingPrice;
}
/// <summary>
/// Profit if we closed the holdings right now including the approximate fees.
/// </summary>
/// <remarks>Does not use the transaction model for market fills but should.</remarks>
public virtual decimal TotalCloseProfit()
{
if (AbsoluteQuantity == 0)
{
return 0;
}
// this is in the account currency
var marketOrder = new MarketOrder(_security.Symbol, -Quantity, _security.Time, type: _security.Type) {Price = Price};
var orderFee = TransactionModel.GetOrderFee(_security, marketOrder);
return (Price - AveragePrice) * Quantity - orderFee;
}
}
} //End Namespace
| |
using System;
using System.Collections.Generic;
using System.IO;
using Xunit;
namespace NDCRaw.Tests
{
public class NDCRawTests
{
const bool KEEP_TEST_RESULTS = false;
const bool SHOW_COMMAND_LINES = true;
List<string> _files = new List<string>();
public NDCRawTests()
{
_files.Add("DSC_0041.NEF");
_files.Add("DSC_3982.NEF");
_files.Add("DSC_9762.NEF");
_files.Add("space test.NEF");
}
[Fact]
public void NoCustomizationTest()
{
ExecuteTest(new DCRawOptions(), "noargs");
ExecuteTest(GetPreferredDefaultOptions(), "pref");
}
[Fact]
public void CurrentConversionTest()
{
var opts = GetPreferredDefaultOptions();
opts.AdjustBrightness = 1.5f;
opts.Write16Bits = true;
ExecuteTest(opts, "curr");
}
[Fact]
public void ColorspaceTests()
{
var opts = GetPreferredDefaultOptions();
opts.Colorspace = Colorspace.Adobe;
ExecuteTest(opts, "adobe");
opts.Colorspace = Colorspace.sRGB;
ExecuteTest(opts, "srgb");
}
[Fact]
public void UseIccProfileTest()
{
var opts = GetPreferredDefaultOptions();
// special key to use the embedded profile if exists
opts.CameraIccProfileFile = "embed";
ExecuteTest(opts, "icc");
}
[Fact]
public void QualityTests()
{
var opts = GetPreferredDefaultOptions();
opts.Quality = InterpolationQuality.Quality0;
ExecuteTest(opts, "q0");
opts.Quality = InterpolationQuality.Quality1;
ExecuteTest(opts, "q1");
opts.Quality = InterpolationQuality.Quality2;
ExecuteTest(opts, "q2");
opts.Quality = InterpolationQuality.Quality3;
ExecuteTest(opts, "q3");
}
[Fact]
public void Quality3CorrectionTests()
{
var opts = GetPreferredDefaultOptions();
opts.AppliedMedianFilterNumberPasses = 1;
ExecuteTest(opts, "q3c1");
opts.AppliedMedianFilterNumberPasses = 2;
ExecuteTest(opts, "q3c2");
}
[Fact]
public void BitTests()
{
var opts = GetPreferredDefaultOptions();
opts.Write16Bits = true;
ExecuteTest(opts, "bit16");
opts.Write16Bits = false;
ExecuteTest(opts, "bit8");
}
[Fact]
public void AverageWhiteBalanceTest()
{
var opts = GetPreferredDefaultOptions();
opts.UseCameraWhiteBalance = false;
opts.AverageWholeImageForWhiteBalance = true;
ExecuteTest(opts, "avgwb");
}
[Fact]
public void AutoBrightenTest()
{
var opts = new DCRawOptions();
opts.DontAutomaticallyBrighten = false;
ExecuteTest(opts, "brighten");
}
[Fact]
public void FormatTest()
{
var opts = new DCRawOptions();
opts.Format = Format.Tiff;
ExecuteTest(opts, "tiff");
}
[Fact]
public void HighlightTests()
{
var opts = new DCRawOptions();
opts.HighlightMode = HighlightMode.Blend;
ExecuteTest(opts, "hblend");
opts.HighlightMode = HighlightMode.Clip;
ExecuteTest(opts, "hclip");
opts.HighlightMode = HighlightMode.Unclip;
ExecuteTest(opts, "hunclip");
opts.HighlightMode = HighlightMode.Rebuild3;
ExecuteTest(opts, "h3");
opts.HighlightMode = HighlightMode.Rebuild5;
ExecuteTest(opts, "h5");
opts.HighlightMode = HighlightMode.Rebuild8;
ExecuteTest(opts, "h8");
opts.HighlightMode = HighlightMode.Rebuild9;
ExecuteTest(opts, "h9");
}
[Fact]
public void MyOptimalDaytimePhotoTest()
{
var opts = GetPreferredDefaultOptions();
opts.HighlightMode = HighlightMode.Blend;
opts.Colorspace = Colorspace.sRGB;
ExecuteTest(opts, "dayopt");
}
[Fact]
public void MyOptimalNighttimePhotoTest()
{
var opts = GetPreferredDefaultOptions();
opts.DontAutomaticallyBrighten = true;
opts.HighlightMode = HighlightMode.Blend;
opts.Colorspace = Colorspace.sRGB;
ExecuteTest(opts, "nightopt");
}
DCRawOptions GetPreferredDefaultOptions()
{
var opts = new DCRawOptions();
opts.UseCameraWhiteBalance = true;
opts.Quality = InterpolationQuality.Quality3;
return opts;
}
void ExecuteTest(DCRawOptions opts, string renameSuffix)
{
foreach(var sourceFile in _files)
{
var dcraw = new DCRaw(opts);
if(SHOW_COMMAND_LINES)
{
Console.WriteLine($"prefix: {renameSuffix} cmdline: {string.Join(" ", opts.GetArguments(sourceFile))}");
}
var result = dcraw.Convert(sourceFile);
Assert.True(File.Exists(result.OutputFilename));
if(!KEEP_TEST_RESULTS)
{
File.Delete(result.OutputFilename);
}
else
{
var dir = "test_output";
Directory.CreateDirectory(dir);
var newFile = Path.Combine(Path.GetDirectoryName(sourceFile), dir, $"{Path.GetFileNameWithoutExtension(result.OutputFilename)}_{renameSuffix}{Path.GetExtension(result.OutputFilename)}");
File.Move(result.OutputFilename, newFile);
}
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Data;
using Apache.NMS;
using Common.Logging;
using Spring.Messaging.Nms.Core;
using Spring.Objects.Factory;
using Spring.Transaction;
using Spring.Transaction.Support;
namespace Spring.Messaging.Nms.Connections
{
/// <summary>
/// A <see cref="AbstractPlatformTransactionManager"/> implementation
/// for a single NMS <code>ConnectionFactory</code>. Binds a
/// Connection/Session pair from the specified ConnecctionFactory to the thread,
/// potentially allowing for one thread-bound Session per ConnectionFactory.
/// </summary>
/// <remarks>
/// <para>
/// Application code is required to retrieve the transactional Session via
/// <see cref="ConnectionFactoryUtils.GetTransactionalSession"/>. Spring's
/// <see cref="NmsTemplate"/> will autodetect a thread-bound Session and
/// automatically participate in it.
/// </para>
/// <para>
/// The use of <see cref="CachingConnectionFactory"/>as a target for this
/// transaction manager is strongly recommended. CachingConnectionFactory
/// uses a single NMS Connection for all NMS access in order to avoid the overhead
/// of repeated Connection creation, as well as maintaining a cache of Sessions.
/// Each transaction will then share the same NMS Connection, while still using
/// its own individual NMS Session.
/// </para>
/// <para>The use of a <i>raw</i> target ConnectionFactory would not only be inefficient
/// because of the lack of resource reuse. It might also lead to strange effects
/// when your NMS provider doesn't accept <code>MessageProducer.close()</code> calls
/// and/or <code>MessageConsumer.close()</code> calls before <code>Session.commit()</code>,
/// with the latter supposed to commit all the messages that have been sent through the
/// producer handle and received through the consumer handle. As a safe general solution,
/// always pass in a <see cref="CachingConnectionFactory"/> into this transaction manager's
/// ConnectionFactory property.
/// </para>
/// <para>
/// Transaction synchronization is turned off by default, as this manager might be used
/// alongside an IDbProvider based Spring transaction manager such as the
/// AdoPlatformTransactionManager, which has stronger needs for synchronization.
/// </para>
/// </remarks>
/// <author>Juergen Hoeller</author>
/// <author>Mark Pollack (.NET)</author>
public class NmsTransactionManager : AbstractPlatformTransactionManager,
IResourceTransactionManager, IInitializingObject
{
#region Logging Definition
private static readonly ILog LOG = LogManager.GetLogger(typeof(NmsTransactionManager));
#endregion
private IConnectionFactory connectionFactory;
/// <summary>
/// Initializes a new instance of the <see cref="NmsTransactionManager"/> class.
/// </summary>
/// <remarks>
/// The ConnectionFactory has to be set before using the instance.
/// This constructor can be used to prepare a NmsTemplate via a ApplicationContext,
/// typically setting the ConnectionFactory via ConnectionFactory property.
/// <para>
/// Turns off transaction synchronization by default, as this manager might
/// be used alongside a dbprovider-based Spring transaction manager like
/// AdoPlatformTransactionManager, which has stronger needs for synchronization.
/// Only one manager is allowed to drive synchronization at any point of time.
/// </para>
/// </remarks>
public NmsTransactionManager()
{
TransactionSynchronization = TransactionSynchronizationState.Never;
}
/// <summary>
/// Initializes a new instance of the <see cref="NmsTransactionManager"/> class
/// given a ConnectionFactory.
/// </summary>
/// <param name="connectionFactory">The connection factory to obtain connections from.</param>
public NmsTransactionManager(IConnectionFactory connectionFactory) : this()
{
ConnectionFactory = connectionFactory;
AfterPropertiesSet();
}
/// <summary>
/// Gets or sets the connection factory that this instance should manage transaction.
/// for.
/// </summary>
/// <value>The connection factory.</value>
public IConnectionFactory ConnectionFactory
{
get { return connectionFactory; }
set
{
connectionFactory = value;
}
}
#region IInitializingObject Members
/// <summary>
/// Make sure the ConnectionFactory has been set.
/// </summary>
public void AfterPropertiesSet()
{
if (ConnectionFactory == null)
{
throw new ArgumentException("Property 'ConnectionFactory' is required.");
}
}
#endregion
#region IResourceTransactionManager Members
/// <summary>
/// Gets the resource factory that this transaction manager operates on,
/// In tihs case the ConnectionFactory
/// </summary>
/// <value>The ConnectionFactory.</value>
public object ResourceFactory
{
get { return ConnectionFactory; }
}
#endregion
/// <summary>
/// Get the MessageTransactionObject.
/// </summary>
/// <returns>he MessageTransactionObject.</returns>
protected override object DoGetTransaction()
{
MessageTransactionObject txObject = new MessageTransactionObject();
txObject.ResourceHolder =
(NmsResourceHolder) TransactionSynchronizationManager.GetResource(ConnectionFactory);
return txObject;
}
/// <summary>
/// Begin a new transaction with the given transaction definition.
/// </summary>
/// <param name="transaction">Transaction object returned by
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
/// <param name="definition"><see cref="Spring.Transaction.ITransactionDefinition"/> instance, describing
/// propagation behavior, isolation level, timeout etc.</param>
/// <remarks>
/// Does not have to care about applying the propagation behavior,
/// as this has already been handled by this abstract manager.
/// </remarks>
/// <exception cref="Spring.Transaction.TransactionException">
/// In the case of creation or system errors.
/// </exception>
protected override void DoBegin(object transaction, ITransactionDefinition definition)
{
//This is the default value defined in DefaultTransactionDefinition
if (definition.TransactionIsolationLevel != IsolationLevel.ReadCommitted)
{
throw new InvalidIsolationLevelException("NMS does not support an isoliation level concept");
}
MessageTransactionObject txObject = (MessageTransactionObject) transaction;
IConnection con = null;
ISession session = null;
try
{
con = CreateConnection();
session = CreateSession(con);
if (LOG.IsDebugEnabled)
{
log.Debug("Created NMS transaction on Session [" + session + "] from Connection [" + con + "]");
}
txObject.ResourceHolder = new NmsResourceHolder(ConnectionFactory, con, session);
txObject.ResourceHolder.SynchronizedWithTransaction = true;
int timeout = DetermineTimeout(definition);
if (timeout != DefaultTransactionDefinition.TIMEOUT_DEFAULT)
{
txObject.ResourceHolder.TimeoutInSeconds = timeout;
}
TransactionSynchronizationManager.BindResource(ConnectionFactory, txObject.ResourceHolder);
} catch (NMSException ex)
{
if (session != null)
{
try
{
session.Close();
} catch (Exception)
{}
}
if (con != null)
{
try
{
con.Close();
} catch (Exception){}
}
throw new CannotCreateTransactionException("Could not create NMS Transaction", ex);
}
}
/// <summary>
/// Suspend the resources of the current transaction.
/// </summary>
/// <param name="transaction">Transaction object returned by
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
/// <returns>
/// An object that holds suspended resources (will be kept unexamined for passing it into
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoResume"/>.)
/// </returns>
/// <remarks>
/// Transaction synchronization will already have been suspended.
/// </remarks>
/// <exception cref="Spring.Transaction.TransactionException">
/// in case of system errors.
/// </exception>
protected override object DoSuspend(object transaction)
{
MessageTransactionObject txObject = (MessageTransactionObject) transaction;
txObject.ResourceHolder = null;
return TransactionSynchronizationManager.UnbindResource(ConnectionFactory);
}
/// <summary>
/// Resume the resources of the current transaction.
/// </summary>
/// <param name="transaction">Transaction object returned by
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
/// <param name="suspendedResources">The object that holds suspended resources as returned by
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoSuspend"/>.</param>
/// <remarks>Transaction synchronization will be resumed afterwards.
/// </remarks>
/// <exception cref="Spring.Transaction.TransactionException">
/// In the case of system errors.
/// </exception>
protected override void DoResume(object transaction, object suspendedResources)
{
NmsResourceHolder conHolder = (NmsResourceHolder) suspendedResources;
TransactionSynchronizationManager.BindResource(ConnectionFactory, conHolder);
}
/// <summary>
/// Perform an actual commit on the given transaction.
/// </summary>
/// <param name="status">The status representation of the transaction.</param>
/// <exception cref="Spring.Transaction.TransactionException">
/// In the case of system errors.
/// </exception>
protected override void DoCommit(DefaultTransactionStatus status)
{
MessageTransactionObject txObject = (MessageTransactionObject)status.Transaction;
ISession session = txObject.ResourceHolder.GetSession();
try
{
if (status.Debug)
{
LOG.Debug("Committing NMS transaction on Session [" + session + "]");
}
session.Commit();
//Note that NMS does not have, TransactionRolledBackException
//See https://issues.apache.org/activemq/browse/AMQNET-93
}
catch (NMSException ex)
{
throw new TransactionSystemException("Could not commit NMS transaction.", ex);
}
}
/// <summary>
/// Perform an actual rollback on the given transaction.
/// </summary>
/// <param name="status">The status representation of the transaction.</param>
/// <exception cref="Spring.Transaction.TransactionException">
/// In the case of system errors.
/// </exception>
protected override void DoRollback(DefaultTransactionStatus status)
{
MessageTransactionObject txObject = (MessageTransactionObject)status.Transaction;
ISession session = txObject.ResourceHolder.GetSession();
try
{
if (status.Debug)
{
LOG.Debug("Rolling back NMS transaction on Session [" + session + "]");
}
session.Rollback();
}
catch (NMSException ex)
{
throw new TransactionSystemException("Could not roll back NMS transaction.", ex);
}
}
/// <summary>
/// Set the given transaction rollback-only. Only called on rollback
/// if the current transaction takes part in an existing one.
/// </summary>
/// <param name="status">The status representation of the transaction.</param>
/// <exception cref="Spring.Transaction.TransactionException">
/// In the case of system errors.
/// </exception>
protected override void DoSetRollbackOnly(DefaultTransactionStatus status)
{
MessageTransactionObject txObject = (MessageTransactionObject)status.Transaction;
txObject.ResourceHolder.RollbackOnly = true;
}
/// <summary>
/// Cleanup resources after transaction completion.
/// </summary>
/// <param name="transaction">Transaction object returned by
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
/// <remarks>
/// <para>
/// Called after <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoCommit"/>
/// and
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoRollback"/>
/// execution on any outcome.
/// </para>
/// </remarks>
protected override void DoCleanupAfterCompletion(object transaction)
{
MessageTransactionObject txObject = (MessageTransactionObject)transaction;
TransactionSynchronizationManager.UnbindResource(ConnectionFactory);
txObject.ResourceHolder.CloseAll();
txObject.ResourceHolder.Clear();
}
/// <summary>
/// Check if the given transaction object indicates an existing transaction
/// (that is, a transaction which has already started).
/// </summary>
/// <param name="transaction">Transaction object returned by
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
/// <returns>
/// True if there is an existing transaction.
/// </returns>
/// <exception cref="Spring.Transaction.TransactionException">
/// In the case of system errors.
/// </exception>
protected override bool IsExistingTransaction(object transaction)
{
MessageTransactionObject txObject = transaction as MessageTransactionObject;
if (txObject != null)
{
return txObject.ResourceHolder != null;
}
return false;
}
/// <summary>
/// Creates the connection via thie manager's ConnectionFactory.
/// </summary>
/// <returns>The new Connection</returns>
/// <exception cref="NMSException">If thrown by underlying messaging APIs</exception>
protected virtual IConnection CreateConnection()
{
return ConnectionFactory.CreateConnection();
}
/// <summary>
/// Creates the session for the given Connection
/// </summary>
/// <param name="connection">The connection to create a Session for.</param>
/// <returns>the new Session</returns>
/// <exception cref="NMSException">If thrown by underlying messaging APIs</exception>
protected virtual ISession CreateSession(IConnection connection)
{
return connection.CreateSession(AcknowledgementMode.Transactional);
}
/// <summary>
/// NMS Transaction object, representing a MessageResourceHolder.
/// Used as transaction object by MessageTransactionManager
/// </summary>
internal class MessageTransactionObject : ISmartTransactionObject
{
private NmsResourceHolder resourceHolder;
public NmsResourceHolder ResourceHolder
{
get { return resourceHolder; }
set { resourceHolder = value; }
}
#region ISmartTransactionObject Members
public bool RollbackOnly
{
get { return resourceHolder.RollbackOnly; }
}
#endregion
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;
using Google.GData.Blogger;
using Google.GData.YouTube;
using X.Google.Caching;
namespace X.Google
{
[Serializable]
public class Repository
{
public string Name { get; set; }
public Cache Cache { get; private set; }
public bool RetrieveAllPost { get; set; }
public virtual GoogleAccount GoogleAccount { get; set; }
public Repository()
{
Cache = new FakeCache();
RetrieveAllPost = false;
Name = "unknown";
}
public Repository(Cache cache)
: this()
{
Cache = cache;
}
protected virtual string CreateCacheKey(string key)
{
return String.Format("x_google_repository_{0}_{1}", Name, key);
}
#region IGoogleRepository
public virtual IEnumerable<Album> Albums
{
get
{
var cacheKey = CreateCacheKey("albums");
var albums = (IEnumerable<Album>)Cache[cacheKey];
if (albums == null)
{
albums = GetAlbums();
Cache.Insert(cacheKey, albums);
}
return albums;
}
}
public virtual IEnumerable<Video> FavoriteVideos
{
get
{
var cacheKey = CreateCacheKey("favorite_videos");
var favoriteVideos = (IEnumerable<Video>)Cache[cacheKey];
if (favoriteVideos == null)
{
favoriteVideos = GetFavoriteVideos();
Cache.Insert(cacheKey, favoriteVideos);
}
return favoriteVideos;
}
}
public virtual IEnumerable<Video> Videos
{
get
{
var cacheKey = CreateCacheKey("videos");
var videos = (IEnumerable<Video>)Cache[cacheKey];
if (videos == null)
{
videos = GetVideos();
Cache.Insert(cacheKey, videos);
}
return videos;
}
}
public virtual IEnumerable<Publication> Publications
{
get
{
var cacheKey = CreateCacheKey("publication");
var publications = (IEnumerable<Publication>)Cache[cacheKey];
if (publications == null)
{
publications = GetPublications();
Cache.Insert(cacheKey, publications);
}
return publications;
}
}
public virtual Album GetAlbum(string albumId)
{
Album album;
//if (Albums != null && Albums.Count() != 0)
//{
// album = Albums.FirstOrDefault(x => x.Id == albumId);
//}
//else
//{
var key = CreateCacheKey(albumId);
album = Cache[key] as Album;
if (album == null)
{
var url = String.Format( "https://picasaweb.google.com/data/feed/base/user/{0}/albumid/{1}?alt=rss&kind=photo",
GoogleAccount.PicasaUserName, albumId);
try
{
var xmlDocument = LoadXmlDocument(url);
var rss = X.Web.RSS.RssDocument.Load(xmlDocument.InnerXml);
var title = rss.Channel.Title;
var description = rss.Channel.Description;
var coverPhoto = new Photo
{
Url = rss.Channel.Image.Url.UrlString,
AlbumId = albumId,
PreviewUrl = rss.Channel.Image.Url.UrlString,
};
album = new Album(this)
{
UserName = GoogleAccount.PicasaUserName,
UserId = GoogleAccount.PicasaUserName,
Id = albumId,
Title = title,
CoverPhoto = coverPhoto,
Description = description
};
Cache[key] = album;
}
catch { }
}
//}
return album;
}
private static XmlDocument LoadXmlDocument(string url)
{
var request = WebRequest.Create(url);
Stream stream = null;
try
{
var response = request.GetResponse();
stream = response.GetResponseStream();
}
catch { }
if (stream != null)
{
var streamReader = new StreamReader(stream);
var xml = streamReader.ReadToEnd();
streamReader.Close();
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
return xmlDocument;
}
return null;
}
public virtual Publication GetPublication(string publicationId)
{
return Publications.FirstOrDefault(x => x.Id == publicationId);
}
public virtual Video GetVideo(string id)
{
var allVideos = new List<Video>();
allVideos.AddRange(Videos);
allVideos.AddRange(FavoriteVideos);
return allVideos.FirstOrDefault(x => x.Id == id);
}
public virtual IEnumerable<Photo> GetAlbumPhotos(string albumId)
{
var cacheKey = CreateCacheKey(String.Format("photos_of_album_{0}", albumId));
var photos = (IEnumerable<Photo>)Cache[cacheKey];
if (photos == null)
{
var photoXmlDescriptionUrl = String.Format("http://picasaweb.google.com/data/feed/base/user/{0}/albumid/{1}", GoogleAccount.PicasaUserName, albumId);
var xmlDocument = LoadXmlDocument(photoXmlDescriptionUrl);
photos = Factory.LoadPhotoListFromAlbumXml(xmlDocument, albumId, GoogleAccount.PicasaUserName);
Cache.Insert(cacheKey, photos);
}
return photos;
}
#endregion
#region internal logic
private IEnumerable<Publication> GetPublications()
{
var url = String.Format("http://www.blogger.com/feeds/{0}/posts/default ", GoogleAccount.BlogId);
var publications = LoadPublications(url, RetrieveAllPost);
return publications;
}
private IEnumerable<Video> GetVideos()
{
var url = String.Format("http://gdata.youtube.com/feeds/api/users/{0}/uploads", GoogleAccount.YouTubeUserName);
var videos = LoadVideos(url);
return videos;
}
private IEnumerable<Video> GetFavoriteVideos()
{
var url = String.Format("http://gdata.youtube.com/feeds/api/users/{0}/favorites", GoogleAccount.YouTubeUserName);
var favoritesVideos = LoadVideos(url);
return favoritesVideos;
}
private IEnumerable<Album> GetAlbums()
{
var url = "http://picasaweb.google.com/data/feed/api/user/" + GoogleAccount.PicasaUserName;
var albums = LoadAlbums(url, this);
return albums;
}
#endregion
public virtual Publication GetSinglePublication(string id)
{
try
{
var query = new BloggerQuery(String.Format("http://www.blogger.com/feeds/{0}/posts/default/{1} ", GoogleAccount.BlogId, id));
var bloggerService = new BloggerService(Factory.GoogleApplicationName);
var feed = bloggerService.Query(query);
var postEntry = (BloggerEntry)feed.Entries.FirstOrDefault();
return Factory.CreateBlog(postEntry);
}
catch
{
return null;
}
}
private static IEnumerable<Album> LoadAlbums(string url, Repository googleRepository)
{
XmlDocument xmlDocument = LoadXmlDocument(url);
if (xmlDocument == null)
{
return null;
}
var nodes = (from n in xmlDocument.ChildNodes[1].ChildNodes.Cast<XmlNode>()
where n.Name == "entry"
select n).ToList();
var albums = new List<Album>();
foreach (var node in nodes)
{
var mediaNode = (from n in node.ChildNodes.Cast<XmlNode>()
where n.Name == "media:group"
select n).SingleOrDefault();
var description = "";
try
{
description = (from n in mediaNode.ChildNodes.Cast<XmlNode>()
where n.Name == "media:description"
select n).SingleOrDefault().InnerText;
}
catch { }
var thumbnailNode = (from n in mediaNode.ChildNodes.Cast<XmlNode>()
where n.Name == "media:thumbnail"
select n).SingleOrDefault();
var title = (from n in node.ChildNodes.Cast<XmlNode>()
where n.Name == "title"
select n.InnerText).SingleOrDefault();
var albumId = (from n in node.ChildNodes.Cast<XmlNode>()
where n.Name == "id"
select n.InnerText).SingleOrDefault().ToLower();
var index = albumId.IndexOf("albumid/");
albumId = albumId.Remove(0, index + 8);
var coverUrl = (from a in thumbnailNode.Attributes.Cast<XmlAttribute>()
where a.Name == "url"
select a.Value).SingleOrDefault();
var coverPhoto = new Photo
{
Url = coverUrl,
AlbumId = albumId,
PreviewUrl = coverUrl,
};
var album = new Album(googleRepository)
{
UserName = googleRepository.GoogleAccount.PicasaUserName,
UserId = googleRepository.GoogleAccount.PicasaUserName,
Id = albumId,
Title = title,
CoverPhoto = coverPhoto,
Description = description
};
albums.Add(album);
}
return albums;
}
private static IEnumerable<Video> LoadVideos(string url)
{
var youTubeService = new YouTubeService(Factory.GoogleApplicationName);
var query = new YouTubeQuery(url);
var feed = youTubeService.Query(query);
var videos = new List<Video>();
foreach (YouTubeEntry entry in feed.Entries)
{
var video = Factory.CreateVideo(entry);
videos.Add(video);
}
return videos;
}
private static IEnumerable<Publication> LoadPublications(string url, bool retrieveAllPost)
{
url = url.Trim();
var publications = new List<Publication>();
var bloggerService = new BloggerService(Factory.GoogleApplicationName);
var query = new BloggerQuery(url);
try
{
var feed = bloggerService.Query(query);
if (retrieveAllPost && feed.TotalResults > feed.Entries.Count)
{
query.NumberToRetrieve = feed.TotalResults;
feed = bloggerService.Query(query);
}
foreach (BloggerEntry entry in feed.Entries)
{
var blog = Factory.CreateBlog(entry);
publications.Add(blog);
}
return publications;
}
catch
{
return new List<Publication>();
}
}
public virtual bool Available
{
get { return true; }
}
public int SaveChanges()
{
throw new NotSupportedException();
}
public void Dispose()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace OpenQA.Selenium
{
[TestFixture]
public class FormHandlingTests : DriverTestFixture
{
[Test]
public void ShouldClickOnSubmitInputElements()
{
driver.Url = formsPage;
driver.FindElement(By.Id("submitButton")).Click();
WaitFor(TitleToBe("We Arrive Here"));
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ClickingOnUnclickableElementsDoesNothing()
{
driver.Url = formsPage;
driver.FindElement(By.XPath("//body")).Click();
}
[Test]
public void ShouldBeAbleToClickImageButtons()
{
driver.Url = formsPage;
driver.FindElement(By.Id("imageButton")).Click();
WaitFor(TitleToBe("We Arrive Here"));
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldBeAbleToSubmitForms()
{
driver.Url = formsPage;
driver.FindElement(By.Name("login")).Submit();
WaitFor(TitleToBe("We Arrive Here"));
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldSubmitAFormWhenAnyInputElementWithinThatFormIsSubmitted()
{
driver.Url = formsPage;
driver.FindElement(By.Id("checky")).Submit();
WaitFor(TitleToBe("We Arrive Here"));
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldSubmitAFormWhenAnyElementWithinThatFormIsSubmitted()
{
driver.Url = formsPage;
driver.FindElement(By.XPath("//form/p")).Submit();
WaitFor(TitleToBe("We Arrive Here"));
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToSubmitAFormThatDoesNotExist()
{
driver.Url = formsPage;
driver.FindElement(By.Name("there is no spoon")).Submit();
}
[Test]
public void ShouldBeAbleToEnterTextIntoATextAreaBySettingItsValue()
{
driver.Url = javascriptPage;
IWebElement textarea = driver.FindElement(By.Id("keyUpArea"));
String cheesey = "Brie and cheddar";
textarea.SendKeys(cheesey);
Assert.AreEqual(textarea.GetAttribute("value"), cheesey);
}
[Test]
public void ShouldSubmitAFormUsingTheNewlineLiteral()
{
driver.Url = formsPage;
IWebElement nestedForm = driver.FindElement(By.Id("nested_form"));
IWebElement input = nestedForm.FindElement(By.Name("x"));
input.SendKeys("\n");
WaitFor(TitleToBe("We Arrive Here"));
Assert.AreEqual("We Arrive Here", driver.Title);
Assert.IsTrue(driver.Url.EndsWith("?x=name"));
}
[Test]
public void ShouldSubmitAFormUsingTheEnterKey()
{
driver.Url = formsPage;
IWebElement nestedForm = driver.FindElement(By.Id("nested_form"));
IWebElement input = nestedForm.FindElement(By.Name("x"));
input.SendKeys(Keys.Enter);
WaitFor(TitleToBe("We Arrive Here"));
Assert.AreEqual("We Arrive Here", driver.Title);
Assert.IsTrue(driver.Url.EndsWith("?x=name"));
}
[Test]
public void ShouldEnterDataIntoFormFields()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']"));
String originalValue = element.GetAttribute("value");
Assert.AreEqual(originalValue, "change");
element.Clear();
element.SendKeys("some text");
element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']"));
String newFormValue = element.GetAttribute("value");
Assert.AreEqual(newFormValue, "some text");
}
[Test]
public void ShouldBeAbleToAlterTheContentsOfAFileUploadInputElement()
{
driver.Url = formsPage;
IWebElement uploadElement = driver.FindElement(By.Id("upload"));
Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value")));
System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt");
System.IO.StreamWriter inputFileWriter = inputFile.CreateText();
inputFileWriter.WriteLine("Hello world");
inputFileWriter.Close();
uploadElement.SendKeys(inputFile.FullName);
System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value"));
Assert.AreEqual(inputFile.Name, outputFile.Name);
inputFile.Delete();
}
[Test]
public void ShouldBeAbleToUploadTheSameFileTwice()
{
System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt");
System.IO.StreamWriter inputFileWriter = inputFile.CreateText();
inputFileWriter.WriteLine("Hello world");
inputFileWriter.Close();
driver.Url = formsPage;
IWebElement uploadElement = driver.FindElement(By.Id("upload"));
Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value")));
uploadElement.SendKeys(inputFile.FullName);
uploadElement.Submit();
driver.Url = formsPage;
uploadElement = driver.FindElement(By.Id("upload"));
Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value")));
uploadElement.SendKeys(inputFile.FullName);
uploadElement.Submit();
// If we get this far, then we're all good.
}
[Test]
public void SendingKeyboardEventsShouldAppendTextInInputs()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("working"));
element.SendKeys("Some");
String value = element.GetAttribute("value");
Assert.AreEqual(value, "Some");
element.SendKeys(" text");
value = element.GetAttribute("value");
Assert.AreEqual(value, "Some text");
}
[Test]
public void SendingKeyboardEventsShouldAppendTextInInputsWithExistingValue()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("inputWithText"));
element.SendKeys(". Some text");
string value = element.GetAttribute("value");
Assert.AreEqual("Example text. Some text", value);
}
[Test]
[IgnoreBrowser(Browser.HtmlUnit, "Not implemented going to the end of the line first")]
public void SendingKeyboardEventsShouldAppendTextInTextAreas()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("withText"));
element.SendKeys(". Some text");
String value = element.GetAttribute("value");
Assert.AreEqual(value, "Example text. Some text");
}
[Test]
public void ShouldBeAbleToClearTextFromInputElements()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("working"));
element.SendKeys("Some text");
String value = element.GetAttribute("value");
Assert.IsTrue(value.Length > 0);
element.Clear();
value = element.GetAttribute("value");
Assert.AreEqual(value.Length, 0);
}
[Test]
public void EmptyTextBoxesShouldReturnAnEmptyStringNotNull()
{
driver.Url = formsPage;
IWebElement emptyTextBox = driver.FindElement(By.Id("working"));
Assert.AreEqual(emptyTextBox.GetAttribute("value"), "");
IWebElement emptyTextArea = driver.FindElement(By.Id("emptyTextArea"));
Assert.AreEqual(emptyTextBox.GetAttribute("value"), "");
}
[Test]
public void ShouldBeAbleToClearTextFromTextAreas()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("withText"));
element.SendKeys("Some text");
String value = element.GetAttribute("value");
Assert.IsTrue(value.Length > 0);
element.Clear();
value = element.GetAttribute("value");
Assert.AreEqual(value.Length, 0);
}
private Func<bool> TitleToBe(string desiredTitle)
{
return () =>
{
return driver.Title == desiredTitle;
};
}
}
}
| |
// 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.
//
// Adapted from
//
// Dhrystone: a synthetic systems programming benchmark
// Reinhold P. Weicker
// Communications of the ACM, Volume 27 Issue 10, Oct 1984, Pages 1013-1030
using Microsoft.Xunit.Performance;
using System;
using System.Runtime.CompilerServices;
using Xunit;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
public static class NDhrystone
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 7000000;
#endif
static T[][] AllocArray<T>(int n1, int n2) {
T[][] a = new T[n1][];
for (int i = 0; i < n1; ++i) {
a[i] = new T[n2];
}
return a;
}
enum Enumeration
{
Ident1 = 1, Ident2, Ident3, Ident4, Ident5
}
sealed class Record
{
public Record PtrComp;
public Enumeration Discr;
public Enumeration EnumComp;
public int IntComp;
public char[] StringComp;
}
static int s_intGlob;
static bool s_boolGlob;
static char s_char1Glob;
static char s_char2Glob;
static int[] m_array1Glob = new int[51];
static int[][] m_array2Glob;
static Record m_ptrGlb = new Record();
static Record m_ptrGlbNext = new Record();
static char[] m_string1Loc;
static char[] m_string2Loc;
static void Proc0() {
int intLoc1;
int intLoc2;
int intLoc3 = 0;
Enumeration enumLoc;
int i; /* modification */
m_ptrGlb.PtrComp = m_ptrGlbNext;
m_ptrGlb.Discr = Enumeration.Ident1;
m_ptrGlb.EnumComp = Enumeration.Ident3;
m_ptrGlb.IntComp = 40;
m_ptrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING".ToCharArray();
m_string1Loc = "DHRYSTONE PROGRAM, 1'ST STRING".ToCharArray();
m_array2Glob[8][7] = 10; /* Was missing in published program */
for (i = 0; i < Iterations; ++i) {
Proc5();
Proc4();
intLoc1 = 2;
intLoc2 = 3;
m_string2Loc = "DHRYSTONE PROGRAM, 2'ND STRING".ToCharArray();
enumLoc = Enumeration.Ident2;
s_boolGlob = !Func2(m_string1Loc, m_string2Loc);
while (intLoc1 < intLoc2) {
intLoc3 = 5 * intLoc1 - intLoc2;
Proc7(intLoc1, intLoc2, ref intLoc3);
++intLoc1;
}
Proc8(m_array1Glob, m_array2Glob, intLoc1, intLoc3);
Proc1(ref m_ptrGlb);
for (char charIndex = 'A'; charIndex <= s_char2Glob; ++charIndex) {
if (enumLoc == Func1(charIndex, 'C')) {
Proc6(Enumeration.Ident1, ref enumLoc);
}
}
intLoc3 = intLoc2 * intLoc1;
intLoc2 = intLoc3 / intLoc1;
intLoc2 = 7 * (intLoc3 - intLoc2) - intLoc1;
Proc2(ref intLoc1);
}
}
static void Proc1(ref Record ptrParIn) {
ptrParIn.PtrComp = m_ptrGlb;
ptrParIn.IntComp = 5;
ptrParIn.PtrComp.IntComp = ptrParIn.IntComp;
ptrParIn.PtrComp.PtrComp = ptrParIn.PtrComp;
Proc3(ref ptrParIn.PtrComp.PtrComp);
if (ptrParIn.PtrComp.Discr == Enumeration.Ident1) {
ptrParIn.PtrComp.IntComp = 6;
Proc6(ptrParIn.EnumComp, ref ptrParIn.PtrComp.EnumComp);
ptrParIn.PtrComp.PtrComp = m_ptrGlb.PtrComp;
Proc7(ptrParIn.PtrComp.IntComp, 10, ref ptrParIn.PtrComp.IntComp);
}
else {
ptrParIn = ptrParIn.PtrComp;
}
}
static void Proc2(ref int intParIO) {
int intLoc;
Enumeration enumLoc = Enumeration.Ident2;
intLoc = intParIO + 10;
for (;;) {
if (s_char1Glob == 'A') {
--intLoc;
intParIO = intLoc - s_intGlob;
enumLoc = Enumeration.Ident1;
}
if (enumLoc == Enumeration.Ident1) {
break;
}
}
}
static void Proc3(ref Record ptrParOut) {
if (m_ptrGlb != null) {
ptrParOut = m_ptrGlb.PtrComp;
}
else {
s_intGlob = 100;
}
Proc7(10, s_intGlob, ref m_ptrGlb.IntComp);
}
static void Proc4() {
bool boolLoc;
boolLoc = s_char1Glob == 'A';
boolLoc |= s_boolGlob;
s_char2Glob = 'B';
}
static void Proc5() {
s_char1Glob = 'A';
s_boolGlob = false;
}
static void Proc6(Enumeration enumParIn, ref Enumeration enumParOut) {
enumParOut = enumParIn;
if (!Func3(enumParIn)) {
enumParOut = Enumeration.Ident4;
}
switch (enumParIn) {
case Enumeration.Ident1:
enumParOut = Enumeration.Ident1;
break;
case Enumeration.Ident2:
if (s_intGlob > 100) {
enumParOut = Enumeration.Ident1;
}
else {
enumParOut = Enumeration.Ident4;
}
break;
case Enumeration.Ident3:
enumParOut = Enumeration.Ident2;
break;
case Enumeration.Ident4:
break;
case Enumeration.Ident5:
enumParOut = Enumeration.Ident3;
break;
}
}
static void Proc7(int intParI1, int intParI2, ref int intParOut) {
int intLoc;
intLoc = intParI1 + 2;
intParOut = intParI2 + intLoc;
}
static void Proc8(int[] array1Par, int[][] array2Par, int intParI1, int intParI2) {
int intLoc;
intLoc = intParI1 + 5;
array1Par[intLoc] = intParI2;
array1Par[intLoc + 1] = array1Par[intLoc];
array1Par[intLoc + 30] = intLoc;
for (int intIndex = intLoc; intIndex <= (intLoc + 1); ++intIndex) {
array2Par[intLoc][intIndex] = intLoc;
}
++array2Par[intLoc][intLoc - 1];
array2Par[intLoc + 20][intLoc] = array1Par[intLoc];
s_intGlob = 5;
}
static Enumeration Func1(char charPar1, char charPar2) {
char charLoc1;
char charLoc2;
charLoc1 = charPar1;
charLoc2 = charLoc1;
if (charLoc2 != charPar2) {
return (Enumeration.Ident1);
}
else {
return (Enumeration.Ident2);
}
}
static bool Func2(char[] strParI1, char[] strParI2) {
int intLoc;
char charLoc = '\0';
intLoc = 1;
while (intLoc <= 1) {
if (Func1(strParI1[intLoc], strParI2[intLoc + 1]) == Enumeration.Ident1) {
charLoc = 'A';
++intLoc;
}
}
if (charLoc >= 'W' && charLoc <= 'Z') {
intLoc = 7;
}
if (charLoc == 'X') {
return true;
}
else {
for (int i = 0; i < 30; i++) {
if (strParI1[i] > strParI2[i]) {
intLoc += 7;
return true;
}
}
return false;
}
}
static bool Func3(Enumeration enumParIn) {
Enumeration enumLoc;
enumLoc = enumParIn;
if (enumLoc == Enumeration.Ident3) {
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool Bench() {
m_array2Glob = AllocArray<int>(51, 51);
Proc0();
return true;
}
[Benchmark]
public static void Test() {
foreach (var iteration in Benchmark.Iterations) {
using (iteration.StartMeasurement()) {
Bench();
}
}
}
static bool TestBase() {
bool result = Bench();
return result;
}
public static int Main() {
bool result = TestBase();
return (result ? 100 : -1);
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
// .NET Compact Framework 1.0 has no support for System.Runtime.Remoting
#if !NETCF
using System;
using System.Collections;
using System.Threading;
using System.Runtime.Remoting.Messaging;
using Ctrip.Layout;
using Ctrip.Core;
using Ctrip.Util;
namespace Ctrip.Appender
{
/// <summary>
/// Delivers logging events to a remote logging sink.
/// </summary>
/// <remarks>
/// <para>
/// This Appender is designed to deliver events to a remote sink.
/// That is any object that implements the <see cref="IRemoteLoggingSink"/>
/// interface. It delivers the events using .NET remoting. The
/// object to deliver events to is specified by setting the
/// appenders <see cref="RemotingAppender.Sink"/> property.</para>
/// <para>
/// The RemotingAppender buffers events before sending them. This allows it to
/// make more efficient use of the remoting infrastructure.</para>
/// <para>
/// Once the buffer is full the events are still not sent immediately.
/// They are scheduled to be sent using a pool thread. The effect is that
/// the send occurs asynchronously. This is very important for a
/// number of non obvious reasons. The remoting infrastructure will
/// flow thread local variables (stored in the <see cref="CallContext"/>),
/// if they are marked as <see cref="ILogicalThreadAffinative"/>, across the
/// remoting boundary. If the server is not contactable then
/// the remoting infrastructure will clear the <see cref="ILogicalThreadAffinative"/>
/// objects from the <see cref="CallContext"/>. To prevent a logging failure from
/// having side effects on the calling application the remoting call must be made
/// from a separate thread to the one used by the application. A <see cref="ThreadPool"/>
/// thread is used for this. If no <see cref="ThreadPool"/> thread is available then
/// the events will block in the thread pool manager until a thread is available.</para>
/// <para>
/// Because the events are sent asynchronously using pool threads it is possible to close
/// this appender before all the queued events have been sent.
/// When closing the appender attempts to wait until all the queued events have been sent, but
/// this will timeout after 30 seconds regardless.</para>
/// <para>
/// If this appender is being closed because the <see cref="AppDomain.ProcessExit"/>
/// event has fired it may not be possible to send all the queued events. During process
/// exit the runtime limits the time that a <see cref="AppDomain.ProcessExit"/>
/// event handler is allowed to run for. If the runtime terminates the threads before
/// the queued events have been sent then they will be lost. To ensure that all events
/// are sent the appender must be closed before the application exits. See
/// <see cref="Ctrip.Core.LoggerManager.Shutdown"/> for details on how to shutdown
/// Ctrip programmatically.</para>
/// </remarks>
/// <seealso cref="IRemoteLoggingSink" />
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Daniel Cazzulino</author>
public class RemotingAppender : BufferingAppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="RemotingAppender" /> class.
/// </summary>
/// <remarks>
/// <para>
/// Default constructor.
/// </para>
/// </remarks>
public RemotingAppender()
{
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the URL of the well-known object that will accept
/// the logging events.
/// </summary>
/// <value>
/// The well-known URL of the remote sink.
/// </value>
/// <remarks>
/// <para>
/// The URL of the remoting sink that will accept logging events.
/// The sink must implement the <see cref="IRemoteLoggingSink"/>
/// interface.
/// </para>
/// </remarks>
public string Sink
{
get { return m_sinkUrl; }
set { m_sinkUrl = value; }
}
#endregion Public Instance Properties
#region Implementation of IOptionHandler
/// <summary>
/// Initialize the appender based on the options set
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
override public void ActivateOptions()
{
base.ActivateOptions();
IDictionary channelProperties = new Hashtable();
channelProperties["typeFilterLevel"] = "Full";
m_sinkObj = (IRemoteLoggingSink)Activator.GetObject(typeof(IRemoteLoggingSink), m_sinkUrl, channelProperties);
}
#endregion
#region Override implementation of BufferingAppenderSkeleton
/// <summary>
/// Send the contents of the buffer to the remote sink.
/// </summary>
/// <remarks>
/// The events are not sent immediately. They are scheduled to be sent
/// using a pool thread. The effect is that the send occurs asynchronously.
/// This is very important for a number of non obvious reasons. The remoting
/// infrastructure will flow thread local variables (stored in the <see cref="CallContext"/>),
/// if they are marked as <see cref="ILogicalThreadAffinative"/>, across the
/// remoting boundary. If the server is not contactable then
/// the remoting infrastructure will clear the <see cref="ILogicalThreadAffinative"/>
/// objects from the <see cref="CallContext"/>. To prevent a logging failure from
/// having side effects on the calling application the remoting call must be made
/// from a separate thread to the one used by the application. A <see cref="ThreadPool"/>
/// thread is used for this. If no <see cref="ThreadPool"/> thread is available then
/// the events will block in the thread pool manager until a thread is available.
/// </remarks>
/// <param name="events">The events to send.</param>
override protected void SendBuffer(LoggingEvent[] events)
{
// Setup for an async send
BeginAsyncSend();
// Send the events
if (!ThreadPool.QueueUserWorkItem(new WaitCallback(SendBufferCallback), events))
{
// Cancel the async send
EndAsyncSend();
ErrorHandler.Error("RemotingAppender ["+Name+"] failed to ThreadPool.QueueUserWorkItem logging events in SendBuffer.");
}
}
/// <summary>
/// Override base class close.
/// </summary>
/// <remarks>
/// <para>
/// This method waits while there are queued work items. The events are
/// sent asynchronously using <see cref="ThreadPool"/> work items. These items
/// will be sent once a thread pool thread is available to send them, therefore
/// it is possible to close the appender before all the queued events have been
/// sent.</para>
/// <para>
/// This method attempts to wait until all the queued events have been sent, but this
/// method will timeout after 30 seconds regardless.</para>
/// <para>
/// If the appender is being closed because the <see cref="AppDomain.ProcessExit"/>
/// event has fired it may not be possible to send all the queued events. During process
/// exit the runtime limits the time that a <see cref="AppDomain.ProcessExit"/>
/// event handler is allowed to run for.</para>
/// </remarks>
override protected void OnClose()
{
base.OnClose();
// Wait for the work queue to become empty before closing, timeout 30 seconds
if (!m_workQueueEmptyEvent.WaitOne(30 * 1000, false))
{
ErrorHandler.Error("RemotingAppender ["+Name+"] failed to send all queued events before close, in OnClose.");
}
}
#endregion
/// <summary>
/// A work item is being queued into the thread pool
/// </summary>
private void BeginAsyncSend()
{
// The work queue is not empty
m_workQueueEmptyEvent.Reset();
// Increment the queued count
Interlocked.Increment(ref m_queuedCallbackCount);
}
/// <summary>
/// A work item from the thread pool has completed
/// </summary>
private void EndAsyncSend()
{
// Decrement the queued count
if (Interlocked.Decrement(ref m_queuedCallbackCount) <= 0)
{
// If the work queue is empty then set the event
m_workQueueEmptyEvent.Set();
}
}
/// <summary>
/// Send the contents of the buffer to the remote sink.
/// </summary>
/// <remarks>
/// This method is designed to be used with the <see cref="ThreadPool"/>.
/// This method expects to be passed an array of <see cref="LoggingEvent"/>
/// objects in the state param.
/// </remarks>
/// <param name="state">the logging events to send</param>
private void SendBufferCallback(object state)
{
try
{
LoggingEvent[] events = (LoggingEvent[])state;
// Send the events
m_sinkObj.LogEvents(events);
}
catch(Exception ex)
{
ErrorHandler.Error("Failed in SendBufferCallback", ex);
}
finally
{
EndAsyncSend();
}
}
#region Private Instance Fields
/// <summary>
/// The URL of the remote sink.
/// </summary>
private string m_sinkUrl;
/// <summary>
/// The local proxy (.NET remoting) for the remote logging sink.
/// </summary>
private IRemoteLoggingSink m_sinkObj;
/// <summary>
/// The number of queued callbacks currently waiting or executing
/// </summary>
private int m_queuedCallbackCount = 0;
/// <summary>
/// Event used to signal when there are no queued work items
/// </summary>
/// <remarks>
/// This event is set when there are no queued work items. In this
/// state it is safe to close the appender.
/// </remarks>
private ManualResetEvent m_workQueueEmptyEvent = new ManualResetEvent(true);
#endregion Private Instance Fields
/// <summary>
/// Interface used to deliver <see cref="LoggingEvent"/> objects to a remote sink.
/// </summary>
/// <remarks>
/// This interface must be implemented by a remoting sink
/// if the <see cref="RemotingAppender"/> is to be used
/// to deliver logging events to the sink.
/// </remarks>
public interface IRemoteLoggingSink
{
/// <summary>
/// Delivers logging events to the remote sink
/// </summary>
/// <param name="events">Array of events to log.</param>
/// <remarks>
/// <para>
/// Delivers logging events to the remote sink
/// </para>
/// </remarks>
void LogEvents(LoggingEvent[] events);
}
}
}
#endif // !NETCF
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
using FickleFrostbite.FIT.Utility;
namespace FickleFrostbite.FIT
{
/// <summary>
/// Architecture defaults to Little Endian (unless decoded from an binary defn as Big Endian)
/// This could be exposed in the future to programatically create BE streams.
/// </summary>
public class MesgDefinition
{
#region Fields
private byte architecture;
private byte localMesgNum;
private List<FieldDefinition> fieldDefs = new List<FieldDefinition>();
#endregion
#region Properties
public ushort GlobalMesgNum { get; set; }
public byte LocalMesgNum
{
get
{
return localMesgNum;
}
set
{
if (value > Fit.LocalMesgNumMask)
{
throw new FitException("MesgDefinition:LocalMesgNum - Invalid Local message number " + value + ". Local message number must be < " + Fit.LocalMesgNumMask);
}
else
{
localMesgNum = value;
}
}
}
public byte NumFields { get; set; }
public bool IsBigEndian
{
get
{
if (architecture == Fit.BigEndian)
{
return true;
}
else
{
return false;
}
}
}
#endregion
#region Constructors
internal MesgDefinition()
{
LocalMesgNum = 0;
GlobalMesgNum = (ushort)MesgNum.Invalid;
architecture = Fit.LittleEndian;
}
public MesgDefinition(Stream fitSource)
{
Read(fitSource);
}
public MesgDefinition(Mesg mesg)
{
LocalMesgNum = mesg.LocalNum;
GlobalMesgNum = mesg.Num;
architecture = Fit.LittleEndian;
NumFields = (byte)mesg.fields.Count;
foreach (Field field in mesg.fields)
{
fieldDefs.Add(new FieldDefinition(field));
}
}
public MesgDefinition(MesgDefinition mesgDef)
{
LocalMesgNum = mesgDef.LocalMesgNum;
GlobalMesgNum = mesgDef.GlobalMesgNum;
architecture = mesgDef.IsBigEndian ? Fit.BigEndian : Fit.LittleEndian;
NumFields = mesgDef.NumFields;
foreach (FieldDefinition fieldDef in mesgDef.fieldDefs)
{
fieldDefs.Add(new FieldDefinition(fieldDef));
}
}
#endregion
#region Methods
public void Read(Stream fitSource)
{
fitSource.Position = 0;
EndianBinaryReader br = new EndianBinaryReader(fitSource, false);
LocalMesgNum = (byte)(br.ReadByte() & Fit.LocalMesgNumMask);
byte reserved = br.ReadByte();
architecture = br.ReadByte();
br.IsBigEndian = this.IsBigEndian;
GlobalMesgNum = br.ReadUInt16();
NumFields = br.ReadByte();
for (int i=0; i<NumFields; i++)
{
FieldDefinition newField = new FieldDefinition();
newField.Num = br.ReadByte();
newField.Size = br.ReadByte();
newField.Type = br.ReadByte();
fieldDefs.Add(newField);
}
}
public void Write (Stream fitDest)
{
BinaryWriter bw = new BinaryWriter(fitDest);
bw.Write((byte)(LocalMesgNum + Fit.MesgDefinitionMask));
bw.Write((byte)Fit.MesgDefinitionReserved);
bw.Write((byte)Fit.LittleEndian);
bw.Write(GlobalMesgNum);
bw.Write(NumFields);
if (NumFields != fieldDefs.Count)
{
throw new FitException("MesgDefinition:Write - Field Count Internal Error");
}
for (int i = 0; i < fieldDefs.Count; i++)
{
bw.Write(fieldDefs[i].Num);
bw.Write(fieldDefs[i].Size);
bw.Write(fieldDefs[i].Type);
}
}
public int GetMesgSize()
{
int mesgSize = 1; // header
foreach (FieldDefinition field in fieldDefs)
{
mesgSize += field.Size;
}
return mesgSize;
}
public void AddField(FieldDefinition field)
{
fieldDefs.Add(field);
}
public void ClearFields()
{
fieldDefs.Clear();
}
public int GetNumFields()
{
return fieldDefs.Count;
}
public List<FieldDefinition> GetFields()
{
// This is a reference to the real list
return fieldDefs;
}
public FieldDefinition GetField(byte num)
{
foreach (FieldDefinition fieldDef in fieldDefs)
{
if (fieldDef.Num == num)
{
return fieldDef;
}
}
return null;
}
public bool Supports(Mesg mesg)
{
return Supports(new MesgDefinition(mesg));
}
public bool Supports(MesgDefinition mesgDef)
{
if (mesgDef == null)
{
return false;
}
if (GlobalMesgNum != mesgDef.GlobalMesgNum)
{
return false;
}
if (LocalMesgNum != mesgDef.LocalMesgNum)
{
return false;
}
foreach (FieldDefinition fieldDef in mesgDef.GetFields())
{
FieldDefinition supportedFieldDef = GetField(fieldDef.Num);
if (supportedFieldDef == null)
{
return false;
}
if (fieldDef.Size > supportedFieldDef.Size)
{
return false;
}
}
return true;
}
#endregion
}
} // namespace
| |
//#define ASTARDEBUG
//#define ASTAR_DEBUGREPLAY
#define ASTAR_RECAST_ARRAY_BASED_LINKED_LIST //Faster Recast scan and nicer to GC, but might be worse at handling very large tile sizes. Makes Recast use linked lists based on structs in arrays instead of classes and references.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
using Pathfinding.Threading;
using Pathfinding.Voxels;
namespace Pathfinding.Voxels {
/** Voxelizer for recast graphs.
*
* In comments: units wu are World Units, vx are Voxels
*
* \astarpro
*/
public partial class Voxelize {
public List<ExtraMesh> inputExtraMeshes;
protected Vector3[] inputVertices;
protected int[] inputTriangles;
/* Minimum floor to 'ceiling' height that will still allow the floor area to
* be considered walkable. [Limit: > 0] [Units: wu] */
//public float walkableHeight = 0.8F;
/* Maximum ledge height that is considered to still be traversable. [Limit: >=0] [Units: wu] */
//public float walkableClimb = 0.8F;
/** Maximum ledge height that is considered to still be traversable. [Limit: >=0] [Units: vx] */
public readonly int voxelWalkableClimb;
/** Minimum floor to 'ceiling' height that will still allow the floor area to
* be considered walkable. [Limit: >= 3] [Units: vx] */
public readonly uint voxelWalkableHeight;
/** The xz-plane cell size to use for fields. [Limit: > 0] [Units: wu] */
public readonly float cellSize = 0.2F;
/** The y-axis cell size to use for fields. [Limit: > 0] [Units: wu] */
public readonly float cellHeight = 0.1F;
public int minRegionSize = 100;
/** The size of the non-navigable border around the heightfield. [Limit: >=0] [Units: vx] */
public int borderSize = 0;
/** The maximum allowed length for contour edges along the border of the mesh. [Limit: >= 0] [Units: vx] */
public float maxEdgeLength = 20;
/** The maximum slope that is considered walkable. [Limits: 0 <= value < 90] [Units: Degrees] */
public float maxSlope = 30;
public RecastGraph.RelevantGraphSurfaceMode relevantGraphSurfaceMode;
/** The world AABB to rasterize */
public Bounds forcedBounds;
public VoxelArea voxelArea;
public VoxelContourSet countourSet;
/** Width in voxels.
* Must match the #forcedBounds
*/
public int width;
/** Depth in voxels.
* Must match the #forcedBounds
*/
public int depth;
#region Debug
public Vector3 voxelOffset;
public Vector3 CompactSpanToVector(int x, int z, int i) {
return voxelOffset+new Vector3(x*cellSize,voxelArea.compactSpans[i].y*cellHeight,z*cellSize);
}
public void VectorToIndex(Vector3 p, out int x, out int z) {
p -= voxelOffset;
x = Mathf.RoundToInt (p.x / cellSize);
z = Mathf.RoundToInt (p.z / cellSize);
}
#endregion
#region Constants /** @name Constants @{ */
public const uint NotConnected = 0x3f;
/** Unmotivated variable, but let's clamp the layers at 65535 */
public const int MaxLayers = 65535;
/** \todo : Check up on this variable */
public const int MaxRegions = 500;
public const int UnwalkableArea = 0;
/** If heightfield region ID has the following bit set, the region is on border area
* and excluded from many calculations. */
public const ushort BorderReg = 0x8000;
/** If contour region ID has the following bit set, the vertex will be later
* removed in order to match the segments and vertices at tile boundaries. */
public const int RC_BORDER_VERTEX = 0x10000;
public const int RC_AREA_BORDER = 0x20000;
public const int VERTEX_BUCKET_COUNT = 1<<12;
public const int RC_CONTOUR_TESS_WALL_EDGES = 0x01; // Tessellate wall edges
public const int RC_CONTOUR_TESS_AREA_EDGES = 0x02; // Tessellate edges between areas.
/** Mask used with contours to extract region id. */
public const int ContourRegMask = 0xffff;
#endregion /** @} */
public string debugString = "";
#if !PhotonImplementation
public void OnGUI () {
GUI.Label (new Rect (5,5,200,Screen.height),debugString);
}
#endif
public readonly Vector3 cellScale;
public readonly Vector3 cellScaleDivision;
public Voxelize (float ch, float cs, float wc, float wh, float ms) {
cellSize = cs;
cellHeight = ch;
float walkableHeight = wh;
float walkableClimb = wc;
maxSlope = ms;
cellScale = new Vector3 (cellSize,cellHeight,cellSize);
cellScaleDivision = new Vector3 (1F/cellSize,1F/cellHeight,1F/cellSize);
voxelWalkableHeight = (uint)(walkableHeight/cellHeight);
voxelWalkableClimb = Mathf.RoundToInt (walkableClimb/cellHeight);
}
public void CollectMeshes () {
CollectMeshes (inputExtraMeshes, forcedBounds,out inputVertices, out inputTriangles);
}
public static void CollectMeshes (List<ExtraMesh> extraMeshes, Bounds bounds, out Vector3[] verts, out int[] tris) {
verts = null;
tris = null;
}
public void Init () {
//Initialize the voxel area
if (voxelArea == null || voxelArea.width != width || voxelArea.depth != depth)
voxelArea = new VoxelArea (width, depth);
else voxelArea.Reset ();
}
public void VoxelizeInput () {
AstarProfiler.StartProfile ("Build Navigation Mesh");
AstarProfiler.StartProfile ("Voxelizing - Step 1");
//Debug.DrawLine (forcedBounds.min,forcedBounds.max,Color.blue);
//Vector3 center = bounds.center;
Vector3 min = forcedBounds.min;
voxelOffset = min;
float ics = 1F/cellSize;
float ich = 1F/cellHeight;
AstarProfiler.EndProfile ("Voxelizing - Step 1");
AstarProfiler.StartProfile ("Voxelizing - Step 2 - Init");
float slopeLimit = Mathf.Cos (Mathf.Atan(Mathf.Tan(maxSlope*Mathf.Deg2Rad)*(ich*cellSize)));
//Utility.StartTimerAdditive (true);
float[] vTris = new float[3*3];
float[] vOut = new float[7*3];
float[] vRow = new float[7*3];
float[] vCellOut = new float[7*3];
float[] vCell = new float[7*3];
if (inputExtraMeshes == null) throw new System.NullReferenceException ("inputExtraMeshes not set");
//Find the largest lenghts of vertex arrays and check for meshes which can be skipped
int maxVerts = 0;
for (int m=0;m<inputExtraMeshes.Count;m++) {
if (!inputExtraMeshes[m].bounds.Intersects (forcedBounds)) continue;
maxVerts = System.Math.Max(inputExtraMeshes[m].vertices.Length, maxVerts);
}
//Create buffer, here vertices will be stored multiplied with the local-to-voxel-space matrix
Vector3[] verts = new Vector3[maxVerts];
Matrix4x4 voxelMatrix = Matrix4x4.Scale (new Vector3(ics,ich,ics)) * Matrix4x4.TRS(-min,Quaternion.identity, Vector3.one);
AstarProfiler.EndProfile ("Voxelizing - Step 2 - Init");
AstarProfiler.StartProfile ("Voxelizing - Step 2");
for (int m=0;m<inputExtraMeshes.Count;m++) {
ExtraMesh mesh = inputExtraMeshes[m];
if (!mesh.bounds.Intersects (forcedBounds)) continue;
Matrix4x4 matrix = mesh.matrix;
matrix = voxelMatrix * matrix;
Vector3[] vs = mesh.vertices;
int[] tris = mesh.triangles;
int trisLength = tris.Length;
for (int i=0;i<vs.Length;i++) verts[i] = matrix.MultiplyPoint3x4(vs[i]);
//AstarProfiler.StartFastProfile(0);
int mesharea = mesh.area;
for (int i=0;i<trisLength;i += 3) {
Vector3 p1;
Vector3 p2;
Vector3 p3;
int minX;
int minZ;
int maxX;
int maxZ;
p1 = verts[tris[i]];
p2 = verts[tris[i+1]];
p3 = verts[tris[i+2]];
minX = (int)(Utility.Min (p1.x,p2.x,p3.x));
// (Mathf.Min (Mathf.Min (p1.x,p2.x),p3.x));
minZ = (int)(Utility.Min (p1.z,p2.z,p3.z));
maxX = (int)System.Math.Ceiling (Utility.Max (p1.x,p2.x,p3.x));
maxZ = (int)System.Math.Ceiling (Utility.Max (p1.z,p2.z,p3.z));
minX = Mathf.Clamp (minX , 0 , voxelArea.width-1);
maxX = Mathf.Clamp (maxX , 0 , voxelArea.width-1);
minZ = Mathf.Clamp (minZ , 0 , voxelArea.depth-1);
maxZ = Mathf.Clamp (maxZ , 0 , voxelArea.depth-1);
if (minX >= voxelArea.width || minZ >= voxelArea.depth || maxX <= 0 || maxZ <= 0) continue;
//Debug.DrawLine (p1*cellSize+min+Vector3.up*0.2F,p2*cellSize+voxelOffset+Vector3.up*0.1F,Color.red);
//Debug.DrawLine (p2*cellSize+min+Vector3.up*0.1F,p3*cellSize+voxelOffset,Color.red);
Vector3 normal;
int area;
//AstarProfiler.StartProfile ("Rasterize...");
normal = Vector3.Cross (p2-p1,p3-p1);
float dot = Vector3.Dot (normal.normalized,Vector3.up);
if (dot < slopeLimit) {
area = UnwalkableArea;
} else {
area = 1 + mesharea;
}
//Debug.DrawRay (((p1+p2+p3)/3.0F)*cellSize+voxelOffset,normal,Color.cyan);
Utility.CopyVector (vTris,0,p1);
Utility.CopyVector (vTris,3,p2);
Utility.CopyVector (vTris,6,p3);
//Utility.StartTimerAdditive (false);
for (int x=minX;x<=maxX;x++) {
int nrow = Utility.ClipPolygon (vTris , 3 , vOut , 1F , -x+0.5F,0);
if (nrow < 3) {
continue;
}
nrow = Utility.ClipPolygon (vOut,nrow,vRow,-1F,x+0.5F,0);
if (nrow < 3) {
continue;
}
float clampZ1 = vRow[2];
float clampZ2 = vRow[2];
for (int q=1; q < nrow;q++) {
float val = vRow[q*3+2];
clampZ1 = System.Math.Min (clampZ1,val);
clampZ2 = System.Math.Max (clampZ2,val);
}
int clampZ1I = AstarMath.Clamp ((int)System.Math.Round (clampZ1),0, voxelArea.depth-1);
int clampZ2I = AstarMath.Clamp ((int)System.Math.Round (clampZ2),0, voxelArea.depth-1);
for (int z=clampZ1I;z<=clampZ2I;z++) {
//AstarProfiler.StartFastProfile(1);
int ncell = Utility.ClipPolygon (vRow , nrow , vCellOut , 1F , -z+0.5F,2);
if (ncell < 3) {
//AstarProfiler.EndFastProfile(1);
continue;
}
ncell = Utility.ClipPolygonY (vCellOut , ncell , vCell , -1F , z+0.5F,2);
if (ncell < 3) {
//AstarProfiler.EndFastProfile(1);
continue;
}
//AstarProfiler.EndFastProfile(1);
/*
for (int q=0, j = ncell-1; q < ncell; j=q, q++) {
Debug.DrawLine (vCell[q]*cellSize+min,vCell[j]*cellSize+min,Color.cyan);
}*/
//AstarProfiler.StartFastProfile(2);
float sMin = vCell[1];
float sMax = vCell[1];
for (int q=1; q < ncell;q++) {
float val = vCell[q*3+1];
sMin = System.Math.Min (sMin,val);
sMax = System.Math.Max (sMax,val);
}
//AstarProfiler.EndFastProfile(2);
//Debug.DrawLine (new Vector3(x,sMin,z)*cellSize+min,new Vector3(x,sMax,z)*cellSize+min,Color.cyan);
//if (z < 0 || x < 0 || z >= voxelArea.depth || x >= voxelArea.width) {
//Debug.DrawRay (new Vector3(x,sMin,z)*cellSize+min, Vector3.up, Color.red);
//continue;
//}
int maxi = (int)System.Math.Ceiling(sMax);
if (maxi >= 0) {
int mini = (int)(sMin+1);
voxelArea.AddLinkedSpan (z*voxelArea.width+x, (mini >= 0 ? (uint)mini : 0),(uint)maxi,area, voxelWalkableClimb);
//voxelArea.cells[z*voxelArea.width+x].AddSpan ((mini >= 0 ? (uint)mini : 0),(uint)maxi,area, voxelWalkableClimb);
}
}
}
}
//AstarProfiler.EndFastProfile(0);
//AstarProfiler.EndProfile ("Rasterize...");
//Utility.EndTimerAdditive ("",false);
}
AstarProfiler.EndProfile ("Voxelizing - Step 2");
//Debug.Log ("Span Count " + voxelArea.maxStackSize + " " + voxelArea.GetSpanCountAll() + " " + voxelArea.GetSpanCountAll2 () + " " + voxelArea.linkedSpanCount + " " + (voxelArea.linkedSpanCount - voxelArea.removedStackCount) + " " + (voxelArea.width*voxelArea.depth));
/*int wd = voxelArea.width*voxelArea.depth;
for (int x=0;x<wd;x++) {
VoxelCell c = voxelArea.cells[x];
float cPos = (float)x/(float)voxelArea.width;
float cPos2 = Mathf.Floor (cPos);
Vector3 p = new Vector3((cPos-cPos2)*voxelArea.width,0,cPos2);
p *= cellSize;
p += min;
VoxelSpan span = c.firstSpan;
int count =0;
while (span != null) {
Color col = count < Utility.colors.Length ? Utility.colors[count] : Color.white;
//p.y = span.bottom*cellSize+min.y;
Debug.DrawLine (p+new Vector3(0,span.bottom*cellSize,0),p+new Vector3(0,span.top*cellSize,0),col);
span = span.next;
count++;
}
}*/
//return;
//Step 2 - Navigable Space
//ErodeWalkableArea (2);
/*
voxelOffset = min;
AstarProfiler.StartProfile ("Build Distance Field");
BuildDistanceField (min);
AstarProfiler.EndProfile ("Build Distance Field");
AstarProfiler.StartProfile ("Build Regions");
BuildRegions (min);
AstarProfiler.EndProfile ("Build Regions");
AstarProfiler.StartProfile ("Build Contours");
BuildContours ();
AstarProfiler.EndProfile ("Build Contours");
AstarProfiler.EndProfile ("Build Navigation Mesh");
AstarProfiler.StartProfile ("Build Debug Mesh");
int sCount = voxelArea.compactSpans.Length;
Vector3[] debugPointsTop = new Vector3[sCount];
Vector3[] debugPointsBottom = new Vector3[sCount];
Color[] debugColors = new Color[sCount];
int debugPointsCount = 0;
//int wd = voxelArea.width*voxelArea.depth;
for (int z=0, pz = 0;z < wd;z += voxelArea.width, pz++) {
for (int x=0;x < voxelArea.width;x++) {
Vector3 p = new Vector3(x,0,pz)*cellSize+min;
//CompactVoxelCell c = voxelArea.compactCells[x+z];
CompactVoxelCell c = voxelArea.compactCells[x+z];
//if (c.count == 0) {
// Debug.DrawRay (p,Vector3.up,Color.red);
//}
for (int i=(int)c.index, ni = (int)(c.index+c.count);i<ni;i++) {
CompactVoxelSpan s = voxelArea.compactSpans[i];
p.y = ((float)(s.y+0.1F))*cellHeight+min.y;
debugPointsTop[debugPointsCount] = p;
p.y = ((float)s.y)*cellHeight+min.y;
debugPointsBottom[debugPointsCount] = p;
debugColors[debugPointsCount] = //Color.Lerp (Color.black, Color.white , (float)voxelArea.dist[i] / (float)voxelArea.maxDistance);
//Utility.GetColor ((int)s.area);
Utility.IntToColor ((int)s.reg,0.8F);
//Color.Lerp (Color.black, Color.white , (float)s.area / 10F);
//(float)(Mathf.Abs(dst[i]-src[i])) / (float)5);//s.area == 1 ? Color.green : (s.area == 2 ? Color.yellow : Color.red);
debugPointsCount++;
//Debug.DrawRay (p,Vector3.up*0.5F,Color.green);
}
}
}
DebugUtility.DrawCubes (debugPointsTop,debugPointsBottom,debugColors, cellSize);
AstarProfiler.EndProfile ("Build Debug Mesh");
/*for (int z=0, pz = 0;z < wd;z += voxelArea.width, pz++) {
for (int x=0;x < voxelArea.width;x++) {
Vector3 p = new Vector3(x,0,pz)*cellSize+min;
CompactVoxelCell c = voxelArea.compactCells[x+z];
if (c.count == 0) {
//Debug.DrawRay (p,Vector3.up,Color.red);
}
for (int i=(int)c.index, ni = (int)(c.index+c.count);i<ni;i++) {
CompactVoxelSpan s = voxelArea.compactSpans[i];
p.y = ((float)s.y)*cellHeight+min.y;
for (int d = 0; d<4;d++) {
int conn = s.GetConnection (d);
if (conn == NotConnected) {
//Debug.DrawRay (p,Vector3.up*0.2F,Color.red);
Debug.DrawRay (p,voxelArea.VectorDirection[d]*cellSize*0.5F,Color.red);
} else {
Debug.DrawRay (p,voxelArea.VectorDirection[d]*cellSize*0.5F,Color.green);
}
}
}
}
}*/
/*int sCount = voxelArea.compactSpans.Length;
Vector3[] debugPointsTop = new Vector3[sCount];
Vector3[] debugPointsBottom = new Vector3[sCount];
Color[] debugColors = new Color[sCount];
int debugPointsCount = 0;
//int wd = voxelArea.width*voxelArea.depth;
for (int z=0, pz = 0;z < wd;z += voxelArea.width, pz++) {
for (int x=0;x < voxelArea.width;x++) {
Vector3 p = new Vector3(x,0,pz)*cellSize+min;
//CompactVoxelCell c = voxelArea.compactCells[x+z];
CompactVoxelCell c = voxelArea.compactCells[x+z];
//if (c.count == 0) {
// Debug.DrawRay (p,Vector3.up,Color.red);
//}
for (int i=(int)c.index, ni = (int)(c.index+c.count);i<ni;i++) {
CompactVoxelSpan s = voxelArea.compactSpans[i];
p.y = ((float)(s.y+0.1F))*cellHeight+min.y;
debugPointsTop[debugPointsCount] = p;
p.y = ((float)s.y)*cellHeight+min.y;
debugPointsBottom[debugPointsCount] = p;
Color col = Color.black;
switch (s.area) {
case 0:
col = Color.red;
break;
case 1:
col = Color.green;
break;
case 2:
col = Color.yellow;
break;
case 3:
col = Color.magenta;
break;
}
debugColors[debugPointsCount] = col;//Color.Lerp (Color.black, Color.white , (float)dst[i] / (float)voxelArea.maxDistance);//(float)(Mathf.Abs(dst[i]-src[i])) / (float)5);//s.area == 1 ? Color.green : (s.area == 2 ? Color.yellow : Color.red);
debugPointsCount++;
//Debug.DrawRay (p,Vector3.up*0.5F,Color.green);
}
}
}
DebugUtility.DrawCubes (debugPointsTop,debugPointsBottom,debugColors, cellSize);*/
//AstarProfiler.PrintResults ();
//firstStep = false;
}
public void BuildCompactField () {
AstarProfiler.StartProfile ("Build Compact Voxel Field");
//Build compact representation
int spanCount = voxelArea.GetSpanCount ();
voxelArea.compactSpanCount = spanCount;
if (voxelArea.compactSpans == null || voxelArea.compactSpans.Length < spanCount) {
voxelArea.compactSpans = new CompactVoxelSpan[spanCount];
voxelArea.areaTypes = new int[spanCount];
}
uint idx = 0;
int w = voxelArea.width;
int d = voxelArea.depth;
int wd = w*d;
if (this.voxelWalkableHeight >= 0xFFFF) {
Debug.LogWarning ("Too high walkable height to guarantee correctness. Increase voxel height or lower walkable height.");
}
#if ASTAR_RECAST_ARRAY_BASED_LINKED_LIST
LinkedVoxelSpan[] spans = voxelArea.linkedSpans;
#endif
//Parallel.For (0, voxelArea.depth, delegate (int pz) {
for (int z=0, pz = 0;z < wd;z += w, pz++) {
for (int x=0;x < w;x++) {
#if ASTAR_RECAST_ARRAY_BASED_LINKED_LIST
int spanIndex = x+z;
if (spans[spanIndex].bottom == VoxelArea.InvalidSpanValue) {
voxelArea.compactCells[x+z] = new CompactVoxelCell (0,0);
continue;
}
uint index = idx;
uint count = 0;
//Vector3 p = new Vector3(x,0,pz)*cellSize+voxelOffset;
while (spanIndex != -1) {
if (spans[spanIndex].area != UnwalkableArea) {
int bottom = (int)spans[spanIndex].top;
int next = spans[spanIndex].next;
int top = next != -1 ? (int)spans[next].bottom : VoxelArea.MaxHeightInt;
voxelArea.compactSpans[idx] = new CompactVoxelSpan ((ushort)(bottom > 0xFFFF ? 0xFFFF : bottom) , (uint)(top-bottom > 0xFFFF ? 0xFFFF : top-bottom));
voxelArea.areaTypes[idx] = spans[spanIndex].area;
idx++;
count++;
}
spanIndex = spans[spanIndex].next;
}
voxelArea.compactCells[x+z] = new CompactVoxelCell (index, count);
#else
VoxelSpan s = voxelArea.cells[x+z].firstSpan;
if (s == null) {
voxelArea.compactCells[x+z] = new CompactVoxelCell (0,0);
continue;
}
uint index = idx;
uint count = 0;
//Vector3 p = new Vector3(x,0,pz)*cellSize+voxelOffset;
while (s != null) {
if (s.area != UnwalkableArea) {
int bottom = (int)s.top;
int top = s.next != null ? (int)s.next.bottom : VoxelArea.MaxHeightInt;
voxelArea.compactSpans[idx] = new CompactVoxelSpan ((ushort)Mathfx.Clamp (bottom, 0, 0xffff) , (uint)Mathfx.Clamp (top-bottom, 0, 0xffff));
voxelArea.areaTypes[idx] = s.area;
idx++;
count++;
}
s = s.next;
}
voxelArea.compactCells[x+z] = new CompactVoxelCell (index, count);
#endif
}
}
AstarProfiler.EndProfile ("Build Compact Voxel Field");
}
public void BuildVoxelConnections () {
AstarProfiler.StartProfile ("Build Voxel Connections");
int wd = voxelArea.width*voxelArea.depth;
CompactVoxelSpan[] spans = voxelArea.compactSpans;
CompactVoxelCell[] cells = voxelArea.compactCells;
//Build voxel connections
for (int z=0, pz = 0;z < wd;z += voxelArea.width, pz++) {
//System.Threading.ManualResetEvent[] handles = new System.Threading.ManualResetEvent[voxelArea.depth];
//This will run the loop in multiple threads (speedup by ? 40%)
//Parallel.For (0, voxelArea.depth, delegate (int pz) {
//System.Threading.WaitCallback del = delegate (System.Object _pz) {
//int pz = (int)_pz;
//int z = pz*voxelArea.width;
for (int x=0;x < voxelArea.width;x++) {
CompactVoxelCell c = cells[x+z];
//Vector3 p = new Vector3(x,0,pz)*cellSize+voxelOffset;
for (int i=(int)c.index, ni = (int)(c.index+c.count);i<ni;i++) {
CompactVoxelSpan s = spans[i];
spans[i].con = 0xFFFFFFFF;
//p.y = ((float)s.y)*cellHeight+voxelOffset.y;
for (int d=0;d<4;d++) {
//s.SetConnection (d,NotConnected);
//voxelArea.compactSpans[i].SetConnection (d,NotConnected);
int nx = x+voxelArea.DirectionX[d];
int nz = z+voxelArea.DirectionZ[d];
if (nx < 0 || nz < 0 || nz >= wd || nx >= voxelArea.width) {
continue;
}
CompactVoxelCell nc = cells[nx+nz];
for (int k=(int)nc.index, nk = (int)(nc.index+nc.count); k<nk; k++) {
CompactVoxelSpan ns = spans[k];
int bottom = System.Math.Max (s.y,ns.y);
int top = AstarMath.Min ((int)s.y+(int)s.h,(int)ns.y+(int)ns.h);
if ((top-bottom) >= voxelWalkableHeight && System.Math.Abs ((int)ns.y - (int)s.y) <= voxelWalkableClimb) {
uint connIdx = (uint)k - nc.index;
if (connIdx > MaxLayers) {
Debug.LogError ("Too many layers");
continue;
}
spans[i].SetConnection (d,connIdx);
break;
}
}
}
}
}
//handles[pz].Set ();
//};
//});
}
/*for (int z=0, pz = 0;z < wd;z += voxelArea.width, pz++) {
handles[pz] = new System.Threading.ManualResetEvent(false);
System.Threading.ThreadPool.QueueUserWorkItem (del, pz);
}
System.Threading.WaitHandle.WaitAll (handles);*/
AstarProfiler.EndProfile ("Build Voxel Connections");
}
public void DrawLine (int a, int b, int[] indices, int[] verts, Color col) {
int p1 = (indices[a] & 0x0fffffff) * 4;
int p2 = (indices[b] & 0x0fffffff) * 4;
Debug.DrawLine (ConvertPosCorrZ (verts[p1+0],verts[p1+1],verts[p1+2]),ConvertPosCorrZ (verts[p2+0],verts[p2+1],verts[p2+2]),col);
}
public Vector3 ConvertPos (int x, int y, int z) {
Vector3 p = Vector3.Scale (
new Vector3 (
x+0.5F,
y,
(z/(float)voxelArea.width)+0.5F
)
,cellScale)
+voxelOffset;
return p;
}
public Vector3 ConvertPosCorrZ (int x, int y, int z) {
Vector3 p = Vector3.Scale (
new Vector3 (
x,
y,
z
)
,cellScale)
+voxelOffset;
return p;
}
public Vector3 ConvertPosWithoutOffset (int x, int y, int z) {
Vector3 p = Vector3.Scale (
new Vector3 (
x,
y,
(z/(float)voxelArea.width)
)
,cellScale)
+voxelOffset;
return p;
}
/*
if (rcGetCon(s, dirp) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(dirp);
const int ay = y + rcGetDirOffsetY(dirp);
const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dirp);
const rcCompactSpan& as = chf.spans[ai];
ch = rcMax(ch, (int)as.y);
regs[3] = chf.spans[ai].reg | (chf.areas[ai] << 16);
if (rcGetCon(as, dir) != RC_NOT_CONNECTED)
{
const int ax2 = ax + rcGetDirOffsetX(dir);
const int ay2 = ay + rcGetDirOffsetY(dir);
const int ai2 = (int)chf.cells[ax2+ay2*chf.width].index + rcGetCon(as, dir);
const rcCompactSpan& as2 = chf.spans[ai2];
ch = rcMax(ch, (int)as2.y);
regs[2] = chf.spans[ai2].reg | (chf.areas[ai2] << 16);
}
}
// Check if the vertex is special edge vertex, these vertices will be removed later.
for (int j = 0; j < 4; ++j)
{
const int a = j;
const int b = (j+1) & 0x3;
const int c = (j+2) & 0x3;
const int d = (j+3) & 0x3;
// The vertex is a border vertex there are two same exterior cells in a row,
// followed by two interior cells and none of the regions are out of bounds.
const bool twoSameExts = (regs[a] & regs[b] & RC_BORDER_REG) != 0 && regs[a] == regs[b];
const bool twoInts = ((regs[c] | regs[d]) & RC_BORDER_REG) == 0;
const bool intsSameArea = (regs[c]>>16) == (regs[d]>>16);
const bool noZeros = regs[a] != 0 && regs[b] != 0 && regs[c] != 0 && regs[d] != 0;
if (twoSameExts && twoInts && intsSameArea && noZeros)
{
isBorderVertex = true;
break;
}
}
return ch;*/
public Vector3 ConvertPosition (int x,int z, int i) {
CompactVoxelSpan s = voxelArea.compactSpans[i];
return new Vector3 (x*cellSize,s.y*cellHeight,(z/(float)voxelArea.width)*cellSize)+voxelOffset;
}
public void ErodeWalkableArea (int radius) {
AstarProfiler.StartProfile ("Erode Walkable Area");
ushort[] src = voxelArea.tmpUShortArr;
if (src == null || src.Length < voxelArea.compactSpanCount) {
src = voxelArea.tmpUShortArr = new ushort[voxelArea.compactSpanCount];
}
Pathfinding.Util.Memory.MemSet<ushort> (src, 0xffff, sizeof(ushort));
//for (int i=0;i<src.Length;i++) {
// src[i] = 0xffff;
//}
CalculateDistanceField (src);
for (int i=0;i<src.Length;i++) {
//Note multiplied with 2 because the distance field increments distance by 2 for each voxel (and 3 for diagonal)
if (src[i] < radius*2) {
voxelArea.areaTypes[i] = UnwalkableArea;
}
}
AstarProfiler.EndProfile ("Erode Walkable Area");
}
public void BuildDistanceField () {
AstarProfiler.StartProfile ("Build Distance Field");
ushort[] src = voxelArea.tmpUShortArr;
if (src == null || src.Length < voxelArea.compactSpanCount) {
src = voxelArea.tmpUShortArr = new ushort[voxelArea.compactSpanCount];
}
Pathfinding.Util.Memory.MemSet<ushort> (src, 0xffff, sizeof(ushort));
//for (int i=0;i<src.Length;i++) {
// src[i] = 0xffff;
//}
voxelArea.maxDistance = CalculateDistanceField (src);
ushort[] dst = voxelArea.dist;
if (dst == null || dst.Length < voxelArea.compactSpanCount) {
dst = new ushort[voxelArea.compactSpanCount];
}
dst = BoxBlur (src,dst);
voxelArea.dist = dst;
AstarProfiler.EndProfile ("Build Distance Field");
}
/** \todo Complete the ErodeVoxels function translation */
[System.Obsolete ("This function is not complete and should not be used")]
public void ErodeVoxels (int radius) {
if (radius > 255) {
Debug.LogError ("Max Erode Radius is 255");
radius = 255;
}
int wd = voxelArea.width*voxelArea.depth;
int[] dist = new int[voxelArea.compactSpanCount];
for (int i=0;i<dist.Length;i++) {
dist[i] = 0xFF;
}
for (int z=0;z < wd;z += voxelArea.width) {
for (int x=0;x < voxelArea.width;x++) {
CompactVoxelCell c = voxelArea.compactCells[x+z];
for (int i= (int)c.index, ni = (int)(c.index+c.count); i < ni; i++) {
if (voxelArea.areaTypes[i] != UnwalkableArea) {
CompactVoxelSpan s = voxelArea.compactSpans[i];
int nc = 0;
for (int dir=0;dir<4;dir++) {
if (s.GetConnection (dir) != NotConnected)
nc++;
}
//At least one missing neighbour
if (nc != 4) {
dist[i] = 0;
}
}
}
}
}
//int nd = 0;
//Pass 1
/*for (int z=0;z < wd;z += voxelArea.width) {
for (int x=0;x < voxelArea.width;x++) {
CompactVoxelCell c = voxelArea.compactCells[x+z];
for (int i= (int)c.index, ci = (int)(c.index+c.count); i < ci; i++) {
CompactVoxelSpan s = voxelArea.compactSpans[i];
if (s.GetConnection (0) != NotConnected) {
// (-1,0)
int nx = x+voxelArea.DirectionX[0];
int nz = z+voxelArea.DirectionZ[0];
int ni = (int)(voxelArea.compactCells[nx+nz].index+s.GetConnection (0));
CompactVoxelSpan ns = voxelArea.compactSpans[ni];
if (dist[ni]+2 < dist[i]) {
dist[i] = (ushort)(dist[ni]+2);
}
if (ns.GetConnection (3) != NotConnected) {
// (-1,0) + (0,-1) = (-1,-1)
int nnx = nx+voxelArea.DirectionX[3];
int nnz = nz+voxelArea.DirectionZ[3];
int nni = (int)(voxelArea.compactCells[nnx+nnz].index+ns.GetConnection (3));
if (src[nni]+3 < src[i]) {
src[i] = (ushort)(src[nni]+3);
}
}
}
if (s.GetConnection (3) != NotConnected) {
// (0,-1)
int nx = x+voxelArea.DirectionX[3];
int nz = z+voxelArea.DirectionZ[3];
int ni = (int)(voxelArea.compactCells[nx+nz].index+s.GetConnection (3));
if (src[ni]+2 < src[i]) {
src[i] = (ushort)(src[ni]+2);
}
CompactVoxelSpan ns = voxelArea.compactSpans[ni];
if (ns.GetConnection (2) != NotConnected) {
// (0,-1) + (1,0) = (1,-1)
int nnx = nx+voxelArea.DirectionX[2];
int nnz = nz+voxelArea.DirectionZ[2];
int nni = (int)(voxelArea.compactCells[nnx+nnz].index+ns.GetConnection (2));
if (src[nni]+3 < src[i]) {
src[i] = (ushort)(src[nni]+3);
}
}
}
}
}
}*/
}
public void FilterLowHeightSpans (uint voxelWalkableHeight, float cs, float ch, Vector3 min) {
int wd = voxelArea.width*voxelArea.depth;
//Filter all ledges
#if ASTAR_RECAST_ARRAY_BASED_LINKED_LIST
LinkedVoxelSpan[] spans = voxelArea.linkedSpans;
for (int z=0, pz = 0;z < wd;z += voxelArea.width, pz++) {
for (int x=0;x < voxelArea.width;x++) {
for (int s = z+x; s != -1 && spans[s].bottom != VoxelArea.InvalidSpanValue; s = spans[s].next) {
uint bottom = spans[s].top;
uint top = spans[s].next != -1 ? spans[spans[s].next].bottom : VoxelArea.MaxHeight;
if (top - bottom < voxelWalkableHeight) {
spans[s].area = UnwalkableArea;
}
}
}
}
#else
for (int z=0, pz = 0;z < wd;z += voxelArea.width, pz++) {
for (int x=0;x < voxelArea.width;x++) {
for (VoxelSpan s = voxelArea.cells[z+x].firstSpan; s != null; s = s.next) {
uint bottom = s.top;
uint top = s.next != null ? s.next.bottom : VoxelArea.MaxHeight;
if (top - bottom < voxelWalkableHeight) {
s.area = UnwalkableArea;
}
}
}
}
#endif
}
//Code almost completely ripped from Recast
public void FilterLedges (uint voxelWalkableHeight, int voxelWalkableClimb, float cs, float ch, Vector3 min) {
int wd = voxelArea.width*voxelArea.depth;
#if ASTAR_RECAST_ARRAY_BASED_LINKED_LIST
LinkedVoxelSpan[] spans = voxelArea.linkedSpans;
#endif
int[] DirectionX = voxelArea.DirectionX;
int[] DirectionZ = voxelArea.DirectionZ;
int width = voxelArea.width;
//int depth = voxelArea.depth;
//Filter all ledges
for (int z=0, pz = 0;z < wd;z += width, pz++) {
for (int x=0;x < width;x++) {
#if ASTAR_RECAST_ARRAY_BASED_LINKED_LIST
if (spans[x+z].bottom == VoxelArea.InvalidSpanValue) continue;
for (int s = x+z; s != -1; s = spans[s].next) {
//Skip non-walkable spans
if (spans[s].area == UnwalkableArea) {
continue;
}
int bottom = (int)spans[s].top;
int top = spans[s].next != -1 ? (int)spans[spans[s].next].bottom : VoxelArea.MaxHeightInt;
int minHeight = VoxelArea.MaxHeightInt;
int aMinHeight = (int)spans[s].top;
int aMaxHeight = aMinHeight;
for (int d = 0; d < 4; d++) {
int nx = x+DirectionX[d];
int nz = z+DirectionZ[d];
//Skip out-of-bounds points
if (nx < 0 || nz < 0 || nz >= wd || nx >= width) {
spans[s].area = UnwalkableArea;
break;
}
int nsx = nx+nz;
int nbottom = -voxelWalkableClimb;
int ntop = spans[nsx].bottom != VoxelArea.InvalidSpanValue ? (int)spans[nsx].bottom : VoxelArea.MaxHeightInt;
if (System.Math.Min (top,ntop) - System.Math.Max (bottom,nbottom) > voxelWalkableHeight) {
minHeight = System.Math.Min (minHeight, nbottom - bottom);
}
//Loop through spans
if (spans[nsx].bottom != VoxelArea.InvalidSpanValue) {
for (int ns = nsx; ns != -1; ns = spans[ns].next) {
nbottom = (int)spans[ns].top;
ntop = spans[ns].next != -1 ? (int)spans[spans[ns].next].bottom : VoxelArea.MaxHeightInt;
if (System.Math.Min (top, ntop) - System.Math.Max (bottom, nbottom) > voxelWalkableHeight) {
minHeight = AstarMath.Min (minHeight, nbottom - bottom);
if (System.Math.Abs (nbottom - bottom) <= voxelWalkableClimb) {
if (nbottom < aMinHeight) { aMinHeight = nbottom; }
if (nbottom > aMaxHeight) { aMaxHeight = nbottom; }
}
}
}
}
}
if (minHeight < -voxelWalkableClimb || (aMaxHeight - aMinHeight) > voxelWalkableClimb) {
spans[s].area = UnwalkableArea;
}
}
#else
for (VoxelSpan s = voxelArea.cells[z+x].firstSpan; s != null; s = s.next) {
//Skip non-walkable spans
if (s.area == UnwalkableArea) {
continue;
}
int bottom = (int)s.top;
int top = s.next != null ? (int)s.next.bottom : VoxelArea.MaxHeightInt;
int minHeight = VoxelArea.MaxHeightInt;
int aMinHeight = (int)s.top;
int aMaxHeight = (int)s.top;
for (int d = 0; d < 4; d++) {
int nx = x+voxelArea.DirectionX[d];
int nz = z+voxelArea.DirectionZ[d];
//Skip out-of-bounds points
if (nx < 0 || nz < 0 || nz >= wd || nx >= voxelArea.width) {
s.area = UnwalkableArea;
break;
}
VoxelSpan nsx = voxelArea.cells[nx+nz].firstSpan;
int nbottom = -voxelWalkableClimb;
int ntop = nsx != null ? (int)nsx.bottom : VoxelArea.MaxHeightInt;
if (Mathfx.Min (top,ntop) - Mathfx.Max (bottom,nbottom) > voxelWalkableHeight) {
minHeight = Mathfx.Min (minHeight, nbottom - bottom);
}
//Loop through spans
for (VoxelSpan ns = nsx; ns != null; ns = ns.next) {
nbottom = (int)ns.top;
ntop = ns.next != null ? (int)ns.next.bottom : VoxelArea.MaxHeightInt;
if (Mathfx.Min (top, ntop) - Mathfx.Max (bottom, nbottom) > voxelWalkableHeight) {
minHeight = Mathfx.Min (minHeight, nbottom - bottom);
if (Mathfx.Abs (nbottom - bottom) <= voxelWalkableClimb) {
if (nbottom < aMinHeight) { aMinHeight = nbottom; }
if (nbottom > aMaxHeight) { aMaxHeight = nbottom; }
}
}
}
}
if (minHeight < -voxelWalkableClimb || (aMaxHeight - aMinHeight) > voxelWalkableClimb) {
s.area = UnwalkableArea;
}
}
#endif
}
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="ObservableCollection.cs" company="Microsoft">
// Copyright (C) 2003 by Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Implementation of an Collection<T> implementing INotifyCollectionChanged
// to notify listeners of dynamic changes of the list.
//
// See spec at http://avalon/connecteddata/Specs/Collection%20Interfaces.mht
//
// History:
// 11/22/2004 : [....] - created
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace System.Collections.ObjectModel
{
/// <summary>
/// Implementation of a dynamic data collection based on generic Collection<T>,
/// implementing INotifyCollectionChanged to notify listeners
/// when items get added, removed or the whole list is refreshed.
/// </summary>
#if !FEATURE_NETCORE
[Serializable()]
[TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
#endif
public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Initializes a new instance of ObservableCollection that is empty and has default initial capacity.
/// </summary>
public ObservableCollection() : base() { }
/// <summary>
/// Initializes a new instance of the ObservableCollection class
/// that contains elements copied from the specified list
/// </summary>
/// <param name="list">The list whose elements are copied to the new list.</param>
/// <remarks>
/// The elements are copied onto the ObservableCollection in the
/// same order they are read by the enumerator of the list.
/// </remarks>
/// <exception cref="ArgumentNullException"> list is a null reference </exception>
public ObservableCollection(List<T> list)
: base((list != null) ? new List<T>(list.Count) : list)
{
// Workaround for VSWhidbey bug 562681 (tracked by Windows bug 1369339).
// We should be able to simply call the base(list) ctor. But Collection<T>
// doesn't copy the list (contrary to the documentation) - it uses the
// list directly as its storage. So we do the copying here.
//
CopyFrom(list);
}
/// <summary>
/// Initializes a new instance of the ObservableCollection class that contains
/// elements copied from the specified collection and has sufficient capacity
/// to accommodate the number of elements copied.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
/// <remarks>
/// The elements are copied onto the ObservableCollection in the
/// same order they are read by the enumerator of the collection.
/// </remarks>
/// <exception cref="ArgumentNullException"> collection is a null reference </exception>
public ObservableCollection(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
CopyFrom(collection);
}
private void CopyFrom(IEnumerable<T> collection)
{
IList<T> items = Items;
if (collection != null && items != null)
{
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
while (enumerator.MoveNext())
{
items.Add(enumerator.Current);
}
}
}
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Move item at oldIndex to newIndex.
/// </summary>
public void Move(int oldIndex, int newIndex)
{
MoveItem(oldIndex, newIndex);
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
#region Public Events
//------------------------------------------------------
#region INotifyPropertyChanged implementation
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add
{
PropertyChanged += value;
}
remove
{
PropertyChanged -= value;
}
}
#endregion INotifyPropertyChanged implementation
//------------------------------------------------------
/// <summary>
/// Occurs when the collection changes, either by adding or removing an item.
/// </summary>
/// <remarks>
/// see <seealso cref="INotifyCollectionChanged"/>
/// </remarks>
#if !FEATURE_NETCORE
[field:NonSerializedAttribute()]
#endif
public virtual event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion Public Events
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Called by base class Collection<T> when the list is being cleared;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void ClearItems()
{
CheckReentrancy();
base.ClearItems();
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnCollectionReset();
}
/// <summary>
/// Called by base class Collection<T> when an item is removed from list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void RemoveItem(int index)
{
CheckReentrancy();
T removedItem = this[index];
base.RemoveItem(index);
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Remove, removedItem, index);
}
/// <summary>
/// Called by base class Collection<T> when an item is added to list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void InsertItem(int index, T item)
{
CheckReentrancy();
base.InsertItem(index, item);
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
}
/// <summary>
/// Called by base class Collection<T> when an item is set in list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void SetItem(int index, T item)
{
CheckReentrancy();
T originalItem = this[index];
base.SetItem(index, item);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Replace, originalItem, item, index);
}
/// <summary>
/// Called by base class ObservableCollection<T> when an item is to be moved within the list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected virtual void MoveItem(int oldIndex, int newIndex)
{
CheckReentrancy();
T removedItem = this[oldIndex];
base.RemoveItem(oldIndex);
base.InsertItem(newIndex, removedItem);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Move, removedItem, newIndex, oldIndex);
}
/// <summary>
/// Raises a PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
#if !FEATURE_NETCORE
[field:NonSerializedAttribute()]
#endif
protected virtual event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raise CollectionChanged event to any listeners.
/// Properties/methods modifying this ObservableCollection will raise
/// a collection changed event through this virtual method.
/// </summary>
/// <remarks>
/// When overriding this method, either call its base implementation
/// or call <see cref="BlockReentrancy"/> to guard against reentrant collection changes.
/// </remarks>
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
using (BlockReentrancy())
{
CollectionChanged(this, e);
}
}
}
/// <summary>
/// Disallow reentrant attempts to change this collection. E.g. a event handler
/// of the CollectionChanged event is not allowed to make changes to this collection.
/// </summary>
/// <remarks>
/// typical usage is to wrap e.g. a OnCollectionChanged call with a using() scope:
/// <code>
/// using (BlockReentrancy())
/// {
/// CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, item, index));
/// }
/// </code>
/// </remarks>
protected IDisposable BlockReentrancy()
{
_monitor.Enter();
return _monitor;
}
/// <summary> Check and assert for reentrant attempts to change this collection. </summary>
/// <exception cref="InvalidOperationException"> raised when changing the collection
/// while another collection change is still being notified to other listeners </exception>
protected void CheckReentrancy()
{
if (_monitor.Busy)
{
// we can allow changes if there's only one listener - the problem
// only arises if reentrant changes make the original event args
// invalid for later listeners. This keeps existing code working
// (e.g. Selector.SelectedItems).
if ((CollectionChanged != null) && (CollectionChanged.GetInvocationList().Length > 1))
throw new InvalidOperationException(SR.GetString(SR.ObservableCollectionReentrancyNotAllowed));
}
}
#endregion Protected Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Helper to raise a PropertyChanged event />).
/// </summary>
private void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index, int oldIndex)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index, oldIndex));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index));
}
/// <summary>
/// Helper to raise CollectionChanged event with action == Reset to any listeners
/// </summary>
private void OnCollectionReset()
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Types
// this class helps prevent reentrant calls
#if !FEATURE_NETCORE
[Serializable()]
[TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
#endif
private class SimpleMonitor : IDisposable
{
public void Enter()
{
++ _busyCount;
}
public void Dispose()
{
-- _busyCount;
}
public bool Busy { get { return _busyCount > 0; } }
int _busyCount;
}
#endregion Private Types
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private const string CountString = "Count";
// This must agree with Binding.IndexerName. It is declared separately
// here so as to avoid a dependency on PresentationFramework.dll.
private const string IndexerName = "Item[]";
private SimpleMonitor _monitor = new SimpleMonitor();
#endregion Private Fields
}
}
| |
namespace NEventStore.Persistence.Sql.SqlDialects
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Transactions;
using NEventStore.Logging;
using NEventStore.Persistence.Sql;
using System.Data.Common;
using System.Threading.Tasks;
using System.Threading;
using ALinq;
using System.Linq;
public class PagedEnumerationCollection : IEnumerable<IDataRecord>, IEnumerator<IDataRecord>
{
private static readonly ILog Logger = LogFactory.BuildLogger(typeof (PagedEnumerationCollection));
private readonly IDbCommand _command;
private readonly ISqlDialect _dialect;
private readonly IEnumerable<IDisposable> _disposable = new IDisposable[] {};
private readonly NextPageDelegate _nextpage;
private readonly int _pageSize;
private readonly TransactionScope _scope;
private IDataRecord _current;
private bool _disposed;
private int _position;
private IDataReader _reader;
public PagedEnumerationCollection(
TransactionScope scope,
ISqlDialect dialect,
IDbCommand command,
NextPageDelegate nextpage,
int pageSize,
params IDisposable[] disposable)
{
_scope = scope;
_dialect = dialect;
_command = command;
_nextpage = nextpage;
_pageSize = pageSize;
_disposable = disposable ?? _disposable;
}
public virtual IEnumerator<IDataRecord> GetEnumerator()
{
if (_disposed)
{
throw new ObjectDisposedException(Messages.ObjectAlreadyDisposed);
}
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
bool IEnumerator.MoveNext()
{
if (_disposed)
{
throw new ObjectDisposedException(Messages.ObjectAlreadyDisposed);
}
if (MoveToNextRecord())
{
return true;
}
Logger.Verbose(Messages.QueryCompleted);
return false;
}
public virtual void Reset()
{
throw new NotSupportedException("Forward-only readers.");
}
public virtual IDataRecord Current
{
get
{
if (_disposed)
{
throw new ObjectDisposedException(Messages.ObjectAlreadyDisposed);
}
return _current = _reader;
}
}
object IEnumerator.Current
{
get { return ((IEnumerator<IDataRecord>) this).Current; }
}
protected virtual void Dispose(bool disposing)
{
if (!disposing || _disposed)
{
return;
}
_disposed = true;
_position = 0;
_current = null;
if (_reader != null)
{
_reader.Dispose();
}
_reader = null;
if (_command != null)
{
_command.Dispose();
}
// queries do not modify state and thus calling Complete() on a so-called 'failed' query only
// allows any outer transaction scope to decide the fate of the transaction
if (_scope != null)
{
_scope.Complete(); // caller will dispose scope.
}
foreach (var dispose in _disposable)
{
dispose.Dispose();
}
}
private bool MoveToNextRecord()
{
if (_pageSize > 0 && _position >= _pageSize)
{
_command.SetParameter(_dialect.Skip, _position);
_nextpage(_command, _current);
}
_reader = _reader ?? OpenNextPage();
if (_reader.Read())
{
return IncrementPosition();
}
if (!PagingEnabled())
{
return false;
}
if (!PageCompletelyEnumerated())
{
return false;
}
Logger.Verbose(Messages.EnumeratedRowCount, _position);
_reader.Dispose();
_reader = OpenNextPage();
//r.GetStreamToSnapshot()
if (_reader.Read())
{
return IncrementPosition();
}
return false;
}
private bool IncrementPosition()
{
_position++;
return true;
}
private bool PagingEnabled()
{
return _pageSize > 0;
}
private bool PageCompletelyEnumerated()
{
return _position > 0 && 0 == _position%_pageSize;
}
private IDataReader OpenNextPage()
{
try
{
return _command.ExecuteReader();
}
catch (Exception e)
{
Logger.Debug(Messages.EnumerationThrewException, e.GetType());
throw new StorageUnavailableException(e.Message, e);
}
}
}
public class AsyncPagedEnumerationCollection : IAsyncEnumerable<IDataRecord>, IAsyncEnumerator<IDataRecord>
{
private static readonly ILog Logger = LogFactory.BuildLogger(typeof(PagedEnumerationCollection));
private readonly IAsyncDbCommand _command;
private readonly ISqlDialect _dialect;
private readonly IEnumerable<IDisposable> _disposable = new IDisposable[] { };
private readonly NextPageDelegate _nextpage;
private readonly int _pageSize;
private readonly TransactionScope _scope;
private IDataRecord _current;
private bool _disposed;
private int _position;
private IAsyncDataReader _reader;
public AsyncPagedEnumerationCollection(
TransactionScope scope,
ISqlDialect dialect,
IAsyncDbCommand command,
NextPageDelegate nextpage,
int pageSize,
params IDisposable[] disposable)
{
_scope = scope;
_dialect = dialect;
_command = command;
_nextpage = nextpage;
_pageSize = pageSize;
_disposable = disposable ?? _disposable;
}
public virtual IAsyncEnumerator<IDataRecord> GetEnumerator()
{
if (_disposed)
{
throw new ObjectDisposedException(Messages.ObjectAlreadyDisposed);
}
return this;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public async Task<bool> MoveNext(CancellationToken cancellationToken)
{
if (_disposed)
{
throw new ObjectDisposedException(Messages.ObjectAlreadyDisposed);
}
if (await MoveToNextRecord())
{
return true;
}
Logger.Verbose(Messages.QueryCompleted);
return false;
}
public virtual IDataRecord Current
{
get
{
if (_disposed)
{
throw new ObjectDisposedException(Messages.ObjectAlreadyDisposed);
}
return _current = _reader;
}
}
object IAsyncEnumerator.Current
{
get
{
return Current;
}
}
protected virtual void Dispose(bool disposing)
{
if (!disposing || _disposed)
{
return;
}
_disposed = true;
_position = 0;
_current = null;
if (_reader != null)
{
_reader.Dispose();
}
_reader = null;
if (_command != null)
{
_command.Dispose();
}
// queries do not modify state and thus calling Complete() on a so-called 'failed' query only
// allows any outer transaction scope to decide the fate of the transaction
if (_scope != null)
{
_scope.Complete(); // caller will dispose scope.
}
foreach (var dispose in _disposable)
{
dispose.Dispose();
}
}
private async Task<bool> MoveToNextRecord()
{
if (_pageSize > 0 && _position >= _pageSize)
{
_command.SetParameter(_dialect.Skip, _position);
_nextpage(_command, _current);
}
_reader = _reader ?? (await OpenNextPage());
if (await _reader.ReadAsync())
{
return IncrementPosition();
}
if (!PagingEnabled())
{
return false;
}
if (!PageCompletelyEnumerated())
{
return false;
}
Logger.Verbose(Messages.EnumeratedRowCount, _position);
_reader.Dispose();
_reader = await OpenNextPage();
//r.GetStreamToSnapshot()
if (await _reader.ReadAsync())
{
return IncrementPosition();
}
return false;
}
private bool IncrementPosition()
{
_position++;
return true;
}
private bool PagingEnabled()
{
return _pageSize > 0;
}
private bool PageCompletelyEnumerated()
{
return _position > 0 && 0 == _position % _pageSize;
}
private async Task<IAsyncDataReader> OpenNextPage()
{
try
{
return await _command.ExecuteReaderAsync();
}
catch (Exception e)
{
Logger.Debug(Messages.EnumerationThrewException, e.GetType());
throw new StorageUnavailableException(e.Message, e);
}
}
IAsyncEnumerator IAsyncEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public async Task<bool> MoveNext()
{
if (_disposed)
{
throw new ObjectDisposedException(Messages.ObjectAlreadyDisposed);
}
if (await MoveToNextRecord())
{
return true;
}
Dispose();
Logger.Verbose(Messages.QueryCompleted);
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information
//
// XmlDsigC14NTransformTest.cs - Test Cases for XmlDsigC14NTransform
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
// Aleksey Sanin (aleksey@aleksey.com)
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// (C) 2003 Aleksey Sanin (aleksey@aleksey.com)
// (C) 2004 Novell (http://www.novell.com)
//
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Resolvers;
using Xunit;
namespace System.Security.Cryptography.Xml.Tests
{
// Note: GetInnerXml is protected in XmlDsigC14NTransform making it
// difficult to test properly. This class "open it up" :-)
public class UnprotectedXmlDsigC14NTransform : XmlDsigC14NTransform
{
public XmlNodeList UnprotectedGetInnerXml()
{
return base.GetInnerXml();
}
}
public class XmlDsigC14NTransformTest
{
[Fact]
public void Constructor_Empty()
{
XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
Assert.Equal("http://www.w3.org/TR/2001/REC-xml-c14n-20010315", transform.Algorithm);
CheckProperties(transform);
}
[Theory]
[InlineData(true, "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments")]
[InlineData(false, "http://www.w3.org/TR/2001/REC-xml-c14n-20010315")]
public void Constructor_Bool(bool includeComments, string expectedAlgorithm)
{
XmlDsigC14NTransform transform = new XmlDsigC14NTransform(includeComments);
Assert.Equal(expectedAlgorithm, transform.Algorithm);
CheckProperties(transform);
}
public void CheckProperties(XmlDsigC14NTransform transform)
{
Assert.Null(transform.Context);
Assert.Equal(new[] { typeof(Stream), typeof(XmlDocument), typeof(XmlNodeList) }, transform.InputTypes);
Assert.Equal(new[] { typeof(Stream) }, transform.OutputTypes);
}
[Fact]
public void GetInnerXml()
{
UnprotectedXmlDsigC14NTransform transform = new UnprotectedXmlDsigC14NTransform();
XmlNodeList xnl = transform.UnprotectedGetInnerXml();
Assert.Null(xnl);
}
static string xml = "<Test attrib='at ' xmlns=\"http://www.go-mono.com/\" > \r\n 
 <Toto/> text & </Test >";
// GOOD for Stream input
static string c14xml2 = "<Test xmlns=\"http://www.go-mono.com/\" attrib=\"at \"> \n 
 <Toto></Toto> text & </Test>";
// GOOD for XmlDocument input. The difference is because once
// xml string is loaded to XmlDocument, there is no difference
// between \r and 
, so every \r must be handled as 
.
static string c14xml3 = "<Test xmlns=\"http://www.go-mono.com/\" attrib=\"at \"> 
\n 
 <Toto></Toto> text & </Test>";
private XmlDocument GetDoc()
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml(xml);
return doc;
}
[Fact]
public void LoadInputAsXmlDocument()
{
XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
XmlDocument doc = GetDoc();
transform.LoadInput(doc);
Stream s = (Stream)transform.GetOutput();
string output = TestHelpers.StreamToString(s, Encoding.UTF8);
Assert.Equal(c14xml3, output);
}
[Fact]
// see LoadInputAsXmlNodeList2 description
public void LoadInputAsXmlNodeList()
{
XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
XmlDocument doc = GetDoc();
// Argument list just contains element Test.
transform.LoadInput(doc.ChildNodes);
Stream s = (Stream)transform.GetOutput();
string output = TestHelpers.StreamToString(s, Encoding.UTF8);
Assert.Equal(@"<Test xmlns=""http://www.go-mono.com/""></Test>", output);
}
[Fact]
// MS has a bug that those namespace declaration nodes in
// the node-set are written to output. Related spec section is:
// http://www.w3.org/TR/2001/REC-xml-c14n-20010315#ProcessingModel
public void LoadInputAsXmlNodeList2()
{
XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
XmlDocument doc = GetDoc();
transform.LoadInput(doc.SelectNodes("//*"));
Stream s = (Stream)transform.GetOutput();
string output = TestHelpers.StreamToString(s, Encoding.UTF8);
string expected = @"<Test xmlns=""http://www.go-mono.com/""><Toto></Toto></Test>";
Assert.Equal(expected, output);
}
[Fact]
public void LoadInputAsStream()
{
XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
MemoryStream ms = new MemoryStream();
byte[] x = Encoding.ASCII.GetBytes(xml);
ms.Write(x, 0, x.Length);
ms.Position = 0;
transform.LoadInput(ms);
Stream s = (Stream)transform.GetOutput();
string output = TestHelpers.StreamToString(s, Encoding.UTF8);
Assert.Equal(c14xml2, output);
}
[Fact]
public void LoadInputWithUnsupportedType()
{
XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
byte[] bad = { 0xBA, 0xD };
AssertExtensions.Throws<ArgumentException>("obj", () => transform.LoadInput(bad));
}
[Fact]
public void UnsupportedOutput()
{
XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
XmlDocument doc = new XmlDocument();
AssertExtensions.Throws<ArgumentException>("type", () => transform.GetOutput(doc.GetType()));
}
[Fact]
public void C14NSpecExample1()
{
XmlPreloadedResolver resolver = new XmlPreloadedResolver();
resolver.Add(new Uri("doc.xsl", UriKind.Relative), "");
string result = TestHelpers.ExecuteTransform(C14NSpecExample1Input, new XmlDsigC14NTransform());
Assert.Equal(C14NSpecExample1Output, result);
}
[Theory]
[InlineData(C14NSpecExample2Input, C14NSpecExample2Output)]
[InlineData(C14NSpecExample3Input, C14NSpecExample3Output)]
[InlineData(C14NSpecExample4Input, C14NSpecExample4Output)]
public void C14NSpecExample(string input, string expectedOutput)
{
string result = TestHelpers.ExecuteTransform(input, new XmlDsigC14NTransform());
Assert.Equal(expectedOutput, result);
}
[Fact]
public void C14NSpecExample5()
{
XmlPreloadedResolver resolver = new XmlPreloadedResolver();
resolver.Add(TestHelpers.ToUri("doc.txt"), "world");
string result = TestHelpers.ExecuteTransform(C14NSpecExample5Input, new XmlDsigC14NTransform(), Encoding.UTF8, resolver);
Assert.Equal(C14NSpecExample5Output, result);
}
[Fact]
public void C14NSpecExample6()
{
string result = TestHelpers.ExecuteTransform(C14NSpecExample6Input, new XmlDsigC14NTransform(), Encoding.GetEncoding("ISO-8859-1"));
Assert.Equal(C14NSpecExample6Output, result);
}
//
// Example 1 from C14N spec - PIs, Comments, and Outside of Document Element:
// http://www.w3.org/TR/xml-c14n#Example-OutsideDoc
//
// Aleksey:
// removed reference to an empty external DTD
//
static string C14NSpecExample1Input =
"<?xml version=\"1.0\"?>\n" +
"\n" +
"<?xml-stylesheet href=\"doc.xsl\"\n" +
" type=\"text/xsl\" ?>\n" +
"\n" +
"\n" +
"<doc>Hello, world!<!-- Comment 1 --></doc>\n" +
"\n" +
"<?pi-without-data ?>\n\n" +
"<!-- Comment 2 -->\n\n" +
"<!-- Comment 3 -->\n";
static string C14NSpecExample1Output =
"<?xml-stylesheet href=\"doc.xsl\"\n" +
" type=\"text/xsl\" ?>\n" +
"<doc>Hello, world!</doc>\n" +
"<?pi-without-data?>";
//
// Example 2 from C14N spec - Whitespace in Document Content:
// http://www.w3.org/TR/xml-c14n#Example-WhitespaceInContent
//
const string C14NSpecExample2Input =
"<doc>\n" +
" <clean> </clean>\n" +
" <dirty> A B </dirty>\n" +
" <mixed>\n" +
" A\n" +
" <clean> </clean>\n" +
" B\n" +
" <dirty> A B </dirty>\n" +
" C\n" +
" </mixed>\n" +
"</doc>\n";
const string C14NSpecExample2Output =
"<doc>\n" +
" <clean> </clean>\n" +
" <dirty> A B </dirty>\n" +
" <mixed>\n" +
" A\n" +
" <clean> </clean>\n" +
" B\n" +
" <dirty> A B </dirty>\n" +
" C\n" +
" </mixed>\n" +
"</doc>";
//
// Example 3 from C14N spec - Start and End Tags:
// http://www.w3.org/TR/xml-c14n#Example-SETags
//
const string C14NSpecExample3Input =
"<!DOCTYPE doc [<!ATTLIST e9 attr CDATA \"default\">]>\n" +
"<doc>\n" +
" <e1 />\n" +
" <e2 ></e2>\n" +
" <e3 name = \"elem3\" id=\"elem3\" />\n" +
" <e4 name=\"elem4\" id=\"elem4\" ></e4>\n" +
" <e5 a:attr=\"out\" b:attr=\"sorted\" attr2=\"all\" attr=\"I\'m\"\n" +
" xmlns:b=\"http://www.ietf.org\" \n" +
" xmlns:a=\"http://www.w3.org\"\n" +
" xmlns=\"http://www.uvic.ca\"/>\n" +
" <e6 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" +
" <e7 xmlns=\"http://www.ietf.org\">\n" +
" <e8 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" +
" <e9 xmlns=\"\" xmlns:a=\"http://www.ietf.org\"/>\n" +
" </e8>\n" +
" </e7>\n" +
" </e6>\n" +
"</doc>\n";
const string C14NSpecExample3Output =
"<doc>\n" +
" <e1></e1>\n" +
" <e2></e2>\n" +
" <e3 id=\"elem3\" name=\"elem3\"></e3>\n" +
" <e4 id=\"elem4\" name=\"elem4\"></e4>\n" +
" <e5 xmlns=\"http://www.uvic.ca\" xmlns:a=\"http://www.w3.org\" xmlns:b=\"http://www.ietf.org\" attr=\"I\'m\" attr2=\"all\" b:attr=\"sorted\" a:attr=\"out\"></e5>\n" +
" <e6 xmlns:a=\"http://www.w3.org\">\n" +
" <e7 xmlns=\"http://www.ietf.org\">\n" +
" <e8 xmlns=\"\">\n" +
" <e9 xmlns:a=\"http://www.ietf.org\" attr=\"default\"></e9>\n" +
// " <e9 xmlns:a=\"http://www.ietf.org\"></e9>\n" +
" </e8>\n" +
" </e7>\n" +
" </e6>\n" +
"</doc>";
//
// Example 4 from C14N spec - Character Modifications and Character References:
// http://www.w3.org/TR/xml-c14n#Example-Chars
//
// Aleksey:
// This test does not include "normId" element
// because it has an invalid ID attribute "id" which
// should be normalized by XML parser. Currently Mono
// does not support this (see comment after this example
// in the spec).
const string C14NSpecExample4Input =
"<!DOCTYPE doc [<!ATTLIST normId id ID #IMPLIED>]>\n" +
"<doc>\n" +
" <text>First line
 Second line</text>\n" +
" <value>2</value>\n" +
" <compute><![CDATA[value>\"0\" && value<\"10\" ?\"valid\":\"error\"]]></compute>\n" +
" <compute expr=\'value>\"0\" && value<\"10\" ?\"valid\":\"error\"\'>valid</compute>\n" +
" <norm attr=\' '   
	 ' \'/>\n" +
// " <normId id=\' '   
	 ' \'/>\n" +
"</doc>\n";
const string C14NSpecExample4Output =
"<doc>\n" +
" <text>First line
\n" +
"Second line</text>\n" +
" <value>2</value>\n" +
" <compute>value>\"0\" && value<\"10\" ?\"valid\":\"error\"</compute>\n" +
" <compute expr=\"value>"0" && value<"10" ?"valid":"error"\">valid</compute>\n" +
" <norm attr=\" \' 
	 \' \"></norm>\n" +
// " <normId id=\"\' 
	 \'\"></normId>\n" +
"</doc>";
//
// Example 5 from C14N spec - Entity References:
// http://www.w3.org/TR/xml-c14n#Example-Entities
//
static string C14NSpecExample5Input =>
"<!DOCTYPE doc [\n" +
"<!ATTLIST doc attrExtEnt ENTITY #IMPLIED>\n" +
"<!ENTITY ent1 \"Hello\">\n" +
$"<!ENTITY ent2 SYSTEM \"doc.txt\">\n" +
"<!ENTITY entExt SYSTEM \"earth.gif\" NDATA gif>\n" +
"<!NOTATION gif SYSTEM \"viewgif.exe\">\n" +
"]>\n" +
"<doc attrExtEnt=\"entExt\">\n" +
" &ent1;, &ent2;!\n" +
"</doc>\n" +
"\n" +
"<!-- Let world.txt contain \"world\" (excluding the quotes) -->\n";
static string C14NSpecExample5Output =
"<doc attrExtEnt=\"entExt\">\n" +
" Hello, world!\n" +
"</doc>";
//
// Example 6 from C14N spec - UTF-8 Encoding:
// http://www.w3.org/TR/xml-c14n#Example-UTF8
//
static string C14NSpecExample6Input =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" +
"<doc>©</doc>\n";
static string C14NSpecExample6Output =
"<doc>\xC2\xA9</doc>";
[Fact]
public void SimpleNamespacePrefixes()
{
string input = "<a:Action xmlns:a='urn:foo'>http://tempuri.org/IFoo/Echo</a:Action>";
string expected = @"<a:Action xmlns:a=""urn:foo"">http://tempuri.org/IFoo/Echo</a:Action>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(input);
XmlDsigC14NTransform t = new XmlDsigC14NTransform();
t.LoadInput(doc);
Stream s = t.GetOutput() as Stream;
Assert.Equal(new StreamReader(s, Encoding.UTF8).ReadToEnd(), expected);
}
[Fact]
public void OrdinalSortForAttributes()
{
XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
XmlDocument doc = new XmlDocument();
string xml = "<foo Aa=\"one\" Bb=\"two\" aa=\"three\" bb=\"four\"><bar></bar></foo>";
doc.LoadXml(xml);
transform.LoadInput(doc);
Stream s = (Stream)transform.GetOutput();
string output = TestHelpers.StreamToString(s, Encoding.UTF8);
Assert.Equal(xml, output);
}
[Fact(Skip = "https://github.com/dotnet/corefx/issues/16780")]
public void PrefixlessNamespaceOutput()
{
XmlDocument doc = new XmlDocument();
doc.AppendChild(doc.CreateElement("foo", "urn:foo"));
doc.DocumentElement.AppendChild(doc.CreateElement("bar", "urn:bar"));
Assert.Equal(String.Empty, doc.DocumentElement.GetAttribute("xmlns"));
XmlDsigC14NTransform t = new XmlDsigC14NTransform();
t.LoadInput(doc);
Stream s = t.GetOutput() as Stream;
Assert.Equal(new StreamReader(s, Encoding.UTF8).ReadToEnd(), "<foo xmlns=\"urn:foo\"><bar xmlns=\"urn:bar\"></bar></foo>");
Assert.Equal("urn:foo", doc.DocumentElement.GetAttribute("xmlns"));
}
[Fact]
public void GetDigestedOutput_Null()
{
Assert.Throws< NullReferenceException>(() => new XmlDsigExcC14NTransform().GetDigestedOutput(null));
}
}
}
| |
// 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 Test.Utilities;
using Xunit;
namespace Desktop.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingAnalyzerTests : DiagnosticAnalyzerTestBase
{
private static readonly string s_CA3075XmlTextReaderSetInsecureResolutionMessage = DesktopAnalyzersResources.XmlTextReaderSetInsecureResolutionMessage;
private DiagnosticResult GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(int line, int column)
{
return GetCSharpResultAt(line, column, CA3075RuleId, s_CA3075XmlTextReaderSetInsecureResolutionMessage);
}
private DiagnosticResult GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(int line, int column)
{
return GetBasicResultAt(line, column, CA3075RuleId, s_CA3075XmlTextReaderSetInsecureResolutionMessage);
}
[Fact]
public void UseXmlTextReaderNoCtorShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
var count = reader.AttributeCount;
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Dim count = reader.AttributeCount
End Sub
End Class
End Namespace");
}
[Fact]
public void XmlTextReaderNoCtorSetResolverToNullShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
reader.XmlResolver = new XmlUrlResolver();
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
reader.XmlResolver = New XmlUrlResolver()
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 13)
);
}
[Fact]
public void XmlTextReaderNoCtorSetDtdProcessingToParseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
reader.DtdProcessing = DtdProcessing.Parse;
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
reader.DtdProcessing = DtdProcessing.Parse
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 13)
);
}
[Fact]
public void XmlTextReaderNoCtorSetBothToInsecureValuesShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader, XmlUrlResolver resolver)
{
reader.XmlResolver = resolver;
reader.DtdProcessing = DtdProcessing.Parse;
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 13),
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader, resolver As XmlUrlResolver)
reader.XmlResolver = resolver
reader.DtdProcessing = DtdProcessing.Parse
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 13),
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 13)
);
}
[Fact]
public void XmlTextReaderNoCtorSetInSecureResolverInTryClauseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try
{
reader.XmlResolver = new XmlUrlResolver();
}
catch { throw; }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 17)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
reader.XmlResolver = New XmlUrlResolver()
Catch
Throw
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetInSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try { }
catch { reader.XmlResolver = new XmlUrlResolver(); }
finally {}
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
Catch
reader.XmlResolver = New XmlUrlResolver()
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(9, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetInSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try { }
catch { throw; }
finally { reader.XmlResolver = new XmlUrlResolver(); }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 23)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
Catch
Throw
Finally
reader.XmlResolver = New XmlUrlResolver()
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetDtdprocessingToParseInTryClauseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try
{
reader.DtdProcessing = DtdProcessing.Parse;
}
catch { throw; }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 17)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
reader.DtdProcessing = DtdProcessing.Parse
Catch
Throw
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetDtdprocessingToParseInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try { }
catch { reader.DtdProcessing = DtdProcessing.Parse; }
finally { }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
Catch
reader.DtdProcessing = DtdProcessing.Parse
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(9, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetDtdprocessingToParseInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try { }
catch { throw; }
finally { reader.DtdProcessing = DtdProcessing.Parse; }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 23)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
Catch
Throw
Finally
reader.DtdProcessing = DtdProcessing.Parse
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 17)
);
}
[Fact]
public void ConstructXmlTextReaderSetInsecureResolverInInitializerShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(string path)
{
XmlTextReader doc = new XmlTextReader(path)
{
XmlResolver = new XmlUrlResolver()
};
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 33)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(path As String)
Dim doc As New XmlTextReader(path) With { _
.XmlResolver = New XmlUrlResolver() _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 24)
);
}
[Fact]
public void ConstructXmlTextReaderSetDtdProcessingParseInInitializerShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(string path)
{
XmlTextReader doc = new XmlTextReader(path)
{
DtdProcessing = DtdProcessing.Parse
};
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 33)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(path As String)
Dim doc As New XmlTextReader(path) With { _
.DtdProcessing = DtdProcessing.Parse _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 24)
);
}
[Fact]
public void ConstructXmlTextReaderSetBothToInsecureValuesInInitializerShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(string path)
{
XmlTextReader doc = new XmlTextReader(path)
{
DtdProcessing = DtdProcessing.Parse,
XmlResolver = new XmlUrlResolver()
};
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 33)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(path As String)
Dim doc As New XmlTextReader(path) With { _
.DtdProcessing = DtdProcessing.Parse, _
.XmlResolver = New XmlUrlResolver() _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 24)
);
}
[Fact]
public void XmlTextReaderDerivedTypeSetInsecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class DerivedType : XmlTextReader {}
class TestClass
{
void TestMethod()
{
var c = new DerivedType(){ XmlResolver = new XmlUrlResolver() };
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(13, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class DerivedType
Inherits XmlTextReader
End Class
Class TestClass
Private Sub TestMethod()
Dim c = New DerivedType() With { _
.XmlResolver = New XmlUrlResolver() _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 21)
);
}
[Fact]
public void XmlTextReaderDerivedTypeSetDtdProcessingParseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class DerivedType : XmlTextReader {}
class TestClass
{
void TestMethod()
{
var c = new DerivedType(){ DtdProcessing = DtdProcessing.Parse };
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(13, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class DerivedType
Inherits XmlTextReader
End Class
Class TestClass
Private Sub TestMethod()
Dim c = New DerivedType() With { _
.DtdProcessing = DtdProcessing.Parse _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 21)
);
}
[Fact]
public void XmlTextReaderCreatedAsTempSetSecureSettingsShouldNotGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public void Method1(string path)
{
Method2(new XmlTextReader(path){ XmlResolver = null, DtdProcessing = DtdProcessing.Prohibit });
}
public void Method2(XmlTextReader reader){}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public Sub Method1(path As String)
Method2(New XmlTextReader(path) With { _
.XmlResolver = Nothing, _
.DtdProcessing = DtdProcessing.Prohibit _
})
End Sub
Public Sub Method2(reader As XmlTextReader)
End Sub
End Class
End Namespace");
}
[Fact]
public void XmlTextReaderCreatedAsTempSetInsecureResolverShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public void Method1(string path)
{
Method2(new XmlTextReader(path){ XmlResolver = new XmlUrlResolver(), DtdProcessing = DtdProcessing.Prohibit });
}
public void Method2(XmlTextReader reader){}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public Sub Method1(path As String)
Method2(New XmlTextReader(path) With { _
.XmlResolver = New XmlUrlResolver(), _
.DtdProcessing = DtdProcessing.Prohibit _
})
End Sub
Public Sub Method2(reader As XmlTextReader)
End Sub
End Class
End Namespace
",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 21)
);
}
[Fact]
public void XmlTextReaderCreatedAsTempSetDtdProcessingParseShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public void Method1(string path)
{
Method2(new XmlTextReader(path){ XmlResolver = null, DtdProcessing = DtdProcessing.Parse });
}
public void Method2(XmlTextReader reader){}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public Sub Method1(path As String)
Method2(New XmlTextReader(path) With { _
.XmlResolver = Nothing, _
.DtdProcessing = DtdProcessing.Parse _
})
End Sub
Public Sub Method2(reader As XmlTextReader)
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 21)
);
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.ElasticLoadBalancing.Model
{
/// <summary>
/// <para> The HealthCheck data type. </para>
/// </summary>
public class HealthCheck
{
private string target;
private int? interval;
private int? timeout;
private int? unhealthyThreshold;
private int? healthyThreshold;
/// <summary>
/// Default constructor for a new HealthCheck object. Callers should use the
/// properties or fluent setter (With...) methods to initialize this object after creating it.
/// </summary>
public HealthCheck() {}
/// <summary>
/// Constructs a new HealthCheck object.
/// Callers should use the properties or fluent setter (With...) methods to
/// initialize any additional object members.
/// </summary>
///
/// <param name="target"> Specifies the instance being checked. The protocol is either TCP, HTTP, HTTPS, or SSL. The range of valid ports is one
/// (1) through 65535. <note> TCP is the default, specified as a TCP: port pair, for example "TCP:5000". In this case a healthcheck simply
/// attempts to open a TCP connection to the instance on the specified port. Failure to connect within the configured timeout is considered
/// unhealthy. SSL is also specified as SSL: port pair, for example, SSL:5000. For HTTP or HTTPS protocol, the situation is different. You have
/// to include a ping path in the string. HTTP is specified as a HTTP:port;/;PathToPing; grouping, for example "HTTP:80/weather/us/wa/seattle".
/// In this case, a HTTP GET request is issued to the instance on the given port and path. Any answer other than "200 OK" within the timeout
/// period is considered unhealthy. The total length of the HTTP ping target needs to be 1024 16-bit Unicode characters or less. </note>
/// </param>
/// <param name="interval"> Specifies the approximate interval, in seconds, between health checks of an individual instance. </param>
/// <param name="timeout"> Specifies the amount of time, in seconds, during which no response means a failed health probe. <note> This value
/// must be less than the <i>Interval</i> value. </note> </param>
/// <param name="unhealthyThreshold"> Specifies the number of consecutive health probe failures required before moving the instance to the
/// <i>Unhealthy</i> state. </param>
/// <param name="healthyThreshold"> Specifies the number of consecutive health probe successes required before moving the instance to the
/// <i>Healthy</i> state. </param>
public HealthCheck(string target, int interval, int timeout, int unhealthyThreshold, int healthyThreshold)
{
this.target = target;
this.interval = interval;
this.timeout = timeout;
this.unhealthyThreshold = unhealthyThreshold;
this.healthyThreshold = healthyThreshold;
}
/// <summary>
/// Specifies the instance being checked. The protocol is either TCP, HTTP, HTTPS, or SSL. The range of valid ports is one (1) through 65535.
/// <note> TCP is the default, specified as a TCP: port pair, for example "TCP:5000". In this case a healthcheck simply attempts to open a TCP
/// connection to the instance on the specified port. Failure to connect within the configured timeout is considered unhealthy. SSL is also
/// specified as SSL: port pair, for example, SSL:5000. For HTTP or HTTPS protocol, the situation is different. You have to include a ping path
/// in the string. HTTP is specified as a HTTP:port;/;PathToPing; grouping, for example "HTTP:80/weather/us/wa/seattle". In this case, a HTTP
/// GET request is issued to the instance on the given port and path. Any answer other than "200 OK" within the timeout period is considered
/// unhealthy. The total length of the HTTP ping target needs to be 1024 16-bit Unicode characters or less. </note>
///
/// </summary>
public string Target
{
get { return this.target; }
set { this.target = value; }
}
/// <summary>
/// Sets the Target property
/// </summary>
/// <param name="target">The value to set for the Target property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public HealthCheck WithTarget(string target)
{
this.target = target;
return this;
}
// Check to see if Target property is set
internal bool IsSetTarget()
{
return this.target != null;
}
/// <summary>
/// Specifies the approximate interval, in seconds, between health checks of an individual instance.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>1 - 300</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int Interval
{
get { return this.interval ?? default(int); }
set { this.interval = value; }
}
/// <summary>
/// Sets the Interval property
/// </summary>
/// <param name="interval">The value to set for the Interval property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public HealthCheck WithInterval(int interval)
{
this.interval = interval;
return this;
}
// Check to see if Interval property is set
internal bool IsSetInterval()
{
return this.interval.HasValue;
}
/// <summary>
/// Specifies the amount of time, in seconds, during which no response means a failed health probe. <note> This value must be less than the
/// <i>Interval</i> value. </note>
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>1 - 300</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int Timeout
{
get { return this.timeout ?? default(int); }
set { this.timeout = value; }
}
/// <summary>
/// Sets the Timeout property
/// </summary>
/// <param name="timeout">The value to set for the Timeout property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public HealthCheck WithTimeout(int timeout)
{
this.timeout = timeout;
return this;
}
// Check to see if Timeout property is set
internal bool IsSetTimeout()
{
return this.timeout.HasValue;
}
/// <summary>
/// Specifies the number of consecutive health probe failures required before moving the instance to the <i>Unhealthy</i> state.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>2 - 10</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int UnhealthyThreshold
{
get { return this.unhealthyThreshold ?? default(int); }
set { this.unhealthyThreshold = value; }
}
/// <summary>
/// Sets the UnhealthyThreshold property
/// </summary>
/// <param name="unhealthyThreshold">The value to set for the UnhealthyThreshold property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public HealthCheck WithUnhealthyThreshold(int unhealthyThreshold)
{
this.unhealthyThreshold = unhealthyThreshold;
return this;
}
// Check to see if UnhealthyThreshold property is set
internal bool IsSetUnhealthyThreshold()
{
return this.unhealthyThreshold.HasValue;
}
/// <summary>
/// Specifies the number of consecutive health probe successes required before moving the instance to the <i>Healthy</i> state.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>2 - 10</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int HealthyThreshold
{
get { return this.healthyThreshold ?? default(int); }
set { this.healthyThreshold = value; }
}
/// <summary>
/// Sets the HealthyThreshold property
/// </summary>
/// <param name="healthyThreshold">The value to set for the HealthyThreshold property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public HealthCheck WithHealthyThreshold(int healthyThreshold)
{
this.healthyThreshold = healthyThreshold;
return this;
}
// Check to see if HealthyThreshold property is set
internal bool IsSetHealthyThreshold()
{
return this.healthyThreshold.HasValue;
}
}
}
| |
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
$GUI_EDITOR_DEFAULT_PROFILE_FILENAME = "art/gui/customProfiles.cs";
$GUI_EDITOR_DEFAULT_PROFILE_CATEGORY = "Other";
//=============================================================================================
// GuiEditor.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function GuiEditor::createNewProfile( %this, %name, %copySource )
{
if( %name $= "" )
return;
// Make sure the object name is unique.
if( isObject( %name ) )
%name = getUniqueName( %name );
// Create the profile.
if( %copySource !$= "" )
eval( "new GuiControlProfile( " @ %name @ " : " @ %copySource.getName() @ " );" );
else
eval( "new GuiControlProfile( " @ %name @ " );" );
// Add the item and select it.
%category = %this.getProfileCategory( %name );
%group = GuiEditorProfilesTree.findChildItemByName( 0, %category );
%id = GuiEditorProfilesTree.insertItem( %group, %name @ " (" @ %name.getId() @ ")", %name.getId(), "" );
GuiEditorProfilesTree.sort( 0, true, true, false );
GuiEditorProfilesTree.clearSelection();
GuiEditorProfilesTree.selectItem( %id );
// Mark it as needing to be saved.
%this.setProfileDirty( %name, true );
}
//---------------------------------------------------------------------------------------------
function GuiEditor::getProfileCategory( %this, %profile )
{
if( %this.isDefaultProfile( %name ) )
return "Default";
else if( %profile.category !$= "" )
return %profile.category;
else
return $GUI_EDITOR_DEFAULT_PROFILE_CATEGORY;
}
//---------------------------------------------------------------------------------------------
function GuiEditor::showDeleteProfileDialog( %this, %profile )
{
if( %profile $= "" )
return;
if( %profile.isInUse() )
{
MessageBoxOk( "Error",
"The profile '" @ %profile.getName() @ "' is still used by Gui controls."
);
return;
}
MessageBoxYesNo( "Delete Profile?",
"Do you really want to delete '" @ %profile.getName() @ "'?",
"GuiEditor.deleteProfile( " @ %profile @ " );"
);
}
//---------------------------------------------------------------------------------------------
function GuiEditor::deleteProfile( %this, %profile )
{
if( isObject( "GuiEditorProfilesPM" ) )
new PersistenceManager( GuiEditorProfilesPM );
// Clear dirty state.
%this.setProfileDirty( %profile, false );
// Remove from tree.
%id = GuiEditorProfilesTree.findItemByValue( %profile.getId() );
GuiEditorProfilesTree.removeItem( %id );
// Remove from file.
GuiEditorProfilesPM.removeObjectFromFile( %profile );
// Delete profile object.
%profile.delete();
}
//---------------------------------------------------------------------------------------------
function GuiEditor::showSaveProfileDialog( %this, %currentFileName )
{
getSaveFileName( "TorqueScript Files|*.cs", %this @ ".doSaveProfile", %currentFileName );
}
//---------------------------------------------------------------------------------------------
function GuiEditor::doSaveProfile( %this, %fileName )
{
%path = makeRelativePath( %fileName, getMainDotCsDir() );
GuiEditorProfileFileName.setText( %path );
%this.saveProfile( GuiEditorProfilesTree.getSelectedProfile(), %path );
}
//---------------------------------------------------------------------------------------------
function GuiEditor::saveProfile( %this, %profile, %fileName )
{
if( !isObject( "GuiEditorProfilesPM" ) )
new PersistenceManager( GuiEditorProfilesPM );
if( !GuiEditorProfilesPM.isDirty( %profile )
&& ( %fileName $= "" || %fileName $= %profile.getFileName() ) )
return;
// Update the filename, if requested.
if( %fileName !$= "" )
{
%profile.setFileName( %fileName );
GuiEditorProfilesPM.setDirty( %profile, %fileName );
}
// Save the object.
GuiEditorProfilesPM.saveDirtyObject( %profile );
// Clear its dirty state.
%this.setProfileDirty( %profile, false, true );
}
//---------------------------------------------------------------------------------------------
function GuiEditor::revertProfile( %this, %profile )
{
// Revert changes.
GuiEditorProfileChangeManager.revertEdits( %profile );
// Clear its dirty state.
%this.setProfileDirty( %profile, false );
// Refresh inspector.
if( GuiEditorProfileInspector.getInspectObject() == %profile )
GuiEditorProfileInspector.refresh();
}
//---------------------------------------------------------------------------------------------
function GuiEditor::isProfileDirty( %this, %profile )
{
if( !isObject( "GuiEditorProfilesPM" ) )
return false;
return GuiEditorProfilesPM.isDirty( %profile );
}
//---------------------------------------------------------------------------------------------
function GuiEditor::setProfileDirty( %this, %profile, %value, %noCheck )
{
if( !isObject( "GuiEditorProfilesPM" ) )
new PersistenceManager( GuiEditorProfilesPM );
if( %value )
{
if( !GuiEditorProfilesPM.isDirty( %profile ) || %noCheck )
{
// If the profile hasn't yet been associated with a file,
// put it in the default file.
if( %profile.getFileName() $= "" )
%profile.setFileName( $GUI_EDITOR_DEFAULT_PROFILE_FILENAME );
// Add the profile to the dirty set.
GuiEditorProfilesPM.setDirty( %profile );
// Show the item as dirty in the tree.
%id = GuiEditorProfilesTree.findItemByValue( %profile.getId() );
GuiEditorProfilesTree.editItem( %id, GuiEditorProfilesTree.getItemText( %id ) SPC "*", %profile.getId() );
// Count the number of unsaved profiles. If this is
// the first one, indicate in the window title that
// we have unsaved profiles.
%this.increaseNumDirtyProfiles();
}
}
else
{
if( GuiEditorProfilesPM.isDirty( %profile ) || %noCheck )
{
// Remove from dirty list.
GuiEditorProfilesPM.removeDirty( %profile );
// Clear the dirty marker in the tree.
%id = GuiEditorProfilesTree.findItemByValue( %profile.getId() );
%text = GuiEditorProfilesTree.getItemText( %id );
GuiEditorProfilesTree.editItem( %id, getSubStr( %text, 0, strlen( %text ) - 2 ), %profile.getId() );
// Count saved profiles. If this was the last unsaved profile,
// remove the unsaved changes indicator from the window title.
%this.decreaseNumDirtyProfiles();
// Remove saved edits from the change manager.
GuiEditorProfileChangeManager.clearEdits( %profile );
}
}
}
//---------------------------------------------------------------------------------------------
/// Return true if the given profile name is the default profile for a
/// GuiControl class or if it's the GuiDefaultProfile.
function GuiEditor::isDefaultProfile( %this, %name )
{
if( %name $= "GuiDefaultProfile" )
return true;
if( !endsWith( %name, "Profile" ) )
return false;
%className = getSubStr( %name, 0, strlen( %name ) - 7 ) @ "Ctrl";
if( !isClass( %className ) )
return false;
return true;
}
//---------------------------------------------------------------------------------------------
function GuiEditor::increaseNumDirtyProfiles( %this )
{
%this.numDirtyProfiles ++;
if( %this.numDirtyProfiles == 1 )
{
%tab = GuiEditorTabBook-->profilesPage;
%tab.setText( %tab.text @ " *" );
}
}
//---------------------------------------------------------------------------------------------
function GuiEditor::decreaseNumDirtyProfiles( %this )
{
%this.numDirtyProfiles --;
if( !%this.numDirtyProfiles )
{
%tab = GuiEditorTabBook-->profilesPage;
%title = %tab.text;
%title = getSubstr( %title, 0, strlen( %title ) - 2 );
%tab.setText( %title );
}
}
//=============================================================================================
// GuiEditorProfilesTree.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function GuiEditorProfilesTree::init( %this )
{
%this.clear();
%defaultGroup = %this.insertItem( 0, "Default", -1 );
%otherGroup = %this.insertItem( 0, $GUI_EDITOR_DEFAULT_PROFILE_CATEGORY, -1 );
foreach( %obj in GuiDataGroup )
{
if( !%obj.isMemberOfClass( "GuiControlProfile" ) )
continue;
// If it's an Editor profile, skip if showing them is not enabled.
if( %obj.category $= "Editor" && !GuiEditor.showEditorProfiles )
continue;
// Create a visible name.
%name = %obj.getName();
if( %name $= "" )
%name = "<Unnamed>";
%text = %name @ " (" @ %obj.getId() @ ")";
// Find which group to put the control in.
%isDefaultProfile = GuiEditor.isDefaultProfile( %name );
if( %isDefaultProfile )
%group = %defaultGroup;
else if( %obj.category !$= "" )
{
%group = %this.findChildItemByName( 0, %obj.category );
if( !%group )
%group = %this.insertItem( 0, %obj.category );
}
else
%group = %otherGroup;
// Insert the item.
%this.insertItem( %group, %text, %obj.getId(), "" );
}
%this.sort( 0, true, true, false );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfilesTree::onSelect( %this, %id )
{
%obj = %this.getItemValue( %id );
if( %obj == -1 )
return;
GuiEditorProfileInspector.inspect( %obj );
%fileName = %obj.getFileName();
if( %fileName $= "" )
%fileName = $GUI_EDITOR_DEFAULT_PROFILE_FILENAME;
GuiEditorProfileFileName.setText( %fileName );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfilesTree::onUnselect( %this, %id )
{
GuiEditorProfileInspector.inspect( 0 );
GuiEditorProfileFileName.setText( "" );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfilesTree::onProfileRenamed( %this, %profile, %newName )
{
%item = %this.findItemByValue( %profile.getId() );
if( %item == -1 )
return;
%newText = %newName @ " (" @ %profile.getId() @ ")";
if( GuiEditor.isProfileDirty( %profile ) )
%newText = %newText @ " *";
%this.editItem( %item, %newText, %profile.getId() );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfilesTree::getSelectedProfile( %this )
{
return %this.getItemValue( %this.getSelectedItem() );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfilesTree::setSelectedProfile( %this, %profile )
{
%id = %this.findItemByValue( %profile.getId() );
%this.selectItem( %id );
}
//=============================================================================================
// GuiEditorProfileInspector.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc )
{
GuiEditorProfileFieldInfo.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onFieldAdded( %this, %object, %fieldName )
{
GuiEditor.setProfileDirty( %object, true );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onFieldRemoved( %this, %object, %fieldName )
{
GuiEditor.setProfileDirty( %object, true );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onFieldRenamed( %this, %object, %oldFieldName, %newFieldName )
{
GuiEditor.setProfileDirty( %object, true );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue )
{
GuiEditor.setProfileDirty( %object, true );
// If it's the name field, make sure to sync up the treeview.
if( %fieldName $= "name" )
GuiEditorProfilesTree.onProfileRenamed( %object, %newValue );
// Add change record.
GuiEditorProfileChangeManager.registerEdit( %object, %fieldName, %arrayIndex, %oldValue );
// Add undo.
pushInstantGroup();
%nameOrClass = %object.getName();
if ( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%action = new InspectorFieldUndoAction()
{
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %oldValue;
arrayIndex = %arrayIndex;
inspectorGui = %this;
};
popInstantGroup();
%action.addToManager( GuiEditor.getUndoManager() );
GuiEditor.updateUndoMenu();
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onInspectorPreFieldModification( %this, %fieldName, %arrayIndex )
{
pushInstantGroup();
%undoManager = GuiEditor.getUndoManager();
%object = %this.getInspectObject();
%nameOrClass = %object.getName();
if( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%action = new InspectorFieldUndoAction()
{
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %object.getFieldValue( %fieldName, %arrayIndex );
arrayIndex = %arrayIndex;
inspectorGui = %this;
};
%this.currentFieldEditAction = %action;
popInstantGroup();
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onInspectorPostFieldModification( %this )
{
%action = %this.currentFieldEditAction;
%object = %action.objectId;
%fieldName = %action.fieldName;
%arrayIndex = %action.arrayIndex;
%oldValue = %action.fieldValue;
%newValue = %object.getFieldValue( %fieldName, %arrayIndex );
// If it's the name field, make sure to sync up the treeview.
if( %action.fieldName $= "name" )
GuiEditorProfilesTree.onProfileRenamed( %object, %newValue );
// Add change record.
GuiEditorProfileChangeManager.registerEdit( %object, %fieldName, %arrayIndex, %oldValue );
%this.currentFieldEditAction.addToManager( GuiEditor.getUndoManager() );
%this.currentFieldEditAction = "";
GuiEditor.updateUndoMenu();
GuiEditor.setProfileDirty( %object, true );
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileInspector::onInspectorDiscardFieldModification( %this )
{
%this.currentFieldEditAction.undo();
%this.currentFieldEditAction.delete();
%this.currentFieldEditAction = "";
}
//=============================================================================================
// GuiEditorProfileChangeManager.
//=============================================================================================
//---------------------------------------------------------------------------------------------
function GuiEditorProfileChangeManager::registerEdit( %this, %profile, %fieldName, %arrayIndex, %oldValue )
{
// Early-out if we already have a registered edit on the same field.
foreach( %obj in %this )
{
if( %obj.profile != %profile )
continue;
if( %obj.fieldName $= %fieldName
&& %obj.arrayIndex $= %arrayIndex )
return;
}
// Create a new change record.
new ScriptObject()
{
parentGroup = %this;
profile = %profile;
fieldName = %fieldName;
arrayIndex = %arrayIndex;
oldValue = %oldValue;
};
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileChangeManager::clearEdits( %this, %profile )
{
for( %i = 0; %i < %this.getCount(); %i ++ )
{
%obj = %this.getObject( %i );
if( %obj.profile != %profile )
continue;
%obj.delete();
%i --;
}
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileChangeManager::revertEdits( %this, %profile )
{
for( %i = 0; %i < %this.getCount(); %i ++ )
{
%obj = %this.getObject( %i );
if( %obj.profile != %profile )
continue;
%profile.setFieldValue( %obj.fieldName, %obj.oldValue, %obj.arrayIndex );
%obj.delete();
%i --;
}
}
//---------------------------------------------------------------------------------------------
function GuiEditorProfileChangeManager::getEdits( %this, %profile )
{
%set = new SimSet();
foreach( %obj in %this )
if( %obj.profile == %profile )
%set.add( %obj );
return %set;
}
| |
namespace KryptonCheckSetExamples
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.buttonClose = new System.Windows.Forms.Button();
this.groupBoxSparkle = new System.Windows.Forms.GroupBox();
this.thetaSparkle = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.gammaSparkle = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.betaSparkle = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.alphaSparkle = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.groupBoxBlue = new System.Windows.Forms.GroupBox();
this.thetaSystem = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.gammaSystem = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.betaSystem = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.alphaSystem = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.kryptonCheckSetOffice = new ComponentFactory.Krypton.Toolkit.KryptonCheckSet(this.components);
this.kryptonCheckSetSystem = new ComponentFactory.Krypton.Toolkit.KryptonCheckSet(this.components);
this.groupBoxCustom = new System.Windows.Forms.GroupBox();
this.forwardCheckButton = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.playCheckButton = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.rewindCheckButton = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.pauseCheckButton = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.kryptonCheckSetCustom = new ComponentFactory.Krypton.Toolkit.KryptonCheckSet(this.components);
this.groupBoxSparkle.SuspendLayout();
this.groupBoxBlue.SuspendLayout();
this.groupBoxCustom.SuspendLayout();
this.SuspendLayout();
//
// buttonClose
//
this.buttonClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonClose.Location = new System.Drawing.Point(263, 304);
this.buttonClose.Name = "buttonClose";
this.buttonClose.Size = new System.Drawing.Size(75, 23);
this.buttonClose.TabIndex = 3;
this.buttonClose.Text = "&Close";
this.buttonClose.UseVisualStyleBackColor = true;
this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
//
// groupBoxSparkle
//
this.groupBoxSparkle.Controls.Add(this.thetaSparkle);
this.groupBoxSparkle.Controls.Add(this.gammaSparkle);
this.groupBoxSparkle.Controls.Add(this.betaSparkle);
this.groupBoxSparkle.Controls.Add(this.alphaSparkle);
this.groupBoxSparkle.Location = new System.Drawing.Point(12, 12);
this.groupBoxSparkle.Name = "groupBoxSparkle";
this.groupBoxSparkle.Size = new System.Drawing.Size(326, 74);
this.groupBoxSparkle.TabIndex = 0;
this.groupBoxSparkle.TabStop = false;
this.groupBoxSparkle.Text = "Sparkle - Blue";
//
// thetaSparkle
//
this.thetaSparkle.Location = new System.Drawing.Point(241, 30);
this.thetaSparkle.Name = "thetaSparkle";
this.thetaSparkle.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.SparkleBlue;
this.thetaSparkle.Size = new System.Drawing.Size(69, 25);
this.thetaSparkle.TabIndex = 3;
this.thetaSparkle.Values.Text = "Theta";
//
// gammaSparkle
//
this.gammaSparkle.Location = new System.Drawing.Point(166, 30);
this.gammaSparkle.Name = "gammaSparkle";
this.gammaSparkle.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.SparkleBlue;
this.gammaSparkle.Size = new System.Drawing.Size(69, 25);
this.gammaSparkle.TabIndex = 2;
this.gammaSparkle.Values.Text = "Gamma";
//
// betaSparkle
//
this.betaSparkle.Location = new System.Drawing.Point(91, 30);
this.betaSparkle.Name = "betaSparkle";
this.betaSparkle.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.SparkleBlue;
this.betaSparkle.Size = new System.Drawing.Size(69, 25);
this.betaSparkle.TabIndex = 1;
this.betaSparkle.Values.Text = "Beta";
this.betaSparkle.Click += new System.EventHandler(this.betaOffice_Click);
//
// alphaSparkle
//
this.alphaSparkle.Checked = true;
this.alphaSparkle.Location = new System.Drawing.Point(16, 30);
this.alphaSparkle.Name = "alphaSparkle";
this.alphaSparkle.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.SparkleBlue;
this.alphaSparkle.Size = new System.Drawing.Size(69, 25);
this.alphaSparkle.TabIndex = 0;
this.alphaSparkle.Values.Text = "Alpha";
//
// groupBoxBlue
//
this.groupBoxBlue.Controls.Add(this.thetaSystem);
this.groupBoxBlue.Controls.Add(this.gammaSystem);
this.groupBoxBlue.Controls.Add(this.betaSystem);
this.groupBoxBlue.Controls.Add(this.alphaSystem);
this.groupBoxBlue.Location = new System.Drawing.Point(12, 92);
this.groupBoxBlue.Name = "groupBoxBlue";
this.groupBoxBlue.Size = new System.Drawing.Size(326, 74);
this.groupBoxBlue.TabIndex = 1;
this.groupBoxBlue.TabStop = false;
this.groupBoxBlue.Text = "Office 2007 - Blue";
//
// thetaSystem
//
this.thetaSystem.AutoSize = true;
this.thetaSystem.Location = new System.Drawing.Point(241, 31);
this.thetaSystem.Name = "thetaSystem";
this.thetaSystem.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Office2007Blue;
this.thetaSystem.Size = new System.Drawing.Size(69, 27);
this.thetaSystem.TabIndex = 3;
this.thetaSystem.Values.Text = "Theta";
//
// gammaSystem
//
this.gammaSystem.AutoSize = true;
this.gammaSystem.Location = new System.Drawing.Point(166, 31);
this.gammaSystem.Name = "gammaSystem";
this.gammaSystem.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Office2007Blue;
this.gammaSystem.Size = new System.Drawing.Size(69, 27);
this.gammaSystem.TabIndex = 2;
this.gammaSystem.Values.Text = "Gamma";
//
// betaSystem
//
this.betaSystem.AutoSize = true;
this.betaSystem.Location = new System.Drawing.Point(91, 31);
this.betaSystem.Name = "betaSystem";
this.betaSystem.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Office2007Blue;
this.betaSystem.Size = new System.Drawing.Size(69, 27);
this.betaSystem.TabIndex = 1;
this.betaSystem.Values.Text = "Beta";
//
// alphaSystem
//
this.alphaSystem.AutoSize = true;
this.alphaSystem.Checked = true;
this.alphaSystem.Location = new System.Drawing.Point(16, 31);
this.alphaSystem.Name = "alphaSystem";
this.alphaSystem.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Office2007Blue;
this.alphaSystem.Size = new System.Drawing.Size(69, 27);
this.alphaSystem.TabIndex = 0;
this.alphaSystem.Values.Text = "Alpha";
//
// kryptonCheckSetOffice
//
this.kryptonCheckSetOffice.CheckButtons.Add(this.thetaSparkle);
this.kryptonCheckSetOffice.CheckButtons.Add(this.gammaSparkle);
this.kryptonCheckSetOffice.CheckButtons.Add(this.betaSparkle);
this.kryptonCheckSetOffice.CheckButtons.Add(this.alphaSparkle);
this.kryptonCheckSetOffice.CheckedButton = this.alphaSparkle;
//
// kryptonCheckSetSystem
//
this.kryptonCheckSetSystem.CheckButtons.Add(this.thetaSystem);
this.kryptonCheckSetSystem.CheckButtons.Add(this.gammaSystem);
this.kryptonCheckSetSystem.CheckButtons.Add(this.betaSystem);
this.kryptonCheckSetSystem.CheckButtons.Add(this.alphaSystem);
this.kryptonCheckSetSystem.CheckedButton = this.alphaSystem;
//
// groupBoxCustom
//
this.groupBoxCustom.Controls.Add(this.forwardCheckButton);
this.groupBoxCustom.Controls.Add(this.playCheckButton);
this.groupBoxCustom.Controls.Add(this.rewindCheckButton);
this.groupBoxCustom.Controls.Add(this.pauseCheckButton);
this.groupBoxCustom.Location = new System.Drawing.Point(12, 172);
this.groupBoxCustom.Name = "groupBoxCustom";
this.groupBoxCustom.Size = new System.Drawing.Size(326, 123);
this.groupBoxCustom.TabIndex = 2;
this.groupBoxCustom.TabStop = false;
this.groupBoxCustom.Text = "Custom Settings";
//
// forwardCheckButton
//
this.forwardCheckButton.AutoSize = true;
this.forwardCheckButton.Location = new System.Drawing.Point(228, 30);
this.forwardCheckButton.Name = "forwardCheckButton";
this.forwardCheckButton.Size = new System.Drawing.Size(61, 75);
this.forwardCheckButton.StateCheckedNormal.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.forwardCheckButton.StateCheckedPressed.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.forwardCheckButton.StateCheckedTracking.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.forwardCheckButton.StateCommon.Back.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.forwardCheckButton.StateCommon.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.forwardCheckButton.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.forwardCheckButton.StateCommon.Content.Padding = new System.Windows.Forms.Padding(2);
this.forwardCheckButton.StateCommon.Content.ShortText.TextV = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Far;
this.forwardCheckButton.StatePressed.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.forwardCheckButton.TabIndex = 3;
this.forwardCheckButton.Values.Image = ((System.Drawing.Image)(resources.GetObject("forwardCheckButton.Values.Image")));
this.forwardCheckButton.Values.ImageStates.ImageCheckedNormal = ((System.Drawing.Image)(resources.GetObject("forwardCheckButton.Values.ImageStates.ImageCheckedNormal")));
this.forwardCheckButton.Values.ImageStates.ImageCheckedPressed = ((System.Drawing.Image)(resources.GetObject("forwardCheckButton.Values.ImageStates.ImageCheckedPressed")));
this.forwardCheckButton.Values.ImageStates.ImageCheckedTracking = ((System.Drawing.Image)(resources.GetObject("forwardCheckButton.Values.ImageStates.ImageCheckedTracking")));
this.forwardCheckButton.Values.ImageStates.ImagePressed = ((System.Drawing.Image)(resources.GetObject("forwardCheckButton.Values.ImageStates.ImagePressed")));
this.forwardCheckButton.Values.ImageStates.ImageTracking = ((System.Drawing.Image)(resources.GetObject("forwardCheckButton.Values.ImageStates.ImageTracking")));
this.forwardCheckButton.Values.Text = "Forward";
//
// playCheckButton
//
this.playCheckButton.AutoSize = true;
this.playCheckButton.Checked = true;
this.playCheckButton.Location = new System.Drawing.Point(168, 30);
this.playCheckButton.Name = "playCheckButton";
this.playCheckButton.Size = new System.Drawing.Size(60, 77);
this.playCheckButton.StateCheckedNormal.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.playCheckButton.StateCheckedPressed.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.playCheckButton.StateCheckedTracking.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.playCheckButton.StateCommon.Back.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.playCheckButton.StateCommon.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.playCheckButton.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.playCheckButton.StateCommon.Content.Padding = new System.Windows.Forms.Padding(2);
this.playCheckButton.StateCommon.Content.ShortText.TextV = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Far;
this.playCheckButton.StatePressed.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.playCheckButton.TabIndex = 2;
this.playCheckButton.Values.Image = ((System.Drawing.Image)(resources.GetObject("playCheckButton.Values.Image")));
this.playCheckButton.Values.ImageStates.ImageCheckedNormal = ((System.Drawing.Image)(resources.GetObject("playCheckButton.Values.ImageStates.ImageCheckedNormal")));
this.playCheckButton.Values.ImageStates.ImageCheckedPressed = ((System.Drawing.Image)(resources.GetObject("playCheckButton.Values.ImageStates.ImageCheckedPressed")));
this.playCheckButton.Values.ImageStates.ImageCheckedTracking = ((System.Drawing.Image)(resources.GetObject("playCheckButton.Values.ImageStates.ImageCheckedTracking")));
this.playCheckButton.Values.ImageStates.ImagePressed = ((System.Drawing.Image)(resources.GetObject("playCheckButton.Values.ImageStates.ImagePressed")));
this.playCheckButton.Values.ImageStates.ImageTracking = ((System.Drawing.Image)(resources.GetObject("playCheckButton.Values.ImageStates.ImageTracking")));
this.playCheckButton.Values.Text = "Play";
//
// rewindCheckButton
//
this.rewindCheckButton.AutoSize = true;
this.rewindCheckButton.Location = new System.Drawing.Point(52, 30);
this.rewindCheckButton.Name = "rewindCheckButton";
this.rewindCheckButton.Size = new System.Drawing.Size(58, 75);
this.rewindCheckButton.StateCheckedNormal.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.rewindCheckButton.StateCheckedPressed.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.rewindCheckButton.StateCheckedTracking.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.rewindCheckButton.StateCommon.Back.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.rewindCheckButton.StateCommon.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.rewindCheckButton.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.rewindCheckButton.StateCommon.Content.Padding = new System.Windows.Forms.Padding(2);
this.rewindCheckButton.StateCommon.Content.ShortText.TextV = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Far;
this.rewindCheckButton.StatePressed.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.rewindCheckButton.TabIndex = 0;
this.rewindCheckButton.Values.Image = ((System.Drawing.Image)(resources.GetObject("rewindCheckButton.Values.Image")));
this.rewindCheckButton.Values.ImageStates.ImageCheckedNormal = ((System.Drawing.Image)(resources.GetObject("rewindCheckButton.Values.ImageStates.ImageCheckedNormal")));
this.rewindCheckButton.Values.ImageStates.ImageCheckedPressed = ((System.Drawing.Image)(resources.GetObject("rewindCheckButton.Values.ImageStates.ImageCheckedPressed")));
this.rewindCheckButton.Values.ImageStates.ImageCheckedTracking = ((System.Drawing.Image)(resources.GetObject("rewindCheckButton.Values.ImageStates.ImageCheckedTracking")));
this.rewindCheckButton.Values.ImageStates.ImagePressed = ((System.Drawing.Image)(resources.GetObject("rewindCheckButton.Values.ImageStates.ImagePressed")));
this.rewindCheckButton.Values.ImageStates.ImageTracking = ((System.Drawing.Image)(resources.GetObject("rewindCheckButton.Values.ImageStates.ImageTracking")));
this.rewindCheckButton.Values.Text = "Rewind";
//
// pauseCheckButton
//
this.pauseCheckButton.AutoSize = true;
this.pauseCheckButton.Location = new System.Drawing.Point(110, 30);
this.pauseCheckButton.Name = "pauseCheckButton";
this.pauseCheckButton.Size = new System.Drawing.Size(58, 75);
this.pauseCheckButton.StateCheckedNormal.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.pauseCheckButton.StateCheckedPressed.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.pauseCheckButton.StateCheckedTracking.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.pauseCheckButton.StateCommon.Back.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.pauseCheckButton.StateCommon.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.pauseCheckButton.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.pauseCheckButton.StateCommon.Content.Padding = new System.Windows.Forms.Padding(2);
this.pauseCheckButton.StateCommon.Content.ShortText.TextV = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Far;
this.pauseCheckButton.StatePressed.Content.Padding = new System.Windows.Forms.Padding(4, 4, 2, 2);
this.pauseCheckButton.TabIndex = 1;
this.pauseCheckButton.Values.Image = ((System.Drawing.Image)(resources.GetObject("pauseCheckButton.Values.Image")));
this.pauseCheckButton.Values.ImageStates.ImageCheckedNormal = ((System.Drawing.Image)(resources.GetObject("pauseCheckButton.Values.ImageStates.ImageCheckedNormal")));
this.pauseCheckButton.Values.ImageStates.ImageCheckedPressed = ((System.Drawing.Image)(resources.GetObject("pauseCheckButton.Values.ImageStates.ImageCheckedPressed")));
this.pauseCheckButton.Values.ImageStates.ImageCheckedTracking = ((System.Drawing.Image)(resources.GetObject("pauseCheckButton.Values.ImageStates.ImageCheckedTracking")));
this.pauseCheckButton.Values.ImageStates.ImagePressed = ((System.Drawing.Image)(resources.GetObject("pauseCheckButton.Values.ImageStates.ImagePressed")));
this.pauseCheckButton.Values.ImageStates.ImageTracking = ((System.Drawing.Image)(resources.GetObject("pauseCheckButton.Values.ImageStates.ImageTracking")));
this.pauseCheckButton.Values.Text = "Pause";
//
// kryptonCheckSetCustom
//
this.kryptonCheckSetCustom.CheckButtons.Add(this.forwardCheckButton);
this.kryptonCheckSetCustom.CheckButtons.Add(this.playCheckButton);
this.kryptonCheckSetCustom.CheckButtons.Add(this.rewindCheckButton);
this.kryptonCheckSetCustom.CheckButtons.Add(this.pauseCheckButton);
this.kryptonCheckSetCustom.CheckedButton = this.playCheckButton;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(350, 336);
this.Controls.Add(this.groupBoxCustom);
this.Controls.Add(this.groupBoxBlue);
this.Controls.Add(this.groupBoxSparkle);
this.Controls.Add(this.buttonClose);
this.Font = new System.Drawing.Font("Tahoma", 8.25F);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.Text = "KryptonCheckSet Examples";
this.groupBoxSparkle.ResumeLayout(false);
this.groupBoxBlue.ResumeLayout(false);
this.groupBoxBlue.PerformLayout();
this.groupBoxCustom.ResumeLayout(false);
this.groupBoxCustom.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button buttonClose;
private System.Windows.Forms.GroupBox groupBoxSparkle;
private System.Windows.Forms.GroupBox groupBoxBlue;
private System.Windows.Forms.GroupBox groupBoxCustom;
private ComponentFactory.Krypton.Toolkit.KryptonCheckSet kryptonCheckSetOffice;
private ComponentFactory.Krypton.Toolkit.KryptonCheckSet kryptonCheckSetSystem;
private ComponentFactory.Krypton.Toolkit.KryptonCheckSet kryptonCheckSetCustom;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton thetaSparkle;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton gammaSparkle;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton betaSparkle;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton alphaSparkle;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton thetaSystem;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton gammaSystem;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton betaSystem;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton alphaSystem;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton forwardCheckButton;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton playCheckButton;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton rewindCheckButton;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton pauseCheckButton;
}
}
| |
using System;
using System.Reflection;
using JetBrains.Annotations;
using log4net;
namespace OpenMLTD.MilliSim.Core {
[UsedImplicitly]
public sealed class GameLog {
private GameLog([NotNull] Assembly assembly, [NotNull] string name) {
_log = LogManager.GetLogger(assembly, name);
}
public static void Initialize([NotNull] string loggerName) {
Initialize(Assembly.GetEntryAssembly(), loggerName);
}
public static void Initialize([NotNull] Assembly assembly, [NotNull] string loggerName) {
if (_isInitialized) {
return;
}
_isInitialized = true;
_instance = new GameLog(assembly, loggerName);
}
public static bool Enabled { get; set; }
#region log:debug
public static void Debug([NotNull] string message) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsDebugEnabled) {
log.Debug(message);
}
}
public static void Debug(object message) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsDebugEnabled) {
log.Debug(message);
}
}
public static void Debug(object message, Exception exception) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsDebugEnabled) {
log.Debug(message, exception);
}
}
[StringFormatMethod("format")]
public static void Debug([NotNull] string format, object arg0) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsDebugEnabled) {
log.DebugFormat(format, arg0);
}
}
[StringFormatMethod("format")]
public static void Debug([NotNull] string format, object arg0, object arg1) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsDebugEnabled) {
log.DebugFormat(format, arg0, arg1);
}
}
[StringFormatMethod("format")]
public static void Debug([NotNull] string format, object arg0, object arg1, object arg2) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsDebugEnabled) {
log.DebugFormat(format, arg0, arg1, arg2);
}
}
[StringFormatMethod("format")]
public static void Debug([NotNull] string format, params object[] args) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsDebugEnabled) {
log.DebugFormat(format, args);
}
}
[StringFormatMethod("format")]
public static void Debug([NotNull] IFormatProvider formatProvider, string format, params object[] args) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsDebugEnabled) {
log.DebugFormat(formatProvider, format, args);
}
}
#endregion
#region log:info
public static void Info([NotNull] string message) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsInfoEnabled) {
log.Info(message);
}
}
public static void Info(object message) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsInfoEnabled) {
log.Info(message);
}
}
public static void Info(object message, Exception exception) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsInfoEnabled) {
log.Info(message, exception);
}
}
[StringFormatMethod("format")]
public static void Info([NotNull] string format, object arg0) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsInfoEnabled) {
log.InfoFormat(format, arg0);
}
}
[StringFormatMethod("format")]
public static void Info([NotNull] string format, object arg0, object arg1) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsInfoEnabled) {
log.InfoFormat(format, arg0, arg1);
}
}
[StringFormatMethod("format")]
public static void Info([NotNull] string format, object arg0, object arg1, object arg2) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsInfoEnabled) {
log.InfoFormat(format, arg0, arg1, arg2);
}
}
[StringFormatMethod("format")]
public static void Info([NotNull] string format, params object[] args) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsInfoEnabled) {
log.InfoFormat(format, args);
}
}
[StringFormatMethod("format")]
public static void Info([NotNull] IFormatProvider formatProvider, string format, params object[] args) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsInfoEnabled) {
log.InfoFormat(formatProvider, format, args);
}
}
#endregion
#region log:warn
public static void Warn([NotNull] string message) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsWarnEnabled) {
log.Warn(message);
}
}
public static void Warn(object message) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsWarnEnabled) {
log.Warn(message);
}
}
public static void Warn(object message, Exception exception) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsWarnEnabled) {
log.Warn(message, exception);
}
}
[StringFormatMethod("format")]
public static void Warn([NotNull] string format, object arg0) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsWarnEnabled) {
log.WarnFormat(format, arg0);
}
}
[StringFormatMethod("format")]
public static void Warn([NotNull] string format, object arg0, object arg1) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsWarnEnabled) {
log.WarnFormat(format, arg0, arg1);
}
}
[StringFormatMethod("format")]
public static void Warn([NotNull] string format, object arg0, object arg1, object arg2) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsWarnEnabled) {
log.WarnFormat(format, arg0, arg1, arg2);
}
}
[StringFormatMethod("format")]
public static void Warn([NotNull] string format, params object[] args) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsWarnEnabled) {
log.WarnFormat(format, args);
}
}
[StringFormatMethod("format")]
public static void Warn([NotNull] IFormatProvider formatProvider, string format, params object[] args) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsWarnEnabled) {
log.WarnFormat(formatProvider, format, args);
}
}
#endregion
#region log:error
public static void Error([NotNull] string message) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsErrorEnabled) {
log.Error(message);
}
}
public static void Error(object message) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsErrorEnabled) {
log.Error(message);
}
}
public static void Error(object message, Exception exception) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsErrorEnabled) {
log.Error(message, exception);
}
}
[StringFormatMethod("format")]
public static void Error([NotNull] string format, object arg0) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsErrorEnabled) {
log.ErrorFormat(format, arg0);
}
}
[StringFormatMethod("format")]
public static void Error([NotNull] string format, object arg0, object arg1) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsErrorEnabled) {
log.ErrorFormat(format, arg0, arg1);
}
}
[StringFormatMethod("format")]
public static void Error([NotNull] string format, object arg0, object arg1, object arg2) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsErrorEnabled) {
log.ErrorFormat(format, arg0, arg1, arg2);
}
}
[StringFormatMethod("format")]
public static void Error([NotNull] string format, params object[] args) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsErrorEnabled) {
log.ErrorFormat(format, args);
}
}
[StringFormatMethod("format")]
public static void Error([NotNull] IFormatProvider formatProvider, string format, params object[] args) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsErrorEnabled) {
log.ErrorFormat(formatProvider, format, args);
}
}
#endregion
#region log:fatal
public static void Fatal([NotNull] string message) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsFatalEnabled) {
log.Fatal(message);
}
}
public static void Fatal(object message) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsFatalEnabled) {
log.Fatal(message);
}
}
public static void Fatal(object message, Exception exception) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsFatalEnabled) {
log.Fatal(message, exception);
}
}
[StringFormatMethod("format")]
public static void Fatal([NotNull] string format, object arg0) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsFatalEnabled) {
log.FatalFormat(format, arg0);
}
}
[StringFormatMethod("format")]
public static void Fatal([NotNull] string format, object arg0, object arg1) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsFatalEnabled) {
log.FatalFormat(format, arg0, arg1);
}
}
[StringFormatMethod("format")]
public static void Fatal([NotNull] string format, object arg0, object arg1, object arg2) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsFatalEnabled) {
log.FatalFormat(format, arg0, arg1, arg2);
}
}
[StringFormatMethod("format")]
public static void Fatal([NotNull] string format, params object[] args) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsFatalEnabled) {
log.FatalFormat(format, args);
}
}
[StringFormatMethod("format")]
public static void Fatal([NotNull] IFormatProvider formatProvider, string format, params object[] args) {
if (!Enabled || _instance == null) {
return;
}
var log = _instance._log;
if (log == null) {
return;
}
if (log.IsFatalEnabled) {
log.FatalFormat(formatProvider, format, args);
}
}
#endregion
private static GameLog _instance;
private static bool _isInitialized;
private readonly ILog _log;
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
namespace DotSpatial.Serialization
{
/// <summary>
/// BaseCollection.
/// </summary>
/// <typeparam name="T">Type of the items in the collection.</typeparam>
public class BaseCollection<T> : ICollection<T>
where T : class
{
#region Fields
/// <summary>
/// Private storage for the inner list.
/// </summary>
private List<T> _innerList;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="BaseCollection{T}"/> class.
/// </summary>
public BaseCollection()
{
_innerList = new List<T>();
}
#endregion
#region Properties
/// <summary>
/// Gets the count of the inner list.
/// </summary>
public int Count => InnerList.Count;
/// <summary>
/// Gets a value indicating whether this is readonly.
/// </summary>
public bool IsReadOnly => false;
/// <summary>
/// Gets or sets the inner list of T that actually controls the content for this BaseCollection.
/// </summary>
[Serialize("InnerList")]
protected List<T> InnerList
{
get
{
return _innerList;
}
set
{
if (_innerList != null && _innerList.Count > 0)
{
foreach (T item in _innerList)
{
OnExclude(item);
}
}
_innerList = value;
foreach (T item in _innerList)
{
OnInclude(item);
}
OnInnerListSet();
}
}
#endregion
#region Methods
/// <summary>
/// Adds an item to this base collection.
/// </summary>
/// <param name="item">Item that gets added.</param>
public void Add(T item)
{
Include(item);
InnerList.Add(item);
OnIncludeComplete(item);
OnInsert(InnerList.IndexOf(item), item);
}
/// <summary>
/// Clears the list.
/// </summary>
public void Clear()
{
OnClear();
}
/// <summary>
/// A boolean that is true if this set contains the specified item.
/// </summary>
/// <param name="item">Item that gets checked.</param>
/// <returns>True, if the item is contained.</returns>
public bool Contains(T item)
{
return InnerList.Contains(item);
}
/// <summary>
/// Copies the items from this collection to the specified array.
/// </summary>
/// <param name="array">The array to copy to.</param>
/// <param name="arrayIndex">The zero based integer array index to start copying to.</param>
public void CopyTo(T[] array, int arrayIndex)
{
InnerList.CopyTo(array, arrayIndex);
}
/// <summary>
/// Returns a type specific enumerator.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<T> GetEnumerator()
{
return InnerList.GetEnumerator();
}
/// <summary>
/// Moves the given item to the new position.
/// </summary>
/// <param name="item">Item that gets moved.</param>
/// <param name="newPosition">Position the item is moved to.</param>
public void Move(T item, int newPosition)
{
if (!InnerList.Contains(item)) return;
int index = InnerList.IndexOf(item);
if (index == newPosition) return;
InnerList.RemoveAt(index);
if (InnerList.Count <= newPosition)
{
// position past list end
InnerList.Add(item);
}
else if (newPosition < 0)
{
// position before list start
InnerList.Insert(0, item);
}
else
{
InnerList.Insert(newPosition, item);
}
// position inside list
OnMoved(item, InnerList.IndexOf(item));
}
/// <summary>
/// Removes the specified item from the collection.
/// </summary>
/// <param name="item">The item to remove from the collection.</param>
/// <returns>Boolean, true if the remove operation is successful. </returns>
public bool Remove(T item)
{
if (InnerList.Contains(item))
{
int index = InnerList.IndexOf(item);
InnerList.Remove(item);
// Removed "Exclude(item) because calling OnRemoveComplete
OnRemoveComplete(index, item);
return true;
}
return false;
}
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns>The enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return InnerList.GetEnumerator();
}
/// <summary>
/// Exclude should be called AFTER the item is successfully removed from the list.
/// This allows any handlers that connect to the item to be removed in the event
/// that the item is no longer anywhere in the list.
/// </summary>
/// <param name="item">The item to be removed.</param>
protected void Exclude(T item)
{
if (!InnerList.Contains(item))
{
OnExclude(item);
}
}
/// <summary>
/// Includes the specified item. This should be called BEFORE an item
/// is added to the list.
/// </summary>
/// <param name="item">Item to be included.</param>
protected void Include(T item)
{
if (!InnerList.Contains(item))
{
OnInclude(item);
}
}
/// <summary>
/// Clears this collection.
/// </summary>
protected virtual void OnClear()
{
List<T> deleteList = new List<T>();
foreach (T item in InnerList)
{
deleteList.Add(item);
}
foreach (T item in deleteList)
{
Remove(item);
}
}
/// <summary>
/// Occurs any time an item is removed from the collection and no longer
/// exists anywhere in the collection.
/// </summary>
/// <param name="item">Item that gets excluded.</param>
protected virtual void OnExclude(T item)
{
}
/// <summary>
/// Occurs any time an item is added or inserted into the collection
/// and did not previously exist in the collection.
/// </summary>
/// <param name="item">Item that gets included.</param>
protected virtual void OnInclude(T item)
{
}
/// <summary>
/// Occurs after the item has been included either by set, insert, or addition.
/// </summary>
/// <param name="item">Item that was included.</param>
protected virtual void OnIncludeComplete(T item)
{
}
/// <summary>
/// After serialization, the inner list is directly set. This is uzed by the FeatureLayer, for instance,
/// to apply the new scheme.
/// </summary>
protected virtual void OnInnerListSet()
{
}
/// <summary>
/// Occurs when items are inserted.
/// </summary>
/// <param name="index">Index where the item should be inserted.</param>
/// <param name="value">Item that should be inserted.</param>
protected virtual void OnInsert(int index, object value)
{
T item = value as T;
Include(item);
}
/// <summary>
/// Occurs after a new item has been inserted, and fires IncludeComplete.
/// </summary>
/// <param name="index">Index where the item should be inserted.</param>
/// <param name="value">Item that should be inserted.</param>
protected virtual void OnInsertComplete(int index, object value)
{
T item = value as T;
OnIncludeComplete(item);
}
/// <summary>
/// Occurs whenever a layer is moved.
/// </summary>
/// <param name="item">Layer that is moved.</param>
/// <param name="newPosition">Position the layer is moved to.</param>
protected virtual void OnMoved(T item, int newPosition)
{
}
/// <summary>
/// Fires after the remove operation, ensuring that OnExclude gets called.
/// </summary>
/// <param name="index">Index where the item should be removed.</param>
/// <param name="value">Item that should be removed.</param>
protected virtual void OnRemoveComplete(int index, object value)
{
T item = value as T;
Exclude(item);
}
/// <summary>
/// Fires before the set operation ensuring the new item is included if necessary.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
protected virtual void OnSet(int index, object oldValue, object newValue)
{
T item = newValue as T;
Include(item);
}
/// <summary>
/// Fires after the set operation, ensuring that the item is removed.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
protected virtual void OnSetComplete(int index, object oldValue, object newValue)
{
T item = oldValue as T;
Exclude(item);
item = newValue as T;
OnIncludeComplete(item);
}
#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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal abstract class EditAndContinueTestHelpers
{
public abstract AbstractEditAndContinueAnalyzer Analyzer { get; }
public abstract SyntaxNode FindNode(SyntaxNode root, TextSpan span);
public abstract SyntaxTree ParseText(string source);
public abstract Compilation CreateLibraryCompilation(string name, IEnumerable<SyntaxTree> trees);
public abstract ImmutableArray<SyntaxNode> GetDeclarators(ISymbol method);
internal void VerifyUnchangedDocument(
string source,
ActiveStatementSpan[] oldActiveStatements,
TextSpan?[] trackingSpansOpt,
TextSpan[] expectedNewActiveStatements,
ImmutableArray<TextSpan>[] expectedOldExceptionRegions,
ImmutableArray<TextSpan>[] expectedNewExceptionRegions)
{
var text = SourceText.From(source);
var tree = ParseText(source);
var root = tree.GetRoot();
tree.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument");
TestActiveStatementTrackingService trackingService;
if (trackingSpansOpt != null)
{
trackingService = new TestActiveStatementTrackingService(documentId, trackingSpansOpt);
}
else
{
trackingService = null;
}
var actualNewActiveStatements = new LinePositionSpan[oldActiveStatements.Length];
var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length];
Analyzer.AnalyzeUnchangedDocument(
oldActiveStatements.AsImmutable(),
text,
root,
documentId,
trackingService,
actualNewActiveStatements,
actualNewExceptionRegions);
// check active statements:
AssertSpansEqual(expectedNewActiveStatements, actualNewActiveStatements, source, text);
// check new exception regions:
Assert.Equal(expectedNewExceptionRegions.Length, actualNewExceptionRegions.Length);
for (int i = 0; i < expectedNewExceptionRegions.Length; i++)
{
AssertSpansEqual(expectedNewExceptionRegions[i], actualNewExceptionRegions[i], source, text);
}
}
internal void VerifyRudeDiagnostics(
EditScript<SyntaxNode> editScript,
ActiveStatementsDescription description,
RudeEditDiagnosticDescription[] expectedDiagnostics)
{
var oldActiveStatements = description.OldSpans;
if (description.TrackingSpans != null)
{
Assert.Equal(oldActiveStatements.Length, description.TrackingSpans.Length);
}
string newSource = editScript.Match.NewRoot.SyntaxTree.ToString();
string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString();
var oldText = SourceText.From(oldSource);
var newText = SourceText.From(newSource);
var diagnostics = new List<RudeEditDiagnostic>();
var actualNewActiveStatements = new LinePositionSpan[oldActiveStatements.Length];
var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length];
var updatedActiveMethodMatches = new List<ValueTuple<int, IReadOnlyDictionary<SyntaxNode, SyntaxNode>>>();
var editMap = Analyzer.BuildEditMap(editScript);
DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument");
TestActiveStatementTrackingService trackingService;
if (description.TrackingSpans != null)
{
trackingService = new TestActiveStatementTrackingService(documentId, description.TrackingSpans);
}
else
{
trackingService = null;
}
Analyzer.AnalyzeSyntax(
editScript,
editMap,
oldText,
newText,
documentId,
trackingService,
oldActiveStatements.AsImmutable(),
actualNewActiveStatements,
actualNewExceptionRegions,
updatedActiveMethodMatches,
diagnostics);
diagnostics.Verify(newSource, expectedDiagnostics);
// check active statements:
AssertSpansEqual(description.NewSpans, actualNewActiveStatements, newSource, newText);
if (diagnostics.Count == 0)
{
// check old exception regions:
for (int i = 0; i < oldActiveStatements.Length; i++)
{
var actualOldExceptionRegions = Analyzer.GetExceptionRegions(
oldText,
editScript.Match.OldRoot,
oldActiveStatements[i].Span,
isLeaf: (oldActiveStatements[i].Flags & ActiveStatementFlags.LeafFrame) != 0);
AssertSpansEqual(description.OldRegions[i], actualOldExceptionRegions, oldSource, oldText);
}
// check new exception regions:
Assert.Equal(description.NewRegions.Length, actualNewExceptionRegions.Length);
for (int i = 0; i < description.NewRegions.Length; i++)
{
AssertSpansEqual(description.NewRegions[i], actualNewExceptionRegions[i], newSource, newText);
}
}
else
{
for (int i = 0; i < oldActiveStatements.Length; i++)
{
Assert.Equal(0, description.NewRegions[i].Length);
}
}
if (description.TrackingSpans != null)
{
AssertEx.Equal(trackingService.TrackingSpans, description.NewSpans.Select(s => (TextSpan?)s));
}
}
internal void VerifyLineEdits(
EditScript<SyntaxNode> editScript,
IEnumerable<LineChange> expectedLineEdits,
IEnumerable<string> expectedNodeUpdates,
RudeEditDiagnosticDescription[] expectedDiagnostics)
{
string newSource = editScript.Match.NewRoot.SyntaxTree.ToString();
string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString();
var oldText = SourceText.From(oldSource);
var newText = SourceText.From(newSource);
var diagnostics = new List<RudeEditDiagnostic>();
var editMap = Analyzer.BuildEditMap(editScript);
var triviaEdits = new List<KeyValuePair<SyntaxNode, SyntaxNode>>();
var actualLineEdits = new List<LineChange>();
Analyzer.AnalyzeTrivia(
oldText,
newText,
editScript.Match,
editMap,
triviaEdits,
actualLineEdits,
diagnostics,
default(CancellationToken));
diagnostics.Verify(newSource, expectedDiagnostics);
AssertEx.Equal(expectedLineEdits, actualLineEdits, itemSeparator: ",\r\n");
var actualNodeUpdates = triviaEdits.Select(e => e.Value.ToString().ToLines().First());
AssertEx.Equal(expectedNodeUpdates, actualNodeUpdates, itemSeparator: ",\r\n");
}
internal void VerifySemantics(
EditScript<SyntaxNode> editScript,
ActiveStatementsDescription activeStatements,
IEnumerable<string> additionalOldSources,
IEnumerable<string> additionalNewSources,
SemanticEditDescription[] expectedSemanticEdits,
RudeEditDiagnosticDescription[] expectedDiagnostics)
{
var editMap = Analyzer.BuildEditMap(editScript);
var oldRoot = editScript.Match.OldRoot;
var newRoot = editScript.Match.NewRoot;
var oldSource = oldRoot.SyntaxTree.ToString();
var newSource = newRoot.SyntaxTree.ToString();
var oldText = SourceText.From(oldSource);
var newText = SourceText.From(newSource);
IEnumerable<SyntaxTree> oldTrees = new[] { oldRoot.SyntaxTree };
IEnumerable<SyntaxTree> newTrees = new[] { newRoot.SyntaxTree };
if (additionalOldSources != null)
{
oldTrees = oldTrees.Concat(additionalOldSources.Select(s => ParseText(s)));
}
if (additionalOldSources != null)
{
newTrees = newTrees.Concat(additionalNewSources.Select(s => ParseText(s)));
}
var oldCompilation = CreateLibraryCompilation("Old", oldTrees);
var newCompilation = CreateLibraryCompilation("New", newTrees);
oldTrees.SelectMany(tree => tree.GetDiagnostics()).Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
newTrees.SelectMany(tree => tree.GetDiagnostics()).Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
var oldModel = oldCompilation.GetSemanticModel(oldRoot.SyntaxTree);
var newModel = newCompilation.GetSemanticModel(newRoot.SyntaxTree);
var oldActiveStatements = activeStatements.OldSpans.AsImmutable();
var updatedActiveMethodMatches = new List<ValueTuple<int, IReadOnlyDictionary<SyntaxNode, SyntaxNode>>>();
var triviaEdits = new List<KeyValuePair<SyntaxNode, SyntaxNode>>();
var actualLineEdits = new List<LineChange>();
var actualSemanticEdits = new List<SemanticEdit>();
var diagnostics = new List<RudeEditDiagnostic>();
var actualNewActiveStatements = new LinePositionSpan[activeStatements.OldSpans.Length];
var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[activeStatements.OldSpans.Length];
Analyzer.AnalyzeSyntax(
editScript,
editMap,
oldText,
newText,
null,
null,
oldActiveStatements,
actualNewActiveStatements,
actualNewExceptionRegions,
updatedActiveMethodMatches,
diagnostics);
diagnostics.Verify(newSource);
Analyzer.AnalyzeTrivia(
oldText,
newText,
editScript.Match,
editMap,
triviaEdits,
actualLineEdits,
diagnostics,
default(CancellationToken));
diagnostics.Verify(newSource);
Analyzer.AnalyzeSemantics(
editScript,
editMap,
oldText,
oldActiveStatements,
triviaEdits,
updatedActiveMethodMatches,
oldModel,
newModel,
actualSemanticEdits,
diagnostics,
default(CancellationToken));
diagnostics.Verify(newSource, expectedDiagnostics);
if (expectedSemanticEdits == null)
{
return;
}
Assert.Equal(expectedSemanticEdits.Length, actualSemanticEdits.Count);
for (int i = 0; i < actualSemanticEdits.Count; i++)
{
var editKind = expectedSemanticEdits[i].Kind;
Assert.Equal(editKind, actualSemanticEdits[i].Kind);
var expectedOldSymbol = (editKind == SemanticEditKind.Update) ? expectedSemanticEdits[i].SymbolProvider(oldCompilation) : null;
var expectedNewSymbol = expectedSemanticEdits[i].SymbolProvider(newCompilation);
var actualOldSymbol = actualSemanticEdits[i].OldSymbol;
var actualNewSymbol = actualSemanticEdits[i].NewSymbol;
Assert.Equal(expectedOldSymbol, actualOldSymbol);
Assert.Equal(expectedNewSymbol, actualNewSymbol);
var expectedSyntaxMap = expectedSemanticEdits[i].SyntaxMap;
var actualSyntaxMap = actualSemanticEdits[i].SyntaxMap;
Assert.Equal(expectedSemanticEdits[i].PreserveLocalVariables, actualSemanticEdits[i].PreserveLocalVariables);
if (expectedSyntaxMap != null)
{
Assert.NotNull(actualSyntaxMap);
Assert.True(expectedSemanticEdits[i].PreserveLocalVariables);
var newNodes = new List<SyntaxNode>();
foreach (var expectedSpanMapping in expectedSyntaxMap)
{
var newNode = FindNode(newRoot, expectedSpanMapping.Value);
var expectedOldNode = FindNode(oldRoot, expectedSpanMapping.Key);
var actualOldNode = actualSyntaxMap(newNode);
Assert.Equal(expectedOldNode, actualOldNode);
newNodes.Add(newNode);
}
AssertEx.SetEqual(newNodes, GetDeclarators(actualNewSymbol));
}
else
{
Assert.Null(actualSyntaxMap);
}
}
}
private static void AssertSpansEqual(IList<TextSpan> expected, IList<LinePositionSpan> actual, string newSource, SourceText newText)
{
AssertEx.Equal(
expected,
actual.Select(span => newText.Lines.GetTextSpan(span)),
itemSeparator: "\r\n",
itemInspector: s => DisplaySpan(newSource, s));
}
private static string DisplaySpan(string source, TextSpan span)
{
return span + ": [" + source.Substring(span.Start, span.Length).Replace("\r\n", " ") + "]";
}
}
internal static class EditScriptTestUtils
{
public static void VerifyEdits<TNode>(this EditScript<TNode> actual, params string[] expected)
{
AssertEx.Equal(expected, actual.Edits.Select(e => e.GetDebuggerDisplay()), itemSeparator: ",\r\n");
}
}
}
| |
// Photo.cs
//
// Authors:
// Andrzej Wytyczak-Partyka <iapart@gmail.com>
// James Willcox <snorp@snorp.net>
//
// Copyright (C) 2008 Andrzej Wytyczak-Partyka
// Copyright (C) 2005 James Willcox <snorp@snorp.net>
//
// 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
//
//
using System;
using System.Collections;
namespace DPAP
{
public class Photo
{
private string author;
private string album;
private string title;
private int year;
private string format;
private TimeSpan duration;
private int id;
private int size;
private int width;
private int height;
private string genre;
private int photo_number;
private int photo_count;
private string filename;
private string thumbnail;
private string path;
private int thumbsize;
private DateTime date_added = DateTime.Now;
private DateTime date_modified = DateTime.Now;
private short bitrate;
public event EventHandler Updated;
public string Author {
get { return author; }
set {
author = value;
EmitUpdated ();
}
}
public string Album {
get { return album; }
set {
album = value;
EmitUpdated ();
}
}
public string Title {
get { return title; }
set {
title = value;
EmitUpdated ();
}
}
public int Year {
get { return year; }
set {
year = value;
EmitUpdated ();
}
}
public string Format {
get { return format; }
set {
format = value;
EmitUpdated ();
}
}
public TimeSpan Duration {
get { return duration; }
set {
duration = value;
EmitUpdated ();
}
}
public int Id {
get { return id; }
}
public int Size {
get { return size; }
set {
size = value;
EmitUpdated ();
}
}
public string FileName {
get { return filename; }
set {
filename = value;
EmitUpdated ();
}
}
public string Path {
get { return path; }
set {
path = value;
EmitUpdated ();
}
}
public string Thumbnail {
get { return thumbnail; }
set {
thumbnail = value;
EmitUpdated ();
}
}
public int ThumbSize {
get { return thumbsize; }
set {
thumbsize = value;
EmitUpdated ();
}
}
public int Width {
get { return width; }
set {
width = value;
EmitUpdated ();
}
}
public int Height {
get { return height; }
set {
height = value;
EmitUpdated ();
}
}
public DateTime DateAdded {
get { return date_added; }
set {
date_added = value;
EmitUpdated ();
}
}
public DateTime DateModified {
get { return date_modified; }
set {
date_modified = value;
EmitUpdated ();
}
}
public object Clone () {
Photo photo = new Photo ();
photo.author = author;
photo.album = album;
photo.title = title;
photo.year = year;
photo.format = format;
photo.duration = duration;
photo.id = id;
photo.size = size;
photo.filename = filename;
photo.thumbnail = thumbnail;
photo.thumbsize = thumbsize;
photo.date_added = date_added;
photo.date_modified = date_modified;
photo.path = path;
return photo;
}
public override string ToString () {
return String.Format ("fname={0}, title={1}, format={2}, id={3}, path={4}", filename, title, format, id, path);
}
internal void SetId (int id) {
this.id = id;
}
internal ContentNode ToFileData (bool thumb) {
ArrayList nodes = new ArrayList ();
Console.WriteLine ("Requested "+ ( (thumb)?"thumb":"file") +", thumbnail=" + thumbnail + ", hires=" + path);
nodes.Add (new ContentNode ("dmap.itemkind", (byte)3));
nodes.Add (new ContentNode ("dmap.itemid", id));
// pass the appropriate file path, depending on wether
//we are sending the thumbnail or the hi-res image
nodes.Add (new ContentNode ("dpap.filedata",
new ContentNode ("dpap.imagefilesize", (thumb)?thumbsize:size),
new ContentNode ("dpap.imagefilename", (thumb)?thumbnail:path),
new ContentNode ("dpap.imagefilename", (thumb)?thumbnail:filename)));
return (new ContentNode ("dmap.listingitem", nodes));
}
internal ContentNode ToNode (string [] fields) {
ArrayList nodes = new ArrayList ();
foreach (string field in fields) {
object val = null;
switch (field) {
case "dmap.itemid":
val = id;
break;
case "dmap.itemname":
val = title;
break;
case "dmap.itemkind":
val = (byte) 3;
break;
case "dmap.persistentid":
val = (long) id;
break;
case "dpap.photoalbum":
val = album;
break;
case "dpap.author":
val = author;
break;
case "dpap.imageformat":
val = format;
break;
case "dpap.imagefilename":
val = filename;
break;
case "dpap.imagefilesize":
val = thumbsize;
break;
case "dpap.imagelargefilesize":
val = size;
break;
/*case "dpap.aspectratio":
val = "0";
break;*/
case "dpap.creationdate":
val = 7799;
break;
case "dpap.pixelheight":
val = 0;
break;
case "dpap.pixelwidth":
val = 0;
break;
case "dpap.imagerating":
val = 0;
break;
default:
break;
}
if (val != null) {
// iTunes wants this to go first, sigh
if (field == "dmap.itemkind")
nodes.Insert (0, new ContentNode (field, val));
else
nodes.Add (new ContentNode (field, val));
}
}
return new ContentNode ("dmap.listingitem", nodes);
}
internal static Photo FromNode (ContentNode node) {
Photo photo = new Photo ();
foreach (ContentNode field in (ContentNode []) node.Value) {
switch (field.Name) {
case "dmap.itemid":
photo.id = (int) field.Value;
break;
case "dmap.itemname":
photo.title = (string) field.Value;
break;
case "dpap.imageformat":
photo.format = (string) field.Value;
break;
case "dpap.imagefilename":
photo.filename = (string) field.Value;
break;
/* case "dpap.imagefilesize":
photo.size = (int) field.Value;
break;
case "dpap.imagepixelwidth":
photo.width = (int) field.Value;
break;
case "dpap.imagepixelheight":
photo.height = (int) field.Value;
break;*/
default:
break;
}
}
return photo;
}
internal ContentNode ToAlbumNode (string [] fields) {
ArrayList nodes = new ArrayList ();
foreach (string field in fields) {
object val = null;
switch (field) {
case "dmap.itemid":
val = id;
break;
case "dmap.itemname":
val = title;
break;
case "dmap.itemkind":
val = (byte) 3;
break;
case "dmap.persistentid":
val = (long) id;
break;
case "dpap.photoalbum":
val = album;
break;
case "dpap.author":
val = author;
break;
case "dpap.imageformat":
val = format;
break;
case "dpap.imagefilename":
val = filename;
break;
case "dpap.imagefilesize":
val = thumbsize;
break;
case "dpap.imagelargefilesize":
val = size;
break;
// Apparently this has to be sent even with bogus data,
// otherwise iPhoto '08 wont show the thumbnails
case "dpap.aspectratio":
val = "1.522581";
break;
case "dpap.creationdate":
val = 7799;
break;
case "dpap.pixelheight":
val = 0;
break;
case "dpap.pixelwidth":
val = 0;
break;
case "dpap.imagerating":
val = 0;
break;
default:
break;
}
if (val != null) {
// iTunes wants this to go first, sigh
if (field == "dmap.itemkind")
nodes.Insert (0, new ContentNode (field, val));
else
nodes.Add (new ContentNode (field, val));
}
}
return new ContentNode ("dmap.listingitem",
new ContentNode ("dmap.itemkind", (byte) 3),
nodes);
/* new ContentNode ("dpap.imagefilename", filename),
new ContentNode ("dmap.itemid", Id),
//new ContentNode ("dmap.containeritemid", containerId),
new ContentNode ("dmap.itemname", Title == null ? String.Empty : Title));
*/
}
internal static void FromAlbumNode (Database db, ContentNode node, out Photo photo, out int containerId) {
photo = null;
containerId = 0;
foreach (ContentNode field in (ContentNode []) node.Value) {
switch (field.Name) {
case "dmap.itemid":
photo = db.LookupPhotoById ( (int) field.Value);
break;
case "dmap.containeritemid":
containerId = (int) field.Value;
break;
default:
break;
}
}
}
private bool Equals (Photo photo) {
return author == photo.Author &&
album == photo.Album &&
title == photo.Title &&
year == photo.Year &&
format == photo.Format &&
size == photo.Size &&
date_added == photo.DateAdded &&
date_modified == photo.DateModified;
}
internal void Update (Photo photo) {
if (Equals (photo))
return;
author = photo.Author;
album = photo.Album;
title = photo.Title;
year = photo.Year;
format = photo.Format;
size = photo.Size;
date_added = photo.DateAdded;
date_modified = photo.DateModified;
EmitUpdated ();
}
private void EmitUpdated () {
if (Updated != null)
Updated (this, new EventArgs ());
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Support;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
namespace Lucene.Net.Store
{
using ArrayUtil = Lucene.Net.Util.ArrayUtil;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using Field = Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using OpenMode = Lucene.Net.Index.OpenMode;
using ScoreDoc = Lucene.Net.Search.ScoreDoc;
using Term = Lucene.Net.Index.Term;
using TermQuery = Lucene.Net.Search.TermQuery;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestBufferedIndexInput : LuceneTestCase
{
private static void WriteBytes(FileInfo aFile, long size)
{
using (FileStream ostream = new FileStream(aFile.FullName, FileMode.Create)) {
for (int i = 0; i < size; i++)
{
ostream.WriteByte(Byten(i));
}
ostream.Flush();
}
}
private const long TEST_FILE_LENGTH = 100 * 1024;
// Call readByte() repeatedly, past the buffer boundary, and see that it
// is working as expected.
// Our input comes from a dynamically generated/ "file" - see
// MyBufferedIndexInput below.
[Test]
public virtual void TestReadByte()
{
MyBufferedIndexInput input = new MyBufferedIndexInput();
for (int i = 0; i < BufferedIndexInput.BUFFER_SIZE * 10; i++)
{
Assert.AreEqual(input.ReadByte(), Byten(i));
}
}
// Call readBytes() repeatedly, with various chunk sizes (from 1 byte to
// larger than the buffer size), and see that it returns the bytes we expect.
// Our input comes from a dynamically generated "file" -
// see MyBufferedIndexInput below.
[Test]
public virtual void TestReadBytes()
{
MyBufferedIndexInput input = new MyBufferedIndexInput();
RunReadBytes(input, BufferedIndexInput.BUFFER_SIZE, Random());
}
private void RunReadBytesAndClose(IndexInput input, int bufferSize, Random r)
{
try
{
RunReadBytes(input, bufferSize, r);
}
finally
{
input.Dispose();
}
}
private void RunReadBytes(IndexInput input, int bufferSize, Random r)
{
int pos = 0;
// gradually increasing size:
for (int size = 1; size < bufferSize * 10; size = size + size / 200 + 1)
{
CheckReadBytes(input, size, pos);
pos += size;
if (pos >= TEST_FILE_LENGTH)
{
// wrap
pos = 0;
input.Seek(0L);
}
}
// wildly fluctuating size:
for (long i = 0; i < 100; i++)
{
int size = r.Next(10000);
CheckReadBytes(input, 1 + size, pos);
pos += 1 + size;
if (pos >= TEST_FILE_LENGTH)
{
// wrap
pos = 0;
input.Seek(0L);
}
}
// constant small size (7 bytes):
for (int i = 0; i < bufferSize; i++)
{
CheckReadBytes(input, 7, pos);
pos += 7;
if (pos >= TEST_FILE_LENGTH)
{
// wrap
pos = 0;
input.Seek(0L);
}
}
}
private byte[] Buffer = new byte[10];
private void CheckReadBytes(IndexInput input, int size, int pos)
{
// Just to see that "offset" is treated properly in readBytes(), we
// add an arbitrary offset at the beginning of the array
int offset = size % 10; // arbitrary
Buffer = ArrayUtil.Grow(Buffer, offset + size);
Assert.AreEqual(pos, input.GetFilePointer());
long left = TEST_FILE_LENGTH - input.GetFilePointer();
if (left <= 0)
{
return;
}
else if (left < size)
{
size = (int)left;
}
input.ReadBytes(Buffer, offset, size);
Assert.AreEqual(pos + size, input.GetFilePointer());
for (int i = 0; i < size; i++)
{
Assert.AreEqual(Byten(pos + i), (byte)Buffer[offset + i], "pos=" + i + " filepos=" + (pos + i));
}
}
// this tests that attempts to readBytes() past an EOF will fail, while
// reads up to the EOF will succeed. The EOF is determined by the
// BufferedIndexInput's arbitrary length() value.
[Test]
public virtual void TestEOF()
{
MyBufferedIndexInput input = new MyBufferedIndexInput(1024);
// see that we can read all the bytes at one go:
CheckReadBytes(input, (int)input.Length, 0);
// go back and see that we can't read more than that, for small and
// large overflows:
int pos = (int)input.Length - 10;
input.Seek(pos);
CheckReadBytes(input, 10, pos);
input.Seek(pos);
try
{
CheckReadBytes(input, 11, pos);
Assert.Fail("Block read past end of file");
}
#pragma warning disable 168
catch (IOException e)
#pragma warning restore 168
{
/* success */
}
input.Seek(pos);
try
{
CheckReadBytes(input, 50, pos);
Assert.Fail("Block read past end of file");
}
#pragma warning disable 168
catch (IOException e)
#pragma warning restore 168
{
/* success */
}
input.Seek(pos);
try
{
CheckReadBytes(input, 100000, pos);
Assert.Fail("Block read past end of file");
}
#pragma warning disable 168
catch (IOException e)
#pragma warning restore 168
{
/* success */
}
}
// byten emulates a file - byten(n) returns the n'th byte in that file.
// MyBufferedIndexInput reads this "file".
private static byte Byten(long n)
{
return (byte)(n * n % 256);
}
private class MyBufferedIndexInput : BufferedIndexInput
{
internal long Pos;
internal long Len;
public MyBufferedIndexInput(long len)
: base("MyBufferedIndexInput(len=" + len + ")", BufferedIndexInput.BUFFER_SIZE)
{
this.Len = len;
this.Pos = 0;
}
public MyBufferedIndexInput()
: this(long.MaxValue)
{
// an infinite file
}
protected override void ReadInternal(byte[] b, int offset, int length)
{
for (int i = offset; i < offset + length; i++)
{
b[i] = Byten(Pos++);
}
}
protected override void SeekInternal(long pos)
{
this.Pos = pos;
}
protected override void Dispose(bool disposing)
{
}
public override long Length
{
get { return Len; }
}
}
[Test]
public virtual void TestSetBufferSize()
{
var indexDir = CreateTempDir("testSetBufferSize");
var dir = new MockFSDirectory(indexDir, Random());
try
{
var writer = new IndexWriter(
dir,
new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))
.SetOpenMode(OpenMode.CREATE)
.SetMergePolicy(NewLogMergePolicy(false)));
for (int i = 0; i < 37; i++)
{
var doc = new Document();
doc.Add(NewTextField("content", "aaa bbb ccc ddd" + i, Field.Store.YES));
doc.Add(NewTextField("id", "" + i, Field.Store.YES));
writer.AddDocument(doc);
}
dir.AllIndexInputs.Clear();
IndexReader reader = DirectoryReader.Open(writer, true);
var aaa = new Term("content", "aaa");
var bbb = new Term("content", "bbb");
reader.Dispose();
dir.TweakBufferSizes();
writer.DeleteDocuments(new Term("id", "0"));
reader = DirectoryReader.Open(writer, true);
var searcher = NewSearcher(reader);
var hits = searcher.Search(new TermQuery(bbb), null, 1000).ScoreDocs;
dir.TweakBufferSizes();
Assert.AreEqual(36, hits.Length);
reader.Dispose();
dir.TweakBufferSizes();
writer.DeleteDocuments(new Term("id", "4"));
reader = DirectoryReader.Open(writer, true);
searcher = NewSearcher(reader);
hits = searcher.Search(new TermQuery(bbb), null, 1000).ScoreDocs;
dir.TweakBufferSizes();
Assert.AreEqual(35, hits.Length);
dir.TweakBufferSizes();
hits = searcher.Search(new TermQuery(new Term("id", "33")), null, 1000).ScoreDocs;
dir.TweakBufferSizes();
Assert.AreEqual(1, hits.Length);
hits = searcher.Search(new TermQuery(aaa), null, 1000).ScoreDocs;
dir.TweakBufferSizes();
Assert.AreEqual(35, hits.Length);
writer.Dispose();
reader.Dispose();
}
finally
{
indexDir.Delete(true);
}
}
private class MockFSDirectory : BaseDirectory
{
internal readonly IList<IndexInput> AllIndexInputs = new List<IndexInput>();
private Random Rand;
private Directory Dir;
public MockFSDirectory(DirectoryInfo path, Random rand)
{
this.Rand = rand;
SetLockFactory(NoLockFactory.GetNoLockFactory());
Dir = new SimpleFSDirectory(path, null);
}
public virtual void TweakBufferSizes()
{
//int count = 0;
foreach (IndexInput ip in AllIndexInputs)
{
BufferedIndexInput bii = (BufferedIndexInput)ip;
int bufferSize = 1024 + Math.Abs(Rand.Next() % 32768);
bii.SetBufferSize(bufferSize);
//count++;
}
//System.out.println("tweak'd " + count + " buffer sizes");
}
public override IndexInput OpenInput(string name, IOContext context)
{
// Make random changes to buffer size
//bufferSize = 1+Math.abs(rand.nextInt() % 10);
IndexInput f = Dir.OpenInput(name, context);
AllIndexInputs.Add(f);
return f;
}
public override IndexOutput CreateOutput(string name, IOContext context)
{
return Dir.CreateOutput(name, context);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Dir.Dispose();
}
}
public override void DeleteFile(string name)
{
Dir.DeleteFile(name);
}
[Obsolete("this method will be removed in 5.0")]
public override bool FileExists(string name)
{
return Dir.FileExists(name);
}
public override string[] ListAll()
{
return Dir.ListAll();
}
public override void Sync(ICollection<string> names)
{
Dir.Sync(names);
}
public override long FileLength(string name)
{
return Dir.FileLength(name);
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if (!(SILVERLIGHT) || WINDOWS_PHONE) && !PORTABLE40
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
#if !(NET20 || PORTABLE40)
using System.Xml.Linq;
#endif
using Newtonsoft.Json.Utilities;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Converters
{
#region XmlNodeWrappers
#if !SILVERLIGHT && !NETFX_CORE && !PORTABLE && !PORTABLE40
internal class XmlDocumentWrapper : XmlNodeWrapper, IXmlDocument
{
private readonly XmlDocument _document;
public XmlDocumentWrapper(XmlDocument document)
: base(document)
{
_document = document;
}
public IXmlNode CreateComment(string data)
{
return new XmlNodeWrapper(_document.CreateComment(data));
}
public IXmlNode CreateTextNode(string text)
{
return new XmlNodeWrapper(_document.CreateTextNode(text));
}
public IXmlNode CreateCDataSection(string data)
{
return new XmlNodeWrapper(_document.CreateCDataSection(data));
}
public IXmlNode CreateWhitespace(string text)
{
return new XmlNodeWrapper(_document.CreateWhitespace(text));
}
public IXmlNode CreateSignificantWhitespace(string text)
{
return new XmlNodeWrapper(_document.CreateSignificantWhitespace(text));
}
public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone)
{
return new XmlNodeWrapper(_document.CreateXmlDeclaration(version, encoding, standalone));
}
public IXmlNode CreateProcessingInstruction(string target, string data)
{
return new XmlNodeWrapper(_document.CreateProcessingInstruction(target, data));
}
public IXmlElement CreateElement(string elementName)
{
return new XmlElementWrapper(_document.CreateElement(elementName));
}
public IXmlElement CreateElement(string qualifiedName, string namespaceUri)
{
return new XmlElementWrapper(_document.CreateElement(qualifiedName, namespaceUri));
}
public IXmlNode CreateAttribute(string name, string value)
{
XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(name));
attribute.Value = value;
return attribute;
}
public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value)
{
XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(qualifiedName, namespaceUri));
attribute.Value = value;
return attribute;
}
public IXmlElement DocumentElement
{
get
{
if (_document.DocumentElement == null)
return null;
return new XmlElementWrapper(_document.DocumentElement);
}
}
}
internal class XmlElementWrapper : XmlNodeWrapper, IXmlElement
{
private readonly XmlElement _element;
public XmlElementWrapper(XmlElement element)
: base(element)
{
_element = element;
}
public void SetAttributeNode(IXmlNode attribute)
{
XmlNodeWrapper xmlAttributeWrapper = (XmlNodeWrapper)attribute;
_element.SetAttributeNode((XmlAttribute) xmlAttributeWrapper.WrappedNode);
}
public string GetPrefixOfNamespace(string namespaceUri)
{
return _element.GetPrefixOfNamespace(namespaceUri);
}
}
internal class XmlDeclarationWrapper : XmlNodeWrapper, IXmlDeclaration
{
private readonly XmlDeclaration _declaration;
public XmlDeclarationWrapper(XmlDeclaration declaration)
: base(declaration)
{
_declaration = declaration;
}
public string Version
{
get { return _declaration.Version; }
}
public string Encoding
{
get { return _declaration.Encoding; }
set { _declaration.Encoding = value; }
}
public string Standalone
{
get { return _declaration.Standalone; }
set { _declaration.Standalone = value; }
}
}
internal class XmlNodeWrapper : IXmlNode
{
private readonly XmlNode _node;
public XmlNodeWrapper(XmlNode node)
{
_node = node;
}
public object WrappedNode
{
get { return _node; }
}
public XmlNodeType NodeType
{
get { return _node.NodeType; }
}
public string LocalName
{
get { return _node.LocalName; }
}
public IList<IXmlNode> ChildNodes
{
get { return _node.ChildNodes.Cast<XmlNode>().Select(n => WrapNode(n)).ToList(); }
}
private IXmlNode WrapNode(XmlNode node)
{
switch (node.NodeType)
{
case XmlNodeType.Element:
return new XmlElementWrapper((XmlElement) node);
case XmlNodeType.XmlDeclaration:
return new XmlDeclarationWrapper((XmlDeclaration) node);
default:
return new XmlNodeWrapper(node);
}
}
public IList<IXmlNode> Attributes
{
get
{
if (_node.Attributes == null)
return null;
return _node.Attributes.Cast<XmlAttribute>().Select(a => WrapNode(a)).ToList();
}
}
public IXmlNode ParentNode
{
get
{
XmlNode node = (_node is XmlAttribute)
? ((XmlAttribute) _node).OwnerElement
: _node.ParentNode;
if (node == null)
return null;
return WrapNode(node);
}
}
public string Value
{
get { return _node.Value; }
set { _node.Value = value; }
}
public IXmlNode AppendChild(IXmlNode newChild)
{
XmlNodeWrapper xmlNodeWrapper = (XmlNodeWrapper) newChild;
_node.AppendChild(xmlNodeWrapper._node);
return newChild;
}
public string NamespaceUri
{
get { return _node.NamespaceURI; }
}
}
#endif
#endregion
#region Interfaces
internal interface IXmlDocument : IXmlNode
{
IXmlNode CreateComment(string text);
IXmlNode CreateTextNode(string text);
IXmlNode CreateCDataSection(string data);
IXmlNode CreateWhitespace(string text);
IXmlNode CreateSignificantWhitespace(string text);
IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone);
IXmlNode CreateProcessingInstruction(string target, string data);
IXmlElement CreateElement(string elementName);
IXmlElement CreateElement(string qualifiedName, string namespaceUri);
IXmlNode CreateAttribute(string name, string value);
IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value);
IXmlElement DocumentElement { get; }
}
internal interface IXmlDeclaration : IXmlNode
{
string Version { get; }
string Encoding { get; set; }
string Standalone { get; set; }
}
internal interface IXmlElement : IXmlNode
{
void SetAttributeNode(IXmlNode attribute);
string GetPrefixOfNamespace(string namespaceUri);
}
internal interface IXmlNode
{
XmlNodeType NodeType { get; }
string LocalName { get; }
IList<IXmlNode> ChildNodes { get; }
IList<IXmlNode> Attributes { get; }
IXmlNode ParentNode { get; }
string Value { get; set; }
IXmlNode AppendChild(IXmlNode newChild);
string NamespaceUri { get; }
object WrappedNode { get; }
}
#endregion
#region XNodeWrappers
#if !NET20
internal class XDeclarationWrapper : XObjectWrapper, IXmlDeclaration
{
internal XDeclaration Declaration { get; private set; }
public XDeclarationWrapper(XDeclaration declaration)
: base(null)
{
Declaration = declaration;
}
public override XmlNodeType NodeType
{
get { return XmlNodeType.XmlDeclaration; }
}
public string Version
{
get { return Declaration.Version; }
}
public string Encoding
{
get { return Declaration.Encoding; }
set { Declaration.Encoding = value; }
}
public string Standalone
{
get { return Declaration.Standalone; }
set { Declaration.Standalone = value; }
}
}
internal class XDocumentWrapper : XContainerWrapper, IXmlDocument
{
private XDocument Document
{
get { return (XDocument)WrappedNode; }
}
public XDocumentWrapper(XDocument document)
: base(document)
{
}
public override IList<IXmlNode> ChildNodes
{
get
{
IList<IXmlNode> childNodes = base.ChildNodes;
if (Document.Declaration != null)
childNodes.Insert(0, new XDeclarationWrapper(Document.Declaration));
return childNodes;
}
}
public IXmlNode CreateComment(string text)
{
return new XObjectWrapper(new XComment(text));
}
public IXmlNode CreateTextNode(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateCDataSection(string data)
{
return new XObjectWrapper(new XCData(data));
}
public IXmlNode CreateWhitespace(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateSignificantWhitespace(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone)
{
return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone));
}
public IXmlNode CreateProcessingInstruction(string target, string data)
{
return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data));
}
public IXmlElement CreateElement(string elementName)
{
return new XElementWrapper(new XElement(elementName));
}
public IXmlElement CreateElement(string qualifiedName, string namespaceUri)
{
string localName = MiscellaneousUtils.GetLocalName(qualifiedName);
return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri)));
}
public IXmlNode CreateAttribute(string name, string value)
{
return new XAttributeWrapper(new XAttribute(name, value));
}
public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value)
{
string localName = MiscellaneousUtils.GetLocalName(qualifiedName);
return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value));
}
public IXmlElement DocumentElement
{
get
{
if (Document.Root == null)
return null;
return new XElementWrapper(Document.Root);
}
}
public override IXmlNode AppendChild(IXmlNode newChild)
{
XDeclarationWrapper declarationWrapper = newChild as XDeclarationWrapper;
if (declarationWrapper != null)
{
Document.Declaration = declarationWrapper.Declaration;
return declarationWrapper;
}
else
{
return base.AppendChild(newChild);
}
}
}
internal class XTextWrapper : XObjectWrapper
{
private XText Text
{
get { return (XText)WrappedNode; }
}
public XTextWrapper(XText text)
: base(text)
{
}
public override string Value
{
get { return Text.Value; }
set { Text.Value = value; }
}
public override IXmlNode ParentNode
{
get
{
if (Text.Parent == null)
return null;
return XContainerWrapper.WrapNode(Text.Parent);
}
}
}
internal class XCommentWrapper : XObjectWrapper
{
private XComment Text
{
get { return (XComment)WrappedNode; }
}
public XCommentWrapper(XComment text)
: base(text)
{
}
public override string Value
{
get { return Text.Value; }
set { Text.Value = value; }
}
public override IXmlNode ParentNode
{
get
{
if (Text.Parent == null)
return null;
return XContainerWrapper.WrapNode(Text.Parent);
}
}
}
internal class XProcessingInstructionWrapper : XObjectWrapper
{
private XProcessingInstruction ProcessingInstruction
{
get { return (XProcessingInstruction)WrappedNode; }
}
public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction)
: base(processingInstruction)
{
}
public override string LocalName
{
get { return ProcessingInstruction.Target; }
}
public override string Value
{
get { return ProcessingInstruction.Data; }
set { ProcessingInstruction.Data = value; }
}
}
internal class XContainerWrapper : XObjectWrapper
{
private XContainer Container
{
get { return (XContainer)WrappedNode; }
}
public XContainerWrapper(XContainer container)
: base(container)
{
}
public override IList<IXmlNode> ChildNodes
{
get { return Container.Nodes().Select(n => WrapNode(n)).ToList(); }
}
public override IXmlNode ParentNode
{
get
{
if (Container.Parent == null)
return null;
return WrapNode(Container.Parent);
}
}
internal static IXmlNode WrapNode(XObject node)
{
if (node is XDocument)
return new XDocumentWrapper((XDocument)node);
else if (node is XElement)
return new XElementWrapper((XElement)node);
else if (node is XContainer)
return new XContainerWrapper((XContainer)node);
else if (node is XProcessingInstruction)
return new XProcessingInstructionWrapper((XProcessingInstruction)node);
else if (node is XText)
return new XTextWrapper((XText)node);
else if (node is XComment)
return new XCommentWrapper((XComment)node);
else if (node is XAttribute)
return new XAttributeWrapper((XAttribute) node);
else
return new XObjectWrapper(node);
}
public override IXmlNode AppendChild(IXmlNode newChild)
{
Container.Add(newChild.WrappedNode);
return newChild;
}
}
internal class XObjectWrapper : IXmlNode
{
private readonly XObject _xmlObject;
public XObjectWrapper(XObject xmlObject)
{
_xmlObject = xmlObject;
}
public object WrappedNode
{
get { return _xmlObject; }
}
public virtual XmlNodeType NodeType
{
get { return _xmlObject.NodeType; }
}
public virtual string LocalName
{
get { return null; }
}
public virtual IList<IXmlNode> ChildNodes
{
get { return new List<IXmlNode>(); }
}
public virtual IList<IXmlNode> Attributes
{
get { return null; }
}
public virtual IXmlNode ParentNode
{
get { return null; }
}
public virtual string Value
{
get { return null; }
set { throw new InvalidOperationException(); }
}
public virtual IXmlNode AppendChild(IXmlNode newChild)
{
throw new InvalidOperationException();
}
public virtual string NamespaceUri
{
get { return null; }
}
}
internal class XAttributeWrapper : XObjectWrapper
{
private XAttribute Attribute
{
get { return (XAttribute)WrappedNode; }
}
public XAttributeWrapper(XAttribute attribute)
: base(attribute)
{
}
public override string Value
{
get { return Attribute.Value; }
set { Attribute.Value = value; }
}
public override string LocalName
{
get { return Attribute.Name.LocalName; }
}
public override string NamespaceUri
{
get { return Attribute.Name.NamespaceName; }
}
public override IXmlNode ParentNode
{
get
{
if (Attribute.Parent == null)
return null;
return XContainerWrapper.WrapNode(Attribute.Parent);
}
}
}
internal class XElementWrapper : XContainerWrapper, IXmlElement
{
private XElement Element
{
get { return (XElement) WrappedNode; }
}
public XElementWrapper(XElement element)
: base(element)
{
}
public void SetAttributeNode(IXmlNode attribute)
{
XObjectWrapper wrapper = (XObjectWrapper)attribute;
Element.Add(wrapper.WrappedNode);
}
public override IList<IXmlNode> Attributes
{
get { return Element.Attributes().Select(a => new XAttributeWrapper(a)).Cast<IXmlNode>().ToList(); }
}
public override string Value
{
get { return Element.Value; }
set { Element.Value = value; }
}
public override string LocalName
{
get { return Element.Name.LocalName; }
}
public override string NamespaceUri
{
get { return Element.Name.NamespaceName; }
}
public string GetPrefixOfNamespace(string namespaceUri)
{
return Element.GetPrefixOfNamespace(namespaceUri);
}
}
#endif
#endregion
/// <summary>
/// Converts XML to and from JSON.
/// </summary>
public class XmlNodeConverter : JsonConverter
{
private const string TextName = "#text";
private const string CommentName = "#comment";
private const string CDataName = "#cdata-section";
private const string WhitespaceName = "#whitespace";
private const string SignificantWhitespaceName = "#significant-whitespace";
private const string DeclarationName = "?xml";
private const string JsonNamespaceUri = "http://james.newtonking.com/projects/json";
/// <summary>
/// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produces multiple root elements.
/// </summary>
/// <value>The name of the deserialize root element.</value>
public string DeserializeRootElementName { get; set; }
/// <summary>
/// Gets or sets a flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </summary>
/// <value><c>true</c> if the array attibute is written to the XML; otherwise, <c>false</c>.</value>
public bool WriteArrayAttribute { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to write the root JSON object.
/// </summary>
/// <value><c>true</c> if the JSON root object is omitted; otherwise, <c>false</c>.</value>
public bool OmitRootObject { get; set; }
#region Writing
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="serializer">The calling serializer.</param>
/// <param name="value">The value.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
IXmlNode node = WrapXml(value);
XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
PushParentNamespaces(node, manager);
if (!OmitRootObject)
writer.WriteStartObject();
SerializeNode(writer, node, manager, !OmitRootObject);
if (!OmitRootObject)
writer.WriteEndObject();
}
private IXmlNode WrapXml(object value)
{
#if !NET20
if (value is XObject)
return XContainerWrapper.WrapNode((XObject)value);
#endif
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
if (value is XmlNode)
return new XmlNodeWrapper((XmlNode)value);
#endif
throw new ArgumentException("Value must be an XML object.", "value");
}
private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager)
{
List<IXmlNode> parentElements = null;
IXmlNode parent = node;
while ((parent = parent.ParentNode) != null)
{
if (parent.NodeType == XmlNodeType.Element)
{
if (parentElements == null)
parentElements = new List<IXmlNode>();
parentElements.Add(parent);
}
}
if (parentElements != null)
{
parentElements.Reverse();
foreach (IXmlNode parentElement in parentElements)
{
manager.PushScope();
foreach (IXmlNode attribute in parentElement.Attributes)
{
if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns")
manager.AddNamespace(attribute.LocalName, attribute.Value);
}
}
}
}
private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager)
{
string prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/"))
? null
: manager.LookupPrefix(node.NamespaceUri);
if (!string.IsNullOrEmpty(prefix))
return prefix + ":" + node.LocalName;
else
return node.LocalName;
}
private string GetPropertyName(IXmlNode node, XmlNamespaceManager manager)
{
switch (node.NodeType)
{
case XmlNodeType.Attribute:
if (node.NamespaceUri == JsonNamespaceUri)
return "$" + node.LocalName;
else
return "@" + ResolveFullName(node, manager);
case XmlNodeType.CDATA:
return CDataName;
case XmlNodeType.Comment:
return CommentName;
case XmlNodeType.Element:
return ResolveFullName(node, manager);
case XmlNodeType.ProcessingInstruction:
return "?" + ResolveFullName(node, manager);
case XmlNodeType.XmlDeclaration:
return DeclarationName;
case XmlNodeType.SignificantWhitespace:
return SignificantWhitespaceName;
case XmlNodeType.Text:
return TextName;
case XmlNodeType.Whitespace:
return WhitespaceName;
default:
throw new JsonSerializationException("Unexpected XmlNodeType when getting node name: " + node.NodeType);
}
}
private bool IsArray(IXmlNode node)
{
IXmlNode jsonArrayAttribute = (node.Attributes != null)
? node.Attributes.SingleOrDefault(a => a.LocalName == "Array" && a.NamespaceUri == JsonNamespaceUri)
: null;
return (jsonArrayAttribute != null && XmlConvert.ToBoolean(jsonArrayAttribute.Value));
}
private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName)
{
// group nodes together by name
Dictionary<string, List<IXmlNode>> nodesGroupedByName = new Dictionary<string, List<IXmlNode>>();
for (int i = 0; i < node.ChildNodes.Count; i++)
{
IXmlNode childNode = node.ChildNodes[i];
string nodeName = GetPropertyName(childNode, manager);
List<IXmlNode> nodes;
if (!nodesGroupedByName.TryGetValue(nodeName, out nodes))
{
nodes = new List<IXmlNode>();
nodesGroupedByName.Add(nodeName, nodes);
}
nodes.Add(childNode);
}
// loop through grouped nodes. write single name instances as normal,
// write multiple names together in an array
foreach (KeyValuePair<string, List<IXmlNode>> nodeNameGroup in nodesGroupedByName)
{
List<IXmlNode> groupedNodes = nodeNameGroup.Value;
bool writeArray;
if (groupedNodes.Count == 1)
{
writeArray = IsArray(groupedNodes[0]);
}
else
{
writeArray = true;
}
if (!writeArray)
{
SerializeNode(writer, groupedNodes[0], manager, writePropertyName);
}
else
{
string elementNames = nodeNameGroup.Key;
if (writePropertyName)
writer.WritePropertyName(elementNames);
writer.WriteStartArray();
for (int i = 0; i < groupedNodes.Count; i++)
{
SerializeNode(writer, groupedNodes[i], manager, false);
}
writer.WriteEndArray();
}
}
}
private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName)
{
switch (node.NodeType)
{
case XmlNodeType.Document:
case XmlNodeType.DocumentFragment:
SerializeGroupedNodes(writer, node, manager, writePropertyName);
break;
case XmlNodeType.Element:
if (IsArray(node) && node.ChildNodes.All(n => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0)
{
SerializeGroupedNodes(writer, node, manager, false);
}
else
{
manager.PushScope();
foreach (IXmlNode attribute in node.Attributes)
{
if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/")
{
string namespacePrefix = (attribute.LocalName != "xmlns")
? attribute.LocalName
: string.Empty;
string namespaceUri = attribute.Value;
manager.AddNamespace(namespacePrefix, namespaceUri);
}
}
if (writePropertyName)
writer.WritePropertyName(GetPropertyName(node, manager));
if (!ValueAttributes(node.Attributes).Any() && node.ChildNodes.Count == 1
&& node.ChildNodes[0].NodeType == XmlNodeType.Text)
{
// write elements with a single text child as a name value pair
writer.WriteValue(node.ChildNodes[0].Value);
}
else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes))
{
// empty element
writer.WriteNull();
}
else
{
writer.WriteStartObject();
for (int i = 0; i < node.Attributes.Count; i++)
{
SerializeNode(writer, node.Attributes[i], manager, true);
}
SerializeGroupedNodes(writer, node, manager, true);
writer.WriteEndObject();
}
manager.PopScope();
}
break;
case XmlNodeType.Comment:
if (writePropertyName)
writer.WriteComment(node.Value);
break;
case XmlNodeType.Attribute:
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri)
return;
if (node.NamespaceUri == JsonNamespaceUri)
{
if (node.LocalName == "Array")
return;
}
if (writePropertyName)
writer.WritePropertyName(GetPropertyName(node, manager));
writer.WriteValue(node.Value);
break;
case XmlNodeType.XmlDeclaration:
IXmlDeclaration declaration = (IXmlDeclaration)node;
writer.WritePropertyName(GetPropertyName(node, manager));
writer.WriteStartObject();
if (!string.IsNullOrEmpty(declaration.Version))
{
writer.WritePropertyName("@version");
writer.WriteValue(declaration.Version);
}
if (!string.IsNullOrEmpty(declaration.Encoding))
{
writer.WritePropertyName("@encoding");
writer.WriteValue(declaration.Encoding);
}
if (!string.IsNullOrEmpty(declaration.Standalone))
{
writer.WritePropertyName("@standalone");
writer.WriteValue(declaration.Standalone);
}
writer.WriteEndObject();
break;
default:
throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType);
}
}
#endregion
#region Reading
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
IXmlDocument document = null;
IXmlNode rootNode = null;
#if !NET20
if (typeof(XObject).IsAssignableFrom(objectType))
{
if (objectType != typeof (XDocument) && objectType != typeof (XElement))
throw new JsonSerializationException("XmlNodeConverter only supports deserializing XDocument or XElement.");
XDocument d = new XDocument();
document = new XDocumentWrapper(d);
rootNode = document;
}
#endif
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
if (typeof(XmlNode).IsAssignableFrom(objectType))
{
if (objectType != typeof (XmlDocument))
throw new JsonSerializationException("XmlNodeConverter only supports deserializing XmlDocuments");
XmlDocument d = new XmlDocument();
document = new XmlDocumentWrapper(d);
rootNode = document;
}
#endif
if (document == null || rootNode == null)
throw new JsonSerializationException("Unexpected type when converting XML: " + objectType);
if (reader.TokenType != JsonToken.StartObject)
throw new JsonSerializationException("XmlNodeConverter can only convert JSON that begins with an object.");
if (!string.IsNullOrEmpty(DeserializeRootElementName))
{
//rootNode = document.CreateElement(DeserializeRootElementName);
//document.AppendChild(rootNode);
ReadElement(reader, document, rootNode, DeserializeRootElementName, manager);
}
else
{
reader.Read();
DeserializeNode(reader, document, manager, rootNode);
}
#if !NET20
if (objectType == typeof(XElement))
{
XElement element = (XElement)document.DocumentElement.WrappedNode;
element.Remove();
return element;
}
#endif
return document.WrappedNode;
}
private void DeserializeValue(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, string propertyName, IXmlNode currentNode)
{
switch (propertyName)
{
case TextName:
currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString()));
break;
case CDataName:
currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString()));
break;
case WhitespaceName:
currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString()));
break;
case SignificantWhitespaceName:
currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString()));
break;
default:
// processing instructions and the xml declaration start with ?
if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?')
{
CreateInstruction(reader, document, currentNode, propertyName);
}
else
{
if (reader.TokenType == JsonToken.StartArray)
{
// handle nested arrays
ReadArrayElements(reader, document, propertyName, currentNode, manager);
return;
}
// have to wait until attributes have been parsed before creating element
// attributes may contain namespace info used by the element
ReadElement(reader, document, currentNode, propertyName, manager);
}
break;
}
}
private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager)
{
if (string.IsNullOrEmpty(propertyName))
throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML.");
Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager);
string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);
if (propertyName.StartsWith("@"))
{
var attributeName = propertyName.Substring(1);
var attributeValue = reader.Value.ToString();
var attributePrefix = MiscellaneousUtils.GetPrefix(attributeName);
var attribute = (!string.IsNullOrEmpty(attributePrefix))
? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue)
: document.CreateAttribute(attributeName, attributeValue);
((IXmlElement)currentNode).SetAttributeNode(attribute);
}
else
{
IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager);
currentNode.AppendChild(element);
// add attributes to newly created element
foreach (KeyValuePair<string, string> nameValue in attributeNameValues)
{
string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key);
IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix))
? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix), nameValue.Value)
: document.CreateAttribute(nameValue.Key, nameValue.Value);
element.SetAttributeNode(attribute);
}
if (reader.TokenType == JsonToken.String
|| reader.TokenType == JsonToken.Integer
|| reader.TokenType == JsonToken.Float
|| reader.TokenType == JsonToken.Boolean
|| reader.TokenType == JsonToken.Date)
{
element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader)));
}
else if (reader.TokenType == JsonToken.Null)
{
// empty element. do nothing
}
else
{
// finished element will have no children to deserialize
if (reader.TokenType != JsonToken.EndObject)
{
manager.PushScope();
DeserializeNode(reader, document, manager, element);
manager.PopScope();
}
}
}
}
private string ConvertTokenToXmlValue(JsonReader reader)
{
if (reader.TokenType == JsonToken.String)
{
return reader.Value.ToString();
}
else if (reader.TokenType == JsonToken.Integer)
{
return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Float)
{
return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Boolean)
{
return XmlConvert.ToString(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Date)
{
DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture);
#if !(NETFX_CORE || PORTABLE)
return XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind));
#else
return XmlConvert.ToString(d);
#endif
}
else if (reader.TokenType == JsonToken.Null)
{
return null;
}
else
{
throw JsonSerializationException.Create(reader, "Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager)
{
string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);
IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager);
currentNode.AppendChild(nestedArrayElement);
int count = 0;
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
DeserializeValue(reader, document, manager, propertyName, nestedArrayElement);
count++;
}
if (WriteArrayAttribute)
{
AddJsonArrayAttribute(nestedArrayElement, document);
}
if (count == 1 && WriteArrayAttribute)
{
IXmlElement arrayElement = nestedArrayElement.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName);
AddJsonArrayAttribute(arrayElement, document);
}
}
private void AddJsonArrayAttribute(IXmlElement element, IXmlDocument document)
{
element.SetAttributeNode(document.CreateAttribute("json:Array", JsonNamespaceUri, "true"));
#if !NET20
// linq to xml doesn't automatically include prefixes via the namespace manager
if (element is XElementWrapper)
{
if (element.GetPrefixOfNamespace(JsonNamespaceUri) == null)
{
element.SetAttributeNode(document.CreateAttribute("xmlns:json", "http://www.w3.org/2000/xmlns/", JsonNamespaceUri));
}
}
#endif
}
private Dictionary<string, string> ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager)
{
Dictionary<string, string> attributeNameValues = new Dictionary<string, string>();
bool finishedAttributes = false;
bool finishedElement = false;
// a string token means the element only has a single text child
if (reader.TokenType != JsonToken.String
&& reader.TokenType != JsonToken.Null
&& reader.TokenType != JsonToken.Boolean
&& reader.TokenType != JsonToken.Integer
&& reader.TokenType != JsonToken.Float
&& reader.TokenType != JsonToken.Date
&& reader.TokenType != JsonToken.StartConstructor)
{
// read properties until first non-attribute is encountered
while (!finishedAttributes && !finishedElement && reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string attributeName = reader.Value.ToString();
if (!string.IsNullOrEmpty(attributeName))
{
char firstChar = attributeName[0];
string attributeValue;
switch (firstChar)
{
case '@':
attributeName = attributeName.Substring(1);
reader.Read();
attributeValue = ConvertTokenToXmlValue(reader);
attributeNameValues.Add(attributeName, attributeValue);
string namespacePrefix;
if (IsNamespaceAttribute(attributeName, out namespacePrefix))
{
manager.AddNamespace(namespacePrefix, attributeValue);
}
break;
case '$':
attributeName = attributeName.Substring(1);
reader.Read();
attributeValue = reader.Value.ToString();
// check that JsonNamespaceUri is in scope
// if it isn't then add it to document and namespace manager
string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri);
if (jsonPrefix == null)
{
// ensure that the prefix used is free
int? i = null;
while (manager.LookupNamespace("json" + i) != null)
{
i = i.GetValueOrDefault() + 1;
}
jsonPrefix = "json" + i;
attributeNameValues.Add("xmlns:" + jsonPrefix, JsonNamespaceUri);
manager.AddNamespace(jsonPrefix, JsonNamespaceUri);
}
attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue);
break;
default:
finishedAttributes = true;
break;
}
}
else
{
finishedAttributes = true;
}
break;
case JsonToken.EndObject:
finishedElement = true;
break;
default:
throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType);
}
}
}
return attributeNameValues;
}
private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName)
{
if (propertyName == DeclarationName)
{
string version = null;
string encoding = null;
string standalone = null;
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
switch (reader.Value.ToString())
{
case "@version":
reader.Read();
version = reader.Value.ToString();
break;
case "@encoding":
reader.Read();
encoding = reader.Value.ToString();
break;
case "@standalone":
reader.Read();
standalone = reader.Value.ToString();
break;
default:
throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value);
}
}
IXmlNode declaration = document.CreateXmlDeclaration(version, encoding, standalone);
currentNode.AppendChild(declaration);
}
else
{
IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString());
currentNode.AppendChild(instruction);
}
}
private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager)
{
string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix);
IXmlElement element = (!string.IsNullOrEmpty(ns)) ? document.CreateElement(elementName, ns) : document.CreateElement(elementName);
return element;
}
private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode currentNode)
{
do
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null)
throw new JsonSerializationException("JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.");
string propertyName = reader.Value.ToString();
reader.Read();
if (reader.TokenType == JsonToken.StartArray)
{
int count = 0;
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
DeserializeValue(reader, document, manager, propertyName, currentNode);
count++;
}
if (count == 1 && WriteArrayAttribute)
{
IXmlElement arrayElement = currentNode.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName);
AddJsonArrayAttribute(arrayElement, document);
}
}
else
{
DeserializeValue(reader, document, manager, propertyName, currentNode);
}
break;
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
while (reader.Read() && reader.TokenType != JsonToken.EndConstructor)
{
DeserializeValue(reader, document, manager, constructorName, currentNode);
}
break;
case JsonToken.Comment:
currentNode.AppendChild(document.CreateComment((string)reader.Value));
break;
case JsonToken.EndObject:
case JsonToken.EndArray:
return;
default:
throw new JsonSerializationException("Unexpected JsonToken when deserializing node: " + reader.TokenType);
}
} while (reader.TokenType == JsonToken.PropertyName || reader.Read());
// don't read if current token is a property. token was already read when parsing element attributes
}
/// <summary>
/// Checks if the attributeName is a namespace attribute.
/// </summary>
/// <param name="attributeName">Attribute name to test.</param>
/// <param name="prefix">The attribute name prefix if it has one, otherwise an empty string.</param>
/// <returns>True if attribute name is for a namespace attribute, otherwise false.</returns>
private bool IsNamespaceAttribute(string attributeName, out string prefix)
{
if (attributeName.StartsWith("xmlns", StringComparison.Ordinal))
{
if (attributeName.Length == 5)
{
prefix = string.Empty;
return true;
}
else if (attributeName[5] == ':')
{
prefix = attributeName.Substring(6, attributeName.Length - 6);
return true;
}
}
prefix = null;
return false;
}
private IEnumerable<IXmlNode> ValueAttributes(IEnumerable<IXmlNode> c)
{
return c.Where(a => a.NamespaceUri != JsonNamespaceUri);
}
#endregion
/// <summary>
/// Determines whether this instance can convert the specified value type.
/// </summary>
/// <param name="valueType">Type of the value.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type valueType)
{
#if !NET20
if (typeof(XObject).IsAssignableFrom(valueType))
return true;
#endif
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
if (typeof(XmlNode).IsAssignableFrom(valueType))
return true;
#endif
return false;
}
}
}
#endif
| |
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEngine.Audio;
using System.Collections;
// GVR soundfield component that allows playback of first-order ambisonic recordings. The
// audio sample should be in Ambix (ACN-SN3D) format.
[AddComponentMenu("GoogleVR/Audio/GvrAudioSoundfield")]
public class GvrAudioSoundfield : MonoBehaviour {
/// Input gain in decibels.
public float gainDb = 0.0f;
/// Play source on awake.
public bool playOnAwake = true;
/// The default AudioClip to play.
public AudioClip clip0102 {
get { return soundfieldClip0102; }
set {
soundfieldClip0102 = value;
if (audioSources != null && audioSources.Length > 0) {
audioSources[0].clip = soundfieldClip0102;
}
}
}
[SerializeField]
private AudioClip soundfieldClip0102 = null;
public AudioClip clip0304 {
get { return soundfieldClip0304; }
set {
soundfieldClip0304 = value;
if (audioSources != null && audioSources.Length > 0) {
audioSources[1].clip = soundfieldClip0304;
}
}
}
[SerializeField]
private AudioClip soundfieldClip0304 = null;
/// Is the clip playing right now (Read Only)?
public bool isPlaying {
get {
if(audioSources != null && audioSources.Length > 0) {
return audioSources[0].isPlaying;
}
return false;
}
}
/// Is the audio clip looping?
public bool loop {
get { return soundfieldLoop; }
set {
soundfieldLoop = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].loop = soundfieldLoop;
}
}
}
}
[SerializeField]
private bool soundfieldLoop = false;
/// Un- / Mutes the soundfield. Mute sets the volume=0, Un-Mute restore the original volume.
public bool mute {
get { return soundfieldMute; }
set {
soundfieldMute = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].mute = soundfieldMute;
}
}
}
}
[SerializeField]
private bool soundfieldMute = false;
/// The pitch of the audio source.
public float pitch {
get { return soundfieldPitch; }
set {
soundfieldPitch = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].pitch = soundfieldPitch;
}
}
}
}
[SerializeField]
[Range(-3.0f, 3.0f)]
private float soundfieldPitch = 1.0f;
/// Sets the priority of the soundfield.
public int priority {
get { return soundfieldPriority; }
set {
soundfieldPriority = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].priority = soundfieldPriority;
}
}
}
}
[SerializeField]
[Range(0, 256)]
private int soundfieldPriority = 32;
/// Playback position in seconds.
public float time {
get {
if(audioSources != null && audioSources.Length > 0) {
return audioSources[0].time;
}
return 0.0f;
}
set {
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].time = value;
}
}
}
}
/// Playback position in PCM samples.
public int timeSamples {
get {
if(audioSources != null && audioSources.Length > 0) {
return audioSources[0].timeSamples;
}
return 0;
}
set {
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].timeSamples = value;
}
}
}
}
/// The volume of the audio source (0.0 to 1.0).
public float volume {
get { return soundfieldVolume; }
set {
soundfieldVolume = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].volume = soundfieldVolume;
}
}
}
}
[SerializeField]
[Range(0.0f, 1.0f)]
private float soundfieldVolume = 1.0f;
// Unique source id.
private int id = -1;
// Unity audio sources per each soundfield channel set.
private AudioSource[] audioSources = null;
// Denotes whether the source is currently paused or not.
private bool isPaused = false;
void Awake () {
// Route the source output to |GvrAudioMixer|.
AudioMixer mixer = (Resources.Load("GvrAudioMixer") as AudioMixer);
if(mixer == null) {
Debug.LogError("GVRAudioMixer could not be found in Resources. Make sure that the GVR SDK" +
"Unity package is imported properly.");
return;
}
audioSources = new AudioSource[GvrAudio.numFoaChannels / 2];
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
GameObject channelSetObject = new GameObject("Channel Set " + channelSet);
channelSetObject.transform.parent = gameObject.transform;
channelSetObject.hideFlags = HideFlags.HideAndDontSave;
audioSources[channelSet] = channelSetObject.AddComponent<AudioSource>();
audioSources[channelSet].enabled = false;
audioSources[channelSet].playOnAwake = false;
audioSources[channelSet].bypassReverbZones = true;
audioSources[channelSet].dopplerLevel = 0.0f;
audioSources[channelSet].spatialBlend = 0.0f;
audioSources[channelSet].outputAudioMixerGroup = mixer.FindMatchingGroups("Master")[0];
}
OnValidate();
}
void OnEnable () {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].enabled = true;
}
if (playOnAwake && !isPlaying && InitializeSoundfield()) {
Play();
}
}
void Start () {
if (playOnAwake && !isPlaying) {
Play();
}
}
void OnDisable () {
Stop();
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].enabled = false;
}
}
void OnDestroy () {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
Destroy(audioSources[channelSet].gameObject);
}
}
void Update () {
// Update soundfield.
if (!isPlaying && !isPaused) {
Stop();
} else {
GvrAudio.UpdateAudioSoundfield(id, transform, gainDb);
}
}
void OnValidate () {
clip0102 = soundfieldClip0102;
clip0304 = soundfieldClip0304;
loop = soundfieldLoop;
mute = soundfieldMute;
pitch = soundfieldPitch;
priority = soundfieldPriority;
volume = soundfieldVolume;
}
/// Pauses playing the clip.
public void Pause () {
if (audioSources != null) {
isPaused = true;
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].Pause();
}
}
}
/// Plays the clip.
public void Play () {
double dspTime = AudioSettings.dspTime;
PlayScheduled(dspTime);
}
/// Plays the clip with a delay specified in seconds.
public void PlayDelayed (float delay) {
double delayedDspTime = AudioSettings.dspTime + (double)delay;
PlayScheduled(delayedDspTime);
}
/// Plays the clip at a specific time on the absolute time-line that AudioSettings.dspTime reads
/// from.
public void PlayScheduled (double time) {
if (audioSources != null && InitializeSoundfield()) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].PlayScheduled(time);
}
isPaused = false;
} else {
Debug.LogWarning ("GVR Audio soundfield not initialized. Audio playback not supported " +
"until after Awake() and OnEnable(). Try calling from Start() instead.");
}
}
/// Stops playing the clip.
public void Stop () {
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].Stop();
}
ShutdownSoundfield();
isPaused = false;
}
}
/// Unpauses the paused playback.
public void UnPause () {
if (audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].UnPause();
}
isPaused = true;
}
}
// Initializes the source.
private bool InitializeSoundfield () {
if (id < 0) {
id = GvrAudio.CreateAudioSoundfield();
if (id >= 0) {
GvrAudio.UpdateAudioSoundfield(id, transform, gainDb);
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
InitializeChannelSet(audioSources[channelSet], channelSet);
}
}
}
return id >= 0;
}
// Shuts down the source.
private void ShutdownSoundfield () {
if (id >= 0) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
ShutdownChannelSet(audioSources[channelSet], channelSet);
}
GvrAudio.DestroyAudioSource(id);
id = -1;
}
}
// Initializes given channel set of the soundfield.
private void InitializeChannelSet(AudioSource source, int channelSet) {
source.spatialize = true;
source.SetSpatializerFloat(0, (float)id);
source.SetSpatializerFloat(1, (float)GvrAudio.SpatializerType.Soundfield);
source.SetSpatializerFloat(2, (float)GvrAudio.numFoaChannels);
source.SetSpatializerFloat(3, (float)channelSet);
}
// Shuts down given channel set of the soundfield.
private void ShutdownChannelSet(AudioSource source, int channelSet) {
source.SetSpatializerFloat(0, -1.0f);
source.spatialize = false;
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for RouteTablesOperations.
/// </summary>
public static partial class RouteTablesOperationsExtensions
{
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
public static void Delete(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName)
{
operations.DeleteAsync(resourceGroupName, routeTableName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
public static RouteTable Get(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, routeTableName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteTable> GetAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeTableName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
public static RouteTable CreateOrUpdate(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, routeTableName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteTable> CreateOrUpdateAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<RouteTable> List(this IRouteTablesOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListAsync(this IRouteTablesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<RouteTable> ListAll(this IRouteTablesOperations operations)
{
return operations.ListAllAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListAllAsync(this IRouteTablesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
public static void BeginDelete(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName)
{
operations.BeginDeleteAsync(resourceGroupName, routeTableName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
public static RouteTable BeginCreateOrUpdate(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, routeTableName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteTable> BeginCreateOrUpdateAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteTable> ListNext(this IRouteTablesOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListNextAsync(this IRouteTablesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteTable> ListAllNext(this IRouteTablesOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListAllNextAsync(this IRouteTablesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using FluentMigrator.Builders.Alter.Column;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
using Moq;
using NUnit.Framework;
namespace FluentMigrator.Tests.Unit.Builders.Alter
{
[TestFixture]
public class AlterColumnExpressionBuilderTests
{
[Test]
public void CallingOnTableSetsTableName()
{
var expressionMock = new Mock<AlterColumnExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.OnTable("Bacon");
expressionMock.VerifySet(x => x.TableName = "Bacon");
}
[Test]
public void CallingAsAnsiStringSetsColumnDbTypeToAnsiString()
{
VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString());
}
[Test]
public void CallingAsAnsiStringWithSizeSetsColumnDbTypeToAnsiString()
{
VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString(42));
}
[Test]
public void CallingAsAnsiStringWithSizeSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(42, b => b.AsAnsiString(42));
}
[Test]
public void CallingAsBinarySetsColumnDbTypeToBinary()
{
VerifyColumnDbType(DbType.Binary, b => b.AsBinary());
}
[Test]
public void CallingAsBinaryWithSizeSetsColumnDbTypeToBinary()
{
VerifyColumnDbType(DbType.Binary, b => b.AsBinary(42));
}
[Test]
public void CallingAsBinaryWithSizeSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(42, b => b.AsBinary(42));
}
[Test]
public void CallingAsBooleanSetsColumnDbTypeToBoolean()
{
VerifyColumnDbType(DbType.Boolean, b => b.AsBoolean());
}
[Test]
public void CallingAsByteSetsColumnDbTypeToByte()
{
VerifyColumnDbType(DbType.Byte, b => b.AsByte());
}
[Test]
public void CallingAsCurrencySetsColumnDbTypeToCurrency()
{
VerifyColumnDbType(DbType.Currency, b => b.AsCurrency());
}
[Test]
public void CallingAsDateSetsColumnDbTypeToDate()
{
VerifyColumnDbType(DbType.Date, b => b.AsDate());
}
[Test]
public void CallingAsDateTimeSetsColumnDbTypeToDateTime()
{
VerifyColumnDbType(DbType.DateTime, b => b.AsDateTime());
}
[Test]
public void CallingAsDecimalSetsColumnDbTypeToDecimal()
{
VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal());
}
[Test]
public void CallingAsDecimalWithSizeAndPrecisionSetsColumnDbTypeToDecimal()
{
VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDecimalStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(1, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDecimalStringSetsColumnPrecisionToSpecifiedValue()
{
VerifyColumnPrecision(2, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDoubleSetsColumnDbTypeToDouble()
{
VerifyColumnDbType(DbType.Double, b => b.AsDouble());
}
[Test]
public void CallingAsGuidSetsColumnDbTypeToGuid()
{
VerifyColumnDbType(DbType.Guid, b => b.AsGuid());
}
[Test]
public void CallingAsFixedLengthStringSetsColumnDbTypeToStringFixedLength()
{
VerifyColumnDbType(DbType.StringFixedLength, e => e.AsFixedLengthString(255));
}
[Test]
public void CallingAsFixedLengthStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthString(255));
}
[Test]
public void CallingAsFixedLengthAnsiStringSetsColumnDbTypeToAnsiStringFixedLength()
{
VerifyColumnDbType(DbType.AnsiStringFixedLength, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsFixedLengthAnsiStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsFloatSetsColumnDbTypeToSingle()
{
VerifyColumnDbType(DbType.Single, b => b.AsFloat());
}
[Test]
public void CallingAsInt16SetsColumnDbTypeToInt16()
{
VerifyColumnDbType(DbType.Int16, b => b.AsInt16());
}
[Test]
public void CallingAsInt32SetsColumnDbTypeToInt32()
{
VerifyColumnDbType(DbType.Int32, b => b.AsInt32());
}
[Test]
public void CallingAsInt64SetsColumnDbTypeToInt64()
{
VerifyColumnDbType(DbType.Int64, b => b.AsInt64());
}
[Test]
public void CallingAsStringSetsColumnDbTypeToString()
{
VerifyColumnDbType(DbType.String, b => b.AsString());
}
[Test]
public void CallingAsStringWithLengthSetsColumnDbTypeToString()
{
VerifyColumnDbType(DbType.String, b => b.AsString(255));
}
[Test]
public void CallingAsStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsTimeSetsColumnDbTypeToTime()
{
VerifyColumnDbType(DbType.Time, b => b.AsTime());
}
[Test]
public void CallingAsXmlSetsColumnDbTypeToXml()
{
VerifyColumnDbType(DbType.Xml, b => b.AsXml());
}
[Test]
public void CallingAsXmlWithSizeSetsColumnDbTypeToXml()
{
VerifyColumnDbType(DbType.Xml, b => b.AsXml(255));
}
[Test]
public void CallingAsXmlSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsXml(255));
}
[Test]
public void CallingAsCustomSetsTypeToNullAndSetsCustomType()
{
VerifyColumnProperty(c => c.Type = null, b => b.AsCustom("Test"));
VerifyColumnProperty(c => c.CustomType = "Test", b => b.AsCustom("Test"));
}
[Test]
public void CallingWithDefaultValueAddsAlterDefaultConstraintExpression()
{
const int value = 42;
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.WithDefaultValue(value);
columnMock.VerifySet(c => c.DefaultValue = value);
collectionMock.Verify(x => x.Add(It.Is<AlterDefaultConstraintExpression>(e => e.DefaultValue.Equals(value))));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingForeignKeySetsIsForeignKeyToTrue()
{
VerifyColumnProperty(c => c.IsForeignKey = true, b => b.ForeignKey());
}
[Test]
public void CallingReferencedByAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<AlterColumnExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.ReferencedBy("fk_foo", "FooTable", "BarColumn");
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.ForeignTable == "FooTable" &&
fk.ForeignKey.ForeignColumns.Contains("BarColumn") &&
fk.ForeignKey.ForeignColumns.Count == 1 &&
fk.ForeignKey.PrimaryTable == "Bacon" &&
fk.ForeignKey.PrimaryColumns.Contains("BaconId") &&
fk.ForeignKey.PrimaryColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingForeignKeyAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<AlterColumnExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.ForeignKey("fk_foo", "FooTable", "BarColumn");
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.PrimaryTable == "FooTable" &&
fk.ForeignKey.PrimaryColumns.Contains("BarColumn") &&
fk.ForeignKey.PrimaryColumns.Count == 1 &&
fk.ForeignKey.ForeignTable == "Bacon" &&
fk.ForeignKey.ForeignColumns.Contains("BaconId") &&
fk.ForeignKey.ForeignColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingIdentitySetsIsIdentityToTrue()
{
VerifyColumnProperty(c => c.IsIdentity = true, b => b.Identity());
}
[Test]
public void CallingIndexedSetsIsIndexedToTrue()
{
VerifyColumnProperty(c => c.IsIndexed = true, b => b.Indexed());
}
[Test]
public void CallingPrimaryKeySetsIsPrimaryKeyToTrue()
{
VerifyColumnProperty(c => c.IsPrimaryKey = true, b => b.PrimaryKey());
}
[Test]
public void CallingNullableSetsIsNullableToTrue()
{
VerifyColumnProperty(c => c.IsNullable = true, b => b.Nullable());
}
[Test]
public void CallingNotNullableSetsIsNullableToFalse()
{
VerifyColumnProperty(c => c.IsNullable = false, b => b.NotNullable());
}
[Test]
public void CallingUniqueSetsIsUniqueToTrue()
{
VerifyColumnProperty(c => c.IsUnique = true, b => b.Unique());
}
private void VerifyColumnProperty(Action<ColumnDefinition> columnExpression, Action<AlterColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
callToTest(new AlterColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(columnExpression);
}
private void VerifyColumnDbType(DbType expected, Action<AlterColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
callToTest(new AlterColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(c => c.Type = expected);
}
private void VerifyColumnSize(int expected, Action<AlterColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
callToTest(new AlterColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(c => c.Size = expected);
}
private void VerifyColumnPrecision(int expected, Action<AlterColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
callToTest(new AlterColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(c => c.Precision = expected);
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
#pragma warning disable 1591 // disable warning on missing comments
using System;
using Adaptive.SimpleBinaryEncoding;
namespace Adaptive.SimpleBinaryEncoding.Examples.Generated
{
public sealed partial class Car
{
public const ushort BlockLength = (ushort)45;
public const ushort TemplateId = (ushort)1;
public const ushort SchemaId = (ushort)1;
public const ushort Schema_Version = (ushort)0;
public const string SematicType = "";
private readonly Car _parentMessage;
private DirectBuffer _buffer;
private int _offset;
private int _limit;
private int _actingBlockLength;
private int _actingVersion;
public int Offset { get { return _offset; } }
public Car()
{
_parentMessage = this;
}
public void WrapForEncode(DirectBuffer buffer, int offset)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = BlockLength;
_actingVersion = Schema_Version;
Limit = offset + _actingBlockLength;
}
public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = actingBlockLength;
_actingVersion = actingVersion;
Limit = offset + _actingBlockLength;
}
public int Size
{
get
{
return _limit - _offset;
}
}
public int Limit
{
get
{
return _limit;
}
set
{
_buffer.CheckLimit(_limit);
_limit = value;
}
}
public const int SerialNumberId = 1;
public static string SerialNumberMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ulong SerialNumberNullValue = 0x8000000000000000UL;
public const ulong SerialNumberMinValue = 0x0UL;
public const ulong SerialNumberMaxValue = 0x7fffffffffffffffUL;
public ulong SerialNumber
{
get
{
return _buffer.Uint64GetLittleEndian(_offset + 0);
}
set
{
_buffer.Uint64PutLittleEndian(_offset + 0, value);
}
}
public const int ModelYearId = 2;
public static string ModelYearMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ushort ModelYearNullValue = (ushort)65535;
public const ushort ModelYearMinValue = (ushort)0;
public const ushort ModelYearMaxValue = (ushort)65534;
public ushort ModelYear
{
get
{
return _buffer.Uint16GetLittleEndian(_offset + 8);
}
set
{
_buffer.Uint16PutLittleEndian(_offset + 8, value);
}
}
public const int AvailableId = 3;
public static string AvailableMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public BooleanType Available
{
get
{
return (BooleanType)_buffer.Uint8Get(_offset + 10);
}
set
{
_buffer.Uint8Put(_offset + 10, (byte)value);
}
}
public const int CodeId = 4;
public static string CodeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public Model Code
{
get
{
return (Model)_buffer.CharGet(_offset + 11);
}
set
{
_buffer.CharPut(_offset + 11, (byte)value);
}
}
public const int SomeNumbersId = 5;
public static string SomeNumbersMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const int SomeNumbersNullValue = -2147483648;
public const int SomeNumbersMinValue = -2147483647;
public const int SomeNumbersMaxValue = 2147483647;
public const int SomeNumbersLength = 5;
public int GetSomeNumbers(int index)
{
if (index < 0 || index >= 5)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.Int32GetLittleEndian(_offset + 12 + (index * 4));
}
public void SetSomeNumbers(int index, int value)
{
if (index < 0 || index >= 5)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.Int32PutLittleEndian(_offset + 12 + (index * 4), value);
}
public const int VehicleCodeId = 6;
public static string VehicleCodeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const byte VehicleCodeNullValue = (byte)0;
public const byte VehicleCodeMinValue = (byte)32;
public const byte VehicleCodeMaxValue = (byte)126;
public const int VehicleCodeLength = 6;
public byte GetVehicleCode(int index)
{
if (index < 0 || index >= 6)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 32 + (index * 1));
}
public void SetVehicleCode(int index, byte value)
{
if (index < 0 || index >= 6)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 32 + (index * 1), value);
}
public const string VehicleCodeCharacterEncoding = "UTF-8";
public int GetVehicleCode(byte[] dst, int dstOffset)
{
const int length = 6;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 32, dst, dstOffset, length);
return length;
}
public void SetVehicleCode(byte[] src, int srcOffset)
{
const int length = 6;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 32, src, srcOffset, length);
}
public const int ExtrasId = 7;
public static string ExtrasMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public OptionalExtras Extras
{
get
{
return (OptionalExtras)_buffer.Uint8Get(_offset + 38);
}
set
{
_buffer.Uint8Put(_offset + 38, (byte)value);
}
}
public const int EngineId = 8;
public static string EngineMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
private readonly Engine _engine = new Engine();
public Engine Engine
{
get
{
_engine.Wrap(_buffer, _offset + 39, _actingVersion);
return _engine;
}
}
private readonly FuelFiguresGroup _fuelFigures = new FuelFiguresGroup();
public const long FuelFiguresId = 9;
public FuelFiguresGroup FuelFigures
{
get
{
_fuelFigures.WrapForDecode(_parentMessage, _buffer, _actingVersion);
return _fuelFigures;
}
}
public FuelFiguresGroup FuelFiguresCount(int count)
{
_fuelFigures.WrapForEncode(_parentMessage, _buffer, count);
return _fuelFigures;
}
public sealed partial class FuelFiguresGroup
{
private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding();
private Car _parentMessage;
private DirectBuffer _buffer;
private int _blockLength;
private int _actingVersion;
private int _count;
private int _index;
private int _offset;
public void WrapForDecode(Car parentMessage, DirectBuffer buffer, int actingVersion)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, actingVersion);
_count = _dimensions.NumInGroup;
_blockLength = _dimensions.BlockLength;
_actingVersion = actingVersion;
_index = -1;
_parentMessage.Limit = parentMessage.Limit + SbeHeaderSize;
}
public void WrapForEncode(Car parentMessage, DirectBuffer buffer, int count)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion);
_dimensions.NumInGroup = (byte)count;
_dimensions.BlockLength = (ushort)6;
_index = -1;
_count = count;
_blockLength = 6;
parentMessage.Limit = parentMessage.Limit + SbeHeaderSize;
}
public const int SbeBlockLength = 6;
public const int SbeHeaderSize = 3;
public int ActingBlockLength { get { return _blockLength; } }
public int Count { get { return _count; } }
public bool HasNext { get { return (_index + 1) < _count; } }
public FuelFiguresGroup Next()
{
if (_index + 1 >= _count)
{
throw new InvalidOperationException();
}
_offset = _parentMessage.Limit;
_parentMessage.Limit = _offset + _blockLength;
++_index;
return this;
}
public const int SpeedId = 10;
public static string SpeedMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ushort SpeedNullValue = (ushort)65535;
public const ushort SpeedMinValue = (ushort)0;
public const ushort SpeedMaxValue = (ushort)65534;
public ushort Speed
{
get
{
return _buffer.Uint16GetLittleEndian(_offset + 0);
}
set
{
_buffer.Uint16PutLittleEndian(_offset + 0, value);
}
}
public const int MpgId = 11;
public static string MpgMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const float MpgNullValue = float.NaN;
public const float MpgMinValue = 1.401298464324817E-45f;
public const float MpgMaxValue = 3.4028234663852886E38f;
public float Mpg
{
get
{
return _buffer.FloatGetLittleEndian(_offset + 2);
}
set
{
_buffer.FloatPutLittleEndian(_offset + 2, value);
}
}
}
private readonly PerformanceFiguresGroup _performanceFigures = new PerformanceFiguresGroup();
public const long PerformanceFiguresId = 12;
public PerformanceFiguresGroup PerformanceFigures
{
get
{
_performanceFigures.WrapForDecode(_parentMessage, _buffer, _actingVersion);
return _performanceFigures;
}
}
public PerformanceFiguresGroup PerformanceFiguresCount(int count)
{
_performanceFigures.WrapForEncode(_parentMessage, _buffer, count);
return _performanceFigures;
}
public sealed partial class PerformanceFiguresGroup
{
private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding();
private Car _parentMessage;
private DirectBuffer _buffer;
private int _blockLength;
private int _actingVersion;
private int _count;
private int _index;
private int _offset;
public void WrapForDecode(Car parentMessage, DirectBuffer buffer, int actingVersion)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, actingVersion);
_count = _dimensions.NumInGroup;
_blockLength = _dimensions.BlockLength;
_actingVersion = actingVersion;
_index = -1;
_parentMessage.Limit = parentMessage.Limit + SbeHeaderSize;
}
public void WrapForEncode(Car parentMessage, DirectBuffer buffer, int count)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion);
_dimensions.NumInGroup = (byte)count;
_dimensions.BlockLength = (ushort)1;
_index = -1;
_count = count;
_blockLength = 1;
parentMessage.Limit = parentMessage.Limit + SbeHeaderSize;
}
public const int SbeBlockLength = 1;
public const int SbeHeaderSize = 3;
public int ActingBlockLength { get { return _blockLength; } }
public int Count { get { return _count; } }
public bool HasNext { get { return (_index + 1) < _count; } }
public PerformanceFiguresGroup Next()
{
if (_index + 1 >= _count)
{
throw new InvalidOperationException();
}
_offset = _parentMessage.Limit;
_parentMessage.Limit = _offset + _blockLength;
++_index;
return this;
}
public const int OctaneRatingId = 13;
public static string OctaneRatingMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const byte OctaneRatingNullValue = (byte)255;
public const byte OctaneRatingMinValue = (byte)90;
public const byte OctaneRatingMaxValue = (byte)110;
public byte OctaneRating
{
get
{
return _buffer.Uint8Get(_offset + 0);
}
set
{
_buffer.Uint8Put(_offset + 0, value);
}
}
private readonly AccelerationGroup _acceleration = new AccelerationGroup();
public const long AccelerationId = 14;
public AccelerationGroup Acceleration
{
get
{
_acceleration.WrapForDecode(_parentMessage, _buffer, _actingVersion);
return _acceleration;
}
}
public AccelerationGroup AccelerationCount(int count)
{
_acceleration.WrapForEncode(_parentMessage, _buffer, count);
return _acceleration;
}
public sealed partial class AccelerationGroup
{
private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding();
private Car _parentMessage;
private DirectBuffer _buffer;
private int _blockLength;
private int _actingVersion;
private int _count;
private int _index;
private int _offset;
public void WrapForDecode(Car parentMessage, DirectBuffer buffer, int actingVersion)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, actingVersion);
_count = _dimensions.NumInGroup;
_blockLength = _dimensions.BlockLength;
_actingVersion = actingVersion;
_index = -1;
_parentMessage.Limit = parentMessage.Limit + SbeHeaderSize;
}
public void WrapForEncode(Car parentMessage, DirectBuffer buffer, int count)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion);
_dimensions.NumInGroup = (byte)count;
_dimensions.BlockLength = (ushort)6;
_index = -1;
_count = count;
_blockLength = 6;
parentMessage.Limit = parentMessage.Limit + SbeHeaderSize;
}
public const int SbeBlockLength = 6;
public const int SbeHeaderSize = 3;
public int ActingBlockLength { get { return _blockLength; } }
public int Count { get { return _count; } }
public bool HasNext { get { return (_index + 1) < _count; } }
public AccelerationGroup Next()
{
if (_index + 1 >= _count)
{
throw new InvalidOperationException();
}
_offset = _parentMessage.Limit;
_parentMessage.Limit = _offset + _blockLength;
++_index;
return this;
}
public const int MphId = 15;
public static string MphMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ushort MphNullValue = (ushort)65535;
public const ushort MphMinValue = (ushort)0;
public const ushort MphMaxValue = (ushort)65534;
public ushort Mph
{
get
{
return _buffer.Uint16GetLittleEndian(_offset + 0);
}
set
{
_buffer.Uint16PutLittleEndian(_offset + 0, value);
}
}
public const int SecondsId = 16;
public static string SecondsMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const float SecondsNullValue = float.NaN;
public const float SecondsMinValue = 1.401298464324817E-45f;
public const float SecondsMaxValue = 3.4028234663852886E38f;
public float Seconds
{
get
{
return _buffer.FloatGetLittleEndian(_offset + 2);
}
set
{
_buffer.FloatPutLittleEndian(_offset + 2, value);
}
}
}
}
public const int MakeId = 17;
public const string MakeCharacterEncoding = "UTF-8";
public static string MakeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Make";
}
return "";
}
public const int MakeHeaderSize = 1;
public int GetMake(byte[] dst, int dstOffset, int length)
{
const int sizeOfLengthField = 1;
int limit = Limit;
_buffer.CheckLimit(limit + sizeOfLengthField);
int dataLength = _buffer.Uint8Get(limit);
int bytesCopied = Math.Min(length, dataLength);
Limit = limit + sizeOfLengthField + dataLength;
_buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int SetMake(byte[] src, int srcOffset, int length)
{
const int sizeOfLengthField = 1;
int limit = Limit;
Limit = limit + sizeOfLengthField + length;
_buffer.Uint8Put(limit, (byte)length);
_buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length);
return length;
}
public const int ModelId = 18;
public const string ModelCharacterEncoding = "UTF-8";
public static string ModelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const int ModelHeaderSize = 1;
public int GetModel(byte[] dst, int dstOffset, int length)
{
const int sizeOfLengthField = 1;
int limit = Limit;
_buffer.CheckLimit(limit + sizeOfLengthField);
int dataLength = _buffer.Uint8Get(limit);
int bytesCopied = Math.Min(length, dataLength);
Limit = limit + sizeOfLengthField + dataLength;
_buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int SetModel(byte[] src, int srcOffset, int length)
{
const int sizeOfLengthField = 1;
int limit = Limit;
Limit = limit + sizeOfLengthField + length;
_buffer.Uint8Put(limit, (byte)length);
_buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length);
return length;
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace WeifenLuo.WinFormsUI.Docking
{
internal class VS2012LightAutoHideStrip : AutoHideStripBase
{
private class TabVS2012Light : Tab
{
internal TabVS2012Light(IDockContent content)
: base(content)
{
}
private int m_tabX = 0;
public int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth = 0;
public int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
public bool IsMouseOver { get; set; }
}
private const int _ImageHeight = 16;
private const int _ImageWidth = 0;
private const int _ImageGapTop = 2;
private const int _ImageGapLeft = 4;
private const int _ImageGapRight = 2;
private const int _ImageGapBottom = 2;
private const int _TextGapLeft = 0;
private const int _TextGapRight = 0;
private const int _TabGapTop = 3;
private const int _TabGapBottom = 8;
private const int _TabGapLeft = 4;
private const int _TabGapBetween = 10;
#region Customizable Properties
public Font TextFont
{
get { return DockPanel.Skin.AutoHideStripSkin.TextFont; }
}
private static StringFormat _stringFormatTabHorizontal;
private StringFormat StringFormatTabHorizontal
{
get
{
if (_stringFormatTabHorizontal == null)
{
_stringFormatTabHorizontal = new StringFormat();
_stringFormatTabHorizontal.Alignment = StringAlignment.Near;
_stringFormatTabHorizontal.LineAlignment = StringAlignment.Center;
_stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap;
_stringFormatTabHorizontal.Trimming = StringTrimming.None;
}
if (RightToLeft == RightToLeft.Yes)
_stringFormatTabHorizontal.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
else
_stringFormatTabHorizontal.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft;
return _stringFormatTabHorizontal;
}
}
private static StringFormat _stringFormatTabVertical;
private StringFormat StringFormatTabVertical
{
get
{
if (_stringFormatTabVertical == null)
{
_stringFormatTabVertical = new StringFormat();
_stringFormatTabVertical.Alignment = StringAlignment.Near;
_stringFormatTabVertical.LineAlignment = StringAlignment.Center;
_stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical;
_stringFormatTabVertical.Trimming = StringTrimming.None;
}
if (RightToLeft == RightToLeft.Yes)
_stringFormatTabVertical.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
else
_stringFormatTabVertical.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft;
return _stringFormatTabVertical;
}
}
private static int ImageHeight
{
get { return _ImageHeight; }
}
private static int ImageWidth
{
get { return _ImageWidth; }
}
private static int ImageGapTop
{
get { return _ImageGapTop; }
}
private static int ImageGapLeft
{
get { return _ImageGapLeft; }
}
private static int ImageGapRight
{
get { return _ImageGapRight; }
}
private static int ImageGapBottom
{
get { return _ImageGapBottom; }
}
private static int TextGapLeft
{
get { return _TextGapLeft; }
}
private static int TextGapRight
{
get { return _TextGapRight; }
}
private static int TabGapTop
{
get { return _TabGapTop; }
}
private static int TabGapBottom
{
get { return _TabGapBottom; }
}
private static int TabGapLeft
{
get { return _TabGapLeft; }
}
private static int TabGapBetween
{
get { return _TabGapBetween; }
}
private static Pen PenTabBorder
{
get { return SystemPens.GrayText; }
}
#endregion
private static Matrix _matrixIdentity = new Matrix();
private static Matrix MatrixIdentity
{
get { return _matrixIdentity; }
}
private static DockState[] _dockStates;
private static DockState[] DockStates
{
get
{
if (_dockStates == null)
{
_dockStates = new DockState[4];
_dockStates[0] = DockState.DockLeftAutoHide;
_dockStates[1] = DockState.DockRightAutoHide;
_dockStates[2] = DockState.DockTopAutoHide;
_dockStates[3] = DockState.DockBottomAutoHide;
}
return _dockStates;
}
}
private static GraphicsPath _graphicsPath;
internal static GraphicsPath GraphicsPath
{
get
{
if (_graphicsPath == null)
_graphicsPath = new GraphicsPath();
return _graphicsPath;
}
}
public VS2012LightAutoHideStrip(DockPanel panel)
: base(panel)
{
SetStyle(ControlStyles.ResizeRedraw |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer, true);
BackColor = SystemColors.ControlLight;
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.FillRectangle(SystemBrushes.Control, ClientRectangle);
DrawTabStrip(g);
}
protected override void OnLayout(LayoutEventArgs levent)
{
CalculateTabs();
base.OnLayout(levent);
}
private void DrawTabStrip(Graphics g)
{
DrawTabStrip(g, DockState.DockTopAutoHide);
DrawTabStrip(g, DockState.DockBottomAutoHide);
DrawTabStrip(g, DockState.DockLeftAutoHide);
DrawTabStrip(g, DockState.DockRightAutoHide);
}
private void DrawTabStrip(Graphics g, DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return;
Matrix matrixIdentity = g.Transform;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
{
Matrix matrixRotated = new Matrix();
matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
g.Transform = matrixRotated;
}
foreach (Pane pane in GetPanes(dockState))
{
foreach (TabVS2012Light tab in pane.AutoHideTabs)
DrawTab(g, tab);
}
g.Transform = matrixIdentity;
}
private void CalculateTabs()
{
CalculateTabs(DockState.DockTopAutoHide);
CalculateTabs(DockState.DockBottomAutoHide);
CalculateTabs(DockState.DockLeftAutoHide);
CalculateTabs(DockState.DockRightAutoHide);
}
private void CalculateTabs(DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight / ImageHeight);
int x = TabGapLeft + rectTabStrip.X;
foreach (Pane pane in GetPanes(dockState))
{
foreach (TabVS2012Light tab in pane.AutoHideTabs)
{
int width = imageWidth + ImageGapLeft + ImageGapRight +
TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width +
TextGapLeft + TextGapRight;
tab.TabX = x;
tab.TabWidth = width;
x += width;
}
x += TabGapBetween;
}
}
private Rectangle RtlTransform(Rectangle rect, DockState dockState)
{
Rectangle rectTransformed;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
rectTransformed = rect;
else
rectTransformed = DrawHelper.RtlTransform(this, rect);
return rectTransformed;
}
private GraphicsPath GetTabOutline(TabVS2012Light tab, bool transformed, bool rtlTransform)
{
DockState dockState = tab.Content.DockHandler.DockState;
Rectangle rectTab = GetTabRectangle(tab, transformed);
if (rtlTransform)
rectTab = RtlTransform(rectTab, dockState);
if (GraphicsPath != null)
{
GraphicsPath.Reset();
GraphicsPath.AddRectangle(rectTab);
}
return GraphicsPath;
}
private void DrawTab(Graphics g, TabVS2012Light tab)
{
Rectangle rectTabOrigin = GetTabRectangle(tab);
if (rectTabOrigin.IsEmpty)
return;
DockState dockState = tab.Content.DockHandler.DockState;
IDockContent content = tab.Content;
Color textColor;
if (tab.Content.DockHandler.IsActivated || tab.IsMouseOver)
textColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.StartColor;
else
textColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.EndColor;
Rectangle rectThickLine = rectTabOrigin;
rectThickLine.X += _TabGapLeft + _TextGapLeft + _ImageGapLeft + _ImageWidth;
rectThickLine.Width = TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width - 8;
rectThickLine.Height = Measures.AutoHideTabLineWidth;
if (dockState == DockState.DockBottomAutoHide || dockState == DockState.DockLeftAutoHide)
rectThickLine.Y += rectTabOrigin.Height - Measures.AutoHideTabLineWidth;
else
if (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide)
rectThickLine.Y += 0;
g.FillRectangle(new SolidBrush(textColor), rectThickLine);
//Set no rotate for drawing icon and text
Matrix matrixRotate = g.Transform;
g.Transform = MatrixIdentity;
// Draw the icon
Rectangle rectImage = rectTabOrigin;
rectImage.X += ImageGapLeft;
rectImage.Y += ImageGapTop;
int imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight / ImageHeight);
rectImage.Height = imageHeight;
rectImage.Width = imageWidth;
rectImage = GetTransformedRectangle(dockState, rectImage);
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
{
// The DockState is DockLeftAutoHide or DockRightAutoHide, so rotate the image 90 degrees to the right.
Rectangle rectTransform = RtlTransform(rectImage, dockState);
Point[] rotationPoints =
{
new Point(rectTransform.X + rectTransform.Width, rectTransform.Y),
new Point(rectTransform.X + rectTransform.Width, rectTransform.Y + rectTransform.Height),
new Point(rectTransform.X, rectTransform.Y)
};
using (Icon rotatedIcon = new Icon(((Form)content).Icon, 16, 16))
{
g.DrawImage(rotatedIcon.ToBitmap(), rotationPoints);
}
}
else
{
// Draw the icon normally without any rotation.
g.DrawIcon(((Form)content).Icon, RtlTransform(rectImage, dockState));
}
// Draw the text
Rectangle rectText = rectTabOrigin;
rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText = RtlTransform(GetTransformedRectangle(dockState, rectText), dockState);
if (DockPanel.ActiveContent == content || tab.IsMouseOver)
textColor = DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor;
else
textColor = DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabVertical);
else
g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabHorizontal);
// Set rotate back
g.Transform = matrixRotate;
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState)
{
return GetLogicalTabStripRectangle(dockState, false);
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed)
{
if (!DockHelper.IsDockStateAutoHide(dockState))
return Rectangle.Empty;
int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count;
int rightPanes = GetPanes(DockState.DockRightAutoHide).Count;
int topPanes = GetPanes(DockState.DockTopAutoHide).Count;
int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count;
int x, y, width, height;
height = MeasureHeight();
if (dockState == DockState.DockLeftAutoHide && leftPanes > 0)
{
x = 0;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockRightAutoHide && rightPanes > 0)
{
x = Width - height;
if (leftPanes != 0 && x < height)
x = height;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockTopAutoHide && topPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = 0;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = Height - height;
if (topPanes != 0 && y < height)
y = height;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else
return Rectangle.Empty;
if (width == 0 || height == 0)
{
return Rectangle.Empty;
}
var rect = new Rectangle(x, y, width, height);
return transformed ? GetTransformedRectangle(dockState, rect) : rect;
}
private Rectangle GetTabRectangle(TabVS2012Light tab)
{
return GetTabRectangle(tab, false);
}
private Rectangle GetTabRectangle(TabVS2012Light tab, bool transformed)
{
DockState dockState = tab.Content.DockHandler.DockState;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return Rectangle.Empty;
int x = tab.TabX;
int y = rectTabStrip.Y +
(dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ?
0 : TabGapTop);
int width = tab.TabWidth;
int height = rectTabStrip.Height - TabGapTop;
if (!transformed)
return new Rectangle(x, y, width, height);
else
return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height));
}
private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect)
{
if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide)
return rect;
PointF[] pts = new PointF[1];
// the center of the rectangle
pts[0].X = (float)rect.X + (float)rect.Width / 2;
pts[0].Y = (float)rect.Y + (float)rect.Height / 2;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
using (var matrix = new Matrix())
{
matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
matrix.TransformPoints(pts);
}
return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F),
(int)(pts[0].Y - (float)rect.Width / 2 + .5F),
rect.Height, rect.Width);
}
protected override IDockContent HitTest(Point ptMouse)
{
Tab tab = TabHitTest(ptMouse);
if (tab != null)
return tab.Content;
else
return null;
}
protected override Rectangle GetTabBounds(Tab tab)
{
GraphicsPath path = GetTabOutline((TabVS2012Light)tab, true, true);
RectangleF bounds = path.GetBounds();
return new Rectangle((int)bounds.Left, (int)bounds.Top, (int)bounds.Width, (int)bounds.Height);
}
protected Tab TabHitTest(Point ptMouse)
{
foreach (DockState state in DockStates)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true);
if (!rectTabStrip.Contains(ptMouse))
continue;
foreach (Pane pane in GetPanes(state))
{
foreach (TabVS2012Light tab in pane.AutoHideTabs)
{
GraphicsPath path = GetTabOutline(tab, true, true);
if (path.IsVisible(ptMouse))
return tab;
}
}
}
return null;
}
private TabVS2012Light lastSelectedTab = null;
protected override void OnMouseHover(EventArgs e)
{
var tab = (TabVS2012Light)TabHitTest(PointToClient(MousePosition));
if (tab != null)
{
tab.IsMouseOver = true;
Invalidate();
}
if (lastSelectedTab != tab)
{
if (lastSelectedTab != null)
lastSelectedTab.IsMouseOver = false;
lastSelectedTab = tab;
}
base.OnMouseHover(e);
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
if (lastSelectedTab != null)
lastSelectedTab.IsMouseOver = false;
Invalidate();
}
protected override int MeasureHeight()
{
return Math.Max(ImageGapBottom +
ImageGapTop + ImageHeight,
TextFont.Height) + TabGapTop + TabGapBottom;
}
protected override void OnRefreshChanges()
{
CalculateTabs();
Invalidate();
}
protected override AutoHideStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2012Light(content);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Html;
namespace Orchard.ResourceManagement
{
public class ResourceManager : IResourceManager
{
private readonly Dictionary<ResourceTypeName, RequireSettings> _required = new Dictionary<ResourceTypeName, RequireSettings>();
private readonly Dictionary<string, IList<ResourceRequiredContext>> _builtResources;
private readonly IEnumerable<IResourceManifestProvider> _providers;
private ResourceManifest _dynamicManifest;
private List<LinkEntry> _links;
private Dictionary<string, MetaEntry> _metas;
private List<IHtmlContent> _headScripts;
private List<IHtmlContent> _footScripts;
private readonly IResourceManifestState _resourceManifestState;
public ResourceManager(
IEnumerable<IResourceManifestProvider> resourceProviders,
IResourceManifestState resourceManifestState)
{
_resourceManifestState = resourceManifestState;
_providers = resourceProviders;
_builtResources = new Dictionary<string, IList<ResourceRequiredContext>>(StringComparer.OrdinalIgnoreCase);
}
public IEnumerable<ResourceManifest> ResourceManifests
{
get
{
if (_resourceManifestState.ResourceManifests == null)
{
var builder = new ResourceManifestBuilder();
foreach (var provider in _providers)
{
provider.BuildManifests(builder);
}
_resourceManifestState.ResourceManifests = builder.ResourceManifests;
}
return _resourceManifestState.ResourceManifests;
}
}
public ResourceManifest InlineManifest
{
get
{
if(_dynamicManifest == null)
{
_dynamicManifest = new ResourceManifest();
}
return _dynamicManifest;
}
}
public RequireSettings RegisterResource(string resourceType, string resourceName)
{
if (resourceType == null)
{
throw new ArgumentNullException(nameof(resourceType));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
RequireSettings settings;
var key = new ResourceTypeName(resourceType, resourceName);
if (!_required.TryGetValue(key, out settings))
{
settings = new RequireSettings { Type = resourceType, Name = resourceName };
_required[key] = settings;
}
_builtResources[resourceType] = null;
return settings;
}
public RequireSettings Include(string resourceType, string resourcePath, string resourceDebugPath)
{
return RegisterUrl(resourceType, resourcePath, resourceDebugPath, null);
}
public RequireSettings RegisterUrl(string resourceType, string resourcePath, string resourceDebugPath, string relativeFromPath)
{
if (resourceType == null)
{
throw new ArgumentNullException(nameof(resourceType));
}
if (resourcePath == null)
{
throw new ArgumentNullException(nameof(resourcePath));
}
// ~/ ==> convert to absolute path (e.g. /orchard/..)
if (resourcePath.StartsWith("~/", StringComparison.Ordinal))
{
// For tilde slash paths, drop the leading ~ to make it work with the underlying IFileProvider.
resourcePath = resourcePath.Substring(1);
}
if (resourceDebugPath != null && resourceDebugPath.StartsWith("~/", StringComparison.Ordinal))
{
// For tilde slash paths, drop the leading ~ to make it work with the underlying IFileProvider.
resourceDebugPath = resourceDebugPath.Substring(1);
}
return RegisterResource(resourceType, resourcePath).Define(d => d.SetUrl(resourcePath, resourceDebugPath));
}
public void RegisterHeadScript(IHtmlContent script)
{
if (_headScripts == null)
{
_headScripts = new List<IHtmlContent>();
}
_headScripts.Add(script);
}
public void RegisterFootScript(IHtmlContent script)
{
if (_footScripts == null)
{
_footScripts = new List<IHtmlContent>();
}
_footScripts.Add(script);
}
public void NotRequired(string resourceType, string resourceName)
{
if (resourceType == null)
{
throw new ArgumentNullException(nameof(resourceType));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
var key = new ResourceTypeName(resourceType, resourceName);
_builtResources[resourceType] = null;
_required.Remove(key);
}
public ResourceDefinition FindResource(RequireSettings settings)
{
return FindResource(settings, true);
}
private ResourceDefinition FindResource(RequireSettings settings, bool resolveInlineDefinitions)
{
// find the resource with the given type and name
// that has at least the given version number. If multiple,
// return the resource with the greatest version number.
// If not found and an inlineDefinition is given, define the resource on the fly
// using the action.
var name = settings.Name ?? "";
var type = settings.Type;
ResourceDefinition resource;
var resources = (from p in ResourceManifests
from r in p.GetResources(type)
where name.Equals(r.Key, StringComparison.OrdinalIgnoreCase)
select r.Value).SelectMany(x => x);
if(!String.IsNullOrEmpty(settings.Version))
{
// Specific version, filter
var upper = GetUpperBoundVersion(settings.Version);
var lower = GetLowerBoundVersion(settings.Version);
resources = from r in resources
let version = r.Version != null ? new Version(r.Version) : null
where lower <= version && version < upper
select r;
}
// Use the highest version of all matches
resource = (from r in resources
let version = r.Version != null ? new Version(r.Version) : null
orderby version descending
select r).FirstOrDefault();
if (resource == null && _dynamicManifest != null)
{
resources = (from r in _dynamicManifest.GetResources(type)
where name.Equals(r.Key, StringComparison.OrdinalIgnoreCase)
select r.Value).SelectMany(x => x);
if (!String.IsNullOrEmpty(settings.Version))
{
// Specific version, filter
var upper = GetUpperBoundVersion(settings.Version);
var lower = GetLowerBoundVersion(settings.Version);
resources = from r in resources
let version = r.Version != null ? new Version(r.Version) : null
where lower <= version && version < upper
select r;
}
// Use the highest version of all matches
resource = (from r in resources
let version = r.Version != null ? new Version(r.Version) : null
orderby version descending
select r).FirstOrDefault();
}
if (resolveInlineDefinitions && resource == null)
{
// Does not seem to exist, but it's possible it is being
// defined by a Define() from a RequireSettings somewhere.
if (ResolveInlineDefinitions(settings.Type))
{
// if any were defined, now try to find it
resource = FindResource(settings, false);
}
}
return resource;
}
/// <summary>
/// Returns the upper bound value of a required version number.
/// For instance, 3.1.0 returns 3.1.1, 4 returns 5.0.0, 6.1 returns 6.2.0
/// </summary>
private Version GetUpperBoundVersion(string minimumVersion)
{
Version version;
if (!Version.TryParse(minimumVersion, out version))
{
// Is is a single number?
int major;
if (int.TryParse(minimumVersion, out major))
{
return new Version(major + 1, 0, 0);
}
}
if (version.Build != -1)
{
return new Version(version.Major, version.Minor, version.Build + 1);
}
if (version.Minor != -1)
{
return new Version(version.Major, version.Minor + 1, 0);
}
return version;
}
/// <summary>
/// Returns the lower bound value of a required version number.
/// For instance, 3.1.0 returns 3.1.0, 4 returns 4.0.0, 6.1 returns 6.1.0
/// </summary>
private Version GetLowerBoundVersion(string minimumVersion)
{
Version version;
if (!Version.TryParse(minimumVersion, out version))
{
// Is is a single number?
int major;
if (int.TryParse(minimumVersion, out major))
{
return new Version(major, 0, 0);
}
}
return version;
}
private bool ResolveInlineDefinitions(string resourceType)
{
bool anyWereDefined = false;
foreach (var settings in ResolveRequiredResources(resourceType).Where(settings => settings.InlineDefinition != null))
{
// defining it on the fly
var resource = FindResource(settings, false);
if (resource == null)
{
// does not already exist, so define it
resource = InlineManifest.DefineResource(resourceType, settings.Name).SetBasePath(settings.BasePath);
anyWereDefined = true;
}
settings.InlineDefinition(resource);
settings.InlineDefinition = null;
}
return anyWereDefined;
}
private IEnumerable<RequireSettings> ResolveRequiredResources(string resourceType)
{
return _required.Where(r => r.Key.Type == resourceType).Select(r => r.Value);
}
public IEnumerable<LinkEntry> GetRegisteredLinks()
{
if (_links == null)
{
return Enumerable.Empty<LinkEntry>();
}
return _links.AsReadOnly();
}
public IEnumerable<MetaEntry> GetRegisteredMetas()
{
if(_metas == null)
{
return Enumerable.Empty<MetaEntry>();
}
return _metas.Values;
}
public IEnumerable<IHtmlContent> GetRegisteredHeadScripts()
{
return _headScripts == null ? Enumerable.Empty<IHtmlContent>() : _headScripts;
}
public IEnumerable<IHtmlContent> GetRegisteredFootScripts()
{
return _footScripts == null ? Enumerable.Empty<IHtmlContent>() : _footScripts;
}
public IEnumerable<ResourceRequiredContext> GetRequiredResources(string resourceType)
{
IList<ResourceRequiredContext> requiredResources;
if (_builtResources.TryGetValue(resourceType, out requiredResources) && requiredResources != null)
{
return requiredResources;
}
var allResources = new OrderedDictionary();
foreach (var settings in ResolveRequiredResources(resourceType))
{
var resource = FindResource(settings);
if (resource == null)
{
throw new InvalidOperationException($"Could not find a resource of type '{settings.Type}' named '{settings.Name}' with version '{settings.Version ?? "any"}.");
}
ExpandDependencies(resource, settings, allResources);
}
requiredResources = (from DictionaryEntry entry in allResources
select new ResourceRequiredContext { Resource = (ResourceDefinition)entry.Key, Settings = (RequireSettings)entry.Value }).ToList();
_builtResources[resourceType] = requiredResources;
return requiredResources;
}
protected virtual void ExpandDependencies(ResourceDefinition resource, RequireSettings settings, OrderedDictionary allResources)
{
if (resource == null)
{
return;
}
// Settings is given so they can cascade down into dependencies. For example, if Foo depends on Bar, and Foo's required
// location is Head, so too should Bar's location.
// forge the effective require settings for this resource
// (1) If a require exists for the resource, combine with it. Last settings in gets preference for its specified values.
// (2) If no require already exists, form a new settings object based on the given one but with its own type/name.
settings = allResources.Contains(resource)
? ((RequireSettings)allResources[resource]).Combine(settings)
: new RequireSettings { Type = resource.Type, Name = resource.Name }.Combine(settings);
if (resource.Dependencies != null)
{
var dependencies = from d in resource.Dependencies
let segments = d.Split('-')
let name = segments[0]
let version = segments.Length > 1 ? segments[1] : null
select FindResource(new RequireSettings { Type = resource.Type, Name = name, Version = version });
foreach (var dependency in dependencies)
{
if (dependency == null)
{
continue;
}
ExpandDependencies(dependency, settings, allResources);
}
}
allResources[resource] = settings;
}
public void RegisterLink(LinkEntry link)
{
if(_links == null)
{
_links = new List<LinkEntry>();
}
_links.Add(link);
}
public void RegisterMeta(MetaEntry meta)
{
if (meta == null)
{
return;
}
if(_metas == null)
{
_metas = new Dictionary<string, MetaEntry>();
}
var index = meta.Name ?? meta.HttpEquiv ?? "charset";
_metas[index] = meta;
}
public void AppendMeta(MetaEntry meta, string contentSeparator)
{
if (meta == null)
{
return;
}
var index = meta.Name ?? meta.HttpEquiv;
if (String.IsNullOrEmpty(index))
{
return;
}
if (_metas == null)
{
_metas = new Dictionary<string, MetaEntry>();
}
MetaEntry existingMeta;
if (_metas.TryGetValue(index, out existingMeta))
{
meta = MetaEntry.Combine(existingMeta, meta, contentSeparator);
}
_metas[index] = meta;
}
public void RenderMeta(IHtmlContentBuilder builder)
{
var first = true;
foreach (var meta in this.GetRegisteredMetas())
{
if (!first)
{
builder.AppendHtml(Environment.NewLine);
}
first = false;
builder.AppendHtml(meta.GetTag());
}
}
public void RenderHeadLink(IHtmlContentBuilder builder)
{
var first = true;
foreach (var link in this.GetRegisteredLinks())
{
if (!first)
{
builder.AppendHtml(Environment.NewLine);
}
first = false;
builder.AppendHtml(link.GetTag());
}
}
public void RenderStylesheet(IHtmlContentBuilder builder, RequireSettings settings)
{
var first = true;
var styleSheets = this.GetRequiredResources("stylesheet");
foreach (var context in styleSheets)
{
if (!first)
{
builder.AppendHtml(Environment.NewLine);
}
first = false;
builder.AppendHtml(context.GetHtmlContent(settings, "/"));
}
}
public void RenderHeadScript(IHtmlContentBuilder builder, RequireSettings settings)
{
var headScripts = this.GetRequiredResources("script");
var first = true;
foreach (var context in headScripts.Where(r => r.Settings.Location == ResourceLocation.Head))
{
if (!first)
{
builder.AppendHtml(Environment.NewLine);
}
first = false;
builder.AppendHtml(context.GetHtmlContent(settings, "/"));
}
foreach (var context in GetRegisteredHeadScripts())
{
if (!first)
{
builder.AppendHtml(Environment.NewLine);
}
first = false;
builder.AppendHtml(context);
}
}
public void RenderFootScript(IHtmlContentBuilder builder, RequireSettings settings)
{
var footScripts = this.GetRequiredResources("script");
var first = true;
foreach (var context in footScripts.Where(r => r.Settings.Location == ResourceLocation.Foot))
{
if (!first)
{
builder.AppendHtml(Environment.NewLine);
}
first = false;
builder.AppendHtml(context.GetHtmlContent(settings, "/"));
}
foreach (var context in GetRegisteredFootScripts())
{
if (!first)
{
builder.AppendHtml(Environment.NewLine);
}
first = false;
builder.AppendHtml(context);
}
}
private class ResourceTypeName : IEquatable<ResourceTypeName>
{
private readonly string _type;
private readonly string _name;
public string Type { get { return _type; } }
public string Name { get { return _name; } }
public ResourceTypeName(string resourceType, string resourceName)
{
_type = resourceType;
_name = resourceName;
}
public bool Equals(ResourceTypeName other)
{
if (other == null)
{
return false;
}
return _type.Equals(other._type) && _name.Equals(other._name);
}
public override int GetHashCode()
{
return _type.GetHashCode() << 17 + _name.GetHashCode();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("(");
sb.Append(_type);
sb.Append(", ");
sb.Append(_name);
sb.Append(")");
return sb.ToString();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
namespace Zios{
using Containers;
using Class = ObjectExtension;
public static partial class ObjectExtension{
[NonSerialized] public static bool debug;
public static List<Type> emptyList = new List<Type>();
public static List<Assembly> assemblies = new List<Assembly>();
public static Hierarchy<Assembly,string,Type> lookup = new Hierarchy<Assembly,string,Type>();
public static Hierarchy<object,string,bool> warned = new Hierarchy<object,string,bool>();
public static Hierarchy<Type,BindingFlags,IList<Type>,string,object> variables = new Hierarchy<Type,BindingFlags,IList<Type>,string,object>();
public static Hierarchy<Type,BindingFlags,string,PropertyInfo> properties = new Hierarchy<Type,BindingFlags,string,PropertyInfo>();
public static Hierarchy<Type,BindingFlags,string,FieldInfo> fields = new Hierarchy<Type,BindingFlags,string,FieldInfo>();
public static Hierarchy<Type,BindingFlags,string,MethodInfo> methods = new Hierarchy<Type,BindingFlags,string,MethodInfo>();
public static Hierarchy<Type,BindingFlags,IList<Type>,string,MethodInfo> exactMethods = new Hierarchy<Type,BindingFlags,IList<Type>,string,MethodInfo>();
public const BindingFlags allFlags = BindingFlags.Static|BindingFlags.Instance|BindingFlags.NonPublic|BindingFlags.Public;
public const BindingFlags allFlatFlags = BindingFlags.Static|BindingFlags.Instance|BindingFlags.NonPublic|BindingFlags.Public|BindingFlags.FlattenHierarchy;
public const BindingFlags staticFlags = BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic;
public const BindingFlags staticPublicFlags = BindingFlags.Static|BindingFlags.Public;
public const BindingFlags instanceFlags = BindingFlags.Instance|BindingFlags.NonPublic|BindingFlags.Public;
public const BindingFlags privateFlags = BindingFlags.Instance|BindingFlags.NonPublic;
public const BindingFlags publicFlags = BindingFlags.Instance|BindingFlags.Public;
//=========================
// Assemblies
//=========================
public static List<Assembly> GetAssemblies(){
if(Class.assemblies.Count < 1){Class.assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();}
return Class.assemblies;
}
//=========================
// Methods
//=========================
public static List<MethodInfo> GetMethods(Type type,BindingFlags flags=allFlags){
var target = Class.methods.AddNew(type).AddNew(flags);
if(target.Count < 1){
foreach(var method in type.GetMethods(flags)){
target[method.Name] = method;
}
}
return target.Values.ToList();
}
public static MethodInfo GetMethod(Type type,string name,BindingFlags flags=allFlags){
var target = Class.methods.AddNew(type).AddNew(flags);
MethodInfo method;
if(!target.TryGetValue(name,out method)){target[name] = method = type.GetMethod(name,flags);}
return method;
}
public static bool HasMethod(this object current,string name,BindingFlags flags=allFlags){
Type type = current is Type ? (Type)current : current.GetType();
return !Class.GetMethod(type,name,flags).IsNull();
}
public static List<MethodInfo> GetExactMethods(this object current,IList<Type> argumentTypes=null,string name="",BindingFlags flags=allFlags){
Type type = current is Type ? (Type)current : current.GetType();
var methods = Class.exactMethods.AddNew(type).AddNew(flags).AddNew(argumentTypes);
if(name.IsEmpty() && methods.Count > 0){return methods.Select(x=>x.Value).ToList();}
MethodInfo existing;
if(methods.TryGetValue(name,out existing)){return existing.AsList();}
foreach(var method in Class.GetMethods(type,flags)){
if(!name.IsEmpty() && !method.Name.Matches(name,true)){continue;}
if(!argumentTypes.IsNull()){
ParameterInfo[] parameters = method.GetParameters();
bool match = parameters.Length == argumentTypes.Count;
if(match){
for(int index=0;index<parameters.Length;++index){
if(!argumentTypes[index].Is(parameters[index].ParameterType)){
match = false;
break;
}
}
}
if(!match){continue;}
}
methods[method.Name] = method;
}
return methods.Values.ToList();
}
public static List<string> ListMethods(this object current,IList<Type> argumentTypes=null,BindingFlags flags=allFlags){
return current.GetExactMethods(argumentTypes,"",flags).Select(x=>x.Name).ToList();
}
public static object CallExactMethod(this object current,string name,params object[] parameters){
return current.CallExactMethod<object>(name,allFlags,parameters);
}
public static V CallExactMethod<V>(this object current,string name,params object[] parameters){
return current.CallExactMethod<V>(name,allFlags,parameters);
}
public static V CallExactMethod<V>(this object current,string name,BindingFlags flags,params object[] parameters){
List<Type> argumentTypes = new List<Type>();
foreach(var parameter in parameters){
argumentTypes.Add(parameter.GetType());
}
var methods = current.GetExactMethods(argumentTypes,name,flags);
if(methods.Count < 1){
if(ObjectExtension.debug){Debug.LogWarning("[Object] No method found to call -- " + name);}
return default(V);
}
if(current.IsStatic() || current is Type){
return (V)methods[0].Invoke(null,parameters);
}
return (V)methods[0].Invoke(current,parameters);
}
public static object CallMethod(this string current,params object[] parameters){
if(Class.lookup.Count < 1){
foreach(var assembly in Class.GetAssemblies()){
var types = assembly.GetTypes();
foreach(var type in types){
Class.lookup.AddNew(assembly)[type.FullName] = type;
}
}
}
var name = current.Split(".").Last();
var path = current.Remove("."+name);
foreach(var item in Class.lookup){
Type existing;
var assembly = item.Value;
if(assembly.TryGetValue(path,out existing)){
var method = Class.GetMethod(existing,name);
if(method.IsNull()){
if(ObjectExtension.debug){Debug.Log("[ObjectReflection] Cannot call. Method does not exist -- " + current + "()");}
return null;
}
if(!method.IsStatic){
if(ObjectExtension.debug){Debug.Log("[ObjectReflection] Cannot call. Method is not static -- " + current + "()");}
return null;
}
var value = existing.CallExactMethod(name,parameters);
return value ?? true;
}
}
if(ObjectExtension.debug){Debug.Log("[ObjectReflection] Cannot call. Path not found -- " + current + "()");}
return null;
}
public static object CallMethod(this object current,string name,params object[] parameters){
return current.CallMethod<object>(name,allFlags,parameters);
}
public static V CallMethod<V>(this object current,string name,params object[] parameters){
return current.CallMethod<V>(name,allFlags,parameters);
}
public static V CallMethod<V>(this object current,string name,BindingFlags flags,params object[] parameters){
Type type = current is Type ? (Type)current : current.GetType();
var method = Class.GetMethod(type,name,flags);
if(method.IsNull()){
if(ObjectExtension.debug){Debug.LogWarning("[Object] No method found to call -- " + name);}
return default(V);
}
if(current.IsStatic() || current is Type){
return (V)method.Invoke(null,parameters);
}
return (V)method.Invoke(current,parameters);
}
//=========================
// Attributes
//=========================
public static bool HasAttribute(this object current,string name,Type attribute){
return current.ListAttributes(name).Exists(x=>x.GetType()==attribute);
}
public static Attribute[] ListAttributes(this object current,string name){
Type type = current is Type ? (Type)current : current.GetType();
var field = Class.GetField(type,name,allFlags);
if(!field.IsNull()){return Attribute.GetCustomAttributes(field);}
var property = Class.GetProperty(type,name,allFlags);
return property.IsNull() ? new Attribute[0] : Attribute.GetCustomAttributes(property);
}
//=========================
// Variables
//=========================
public static void ResetCache(){
Class.properties.Clear();
Class.variables.Clear();
Class.methods.Clear();
Class.fields.Clear();
}
public static PropertyInfo GetProperty(Type type,string name,BindingFlags flags=allFlags){
var target = Class.properties.AddNew(type).AddNew(flags);
PropertyInfo property;
if(!target.TryGetValue(name,out property)){target[name] = property = type.GetProperty(name,flags);}
return property;
}
public static FieldInfo GetField(Type type,string name,BindingFlags flags=allFlags){
var target = Class.fields.AddNew(type).AddNew(flags);
FieldInfo field;
if(!target.TryGetValue(name,out field)){target[name] = field = type.GetField(name,flags);}
return field;
}
public static bool HasVariable(this object current,string name,BindingFlags flags=allFlags){
Type type = current is Type ? (Type)current : current.GetType();
return !Class.GetField(type,name,flags).IsNull() || !Class.GetProperty(type,name,flags).IsNull();
}
public static Type GetVariableType(this object current,string name,int index=-1,BindingFlags flags=allFlags){
Type type = current is Type ? (Type)current : current.GetType();
var field = Class.GetField(type,name,flags);
if(!field.IsNull()){
if(index != -1){
if(current is Vector3){return typeof(float);}
IList list = (IList)field.GetValue(current);
return list[index].GetType();
}
return field.FieldType;
}
var property = Class.GetProperty(type,name,flags);
return property.IsNull() ? typeof(Type) : property.PropertyType;
}
public static object GetVariable(this object current,string name,int index=-1,BindingFlags flags=allFlags){return current.GetVariable<object>(name,index,flags);}
public static T GetVariable<T>(this object current,string name,BindingFlags flags){return current.GetVariable<T>(name,-1,flags);}
public static T GetVariable<T>(this object current,string name,int index=-1,BindingFlags flags=allFlags){
if(current.IsNull()){return default(T);}
if(name.IsNumber()){
index = name.ToInt();
name = "";
}
if(current is IDictionary && current.As<IDictionary>().ContainsKey(name,true)){return current.As<IDictionary>()[name].As<T>();}
if(index != -1 && current is Vector3){return current.As<Vector3>()[index].As<T>();}
if(index != -1 && current is IList){return current.As<IList>()[index].As<T>();}
var value = default(T);
object instance = current is Type || current.IsStatic() ? null : current;
var type = current is Type ? (Type)current : current.GetType();
var field = Class.GetField(type,name,flags);
var property = field.IsNull() ? Class.GetProperty(type,name,flags) : null;
if(!name.IsEmpty() && property.IsNull() && field.IsNull()){
if(ObjectExtension.debug && !Class.warned.AddNew(current).AddNew(name)){
Debug.LogWarning("[ObjectReflection] Could not find variable to get -- " + type.Name + "." + name);
Class.warned[current][name] = true;
}
return value;
}
if(!property.IsNull()){value = (T)property.GetValue(instance,null);}
if(!field.IsNull()){value = (T)field.GetValue(instance);}
if(index != -1 && (value is IList || value is Vector3)){
return value.GetVariable<T>(name,index,flags);
}
return value;
}
public static void SetVariables<T>(this object current,IDictionary<string,T> values,BindingFlags flags=allFlags){
foreach(var item in values){
current.SetVariable<T>(item.Key,item.Value,-1,flags);
}
}
public static void SetVariable<T>(this object current,string name,T value,int index=-1,BindingFlags flags=allFlags){
if(current.IsNull()){return;}
if(name.IsNumber()){
index = name.ToInt();
name = "";
}
if(current is IDictionary){
current.As<IDictionary>()[name] = value;
return;
}
if(index != -1 && current is IList){
current.As<IList>()[index] = value;
return;
}
if(index != -1 && current is Vector3){
var goal = current.As<Vector3>();
goal[index] = value.ToFloat();
current.As<Vector3>().Set(goal.x,goal.y,goal.z);
return;
}
var instance = current is Type || current.IsStatic() ? null : current;
var type = current is Type ? (Type)current : current.GetType();
var field = Class.GetField(type,name,flags);
var property = field.IsNull() ? Class.GetProperty(type,name,flags) : null;
if(!name.IsNull() && property.IsNull() && field.IsNull() && !Class.warned.AddNew(current).AddNew(name)){
if(ObjectExtension.debug){Debug.LogWarning("[ObjectReflection] Could not find variable to set -- " + name);}
Class.warned[current][name] = true;
return;
}
if(index != -1){
var targetValue = property.IsNull() ? field.GetValue(instance) : property.GetValue(instance,null);
if(targetValue is IList || targetValue is Vector3){
targetValue.SetVariable<T>(name,value,index,flags);
return;
}
}
if(!field.IsNull() && !field.FieldType.IsGeneric()){
field.SetValue(instance,value);
}
if(!property.IsNull() && property.CanWrite){
property.SetValue(instance,value,null);
}
}
public static Dictionary<string,T> GetVariables<T>(this object current,IList<Type> withoutAttributes=null,BindingFlags flags=allFlags){
var allVariables = current.GetVariables(withoutAttributes,flags);
return allVariables.Where(x=>x.Value.Is<T>()).ToDictionary(x=>x.Key,x=>(T)x.Value);
}
public static Dictionary<string,object> GetVariables(this object current,IList<Type> withoutAttributes=null,BindingFlags flags=allFlags){
if(current.IsNull()){return new Dictionary<string,object>();}
Type type = current is Type ? (Type)current : current.GetType();
var target = Class.variables.AddNew(type).AddNew(flags);
IEnumerable<KeyValuePair<IList<Type>,Dictionary<string,object>>> match = null;
if(withoutAttributes.IsNull()){
withoutAttributes = Class.emptyList;
Dictionary<string,object> existing;
if(target.TryGetValue(withoutAttributes,out existing)){
return existing;
}
}
else{
match = target.Where(x=>x.Key.SequenceEqual(withoutAttributes));
}
if(match.IsNull() || match.Count() < 1){
object instance = current.IsStatic() || current is Type ? null : current;
Dictionary<string,object> variables = new Dictionary<string,object>();
foreach(FieldInfo field in type.GetFields(flags)){
if(field.FieldType.IsGeneric()){continue;}
if(withoutAttributes.Count > 0){
var attributes = Attribute.GetCustomAttributes(field);
if(attributes.Any(x=>withoutAttributes.Any(y=>y==x.GetType()))){continue;}
}
variables[field.Name] = field.GetValue(instance);
}
foreach(PropertyInfo property in type.GetProperties(flags).Where(x=>x.CanRead)){
if(!property.CanWrite || property.PropertyType.IsGeneric()){continue;}
if(withoutAttributes.Count > 0){
var attributes = Attribute.GetCustomAttributes(property);
if(attributes.Any(x=>withoutAttributes.Any(y=>y==x.GetType()))){continue;}
}
try{variables[property.Name] = property.GetValue(instance,null);}
catch{}
}
target[withoutAttributes] = variables;
return variables;
}
return match.ToDictionary().Values.FirstOrDefault();
}
public static List<string> ListVariables(this object current,IList<Type> withoutAttributes=null,BindingFlags flags=allFlags){
return current.GetVariables(withoutAttributes,flags).Keys.ToList();
}
public static T UseVariables<T>(this T current,T other,IList<Type> withoutAttributes=null,BindingFlags flags = publicFlags) where T : class{
foreach(var name in current.ListVariables(withoutAttributes,flags)){
current.SetVariable(name,other.GetVariable(name));
}
return current;
}
public static void ClearVariable(this object current,string name,BindingFlags flags=allFlags){
Type type = current is Type ? (Type)current : current.GetType();
current = current.IsStatic() ? null : current;
FieldInfo field = Class.GetField(type,name,flags);
if(!field.IsNull()){
if(!field.FieldType.IsGeneric()){
field.SetValue(current,null);
}
return;
}
PropertyInfo property = Class.GetProperty(type,name,flags);
if(!property.IsNull() && property.CanWrite){
property.SetValue(current,null,null);
}
}
public static object InstanceVariable(this object current,string name,bool force){return current.InstanceVariable(name,-1,allFlags,force);}
public static object InstanceVariable(this object current,string name,BindingFlags flags,bool force=false){return current.InstanceVariable(name,-1,flags,force);}
public static object InstanceVariable(this object current,string name,int index=-1,BindingFlags flags=allFlags,bool force=false){
object instance = current.GetVariable(name,index,flags);
if(force || instance.IsNull()){
var instanceType = current.GetVariableType(name,index,flags);
if(!instanceType.GetConstructor(Type.EmptyTypes).IsNull()){
try{
instance = Activator.CreateInstance(instanceType);
current.SetVariable(name,instance,index,flags);
}
catch{}
}
}
return instance;
}
//=========================
// Values
//=========================
public static void SetValuesByType<T>(this object current,IList<T> values,IList<Type> withoutAttributes=null,BindingFlags flags=allFlags){
var existing = current.GetVariables<T>(withoutAttributes,flags);
int index = 0;
foreach(var item in existing){
if(index >= values.Count){break;}
current.SetVariable(item.Key,values[index]);
++index;
}
}
public static void SetValuesByName<T>(this object current,Dictionary<string,T> values,IList<Type> withoutAttributes=null,BindingFlags flags=allFlags){
var existing = current.GetVariables<T>(withoutAttributes,flags);
foreach(var item in existing){
if(!values.ContainsKey(item.Key)){
if(ObjectExtension.debug){Debug.Log("[ObjectReflection] : No key found when attempting to assign values by name -- " + item.Key);}
continue;
}
current.SetVariable(item.Key,values[item.Key]);
}
}
public static T[] GetValues<T>(this object current,IList<Type> withoutAttributes=null,BindingFlags flags=allFlags){
var allVariables = current.GetVariables<T>(withoutAttributes,flags);
return allVariables.Values.ToArray();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading;
namespace Internal.TypeSystem
{
/// <summary>
/// Represents an array type - either a multidimensional array, or a vector
/// (a one-dimensional array with a zero lower bound).
/// </summary>
public sealed partial class ArrayType : ParameterizedType
{
private int _rank; // -1 for regular single dimensional arrays, > 0 for multidimensional arrays
internal ArrayType(TypeDesc elementType, int rank)
: base(elementType)
{
_rank = rank;
}
public override int GetHashCode()
{
return Internal.NativeFormat.TypeHashingAlgorithms.ComputeArrayTypeHashCode(this.ElementType.GetHashCode(), _rank == -1 ? 1 : _rank);
}
public override DefType BaseType
{
get
{
return this.Context.GetWellKnownType(WellKnownType.Array);
}
}
/// <summary>
/// Gets the type of the element of this array.
/// </summary>
public TypeDesc ElementType
{
get
{
return this.ParameterType;
}
}
internal MethodDesc[] _methods;
/// <summary>
/// Gets a value indicating whether this type is a vector.
/// </summary>
public new bool IsSzArray
{
get
{
return _rank < 0;
}
}
/// <summary>
/// Gets the rank of this array. Note this returns "1" for both vectors, and
/// for general arrays of rank 1. Use <see cref="IsSzArray"/> to disambiguate.
/// </summary>
public int Rank
{
get
{
return (_rank < 0) ? 1 : _rank;
}
}
private void InitializeMethods()
{
int numCtors;
if (IsSzArray)
{
numCtors = 1;
// Jagged arrays have constructor for each possible depth
var t = this.ElementType;
while (t.IsSzArray)
{
t = ((ArrayType)t).ElementType;
numCtors++;
}
}
else
{
// Multidimensional arrays have two ctors, one with and one without lower bounds
numCtors = 2;
}
MethodDesc[] methods = new MethodDesc[(int)ArrayMethodKind.Ctor + numCtors];
for (int i = 0; i < methods.Length; i++)
methods[i] = new ArrayMethod(this, (ArrayMethodKind)i);
Interlocked.CompareExchange(ref _methods, methods, null);
}
public override IEnumerable<MethodDesc> GetMethods()
{
if (_methods == null)
InitializeMethods();
return _methods;
}
public MethodDesc GetArrayMethod(ArrayMethodKind kind)
{
if (_methods == null)
InitializeMethods();
return _methods[(int)kind];
}
public override TypeDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
TypeDesc instantiatedElementType = this.ElementType.InstantiateSignature(typeInstantiation, methodInstantiation);
return instantiatedElementType.Context.GetArrayType(instantiatedElementType, _rank);
}
protected override TypeFlags ComputeTypeFlags(TypeFlags mask)
{
TypeFlags flags = _rank == -1 ? TypeFlags.SzArray : TypeFlags.Array;
if ((mask & TypeFlags.ContainsGenericVariablesComputed) != 0)
{
flags |= TypeFlags.ContainsGenericVariablesComputed;
if (this.ParameterType.ContainsGenericVariables)
flags |= TypeFlags.ContainsGenericVariables;
}
flags |= TypeFlags.HasGenericVarianceComputed;
return flags;
}
public override string ToString()
{
return this.ElementType.ToString() + "[" + new String(',', Rank - 1) + "]";
}
}
public enum ArrayMethodKind
{
Get,
Set,
Address,
Ctor
}
/// <summary>
/// Represents one of the methods on array types. While array types are not typical
/// classes backed by metadata, they do have methods that can be referenced from the IL
/// and the type system needs to provide a way to represent them.
/// </summary>
public partial class ArrayMethod : MethodDesc
{
private ArrayType _owningType;
private ArrayMethodKind _kind;
internal ArrayMethod(ArrayType owningType, ArrayMethodKind kind)
{
_owningType = owningType;
_kind = kind;
}
public override TypeSystemContext Context
{
get
{
return _owningType.Context;
}
}
public override TypeDesc OwningType
{
get
{
return _owningType;
}
}
public ArrayMethodKind Kind
{
get
{
return _kind;
}
}
private MethodSignature _signature;
public override MethodSignature Signature
{
get
{
if (_signature == null)
{
switch (_kind)
{
case ArrayMethodKind.Get:
{
var parameters = new TypeDesc[_owningType.Rank];
for (int i = 0; i < _owningType.Rank; i++)
parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, _owningType.ElementType, parameters);
break;
}
case ArrayMethodKind.Set:
{
var parameters = new TypeDesc[_owningType.Rank + 1];
for (int i = 0; i < _owningType.Rank; i++)
parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
parameters[_owningType.Rank] = _owningType.ElementType;
_signature = new MethodSignature(0, 0, this.Context.GetWellKnownType(WellKnownType.Void), parameters);
break;
}
case ArrayMethodKind.Address:
{
var parameters = new TypeDesc[_owningType.Rank];
for (int i = 0; i < _owningType.Rank; i++)
parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, _owningType.ElementType.MakeByRefType(), parameters);
}
break;
default:
{
int numArgs;
if (_owningType.IsSzArray)
{
numArgs = 1 + (int)_kind - (int)ArrayMethodKind.Ctor;
}
else
{
numArgs = (_kind == ArrayMethodKind.Ctor) ? _owningType.Rank : 2 * _owningType.Rank;
}
var argTypes = new TypeDesc[numArgs];
for (int i = 0; i < argTypes.Length; i++)
argTypes[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, this.Context.GetWellKnownType(WellKnownType.Void), argTypes);
}
break;
}
}
return _signature;
}
}
public override string Name
{
get
{
switch (_kind)
{
case ArrayMethodKind.Get:
return "Get";
case ArrayMethodKind.Set:
return "Set";
case ArrayMethodKind.Address:
return "Address";
default:
return ".ctor";
}
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return false;
}
public override MethodDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
TypeDesc owningType = this.OwningType;
TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation);
if (owningType != instantiatedOwningType)
return ((ArrayType)instantiatedOwningType).GetArrayMethod(_kind);
else
return this;
}
public override string ToString()
{
return _owningType.ToString() + "." + Name;
}
}
}
| |
// Copyright 2010 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Annotations;
using NodaTime.Utility;
using System;
using System.Diagnostics;
namespace NodaTime.TimeZones
{
/// <summary>
/// Represents a range of time for which a particular Offset applies.
/// </summary>
/// <remarks>
/// <para>
/// Equality is defined component-wise in terms of all properties: the name, the start and end, and the offsets.
/// There is no ordering defined between zone intervals.
/// </para>
/// </remarks>
/// <threadsafety>This type is an immutable reference type. See the thread safety section of the user guide for more information.</threadsafety>
[Immutable]
public sealed class ZoneInterval : IEquatable<ZoneInterval?>
{
/// <summary>
/// Returns the underlying start instant of this zone interval. If the zone interval extends to the
/// beginning of time, the return value will be <see cref="Instant.BeforeMinValue"/>; this value
/// should *not* be exposed publicly.
/// </summary>
internal Instant RawStart { get; }
/// <summary>
/// Returns the underlying end instant of this zone interval. If the zone interval extends to the
/// end of time, the return value will be <see cref="Instant.AfterMaxValue"/>; this value
/// should *not* be exposed publicly.
/// </summary>
internal Instant RawEnd { get; }
private readonly LocalInstant localStart;
private readonly LocalInstant localEnd;
/// <summary>
/// Gets the standard offset for this period. This is the offset without any daylight savings
/// contributions.
/// </summary>
/// <remarks>
/// This is effectively <c>WallOffset - Savings</c>.
/// </remarks>
/// <value>The base Offset.</value>
public Offset StandardOffset
{
[DebuggerStepThrough]
get { return WallOffset - Savings; }
}
/// <summary>
/// Gets the duration of this zone interval.
/// </summary>
/// <remarks>
/// This is effectively <c>End - Start</c>.
/// </remarks>
/// <value>The Duration of this zone interval.</value>
/// <exception cref="InvalidOperationException">This zone extends to the start or end of time.</exception>
public Duration Duration
{
[DebuggerStepThrough]
get { return End - Start; }
}
/// <summary>
/// Returns <c>true</c> if this zone interval has a fixed start point, or <c>false</c> if it
/// extends to the beginning of time.
/// </summary>
/// <value><c>true</c> if this interval has a fixed start point, or <c>false</c> if it
/// extends to the beginning of time.</value>
public bool HasStart => RawStart.IsValid;
/// <summary>
/// Gets the last Instant (exclusive) that the Offset applies.
/// </summary>
/// <value>The last Instant (exclusive) that the Offset applies.</value>
/// <exception cref="InvalidOperationException">The zone interval extends to the end of time</exception>
public Instant End
{
[DebuggerStepThrough]
get
{
Preconditions.CheckState(RawEnd.IsValid, "Zone interval extends to the end of time");
return RawEnd;
}
}
/// <summary>
/// Returns <c>true</c> if this zone interval has a fixed end point, or <c>false</c> if it
/// extends to the end of time.
/// </summary>
/// <value><c>true</c> if this interval has a fixed end point, or <c>false</c> if it
/// extends to the end of time.</value>
public bool HasEnd => RawEnd.IsValid;
// TODO(feature): Consider whether we need some way of checking whether IsoLocalStart/End will throw.
// Clients can check HasStart/HasEnd for infinity, but what about unrepresentable local values?
/// <summary>
/// Gets the local start time of the interval, as a <see cref="LocalDateTime" />
/// in the ISO calendar.
/// </summary>
/// <value>The local start time of the interval in the ISO calendar, with the offset of
/// this zone interval.</value>
/// <exception cref="OverflowException">The interval starts too early to represent as a `LocalDateTime`.</exception>
/// <exception cref="InvalidOperationException">The interval extends to the start of time.</exception>
public LocalDateTime IsoLocalStart
{
// Use the Start property to trigger the appropriate end-of-time exception.
// Call Plus to trigger an appropriate out-of-range exception.
[DebuggerStepThrough]
get { return new LocalDateTime(Start.Plus(WallOffset)); }
}
/// <summary>
/// Gets the local end time of the interval, as a <see cref="LocalDateTime" />
/// in the ISO calendar.
/// </summary>
/// <value>The local end time of the interval in the ISO calendar, with the offset
/// of this zone interval. As the end time is exclusive, by the time this local time
/// is reached, the next interval will be in effect and the local time will usually
/// have changed (e.g. by adding or subtracting an hour).</value>
/// <exception cref="OverflowException">The interval ends too late to represent as a `LocalDateTime`.</exception>
/// <exception cref="InvalidOperationException">The interval extends to the end of time.</exception>
public LocalDateTime IsoLocalEnd
{
[DebuggerStepThrough]
// Use the End property to trigger the appropriate end-of-time exception.
// Call Plus to trigger an appropriate out-of-range exception.
get { return new LocalDateTime(End.Plus(WallOffset)); }
}
/// <summary>
/// Gets the name of this offset period (e.g. PST or PDT).
/// </summary>
/// <value>The name of this offset period (e.g. PST or PDT).</value>
public string Name { [DebuggerStepThrough] get; }
/// <summary>
/// Gets the offset from UTC for this period. This includes any daylight savings value.
/// </summary>
/// <value>The offset from UTC for this period.</value>
public Offset WallOffset { [DebuggerStepThrough] get; }
/// <summary>
/// Gets the daylight savings value for this period.
/// </summary>
/// <value>The savings value.</value>
public Offset Savings { [DebuggerStepThrough] get; }
/// <summary>
/// Gets the first Instant that the Offset applies.
/// </summary>
/// <value>The first Instant that the Offset applies.</value>
/// <exception cref="InvalidOperationException">The interval extends to the start of time.</exception>
public Instant Start
{
[DebuggerStepThrough]
get
{
Preconditions.CheckState(RawStart.IsValid, "Zone interval extends to the beginning of time");
return RawStart;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ZoneInterval" /> class.
/// </summary>
/// <param name="name">The name of this offset period (e.g. PST or PDT).</param>
/// <param name="start">The first <see cref="Instant" /> that the <paramref name = "wallOffset" /> applies,
/// or <c>null</c> to make the zone interval extend to the start of time.</param>
/// <param name="end">The last <see cref="Instant" /> (exclusive) that the <paramref name = "wallOffset" /> applies,
/// or <c>null</c> to make the zone interval extend to the end of time.</param>
/// <param name="wallOffset">The <see cref="WallOffset" /> from UTC for this period including any daylight savings.</param>
/// <param name="savings">The <see cref="WallOffset" /> daylight savings contribution to the offset.</param>
/// <exception cref="ArgumentException">If <c><paramref name = "start" /> >= <paramref name = "end" /></c>.</exception>
public ZoneInterval(string name, Instant? start, Instant? end, Offset wallOffset, Offset savings)
: this(name, start ?? Instant.BeforeMinValue, end ?? Instant.AfterMaxValue, wallOffset, savings)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ZoneInterval" /> class.
/// </summary>
/// <param name="name">The name of this offset period (e.g. PST or PDT).</param>
/// <param name="start">The first <see cref="Instant" /> that the <paramref name = "wallOffset" /> applies,
/// or <see cref="Instant.BeforeMinValue"/> to make the zone interval extend to the start of time.</param>
/// <param name="end">The last <see cref="Instant" /> (exclusive) that the <paramref name = "wallOffset" /> applies,
/// or <see cref="Instant.AfterMaxValue"/> to make the zone interval extend to the end of time.</param>
/// <param name="wallOffset">The <see cref="WallOffset" /> from UTC for this period including any daylight savings.</param>
/// <param name="savings">The <see cref="WallOffset" /> daylight savings contribution to the offset.</param>
/// <exception cref="ArgumentException">If <c><paramref name = "start" /> >= <paramref name = "end" /></c>.</exception>
internal ZoneInterval(string name, Instant start, Instant end, Offset wallOffset, Offset savings)
{
Preconditions.CheckNotNull(name, nameof(name));
Preconditions.CheckArgument(start < end, nameof(start), "The start Instant must be less than the end Instant");
this.Name = name;
this.RawStart = start;
this.RawEnd = end;
this.WallOffset = wallOffset;
this.Savings = savings;
// Work out the corresponding local instants, taking care to "go infinite" appropriately.
localStart = start.SafePlus(wallOffset);
localEnd = end.SafePlus(wallOffset);
}
/// <summary>
/// Returns a copy of this zone interval, but with the given start instant.
/// </summary>
internal ZoneInterval WithStart(Instant newStart)
{
return new ZoneInterval(Name, newStart, RawEnd, WallOffset, Savings);
}
/// <summary>
/// Returns a copy of this zone interval, but with the given end instant.
/// </summary>
internal ZoneInterval WithEnd(Instant newEnd)
{
return new ZoneInterval(Name, RawStart, newEnd, WallOffset, Savings);
}
#region Contains
/// <summary>
/// Determines whether this period contains the given Instant in its range.
/// </summary>
/// <remarks>
/// Usually this is half-open, i.e. the end is exclusive, but an interval with an end point of "the end of time"
/// is deemed to be inclusive at the end.
/// </remarks>
/// <param name="instant">The instant to test.</param>
/// <returns>
/// <c>true</c> if this period contains the given Instant in its range; otherwise, <c>false</c>.
/// </returns>
[DebuggerStepThrough]
public bool Contains(Instant instant) => RawStart <= instant && instant < RawEnd;
/// <summary>
/// Determines whether this period contains the given LocalInstant in its range.
/// </summary>
/// <param name="localInstant">The local instant to test.</param>
/// <returns>
/// <c>true</c> if this period contains the given LocalInstant in its range; otherwise, <c>false</c>.
/// </returns>
[DebuggerStepThrough]
internal bool Contains(LocalInstant localInstant) => localStart <= localInstant && localInstant < localEnd;
/// <summary>
/// Returns whether this zone interval has the same offsets and name as another.
/// </summary>
internal bool EqualIgnoreBounds([Trusted] ZoneInterval other)
{
Preconditions.DebugCheckNotNull(other, nameof(other));
return other.WallOffset == WallOffset && other.Savings == Savings && other.Name == Name;
}
#endregion // Contains
#region IEquatable<ZoneInterval> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name = "other" /> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
[DebuggerStepThrough]
public bool Equals(ZoneInterval? other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Name == other.Name && RawStart == other.RawStart && RawEnd == other.RawEnd
&& WallOffset == other.WallOffset && Savings == other.Savings;
}
/// <summary>
/// Implements the operator == (equality).
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns><c>true</c> if values are equal to each other, otherwise <c>false</c>.</returns>
public static bool operator ==(ZoneInterval? left, ZoneInterval? right) => ReferenceEquals(left, right) || (left is object && left.Equals(right));
/// <summary>
/// Implements the operator != (inequality).
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <param name="left">The left hand side of the operator.</param>
/// <param name="right">The right hand side of the operator.</param>
/// <returns><c>true</c> if values are not equal to each other, otherwise <c>false</c>.</returns>
public static bool operator !=(ZoneInterval? left, ZoneInterval? right) => !(left == right);
#endregion
#region object Overrides
/// <summary>
/// Determines whether the specified <see cref="System.Object" /> is equal to the current <see cref="System.Object" />.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to the current <see cref="System.Object" />; otherwise, <c>false</c>.
/// </returns>
/// <param name="obj">The <see cref="System.Object" /> to compare with the current <see cref="System.Object" />.</param>
/// <filterpriority>2</filterpriority>
[DebuggerStepThrough]
public override bool Equals(object? obj) => Equals(obj as ZoneInterval);
/// <summary>
/// Returns a hash code for this zone interval.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <returns>A hash code for this zone interval.</returns>
public override int GetHashCode() =>
HashCodeHelper.Initialize()
.Hash(Name)
.Hash(RawStart)
.Hash(RawEnd)
.Hash(WallOffset)
.Hash(Savings)
.Value;
/// <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() => $"{Name}: [{RawStart}, {RawEnd}) {WallOffset} ({Savings})";
#endregion // object Overrides
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.